@cairnvibe/sdk 0.2.11 → 0.2.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";(()=>{var gt=Object.defineProperty;var yt=(n,e)=>{for(var t in e)gt(n,t,{get:e[t],enumerable:!0})};function je(){if(typeof document>"u"||typeof window>"u")return[];let n=document.querySelectorAll("[data-ai]"),e=[];return n.forEach(t=>{let r=t.getBoundingClientRect();if(!(r.bottom>0&&r.top<window.innerHeight&&r.right>0&&r.left<window.innerWidth))return;let s=t.getAttribute("data-ai");s&&e.push(s)}),e}function H(n,e){let t=e?.get(n);if(t)return t;if(typeof document>"u")return null;let r=document.querySelector(`[data-ai="${Le(n)}"]`);if(r)return r;let i=document.querySelector(`[aria-label="${Le(n)}"]`);if(i)return i;let s=document.querySelector(`[role="${Le(n)}"]`);if(s)return s;let a=document.querySelectorAll("button, a, [role='button'], input[type='submit'], input[type='button']"),o=Ie(n);for(let d of Array.from(a))if(Ie(d.textContent??"")===o)return d;for(let d of Array.from(a))if(Ie(d.textContent??"").includes(o))return d;return null}function G(n,e=4e3){n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.add("cairn-glow"),window.setTimeout(()=>n.classList.remove("cairn-glow"),e)}function We(n){return n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.tagName==="SELECT"}function qe(n,e){if(!We(n))return!1;let r=(typeof window<"u"?{INPUT:window.HTMLInputElement,TEXTAREA:window.HTMLTextAreaElement,SELECT:window.HTMLSelectElement}:{})[n.tagName],i=r&&Object.getOwnPropertyDescriptor(r.prototype,"value")?.set;return i?i.call(n,e):n.value=e,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0})),!0}function Ge(n){let t=(We(n)?n.value:n.textContent??"").replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,499)}\u2026`:t||"(empty)"}var Ue="cairn:misses",vt=200;function z(n){try{let e=window.localStorage.getItem(Ue),t=e?JSON.parse(e):[];t.push({...n,at:new Date().toISOString()}),window.localStorage.setItem(Ue,JSON.stringify(t.slice(-vt)))}catch{}}function Ie(n){return n.trim().toLowerCase().replace(/\s+/g," ")}function Le(n){return n.replace(/["\\]/g,"\\$&")}var c={};yt(c,{BRAND:()=>Ft,DIRTY:()=>J,EMPTY_PATH:()=>kt,INVALID:()=>m,NEVER:()=>Mn,OK:()=>T,ParseStatus:()=>w,Schema:()=>x,ZodAny:()=>W,ZodArray:()=>V,ZodBigInt:()=>X,ZodBoolean:()=>Q,ZodBranded:()=>Te,ZodCatch:()=>le,ZodDate:()=>K,ZodDefault:()=>ce,ZodDiscriminatedUnion:()=>Ce,ZodEffects:()=>M,ZodEnum:()=>ae,ZodError:()=>E,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Oe,ZodIntersection:()=>re,ZodIssueCode:()=>l,ZodLazy:()=>ie,ZodLiteral:()=>se,ZodMap:()=>ve,ZodNaN:()=>be,ZodNativeEnum:()=>oe,ZodNever:()=>O,ZodNull:()=>te,ZodNullable:()=>B,ZodNumber:()=>Y,ZodObject:()=>S,ZodOptional:()=>A,ZodParsedType:()=>p,ZodPipeline:()=>Ee,ZodPromise:()=>q,ZodReadonly:()=>de,ZodRecord:()=>Me,ZodSchema:()=>x,ZodSet:()=>xe,ZodString:()=>U,ZodSymbol:()=>ge,ZodTransformer:()=>M,ZodTuple:()=>N,ZodType:()=>x,ZodUndefined:()=>ee,ZodUnion:()=>ne,ZodUnknown:()=>$,ZodVoid:()=>ye,addIssueToContext:()=>u,any:()=>Kt,array:()=>rn,bigint:()=>Gt,boolean:()=>st,coerce:()=>Cn,custom:()=>nt,date:()=>Jt,datetimeRegex:()=>et,defaultErrorMap:()=>L,discriminatedUnion:()=>cn,effect:()=>bn,enum:()=>yn,function:()=>fn,getErrorMap:()=>pe,getParsedType:()=>R,instanceof:()=>Wt,intersection:()=>ln,isAborted:()=>Se,isAsync:()=>fe,isDirty:()=>Ae,isValid:()=>F,late:()=>Ut,lazy:()=>mn,literal:()=>gn,makeIssue:()=>we,map:()=>hn,nan:()=>qt,nativeEnum:()=>vn,never:()=>tn,null:()=>Qt,nullable:()=>kn,number:()=>it,object:()=>sn,objectUtil:()=>Pe,oboolean:()=>An,onumber:()=>Sn,optional:()=>_n,ostring:()=>En,pipeline:()=>Tn,preprocess:()=>wn,promise:()=>xn,quotelessJson:()=>xt,record:()=>un,set:()=>pn,setErrorMap:()=>_t,strictObject:()=>an,string:()=>rt,symbol:()=>Yt,transformer:()=>bn,tuple:()=>dn,undefined:()=>Xt,union:()=>on,unknown:()=>en,util:()=>b,void:()=>nn});var b;(function(n){n.assertEqual=i=>{};function e(i){}n.assertIs=e;function t(i){throw new Error}n.assertNever=t,n.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},n.getValidEnumValues=i=>{let s=n.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(let o of s)a[o]=i[o];return n.objectValues(a)},n.objectValues=i=>n.objectKeys(i).map(function(s){return i[s]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},n.find=(i,s)=>{for(let a of i)if(s(a))return a},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}n.joinValues=r,n.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(b||(b={}));var Pe;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Pe||(Pe={}));var p=b.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),R=n=>{switch(typeof n){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(n)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(n)?p.array:n===null?p.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?p.promise:typeof Map<"u"&&n instanceof Map?p.map:typeof Set<"u"&&n instanceof Set?p.set:typeof Date<"u"&&n instanceof Date?p.date:p.object;default:return p.unknown}};var l=b.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),xt=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),E=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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(s){return s.message},r={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let o=r,d=0;for(;d<a.path.length;){let h=a.path[d];d===a.path.length-1?(o[h]=o[h]||{_errors:[]},o[h]._errors.push(t(a))):o[h]=o[h]||{_errors:[]},o=o[h],d++}}};return i(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,b.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];t[s]=t[s]||[],t[s].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};E.create=n=>new E(n);var bt=(n,e)=>{let t;switch(n.code){case l.invalid_type:n.received===p.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,b.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${b.joinValues(n.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${b.joinValues(n.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${b.joinValues(n.options)}, received '${n.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:b.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case l.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case l.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,b.assertNever(n)}return{message:t}},L=bt;var Je=L;function _t(n){Je=n}function pe(){return Je}var we=n=>{let{data:e,path:t,errorMaps:r,issueData:i}=n,s=[...t,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",d=r.filter(h=>!!h).slice().reverse();for(let h of d)o=h(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},kt=[];function u(n,e){let t=pe(),r=we({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===L?void 0:L].filter(i=>!!i)});n.common.issues.push(r)}var w=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if(i.status==="aborted")return m;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let i of t){let s=await i.key,a=await i.value;r.push({key:s,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return m;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:e.value,value:r}}},m=Object.freeze({status:"aborted"}),J=n=>({status:"dirty",value:n}),T=n=>({status:"valid",value:n}),Se=n=>n.status==="aborted",Ae=n=>n.status==="dirty",F=n=>n.status==="valid",fe=n=>typeof Promise<"u"&&n instanceof Promise;var f;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(f||(f={}));var C=class{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}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}},Ye=(n,e)=>{if(F(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new E(n.common.issues);return this._error=t,this._error}}};function v(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:i}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{let{message:d}=n;return a.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:i}}var x=class{get description(){return this._def.description}_getType(e){return R(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:R(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(fe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},i=this._parseSync({data:e,path:r.path,parent:r});return Ye(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return F(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>F(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:R(e)},i=this._parse({data:e,path:r.path,parent:r}),s=await(fe(i)?i:Promise.resolve(i));return Ye(r,s)}refine(e,t){let r=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,s)=>{let a=e(i),o=()=>s.addIssue({code:l.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof t=="function"?t(r,i):t),!1))}_refinement(e){return new M({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return A.create(this,this._def)}nullable(){return B.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return V.create(this)}promise(){return q.create(this,this._def)}or(e){return ne.create([this,e],this._def)}and(e){return re.create(this,e,this._def)}transform(e){return new M({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ce({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new Te({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new le({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return de.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},wt=/^c[^\s-]{8,}$/i,Tt=/^[0-9a-z]+$/,Et=/^[0-9A-HJKMNP-TV-Z]{26}$/i,St=/^[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,At=/^[a-z0-9_-]{21}$/i,Ct=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Mt=/^[-+]?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)?)??$/,Ot=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Rt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$e,Nt=/^(?:(?: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])$/,Bt=/^(?:(?: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])$/,jt=/^(([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]))$/,It=/^(([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])$/,Lt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Pt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qe="((\\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])))",$t=new RegExp(`^${Qe}$`);function Ke(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Vt(n){return new RegExp(`^${Ke(n)}$`)}function et(n){let e=`${Qe}T${Ke(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Dt(n,e){return!!((e==="v4"||!e)&&Nt.test(n)||(e==="v6"||!e)&&jt.test(n))}function Zt(n,e){if(!Ct.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Ht(n,e){return!!((e==="v4"||!e)&&Bt.test(n)||(e==="v6"||!e)&&It.test(n))}var U=class n extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_type,expected:p.string,received:s.parsedType}),m}let r=new w,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?u(i,{code:l.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&u(i,{code:l.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ot.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"email",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")$e||($e=new RegExp(Rt,"u")),$e.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"emoji",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")St.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"uuid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")At.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"nanoid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")wt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"cuid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Tt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"cuid2",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Et.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"ulid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),u(i,{validation:"url",code:l.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"regex",code:l.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?et(s).test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?$t.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Vt(s).test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Mt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"duration",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Dt(e.data,s.version)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"ip",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Zt(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"jwt",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Ht(e.data,s.version)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"cidr",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Lt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"base64",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Pt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"base64url",code:l.invalid_string,message:s.message}),r.dirty()):b.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(i=>e.test(i),{validation:t,code:l.invalid_string,...f.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...f.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...f.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...f.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...f.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...f.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...f.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...f.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...f.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...f.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...f.errToObj(t)})}nonempty(e){return this.min(1,f.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...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}};U.create=n=>new U({checks:[],typeName:g.ZodString,coerce:n?.coerce??!1,...v(n)});function zt(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=t>r?t:r,s=Number.parseInt(n.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var Y=class n extends x{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)!==p.number){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_type,expected:p.number,received:s.parsedType}),m}let r,i=new w;for(let s of this._def.checks)s.kind==="int"?b.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:l.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?zt(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:l.not_finite,message:s.message}),i.dirty()):b.assertNever(s);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,r,i){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:f.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:f.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.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"&&b.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Y.create=n=>new Y({checks:[],typeName:g.ZodNumber,coerce:n?.coerce||!1,...v(n)});var X=class n extends x{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)!==p.bigint)return this._getInvalidInput(e);let r,i=new w;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):b.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return u(t,{code:l.invalid_type,expected:p.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,r,i){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.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}};X.create=n=>new X({checks:[],typeName:g.ZodBigInt,coerce:n?.coerce??!1,...v(n)});var Q=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.boolean,received:r.parsedType}),m}return T(e.data)}};Q.create=n=>new Q({typeName:g.ZodBoolean,coerce:n?.coerce||!1,...v(n)});var K=class n extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_type,expected:p.date,received:s.parsedType}),m}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_date}),m}let r=new w,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):b.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:f.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:f.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?new Date(e):null}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?new Date(e):null}};K.create=n=>new K({checks:[],coerce:n?.coerce||!1,typeName:g.ZodDate,...v(n)});var ge=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.symbol,received:r.parsedType}),m}return T(e.data)}};ge.create=n=>new ge({typeName:g.ZodSymbol,...v(n)});var ee=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.undefined,received:r.parsedType}),m}return T(e.data)}};ee.create=n=>new ee({typeName:g.ZodUndefined,...v(n)});var te=class extends x{_parse(e){if(this._getType(e)!==p.null){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.null,received:r.parsedType}),m}return T(e.data)}};te.create=n=>new te({typeName:g.ZodNull,...v(n)});var W=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};W.create=n=>new W({typeName:g.ZodAny,...v(n)});var $=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};$.create=n=>new $({typeName:g.ZodUnknown,...v(n)});var O=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return u(t,{code:l.invalid_type,expected:p.never,received:t.parsedType}),m}};O.create=n=>new O({typeName:g.ZodNever,...v(n)});var ye=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.void,received:r.parsedType}),m}return T(e.data)}};ye.create=n=>new ye({typeName:g.ZodVoid,...v(n)});var V=class n extends x{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==p.array)return u(t,{code:l.invalid_type,expected:p.array,received:t.parsedType}),m;if(i.exactLength!==null){let a=t.data.length>i.exactLength.value,o=t.data.length<i.exactLength.value;(a||o)&&(u(t,{code:a?l.too_big:l.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(u(t,{code:l.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(u(t,{code:l.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>i.type._parseAsync(new C(t,a,t.path,o)))).then(a=>w.mergeArray(r,a));let s=[...t.data].map((a,o)=>i.type._parseSync(new C(t,a,t.path,o)));return w.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:f.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:f.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:f.toString(t)}})}nonempty(e){return this.min(1,e)}};V.create=(n,e)=>new V({type:n,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...v(e)});function me(n){if(n instanceof S){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=A.create(me(r))}return new S({...n._def,shape:()=>e})}else return n instanceof V?new V({...n._def,type:me(n.element)}):n instanceof A?A.create(me(n.unwrap())):n instanceof B?B.create(me(n.unwrap())):n instanceof N?N.create(n.items.map(e=>me(e))):n}var S=class n extends x{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=b.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==p.object){let h=this._getOrReturnCtx(e);return u(h,{code:l.invalid_type,expected:p.object,received:h.parsedType}),m}let{status:r,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof O&&this._def.unknownKeys==="strip"))for(let h in i.data)a.includes(h)||o.push(h);let d=[];for(let h of a){let y=s[h],_=i.data[h];d.push({key:{status:"valid",value:h},value:y._parse(new C(i,_,i.path,h)),alwaysSet:h in i.data})}if(this._def.catchall instanceof O){let h=this._def.unknownKeys;if(h==="passthrough")for(let y of o)d.push({key:{status:"valid",value:y},value:{status:"valid",value:i.data[y]}});else if(h==="strict")o.length>0&&(u(i,{code:l.unrecognized_keys,keys:o}),r.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let h=this._def.catchall;for(let y of o){let _=i.data[y];d.push({key:{status:"valid",value:y},value:h._parse(new C(i,_,i.path,y)),alwaysSet:y in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let h=[];for(let y of d){let _=await y.key,_e=await y.value;h.push({key:_,value:_e,alwaysSet:y.alwaysSet})}return h}).then(h=>w.mergeObjectSync(r,h)):w.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return f.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:f.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of b.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of b.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return me(this)}partial(e){let t={};for(let r of b.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of b.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof A;)s=s._def.innerType;t[r]=s}return new n({...this._def,shape:()=>t})}keyof(){return tt(b.objectKeys(this.shape))}};S.create=(n,e)=>new S({shape:()=>n,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,...v(e)});S.strictCreate=(n,e)=>new S({shape:()=>n,unknownKeys:"strict",catchall:O.create(),typeName:g.ZodObject,...v(e)});S.lazycreate=(n,e)=>new S({shape:n,unknownKeys:"strip",catchall:O.create(),typeName:g.ZodObject,...v(e)});var ne=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(o=>new E(o.ctx.common.issues));return u(t,{code:l.invalid_union,unionErrors:a}),m}if(t.common.async)return Promise.all(r.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let d of r){let h={...t,common:{...t.common,issues:[]},parent:null},y=d._parseSync({data:t.data,path:t.path,parent:h});if(y.status==="valid")return y;y.status==="dirty"&&!s&&(s={result:y,ctx:h}),h.common.issues.length&&a.push(h.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(d=>new E(d));return u(t,{code:l.invalid_union,unionErrors:o}),m}}get options(){return this._def.options}};ne.create=(n,e)=>new ne({options:n,typeName:g.ZodUnion,...v(e)});var P=n=>n instanceof ie?P(n.schema):n instanceof M?P(n.innerType()):n instanceof se?[n.value]:n instanceof ae?n.options:n instanceof oe?b.objectValues(n.enum):n instanceof ce?P(n._def.innerType):n instanceof ee?[void 0]:n instanceof te?[null]:n instanceof A?[void 0,...P(n.unwrap())]:n instanceof B?[null,...P(n.unwrap())]:n instanceof Te||n instanceof de?P(n.unwrap()):n instanceof le?P(n._def.innerType):[],Ce=class n extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.object)return u(t,{code:l.invalid_type,expected:p.object,received:t.parsedType}),m;let r=this.discriminator,i=t.data[r],s=this.optionsMap.get(i);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let s of t){let a=P(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new n({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...v(r)})}};function Ve(n,e){let t=R(n),r=R(e);if(n===e)return{valid:!0,data:n};if(t===p.object&&r===p.object){let i=b.objectKeys(e),s=b.objectKeys(n).filter(o=>i.indexOf(o)!==-1),a={...n,...e};for(let o of s){let d=Ve(n[o],e[o]);if(!d.valid)return{valid:!1};a[o]=d.data}return{valid:!0,data:a}}else if(t===p.array&&r===p.array){if(n.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<n.length;s++){let a=n[s],o=e[s],d=Ve(a,o);if(!d.valid)return{valid:!1};i.push(d.data)}return{valid:!0,data:i}}else return t===p.date&&r===p.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var re=class extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(s,a)=>{if(Se(s)||Se(a))return m;let o=Ve(s.value,a.value);return o.valid?((Ae(s)||Ae(a))&&t.dirty(),{status:t.value,value:o.data}):(u(r,{code:l.invalid_intersection_types}),m)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};re.create=(n,e,t)=>new re({left:n,right:e,typeName:g.ZodIntersection,...v(t)});var N=class n extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.array)return u(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),m;if(r.data.length<this._def.items.length)return u(r,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&r.data.length>this._def.items.length&&(u(r,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let s=[...r.data].map((a,o)=>{let d=this._def.items[o]||this._def.rest;return d?d._parse(new C(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>w.mergeArray(t,a)):w.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};N.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new N({items:n,typeName:g.ZodTuple,rest:null,...v(e)})};var Me=class n extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return u(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),m;let i=[],s=this._def.keyType,a=this._def.valueType;for(let o in r.data)i.push({key:s._parse(new C(r,o,r.path,o)),value:a._parse(new C(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?w.mergeObjectAsync(t,i):w.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof x?new n({keyType:e,valueType:t,typeName:g.ZodRecord,...v(r)}):new n({keyType:U.create(),valueType:e,typeName:g.ZodRecord,...v(t)})}},ve=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.map)return u(r,{code:l.invalid_type,expected:p.map,received:r.parsedType}),m;let i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([o,d],h)=>({key:i._parse(new C(r,o,r.path,[h,"key"])),value:s._parse(new C(r,d,r.path,[h,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let d of a){let h=await d.key,y=await d.value;if(h.status==="aborted"||y.status==="aborted")return m;(h.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(h.value,y.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let d of a){let h=d.key,y=d.value;if(h.status==="aborted"||y.status==="aborted")return m;(h.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(h.value,y.value)}return{status:t.value,value:o}}}};ve.create=(n,e,t)=>new ve({valueType:e,keyType:n,typeName:g.ZodMap,...v(t)});var xe=class n extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.set)return u(r,{code:l.invalid_type,expected:p.set,received:r.parsedType}),m;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(u(r,{code:l.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(u(r,{code:l.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let s=this._def.valueType;function a(d){let h=new Set;for(let y of d){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),h.add(y.value)}return{status:t.value,value:h}}let o=[...r.data.values()].map((d,h)=>s._parse(new C(r,d,r.path,h)));return r.common.async?Promise.all(o).then(d=>a(d)):a(o)}min(e,t){return new n({...this._def,minSize:{value:e,message:f.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:f.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};xe.create=(n,e)=>new xe({valueType:n,minSize:null,maxSize:null,typeName:g.ZodSet,...v(e)});var Oe=class n extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.function)return u(t,{code:l.invalid_type,expected:p.function,received:t.parsedType}),m;function r(o,d){return we({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),L].filter(h=>!!h),issueData:{code:l.invalid_arguments,argumentsError:d}})}function i(o,d){return we({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),L].filter(h=>!!h),issueData:{code:l.invalid_return_type,returnTypeError:d}})}let s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof q){let o=this;return T(async function(...d){let h=new E([]),y=await o._def.args.parseAsync(d,s).catch(ke=>{throw h.addIssue(r(d,ke)),h}),_=await Reflect.apply(a,this,y);return await o._def.returns._def.type.parseAsync(_,s).catch(ke=>{throw h.addIssue(i(_,ke)),h})})}else{let o=this;return T(function(...d){let h=o._def.args.safeParse(d,s);if(!h.success)throw new E([r(d,h.error)]);let y=Reflect.apply(a,this,h.data),_=o._def.returns.safeParse(y,s);if(!_.success)throw new E([i(y,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:N.create(e).rest($.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||N.create([]).rest($.create()),returns:t||$.create(),typeName:g.ZodFunction,...v(r)})}},ie=class extends x{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})}};ie.create=(n,e)=>new ie({getter:n,typeName:g.ZodLazy,...v(e)});var se=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};se.create=(n,e)=>new se({value:n,typeName:g.ZodLiteral,...v(e)});function tt(n,e){return new ae({values:n,typeName:g.ZodEnum,...v(e)})}var ae=class n extends x{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return u(t,{expected:b.joinValues(r),received:t.parsedType,code:l.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return u(t,{received:t.data,code:l.invalid_enum_value,options:r}),m}return T(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(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};ae.create=tt;var oe=class extends x{_parse(e){let t=b.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==p.string&&r.parsedType!==p.number){let i=b.objectValues(t);return u(r,{expected:b.joinValues(i),received:r.parsedType,code:l.invalid_type}),m}if(this._cache||(this._cache=new Set(b.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=b.objectValues(t);return u(r,{received:r.data,code:l.invalid_enum_value,options:i}),m}return T(e.data)}get enum(){return this._def.values}};oe.create=(n,e)=>new oe({values:n,typeName:g.ZodNativeEnum,...v(e)});var q=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.promise&&t.common.async===!1)return u(t,{code:l.invalid_type,expected:p.promise,received:t.parsedType}),m;let r=t.parsedType===p.promise?t.data:Promise.resolve(t.data);return T(r.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};q.create=(n,e)=>new q({type:n,typeName:g.ZodPromise,...v(e)});var M=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{u(r,a),a.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return m;let d=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return d.status==="aborted"?m:d.status==="dirty"?J(d.value):t.value==="dirty"?J(d.value):d});{if(t.value==="aborted")return m;let o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?m:o.status==="dirty"?J(o.value):t.value==="dirty"?J(o.value):o}}if(i.type==="refinement"){let a=o=>{let d=i.refinement(o,s);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!F(a))return m;let o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>F(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:t.value,value:o})):m);b.assertNever(i)}};M.create=(n,e,t)=>new M({schema:n,typeName:g.ZodEffects,effect:e,...v(t)});M.createWithPreprocess=(n,e,t)=>new M({schema:e,effect:{type:"preprocess",transform:n},typeName:g.ZodEffects,...v(t)});var A=class extends x{_parse(e){return this._getType(e)===p.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A.create=(n,e)=>new A({innerType:n,typeName:g.ZodOptional,...v(e)});var B=class extends x{_parse(e){return this._getType(e)===p.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};B.create=(n,e)=>new B({innerType:n,typeName:g.ZodNullable,...v(e)});var ce=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===p.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ce.create=(n,e)=>new ce({innerType:n,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var le=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return fe(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};le.create=(n,e)=>new le({innerType:n,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var be=class extends x{_parse(e){if(this._getType(e)!==p.nan){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.nan,received:r.parsedType}),m}return{status:"valid",value:e.data}}};be.create=n=>new be({typeName:g.ZodNaN,...v(n)});var Ft=Symbol("zod_brand"),Te=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Ee=class n extends x{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?m:s.status==="dirty"?(t.dirty(),J(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?m:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:g.ZodPipeline})}},de=class extends x{_parse(e){let t=this._def.innerType._parse(e),r=i=>(F(i)&&(i.value=Object.freeze(i.value)),i);return fe(t)?t.then(i=>r(i)):r(t)}unwrap(){return this._def.innerType}};de.create=(n,e)=>new de({innerType:n,typeName:g.ZodReadonly,...v(e)});function Xe(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function nt(n,e={},t){return n?W.create().superRefine((r,i)=>{let s=n(r);if(s instanceof Promise)return s.then(a=>{if(!a){let o=Xe(e,r),d=o.fatal??t??!0;i.addIssue({code:"custom",...o,fatal:d})}});if(!s){let a=Xe(e,r),o=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:o})}}):W.create()}var Ut={object:S.lazycreate},g;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(g||(g={}));var Wt=(n,e={message:`Input not instance of ${n.name}`})=>nt(t=>t instanceof n,e),rt=U.create,it=Y.create,qt=be.create,Gt=X.create,st=Q.create,Jt=K.create,Yt=ge.create,Xt=ee.create,Qt=te.create,Kt=W.create,en=$.create,tn=O.create,nn=ye.create,rn=V.create,sn=S.create,an=S.strictCreate,on=ne.create,cn=Ce.create,ln=re.create,dn=N.create,un=Me.create,hn=ve.create,pn=xe.create,fn=Oe.create,mn=ie.create,gn=se.create,yn=ae.create,vn=oe.create,xn=q.create,bn=M.create,_n=A.create,kn=B.create,wn=M.createWithPreprocess,Tn=Ee.create,En=()=>rt().optional(),Sn=()=>it().optional(),An=()=>st().optional(),Cn={string:n=>U.create({...n,coerce:!0}),number:n=>Y.create({...n,coerce:!0}),boolean:n=>Q.create({...n,coerce:!0}),bigint:n=>X.create({...n,coerce:!0}),date:n=>K.create({...n,coerce:!0})};var Mn=m;var at=c.object({method:c.enum(["POST","PUT","PATCH","DELETE"]),url:c.string()}),On=c.object({id:c.string(),label:c.string(),selector:c.string(),fallbacks:c.array(c.string()),does:c.string(),confidence:c.number().min(0).max(1),evidence:c.array(c.string()),apiCall:at.nullable().optional()}),Rn=c.object({id:c.string(),route:c.string(),file:c.string(),title:c.string(),purpose:c.string(),whenToUse:c.string(),confidence:c.number().min(0).max(1),elements:c.array(On)}),Nn=c.object({candidates:c.array(c.string()),chose:c.string(),reason:c.string(),confidence:c.number().min(0).max(1)}),jr=c.object({version:c.literal("1"),commit:c.string(),generatedAt:c.string(),pages:c.array(Rn),dead:c.array(c.string()),conflicts:c.array(Nn)}),D=()=>c.preprocess(n=>n===null?void 0:n,c.string().optional()),Bn=()=>c.preprocess(n=>n===null?void 0:n,at.optional()),jn=()=>c.preprocess(n=>n===null?void 0:n,c.boolean().optional()),ot=()=>c.preprocess(n=>n===null?void 0:n,c.record(c.string(),c.unknown()).optional()),In=()=>c.preprocess(n=>n===null?void 0:n,c.array(c.unknown()).optional()),j={text:D(),target:D(),route:D(),action:D(),value:D(),name:D(),args:ot(),steps:In()},ct=c.discriminatedUnion("verb",[c.object({...j,verb:c.literal("explain"),text:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("highlight"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("open"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("navigate"),route:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("do"),action:c.string().min(1),target:D(),apiCall:Bn()}).strict(),c.object({...j,verb:c.literal("tour"),steps:c.array(c.object({text:c.string().min(1),target:D(),route:D(),click:jn()}).strict()).min(2).max(6)}).strict(),c.object({...j,verb:c.literal("click"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("fill"),target:c.string().min(1),value:c.string()}).strict(),c.object({...j,verb:c.literal("read"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("call_tool"),name:c.string().min(1),args:ot()}).strict()]),Ln=c.object({role:c.enum(["user","assistant"]),text:c.string()}),Pn=c.object({id:c.string().max(200),role:c.string().max(50),label:c.string().max(120)}),$n=c.object({name:c.string().max(200),description:c.string().max(500),inputSchema:c.record(c.string(),c.unknown()).optional()}),Ir=c.object({route:c.string(),question:c.string().min(1),visible:c.array(c.string()),history:c.array(Ln).optional(),liveElements:c.array(Pn).max(60).optional(),webMcpTools:c.array($n).max(30).optional()});function Vn(){return typeof document>"u"?null:document.modelContext??null}async function lt(n,e){let t=Vn();if(!t?.getTools||!t.executeTool)return{ok:!1,observation:"This page no longer has that tool available."};try{let r=await t.getTools(),i=Array.isArray(r)?r.find(o=>o.name===n):void 0;if(!i)return{ok:!1,observation:`No tool named "${n}" is available on this page right now.`};let s=await t.executeTool(i,e??{});return{ok:!0,observation:(typeof s=="string"?s:JSON.stringify(s??null)).slice(0,2e3)}}catch(r){return{ok:!1,observation:`That tool failed: ${r instanceof Error?r.message:"unknown error"}`}}}var Dn="I'm not sure \u2014 I couldn't understand that response. Try rephrasing your question.";function dt(n,e,t){let r=ct.safeParse(n);if(!r.success){t.onExplain(Dn);return}Zn(r.data,e,t)}function Zn(n,e,t){switch(n.verb){case"explain":t.onExplain(n.text);return;case"highlight":case"open":{let r=H(n.target,t.liveElements);if(!r){(t.onMiss??z)({attempted:n.target,route:e}),t.onExplain(n.text??"I know what you need, but I can't find it on this page right now.");return}G(r),n.verb==="open"&&r.click(),n.text&&t.onExplain(n.text);return}case"navigate":t.onNavigate?.(n.route),n.text&&t.onExplain(n.text);return;case"do":{if((t.registeredActions??[]).includes(n.action)){t.onDo?.(n.action,n.target),n.text&&t.onExplain(n.text);return}if(n.target||n.apiCall){let i=n.target?H(n.target,t.liveElements):null;if(i){G(i),i.click(),n.text&&t.onExplain(n.text);return}if(n.target&&(t.onMiss??z)({attempted:n.target,route:e}),n.apiCall){n.text&&t.onExplain(n.text),Hn(n.apiCall).then(s=>{s.ok||t.onExplain("I tried to do that, but something went wrong \u2014 try again in a moment.")});return}}t.onExplain(n.text??"That action isn't available here.");return}case"tour":t.onTour?t.onTour(n.steps):t.onExplain(n.steps.map(r=>r.text).join(" "));return;case"click":{n.text&&t.onExplain(n.text);let r=H(n.target,t.liveElements);if(!r){(t.onMiss??z)({attempted:n.target,route:e}),t.onToolStep?.({verb:"click",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}G(r),r.click(),t.onToolStep?.({verb:"click",target:n.target,ok:!0,observation:"Clicked it."});return}case"fill":{n.text&&t.onExplain(n.text);let r=H(n.target,t.liveElements);if(!r||!qe(r,n.value)){(t.onMiss??z)({attempted:n.target,route:e}),t.onToolStep?.({verb:"fill",target:n.target,ok:!1,observation:r?"That element isn't a real form field \u2014 can't type into it.":"Could not find that element on the page."});return}G(r),t.onToolStep?.({verb:"fill",target:n.target,ok:!0,observation:`Typed "${n.value}" into it.`});return}case"read":{n.text&&t.onExplain(n.text);let r=H(n.target,t.liveElements);if(!r){(t.onMiss??z)({attempted:n.target,route:e}),t.onToolStep?.({verb:"read",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}t.onToolStep?.({verb:"read",target:n.target,ok:!0,observation:Ge(r)});return}case"call_tool":{n.text&&t.onExplain(n.text),lt(n.name,n.args).then(r=>{t.onToolStep?.({verb:"call_tool",target:n.name,ok:r.ok,observation:r.observation})});return}}}async function Hn(n){try{let e=await fetch(n.url,{method:n.method,credentials:"same-origin"});return{ok:e.ok,status:e.status}}catch{return{ok:!1}}}var zn={idle:"",asking:"Thinking\u2026",recording:"Listening \u2014 transcribing live\u2026","rt-connecting":"Connecting\u2026","rt-listening":"Listening\u2026","rt-thinking":"Thinking\u2026","rt-speaking":"Speaking\u2026"},Fn=8,Un=`
1
+ "use strict";(()=>{var vt=Object.defineProperty;var bt=(n,e)=>{for(var t in e)vt(n,t,{get:e[t],enumerable:!0})};function Le(){if(typeof document>"u"||typeof window>"u")return[];let n=document.querySelectorAll("[data-ai]"),e=[];return n.forEach(t=>{let r=t.getBoundingClientRect();if(!(r.bottom>0&&r.top<window.innerHeight&&r.right>0&&r.left<window.innerWidth))return;let s=t.getAttribute("data-ai");s&&e.push(s)}),e}function R(n,e){let t=e?.get(n);if(t)return t;if(typeof document>"u")return null;let r=document.querySelector(`[data-ai="${$e(n)}"]`);if(r)return r;let i=document.querySelector(`[aria-label="${$e(n)}"]`);if(i)return i;let s=document.querySelector(`[role="${$e(n)}"]`);if(s)return s;let a=document.querySelectorAll("button, a, [role='button'], input[type='submit'], input[type='button']"),o=Pe(n);for(let d of Array.from(a))if(Pe(d.textContent??"")===o)return d;for(let d of Array.from(a))if(Pe(d.textContent??"").includes(o))return d;return null}function V(n,e=4e3){n.scrollIntoView({behavior:"smooth",block:"center"}),n.classList.add("cairn-glow"),window.setTimeout(()=>n.classList.remove("cairn-glow"),e)}function Xe(n){return n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.tagName==="SELECT"}function Ve(n,e){if(!Xe(n))return!1;let r=(typeof window<"u"?{INPUT:window.HTMLInputElement,TEXTAREA:window.HTMLTextAreaElement,SELECT:window.HTMLSelectElement}:{})[n.tagName],i=r&&Object.getOwnPropertyDescriptor(r.prototype,"value")?.set;return i?i.call(n,e):n.value=e,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0})),!0}function De(n){let t=(Xe(n)?n.value:n.textContent??"").replace(/\s+/g," ").trim();return t.length>500?`${t.slice(0,499)}\u2026`:t||"(empty)"}var Ye="cairn:misses",xt=200;function N(n){try{let e=window.localStorage.getItem(Ye),t=e?JSON.parse(e):[];t.push({...n,at:new Date().toISOString()}),window.localStorage.setItem(Ye,JSON.stringify(t.slice(-xt)))}catch{}}function Pe(n){return n.trim().toLowerCase().replace(/\s+/g," ")}function $e(n){return n.replace(/["\\]/g,"\\$&")}var c={};bt(c,{BRAND:()=>Wt,DIRTY:()=>J,EMPTY_PATH:()=>Tt,INVALID:()=>m,NEVER:()=>Rn,OK:()=>T,ParseStatus:()=>w,Schema:()=>b,ZodAny:()=>q,ZodArray:()=>z,ZodBigInt:()=>X,ZodBoolean:()=>Q,ZodBranded:()=>Te,ZodCatch:()=>le,ZodDate:()=>K,ZodDefault:()=>ce,ZodDiscriminatedUnion:()=>Ce,ZodEffects:()=>M,ZodEnum:()=>ae,ZodError:()=>E,ZodFirstPartyTypeKind:()=>g,ZodFunction:()=>Oe,ZodIntersection:()=>re,ZodIssueCode:()=>l,ZodLazy:()=>ie,ZodLiteral:()=>se,ZodMap:()=>ve,ZodNaN:()=>xe,ZodNativeEnum:()=>oe,ZodNever:()=>B,ZodNull:()=>te,ZodNullable:()=>P,ZodNumber:()=>Y,ZodObject:()=>S,ZodOptional:()=>A,ZodParsedType:()=>p,ZodPipeline:()=>Ee,ZodPromise:()=>G,ZodReadonly:()=>de,ZodRecord:()=>Me,ZodSchema:()=>b,ZodSet:()=>be,ZodString:()=>W,ZodSymbol:()=>ge,ZodTransformer:()=>M,ZodTuple:()=>L,ZodType:()=>b,ZodUndefined:()=>ee,ZodUnion:()=>ne,ZodUnknown:()=>H,ZodVoid:()=>ye,addIssueToContext:()=>u,any:()=>tn,array:()=>an,bigint:()=>Yt,boolean:()=>ct,coerce:()=>On,custom:()=>st,date:()=>Xt,datetimeRegex:()=>rt,defaultErrorMap:()=>D,discriminatedUnion:()=>dn,effect:()=>kn,enum:()=>bn,function:()=>gn,getErrorMap:()=>pe,getParsedType:()=>I,instanceof:()=>Gt,intersection:()=>un,isAborted:()=>Se,isAsync:()=>fe,isDirty:()=>Ae,isValid:()=>U,late:()=>qt,lazy:()=>yn,literal:()=>vn,makeIssue:()=>we,map:()=>fn,nan:()=>Jt,nativeEnum:()=>xn,never:()=>rn,null:()=>en,nullable:()=>Tn,number:()=>ot,object:()=>on,objectUtil:()=>Ze,oboolean:()=>Mn,onumber:()=>Cn,optional:()=>wn,ostring:()=>An,pipeline:()=>Sn,preprocess:()=>En,promise:()=>_n,quotelessJson:()=>_t,record:()=>pn,set:()=>mn,setErrorMap:()=>wt,strictObject:()=>cn,string:()=>at,symbol:()=>Qt,transformer:()=>kn,tuple:()=>hn,undefined:()=>Kt,union:()=>ln,unknown:()=>nn,util:()=>x,void:()=>sn});var x;(function(n){n.assertEqual=i=>{};function e(i){}n.assertIs=e;function t(i){throw new Error}n.assertNever=t,n.arrayToEnum=i=>{let s={};for(let a of i)s[a]=a;return s},n.getValidEnumValues=i=>{let s=n.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(let o of s)a[o]=i[o];return n.objectValues(a)},n.objectValues=i=>n.objectKeys(i).map(function(s){return i[s]}),n.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let s=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},n.find=(i,s)=>{for(let a of i)if(s(a))return a},n.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}n.joinValues=r,n.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(x||(x={}));var Ze;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Ze||(Ze={}));var p=x.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I=n=>{switch(typeof n){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(n)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(n)?p.array:n===null?p.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?p.promise:typeof Map<"u"&&n instanceof Map?p.map:typeof Set<"u"&&n instanceof Set?p.set:typeof Date<"u"&&n instanceof Date?p.date:p.object;default:return p.unknown}};var l=x.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),_t=n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),E=class n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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(s){return s.message},r={_errors:[]},i=s=>{for(let a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let o=r,d=0;for(;d<a.path.length;){let h=a.path[d];d===a.path.length-1?(o[h]=o[h]||{_errors:[]},o[h]._errors.push(t(a))):o[h]=o[h]||{_errors:[]},o=o[h],d++}}};return i(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,x.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let i of this.issues)if(i.path.length>0){let s=i.path[0];t[s]=t[s]||[],t[s].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};E.create=n=>new E(n);var kt=(n,e)=>{let t;switch(n.code){case l.invalid_type:n.received===p.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case l.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,x.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:t=`Unrecognized key(s) in object: ${x.joinValues(n.keys,", ")}`;break;case l.invalid_union:t="Invalid input";break;case l.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${x.joinValues(n.options)}`;break;case l.invalid_enum_value:t=`Invalid enum value. Expected ${x.joinValues(n.options)}, received '${n.received}'`;break;case l.invalid_arguments:t="Invalid function arguments";break;case l.invalid_return_type:t="Invalid function return type";break;case l.invalid_date:t="Invalid date";break;case l.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:x.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case l.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case l.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case l.custom:t="Invalid input";break;case l.invalid_intersection_types:t="Intersection results could not be merged";break;case l.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case l.not_finite:t="Number must be finite";break;default:t=e.defaultError,x.assertNever(n)}return{message:t}},D=kt;var Qe=D;function wt(n){Qe=n}function pe(){return Qe}var we=n=>{let{data:e,path:t,errorMaps:r,issueData:i}=n,s=[...t,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="",d=r.filter(h=>!!h).slice().reverse();for(let h of d)o=h(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},Tt=[];function u(n,e){let t=pe(),r=we({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===D?void 0:D].filter(i=>!!i)});n.common.issues.push(r)}var w=class n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let i of t){if(i.status==="aborted")return m;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let i of t){let s=await i.key,a=await i.value;r.push({key:s,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let i of t){let{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return m;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:e.value,value:r}}},m=Object.freeze({status:"aborted"}),J=n=>({status:"dirty",value:n}),T=n=>({status:"valid",value:n}),Se=n=>n.status==="aborted",Ae=n=>n.status==="dirty",U=n=>n.status==="valid",fe=n=>typeof Promise<"u"&&n instanceof Promise;var f;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(f||(f={}));var C=class{constructor(e,t,r,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=i}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}},Ke=(n,e)=>{if(U(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new E(n.common.issues);return this._error=t,this._error}}};function v(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:i}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{let{message:d}=n;return a.code==="invalid_enum_value"?{message:d??o.defaultError}:typeof o.data>"u"?{message:d??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:d??t??o.defaultError}},description:i}}var b=class{get description(){return this._def.description}_getType(e){return I(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:I(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:I(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(fe(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:I(e)},i=this._parseSync({data:e,path:r.path,parent:r});return Ke(r,i)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:I(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return U(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>U(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:I(e)},i=this._parse({data:e,path:r.path,parent:r}),s=await(fe(i)?i:Promise.resolve(i));return Ke(r,s)}refine(e,t){let r=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,s)=>{let a=e(i),o=()=>s.addIssue({code:l.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof t=="function"?t(r,i):t),!1))}_refinement(e){return new M({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return A.create(this,this._def)}nullable(){return P.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return z.create(this)}promise(){return G.create(this,this._def)}or(e){return ne.create([this,e],this._def)}and(e){return re.create(this,e,this._def)}transform(e){return new M({...v(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new ce({...v(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new Te({typeName:g.ZodBranded,type:this,...v(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new le({...v(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return de.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Et=/^c[^\s-]{8,}$/i,St=/^[0-9a-z]+$/,At=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ct=/^[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,Mt=/^[a-z0-9_-]{21}$/i,Ot=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rt=/^[-+]?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)?)??$/,Nt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",He,jt=/^(?:(?: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])$/,It=/^(?:(?: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])$/,Lt=/^(([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]))$/,Pt=/^(([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])$/,$t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Vt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,tt="((\\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])))",Dt=new RegExp(`^${tt}$`);function nt(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Zt(n){return new RegExp(`^${nt(n)}$`)}function rt(n){let e=`${tt}T${nt(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ht(n,e){return!!((e==="v4"||!e)&&jt.test(n)||(e==="v6"||!e)&&Lt.test(n))}function zt(n,e){if(!Ot.test(n))return!1;try{let[t]=n.split(".");if(!t)return!1;let r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Ft(n,e){return!!((e==="v4"||!e)&&It.test(n)||(e==="v6"||!e)&&Pt.test(n))}var W=class n extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_type,expected:p.string,received:s.parsedType}),m}let r=new w,i;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?u(i,{code:l.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&u(i,{code:l.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Nt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"email",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")He||(He=new RegExp(Bt,"u")),He.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"emoji",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Ct.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"uuid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Mt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"nanoid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Et.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"cuid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")St.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"cuid2",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")At.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"ulid",code:l.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),u(i,{validation:"url",code:l.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"regex",code:l.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?rt(s).test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Dt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?Zt(s).test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{code:l.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Rt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"duration",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Ht(e.data,s.version)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"ip",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?zt(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"jwt",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?Ft(e.data,s.version)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"cidr",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?$t.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"base64",code:l.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Vt.test(e.data)||(i=this._getOrReturnCtx(e,i),u(i,{validation:"base64url",code:l.invalid_string,message:s.message}),r.dirty()):x.assertNever(s);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(i=>e.test(i),{validation:t,code:l.invalid_string,...f.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...f.errToObj(e)})}url(e){return this._addCheck({kind:"url",...f.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...f.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...f.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...f.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...f.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...f.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...f.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...f.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...f.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...f.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...f.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...f.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...f.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...f.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...f.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...f.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...f.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...f.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...f.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...f.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...f.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...f.errToObj(t)})}nonempty(e){return this.min(1,f.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...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}};W.create=n=>new W({checks:[],typeName:g.ZodString,coerce:n?.coerce??!1,...v(n)});function Ut(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=t>r?t:r,s=Number.parseInt(n.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}var Y=class n extends b{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)!==p.number){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_type,expected:p.number,received:s.parsedType}),m}let r,i=new w;for(let s of this._def.checks)s.kind==="int"?x.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:l.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?Ut(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),u(r,{code:l.not_finite,message:s.message}),i.dirty()):x.assertNever(s);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,r,i){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:f.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:f.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.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"&&x.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Y.create=n=>new Y({checks:[],typeName:g.ZodNumber,coerce:n?.coerce||!1,...v(n)});var X=class n extends b{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)!==p.bigint)return this._getInvalidInput(e);let r,i=new w;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),u(r,{code:l.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):x.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return u(t,{code:l.invalid_type,expected:p.bigint,received:t.parsedType}),m}gte(e,t){return this.setLimit("min",e,!0,f.toString(t))}gt(e,t){return this.setLimit("min",e,!1,f.toString(t))}lte(e,t){return this.setLimit("max",e,!0,f.toString(t))}lt(e,t){return this.setLimit("max",e,!1,f.toString(t))}setLimit(e,t,r,i){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:f.toString(i)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:f.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}};X.create=n=>new X({checks:[],typeName:g.ZodBigInt,coerce:n?.coerce??!1,...v(n)});var Q=class extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.boolean,received:r.parsedType}),m}return T(e.data)}};Q.create=n=>new Q({typeName:g.ZodBoolean,coerce:n?.coerce||!1,...v(n)});var K=class n extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_type,expected:p.date,received:s.parsedType}),m}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return u(s,{code:l.invalid_date}),m}let r=new w,i;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),u(i,{code:l.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):x.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:f.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:f.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?new Date(e):null}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?new Date(e):null}};K.create=n=>new K({checks:[],coerce:n?.coerce||!1,typeName:g.ZodDate,...v(n)});var ge=class extends b{_parse(e){if(this._getType(e)!==p.symbol){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.symbol,received:r.parsedType}),m}return T(e.data)}};ge.create=n=>new ge({typeName:g.ZodSymbol,...v(n)});var ee=class extends b{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.undefined,received:r.parsedType}),m}return T(e.data)}};ee.create=n=>new ee({typeName:g.ZodUndefined,...v(n)});var te=class extends b{_parse(e){if(this._getType(e)!==p.null){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.null,received:r.parsedType}),m}return T(e.data)}};te.create=n=>new te({typeName:g.ZodNull,...v(n)});var q=class extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return T(e.data)}};q.create=n=>new q({typeName:g.ZodAny,...v(n)});var H=class extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return T(e.data)}};H.create=n=>new H({typeName:g.ZodUnknown,...v(n)});var B=class extends b{_parse(e){let t=this._getOrReturnCtx(e);return u(t,{code:l.invalid_type,expected:p.never,received:t.parsedType}),m}};B.create=n=>new B({typeName:g.ZodNever,...v(n)});var ye=class extends b{_parse(e){if(this._getType(e)!==p.undefined){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.void,received:r.parsedType}),m}return T(e.data)}};ye.create=n=>new ye({typeName:g.ZodVoid,...v(n)});var z=class n extends b{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),i=this._def;if(t.parsedType!==p.array)return u(t,{code:l.invalid_type,expected:p.array,received:t.parsedType}),m;if(i.exactLength!==null){let a=t.data.length>i.exactLength.value,o=t.data.length<i.exactLength.value;(a||o)&&(u(t,{code:a?l.too_big:l.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&t.data.length<i.minLength.value&&(u(t,{code:l.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&t.data.length>i.maxLength.value&&(u(t,{code:l.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>i.type._parseAsync(new C(t,a,t.path,o)))).then(a=>w.mergeArray(r,a));let s=[...t.data].map((a,o)=>i.type._parseSync(new C(t,a,t.path,o)));return w.mergeArray(r,s)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:f.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:f.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:f.toString(t)}})}nonempty(e){return this.min(1,e)}};z.create=(n,e)=>new z({type:n,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...v(e)});function me(n){if(n instanceof S){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=A.create(me(r))}return new S({...n._def,shape:()=>e})}else return n instanceof z?new z({...n._def,type:me(n.element)}):n instanceof A?A.create(me(n.unwrap())):n instanceof P?P.create(me(n.unwrap())):n instanceof L?L.create(n.items.map(e=>me(e))):n}var S=class n extends b{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=x.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==p.object){let h=this._getOrReturnCtx(e);return u(h,{code:l.invalid_type,expected:p.object,received:h.parsedType}),m}let{status:r,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof B&&this._def.unknownKeys==="strip"))for(let h in i.data)a.includes(h)||o.push(h);let d=[];for(let h of a){let y=s[h],_=i.data[h];d.push({key:{status:"valid",value:h},value:y._parse(new C(i,_,i.path,h)),alwaysSet:h in i.data})}if(this._def.catchall instanceof B){let h=this._def.unknownKeys;if(h==="passthrough")for(let y of o)d.push({key:{status:"valid",value:y},value:{status:"valid",value:i.data[y]}});else if(h==="strict")o.length>0&&(u(i,{code:l.unrecognized_keys,keys:o}),r.dirty());else if(h!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let h=this._def.catchall;for(let y of o){let _=i.data[y];d.push({key:{status:"valid",value:y},value:h._parse(new C(i,_,i.path,y)),alwaysSet:y in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let h=[];for(let y of d){let _=await y.key,_e=await y.value;h.push({key:_,value:_e,alwaysSet:y.alwaysSet})}return h}).then(h=>w.mergeObjectSync(r,h)):w.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return f.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let i=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:f.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};for(let r of x.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}omit(e){let t={};for(let r of x.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new n({...this._def,shape:()=>t})}deepPartial(){return me(this)}partial(e){let t={};for(let r of x.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?t[r]=i:t[r]=i.optional()}return new n({...this._def,shape:()=>t})}required(e){let t={};for(let r of x.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof A;)s=s._def.innerType;t[r]=s}return new n({...this._def,shape:()=>t})}keyof(){return it(x.objectKeys(this.shape))}};S.create=(n,e)=>new S({shape:()=>n,unknownKeys:"strip",catchall:B.create(),typeName:g.ZodObject,...v(e)});S.strictCreate=(n,e)=>new S({shape:()=>n,unknownKeys:"strict",catchall:B.create(),typeName:g.ZodObject,...v(e)});S.lazycreate=(n,e)=>new S({shape:n,unknownKeys:"strip",catchall:B.create(),typeName:g.ZodObject,...v(e)});var ne=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function i(s){for(let o of s)if(o.result.status==="valid")return o.result;for(let o of s)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(o=>new E(o.ctx.common.issues));return u(t,{code:l.invalid_union,unionErrors:a}),m}if(t.common.async)return Promise.all(r.map(async s=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await s._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(i);{let s,a=[];for(let d of r){let h={...t,common:{...t.common,issues:[]},parent:null},y=d._parseSync({data:t.data,path:t.path,parent:h});if(y.status==="valid")return y;y.status==="dirty"&&!s&&(s={result:y,ctx:h}),h.common.issues.length&&a.push(h.common.issues)}if(s)return t.common.issues.push(...s.ctx.common.issues),s.result;let o=a.map(d=>new E(d));return u(t,{code:l.invalid_union,unionErrors:o}),m}}get options(){return this._def.options}};ne.create=(n,e)=>new ne({options:n,typeName:g.ZodUnion,...v(e)});var Z=n=>n instanceof ie?Z(n.schema):n instanceof M?Z(n.innerType()):n instanceof se?[n.value]:n instanceof ae?n.options:n instanceof oe?x.objectValues(n.enum):n instanceof ce?Z(n._def.innerType):n instanceof ee?[void 0]:n instanceof te?[null]:n instanceof A?[void 0,...Z(n.unwrap())]:n instanceof P?[null,...Z(n.unwrap())]:n instanceof Te||n instanceof de?Z(n.unwrap()):n instanceof le?Z(n._def.innerType):[],Ce=class n extends b{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.object)return u(t,{code:l.invalid_type,expected:p.object,received:t.parsedType}),m;let r=this.discriminator,i=t.data[r],s=this.optionsMap.get(i);return s?t.common.async?s._parseAsync({data:t.data,path:t.path,parent:t}):s._parseSync({data:t.data,path:t.path,parent:t}):(u(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),m)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let i=new Map;for(let s of t){let a=Z(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new n({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...v(r)})}};function ze(n,e){let t=I(n),r=I(e);if(n===e)return{valid:!0,data:n};if(t===p.object&&r===p.object){let i=x.objectKeys(e),s=x.objectKeys(n).filter(o=>i.indexOf(o)!==-1),a={...n,...e};for(let o of s){let d=ze(n[o],e[o]);if(!d.valid)return{valid:!1};a[o]=d.data}return{valid:!0,data:a}}else if(t===p.array&&r===p.array){if(n.length!==e.length)return{valid:!1};let i=[];for(let s=0;s<n.length;s++){let a=n[s],o=e[s],d=ze(a,o);if(!d.valid)return{valid:!1};i.push(d.data)}return{valid:!0,data:i}}else return t===p.date&&r===p.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}var re=class extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=(s,a)=>{if(Se(s)||Se(a))return m;let o=ze(s.value,a.value);return o.valid?((Ae(s)||Ae(a))&&t.dirty(),{status:t.value,value:o.data}):(u(r,{code:l.invalid_intersection_types}),m)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};re.create=(n,e,t)=>new re({left:n,right:e,typeName:g.ZodIntersection,...v(t)});var L=class n extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.array)return u(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),m;if(r.data.length<this._def.items.length)return u(r,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),m;!this._def.rest&&r.data.length>this._def.items.length&&(u(r,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let s=[...r.data].map((a,o)=>{let d=this._def.items[o]||this._def.rest;return d?d._parse(new C(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>w.mergeArray(t,a)):w.mergeArray(t,s)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};L.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new L({items:n,typeName:g.ZodTuple,rest:null,...v(e)})};var Me=class n extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return u(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),m;let i=[],s=this._def.keyType,a=this._def.valueType;for(let o in r.data)i.push({key:s._parse(new C(r,o,r.path,o)),value:a._parse(new C(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?w.mergeObjectAsync(t,i):w.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof b?new n({keyType:e,valueType:t,typeName:g.ZodRecord,...v(r)}):new n({keyType:W.create(),valueType:e,typeName:g.ZodRecord,...v(t)})}},ve=class extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.map)return u(r,{code:l.invalid_type,expected:p.map,received:r.parsedType}),m;let i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([o,d],h)=>({key:i._parse(new C(r,o,r.path,[h,"key"])),value:s._parse(new C(r,d,r.path,[h,"value"]))}));if(r.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let d of a){let h=await d.key,y=await d.value;if(h.status==="aborted"||y.status==="aborted")return m;(h.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(h.value,y.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let d of a){let h=d.key,y=d.value;if(h.status==="aborted"||y.status==="aborted")return m;(h.status==="dirty"||y.status==="dirty")&&t.dirty(),o.set(h.value,y.value)}return{status:t.value,value:o}}}};ve.create=(n,e,t)=>new ve({valueType:e,keyType:n,typeName:g.ZodMap,...v(t)});var be=class n extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==p.set)return u(r,{code:l.invalid_type,expected:p.set,received:r.parsedType}),m;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(u(r,{code:l.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),t.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(u(r,{code:l.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let s=this._def.valueType;function a(d){let h=new Set;for(let y of d){if(y.status==="aborted")return m;y.status==="dirty"&&t.dirty(),h.add(y.value)}return{status:t.value,value:h}}let o=[...r.data.values()].map((d,h)=>s._parse(new C(r,d,r.path,h)));return r.common.async?Promise.all(o).then(d=>a(d)):a(o)}min(e,t){return new n({...this._def,minSize:{value:e,message:f.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:f.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};be.create=(n,e)=>new be({valueType:n,minSize:null,maxSize:null,typeName:g.ZodSet,...v(e)});var Oe=class n extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.function)return u(t,{code:l.invalid_type,expected:p.function,received:t.parsedType}),m;function r(o,d){return we({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),D].filter(h=>!!h),issueData:{code:l.invalid_arguments,argumentsError:d}})}function i(o,d){return we({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pe(),D].filter(h=>!!h),issueData:{code:l.invalid_return_type,returnTypeError:d}})}let s={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof G){let o=this;return T(async function(...d){let h=new E([]),y=await o._def.args.parseAsync(d,s).catch(ke=>{throw h.addIssue(r(d,ke)),h}),_=await Reflect.apply(a,this,y);return await o._def.returns._def.type.parseAsync(_,s).catch(ke=>{throw h.addIssue(i(_,ke)),h})})}else{let o=this;return T(function(...d){let h=o._def.args.safeParse(d,s);if(!h.success)throw new E([r(d,h.error)]);let y=Reflect.apply(a,this,h.data),_=o._def.returns.safeParse(y,s);if(!_.success)throw new E([i(y,_.error)]);return _.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:L.create(e).rest(H.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||L.create([]).rest(H.create()),returns:t||H.create(),typeName:g.ZodFunction,...v(r)})}},ie=class extends b{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})}};ie.create=(n,e)=>new ie({getter:n,typeName:g.ZodLazy,...v(e)});var se=class extends b{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return u(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),m}return{status:"valid",value:e.data}}get value(){return this._def.value}};se.create=(n,e)=>new se({value:n,typeName:g.ZodLiteral,...v(e)});function it(n,e){return new ae({values:n,typeName:g.ZodEnum,...v(e)})}var ae=class n extends b{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return u(t,{expected:x.joinValues(r),received:t.parsedType,code:l.invalid_type}),m}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return u(t,{received:t.data,code:l.invalid_enum_value,options:r}),m}return T(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(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};ae.create=it;var oe=class extends b{_parse(e){let t=x.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==p.string&&r.parsedType!==p.number){let i=x.objectValues(t);return u(r,{expected:x.joinValues(i),received:r.parsedType,code:l.invalid_type}),m}if(this._cache||(this._cache=new Set(x.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=x.objectValues(t);return u(r,{received:r.data,code:l.invalid_enum_value,options:i}),m}return T(e.data)}get enum(){return this._def.values}};oe.create=(n,e)=>new oe({values:n,typeName:g.ZodNativeEnum,...v(e)});var G=class extends b{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==p.promise&&t.common.async===!1)return u(t,{code:l.invalid_type,expected:p.promise,received:t.parsedType}),m;let r=t.parsedType===p.promise?t.data:Promise.resolve(t.data);return T(r.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};G.create=(n,e)=>new G({type:n,typeName:g.ZodPromise,...v(e)});var M=class extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{u(r,a),a.fatal?t.abort():t.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){let a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return m;let d=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return d.status==="aborted"?m:d.status==="dirty"?J(d.value):t.value==="dirty"?J(d.value):d});{if(t.value==="aborted")return m;let o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?m:o.status==="dirty"?J(o.value):t.value==="dirty"?J(o.value):o}}if(i.type==="refinement"){let a=o=>{let d=i.refinement(o,s);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?m:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!U(a))return m;let o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>U(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:t.value,value:o})):m);x.assertNever(i)}};M.create=(n,e,t)=>new M({schema:n,typeName:g.ZodEffects,effect:e,...v(t)});M.createWithPreprocess=(n,e,t)=>new M({schema:e,effect:{type:"preprocess",transform:n},typeName:g.ZodEffects,...v(t)});var A=class extends b{_parse(e){return this._getType(e)===p.undefined?T(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};A.create=(n,e)=>new A({innerType:n,typeName:g.ZodOptional,...v(e)});var P=class extends b{_parse(e){return this._getType(e)===p.null?T(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};P.create=(n,e)=>new P({innerType:n,typeName:g.ZodNullable,...v(e)});var ce=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===p.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ce.create=(n,e)=>new ce({innerType:n,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var le=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return fe(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new E(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};le.create=(n,e)=>new le({innerType:n,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var xe=class extends b{_parse(e){if(this._getType(e)!==p.nan){let r=this._getOrReturnCtx(e);return u(r,{code:l.invalid_type,expected:p.nan,received:r.parsedType}),m}return{status:"valid",value:e.data}}};xe.create=n=>new xe({typeName:g.ZodNaN,...v(n)});var Wt=Symbol("zod_brand"),Te=class extends b{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},Ee=class n extends b{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?m:s.status==="dirty"?(t.dirty(),J(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?m:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:g.ZodPipeline})}},de=class extends b{_parse(e){let t=this._def.innerType._parse(e),r=i=>(U(i)&&(i.value=Object.freeze(i.value)),i);return fe(t)?t.then(i=>r(i)):r(t)}unwrap(){return this._def.innerType}};de.create=(n,e)=>new de({innerType:n,typeName:g.ZodReadonly,...v(e)});function et(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function st(n,e={},t){return n?q.create().superRefine((r,i)=>{let s=n(r);if(s instanceof Promise)return s.then(a=>{if(!a){let o=et(e,r),d=o.fatal??t??!0;i.addIssue({code:"custom",...o,fatal:d})}});if(!s){let a=et(e,r),o=a.fatal??t??!0;i.addIssue({code:"custom",...a,fatal:o})}}):q.create()}var qt={object:S.lazycreate},g;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(g||(g={}));var Gt=(n,e={message:`Input not instance of ${n.name}`})=>st(t=>t instanceof n,e),at=W.create,ot=Y.create,Jt=xe.create,Yt=X.create,ct=Q.create,Xt=K.create,Qt=ge.create,Kt=ee.create,en=te.create,tn=q.create,nn=H.create,rn=B.create,sn=ye.create,an=z.create,on=S.create,cn=S.strictCreate,ln=ne.create,dn=Ce.create,un=re.create,hn=L.create,pn=Me.create,fn=ve.create,mn=be.create,gn=Oe.create,yn=ie.create,vn=se.create,bn=ae.create,xn=oe.create,_n=G.create,kn=M.create,wn=A.create,Tn=P.create,En=M.createWithPreprocess,Sn=Ee.create,An=()=>at().optional(),Cn=()=>ot().optional(),Mn=()=>ct().optional(),On={string:n=>W.create({...n,coerce:!0}),number:n=>Y.create({...n,coerce:!0}),boolean:n=>Q.create({...n,coerce:!0}),bigint:n=>X.create({...n,coerce:!0}),date:n=>K.create({...n,coerce:!0})};var Rn=m;var dt=c.object({method:c.enum(["POST","PUT","PATCH","DELETE"]),url:c.string()}),Nn=c.object({id:c.string(),label:c.string(),selector:c.string(),fallbacks:c.array(c.string()),does:c.string(),confidence:c.number().min(0).max(1),evidence:c.array(c.string()),apiCall:dt.nullable().optional()}),Bn=c.object({id:c.string(),route:c.string(),file:c.string(),title:c.string(),purpose:c.string(),whenToUse:c.string(),confidence:c.number().min(0).max(1),elements:c.array(Nn)}),jn=c.object({candidates:c.array(c.string()),chose:c.string(),reason:c.string(),confidence:c.number().min(0).max(1)}),$r=c.object({version:c.literal("1"),commit:c.string(),generatedAt:c.string(),pages:c.array(Bn),dead:c.array(c.string()),conflicts:c.array(jn)}),O=()=>c.preprocess(n=>n===null?void 0:n,c.string().optional()),In=()=>c.preprocess(n=>n===null?void 0:n,dt.optional()),Ln=()=>c.preprocess(n=>n===null?void 0:n,c.boolean().optional()),Ne=()=>c.preprocess(n=>n===null?void 0:n,c.record(c.string(),c.unknown()).optional()),lt=()=>c.preprocess(n=>n===null?void 0:n,c.array(c.unknown()).optional()),j={text:O(),target:O(),route:O(),action:O(),value:O(),name:O(),args:Ne(),steps:lt(),actions:lt()},Re={target:O(),value:O(),name:O(),args:Ne()},Pn=c.discriminatedUnion("verb",[c.object({...Re,verb:c.literal("click"),target:c.string().min(1)}).strict(),c.object({...Re,verb:c.literal("fill"),target:c.string().min(1),value:c.string()}).strict(),c.object({...Re,verb:c.literal("read"),target:c.string().min(1)}).strict(),c.object({...Re,verb:c.literal("call_tool"),name:c.string().min(1),args:Ne()}).strict()]),ut=c.discriminatedUnion("verb",[c.object({...j,verb:c.literal("explain"),text:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("highlight"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("open"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("navigate"),route:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("do"),action:c.string().min(1),target:O(),apiCall:In()}).strict(),c.object({...j,verb:c.literal("tour"),steps:c.array(c.object({text:c.string().min(1),target:O(),route:O(),click:Ln()}).strict()).min(2).max(6)}).strict(),c.object({...j,verb:c.literal("click"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("fill"),target:c.string().min(1),value:c.string()}).strict(),c.object({...j,verb:c.literal("read"),target:c.string().min(1)}).strict(),c.object({...j,verb:c.literal("call_tool"),name:c.string().min(1),args:Ne()}).strict(),c.object({...j,verb:c.literal("batch"),actions:c.array(Pn).min(2).max(5)}).strict()]),$n=c.object({role:c.enum(["user","assistant"]),text:c.string()}),Vn=c.object({id:c.string().max(200),role:c.string().max(50),label:c.string().max(120)}),Dn=c.object({name:c.string().max(200),description:c.string().max(500),inputSchema:c.record(c.string(),c.unknown()).optional()}),Vr=c.object({route:c.string(),question:c.string().min(1),visible:c.array(c.string()),history:c.array($n).optional(),liveElements:c.array(Vn).max(60).optional(),webMcpTools:c.array(Dn).max(30).optional()});function Zn(){return typeof document>"u"?null:document.modelContext??null}async function Fe(n,e){let t=Zn();if(!t?.getTools||!t.executeTool)return{ok:!1,observation:"This page no longer has that tool available."};try{let r=await t.getTools(),i=Array.isArray(r)?r.find(o=>o.name===n):void 0;if(!i)return{ok:!1,observation:`No tool named "${n}" is available on this page right now.`};let s=await t.executeTool(i,e??{});return{ok:!0,observation:(typeof s=="string"?s:JSON.stringify(s??null)).slice(0,2e3)}}catch(r){return{ok:!1,observation:`That tool failed: ${r instanceof Error?r.message:"unknown error"}`}}}var Hn="I'm not sure \u2014 I couldn't understand that response. Try rephrasing your question.";function ht(n,e,t){let r=ut.safeParse(n);if(!r.success){t.onExplain(Hn);return}zn(r.data,e,t)}function zn(n,e,t){switch(n.verb){case"explain":t.onExplain(n.text);return;case"highlight":case"open":{let r=R(n.target,t.liveElements);if(!r){(t.onMiss??N)({attempted:n.target,route:e}),t.onExplain(n.text??"I know what you need, but I can't find it on this page right now.");return}V(r),n.verb==="open"&&r.click(),n.text&&t.onExplain(n.text);return}case"navigate":t.onNavigate?.(n.route),n.text&&t.onExplain(n.text);return;case"do":{if((t.registeredActions??[]).includes(n.action)){t.onDo?.(n.action,n.target),n.text&&t.onExplain(n.text);return}if(n.target||n.apiCall){let i=n.target?R(n.target,t.liveElements):null;if(i){V(i),i.click(),n.text&&t.onExplain(n.text);return}if(n.target&&(t.onMiss??N)({attempted:n.target,route:e}),n.apiCall){n.text&&t.onExplain(n.text),Wn(n.apiCall).then(s=>{s.ok||t.onExplain("I tried to do that, but something went wrong \u2014 try again in a moment.")});return}}t.onExplain(n.text??"That action isn't available here.");return}case"tour":t.onTour?t.onTour(n.steps):t.onExplain(n.steps.map(r=>r.text).join(" "));return;case"click":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r){(t.onMiss??N)({attempted:n.target,route:e}),t.onToolStep?.({verb:"click",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}V(r),r.click(),t.onToolStep?.({verb:"click",target:n.target,ok:!0,observation:"Clicked it."});return}case"fill":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r||!Ve(r,n.value)){(t.onMiss??N)({attempted:n.target,route:e}),t.onToolStep?.({verb:"fill",target:n.target,ok:!1,observation:r?"That element isn't a real form field \u2014 can't type into it.":"Could not find that element on the page."});return}V(r),t.onToolStep?.({verb:"fill",target:n.target,ok:!0,observation:`Typed "${n.value}" into it.`});return}case"read":{n.text&&t.onExplain(n.text);let r=R(n.target,t.liveElements);if(!r){(t.onMiss??N)({attempted:n.target,route:e}),t.onToolStep?.({verb:"read",target:n.target,ok:!1,observation:"Could not find that element on the page."});return}t.onToolStep?.({verb:"read",target:n.target,ok:!0,observation:De(r)});return}case"call_tool":{n.text&&t.onExplain(n.text),Fe(n.name,n.args).then(r=>{t.onToolStep?.({verb:"call_tool",target:n.name,ok:r.ok,observation:r.observation})});return}case"batch":{n.text&&t.onExplain(n.text),Fn(n.actions,e,t).then(r=>{t.onToolStep?.({verb:"batch",ok:r.ok,observation:r.observation})});return}}}async function Fn(n,e,t){let r=[];for(let i of n){let s=await Un(i,e,t);if(r.push(`${i.verb} ${"target"in i?i.target:i.name}: ${s.observation}`),!s.ok)return{ok:!1,observation:r.join(" | ")}}return{ok:!0,observation:r.join(" | ")}}async function Un(n,e,t){switch(n.verb){case"click":{let r=R(n.target,t.liveElements);return r?(V(r),r.click(),{ok:!0,observation:"Clicked it."}):((t.onMiss??N)({attempted:n.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"fill":{let r=R(n.target,t.liveElements);return!r||!Ve(r,n.value)?((t.onMiss??N)({attempted:n.target,route:e}),{ok:!1,observation:r?"That element isn't a real form field \u2014 can't type into it.":"Could not find that element on the page."}):(V(r),{ok:!0,observation:`Typed "${n.value}" into it.`})}case"read":{let r=R(n.target,t.liveElements);return r?{ok:!0,observation:De(r)}:((t.onMiss??N)({attempted:n.target,route:e}),{ok:!1,observation:"Could not find that element on the page."})}case"call_tool":{let r=await Fe(n.name,n.args);return{ok:r.ok,observation:r.observation}}}}async function Wn(n){try{let e=await fetch(n.url,{method:n.method,credentials:"same-origin"});return{ok:e.ok,status:e.status}}catch{return{ok:!1}}}var qn={idle:"",asking:"Thinking\u2026",recording:"Listening \u2014 transcribing live\u2026","rt-connecting":"Connecting\u2026","rt-listening":"Listening\u2026","rt-thinking":"Thinking\u2026","rt-speaking":"Speaking\u2026"},Gn=8,Jn=`
2
2
  :host {
3
3
  all: initial;
4
4
  font: 13.5px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", sans-serif;
@@ -225,4 +225,4 @@
225
225
  .cairn-rt-dot-rt-thinking { background: #f59e0b; }
226
226
  .cairn-rt-label { flex: 1; font-size: 12.5px; color: #33384a; }
227
227
  .cairn-rt-controls { display: flex; gap: 6px; }
228
- `,ut='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',Re='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><line x1="12" x2="12" y1="18" y2="22"/></svg>',Wn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"/><line x1="12" y1="19" x2="12" y2="22"/></svg>',qn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>',Gn='<svg class="cairn-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Jn='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',ht='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="7" y="12.5" width="6" height="2.6" rx="0.5" fill="currentColor"/><rect x="4.5" y="8.5" width="11" height="2.6" rx="0.5" fill="currentColor" opacity="0.75"/><rect x="8.2" y="4.5" width="3.6" height="2.6" rx="0.5" fill="currentColor" opacity="0.5"/></svg>',Yn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"/></svg>',Xn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.83 16.57a1 1 0 0 0 1.21-.3l.36-.47A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A17.87 17.87 0 0 1 9.3 17.6"/><path d="M4.27 5.34C3.5 6.44 4 8 4 8a17.9 17.9 0 0 0 2.14 6.6"/><path d="M2 2v0"/><line x1="2" y1="2" x2="22" y2="22"/></svg>',pt='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>',Qn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>',De=class extends HTMLElement{shadow;fab;panel;stackEl;userBubbleEl;agentBubbleEl;chipEl;agentTextEl;thinkingEl;formEl;inputEl;sendBtn;micBtn=null;phoneBtn=null;rtBar;rtDot;rtLabel;rtMicBtn;rtSpeakerBtn;rtEndBtn;isOpen=!1;status="idle";recording=!1;touringActive=!1;caption="";answer=null;lastQuestion=null;tourGeneration=0;mediaRecorder=null;audioChunks=[];transcribeInFlight=!1;activeAudio=null;history=[];rtSocket=null;rtCleanup=null;rtMicMuted=!1;rtSpeakerMuted=!1;rtStarting=!1;rtPlaybackCtx=null;rtPlaybackGain=null;rtNextPlayTime=0;rtScheduledSources=[];rtThinkingWatchdog=null;rtAudioDoneArriving=!0;rtTourAudioDoneResolve=null;static get observedAttributes(){return["persona"]}connectedCallback(){this.shadow||(this.shadow=this.attachShadow({mode:"open"}),this.buildDom())}attributeChangedCallback(e){e==="persona"&&this.panel&&this.panel.setAttribute("aria-label",`${this.persona} help panel`)}get endpoint(){return this.getAttribute("endpoint")??"/api/copilot"}get speakEndpoint(){return this.getAttribute("speak-endpoint")}get transcribeEndpoint(){return this.getAttribute("transcribe-endpoint")}get reportMissesEndpoint(){return this.getAttribute("report-misses-endpoint")}get realtimeUrl(){return this.getAttribute("realtime-url")}get persona(){return this.getAttribute("persona")??"Cairn"}get registeredActions(){return(this.getAttribute("registered-actions")??"").split(",").map(e=>e.trim()).filter(Boolean)}get realtimeActive(){return this.status.startsWith("rt-")}get busy(){return this.status==="asking"||this.status==="rt-thinking"||this.touringActive}micSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"}buildDom(){let e=document.createElement("style");e.textContent=Un,this.shadow.appendChild(e),this.fab=document.createElement("button"),this.fab.className="cairn-fab",this.fab.innerHTML=ht,this.fab.setAttribute("aria-label",`Open ${this.persona} help`),this.fab.addEventListener("click",()=>this.toggleOpen()),this.shadow.appendChild(this.fab),this.panel=document.createElement("div"),this.panel.className="cairn-panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",`${this.persona} help panel`),this.stackEl=document.createElement("div"),this.stackEl.className="cairn-stack",this.stackEl.style.display="none",this.userBubbleEl=document.createElement("div"),this.userBubbleEl.className="cairn-bubble cairn-bubble-user",this.userBubbleEl.style.display="none",this.stackEl.appendChild(this.userBubbleEl),this.agentBubbleEl=document.createElement("div"),this.agentBubbleEl.className="cairn-bubble cairn-bubble-agent",this.agentBubbleEl.style.display="none",this.chipEl=document.createElement("span"),this.chipEl.className="cairn-chip",this.chipEl.style.display="none",this.agentBubbleEl.appendChild(this.chipEl),this.agentTextEl=document.createElement("span"),this.agentTextEl.className="cairn-bubble-text",this.agentBubbleEl.appendChild(this.agentTextEl),this.thinkingEl=document.createElement("span"),this.thinkingEl.className="cairn-thinking",this.thinkingEl.setAttribute("aria-label","Thinking"),this.thinkingEl.style.display="none",this.thinkingEl.innerHTML='<span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span>',this.agentBubbleEl.appendChild(this.thinkingEl),this.stackEl.appendChild(this.agentBubbleEl),this.panel.appendChild(this.stackEl),this.rtBar=document.createElement("div"),this.rtBar.className="cairn-rt-bar",this.rtBar.style.display="none",this.rtDot=document.createElement("span"),this.rtDot.className="cairn-rt-dot",this.rtBar.appendChild(this.rtDot),this.rtLabel=document.createElement("span"),this.rtLabel.className="cairn-rt-label",this.rtBar.appendChild(this.rtLabel);let t=document.createElement("div");t.className="cairn-rt-controls",this.rtMicBtn=document.createElement("button"),this.rtMicBtn.type="button",this.rtMicBtn.className="cairn-icon-btn",this.rtMicBtn.innerHTML=Re,this.rtMicBtn.setAttribute("aria-label","Mute microphone"),this.rtMicBtn.addEventListener("click",()=>this.toggleRtMic()),t.appendChild(this.rtMicBtn),this.rtSpeakerBtn=document.createElement("button"),this.rtSpeakerBtn.type="button",this.rtSpeakerBtn.className="cairn-icon-btn",this.rtSpeakerBtn.innerHTML=pt,this.rtSpeakerBtn.setAttribute("aria-label","Mute speaker"),this.rtSpeakerBtn.addEventListener("click",()=>this.toggleRtSpeaker()),t.appendChild(this.rtSpeakerBtn),this.rtEndBtn=document.createElement("button"),this.rtEndBtn.type="button",this.rtEndBtn.className="cairn-icon-btn cairn-icon-btn-end",this.rtEndBtn.innerHTML=Xn,this.rtEndBtn.setAttribute("aria-label","End conversation"),this.rtEndBtn.addEventListener("click",()=>this.endRealtime()),t.appendChild(this.rtEndBtn),this.rtBar.appendChild(t),this.panel.appendChild(this.rtBar),this.formEl=document.createElement("form");let r=document.createElement("div");r.className="cairn-input-row",this.inputEl=document.createElement("input"),this.inputEl.placeholder="What do you need help with?",this.inputEl.setAttribute("aria-label",`Ask ${this.persona} a question`),this.inputEl.addEventListener("input",()=>this.updateBusyState()),r.appendChild(this.inputEl),this.realtimeUrl&&this.micSupported()&&(this.phoneBtn=document.createElement("button"),this.phoneBtn.type="button",this.phoneBtn.className="cairn-icon-btn",this.phoneBtn.innerHTML=Yn,this.phoneBtn.setAttribute("aria-label","Start realtime conversation"),this.phoneBtn.addEventListener("click",()=>void this.startRealtime()),r.appendChild(this.phoneBtn)),this.transcribeEndpoint&&this.micSupported()&&(this.micBtn=document.createElement("button"),this.micBtn.type="button",this.micBtn.className="cairn-icon-btn",this.micBtn.innerHTML=Re,this.micBtn.setAttribute("aria-label","Ask by voice"),this.micBtn.addEventListener("click",()=>this.recording?this.stopRecording():void this.startRecording()),r.appendChild(this.micBtn)),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="cairn-send",this.sendBtn.innerHTML=ut,this.sendBtn.setAttribute("aria-label","Send"),r.appendChild(this.sendBtn),this.formEl.appendChild(r),this.formEl.addEventListener("submit",i=>{i.preventDefault();let s=this.inputEl.value.trim();s&&this.ask(s)}),this.panel.appendChild(this.formEl),this.shadow.appendChild(this.panel),this.render()}toggleOpen(){this.isOpen=!this.isOpen,this.panel.classList.toggle("cairn-open",this.isOpen),this.fab.innerHTML=this.isOpen?Jn:ht,this.fab.setAttribute("aria-label",this.isOpen?`Close ${this.persona} help`:`Open ${this.persona} help`),this.isOpen&&!this.realtimeActive&&this.inputEl.focus()}render(){let e=this.realtimeActive;if(this.fab.classList.toggle("cairn-fab-speaking",this.status==="rt-speaking"),this.rtBar.style.display=e?"flex":"none",this.formEl.style.display=e?"none":"block",e){this.rtDot.className=`cairn-rt-dot cairn-rt-dot-${this.status}`,this.rtLabel.textContent=zn[this.status];let s=this.status==="rt-speaking";this.rtMicBtn.className=s?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtSpeakerBtn.className=s?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtMicBtn.innerHTML=this.rtMicMuted?Wn:Re,this.rtMicBtn.setAttribute("aria-label",this.rtMicMuted?"Unmute microphone":"Mute microphone"),this.rtSpeakerBtn.innerHTML=this.rtSpeakerMuted?Qn:pt,this.rtSpeakerBtn.setAttribute("aria-label",this.rtSpeakerMuted?"Unmute speaker":"Mute speaker")}let t=this.touringActive?this.caption:"",r=!this.touringActive&&(this.recording||e)?this.caption:this.lastQuestion??"",i=!!this.answer||this.busy;this.stackEl.style.display=r||i?"flex":"none",this.userBubbleEl.style.display=r?"block":"none",this.userBubbleEl.textContent=r,this.agentBubbleEl.style.display=i?"flex":"none",this.chipEl.style.display=t?"inline-block":"none",this.chipEl.textContent=t,this.answer?(this.agentTextEl.style.display="inline",this.renderCaptionWords(this.agentTextEl,this.answer),this.thinkingEl.style.display="none"):(this.agentTextEl.style.display="none",this.agentTextEl.textContent="",this.thinkingEl.style.display=this.busy?"inline-flex":"none"),this.phoneBtn&&(this.phoneBtn.disabled=this.busy||this.recording),this.updateBusyState()}setStatus(e){this.status=e,this.render()}setCaption(e){this.caption=e,this.render()}updateBusyState(){this.inputEl.disabled=this.recording||this.touringActive,this.sendBtn.disabled=this.busy||this.recording||!this.inputEl.value.trim(),this.sendBtn.innerHTML=this.busy?Gn:ut,this.micBtn&&(this.micBtn.disabled=this.touringActive)}setAnswer(e){this.answer=e,this.render()}renderCaptionWords(e,t){e.innerHTML="";let r=t.split(" ");r.forEach((i,s)=>{let a=document.createElement("span");a.className="cairn-word",a.style.animationDelay=`${Math.min(s*55,2800)}ms`,a.textContent=s<r.length-1?i+" ":i,e.appendChild(a)})}reportMiss(e){z(e);let t=this.reportMissesEndpoint;t&&fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async ask(e){this.setStatus("asking"),this.setAnswer(null),this.lastQuestion=e,this.inputEl.value="",this.render();try{let r=await(await fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:location.pathname,question:e,visible:je(),history:this.history})})).json().catch(()=>null);this.handleVerb(r),this.history=[...this.history,{role:"user",text:e},{role:"assistant",text:Kn(r)}].slice(-Fn)}catch{this.setAnswer("Something went wrong reaching the help service \u2014 try again in a moment.")}finally{this.setStatus("idle")}}handleVerb(e){dt(e,location.pathname,{onExplain:t=>{this.setAnswer(t),this.realtimeActive||this.speak(t)},onNavigate:t=>{location.assign(t)},onMiss:t=>this.reportMiss(t),onDo:(t,r)=>{this.dispatchEvent(new CustomEvent("cairn-do",{detail:{action:t,target:r},bubbles:!0,composed:!0}))},onTour:t=>void this.runTour(t),registeredActions:this.registeredActions})}async runTour(e){let t=++this.tourGeneration,r=this.realtimeActive;this.touringActive=!0,r&&this.setStatus("rt-speaking"),this.setAnswer(null);let i=location.pathname;try{for(let s=0;s<e.length;s++){if(this.tourGeneration!==t)return;let a=e[s];if(this.setCaption(`Step ${s+1} of ${e.length}`),this.setAnswer(a.text),a.route&&a.route!==i){location.assign(a.route);return}if(a.target){let o=H(a.target);o?G(o):this.reportMiss({attempted:a.target,route:i})}if(r&&this.rtSocket?.readyState===WebSocket.OPEN?await this.speakOverRealtime(a.text):this.speakEndpoint?await this.speakAndWait(a.text):await new Promise(o=>setTimeout(o,Math.max(1200,a.text.length*45))),this.tourGeneration!==t)return}if(this.tourGeneration!==t)return;this.setCaption(""),r&&this.realtimeActive&&this.setStatus("rt-listening")}finally{this.tourGeneration===t&&(this.touringActive=!1,this.render())}}playResponseAudio(e){this.activeAudio&&(this.activeAudio.pause(),this.activeAudio.currentTime=0);let t=URL.createObjectURL(e),r=new Audio(t);return this.activeAudio=r,new Promise(i=>{let s=()=>{URL.revokeObjectURL(t),this.activeAudio===r&&(this.activeAudio=null),i()};r.onended=s,r.play().catch(s)})}async speak(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;this.playResponseAudio(await t.blob())}catch{}}async speakAndWait(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;await this.playResponseAudio(await t.blob())}catch{}}speakOverRealtime(e){return new Promise(t=>{let r=this.rtSocket;if(!r||r.readyState!==WebSocket.OPEN){t();return}this.rtAudioDoneArriving=!1;let i=!1,s=()=>{i||(i=!0,this.rtTourAudioDoneResolve=null,t())};this.rtTourAudioDoneResolve=s,setTimeout(()=>{i||console.warn("[cairn] tour step audio confirmation timed out \u2014 continuing"),s()},15e3),r.send(JSON.stringify({type:"speak",text:e}))})}async startRecording(){if(!(!this.transcribeEndpoint||!this.micSupported()||this.realtimeActive))try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e);this.audioChunks=[],this.setCaption(""),t.ondataavailable=r=>{r.data.size!==0&&(this.audioChunks.push(r.data),this.transcribeSoFar(t.mimeType||"audio/webm",!0))},t.onstop=()=>void this.transcribeSoFar(t.mimeType||"audio/webm",!1),this.mediaRecorder=t,t.start(2e3),this.recording=!0,this.micBtn&&(this.micBtn.innerHTML=qn,this.micBtn.classList.add("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Stop recording")),this.render()}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site.")}}stopRecording(){let e=this.mediaRecorder?.stream;this.mediaRecorder?.stop(),e?.getTracks().forEach(t=>t.stop()),this.recording=!1,this.micBtn&&(this.micBtn.innerHTML=Re,this.micBtn.classList.remove("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Ask by voice")),this.render()}async transcribeSoFar(e,t){if(this.transcribeEndpoint&&!(t&&this.transcribeInFlight)){this.transcribeInFlight=!0;try{let r=new Blob(this.audioChunks,{type:e}),s=await(await fetch(this.transcribeEndpoint,{method:"POST",headers:{"content-type":e},body:r})).json().catch(()=>null);s?.text?(this.inputEl.value=s.text,this.setCaption(s.text),this.updateBusyState()):t||this.setAnswer("Couldn't make that out \u2014 try typing instead.")}catch{t||this.setAnswer("Couldn't reach the transcription service.")}finally{this.transcribeInFlight=!1}}}async startRealtime(){if(!(!this.realtimeUrl||!this.micSupported()||this.realtimeActive||this.rtStarting)){this.rtStarting=!0,this.setAnswer(null),this.setCaption(""),this.setStatus("rt-connecting");try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new WebSocket(this.realtimeUrl);t.binaryType="arraybuffer",this.rtSocket=t;let r=new AudioContext,i=r.createGain();i.gain.value=this.rtSpeakerMuted?0:1,i.connect(r.destination),this.rtPlaybackCtx=r,this.rtPlaybackGain=i,this.rtNextPlayTime=0,this.rtScheduledSources=[],this.rtAudioDoneArriving=!0;let s=new AudioContext,a=s.createMediaStreamSource(e),o=s.createScriptProcessor(4096,1,1),d=s.createGain();d.gain.value=0;let h=()=>{if(this.rtAudioDoneArriving&&!(this.rtScheduledSources.length>0)){if(this.touringActive){this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null;return}this.setStatus("rt-listening"),this.setCaption("")}},y=()=>{this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null)},_=()=>{y(),this.rtThinkingWatchdog=setTimeout(()=>{this.rtThinkingWatchdog=null,console.warn("[cairn] realtime turn timed out waiting on the server \u2014 resuming listening"),this.rtAudioDoneArriving=!0,this.setStatus("rt-listening"),this.setCaption("")},2e4)},_e=()=>{for(let I of this.rtScheduledSources)try{I.stop()}catch{}this.rtScheduledSources=[],this.rtNextPlayTime=this.rtPlaybackCtx?.currentTime??0},ke=()=>{y(),_e(),this.rtAudioDoneArriving=!0,t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"barge_in"})),this.setStatus("rt-listening"),this.setCaption("")};o.onaudioprocess=I=>{if(t.readyState!==WebSocket.OPEN||this.rtMicMuted)return;if(this.status==="rt-speaking"&&!this.touringActive){tr(I.inputBuffer.getChannelData(0))>er&&ke();return}if(this.status!=="rt-listening")return;let k=rr(nr(I.inputBuffer.getChannelData(0),s.sampleRate));t.send(k)},a.connect(o),o.connect(d),d.connect(s.destination),this.rtCleanup=()=>{o.disconnect(),a.disconnect(),e.getTracks().forEach(I=>I.stop()),s.close(),_e(),r.close(),this.rtPlaybackCtx=null,this.rtPlaybackGain=null},t.onopen=()=>{t.send(JSON.stringify({type:"context",route:location.pathname,visible:je()})),this.setStatus("rt-listening"),this.rtStarting=!1},t.onmessage=I=>{if(typeof I.data!="string")return;let k=JSON.parse(I.data);if(k.type==="interim")this.setCaption(k.text);else if(k.type==="final")this.setCaption(k.text),this.setStatus("rt-thinking"),_();else if(k.type==="verb")y(),this.handleVerb(k.verb);else if(k.type==="speaking_start")y(),this.rtAudioDoneArriving=!1,this.setStatus("rt-speaking");else if(k.type==="audio_chunk"){let ue=this.rtPlaybackCtx,Ze=this.rtPlaybackGain;if(!ue||!Ze)return;ue.resume().catch(()=>{});let He=Uint8Array.from(atob(k.audio),Z=>Z.charCodeAt(0)),Ne=He.length/2,ze=new Float32Array(Ne),ft=new DataView(He.buffer);for(let Z=0;Z<Ne;Z++)ze[Z]=ft.getInt16(Z*2,!0)/32768;let mt=typeof k.sampleRate=="number"?k.sampleRate:24e3,Be=ue.createBuffer(1,Ne,mt);Be.copyToChannel(ze,0);let he=ue.createBufferSource();he.buffer=Be,he.connect(Ze);let Fe=Math.max(ue.currentTime,this.rtNextPlayTime);he.start(Fe),this.rtNextPlayTime=Fe+Be.duration,this.rtScheduledSources.push(he),he.onended=()=>{this.rtScheduledSources=this.rtScheduledSources.filter(Z=>Z!==he),h()}}else k.type==="speaking_end"||k.type==="turn_complete"?(y(),this.rtAudioDoneArriving=!0,h()):k.type==="error"&&(y(),this.setAnswer(k.message??"Something went wrong."),this.touringActive||(this.setStatus("rt-listening"),this.setCaption("")))},t.onerror=()=>{this.setAnswer("Couldn't connect to the realtime voice service."),this.endRealtime()},t.onclose=()=>{this.status!=="idle"&&this.endRealtime()}}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site."),this.setStatus("idle"),this.rtStarting=!1}}}endRealtime(){this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null),this.rtStarting=!1,this.activeAudio?.pause(),this.activeAudio=null,this.rtSocket?.close(),this.rtSocket=null,this.rtCleanup?.(),this.rtCleanup=null,this.rtMicMuted=!1,this.rtSpeakerMuted=!1,this.setCaption(""),this.setStatus("idle"),this.tourGeneration++,this.touringActive=!1,this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null,this.render()}toggleRtMic(){this.rtMicMuted=!this.rtMicMuted,this.render()}toggleRtSpeaker(){this.rtSpeakerMuted=!this.rtSpeakerMuted,this.rtPlaybackGain&&(this.rtPlaybackGain.gain.value=this.rtSpeakerMuted?0:1),this.render()}};function Kn(n){if(!n||typeof n!="object")return"(no response)";let e=n;if(typeof e.text=="string"&&e.text)return e.text;switch(e.verb){case"highlight":case"open":return`(highlighted ${String(e.target)})`;case"navigate":return`(navigated to ${String(e.route)})`;case"do":return`(ran ${String(e.action)}${e.target?` on ${String(e.target)}`:""})`;case"tour":return Array.isArray(e.steps)?e.steps.map(t=>t.text??"").join(" "):"(tour)";default:return"(no response)"}}var er=.02;function tr(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return Math.sqrt(e/n.length)}function nr(n,e){if(e===16e3)return n;let r=e/16e3,i=Math.round(n.length/r),s=new Float32Array(i),a=0,o=0;for(;a<i;){let d=Math.round((a+1)*r),h=0,y=0;for(let _=o;_<d&&_<n.length;_++)h+=n[_],y++;s[a]=y>0?h/y:0,a++,o=d}return s}function rr(n){let e=new ArrayBuffer(n.length*2),t=new DataView(e);for(let r=0;r<n.length;r++){let i=Math.max(-1,Math.min(1,n[r]));t.setInt16(r*2,i<0?i*32768:i*32767,!0)}return e}typeof customElements<"u"&&!customElements.get("cairn-widget")&&customElements.define("cairn-widget",De);})();
228
+ `,pt='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>',Be='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1"/><line x1="12" x2="12" y1="18" y2="22"/></svg>',Yn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="2" y1="2" x2="22" y2="22"/><path d="M9 9v3a3 3 0 0 0 5.12 2.12M15 9.34V5a3 3 0 0 0-5.94-.6"/><path d="M17 16.95A7 7 0 0 1 5 12v-2m14 0v2a7 7 0 0 1-.11 1.23"/><line x1="12" y1="19" x2="12" y2="22"/></svg>',Xn='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="5" y="5" rx="2"/></svg>',Qn='<svg class="cairn-spin" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',Kn='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>',ft='<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><rect x="7" y="12.5" width="6" height="2.6" rx="0.5" fill="currentColor"/><rect x="4.5" y="8.5" width="11" height="2.6" rx="0.5" fill="currentColor" opacity="0.75"/><rect x="8.2" y="4.5" width="3.6" height="2.6" rx="0.5" fill="currentColor" opacity="0.5"/></svg>',er='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"/></svg>',tr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13.83 16.57a1 1 0 0 0 1.21-.3l.36-.47A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A17.87 17.87 0 0 1 9.3 17.6"/><path d="M4.27 5.34C3.5 6.44 4 8 4 8a17.9 17.9 0 0 0 2.14 6.6"/><path d="M2 2v0"/><line x1="2" y1="2" x2="22" y2="22"/></svg>',mt='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><path d="M15.54 8.46a5 5 0 0 1 0 7.07"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14"/></svg>',nr='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="22" y1="9" x2="16" y2="15"/><line x1="16" y1="9" x2="22" y2="15"/></svg>',Ue=class extends HTMLElement{shadow;fab;panel;stackEl;userBubbleEl;agentBubbleEl;chipEl;agentTextEl;thinkingEl;formEl;inputEl;sendBtn;micBtn=null;phoneBtn=null;rtBar;rtDot;rtLabel;rtMicBtn;rtSpeakerBtn;rtEndBtn;isOpen=!1;status="idle";recording=!1;touringActive=!1;caption="";answer=null;lastQuestion=null;tourGeneration=0;mediaRecorder=null;audioChunks=[];transcribeInFlight=!1;activeAudio=null;history=[];rtSocket=null;rtCleanup=null;rtMicMuted=!1;rtSpeakerMuted=!1;rtStarting=!1;rtPlaybackCtx=null;rtPlaybackGain=null;rtNextPlayTime=0;rtScheduledSources=[];rtThinkingWatchdog=null;rtAudioDoneArriving=!0;rtTourAudioDoneResolve=null;static get observedAttributes(){return["persona"]}connectedCallback(){this.shadow||(this.shadow=this.attachShadow({mode:"open"}),this.buildDom())}attributeChangedCallback(e){e==="persona"&&this.panel&&this.panel.setAttribute("aria-label",`${this.persona} help panel`)}get endpoint(){return this.getAttribute("endpoint")??"/api/copilot"}get speakEndpoint(){return this.getAttribute("speak-endpoint")}get transcribeEndpoint(){return this.getAttribute("transcribe-endpoint")}get reportMissesEndpoint(){return this.getAttribute("report-misses-endpoint")}get realtimeUrl(){return this.getAttribute("realtime-url")}get persona(){return this.getAttribute("persona")??"Cairn"}get registeredActions(){return(this.getAttribute("registered-actions")??"").split(",").map(e=>e.trim()).filter(Boolean)}get realtimeActive(){return this.status.startsWith("rt-")}get busy(){return this.status==="asking"||this.status==="rt-thinking"||this.touringActive}micSupported(){return typeof navigator<"u"&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<"u"}buildDom(){let e=document.createElement("style");e.textContent=Jn,this.shadow.appendChild(e),this.fab=document.createElement("button"),this.fab.className="cairn-fab",this.fab.innerHTML=ft,this.fab.setAttribute("aria-label",`Open ${this.persona} help`),this.fab.addEventListener("click",()=>this.toggleOpen()),this.shadow.appendChild(this.fab),this.panel=document.createElement("div"),this.panel.className="cairn-panel",this.panel.setAttribute("role","dialog"),this.panel.setAttribute("aria-label",`${this.persona} help panel`),this.stackEl=document.createElement("div"),this.stackEl.className="cairn-stack",this.stackEl.style.display="none",this.userBubbleEl=document.createElement("div"),this.userBubbleEl.className="cairn-bubble cairn-bubble-user",this.userBubbleEl.style.display="none",this.stackEl.appendChild(this.userBubbleEl),this.agentBubbleEl=document.createElement("div"),this.agentBubbleEl.className="cairn-bubble cairn-bubble-agent",this.agentBubbleEl.style.display="none",this.chipEl=document.createElement("span"),this.chipEl.className="cairn-chip",this.chipEl.style.display="none",this.agentBubbleEl.appendChild(this.chipEl),this.agentTextEl=document.createElement("span"),this.agentTextEl.className="cairn-bubble-text",this.agentBubbleEl.appendChild(this.agentTextEl),this.thinkingEl=document.createElement("span"),this.thinkingEl.className="cairn-thinking",this.thinkingEl.setAttribute("aria-label","Thinking"),this.thinkingEl.style.display="none",this.thinkingEl.innerHTML='<span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span><span class="cairn-thinking-dot"></span>',this.agentBubbleEl.appendChild(this.thinkingEl),this.stackEl.appendChild(this.agentBubbleEl),this.panel.appendChild(this.stackEl),this.rtBar=document.createElement("div"),this.rtBar.className="cairn-rt-bar",this.rtBar.style.display="none",this.rtDot=document.createElement("span"),this.rtDot.className="cairn-rt-dot",this.rtBar.appendChild(this.rtDot),this.rtLabel=document.createElement("span"),this.rtLabel.className="cairn-rt-label",this.rtBar.appendChild(this.rtLabel);let t=document.createElement("div");t.className="cairn-rt-controls",this.rtMicBtn=document.createElement("button"),this.rtMicBtn.type="button",this.rtMicBtn.className="cairn-icon-btn",this.rtMicBtn.innerHTML=Be,this.rtMicBtn.setAttribute("aria-label","Mute microphone"),this.rtMicBtn.addEventListener("click",()=>this.toggleRtMic()),t.appendChild(this.rtMicBtn),this.rtSpeakerBtn=document.createElement("button"),this.rtSpeakerBtn.type="button",this.rtSpeakerBtn.className="cairn-icon-btn",this.rtSpeakerBtn.innerHTML=mt,this.rtSpeakerBtn.setAttribute("aria-label","Mute speaker"),this.rtSpeakerBtn.addEventListener("click",()=>this.toggleRtSpeaker()),t.appendChild(this.rtSpeakerBtn),this.rtEndBtn=document.createElement("button"),this.rtEndBtn.type="button",this.rtEndBtn.className="cairn-icon-btn cairn-icon-btn-end",this.rtEndBtn.innerHTML=tr,this.rtEndBtn.setAttribute("aria-label","End conversation"),this.rtEndBtn.addEventListener("click",()=>this.endRealtime()),t.appendChild(this.rtEndBtn),this.rtBar.appendChild(t),this.panel.appendChild(this.rtBar),this.formEl=document.createElement("form");let r=document.createElement("div");r.className="cairn-input-row",this.inputEl=document.createElement("input"),this.inputEl.placeholder="What do you need help with?",this.inputEl.setAttribute("aria-label",`Ask ${this.persona} a question`),this.inputEl.addEventListener("input",()=>this.updateBusyState()),r.appendChild(this.inputEl),this.realtimeUrl&&this.micSupported()&&(this.phoneBtn=document.createElement("button"),this.phoneBtn.type="button",this.phoneBtn.className="cairn-icon-btn",this.phoneBtn.innerHTML=er,this.phoneBtn.setAttribute("aria-label","Start realtime conversation"),this.phoneBtn.addEventListener("click",()=>void this.startRealtime()),r.appendChild(this.phoneBtn)),this.transcribeEndpoint&&this.micSupported()&&(this.micBtn=document.createElement("button"),this.micBtn.type="button",this.micBtn.className="cairn-icon-btn",this.micBtn.innerHTML=Be,this.micBtn.setAttribute("aria-label","Ask by voice"),this.micBtn.addEventListener("click",()=>this.recording?this.stopRecording():void this.startRecording()),r.appendChild(this.micBtn)),this.sendBtn=document.createElement("button"),this.sendBtn.type="submit",this.sendBtn.className="cairn-send",this.sendBtn.innerHTML=pt,this.sendBtn.setAttribute("aria-label","Send"),r.appendChild(this.sendBtn),this.formEl.appendChild(r),this.formEl.addEventListener("submit",i=>{i.preventDefault();let s=this.inputEl.value.trim();s&&this.ask(s)}),this.panel.appendChild(this.formEl),this.shadow.appendChild(this.panel),this.render()}toggleOpen(){this.isOpen=!this.isOpen,this.panel.classList.toggle("cairn-open",this.isOpen),this.fab.innerHTML=this.isOpen?Kn:ft,this.fab.setAttribute("aria-label",this.isOpen?`Close ${this.persona} help`:`Open ${this.persona} help`),this.isOpen&&!this.realtimeActive&&this.inputEl.focus()}render(){let e=this.realtimeActive;if(this.fab.classList.toggle("cairn-fab-speaking",this.status==="rt-speaking"),this.rtBar.style.display=e?"flex":"none",this.formEl.style.display=e?"none":"block",e){this.rtDot.className=`cairn-rt-dot cairn-rt-dot-${this.status}`,this.rtLabel.textContent=qn[this.status];let s=this.status==="rt-speaking";this.rtMicBtn.className=s?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtSpeakerBtn.className=s?"cairn-icon-btn cairn-icon-btn-speaking":"cairn-icon-btn",this.rtMicBtn.innerHTML=this.rtMicMuted?Yn:Be,this.rtMicBtn.setAttribute("aria-label",this.rtMicMuted?"Unmute microphone":"Mute microphone"),this.rtSpeakerBtn.innerHTML=this.rtSpeakerMuted?nr:mt,this.rtSpeakerBtn.setAttribute("aria-label",this.rtSpeakerMuted?"Unmute speaker":"Mute speaker")}let t=this.touringActive?this.caption:"",r=!this.touringActive&&(this.recording||e)?this.caption:this.lastQuestion??"",i=!!this.answer||this.busy;this.stackEl.style.display=r||i?"flex":"none",this.userBubbleEl.style.display=r?"block":"none",this.userBubbleEl.textContent=r,this.agentBubbleEl.style.display=i?"flex":"none",this.chipEl.style.display=t?"inline-block":"none",this.chipEl.textContent=t,this.answer?(this.agentTextEl.style.display="inline",this.renderCaptionWords(this.agentTextEl,this.answer),this.thinkingEl.style.display="none"):(this.agentTextEl.style.display="none",this.agentTextEl.textContent="",this.thinkingEl.style.display=this.busy?"inline-flex":"none"),this.phoneBtn&&(this.phoneBtn.disabled=this.busy||this.recording),this.updateBusyState()}setStatus(e){this.status=e,this.render()}setCaption(e){this.caption=e,this.render()}updateBusyState(){this.inputEl.disabled=this.recording||this.touringActive,this.sendBtn.disabled=this.busy||this.recording||!this.inputEl.value.trim(),this.sendBtn.innerHTML=this.busy?Qn:pt,this.micBtn&&(this.micBtn.disabled=this.touringActive)}setAnswer(e){this.answer=e,this.render()}renderCaptionWords(e,t){e.innerHTML="";let r=t.split(" ");r.forEach((i,s)=>{let a=document.createElement("span");a.className="cairn-word",a.style.animationDelay=`${Math.min(s*55,2800)}ms`,a.textContent=s<r.length-1?i+" ":i,e.appendChild(a)})}reportMiss(e){N(e);let t=this.reportMissesEndpoint;t&&fetch(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async ask(e){this.setStatus("asking"),this.setAnswer(null),this.lastQuestion=e,this.inputEl.value="",this.render();try{let r=await(await fetch(this.endpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({route:location.pathname,question:e,visible:Le(),history:this.history})})).json().catch(()=>null);this.handleVerb(r),this.history=[...this.history,{role:"user",text:e},{role:"assistant",text:rr(r)}].slice(-Gn)}catch{this.setAnswer("Something went wrong reaching the help service \u2014 try again in a moment.")}finally{this.setStatus("idle")}}handleVerb(e){ht(e,location.pathname,{onExplain:t=>{this.setAnswer(t),this.realtimeActive||this.speak(t)},onNavigate:t=>{location.assign(t)},onMiss:t=>this.reportMiss(t),onDo:(t,r)=>{this.dispatchEvent(new CustomEvent("cairn-do",{detail:{action:t,target:r},bubbles:!0,composed:!0}))},onTour:t=>void this.runTour(t),registeredActions:this.registeredActions})}async runTour(e){let t=++this.tourGeneration,r=this.realtimeActive;this.touringActive=!0,r&&this.setStatus("rt-speaking"),this.setAnswer(null);let i=location.pathname;try{for(let s=0;s<e.length;s++){if(this.tourGeneration!==t)return;let a=e[s];if(this.setCaption(`Step ${s+1} of ${e.length}`),this.setAnswer(a.text),a.route&&a.route!==i){location.assign(a.route);return}if(a.target){let o=R(a.target);o?V(o):this.reportMiss({attempted:a.target,route:i})}if(r&&this.rtSocket?.readyState===WebSocket.OPEN?await this.speakOverRealtime(a.text):this.speakEndpoint?await this.speakAndWait(a.text):await new Promise(o=>setTimeout(o,Math.max(1200,a.text.length*45))),this.tourGeneration!==t)return}if(this.tourGeneration!==t)return;this.setCaption(""),r&&this.realtimeActive&&this.setStatus("rt-listening")}finally{this.tourGeneration===t&&(this.touringActive=!1,this.render())}}playResponseAudio(e){this.activeAudio&&(this.activeAudio.pause(),this.activeAudio.currentTime=0);let t=URL.createObjectURL(e),r=new Audio(t);return this.activeAudio=r,new Promise(i=>{let s=()=>{URL.revokeObjectURL(t),this.activeAudio===r&&(this.activeAudio=null),i()};r.onended=s,r.play().catch(s)})}async speak(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;this.playResponseAudio(await t.blob())}catch{}}async speakAndWait(e){if(!(!this.speakEndpoint||!e.trim()))try{let t=await fetch(this.speakEndpoint,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)return;await this.playResponseAudio(await t.blob())}catch{}}speakOverRealtime(e){return new Promise(t=>{let r=this.rtSocket;if(!r||r.readyState!==WebSocket.OPEN){t();return}this.rtAudioDoneArriving=!1;let i=!1,s=()=>{i||(i=!0,this.rtTourAudioDoneResolve=null,t())};this.rtTourAudioDoneResolve=s,setTimeout(()=>{i||console.warn("[cairn] tour step audio confirmation timed out \u2014 continuing"),s()},15e3),r.send(JSON.stringify({type:"speak",text:e}))})}async startRecording(){if(!(!this.transcribeEndpoint||!this.micSupported()||this.realtimeActive))try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e);this.audioChunks=[],this.setCaption(""),t.ondataavailable=r=>{r.data.size!==0&&(this.audioChunks.push(r.data),this.transcribeSoFar(t.mimeType||"audio/webm",!0))},t.onstop=()=>void this.transcribeSoFar(t.mimeType||"audio/webm",!1),this.mediaRecorder=t,t.start(2e3),this.recording=!0,this.micBtn&&(this.micBtn.innerHTML=Xn,this.micBtn.classList.add("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Stop recording")),this.render()}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site.")}}stopRecording(){let e=this.mediaRecorder?.stream;this.mediaRecorder?.stop(),e?.getTracks().forEach(t=>t.stop()),this.recording=!1,this.micBtn&&(this.micBtn.innerHTML=Be,this.micBtn.classList.remove("cairn-icon-btn-recording"),this.micBtn.setAttribute("aria-label","Ask by voice")),this.render()}async transcribeSoFar(e,t){if(this.transcribeEndpoint&&!(t&&this.transcribeInFlight)){this.transcribeInFlight=!0;try{let r=new Blob(this.audioChunks,{type:e}),s=await(await fetch(this.transcribeEndpoint,{method:"POST",headers:{"content-type":e},body:r})).json().catch(()=>null);s?.text?(this.inputEl.value=s.text,this.setCaption(s.text),this.updateBusyState()):t||this.setAnswer("Couldn't make that out \u2014 try typing instead.")}catch{t||this.setAnswer("Couldn't reach the transcription service.")}finally{this.transcribeInFlight=!1}}}async startRealtime(){if(!(!this.realtimeUrl||!this.micSupported()||this.realtimeActive||this.rtStarting)){this.rtStarting=!0,this.setAnswer(null),this.setCaption(""),this.setStatus("rt-connecting");try{let e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new WebSocket(this.realtimeUrl);t.binaryType="arraybuffer",this.rtSocket=t;let r=new AudioContext,i=r.createGain();i.gain.value=this.rtSpeakerMuted?0:1,i.connect(r.destination),this.rtPlaybackCtx=r,this.rtPlaybackGain=i,this.rtNextPlayTime=0,this.rtScheduledSources=[],this.rtAudioDoneArriving=!0;let s=new AudioContext,a=s.createMediaStreamSource(e),o=s.createScriptProcessor(4096,1,1),d=s.createGain();d.gain.value=0;let h=()=>{if(this.rtAudioDoneArriving&&!(this.rtScheduledSources.length>0)){if(this.touringActive){this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null;return}this.setStatus("rt-listening"),this.setCaption("")}},y=()=>{this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null)},_=()=>{y(),this.rtThinkingWatchdog=setTimeout(()=>{this.rtThinkingWatchdog=null,console.warn("[cairn] realtime turn timed out waiting on the server \u2014 resuming listening"),this.rtAudioDoneArriving=!0,this.setStatus("rt-listening"),this.setCaption("")},2e4)},_e=()=>{for(let $ of this.rtScheduledSources)try{$.stop()}catch{}this.rtScheduledSources=[],this.rtNextPlayTime=this.rtPlaybackCtx?.currentTime??0},ke=()=>{y(),_e(),this.rtAudioDoneArriving=!0,t.readyState===WebSocket.OPEN&&t.send(JSON.stringify({type:"barge_in"})),this.setStatus("rt-listening"),this.setCaption("")};o.onaudioprocess=$=>{if(t.readyState!==WebSocket.OPEN||this.rtMicMuted)return;if(this.status==="rt-speaking"&&!this.touringActive){sr($.inputBuffer.getChannelData(0))>ir&&ke();return}if(this.status!=="rt-listening")return;let k=or(ar($.inputBuffer.getChannelData(0),s.sampleRate));t.send(k)},a.connect(o),o.connect(d),d.connect(s.destination),this.rtCleanup=()=>{o.disconnect(),a.disconnect(),e.getTracks().forEach($=>$.stop()),s.close(),_e(),r.close(),this.rtPlaybackCtx=null,this.rtPlaybackGain=null},t.onopen=()=>{t.send(JSON.stringify({type:"context",route:location.pathname,visible:Le()})),this.setStatus("rt-listening"),this.rtStarting=!1},t.onmessage=$=>{if(typeof $.data!="string")return;let k=JSON.parse($.data);if(k.type==="interim")this.setCaption(k.text);else if(k.type==="final")this.setCaption(k.text),this.setStatus("rt-thinking"),_();else if(k.type==="verb")y(),this.handleVerb(k.verb);else if(k.type==="speaking_start")y(),this.rtAudioDoneArriving=!1,this.setStatus("rt-speaking");else if(k.type==="audio_chunk"){let ue=this.rtPlaybackCtx,We=this.rtPlaybackGain;if(!ue||!We)return;ue.resume().catch(()=>{});let qe=Uint8Array.from(atob(k.audio),F=>F.charCodeAt(0)),je=qe.length/2,Ge=new Float32Array(je),gt=new DataView(qe.buffer);for(let F=0;F<je;F++)Ge[F]=gt.getInt16(F*2,!0)/32768;let yt=typeof k.sampleRate=="number"?k.sampleRate:24e3,Ie=ue.createBuffer(1,je,yt);Ie.copyToChannel(Ge,0);let he=ue.createBufferSource();he.buffer=Ie,he.connect(We);let Je=Math.max(ue.currentTime,this.rtNextPlayTime);he.start(Je),this.rtNextPlayTime=Je+Ie.duration,this.rtScheduledSources.push(he),he.onended=()=>{this.rtScheduledSources=this.rtScheduledSources.filter(F=>F!==he),h()}}else k.type==="speaking_end"||k.type==="turn_complete"?(y(),this.rtAudioDoneArriving=!0,h()):k.type==="error"&&(y(),this.setAnswer(k.message??"Something went wrong."),this.touringActive||(this.setStatus("rt-listening"),this.setCaption("")))},t.onerror=()=>{this.setAnswer("Couldn't connect to the realtime voice service."),this.endRealtime()},t.onclose=()=>{this.status!=="idle"&&this.endRealtime()}}catch{this.setAnswer("Couldn't access the microphone \u2014 check your browser's permission for this site."),this.setStatus("idle"),this.rtStarting=!1}}}endRealtime(){this.rtThinkingWatchdog&&(clearTimeout(this.rtThinkingWatchdog),this.rtThinkingWatchdog=null),this.rtStarting=!1,this.activeAudio?.pause(),this.activeAudio=null,this.rtSocket?.close(),this.rtSocket=null,this.rtCleanup?.(),this.rtCleanup=null,this.rtMicMuted=!1,this.rtSpeakerMuted=!1,this.setCaption(""),this.setStatus("idle"),this.tourGeneration++,this.touringActive=!1,this.rtTourAudioDoneResolve?.(),this.rtTourAudioDoneResolve=null,this.render()}toggleRtMic(){this.rtMicMuted=!this.rtMicMuted,this.render()}toggleRtSpeaker(){this.rtSpeakerMuted=!this.rtSpeakerMuted,this.rtPlaybackGain&&(this.rtPlaybackGain.gain.value=this.rtSpeakerMuted?0:1),this.render()}};function rr(n){if(!n||typeof n!="object")return"(no response)";let e=n;if(typeof e.text=="string"&&e.text)return e.text;switch(e.verb){case"highlight":case"open":return`(highlighted ${String(e.target)})`;case"navigate":return`(navigated to ${String(e.route)})`;case"do":return`(ran ${String(e.action)}${e.target?` on ${String(e.target)}`:""})`;case"tour":return Array.isArray(e.steps)?e.steps.map(t=>t.text??"").join(" "):"(tour)";default:return"(no response)"}}var ir=.02;function sr(n){let e=0;for(let t=0;t<n.length;t++)e+=n[t]*n[t];return Math.sqrt(e/n.length)}function ar(n,e){if(e===16e3)return n;let r=e/16e3,i=Math.round(n.length/r),s=new Float32Array(i),a=0,o=0;for(;a<i;){let d=Math.round((a+1)*r),h=0,y=0;for(let _=o;_<d&&_<n.length;_++)h+=n[_],y++;s[a]=y>0?h/y:0,a++,o=d}return s}function or(n){let e=new ArrayBuffer(n.length*2),t=new DataView(e);for(let r=0;r<n.length;r++){let i=Math.max(-1,Math.min(1,n[r]));t.setInt16(r*2,i<0?i*32768:i*32767,!0)}return e}typeof customElements<"u"&&!customElements.get("cairn-widget")&&customElements.define("cairn-widget",Ue);})();
package/dist/index.js CHANGED
@@ -1051,6 +1051,8 @@ function summarizeVerbForHistory(raw) {
1051
1051
  return `(read ${String(v.target)})`;
1052
1052
  case "call_tool":
1053
1053
  return `(called ${String(v.name)})`;
1054
+ case "batch":
1055
+ return Array.isArray(v.actions) ? `(${v.actions.length} steps: ${v.actions.map((a) => a.verb).join(", ")})` : "(batch)";
1054
1056
  default:
1055
1057
  return "(no response)";
1056
1058
  }
@@ -512,6 +512,8 @@ function summarizeVerbForHistory(verb) {
512
512
  return `(read ${verb.target})`;
513
513
  case "call_tool":
514
514
  return `(called ${verb.name})`;
515
+ case "batch":
516
+ return `(${verb.actions.length} steps: ${verb.actions.map((a) => a.verb).join(", ")})`;
515
517
  default:
516
518
  return "(no response)";
517
519
  }
package/dist/server.js CHANGED
@@ -111,21 +111,29 @@ async function resolveVerb(llm, systemPrompt, manifest, registeredActions, capab
111
111
  // to be a real element from the current page's manifest or this exact
112
112
  // request's own liveElements, and call_tool's name has to be one this
113
113
  // exact request's own webMcpTools reported — never invented.
114
+ const pageElements = manifest.pages.find((p) => p.route === input.route)?.elements ?? [];
115
+ const isKnownTarget = (target) => pageElements.some((e) => e.id === target) || (input.liveElements ?? []).some((e) => e.id === target);
116
+ const isKnownTool = (name) => (input.webMcpTools ?? []).some((t) => t.name === name);
114
117
  if (parsedVerb.data.verb === "click" || parsedVerb.data.verb === "fill" || parsedVerb.data.verb === "read") {
115
- const pageElements = manifest.pages.find((p) => p.route === input.route)?.elements ?? [];
116
- const target = parsedVerb.data.target;
117
- const known = pageElements.some((e) => e.id === target) || (input.liveElements ?? []).some((e) => e.id === target);
118
- if (!known) {
118
+ if (!isKnownTarget(parsedVerb.data.target)) {
119
119
  return { verb: "explain", text: "I don't see that on this page right now." };
120
120
  }
121
121
  }
122
122
  if (parsedVerb.data.verb === "call_tool") {
123
- const toolName = parsedVerb.data.name;
124
- const known = (input.webMcpTools ?? []).some((t) => t.name === toolName);
125
- if (!known) {
123
+ if (!isKnownTool(parsedVerb.data.name)) {
126
124
  return { verb: "explain", text: "That isn't something I can do here." };
127
125
  }
128
126
  }
127
+ if (parsedVerb.data.verb === "batch") {
128
+ // Every step validated up front, against the SAME real state — never
129
+ // partially execute a batch whose later step names something the
130
+ // model invented; refuse the whole turn instead of guessing which
131
+ // steps were "safe enough" to run.
132
+ const allKnown = parsedVerb.data.actions.every((action) => action.verb === "call_tool" ? isKnownTool(action.name) : isKnownTarget(action.target));
133
+ if (!allKnown) {
134
+ return { verb: "explain", text: "I don't see everything I'd need for that on this page right now." };
135
+ }
136
+ }
129
137
  // tour is allowed at every tier (see TIER_ALLOWED_VERBS) because
130
138
  // highlighting-only steps never move the user — but a step carrying a
131
139
  // "route" navigates just like the navigate verb does, and a step marked
@@ -301,7 +309,7 @@ function buildVerbToolSchema(registeredActions) {
301
309
  properties: {
302
310
  verb: { type: "string", enum: [...core_1.VERBS] },
303
311
  text: nullableString("Shown to the user. Required for explain. null (or omitted) if not applicable."),
304
- target: nullableString("An id from currentPageElements or liveElements. Required for highlight/open/click/fill/read. For do, the id of what the action applies to, if it needs one — prefer a liveElements id when the user means one specific item among several. null (or omitted) if not applicable."),
312
+ target: nullableString("An id from currentPageElements or liveElements. Required for highlight/open/click/fill/read. For do, the id of what the action applies to, if it needs one — prefer a liveElements id when the user means one specific item among several. Not used for batch — each of its own actions carries its own target instead. null (or omitted) if not applicable."),
305
313
  route: nullableString("A route from the manifest. Required for navigate. null (or omitted) if not applicable."),
306
314
  action: nullableString("Required for do. A short label for what's being done, e.g. \"archive-invoice\" " +
307
315
  (registeredActions.length
@@ -332,6 +340,25 @@ function buildVerbToolSchema(registeredActions) {
332
340
  additionalProperties: false,
333
341
  },
334
342
  },
343
+ actions: {
344
+ type: ["array", "null"],
345
+ description: "Required for batch, 2-5 items. Several click/fill/read/call_tool steps executed in order in ONE round trip, instead of one round trip each — use this when you already know several steps are needed and don't need to see one step's real result before choosing the next (e.g. filling three known fields, or clicking through a sequence you're already sure about). If a later step genuinely depends on what an earlier one turns up, use a single step instead and decide the next one once you see its real result. text (if any) is spoken once for the whole batch, not per step. null (or omitted) if not applicable.",
346
+ items: {
347
+ type: "object",
348
+ properties: {
349
+ verb: { type: "string", enum: ["click", "fill", "read", "call_tool"] },
350
+ target: nullableString("An id from currentPageElements or liveElements. Required for click/fill/read. null (or omitted) if not applicable."),
351
+ value: nullableString('Required for fill — the exact text to type into "target". null (or omitted) if not applicable.'),
352
+ name: nullableString("Required for call_tool — a tool name from this turn's webMcpTools list. null (or omitted) if not applicable."),
353
+ args: {
354
+ type: ["object", "null"],
355
+ description: "For call_tool — the arguments object, matching that tool's own inputSchema. null (or omitted) if the tool takes none.",
356
+ },
357
+ },
358
+ required: ["verb"],
359
+ additionalProperties: false,
360
+ },
361
+ },
335
362
  },
336
363
  required: ["verb"],
337
364
  additionalProperties: false,
@@ -368,9 +395,12 @@ directory below plus three things attached to each request:
368
395
  dynamically-rendered list (a specific session, a specific row) that
369
396
  currentPageElements has no way to know about ahead of time, and what lets
370
397
  you describe what's really on screen instead of only what the page
371
- generically does. It only covers what's currently visible in the
372
- viewport if the user means something scrolled out of view or not
373
- loaded yet, say so rather than guessing.
398
+ generically does. It covers what's on screen now and what's just
399
+ scrolled out of view, ranked by nearest first an entry further down
400
+ this list may need scrolling to before it's visible, which happens
401
+ automatically when you act on it. It won't include something not
402
+ rendered at all yet (behind a click, a different tab, not loaded) — say
403
+ so rather than guessing if the user means that.
374
404
  - "webMcpTools": real functions this exact page registered for you to call
375
405
  directly (name, description, and its own input schema) — when a real
376
406
  tool exists for what the user's asking, it's the most reliable way to do
@@ -448,6 +478,17 @@ webMcpTools — never invent one. You'll be shown the real result of each
448
478
  step and asked again what to do next; after a small number of steps,
449
479
  answer with a terminal verb even if incomplete, explaining what you found.
450
480
 
481
+ - batch: 2-5 of the four steps above (click/fill/read/call_tool, each in
482
+ its own shape — no separate "text"), run in order, in "actions" — use
483
+ this INSTEAD of separate single steps when you already know every step
484
+ you need and none of them depends on seeing an earlier one's real result
485
+ first (e.g. filling three fields you can already see, or a known
486
+ sequence of clicks). If a later step needs to react to what an earlier
487
+ one turns up, or depends on something an earlier step's click would
488
+ newly reveal, use single steps instead — a batch only sees the page as
489
+ it is right now, not as an earlier step in the same batch leaves it. One
490
+ step failing stops the rest of that batch.
491
+
451
492
  Every "text" field (in explain, or per-step in tour, or the optional text on
452
493
  any other verb) is read aloud AND shown on screen, so it must sound like a
453
494
  person talking, not documentation:
@@ -1,13 +1,14 @@
1
1
  import { type TourStep } from "@cairnvibe/core";
2
2
  import { type MissContext } from "./element-ladder";
3
- /** The real result of one agent-loop step (click/fill/read/call_tool)
4
- * fed back to the model as its next turn's "observation" so it can decide
5
- * what to do next instead of acting blind. The loop that drives this lives
6
- * on the caller's side, not here: index.tsx's runTypedAgentLoop for the
7
- * HTTP path, realtime-server.ts's finalizeTurn for the realtime one — this
8
- * module only ever executes one step at a time. */
3
+ /** The real result of one agent-loop step (click/fill/read/call_tool, or a
4
+ * batch of several) — fed back to the model as its next turn's
5
+ * "observation" so it can decide what to do next instead of acting blind.
6
+ * The loop that drives this lives on the caller's side, not here:
7
+ * index.tsx's runTypedAgentLoop for the HTTP path, realtime-server.ts's
8
+ * finalizeTurn for the realtime one this module only ever executes one
9
+ * step (or one batch of steps) at a time. */
9
10
  export interface ToolStepResult {
10
- verb: "click" | "fill" | "read" | "call_tool";
11
+ verb: "click" | "fill" | "read" | "call_tool" | "batch";
11
12
  target?: string;
12
13
  ok: boolean;
13
14
  observation: string;
@@ -190,6 +190,70 @@ function dispatchVerb(verb, route, options) {
190
190
  });
191
191
  return;
192
192
  }
193
+ // Several click/fill/read/call_tool steps in one round trip instead of
194
+ // one each — server.ts's resolveVerb already validated every action's
195
+ // target/name against real state before this ever arrived. Runs in
196
+ // order (never parallel — a later step may depend on an earlier one's
197
+ // DOM change) and stops at the first failure, reporting one combined
198
+ // observation back — a batch that stops partway is still a real,
199
+ // informative result for the model's next turn, not a silent partial
200
+ // success.
201
+ case "batch": {
202
+ if (verb.text)
203
+ options.onExplain(verb.text);
204
+ void executeBatchActions(verb.actions, route, options).then((result) => {
205
+ options.onToolStep?.({ verb: "batch", ok: result.ok, observation: result.observation });
206
+ });
207
+ return;
208
+ }
209
+ }
210
+ }
211
+ async function executeBatchActions(actions, route, options) {
212
+ const steps = [];
213
+ for (const action of actions) {
214
+ const result = await executeOneBatchAction(action, route, options);
215
+ steps.push(`${action.verb} ${"target" in action ? action.target : action.name}: ${result.observation}`);
216
+ if (!result.ok)
217
+ return { ok: false, observation: steps.join(" | ") };
218
+ }
219
+ return { ok: true, observation: steps.join(" | ") };
220
+ }
221
+ async function executeOneBatchAction(action, route, options) {
222
+ switch (action.verb) {
223
+ case "click": {
224
+ const el = (0, element_ladder_1.findElement)(action.target, options.liveElements);
225
+ if (!el) {
226
+ (options.onMiss ?? element_ladder_1.logMiss)({ attempted: action.target, route });
227
+ return { ok: false, observation: "Could not find that element on the page." };
228
+ }
229
+ (0, element_ladder_1.highlightElement)(el);
230
+ el.click();
231
+ return { ok: true, observation: "Clicked it." };
232
+ }
233
+ case "fill": {
234
+ const el = (0, element_ladder_1.findElement)(action.target, options.liveElements);
235
+ if (!el || !(0, element_ladder_1.fillElement)(el, action.value)) {
236
+ (options.onMiss ?? element_ladder_1.logMiss)({ attempted: action.target, route });
237
+ return {
238
+ ok: false,
239
+ observation: el ? "That element isn't a real form field — can't type into it." : "Could not find that element on the page.",
240
+ };
241
+ }
242
+ (0, element_ladder_1.highlightElement)(el);
243
+ return { ok: true, observation: `Typed "${action.value}" into it.` };
244
+ }
245
+ case "read": {
246
+ const el = (0, element_ladder_1.findElement)(action.target, options.liveElements);
247
+ if (!el) {
248
+ (options.onMiss ?? element_ladder_1.logMiss)({ attempted: action.target, route });
249
+ return { ok: false, observation: "Could not find that element on the page." };
250
+ }
251
+ return { ok: true, observation: (0, element_ladder_1.readElement)(el) };
252
+ }
253
+ case "call_tool": {
254
+ const result = await (0, webmcp_client_1.executeWebMcpTool)(action.name, action.args);
255
+ return { ok: result.ok, observation: result.observation };
256
+ }
193
257
  }
194
258
  }
195
259
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cairnvibe/sdk",
3
- "version": "0.2.11",
3
+ "version": "0.2.12",
4
4
  "description": "In-app AI copilot — <Copilot/> for React/Next.js, <cairn-widget> for any framework — plus the server handlers and realtime voice relay behind them.",
5
5
  "license": "MIT",
6
6
  "publishConfig": { "access": "public" },
package/src/index.tsx CHANGED
@@ -1247,6 +1247,8 @@ function summarizeVerbForHistory(raw: unknown): string {
1247
1247
  return `(read ${String(v.target)})`;
1248
1248
  case "call_tool":
1249
1249
  return `(called ${String(v.name)})`;
1250
+ case "batch":
1251
+ return Array.isArray(v.actions) ? `(${v.actions.length} steps: ${v.actions.map((a: { verb?: string }) => a.verb).join(", ")})` : "(batch)";
1250
1252
  default:
1251
1253
  return "(no response)";
1252
1254
  }
@@ -579,6 +579,8 @@ function summarizeVerbForHistory(verb: VerbResponse): string {
579
579
  return `(read ${verb.target})`;
580
580
  case "call_tool":
581
581
  return `(called ${verb.name})`;
582
+ case "batch":
583
+ return `(${verb.actions.length} steps: ${verb.actions.map((a) => a.verb).join(", ")})`;
582
584
  default:
583
585
  return "(no response)";
584
586
  }
package/src/server.ts CHANGED
@@ -185,21 +185,32 @@ export async function resolveVerb(
185
185
  // to be a real element from the current page's manifest or this exact
186
186
  // request's own liveElements, and call_tool's name has to be one this
187
187
  // exact request's own webMcpTools reported — never invented.
188
+ const pageElements = manifest.pages.find((p) => p.route === input.route)?.elements ?? [];
189
+ const isKnownTarget = (target: string) => pageElements.some((e) => e.id === target) || (input.liveElements ?? []).some((e) => e.id === target);
190
+ const isKnownTool = (name: string) => (input.webMcpTools ?? []).some((t) => t.name === name);
191
+
188
192
  if (parsedVerb.data.verb === "click" || parsedVerb.data.verb === "fill" || parsedVerb.data.verb === "read") {
189
- const pageElements = manifest.pages.find((p) => p.route === input.route)?.elements ?? [];
190
- const target = parsedVerb.data.target;
191
- const known = pageElements.some((e) => e.id === target) || (input.liveElements ?? []).some((e) => e.id === target);
192
- if (!known) {
193
+ if (!isKnownTarget(parsedVerb.data.target)) {
193
194
  return { verb: "explain", text: "I don't see that on this page right now." };
194
195
  }
195
196
  }
196
197
  if (parsedVerb.data.verb === "call_tool") {
197
- const toolName = parsedVerb.data.name;
198
- const known = (input.webMcpTools ?? []).some((t) => t.name === toolName);
199
- if (!known) {
198
+ if (!isKnownTool(parsedVerb.data.name)) {
200
199
  return { verb: "explain", text: "That isn't something I can do here." };
201
200
  }
202
201
  }
202
+ if (parsedVerb.data.verb === "batch") {
203
+ // Every step validated up front, against the SAME real state — never
204
+ // partially execute a batch whose later step names something the
205
+ // model invented; refuse the whole turn instead of guessing which
206
+ // steps were "safe enough" to run.
207
+ const allKnown = parsedVerb.data.actions.every((action) =>
208
+ action.verb === "call_tool" ? isKnownTool(action.name) : isKnownTarget(action.target),
209
+ );
210
+ if (!allKnown) {
211
+ return { verb: "explain", text: "I don't see everything I'd need for that on this page right now." };
212
+ }
213
+ }
203
214
 
204
215
  // tour is allowed at every tier (see TIER_ALLOWED_VERBS) because
205
216
  // highlighting-only steps never move the user — but a step carrying a
@@ -394,7 +405,7 @@ export function buildVerbToolSchema(registeredActions: string[]): Record<string,
394
405
  verb: { type: "string", enum: [...VERBS] },
395
406
  text: nullableString("Shown to the user. Required for explain. null (or omitted) if not applicable."),
396
407
  target: nullableString(
397
- "An id from currentPageElements or liveElements. Required for highlight/open/click/fill/read. For do, the id of what the action applies to, if it needs one — prefer a liveElements id when the user means one specific item among several. null (or omitted) if not applicable.",
408
+ "An id from currentPageElements or liveElements. Required for highlight/open/click/fill/read. For do, the id of what the action applies to, if it needs one — prefer a liveElements id when the user means one specific item among several. Not used for batch — each of its own actions carries its own target instead. null (or omitted) if not applicable.",
398
409
  ),
399
410
  route: nullableString("A route from the manifest. Required for navigate. null (or omitted) if not applicable."),
400
411
  action: nullableString(
@@ -434,6 +445,26 @@ export function buildVerbToolSchema(registeredActions: string[]): Record<string,
434
445
  additionalProperties: false,
435
446
  },
436
447
  },
448
+ actions: {
449
+ type: ["array", "null"],
450
+ description:
451
+ "Required for batch, 2-5 items. Several click/fill/read/call_tool steps executed in order in ONE round trip, instead of one round trip each — use this when you already know several steps are needed and don't need to see one step's real result before choosing the next (e.g. filling three known fields, or clicking through a sequence you're already sure about). If a later step genuinely depends on what an earlier one turns up, use a single step instead and decide the next one once you see its real result. text (if any) is spoken once for the whole batch, not per step. null (or omitted) if not applicable.",
452
+ items: {
453
+ type: "object",
454
+ properties: {
455
+ verb: { type: "string", enum: ["click", "fill", "read", "call_tool"] },
456
+ target: nullableString("An id from currentPageElements or liveElements. Required for click/fill/read. null (or omitted) if not applicable."),
457
+ value: nullableString('Required for fill — the exact text to type into "target". null (or omitted) if not applicable.'),
458
+ name: nullableString("Required for call_tool — a tool name from this turn's webMcpTools list. null (or omitted) if not applicable."),
459
+ args: {
460
+ type: ["object", "null"],
461
+ description: "For call_tool — the arguments object, matching that tool's own inputSchema. null (or omitted) if the tool takes none.",
462
+ },
463
+ },
464
+ required: ["verb"],
465
+ additionalProperties: false,
466
+ },
467
+ },
437
468
  },
438
469
  required: ["verb"],
439
470
  additionalProperties: false,
@@ -472,9 +503,12 @@ directory below plus three things attached to each request:
472
503
  dynamically-rendered list (a specific session, a specific row) that
473
504
  currentPageElements has no way to know about ahead of time, and what lets
474
505
  you describe what's really on screen instead of only what the page
475
- generically does. It only covers what's currently visible in the
476
- viewport if the user means something scrolled out of view or not
477
- loaded yet, say so rather than guessing.
506
+ generically does. It covers what's on screen now and what's just
507
+ scrolled out of view, ranked by nearest first an entry further down
508
+ this list may need scrolling to before it's visible, which happens
509
+ automatically when you act on it. It won't include something not
510
+ rendered at all yet (behind a click, a different tab, not loaded) — say
511
+ so rather than guessing if the user means that.
478
512
  - "webMcpTools": real functions this exact page registered for you to call
479
513
  directly (name, description, and its own input schema) — when a real
480
514
  tool exists for what the user's asking, it's the most reliable way to do
@@ -552,6 +586,17 @@ webMcpTools — never invent one. You'll be shown the real result of each
552
586
  step and asked again what to do next; after a small number of steps,
553
587
  answer with a terminal verb even if incomplete, explaining what you found.
554
588
 
589
+ - batch: 2-5 of the four steps above (click/fill/read/call_tool, each in
590
+ its own shape — no separate "text"), run in order, in "actions" — use
591
+ this INSTEAD of separate single steps when you already know every step
592
+ you need and none of them depends on seeing an earlier one's real result
593
+ first (e.g. filling three fields you can already see, or a known
594
+ sequence of clicks). If a later step needs to react to what an earlier
595
+ one turns up, or depends on something an earlier step's click would
596
+ newly reveal, use single steps instead — a batch only sees the page as
597
+ it is right now, not as an earlier step in the same batch leaves it. One
598
+ step failing stops the rest of that batch.
599
+
555
600
  Every "text" field (in explain, or per-step in tour, or the optional text on
556
601
  any other verb) is read aloud AND shown on screen, so it must sound like a
557
602
  person talking, not documentation:
@@ -5,18 +5,19 @@
5
5
  // explain — never guess, never wrong-click"). The server (`server.ts`)
6
6
  // enforces the same schema independently — never trust the client alone.
7
7
 
8
- import { VerbResponseSchema, type ApiCall, type TourStep, type VerbResponse } from "@cairnvibe/core";
8
+ import { VerbResponseSchema, type ApiCall, type BatchAction, type TourStep, type VerbResponse } from "@cairnvibe/core";
9
9
  import { findElement, fillElement, highlightElement, logMiss, readElement, type MissContext } from "./element-ladder";
10
10
  import { executeWebMcpTool } from "./webmcp-client";
11
11
 
12
- /** The real result of one agent-loop step (click/fill/read/call_tool)
13
- * fed back to the model as its next turn's "observation" so it can decide
14
- * what to do next instead of acting blind. The loop that drives this lives
15
- * on the caller's side, not here: index.tsx's runTypedAgentLoop for the
16
- * HTTP path, realtime-server.ts's finalizeTurn for the realtime one — this
17
- * module only ever executes one step at a time. */
12
+ /** The real result of one agent-loop step (click/fill/read/call_tool, or a
13
+ * batch of several) — fed back to the model as its next turn's
14
+ * "observation" so it can decide what to do next instead of acting blind.
15
+ * The loop that drives this lives on the caller's side, not here:
16
+ * index.tsx's runTypedAgentLoop for the HTTP path, realtime-server.ts's
17
+ * finalizeTurn for the realtime one this module only ever executes one
18
+ * step (or one batch of steps) at a time. */
18
19
  export interface ToolStepResult {
19
- verb: "click" | "fill" | "read" | "call_tool";
20
+ verb: "click" | "fill" | "read" | "call_tool" | "batch";
20
21
  target?: string;
21
22
  ok: boolean;
22
23
  observation: string;
@@ -229,6 +230,75 @@ function dispatchVerb(verb: VerbResponse, route: string, options: VerbExecutorOp
229
230
  });
230
231
  return;
231
232
  }
233
+
234
+ // Several click/fill/read/call_tool steps in one round trip instead of
235
+ // one each — server.ts's resolveVerb already validated every action's
236
+ // target/name against real state before this ever arrived. Runs in
237
+ // order (never parallel — a later step may depend on an earlier one's
238
+ // DOM change) and stops at the first failure, reporting one combined
239
+ // observation back — a batch that stops partway is still a real,
240
+ // informative result for the model's next turn, not a silent partial
241
+ // success.
242
+ case "batch": {
243
+ if (verb.text) options.onExplain(verb.text);
244
+ void executeBatchActions(verb.actions, route, options).then((result) => {
245
+ options.onToolStep?.({ verb: "batch", ok: result.ok, observation: result.observation });
246
+ });
247
+ return;
248
+ }
249
+ }
250
+ }
251
+
252
+ async function executeBatchActions(
253
+ actions: BatchAction[],
254
+ route: string,
255
+ options: VerbExecutorOptions,
256
+ ): Promise<{ ok: boolean; observation: string }> {
257
+ const steps: string[] = [];
258
+ for (const action of actions) {
259
+ const result = await executeOneBatchAction(action, route, options);
260
+ steps.push(`${action.verb} ${"target" in action ? action.target : action.name}: ${result.observation}`);
261
+ if (!result.ok) return { ok: false, observation: steps.join(" | ") };
262
+ }
263
+ return { ok: true, observation: steps.join(" | ") };
264
+ }
265
+
266
+ async function executeOneBatchAction(action: BatchAction, route: string, options: VerbExecutorOptions): Promise<{ ok: boolean; observation: string }> {
267
+ switch (action.verb) {
268
+ case "click": {
269
+ const el = findElement(action.target, options.liveElements);
270
+ if (!el) {
271
+ (options.onMiss ?? logMiss)({ attempted: action.target, route });
272
+ return { ok: false, observation: "Could not find that element on the page." };
273
+ }
274
+ highlightElement(el);
275
+ el.click();
276
+ return { ok: true, observation: "Clicked it." };
277
+ }
278
+ case "fill": {
279
+ const el = findElement(action.target, options.liveElements);
280
+ if (!el || !fillElement(el, action.value)) {
281
+ (options.onMiss ?? logMiss)({ attempted: action.target, route });
282
+ return {
283
+ ok: false,
284
+ observation: el ? "That element isn't a real form field — can't type into it." : "Could not find that element on the page.",
285
+ };
286
+ }
287
+ highlightElement(el);
288
+ return { ok: true, observation: `Typed "${action.value}" into it.` };
289
+ }
290
+ case "read": {
291
+ const el = findElement(action.target, options.liveElements);
292
+ if (!el) {
293
+ (options.onMiss ?? logMiss)({ attempted: action.target, route });
294
+ return { ok: false, observation: "Could not find that element on the page." };
295
+ }
296
+ return { ok: true, observation: readElement(el) };
297
+ }
298
+ case "call_tool": {
299
+ const result = await executeWebMcpTool(action.name, action.args);
300
+ return { ok: result.ok, observation: result.observation };
301
+ }
232
302
  }
233
303
  }
234
304