@artooi/ag-ui-web-component 0.6.0 → 0.8.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +73 -1
  2. package/README.md +180 -9
  3. package/dist/ag-ui-web-component.bundle.js +268 -47
  4. package/dist/ag-ui-web-component.bundle.js.map +4 -4
  5. package/dist/constants.d.ts +5 -0
  6. package/dist/constants.d.ts.map +1 -1
  7. package/dist/core/ag_ui_chat.d.ts +20 -0
  8. package/dist/core/ag_ui_chat.d.ts.map +1 -1
  9. package/dist/core/agui_client.d.ts +16 -0
  10. package/dist/core/agui_client.d.ts.map +1 -1
  11. package/dist/index.d.ts +3 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +847 -237
  14. package/dist/index.js.map +3 -3
  15. package/dist/tools/page_action_tools.d.ts +31 -0
  16. package/dist/tools/page_action_tools.d.ts.map +1 -0
  17. package/dist/ui/attachment_tray.d.ts +3 -0
  18. package/dist/ui/attachment_tray.d.ts.map +1 -1
  19. package/dist/ui/confirmation_card.d.ts +4 -1
  20. package/dist/ui/confirmation_card.d.ts.map +1 -1
  21. package/dist/ui/relative_time.d.ts +5 -3
  22. package/dist/ui/relative_time.d.ts.map +1 -1
  23. package/dist/ui/styles.d.ts +1 -1
  24. package/dist/ui/styles.d.ts.map +1 -1
  25. package/dist/ui/thread_drawer.d.ts +7 -1
  26. package/dist/ui/thread_drawer.d.ts.map +1 -1
  27. package/dist/ui/tool_call_card.d.ts +19 -8
  28. package/dist/ui/tool_call_card.d.ts.map +1 -1
  29. package/dist/ui/ui_strings.d.ts +126 -0
  30. package/dist/ui/ui_strings.d.ts.map +1 -0
  31. package/package.json +1 -1
  32. package/src/constants.ts +5 -0
  33. package/src/core/ag_ui_chat.ts +267 -46
  34. package/src/core/agui_client.ts +33 -2
  35. package/src/index.ts +7 -0
  36. package/src/tools/page_action_tools.ts +130 -0
  37. package/src/ui/attachment_tray.ts +13 -7
  38. package/src/ui/confirmation_card.ts +15 -5
  39. package/src/ui/relative_time.ts +15 -8
  40. package/src/ui/styles.ts +221 -0
  41. package/src/ui/thread_drawer.ts +53 -25
  42. package/src/ui/tool_call_card.ts +63 -25
  43. package/src/ui/ui_strings.ts +208 -0
  44. package/src/version.ts +1 -1
@@ -1,79 +1,79 @@
1
- var Iu=Object.defineProperty;var Es=(t,e)=>{for(var n in e)Iu(t,n,{get:e[n],enumerable:!0})};var br="ag-ui-chat",Ts="ag-ui-submit",_s="ag-ui-toggle",Xe={USER:"user",ASSISTANT:"assistant"},On="x-destructive",Ss="x-confirm",Ze="x-summary",Mn="x-navigates",ws=10,de={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Ge={UPLOADING:"uploading",READY:"ready",ERROR:"error"},As=10*1024*1024,Ke={MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Cu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function Ia(t,e){let n=[];return{text:t.replace(Cu,(o,s)=>{let i=e[s];return i==null||i===""?(n.includes(s)||n.push(s),o):String(i)}),missing:n}}function Nu(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&typeof e.prompt=="string"}function ks(t){return Array.isArray(t)?t.filter(Nu):[]}var Ln=class{#e=new Map;register(e){this.#e.set(e.name,e)}has(e){return this.#e.has(e)}get(e){let n=this.#e.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#e.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Is(t){return t[On]===!0}function Cs(t){return t[Mn]===!0}function Ns(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Rs(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,s=r.summary;typeof o=="string"&&typeof s=="string"&&(e[o]=s)}return e}var Ca=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Ru(t){let e=[];for(let n of t.matchAll(Ca)){let r=n[1];r!==void 0&&e.push(r)}return e}function Ou(t,e,n){let r={...n};return{path:e.replace(Ca,(s,i)=>{let a=n[i];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${i}"`);return delete r[i],encodeURIComponent(String(a))}),leftover:r}}function Mu(t,e){let n=new URLSearchParams;for(let[o,s]of Object.entries(e))n.set(o,String(s));let r=n.toString();return r===""?t:`${t}?${r}`}function Os(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Ze]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Ru(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[Mn]:!0,[Ze]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(p=>p.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let s=n.params??{},{path:i,leftover:a}=Ou(o.id,o.path,s),l=Mu(i,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}function Ms(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Ze]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[On]:!0,[Ze]:`Update ${t.name}`},handler:r=>n(r)}),e}function Ls(t){let e=document.createElement("div");e.className="attachment-chips";for(let n of t)e.appendChild(Lu(n));return e}function Lu(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready";let n=document.createElement("span");n.className="attachment-chip-icon",n.textContent=Ps(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.textContent=xr(t.size),e.append(n,r,o),e}function Ps(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function xr(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var ge=[];for(let t=0;t<256;++t)ge.push((t+256).toString(16).slice(1));function Na(t,e=0){return(ge[t[e+0]]+ge[t[e+1]]+ge[t[e+2]]+ge[t[e+3]]+"-"+ge[t[e+4]]+ge[t[e+5]]+"-"+ge[t[e+6]]+ge[t[e+7]]+"-"+ge[t[e+8]]+ge[t[e+9]]+"-"+ge[t[e+10]]+ge[t[e+11]]+ge[t[e+12]]+ge[t[e+13]]+ge[t[e+14]]+ge[t[e+15]]).toLowerCase()}var Ds,Pu=new Uint8Array(16);function Us(){if(!Ds){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ds=crypto.getRandomValues.bind(crypto)}return Ds(Pu)}var Du=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Gs={randomUUID:Du};function Uu(t,e,n){if(Gs.randomUUID&&!e&&!t)return Gs.randomUUID();t=t||{};let r=t.random??t.rng?.()??Us();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Na(r)}var ht=Uu;var u={};Es(u,{BRAND:()=>cd,DIRTY:()=>_t,EMPTY_PATH:()=>$u,INVALID:()=>O,NEVER:()=>Xd,OK:()=>xe,ParseStatus:()=>ve,Schema:()=>U,ZodAny:()=>vt,ZodArray:()=>ct,ZodBigInt:()=>wt,ZodBoolean:()=>At,ZodBranded:()=>Dn,ZodCatch:()=>Ut,ZodDate:()=>kt,ZodDefault:()=>Dt,ZodDiscriminatedUnion:()=>_r,ZodEffects:()=>Me,ZodEnum:()=>Lt,ZodError:()=>we,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>wr,ZodIntersection:()=>Rt,ZodIssueCode:()=>E,ZodLazy:()=>Ot,ZodLiteral:()=>Mt,ZodMap:()=>cn,ZodNaN:()=>dn,ZodNativeEnum:()=>Pt,ZodNever:()=>He,ZodNull:()=>Ct,ZodNullable:()=>Je,ZodNumber:()=>St,ZodObject:()=>Ae,ZodOptional:()=>Re,ZodParsedType:()=>k,ZodPipeline:()=>Un,ZodPromise:()=>yt,ZodReadonly:()=>Gt,ZodRecord:()=>Sr,ZodSchema:()=>U,ZodSet:()=>un,ZodString:()=>gt,ZodSymbol:()=>an,ZodTransformer:()=>Me,ZodTuple:()=>qe,ZodType:()=>U,ZodUndefined:()=>It,ZodUnion:()=>Nt,ZodUnknown:()=>lt,ZodVoid:()=>ln,addIssueToContext:()=>w,any:()=>yd,array:()=>Td,bigint:()=>fd,boolean:()=>$a,coerce:()=>Wd,custom:()=>Ga,date:()=>hd,datetimeRegex:()=>Da,defaultErrorMap:()=>it,discriminatedUnion:()=>Ad,effect:()=>Gd,enum:()=>Pd,function:()=>Od,getErrorMap:()=>rn,getParsedType:()=>Ye,instanceof:()=>dd,intersection:()=>kd,isAborted:()=>Er,isAsync:()=>on,isDirty:()=>Tr,isValid:()=>mt,late:()=>ud,lazy:()=>Md,literal:()=>Ld,makeIssue:()=>Pn,map:()=>Nd,nan:()=>pd,nativeEnum:()=>Dd,never:()=>xd,null:()=>vd,nullable:()=>Fd,number:()=>Fa,object:()=>_d,objectUtil:()=>Hs,oboolean:()=>jd,onumber:()=>Vd,optional:()=>Hd,ostring:()=>Bd,pipeline:()=>zd,preprocess:()=>$d,promise:()=>Ud,quotelessJson:()=>Gu,record:()=>Cd,set:()=>Rd,setErrorMap:()=>Fu,strictObject:()=>Sd,string:()=>Ha,symbol:()=>md,transformer:()=>Gd,tuple:()=>Id,undefined:()=>gd,union:()=>wd,unknown:()=>bd,util:()=>F,void:()=>Ed});var F;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(F||(F={}));var Hs;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Hs||(Hs={}));var k=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ye=t=>{switch(typeof t){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(t)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(t)?k.array:t===null?k.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?k.promise:typeof Map<"u"&&t instanceof Map?k.map:typeof Set<"u"&&t instanceof Set?k.set:typeof Date<"u"&&t instanceof Date?k.date:k.object;default:return k.unknown}};var E=F.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"]),Gu=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),we=class t 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};we.create=t=>new we(t);var Hu=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===k.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,F.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${F.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${F.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${F.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:F.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,F.assertNever(t)}return{message:n}},it=Hu;var Ra=it;function Fu(t){Ra=t}function rn(){return Ra}var Pn=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},$u=[];function w(t,e){let n=rn(),r=Pn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===it?void 0:it].filter(o=>!!o)});t.common.issues.push(r)}var ve=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return O;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return O;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},O=Object.freeze({status:"aborted"}),_t=t=>({status:"dirty",value:t}),xe=t=>({status:"valid",value:t}),Er=t=>t.status==="aborted",Tr=t=>t.status==="dirty",mt=t=>t.status==="valid",on=t=>typeof Promise<"u"&&t instanceof Promise;var I;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}));var Oe=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}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}},Oa=(t,e)=>{if(mt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new we(t.common.issues);return this._error=n,this._error}}};function L(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:l}=t;return i.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var U=class{get description(){return this._def.description}_getType(e){return Ye(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ve,ctx:{common:e.parent.common,data:e.data,parsedType:Ye(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(on(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Oa(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return mt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>mt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ye(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(on(o)?o:Promise.resolve(o));return Oa(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Me({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Re.create(this,this._def)}nullable(){return Je.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ct.create(this)}promise(){return yt.create(this,this._def)}or(e){return Nt.create([this,e],this._def)}and(e){return Rt.create(this,e,this._def)}transform(e){return new Me({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Dt({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Dn({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ut({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Un.create(this,e)}readonly(){return Gt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},zu=/^c[^\s-]{8,}$/i,Bu=/^[0-9a-z]+$/,Vu=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ju=/^[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,Wu=/^[a-z0-9_-]{21}$/i,Xu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Zu=/^[-+]?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)?)??$/,Ku=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Yu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Fs,qu=/^(?:(?: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])$/,Ju=/^(?:(?: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])$/,Qu=/^(([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]))$/,ed=/^(([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])$/,td=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,La="((\\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])))",rd=new RegExp(`^${La}$`);function Pa(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function od(t){return new RegExp(`^${Pa(t)}$`)}function Da(t){let e=`${La}T${Pa(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function sd(t,e){return!!((e==="v4"||!e)&&qu.test(t)||(e==="v6"||!e)&&Qu.test(t))}function id(t,e){if(!Xu.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function ad(t,e){return!!((e==="v4"||!e)&&Ju.test(t)||(e==="v6"||!e)&&ed.test(t))}var gt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:k.string,received:s.parsedType}),O}let r=new ve,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.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&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?w(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&w(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Ku.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Fs||(Fs=new RegExp(Yu,"u")),Fs.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")ju.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Wu.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")zu.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Bu.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Vu.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),w(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"regex",code:E.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)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.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)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Da(s).test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?rd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?od(s).test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Zu.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?sd(e.data,s.version)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?id(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?ad(e.data,s.version)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?td.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?nd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):F.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:E.invalid_string,...I.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.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,...I.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,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...I.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...I.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...I.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...I.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...I.errToObj(n)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};gt.create=t=>new gt({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...L(t)});function ld(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var St=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==k.number){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:k.number,received:s.parsedType}),O}let r,o=new ve;for(let s of this._def.checks)s.kind==="int"?F.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ld(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_finite,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&F.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};St.create=t=>new St({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...L(t)});var wt=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==k.bigint)return this._getInvalidInput(e);let r,o=new ve;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),w(r,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):F.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return w(n,{code:E.invalid_type,expected:k.bigint,received:n.parsedType}),O}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};wt.create=t=>new wt({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...L(t)});var At=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.boolean,received:r.parsedType}),O}return xe(e.data)}};At.create=t=>new At({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...L(t)});var kt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_type,expected:k.date,received:s.parsedType}),O}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return w(s,{code:E.invalid_date}),O}let r=new ve,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):F.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:I.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:I.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};kt.create=t=>new kt({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...L(t)});var an=class extends U{_parse(e){if(this._getType(e)!==k.symbol){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.symbol,received:r.parsedType}),O}return xe(e.data)}};an.create=t=>new an({typeName:M.ZodSymbol,...L(t)});var It=class extends U{_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.undefined,received:r.parsedType}),O}return xe(e.data)}};It.create=t=>new It({typeName:M.ZodUndefined,...L(t)});var Ct=class extends U{_parse(e){if(this._getType(e)!==k.null){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.null,received:r.parsedType}),O}return xe(e.data)}};Ct.create=t=>new Ct({typeName:M.ZodNull,...L(t)});var vt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return xe(e.data)}};vt.create=t=>new vt({typeName:M.ZodAny,...L(t)});var lt=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xe(e.data)}};lt.create=t=>new lt({typeName:M.ZodUnknown,...L(t)});var He=class extends U{_parse(e){let n=this._getOrReturnCtx(e);return w(n,{code:E.invalid_type,expected:k.never,received:n.parsedType}),O}};He.create=t=>new He({typeName:M.ZodNever,...L(t)});var ln=class extends U{_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.void,received:r.parsedType}),O}return xe(e.data)}};ln.create=t=>new ln({typeName:M.ZodVoid,...L(t)});var ct=class t extends U{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==k.array)return w(n,{code:E.invalid_type,expected:k.array,received:n.parsedType}),O;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(w(n,{code:i?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(w(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(w(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new Oe(n,i,n.path,a)))).then(i=>ve.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new Oe(n,i,n.path,a)));return ve.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:I.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};ct.create=(t,e)=>new ct({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(e)});function sn(t){if(t instanceof Ae){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Re.create(sn(r))}return new Ae({...t._def,shape:()=>e})}else return t instanceof ct?new ct({...t._def,type:sn(t.element)}):t instanceof Re?Re.create(sn(t.unwrap())):t instanceof Je?Je.create(sn(t.unwrap())):t instanceof qe?qe.create(t.items.map(e=>sn(e))):t}var Ae=class t extends U{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(),n=F.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==k.object){let c=this._getOrReturnCtx(e);return w(c,{code:E.invalid_type,expected:k.object,received:c.parsedType}),O}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof He&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let l=[];for(let c of i){let p=s[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new Oe(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof He){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of a)l.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")a.length>0&&(w(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let p of a){let m=o.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new Oe(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of l){let m=await p.key,x=await p.value;c.push({key:m,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>ve.mergeObjectSync(r,c)):ve.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return I.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of F.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of F.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return sn(this)}partial(e){let n={};for(let r of F.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of F.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof Re;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return Ua(F.objectKeys(this.shape))}};Ae.create=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strip",catchall:He.create(),typeName:M.ZodObject,...L(e)});Ae.strictCreate=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strict",catchall:He.create(),typeName:M.ZodObject,...L(e)});Ae.lazycreate=(t,e)=>new Ae({shape:t,unknownKeys:"strip",catchall:He.create(),typeName:M.ZodObject,...L(e)});var Nt=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new we(a.ctx.common.issues));return w(n,{code:E.invalid_union,unionErrors:i}),O}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!s&&(s={result:p,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(l=>new we(l));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Nt.create=(t,e)=>new Nt({options:t,typeName:M.ZodUnion,...L(e)});var at=t=>t instanceof Ot?at(t.schema):t instanceof Me?at(t.innerType()):t instanceof Mt?[t.value]:t instanceof Lt?t.options:t instanceof Pt?F.objectValues(t.enum):t instanceof Dt?at(t._def.innerType):t instanceof It?[void 0]:t instanceof Ct?[null]:t instanceof Re?[void 0,...at(t.unwrap())]:t instanceof Je?[null,...at(t.unwrap())]:t instanceof Dn||t instanceof Gt?at(t.unwrap()):t instanceof Ut?at(t._def.innerType):[],_r=class t extends U{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.object)return w(n,{code:E.invalid_type,expected:k.object,received:n.parsedType}),O;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(w(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=at(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...L(r)})}};function $s(t,e){let n=Ye(t),r=Ye(e);if(t===e)return{valid:!0,data:t};if(n===k.object&&r===k.object){let o=F.objectKeys(e),s=F.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let l=$s(t[a],e[a]);if(!l.valid)return{valid:!1};i[a]=l.data}return{valid:!0,data:i}}else if(n===k.array&&r===k.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],l=$s(i,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Rt=class extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Er(s)||Er(i))return O;let a=$s(s.value,i.value);return a.valid?((Tr(s)||Tr(i))&&n.dirty(),{status:n.value,value:a.data}):(w(r,{code:E.invalid_intersection_types}),O)};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,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Rt.create=(t,e,n)=>new Rt({left:t,right:e,typeName:M.ZodIntersection,...L(n)});var qe=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.array)return w(r,{code:E.invalid_type,expected:k.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return w(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(w(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Oe(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>ve.mergeArray(n,i)):ve.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};qe.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new qe({items:t,typeName:M.ZodTuple,rest:null,...L(e)})};var Sr=class t extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.object)return w(r,{code:E.invalid_type,expected:k.object,received:r.parsedType}),O;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new Oe(r,a,r.path,a)),value:i._parse(new Oe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ve.mergeObjectAsync(n,o):ve.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof U?new t({keyType:e,valueType:n,typeName:M.ZodRecord,...L(r)}):new t({keyType:gt.create(),valueType:e,typeName:M.ZodRecord,...L(n)})}},cn=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.map)return w(r,{code:E.invalid_type,expected:k.map,received:r.parsedType}),O;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Oe(r,a,r.path,[c,"key"])),value:s._parse(new Oe(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of i){let c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}}}};cn.create=(t,e,n)=>new cn({valueType:e,keyType:t,typeName:M.ZodMap,...L(n)});var un=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return w(r,{code:E.invalid_type,expected:k.set,received:r.parsedType}),O;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(w(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(w(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(l){let c=new Set;for(let p of l){if(p.status==="aborted")return O;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>s._parse(new Oe(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>i(l)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:I.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};un.create=(t,e)=>new un({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...L(e)});var wr=class t extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.function)return w(n,{code:E.invalid_type,expected:k.function,received:n.parsedType}),O;function r(a,l){return Pn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,rn(),it].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function o(a,l){return Pn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,rn(),it].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:l}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof yt){let a=this;return xe(async function(...l){let c=new we([]),p=await a._def.args.parseAsync(l,s).catch(f=>{throw c.addIssue(r(l,f)),c}),m=await Reflect.apply(i,this,p);return await a._def.returns._def.type.parseAsync(m,s).catch(f=>{throw c.addIssue(o(m,f)),c})})}else{let a=this;return xe(function(...l){let c=a._def.args.safeParse(l,s);if(!c.success)throw new we([r(l,c.error)]);let p=Reflect.apply(i,this,c.data),m=a._def.returns.safeParse(p,s);if(!m.success)throw new we([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:qe.create(e).rest(lt.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||qe.create([]).rest(lt.create()),returns:n||lt.create(),typeName:M.ZodFunction,...L(r)})}},Ot=class extends U{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ot.create=(t,e)=>new Ot({getter:t,typeName:M.ZodLazy,...L(e)});var Mt=class extends U{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return w(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:e.data}}get value(){return this._def.value}};Mt.create=(t,e)=>new Mt({value:t,typeName:M.ZodLiteral,...L(e)});function Ua(t,e){return new Lt({values:t,typeName:M.ZodEnum,...L(e)})}var Lt=class t extends U{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return w(n,{expected:F.joinValues(r),received:n.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return w(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return xe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Lt.create=Ua;var Pt=class extends U{_parse(e){let n=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.number){let o=F.objectValues(n);return w(r,{expected:F.joinValues(o),received:r.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=F.objectValues(n);return w(r,{received:r.data,code:E.invalid_enum_value,options:o}),O}return xe(e.data)}get enum(){return this._def.values}};Pt.create=(t,e)=>new Pt({values:t,typeName:M.ZodNativeEnum,...L(e)});var yt=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.promise&&n.common.async===!1)return w(n,{code:E.invalid_type,expected:k.promise,received:n.parsedType}),O;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return xe(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};yt.create=(t,e)=>new yt({type:t,typeName:M.ZodPromise,...L(e)});var Me=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{w(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return O;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?O:l.status==="dirty"?_t(l.value):n.value==="dirty"?_t(l.value):l});{if(n.value==="aborted")return O;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?O:a.status==="dirty"?_t(a.value):n.value==="dirty"?_t(a.value):a}}if(o.type==="refinement"){let i=a=>{let l=o.refinement(a,s);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!mt(i))return O;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>mt(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):O);F.assertNever(o)}};Me.create=(t,e,n)=>new Me({schema:t,typeName:M.ZodEffects,effect:e,...L(n)});Me.createWithPreprocess=(t,e,n)=>new Me({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...L(n)});var Re=class extends U{_parse(e){return this._getType(e)===k.undefined?xe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Re.create=(t,e)=>new Re({innerType:t,typeName:M.ZodOptional,...L(e)});var Je=class extends U{_parse(e){return this._getType(e)===k.null?xe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Je.create=(t,e)=>new Je({innerType:t,typeName:M.ZodNullable,...L(e)});var Dt=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Dt.create=(t,e)=>new Dt({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...L(e)});var Ut=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return on(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ut.create=(t,e)=>new Ut({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...L(e)});var dn=class extends U{_parse(e){if(this._getType(e)!==k.nan){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.nan,received:r.parsedType}),O}return{status:"valid",value:e.data}}};dn.create=t=>new dn({typeName:M.ZodNaN,...L(t)});var cd=Symbol("zod_brand"),Dn=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Un=class t extends U{_parse(e){let{status:n,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"?O:s.status==="dirty"?(n.dirty(),_t(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:M.ZodPipeline})}},Gt=class extends U{_parse(e){let n=this._def.innerType._parse(e),r=o=>(mt(o)&&(o.value=Object.freeze(o.value)),o);return on(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Gt.create=(t,e)=>new Gt({innerType:t,typeName:M.ZodReadonly,...L(e)});function Ma(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Ga(t,e={},n){return t?vt.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Ma(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!s){let i=Ma(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):vt.create()}var ud={object:Ae.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var dd=(t,e={message:`Input not instance of ${t.name}`})=>Ga(n=>n instanceof t,e),Ha=gt.create,Fa=St.create,pd=dn.create,fd=wt.create,$a=At.create,hd=kt.create,md=an.create,gd=It.create,vd=Ct.create,yd=vt.create,bd=lt.create,xd=He.create,Ed=ln.create,Td=ct.create,_d=Ae.create,Sd=Ae.strictCreate,wd=Nt.create,Ad=_r.create,kd=Rt.create,Id=qe.create,Cd=Sr.create,Nd=cn.create,Rd=un.create,Od=wr.create,Md=Ot.create,Ld=Mt.create,Pd=Lt.create,Dd=Pt.create,Ud=yt.create,Gd=Me.create,Hd=Re.create,Fd=Je.create,$d=Me.createWithPreprocess,zd=Un.create,Bd=()=>Ha().optional(),Vd=()=>Fa().optional(),jd=()=>$a().optional(),Wd={string:(t=>gt.create({...t,coerce:!0})),number:(t=>St.create({...t,coerce:!0})),boolean:(t=>At.create({...t,coerce:!0})),bigint:(t=>wt.create({...t,coerce:!0})),date:(t=>kt.create({...t,coerce:!0}))};var Xd=O;var Zd=u.object({name:u.string(),arguments:u.string()}),Kd=u.object({id:u.string(),type:u.literal("function"),function:Zd,encryptedValue:u.string().optional()}),Ar=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),Yd=u.object({type:u.literal("text"),text:u.string()}),qd=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),Jd=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),kr=u.discriminatedUnion("type",[qd,Jd]),Qd=u.object({type:u.literal("image"),source:kr,metadata:u.unknown().optional()}),ep=u.object({type:u.literal("audio"),source:kr,metadata:u.unknown().optional()}),tp=u.object({type:u.literal("video"),source:kr,metadata:u.unknown().optional()}),np=u.object({type:u.literal("document"),source:kr,metadata:u.unknown().optional()});var za=u.object({type:u.literal("binary"),mimeType:u.string(),id:u.string().optional(),url:u.string().optional(),data:u.string().optional(),filename:u.string().optional()}),Ba=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:u.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},Ev=za.superRefine((t,e)=>{Ba(t,e)}),rp=u.discriminatedUnion("type",[Yd,Qd,ep,tp,np,za]),op=rp.superRefine((t,e)=>{t.type==="binary"&&Ba(t,e)}),sp=Ar.extend({role:u.literal("developer"),content:u.string()}),ip=Ar.extend({role:u.literal("system"),content:u.string()}),ap=Ar.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(Kd).optional()}),lp=Ar.extend({role:u.literal("user"),content:u.union([u.string(),u.array(op)])}),cp=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),up=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),dp=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),Va=u.discriminatedUnion("role",[sp,ip,ap,lp,cp,up,dp]),Tv=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),pp=u.object({description:u.string(),value:u.string()}),ja=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),fp=u.object({id:u.string(),reason:u.string(),message:u.string().optional(),toolCallId:u.string().optional(),responseSchema:u.record(u.any()).optional(),expiresAt:u.string().optional(),metadata:u.record(u.any()).optional()}),hp=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),mp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(Va),tools:u.array(ja),context:u.array(pp),forwardedProps:u.any(),resume:u.array(hp).optional()}),gp=u.any(),q=class extends Error{constructor(t){super(t)}},zs=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},vp=u.object({name:u.string(),description:u.string().optional()}),yp=u.object({name:u.string().optional(),type:u.string().optional(),description:u.string().optional(),version:u.string().optional(),provider:u.string().optional(),documentationUrl:u.string().optional(),metadata:u.record(u.unknown()).optional()}),bp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),xp=u.object({supported:u.boolean().optional(),items:u.array(ja).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Ep=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),Tp=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),_p=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(vp).optional()}),Sp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),wp=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),Ap=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),kp=u.object({input:wp.optional(),output:Ap.optional()}),Ip=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),Cp=u.object({supported:u.boolean().optional(),approvals:u.boolean().optional(),interventions:u.boolean().optional(),feedback:u.boolean().optional(),interrupts:u.boolean().optional(),approveWithEdits:u.boolean().optional()}),_v=u.object({identity:yp.optional(),transport:bp.optional(),tools:xp.optional(),output:Ep.optional(),state:Tp.optional(),multiAgent:_p.optional(),reasoning:Sp.optional(),multimodal:kp.optional(),execution:Ip.optional(),humanInTheLoop:Cp.optional(),custom:u.record(u.unknown()).optional()}),Wa=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user")]),v=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),V=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),Np=V.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:Wa.default("assistant"),name:u.string().optional()}),Xa=V.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Rp=V.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),Op=V.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:Wa.optional(),delta:u.string().optional(),name:u.string().optional()}),Mp=V.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),Lp=Xa.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Pp=V.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),Dp=V.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),Up=V.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),Gp=V.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),Hp=V.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),Fp=V.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),$p=V.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),zp=V.extend({type:u.literal(v.THINKING_END)}),Bp=V.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:gp}),Vp=V.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),jp=V.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(Va)}),Wp=V.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),Xp=V.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),Zp=V.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),Kp=V.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Yp=V.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:mp.optional()}),qp=u.object({type:u.literal("success")}).strict(),Jp=u.object({type:u.literal("interrupt"),interrupts:u.array(fp).min(1)}).strict(),Qp=u.discriminatedUnion("type",[qp,Jp]),ef=V.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:Qp.nullable().optional().transform(t=>t??void 0)}),tf=V.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),nf=V.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),rf=V.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),of=u.union([u.literal("tool-call"),u.literal("message")]),sf=V.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),af=V.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),lf=V.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),cf=V.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),uf=V.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),df=V.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),pf=V.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:of,entityId:u.string(),encryptedValue:u.string()}),Ir=u.discriminatedUnion("type",[Np,Xa,Rp,Op,$p,zp,Mp,Lp,Pp,Dp,Up,Gp,Fp,Hp,Bp,Vp,jp,Wp,Xp,Zp,Kp,Yp,ef,tf,nf,rf,sf,af,lf,cf,uf,df,pf]);var Bs={};Es(Bs,{JsonPatchError:()=>ne,_areEquals:()=>Fn,applyOperation:()=>Ht,applyPatch:()=>Pr,applyReducer:()=>vf,deepClone:()=>mf,getValueByPointer:()=>Mr,validate:()=>Ka,validator:()=>Lr});var ff=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var s in o)o.hasOwnProperty(s)&&(r[s]=o[s])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),hf=Object.prototype.hasOwnProperty;function Nr(t,e){return hf.call(t,e)}function Rr(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var o in t)Nr(t,o)&&r.push(o);return r}function ye(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Or(t){for(var e=0,n=t.length,r;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function Qe(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Gn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Cr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Cr(t[e]))return!0}else if(typeof t=="object"){for(var r=Rr(t),o=r.length,s=0;s<o;s++)if(Cr(t[r[s]]))return!0}}return!1}function Za(t,e){var n=[t];for(var r in e){var o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
2
- `)}var Hn=(function(t){ff(e,t);function e(n,r,o,s,i){var a=this.constructor,l=t.call(this,Za(n,{name:r,index:o,operation:s,tree:i}))||this;return l.name=r,l.index=o,l.operation=s,l.tree=i,Object.setPrototypeOf(l,a.prototype),l.message=Za(n,{name:r,index:o,operation:s,tree:i}),l}return e})(Error);var ne=Hn,mf=ye,pn={add:function(t,e,n){return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){var r=Mr(n,this.path);r&&(r=ye(r));var o=Ht(n,{op:"remove",path:this.from}).removed;return Ht(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Mr(n,this.from);return Ht(n,{op:"add",path:this.path,value:ye(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Fn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},gf={add:function(t,e,n){return Or(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){var r=t.splice(e,1);return{newDocument:n,removed:r[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:pn.move,copy:pn.copy,test:pn.test,_get:pn._get};function Mr(t,e){if(e=="")return t;var n={op:"_get",path:e};return Ht(t,n),n.value}function Ht(t,e,n,r,o,s){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),s===void 0&&(s=0),n&&(typeof n=="function"?n(e,0,t,e.path):Lr(e,0)),e.path===""){var i={newDocument:t};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=t,i;if(e.op==="move"||e.op==="copy")return i.newDocument=Mr(t,e.from),e.op==="move"&&(i.removed=t),i;if(e.op==="test"){if(i.test=Fn(t,e.value),i.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i.newDocument=t,i}else{if(e.op==="remove")return i.removed=t,i.newDocument=null,i;if(e.op==="_get")return e.value=t,i;if(n)throw new ne("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return i}}else{r||(t=ye(t));var a=e.path||"",l=a.split("/"),c=t,p=1,m=l.length,x=void 0,f=void 0,h=void 0;for(typeof n=="function"?h=n:h=Lr;;){if(f=l[p],f&&f.indexOf("~")!=-1&&(f=Gn(f)),o&&(f=="__proto__"||f=="prototype"&&p>0&&l[p-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&x===void 0&&(c[f]===void 0?x=l.slice(0,p).join("/"):p==m-1&&(x=e.path),x!==void 0&&h(e,0,t,x)),p++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Or(f))throw new ne("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Or(f)&&(f=~~f)}if(p>=m){if(n&&e.op==="add"&&f>c.length)throw new ne("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);var i=gf[e.op].call(e,c,f,t);if(i.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}}else if(p>=m){var i=pn[e.op].call(e,c,f,t);if(i.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return i}if(c=c[f],n&&p<m&&(!c||typeof c!="object"))throw new ne("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Pr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ye(t));for(var s=new Array(e.length),i=0,a=e.length;i<a;i++)s[i]=Ht(t,e[i],n,!0,o,i),t=s[i].newDocument;return s.newDocument=t,s}function vf(t,e,n){var r=Ht(t,e);if(r.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Lr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new ne("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(pn[t.op]){if(typeof t.path!="string")throw new ne("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ne('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ne("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ne("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Cr(t.value))throw new ne("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,s=r.split("/").length;if(o!==s+1&&o!==s)throw new ne("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new ne("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var i={op:"_get",path:t.from,value:void 0},a=Ka([i],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new ne("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new ne("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function Ka(t,e,n){try{if(!Array.isArray(t))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Pr(ye(e),ye(t),n||!0);else{n=n||Lr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof ne)return o;throw o}}function Fn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,s,i;if(n&&r){if(s=t.length,s!=e.length)return!1;for(o=s;o--!==0;)if(!Fn(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(s=a.length,s!==Object.keys(e).length)return!1;for(o=s;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=s;o--!==0;)if(i=a[o],!Fn(t[i],e[i]))return!1;return!0}return t!==t&&e!==e}var Xs={};Es(Xs,{compare:()=>wf,generate:()=>Vs,observe:()=>Sf,unobserve:()=>_f});var js=new WeakMap,yf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),bf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function xf(t){return js.get(t)}function Ef(t,e){return t.observers.get(e)}function Tf(t,e){t.observers.delete(e.callback)}function _f(t,e){e.unobserve()}function Sf(t,e){var n=[],r,o=xf(t);if(!o)o=new yf(t),js.set(t,o);else{var s=Ef(o,e);r=s&&s.observer}if(r)return r;if(r={},o.value=ye(t),e){r.callback=e,r.next=null;var i=function(){Vs(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(i)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=t,r.unobserve=function(){Vs(r),clearTimeout(r.next),Tf(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new bf(e,r)),r}function Vs(t,e){e===void 0&&(e=!1);var n=js.get(t.object);Ws(n.value,t.object,t.patches,"",e),t.patches.length&&Pr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function Ws(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Rr(e),i=Rr(t),a=!1,l=!1,c=i.length-1;c>=0;c--){var p=i[c],m=t[p];if(Nr(e,p)&&!(e[p]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var x=e[p];typeof m=="object"&&m!=null&&typeof x=="object"&&x!=null&&Array.isArray(m)===Array.isArray(x)?Ws(m,x,n,r+"/"+Qe(p),o):m!==x&&(a=!0,o&&n.push({op:"test",path:r+"/"+Qe(p),value:ye(m)}),n.push({op:"replace",path:r+"/"+Qe(p),value:ye(x)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+Qe(p),value:ye(m)}),n.push({op:"remove",path:r+"/"+Qe(p)}),l=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&s.length==i.length))for(var c=0;c<s.length;c++){var p=s[c];!Nr(t,p)&&e[p]!==void 0&&n.push({op:"add",path:r+"/"+Qe(p),value:ye(e[p])})}}}function wf(t,e,n){n===void 0&&(n=!1);var r=[];return Ws(t,e,r,"",n),r}var Dr=Object.assign({},Bs,Xs,{JsonPatchError:Hn,deepClone:ye,escapePathComponent:Qe,unescapePathComponent:Gn});var Zs=function(t,e){return Zs=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Zs(t,e)};function et(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Zs(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Ya(t,e,n,r){function o(s){return s instanceof n?s:new n(function(i){i(s)})}return new(n||(n=Promise))(function(s,i){function a(p){try{c(r.next(p))}catch(m){i(m)}}function l(p){try{c(r.throw(p))}catch(m){i(m)}}function c(p){p.done?s(p.value):o(p.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function Ur(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,o,s,i=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return i.next=a(0),i.throw=a(1),i.return=a(2),typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(c){return function(p){return l([c,p])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;i&&(i=0,c[0]&&(n=0)),n;)try{if(r=1,o&&(s=c[0]&2?o.return:c[0]?o.throw||((s=o.return)&&s.call(o),0):o.next)&&!(s=s.call(o,c[1])).done)return s;switch(o=0,s&&(c=[c[0]&2,s.value]),c[0]){case 0:case 1:s=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,o=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!s||c[1]>s[0]&&c[1]<s[3])){n.label=c[1];break}if(c[0]===6&&n.label<s[1]){n.label=s[1],s=c;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(c);break}s[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(p){c=[6,p],o=0}finally{r=s=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ut(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function fn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,s=[],i;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)s.push(o.value)}catch(a){i={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}return s}function hn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,s;r<o;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))}function Ft(t){return this instanceof Ft?(this.v=t,this):new Ft(t)}function qa(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,s=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),o[Symbol.asyncIterator]=function(){return this},o;function i(f){return function(h){return Promise.resolve(h).then(f,m)}}function a(f,h){r[f]&&(o[f]=function(g){return new Promise(function(T,S){s.push([f,g,T,S])>1||l(f,g)})},h&&(o[f]=h(o[f])))}function l(f,h){try{c(r[f](h))}catch(g){x(s[0][3],g)}}function c(f){f.value instanceof Ft?Promise.resolve(f.value.v).then(p,m):x(s[0][2],f)}function p(f){l("next",f)}function m(f){l("throw",f)}function x(f,h){f(h),s.shift(),s.length&&l(s[0][0],s[0][1])}}function Ja(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ut=="function"?ut(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(i){return new Promise(function(a,l){i=t[s](i),o(a,l,i.done,i.value)})}}function o(s,i,a,l){Promise.resolve(l).then(function(c){s({value:c,done:a})},i)}}function G(t){return typeof t=="function"}function mn(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var Gr=mn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
1
+ var Lu=Object.defineProperty;var _i=(t,e)=>{for(var n in e)Lu(t,n,{get:e[n],enumerable:!0})};var Er="ag-ui-chat",wi="ag-ui-submit",Ai="ag-ui-toggle",Ye={USER:"user",ASSISTANT:"assistant"},Mn="x-destructive",ki="x-confirm",Ce="x-summary",Ln="x-navigates",Ii=10,ce={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Fe={UPLOADING:"uploading",READY:"ready",ERROR:"error"},Ci=10*1024*1024,$e={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Pu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function La(t,e){let n=[];return{text:t.replace(Pu,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Du(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&typeof e.prompt=="string"}function Ni(t){return Array.isArray(t)?t.filter(Du):[]}var Pn=class{#t=new Map;register(e){this.#t.set(e.name,e)}has(e){return this.#t.has(e)}get(e){let n=this.#t.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#t.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Ri(t){return t[Mn]===!0}function Oi(t){return t[Ln]===!0}function Tr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Uu=Tr(HTMLInputElement.prototype,"value"),Gu=Tr(HTMLTextAreaElement.prototype,"value"),Hu=Tr(HTMLSelectElement.prototype,"value"),Fu=Tr(HTMLInputElement.prototype,"checked");function wt(t,e){t instanceof HTMLTextAreaElement?Gu.call(t,e):t instanceof HTMLSelectElement?Hu.call(t,e):Uu.call(t,e)}function Dn(t,e){Fu.call(t,e)}var Pa="#4f46e5";function Sr(t){return new Promise(e=>{setTimeout(e,t)})}async function Mi(t,e,n={}){let r=n.charDelayMs??35;wt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)wt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Sr(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Li(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Pa}`,t.style.outlineOffset="2px",await Sr(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function at(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function Pi(t,e={}){let n=e.flashMs??200;t.focus();let r=t.style.boxShadow;t.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await Sr(n),t.style.boxShadow=r}var Da="0 0 0 3px rgba(79, 70, 229, 0.4)";function Ua(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Di(t){return t<=0||Ua()?Promise.resolve():Sr(t)}async function Ui(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=Da,await Di(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function $u(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function Gi(t,e,n={}){let r=$u(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${Pa}`,t.style.outlineOffset="2px",await Di(o),wt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function Hi(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=Da,await Di(r),Dn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var Fi={SCROLL:"scroll",DRAG:"drag"};function $i(t,e){let n=[];return t.has(Fi.SCROLL)&&n.push(zu(e)),t.has(Fi.DRAG)&&n.push(Bu(e)),n}function zu(t){return{name:"scroll_to",description:"Scroll a target into view. `target` is `top`, `bottom`, or a CSS selector / page-map element id. Read-only: it changes nothing on the page.",parameters:{type:"object",properties:{target:{type:"string"}},required:["target"],[Ce]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return at(r),{scrolled:!0,target:n}}}}function Bu(t){return{name:"drag_and_drop",description:"Drag the `from` element onto the `to` element (CSS selectors or page-map element ids), firing the page's native drag-and-drop. Use for reordering sortable lists. The page decides what the drop commits.",parameters:{type:"object",properties:{from:{type:"string"},to:{type:"string"}},required:["from","to"],[Ce]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return ju(o,i),{dragged:!0,from:n,to:r}}}}function ju(t,e){let n=new DataTransfer;Un(t,"dragstart",n),Un(e,"dragenter",n),Un(e,"dragover",n),Un(e,"drop",n),Un(t,"dragend",n)}function Un(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function zi(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Bi(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary;typeof o=="string"&&typeof i=="string"&&(e[o]=i)}return e}var Ga=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Vu(t){let e=[];for(let n of t.matchAll(Ga)){let r=n[1];r!==void 0&&e.push(r)}return e}function Wu(t,e,n){let r={...n};return{path:e.replace(Ga,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function Xu(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function ji(t,e){return[{name:"list_routes",description:"List the routes the app can navigate to. Each route's `pathParams` names the dynamic segments to pass as `params` to `navigate_to_route`.",parameters:{type:"object",properties:{},required:[],[Ce]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Vu(n.path)}))},{name:"navigate_to_route",description:"Navigate to one of the app's routes by its id, filling any dynamic `:name` path segments (and extra query params) from `params`.",parameters:{type:"object",properties:{route_id:{type:"string"},params:{type:"object"}},required:["route_id"],[Ln]:!0,[Ce]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(p=>p.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=Wu(o.id,o.path,i),l=Xu(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}function Vi(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Ce]:`Read ${t.name}`},handler:()=>t.read()}],n=t.write;return n!==void 0&&e.push({name:`set_${t.name}`,description:`Update the "${t.name}" state.`,parameters:{...t.schema??{type:"object"},[Mn]:!0,[Ce]:`Update ${t.name}`},handler:r=>n(r)}),e}function Wi(t){let e=document.createElement("div");e.className="attachment-chips";for(let n of t)e.appendChild(Zu(n));return e}function Zu(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready";let n=document.createElement("span");n.className="attachment-chip-icon",n.textContent=Xi(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.textContent=t.name,r.title=t.name;let o=document.createElement("span");return o.className="attachment-chip-size",o.textContent=_r(t.size),e.append(n,r,o),e}function Xi(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function _r(t){if(t<1024)return`${t} B`;let e=["KB","MB","GB"],n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r+=1;return`${n<10?Math.round(n*10)/10:Math.round(n)} ${e[r]}`}var ge=[];for(let t=0;t<256;++t)ge.push((t+256).toString(16).slice(1));function Ha(t,e=0){return(ge[t[e+0]]+ge[t[e+1]]+ge[t[e+2]]+ge[t[e+3]]+"-"+ge[t[e+4]]+ge[t[e+5]]+"-"+ge[t[e+6]]+ge[t[e+7]]+"-"+ge[t[e+8]]+ge[t[e+9]]+"-"+ge[t[e+10]]+ge[t[e+11]]+ge[t[e+12]]+ge[t[e+13]]+ge[t[e+14]]+ge[t[e+15]]).toLowerCase()}var Zi,Ku=new Uint8Array(16);function Ki(){if(!Zi){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Zi=crypto.getRandomValues.bind(crypto)}return Zi(Ku)}var Yu=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Yi={randomUUID:Yu};function qu(t,e,n){if(Yi.randomUUID&&!e&&!t)return Yi.randomUUID();t=t||{};let r=t.random??t.rng?.()??Ki();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return Ha(r)}var gt=qu;var u={};_i(u,{BRAND:()=>Sd,DIRTY:()=>At,EMPTY_PATH:()=>td,INVALID:()=>O,NEVER:()=>ap,OK:()=>xe,ParseStatus:()=>ve,Schema:()=>U,ZodAny:()=>bt,ZodArray:()=>dt,ZodBigInt:()=>It,ZodBoolean:()=>Ct,ZodBranded:()=>Hn,ZodCatch:()=>Ft,ZodDate:()=>Nt,ZodDefault:()=>Ht,ZodDiscriminatedUnion:()=>kr,ZodEffects:()=>Pe,ZodEnum:()=>Ut,ZodError:()=>we,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Cr,ZodIntersection:()=>Lt,ZodIssueCode:()=>E,ZodLazy:()=>Pt,ZodLiteral:()=>Dt,ZodMap:()=>un,ZodNaN:()=>pn,ZodNativeEnum:()=>Gt,ZodNever:()=>ze,ZodNull:()=>Ot,ZodNullable:()=>Qe,ZodNumber:()=>kt,ZodObject:()=>Ae,ZodOptional:()=>Me,ZodParsedType:()=>k,ZodPipeline:()=>Fn,ZodPromise:()=>xt,ZodReadonly:()=>$t,ZodRecord:()=>Ir,ZodSchema:()=>U,ZodSet:()=>dn,ZodString:()=>yt,ZodSymbol:()=>ln,ZodTransformer:()=>Pe,ZodTuple:()=>Je,ZodType:()=>U,ZodUndefined:()=>Rt,ZodUnion:()=>Mt,ZodUnknown:()=>ut,ZodVoid:()=>cn,addIssueToContext:()=>w,any:()=>Od,array:()=>Dd,bigint:()=>kd,boolean:()=>Ya,coerce:()=>sp,custom:()=>Xa,date:()=>Id,datetimeRegex:()=>Va,defaultErrorMap:()=>lt,discriminatedUnion:()=>Fd,effect:()=>Jd,enum:()=>Kd,function:()=>Wd,getErrorMap:()=>on,getParsedType:()=>qe,instanceof:()=>wd,intersection:()=>$d,isAborted:()=>wr,isAsync:()=>sn,isDirty:()=>Ar,isValid:()=>vt,late:()=>_d,lazy:()=>Xd,literal:()=>Zd,makeIssue:()=>Gn,map:()=>jd,nan:()=>Ad,nativeEnum:()=>Yd,never:()=>Ld,null:()=>Rd,nullable:()=>ep,number:()=>Ka,object:()=>Ud,objectUtil:()=>qi,oboolean:()=>ip,onumber:()=>op,optional:()=>Qd,ostring:()=>rp,pipeline:()=>np,preprocess:()=>tp,promise:()=>qd,quotelessJson:()=>Ju,record:()=>Bd,set:()=>Vd,setErrorMap:()=>ed,strictObject:()=>Gd,string:()=>Za,symbol:()=>Cd,transformer:()=>Jd,tuple:()=>zd,undefined:()=>Nd,union:()=>Hd,unknown:()=>Md,util:()=>F,void:()=>Pd});var F;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(F||(F={}));var qi;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(qi||(qi={}));var k=F.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qe=t=>{switch(typeof t){case"undefined":return k.undefined;case"string":return k.string;case"number":return Number.isNaN(t)?k.nan:k.number;case"boolean":return k.boolean;case"function":return k.function;case"bigint":return k.bigint;case"symbol":return k.symbol;case"object":return Array.isArray(t)?k.array:t===null?k.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?k.promise:typeof Map<"u"&&t instanceof Map?k.map:typeof Set<"u"&&t instanceof Set?k.set:typeof Date<"u"&&t instanceof Date?k.date:k.object;default:return k.unknown}};var E=F.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"]),Ju=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),we=class t 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 n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,F.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};we.create=t=>new we(t);var Qu=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===k.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,F.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${F.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${F.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${F.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:F.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,F.assertNever(t)}return{message:n}},lt=Qu;var Fa=lt;function ed(t){Fa=t}function on(){return Fa}var Gn=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},td=[];function w(t,e){let n=on(),r=Gn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===lt?void 0:lt].filter(o=>!!o)});t.common.issues.push(r)}var ve=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return O;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return O;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},O=Object.freeze({status:"aborted"}),At=t=>({status:"dirty",value:t}),xe=t=>({status:"valid",value:t}),wr=t=>t.status==="aborted",Ar=t=>t.status==="dirty",vt=t=>t.status==="valid",sn=t=>typeof Promise<"u"&&t instanceof Promise;var I;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(I||(I={}));var Le=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}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}},$a=(t,e)=>{if(vt(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new we(t.common.issues);return this._error=n,this._error}}};function L(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var U=class{get description(){return this._def.description}_getType(e){return qe(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:qe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ve,ctx:{common:e.parent.common,data:e.data,parsedType:qe(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(sn(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qe(e)},o=this._parseSync({data:e,path:r.path,parent:r});return $a(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qe(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return vt(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>vt(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qe(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(sn(o)?o:Promise.resolve(o));return $a(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Pe({schema:this,typeName:M.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Me.create(this,this._def)}nullable(){return Qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return xt.create(this,this._def)}or(e){return Mt.create([this,e],this._def)}and(e){return Lt.create(this,e,this._def)}transform(e){return new Pe({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ht({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Hn({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Ft({...L(this._def),innerType:this,catchValue:n,typeName:M.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Fn.create(this,e)}readonly(){return $t.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nd=/^c[^\s-]{8,}$/i,rd=/^[0-9a-z]+$/,od=/^[0-9A-HJKMNP-TV-Z]{26}$/i,id=/^[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,sd=/^[a-z0-9_-]{21}$/i,ad=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ld=/^[-+]?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)?)??$/,cd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ud="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ji,dd=/^(?:(?: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])$/,pd=/^(?:(?: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])$/,fd=/^(([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]))$/,hd=/^(([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])$/,md=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,gd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ba="((\\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])))",vd=new RegExp(`^${Ba}$`);function ja(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function yd(t){return new RegExp(`^${ja(t)}$`)}function Va(t){let e=`${Ba}T${ja(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function bd(t,e){return!!((e==="v4"||!e)&&dd.test(t)||(e==="v6"||!e)&&fd.test(t))}function xd(t,e){if(!ad.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Ed(t,e){return!!((e==="v4"||!e)&&pd.test(t)||(e==="v6"||!e)&&hd.test(t))}var yt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let i=this._getOrReturnCtx(e);return w(i,{code:E.invalid_type,expected:k.string,received:i.parsedType}),O}let r=new ve,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?w(o,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&w(o,{code:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")cd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"email",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Ji||(Ji=new RegExp(ud,"u")),Ji.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"emoji",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")id.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"uuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")sd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"nanoid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")nd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")rd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cuid2",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")od.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"ulid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),w(o,{validation:"url",code:E.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"regex",code:E.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Va(i).test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?vd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?yd(i).test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{code:E.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?ld.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"duration",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?bd(e.data,i.version)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"ip",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?xd(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"jwt",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Ed(e.data,i.version)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"cidr",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?md.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?gd.test(e.data)||(o=this._getOrReturnCtx(e,o),w(o,{validation:"base64url",code:E.invalid_string,message:i.message}),r.dirty()):F.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:E.invalid_string,...I.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...I.errToObj(e)})}url(e){return this._addCheck({kind:"url",...I.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...I.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...I.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...I.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...I.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...I.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...I.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...I.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...I.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...I.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...I.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...I.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,...I.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,...I.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...I.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...I.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...I.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...I.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...I.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...I.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...I.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...I.errToObj(n)})}nonempty(e){return this.min(1,I.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};yt.create=t=>new yt({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...L(t)});function Td(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}var kt=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==k.number){let i=this._getOrReturnCtx(e);return w(i,{code:E.invalid_type,expected:k.number,received:i.parsedType}),O}let r,o=new ve;for(let i of this._def.checks)i.kind==="int"?F.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Td(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_finite,message:i.message}),o.dirty()):F.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:I.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:I.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&F.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};kt.create=t=>new kt({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...L(t)});var It=class t extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==k.bigint)return this._getInvalidInput(e);let r,o=new ve;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):F.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return w(n,{code:E.invalid_type,expected:k.bigint,received:n.parsedType}),O}gte(e,n){return this.setLimit("min",e,!0,I.toString(n))}gt(e,n){return this.setLimit("min",e,!1,I.toString(n))}lte(e,n){return this.setLimit("max",e,!0,I.toString(n))}lt(e,n){return this.setLimit("max",e,!1,I.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:I.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};It.create=t=>new It({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...L(t)});var Ct=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.boolean,received:r.parsedType}),O}return xe(e.data)}};Ct.create=t=>new Ct({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...L(t)});var Nt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let i=this._getOrReturnCtx(e);return w(i,{code:E.invalid_type,expected:k.date,received:i.parsedType}),O}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return w(i,{code:E.invalid_date}),O}let r=new ve,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),w(o,{code:E.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):F.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:I.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:I.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Nt.create=t=>new Nt({checks:[],coerce:t?.coerce||!1,typeName:M.ZodDate,...L(t)});var ln=class extends U{_parse(e){if(this._getType(e)!==k.symbol){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.symbol,received:r.parsedType}),O}return xe(e.data)}};ln.create=t=>new ln({typeName:M.ZodSymbol,...L(t)});var Rt=class extends U{_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.undefined,received:r.parsedType}),O}return xe(e.data)}};Rt.create=t=>new Rt({typeName:M.ZodUndefined,...L(t)});var Ot=class extends U{_parse(e){if(this._getType(e)!==k.null){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.null,received:r.parsedType}),O}return xe(e.data)}};Ot.create=t=>new Ot({typeName:M.ZodNull,...L(t)});var bt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return xe(e.data)}};bt.create=t=>new bt({typeName:M.ZodAny,...L(t)});var ut=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return xe(e.data)}};ut.create=t=>new ut({typeName:M.ZodUnknown,...L(t)});var ze=class extends U{_parse(e){let n=this._getOrReturnCtx(e);return w(n,{code:E.invalid_type,expected:k.never,received:n.parsedType}),O}};ze.create=t=>new ze({typeName:M.ZodNever,...L(t)});var cn=class extends U{_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.void,received:r.parsedType}),O}return xe(e.data)}};cn.create=t=>new cn({typeName:M.ZodVoid,...L(t)});var dt=class t extends U{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==k.array)return w(n,{code:E.invalid_type,expected:k.array,received:n.parsedType}),O;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(w(n,{code:s?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(w(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(w(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Le(n,s,n.path,a)))).then(s=>ve.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Le(n,s,n.path,a)));return ve.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:I.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:I.toString(n)}})}nonempty(e){return this.min(1,e)}};dt.create=(t,e)=>new dt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:M.ZodArray,...L(e)});function an(t){if(t instanceof Ae){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Me.create(an(r))}return new Ae({...t._def,shape:()=>e})}else return t instanceof dt?new dt({...t._def,type:an(t.element)}):t instanceof Me?Me.create(an(t.unwrap())):t instanceof Qe?Qe.create(an(t.unwrap())):t instanceof Je?Je.create(t.items.map(e=>an(e))):t}var Ae=class t extends U{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(),n=F.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==k.object){let c=this._getOrReturnCtx(e);return w(c,{code:E.invalid_type,expected:k.object,received:c.parsedType}),O}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ze&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let p=i[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new Le(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof ze){let c=this._def.unknownKeys;if(c==="passthrough")for(let p of a)l.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(c==="strict")a.length>0&&(w(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let p of a){let m=o.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new Le(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let p of l){let m=await p.key,x=await p.value;c.push({key:m,value:x,alwaysSet:p.alwaysSet})}return c}).then(c=>ve.mergeObjectSync(r,c)):ve.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return I.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:M.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of F.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of F.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return an(this)}partial(e){let n={};for(let r of F.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of F.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Me;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Wa(F.objectKeys(this.shape))}};Ae.create=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strip",catchall:ze.create(),typeName:M.ZodObject,...L(e)});Ae.strictCreate=(t,e)=>new Ae({shape:()=>t,unknownKeys:"strict",catchall:ze.create(),typeName:M.ZodObject,...L(e)});Ae.lazycreate=(t,e)=>new Ae({shape:t,unknownKeys:"strip",catchall:ze.create(),typeName:M.ZodObject,...L(e)});var Mt=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new we(a.ctx.common.issues));return w(n,{code:E.invalid_union,unionErrors:s}),O}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},p=l._parseSync({data:n.data,path:n.path,parent:c});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new we(l));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Mt.create=(t,e)=>new Mt({options:t,typeName:M.ZodUnion,...L(e)});var ct=t=>t instanceof Pt?ct(t.schema):t instanceof Pe?ct(t.innerType()):t instanceof Dt?[t.value]:t instanceof Ut?t.options:t instanceof Gt?F.objectValues(t.enum):t instanceof Ht?ct(t._def.innerType):t instanceof Rt?[void 0]:t instanceof Ot?[null]:t instanceof Me?[void 0,...ct(t.unwrap())]:t instanceof Qe?[null,...ct(t.unwrap())]:t instanceof Hn||t instanceof $t?ct(t.unwrap()):t instanceof Ft?ct(t._def.innerType):[],kr=class t extends U{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.object)return w(n,{code:E.invalid_type,expected:k.object,received:n.parsedType}),O;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(w(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),O)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=ct(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...L(r)})}};function Qi(t,e){let n=qe(t),r=qe(e);if(t===e)return{valid:!0,data:t};if(n===k.object&&r===k.object){let o=F.objectKeys(e),i=F.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=Qi(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===k.array&&r===k.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=Qi(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Lt=class extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(wr(i)||wr(s))return O;let a=Qi(i.value,s.value);return a.valid?((Ar(i)||Ar(s))&&n.dirty(),{status:n.value,value:a.data}):(w(r,{code:E.invalid_intersection_types}),O)};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(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Lt.create=(t,e,n)=>new Lt({left:t,right:e,typeName:M.ZodIntersection,...L(n)});var Je=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.array)return w(r,{code:E.invalid_type,expected:k.array,received:r.parsedType}),O;if(r.data.length<this._def.items.length)return w(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),O;!this._def.rest&&r.data.length>this._def.items.length&&(w(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Le(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>ve.mergeArray(n,s)):ve.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Je.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Je({items:t,typeName:M.ZodTuple,rest:null,...L(e)})};var Ir=class t extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.object)return w(r,{code:E.invalid_type,expected:k.object,received:r.parsedType}),O;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new Le(r,a,r.path,a)),value:s._parse(new Le(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ve.mergeObjectAsync(n,o):ve.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof U?new t({keyType:e,valueType:n,typeName:M.ZodRecord,...L(r)}):new t({keyType:yt.create(),valueType:e,typeName:M.ZodRecord,...L(n)})}},un=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.map)return w(r,{code:E.invalid_type,expected:k.map,received:r.parsedType}),O;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Le(r,a,r.path,[c,"key"])),value:i._parse(new Le(r,l,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let c=await l.key,p=await l.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,p=l.value;if(c.status==="aborted"||p.status==="aborted")return O;(c.status==="dirty"||p.status==="dirty")&&n.dirty(),a.set(c.value,p.value)}return{status:n.value,value:a}}}};un.create=(t,e,n)=>new un({valueType:e,keyType:t,typeName:M.ZodMap,...L(n)});var dn=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return w(r,{code:E.invalid_type,expected:k.set,received:r.parsedType}),O;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(w(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(w(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let p of l){if(p.status==="aborted")return O;p.status==="dirty"&&n.dirty(),c.add(p.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new Le(r,l,r.path,c)));return r.common.async?Promise.all(a).then(l=>s(l)):s(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:I.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:I.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};dn.create=(t,e)=>new dn({valueType:t,minSize:null,maxSize:null,typeName:M.ZodSet,...L(e)});var Cr=class t extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.function)return w(n,{code:E.invalid_type,expected:k.function,received:n.parsedType}),O;function r(a,l){return Gn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,on(),lt].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function o(a,l){return Gn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,on(),lt].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof xt){let a=this;return xe(async function(...l){let c=new we([]),p=await a._def.args.parseAsync(l,i).catch(f=>{throw c.addIssue(r(l,f)),c}),m=await Reflect.apply(s,this,p);return await a._def.returns._def.type.parseAsync(m,i).catch(f=>{throw c.addIssue(o(m,f)),c})})}else{let a=this;return xe(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new we([r(l,c.error)]);let p=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(p,i);if(!m.success)throw new we([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Je.create(e).rest(ut.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||Je.create([]).rest(ut.create()),returns:n||ut.create(),typeName:M.ZodFunction,...L(r)})}},Pt=class extends U{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Pt.create=(t,e)=>new Pt({getter:t,typeName:M.ZodLazy,...L(e)});var Dt=class extends U{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return w(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),O}return{status:"valid",value:e.data}}get value(){return this._def.value}};Dt.create=(t,e)=>new Dt({value:t,typeName:M.ZodLiteral,...L(e)});function Wa(t,e){return new Ut({values:t,typeName:M.ZodEnum,...L(e)})}var Ut=class t extends U{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return w(n,{expected:F.joinValues(r),received:n.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return w(n,{received:n.data,code:E.invalid_enum_value,options:r}),O}return xe(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Ut.create=Wa;var Gt=class extends U{_parse(e){let n=F.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.number){let o=F.objectValues(n);return w(r,{expected:F.joinValues(o),received:r.parsedType,code:E.invalid_type}),O}if(this._cache||(this._cache=new Set(F.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=F.objectValues(n);return w(r,{received:r.data,code:E.invalid_enum_value,options:o}),O}return xe(e.data)}get enum(){return this._def.values}};Gt.create=(t,e)=>new Gt({values:t,typeName:M.ZodNativeEnum,...L(e)});var xt=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.promise&&n.common.async===!1)return w(n,{code:E.invalid_type,expected:k.promise,received:n.parsedType}),O;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return xe(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};xt.create=(t,e)=>new xt({type:t,typeName:M.ZodPromise,...L(e)});var Pe=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===M.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{w(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return O;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?O:l.status==="dirty"?At(l.value):n.value==="dirty"?At(l.value):l});{if(n.value==="aborted")return O;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?O:a.status==="dirty"?At(a.value):n.value==="dirty"?At(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),s(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?O:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!vt(s))return O;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>vt(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):O);F.assertNever(o)}};Pe.create=(t,e,n)=>new Pe({schema:t,typeName:M.ZodEffects,effect:e,...L(n)});Pe.createWithPreprocess=(t,e,n)=>new Pe({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...L(n)});var Me=class extends U{_parse(e){return this._getType(e)===k.undefined?xe(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Me.create=(t,e)=>new Me({innerType:t,typeName:M.ZodOptional,...L(e)});var Qe=class extends U{_parse(e){return this._getType(e)===k.null?xe(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Qe.create=(t,e)=>new Qe({innerType:t,typeName:M.ZodNullable,...L(e)});var Ht=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===k.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ht.create=(t,e)=>new Ht({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...L(e)});var Ft=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return sn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new we(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:M.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...L(e)});var pn=class extends U{_parse(e){if(this._getType(e)!==k.nan){let r=this._getOrReturnCtx(e);return w(r,{code:E.invalid_type,expected:k.nan,received:r.parsedType}),O}return{status:"valid",value:e.data}}};pn.create=t=>new pn({typeName:M.ZodNaN,...L(t)});var Sd=Symbol("zod_brand"),Hn=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Fn=class t extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?O:i.status==="dirty"?(n.dirty(),At(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:M.ZodPipeline})}},$t=class extends U{_parse(e){let n=this._def.innerType._parse(e),r=o=>(vt(o)&&(o.value=Object.freeze(o.value)),o);return sn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};$t.create=(t,e)=>new $t({innerType:t,typeName:M.ZodReadonly,...L(e)});function za(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Xa(t,e={},n){return t?bt.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=za(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=za(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):bt.create()}var _d={object:Ae.lazycreate},M;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(M||(M={}));var wd=(t,e={message:`Input not instance of ${t.name}`})=>Xa(n=>n instanceof t,e),Za=yt.create,Ka=kt.create,Ad=pn.create,kd=It.create,Ya=Ct.create,Id=Nt.create,Cd=ln.create,Nd=Rt.create,Rd=Ot.create,Od=bt.create,Md=ut.create,Ld=ze.create,Pd=cn.create,Dd=dt.create,Ud=Ae.create,Gd=Ae.strictCreate,Hd=Mt.create,Fd=kr.create,$d=Lt.create,zd=Je.create,Bd=Ir.create,jd=un.create,Vd=dn.create,Wd=Cr.create,Xd=Pt.create,Zd=Dt.create,Kd=Ut.create,Yd=Gt.create,qd=xt.create,Jd=Pe.create,Qd=Me.create,ep=Qe.create,tp=Pe.createWithPreprocess,np=Fn.create,rp=()=>Za().optional(),op=()=>Ka().optional(),ip=()=>Ya().optional(),sp={string:(t=>yt.create({...t,coerce:!0})),number:(t=>kt.create({...t,coerce:!0})),boolean:(t=>Ct.create({...t,coerce:!0})),bigint:(t=>It.create({...t,coerce:!0})),date:(t=>Nt.create({...t,coerce:!0}))};var ap=O;var lp=u.object({name:u.string(),arguments:u.string()}),cp=u.object({id:u.string(),type:u.literal("function"),function:lp,encryptedValue:u.string().optional()}),Nr=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),up=u.object({type:u.literal("text"),text:u.string()}),dp=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),pp=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),Rr=u.discriminatedUnion("type",[dp,pp]),fp=u.object({type:u.literal("image"),source:Rr,metadata:u.unknown().optional()}),hp=u.object({type:u.literal("audio"),source:Rr,metadata:u.unknown().optional()}),mp=u.object({type:u.literal("video"),source:Rr,metadata:u.unknown().optional()}),gp=u.object({type:u.literal("document"),source:Rr,metadata:u.unknown().optional()});var qa=u.object({type:u.literal("binary"),mimeType:u.string(),id:u.string().optional(),url:u.string().optional(),data:u.string().optional(),filename:u.string().optional()}),Ja=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:u.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},Dv=qa.superRefine((t,e)=>{Ja(t,e)}),vp=u.discriminatedUnion("type",[up,fp,hp,mp,gp,qa]),yp=vp.superRefine((t,e)=>{t.type==="binary"&&Ja(t,e)}),bp=Nr.extend({role:u.literal("developer"),content:u.string()}),xp=Nr.extend({role:u.literal("system"),content:u.string()}),Ep=Nr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(cp).optional()}),Tp=Nr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(yp)])}),Sp=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),_p=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),wp=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),Qa=u.discriminatedUnion("role",[bp,xp,Ep,Tp,Sp,_p,wp]),Uv=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),Ap=u.object({description:u.string(),value:u.string()}),el=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),kp=u.object({id:u.string(),reason:u.string(),message:u.string().optional(),toolCallId:u.string().optional(),responseSchema:u.record(u.any()).optional(),expiresAt:u.string().optional(),metadata:u.record(u.any()).optional()}),Ip=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Cp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(Qa),tools:u.array(el),context:u.array(Ap),forwardedProps:u.any(),resume:u.array(Ip).optional()}),Np=u.any(),q=class extends Error{constructor(t){super(t)}},es=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Rp=u.object({name:u.string(),description:u.string().optional()}),Op=u.object({name:u.string().optional(),type:u.string().optional(),description:u.string().optional(),version:u.string().optional(),provider:u.string().optional(),documentationUrl:u.string().optional(),metadata:u.record(u.unknown()).optional()}),Mp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),Lp=u.object({supported:u.boolean().optional(),items:u.array(el).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Pp=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),Dp=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),Up=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(Rp).optional()}),Gp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),Hp=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),Fp=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),$p=u.object({input:Hp.optional(),output:Fp.optional()}),zp=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),Bp=u.object({supported:u.boolean().optional(),approvals:u.boolean().optional(),interventions:u.boolean().optional(),feedback:u.boolean().optional(),interrupts:u.boolean().optional(),approveWithEdits:u.boolean().optional()}),Gv=u.object({identity:Op.optional(),transport:Mp.optional(),tools:Lp.optional(),output:Pp.optional(),state:Dp.optional(),multiAgent:Up.optional(),reasoning:Gp.optional(),multimodal:$p.optional(),execution:zp.optional(),humanInTheLoop:Bp.optional(),custom:u.record(u.unknown()).optional()}),tl=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user")]),v=(function(t){return t.TEXT_MESSAGE_START="TEXT_MESSAGE_START",t.TEXT_MESSAGE_CONTENT="TEXT_MESSAGE_CONTENT",t.TEXT_MESSAGE_END="TEXT_MESSAGE_END",t.TEXT_MESSAGE_CHUNK="TEXT_MESSAGE_CHUNK",t.TOOL_CALL_START="TOOL_CALL_START",t.TOOL_CALL_ARGS="TOOL_CALL_ARGS",t.TOOL_CALL_END="TOOL_CALL_END",t.TOOL_CALL_CHUNK="TOOL_CALL_CHUNK",t.TOOL_CALL_RESULT="TOOL_CALL_RESULT",t.THINKING_START="THINKING_START",t.THINKING_END="THINKING_END",t.THINKING_TEXT_MESSAGE_START="THINKING_TEXT_MESSAGE_START",t.THINKING_TEXT_MESSAGE_CONTENT="THINKING_TEXT_MESSAGE_CONTENT",t.THINKING_TEXT_MESSAGE_END="THINKING_TEXT_MESSAGE_END",t.STATE_SNAPSHOT="STATE_SNAPSHOT",t.STATE_DELTA="STATE_DELTA",t.MESSAGES_SNAPSHOT="MESSAGES_SNAPSHOT",t.ACTIVITY_SNAPSHOT="ACTIVITY_SNAPSHOT",t.ACTIVITY_DELTA="ACTIVITY_DELTA",t.RAW="RAW",t.CUSTOM="CUSTOM",t.RUN_STARTED="RUN_STARTED",t.RUN_FINISHED="RUN_FINISHED",t.RUN_ERROR="RUN_ERROR",t.STEP_STARTED="STEP_STARTED",t.STEP_FINISHED="STEP_FINISHED",t.REASONING_START="REASONING_START",t.REASONING_MESSAGE_START="REASONING_MESSAGE_START",t.REASONING_MESSAGE_CONTENT="REASONING_MESSAGE_CONTENT",t.REASONING_MESSAGE_END="REASONING_MESSAGE_END",t.REASONING_MESSAGE_CHUNK="REASONING_MESSAGE_CHUNK",t.REASONING_END="REASONING_END",t.REASONING_ENCRYPTED_VALUE="REASONING_ENCRYPTED_VALUE",t})({}),j=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),jp=j.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:tl.default("assistant"),name:u.string().optional()}),nl=j.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Vp=j.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),Wp=j.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:tl.optional(),delta:u.string().optional(),name:u.string().optional()}),Xp=j.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),Zp=nl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Kp=j.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),Yp=j.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),qp=j.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),Jp=j.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),Qp=j.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),ef=j.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),tf=j.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),nf=j.extend({type:u.literal(v.THINKING_END)}),rf=j.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:Np}),of=j.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),sf=j.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(Qa)}),af=j.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),lf=j.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),cf=j.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),uf=j.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),df=j.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Cp.optional()}),pf=u.object({type:u.literal("success")}).strict(),ff=u.object({type:u.literal("interrupt"),interrupts:u.array(kp).min(1)}).strict(),hf=u.discriminatedUnion("type",[pf,ff]),mf=j.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:hf.nullable().optional().transform(t=>t??void 0)}),gf=j.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),vf=j.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),yf=j.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),bf=u.union([u.literal("tool-call"),u.literal("message")]),xf=j.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),Ef=j.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),Tf=j.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Sf=j.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),_f=j.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),wf=j.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),Af=j.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:bf,entityId:u.string(),encryptedValue:u.string()}),Or=u.discriminatedUnion("type",[jp,nl,Vp,Wp,tf,nf,Xp,Zp,Kp,Yp,qp,Jp,ef,Qp,rf,of,sf,af,lf,cf,uf,df,mf,gf,vf,yf,xf,Ef,Tf,Sf,_f,wf,Af]);var ts={};_i(ts,{JsonPatchError:()=>ne,_areEquals:()=>Bn,applyOperation:()=>zt,applyPatch:()=>Hr,applyReducer:()=>Rf,deepClone:()=>Cf,getValueByPointer:()=>Ur,validate:()=>ol,validator:()=>Gr});var kf=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)o.hasOwnProperty(i)&&(r[i]=o[i])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),If=Object.prototype.hasOwnProperty;function Lr(t,e){return If.call(t,e)}function Pr(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var o in t)Lr(t,o)&&r.push(o);return r}function ye(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Dr(t){for(var e=0,n=t.length,r;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function et(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function $n(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Mr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Mr(t[e]))return!0}else if(typeof t=="object"){for(var r=Pr(t),o=r.length,i=0;i<o;i++)if(Mr(t[r[i]]))return!0}}return!1}function rl(t,e){var n=[t];for(var r in e){var o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
2
+ `)}var zn=(function(t){kf(e,t);function e(n,r,o,i,s){var a=this.constructor,l=t.call(this,rl(n,{name:r,index:o,operation:i,tree:s}))||this;return l.name=r,l.index=o,l.operation=i,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=rl(n,{name:r,index:o,operation:i,tree:s}),l}return e})(Error);var ne=zn,Cf=ye,fn={add:function(t,e,n){return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){var r=Ur(n,this.path);r&&(r=ye(r));var o=zt(n,{op:"remove",path:this.from}).removed;return zt(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Ur(n,this.from);return zt(n,{op:"add",path:this.path,value:ye(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Bn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},Nf={add:function(t,e,n){return Dr(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){var r=t.splice(e,1);return{newDocument:n,removed:r[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:fn.move,copy:fn.copy,test:fn.test,_get:fn._get};function Ur(t,e){if(e=="")return t;var n={op:"_get",path:e};return zt(t,n),n.value}function zt(t,e,n,r,o,i){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),i===void 0&&(i=0),n&&(typeof n=="function"?n(e,0,t,e.path):Gr(e,0)),e.path===""){var s={newDocument:t};if(e.op==="add")return s.newDocument=e.value,s;if(e.op==="replace")return s.newDocument=e.value,s.removed=t,s;if(e.op==="move"||e.op==="copy")return s.newDocument=Ur(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Bn(t,e.value),s.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new ne("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=ye(t));var a=e.path||"",l=a.split("/"),c=t,p=1,m=l.length,x=void 0,f=void 0,h=void 0;for(typeof n=="function"?h=n:h=Gr;;){if(f=l[p],f&&f.indexOf("~")!=-1&&(f=$n(f)),o&&(f=="__proto__"||f=="prototype"&&p>0&&l[p-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&x===void 0&&(c[f]===void 0?x=l.slice(0,p).join("/"):p==m-1&&(x=e.path),x!==void 0&&h(e,0,t,x)),p++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Dr(f))throw new ne("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Dr(f)&&(f=~~f)}if(p>=m){if(n&&e.op==="add"&&f>c.length)throw new ne("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);var s=Nf[e.op].call(e,c,f,t);if(s.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}}else if(p>=m){var s=fn[e.op].call(e,c,f,t);if(s.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}if(c=c[f],n&&p<m&&(!c||typeof c!="object"))throw new ne("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Hr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ye(t));for(var i=new Array(e.length),s=0,a=e.length;s<a;s++)i[s]=zt(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function Rf(t,e,n){var r=zt(t,e);if(r.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Gr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new ne("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(fn[t.op]){if(typeof t.path!="string")throw new ne("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ne('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new ne("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new ne("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Mr(t.value))throw new ne("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new ne("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new ne("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var s={op:"_get",path:t.from,value:void 0},a=ol([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new ne("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new ne("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function ol(t,e,n){try{if(!Array.isArray(t))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Hr(ye(e),ye(t),n||!0);else{n=n||Gr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof ne)return o;throw o}}function Bn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,i,s;if(n&&r){if(i=t.length,i!=e.length)return!1;for(o=i;o--!==0;)if(!Bn(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(i=a.length,i!==Object.keys(e).length)return!1;for(o=i;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=i;o--!==0;)if(s=a[o],!Bn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var is={};_i(is,{compare:()=>Hf,generate:()=>ns,observe:()=>Gf,unobserve:()=>Uf});var rs=new WeakMap,Of=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Mf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function Lf(t){return rs.get(t)}function Pf(t,e){return t.observers.get(e)}function Df(t,e){t.observers.delete(e.callback)}function Uf(t,e){e.unobserve()}function Gf(t,e){var n=[],r,o=Lf(t);if(!o)o=new Of(t),rs.set(t,o);else{var i=Pf(o,e);r=i&&i.observer}if(r)return r;if(r={},o.value=ye(t),e){r.callback=e,r.next=null;var s=function(){ns(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=t,r.unobserve=function(){ns(r),clearTimeout(r.next),Df(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new Mf(e,r)),r}function ns(t,e){e===void 0&&(e=!1);var n=rs.get(t.object);os(n.value,t.object,t.patches,"",e),t.patches.length&&Hr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function os(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=Pr(e),s=Pr(t),a=!1,l=!1,c=s.length-1;c>=0;c--){var p=s[c],m=t[p];if(Lr(e,p)&&!(e[p]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var x=e[p];typeof m=="object"&&m!=null&&typeof x=="object"&&x!=null&&Array.isArray(m)===Array.isArray(x)?os(m,x,n,r+"/"+et(p),o):m!==x&&(a=!0,o&&n.push({op:"test",path:r+"/"+et(p),value:ye(m)}),n.push({op:"replace",path:r+"/"+et(p),value:ye(x)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+et(p),value:ye(m)}),n.push({op:"remove",path:r+"/"+et(p)}),l=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&i.length==s.length))for(var c=0;c<i.length;c++){var p=i[c];!Lr(t,p)&&e[p]!==void 0&&n.push({op:"add",path:r+"/"+et(p),value:ye(e[p])})}}}function Hf(t,e,n){n===void 0&&(n=!1);var r=[];return os(t,e,r,"",n),r}var Fr=Object.assign({},ts,is,{JsonPatchError:zn,deepClone:ye,escapePathComponent:et,unescapePathComponent:$n});var ss=function(t,e){return ss=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},ss(t,e)};function tt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ss(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function il(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(p){try{c(r.next(p))}catch(m){s(m)}}function l(p){try{c(r.throw(p))}catch(m){s(m)}}function c(p){p.done?i(p.value):o(p.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function $r(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,o,i,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(p){return l([c,p])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(n=0)),n;)try{if(r=1,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,o=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){n.label=c[1];break}if(c[0]===6&&n.label<i[1]){n.label=i[1],i=c;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(c);break}i[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(p){c=[6,p],o=0}finally{r=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function pt(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function hn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return i}function mn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}function Bt(t){return this instanceof Bt?(this.v=t,this):new Bt(t)}function sl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),o[Symbol.asyncIterator]=function(){return this},o;function s(f){return function(h){return Promise.resolve(h).then(f,m)}}function a(f,h){r[f]&&(o[f]=function(g){return new Promise(function(T,_){i.push([f,g,T,_])>1||l(f,g)})},h&&(o[f]=h(o[f])))}function l(f,h){try{c(r[f](h))}catch(g){x(i[0][3],g)}}function c(f){f.value instanceof Bt?Promise.resolve(f.value.v).then(p,m):x(i[0][2],f)}function p(f){l("next",f)}function m(f){l("throw",f)}function x(f,h){f(h),i.shift(),i.length&&l(i[0][0],i[0][1])}}function al(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof pt=="function"?pt(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(s){return new Promise(function(a,l){s=t[i](s),o(a,l,s.done,s.value)})}}function o(i,s,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},s)}}function G(t){return typeof t=="function"}function gn(t){var e=function(r){Error.call(r),r.stack=new Error().stack},n=t(e);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}var zr=gn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
3
3
  `+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
4
- `):"",this.name="UnsubscriptionError",this.errors=n}});function $n(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var gn=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,s;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var a=ut(i),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else i.remove(this);var p=this.initialTeardown;if(G(p))try{p()}catch(g){s=g instanceof Gr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var x=ut(m),f=x.next();!f.done;f=x.next()){var h=f.value;try{Qa(h)}catch(g){s=s??[],g instanceof Gr?s=hn(hn([],fn(s)),fn(g.errors)):s.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=x.return)&&o.call(x)}finally{if(r)throw r.error}}}if(s)throw new Gr(s)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Qa(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&$n(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&$n(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Ks=gn.EMPTY;function Hr(t){return t instanceof gn||t&&"closed"in t&&G(t.remove)&&G(t.add)&&G(t.unsubscribe)}function Qa(t){G(t)?t():t.unsubscribe()}var Fe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var vn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=vn.delegate;return o?.setTimeout?o.setTimeout.apply(o,hn([t,e],fn(n))):setTimeout.apply(void 0,hn([t,e],fn(n)))},clearTimeout:function(t){var e=vn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function Fr(t){vn.setTimeout(function(){var e=Fe.onUnhandledError;if(e)e(t);else throw t})}function zn(){}var el=(function(){return Ys("C",void 0,void 0)})();function tl(t){return Ys("E",void 0,t)}function nl(t){return Ys("N",t,void 0)}function Ys(t,e,n){return{kind:t,value:e,error:n}}var $t=null;function yn(t){if(Fe.useDeprecatedSynchronousErrorHandling){var e=!$t;if(e&&($t={errorThrown:!1,error:null}),t(),e){var n=$t,r=n.errorThrown,o=n.error;if($t=null,r)throw o}}else t()}function rl(t){Fe.useDeprecatedSynchronousErrorHandling&&$t&&($t.errorThrown=!0,$t.error=t)}var Bn=(function(t){et(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Hr(n)&&n.add(r)):r.destination=Cf,r}return e.create=function(n,r,o){return new zr(n,r,o)},e.prototype.next=function(n){this.isStopped?Js(nl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?Js(tl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?Js(el,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(gn);var Af=Function.prototype.bind;function qs(t,e){return Af.call(t,e)}var kf=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){$r(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){$r(r)}else $r(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){$r(n)}},t})(),zr=(function(t){et(e,t);function e(n,r,o){var s=t.call(this)||this,i;if(G(n)||!n)i={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;s&&Fe.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return s.unsubscribe()},i={next:n.next&&qs(n.next,a),error:n.error&&qs(n.error,a),complete:n.complete&&qs(n.complete,a)}):i=n}return s.destination=new kf(i),s}return e})(Bn);function $r(t){Fe.useDeprecatedSynchronousErrorHandling?rl(t):Fr(t)}function If(t){throw t}function Js(t,e){var n=Fe.onStoppedNotification;n&&vn.setTimeout(function(){return n(t,e)})}var Cf={closed:!0,next:zn,error:If,complete:zn};var bn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function xn(t){return t}function Br(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Qs(t)}function Qs(t){return t.length===0?xn:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var J=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,s=Rf(e)?e:new zr(e,n,r);return yn(function(){var i=o,a=i.operator,l=i.source;s.add(a?a.call(s,l):l?o._subscribe(s):o._trySubscribe(s))}),s},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=ol(n),new n(function(o,s){var i=new zr({next:function(a){try{e(a)}catch(l){s(l),i.unsubscribe()}},error:s,complete:o});r.subscribe(i)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[bn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Qs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=ol(e),new e(function(r,o){var s;n.subscribe(function(i){return s=i},function(i){return o(i)},function(){return r(s)})})},t.create=function(e){return new t(e)},t})();function ol(t){var e;return(e=t??Fe.Promise)!==null&&e!==void 0?e:Promise}function Nf(t){return t&&G(t.next)&&G(t.error)&&G(t.complete)}function Rf(t){return t&&t instanceof Bn||Nf(t)&&Hr(t)}function Of(t){return G(t?.lift)}function ce(t){return function(e){if(Of(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function he(t,e,n,r,o){return new Mf(t,e,n,r,o)}var Mf=(function(t){et(e,t);function e(n,r,o,s,i,a){var l=t.call(this,n)||this;return l.onFinalize=i,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(p){n.error(p)}}:t.prototype._next,l._error=s?function(c){try{s(c)}catch(p){n.error(p)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(c){n.error(c)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e})(Bn);var sl=mn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var tt=(function(t){et(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new il(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new sl},e.prototype.next=function(n){var r=this;yn(function(){var o,s;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var i=ut(r.currentObservers),a=i.next();!a.done;a=i.next()){var l=a.value;l.next(n)}}catch(c){o={error:c}}finally{try{a&&!a.done&&(s=i.return)&&s.call(i)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;yn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;yn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,s=o.hasError,i=o.isStopped,a=o.observers;return s||i?Ks:(this.currentObservers=null,a.push(n),new gn(function(){r.currentObservers=null,$n(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,s=r.thrownError,i=r.isStopped;o?n.error(s):i&&n.complete()},e.prototype.asObservable=function(){var n=new J;return n.source=this,n},e.create=function(n,r){return new il(n,r)},e})(J);var il=(function(t){et(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:Ks},e})(tt);var ei={now:function(){return(ei.delegate||Date).now()},delegate:void 0};var Vr=(function(t){et(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=ei);var s=t.call(this)||this;return s._bufferSize=n,s._windowTime=r,s._timestampProvider=o,s._buffer=[],s._infiniteTimeWindow=!0,s._infiniteTimeWindow=r===1/0,s._bufferSize=Math.max(1,n),s._windowTime=Math.max(1,r),s}return e.prototype.next=function(n){var r=this,o=r.isStopped,s=r._buffer,i=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;o||(s.push(n),!i&&s.push(a.now()+l)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,s=o._infiniteTimeWindow,i=o._buffer,a=i.slice(),l=0;l<a.length&&!n.closed;l+=s?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,s=n._buffer,i=n._infiniteTimeWindow,a=(i?1:2)*r;if(r<1/0&&a<s.length&&s.splice(0,s.length-a),!i){for(var l=o.now(),c=0,p=1;p<s.length&&s[p]<=l;p+=2)c=p;c&&s.splice(0,c+1)}},e})(tt);var jr=new J(function(t){return t.complete()});function al(t){return t&&G(t.schedule)}function Lf(t){return t[t.length-1]}function ll(t){return al(Lf(t))?t.pop():void 0}var Wr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Xr(t){return G(t?.then)}function Zr(t){return G(t[bn])}function Kr(t){return Symbol.asyncIterator&&G(t?.[Symbol.asyncIterator])}function Yr(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Pf(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var qr=Pf();function Jr(t){return G(t?.[qr])}function Qr(t){return qa(this,arguments,function(){var n,r,o,s;return Ur(this,function(i){switch(i.label){case 0:n=t.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,Ft(n.read())];case 3:return r=i.sent(),o=r.value,s=r.done,s?[4,Ft(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,Ft(o)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function eo(t){return G(t?.getReader)}function me(t){if(t instanceof J)return t;if(t!=null){if(Zr(t))return Df(t);if(Wr(t))return Uf(t);if(Xr(t))return Gf(t);if(Kr(t))return cl(t);if(Jr(t))return Hf(t);if(eo(t))return Ff(t)}throw Yr(t)}function Df(t){return new J(function(e){var n=t[bn]();if(G(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Uf(t){return new J(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Gf(t){return new J(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Fr)})}function Hf(t){return new J(function(e){var n,r;try{for(var o=ut(t),s=o.next();!s.done;s=o.next()){var i=s.value;if(e.next(i),e.closed)return}}catch(a){n={error:a}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function cl(t){return new J(function(e){$f(t,e).catch(function(n){return e.error(n)})})}function Ff(t){return cl(Qr(t))}function $f(t,e){var n,r,o,s;return Ya(this,void 0,void 0,function(){var i,a;return Ur(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Ja(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(i=r.value,e.next(i),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),o={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Le(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var s=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(s),!o)return s}function to(t,e){return e===void 0&&(e=0),ce(function(n,r){n.subscribe(he(r,function(o){return Le(r,t,function(){return r.next(o)},e)},function(){return Le(r,t,function(){return r.complete()},e)},function(o){return Le(r,t,function(){return r.error(o)},e)}))})}function no(t,e){return e===void 0&&(e=0),ce(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function ul(t,e){return me(t).pipe(no(e),to(e))}function dl(t,e){return me(t).pipe(no(e),to(e))}function pl(t,e){return new J(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function fl(t,e){return new J(function(n){var r;return Le(n,e,function(){r=t[qr](),Le(n,e,function(){var o,s,i;try{o=r.next(),s=o.value,i=o.done}catch(a){n.error(a);return}i?n.complete():n.next(s)},0,!0)}),function(){return G(r?.return)&&r.return()}})}function ro(t,e){if(!t)throw new Error("Iterable cannot be null");return new J(function(n){Le(n,e,function(){var r=t[Symbol.asyncIterator]();Le(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function hl(t,e){return ro(Qr(t),e)}function ml(t,e){if(t!=null){if(Zr(t))return ul(t,e);if(Wr(t))return pl(t,e);if(Xr(t))return dl(t,e);if(Kr(t))return ro(t,e);if(Jr(t))return fl(t,e);if(eo(t))return hl(t,e)}throw Yr(t)}function zt(t,e){return e?ml(t,e):me(t)}function te(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=ll(t);return zt(t,n)}function Q(t,e){var n=G(t)?t:function(){return t},r=function(o){return o.error(n())};return new J(e?function(o){return e.schedule(r,0,o)}:r)}var gl=mn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function oo(t,e){var n=typeof e=="object";return new Promise(function(r,o){var s=!1,i;t.subscribe({next:function(a){i=a,s=!0},error:o,complete:function(){s?r(i):n?r(e.defaultValue):o(new gl)}})})}function Bt(t,e){return ce(function(n,r){var o=0;n.subscribe(he(r,function(s){r.next(t.call(e,s,o++))}))})}function vl(t,e,n,r,o,s,i,a){var l=[],c=0,p=0,m=!1,x=function(){m&&!l.length&&!c&&e.complete()},f=function(g){return c<r?h(g):l.push(g)},h=function(g){s&&e.next(g),c++;var T=!1;me(n(g,p++)).subscribe(he(e,function(S){o?.(S),s?f(S):e.next(S)},function(){T=!0},void 0,function(){if(T)try{c--;for(var S=function(){var b=l.shift();i?Le(e,i,function(){return h(b)}):h(b)};l.length&&c<r;)S();x()}catch(b){e.error(b)}}))};return t.subscribe(he(e,f,function(){m=!0,x()})),function(){a?.()}}function ke(t,e,n){return n===void 0&&(n=1/0),G(e)?ke(function(r,o){return Bt(function(s,i){return e(r,s,o,i)})(me(t(r,o)))},n):(typeof e=="number"&&(n=e),ce(function(r,o){return vl(r,o,t,n)}))}function ti(t){return t===void 0&&(t=1/0),ke(xn,t)}function so(t){return new J(function(e){me(t()).subscribe(e)})}function Vn(t){return ce(function(e,n){var r=null,o=!1,s;r=e.subscribe(he(n,void 0,void 0,function(i){s=me(t(i,Vn(t)(e))),r?(r.unsubscribe(),r=null,s.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,s.subscribe(n))})}function io(t,e){return G(e)?ke(t,e,1):ke(t,1)}function ni(t){return ce(function(e,n){var r=!1;e.subscribe(he(n,function(o){r=!0,n.next(o)},function(){r||n.next(t),n.complete()}))})}function Vt(t){return ce(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function ri(t,e){return ce(function(n,r){var o=null,s=0,i=!1,a=function(){return i&&!o&&r.complete()};n.subscribe(he(r,function(l){o?.unsubscribe();var c=0,p=s++;me(t(l,p)).subscribe(o=he(r,function(m){return r.next(e?e(l,m,p,c++):m)},function(){o=null,a()}))},function(){i=!0,a()}))})}function ao(t){return ce(function(e,n){me(t).subscribe(he(n,function(){return n.complete()},zn)),!n.closed&&e.subscribe(n)})}function oi(t,e,n){var r=G(t)||e||n?{next:t,error:e,complete:n}:t;return r?ce(function(o,s){var i;(i=r.subscribe)===null||i===void 0||i.call(r);var a=!0;o.subscribe(he(s,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),s.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),s.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),s.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):xn}function yl(t){return` \r
5
- `.indexOf(t)>=0}function lo(t){for(var e=["topLevel"],n=0,r,o,s,i=function(b){return e.push(b)},a=function(b){return e[e.length-1]=b},l=function(b){r==null&&(r=n,o=e.length,s=b)},c=function(b){b===s&&(r=void 0,o=void 0,s=void 0)},p=function(){return e.pop()},m=function(){return n--},x=function(b){if("0"<=b&&b<="9"){i("number");return}switch(b){case'"':i("string");return;case"-":i("numberNeedsDigit");return;case"t":i("true");return;case"f":i("false");return;case"n":i("null");return;case"[":i("arrayNeedsValue");return;case"{":i("objectNeedsKey");return}},f=t.length;n<f;n++){var h=t[n];switch(e[e.length-1]){case"topLevel":x(h);break;case"string":switch(h){case'"':p();break;case"\\":l("stringEscape"),i("stringEscaped");break}break;case"stringEscaped":h==="u"?i("stringUnicode"):(c("stringEscape"),p());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),p());break;case"number":h==="."?a("numberNeedsDigit"):h==="e"||h==="E"?a("numberNeedsExponent"):(h<"0"||h>"9")&&(m(),p());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(h==="+"||h==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(h<"a"||h>"z")&&(m(),p());break;case"arrayNeedsValue":h==="]"?p():yl(h)||(c("collectionItem"),a("arrayNeedsComma"),x(h));break;case"arrayNeedsComma":h==="]"?p():h===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":h==="}"?p():h==='"'&&(l("collectionItem"),a("objectNeedsColon"),i("string"));break;case"objectNeedsColon":h===":"&&a("objectNeedsValue");break;case"objectNeedsValue":yl(h)||(c("collectionItem"),a("objectNeedsComma"),x(h));break;case"objectNeedsComma":h==="}"?p():h===","&&(l("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var g=[r!=null?t.slice(0,r):t],T=function(b){return g.push(b.slice(t.length-t.lastIndexOf(b[0])))},S=e.length-1;S>=0;S--)switch(e[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":T("true");break;case"false":T("false");break;case"null":T("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function xl(){let t=0,e=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function uo(t,e,n){for(let s=0;s<28;s=s+7){let i=t>>>s,a=!(!(i>>>7)&&e==0),l=(a?i|128:i)&255;if(n.push(l),!a)return}let r=t>>>28&15|(e&7)<<4,o=e>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let s=3;s<31;s=s+7){let i=e>>>s,a=!!(i>>>7),l=(a?i|128:i)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var co=4294967296;function si(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function s(i,a){let l=Number(t.slice(i,a));o*=n,r=r*n+l,r>=co&&(o=o+(r/co|0),r=r%co)}return s(-24,-18),s(-18,-12),s(-12,-6),s(-6),e?Tl(r,o):ai(r,o)}function El(t,e){let n=ai(t,e),r=n.hi&2147483648;r&&(n=Tl(n.lo,n.hi));let o=ii(n.lo,n.hi);return r?"-"+o:o}function ii(t,e){if({lo:t,hi:e}=zf(t,e),e<=2097151)return String(co*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,o=e>>16&65535,s=n+r*6777216+o*6710656,i=r+o*8147497,a=o*2,l=1e7;return s>=l&&(i+=Math.floor(s/l),s%=l),i>=l&&(a+=Math.floor(i/l),i%=l),a.toString()+bl(i)+bl(s)}function zf(t,e){return{lo:t>>>0,hi:e>>>0}}function ai(t,e){return{lo:t|0,hi:e|0}}function Tl(t,e){return e=~e,t?t=~t+1:e+=1,ai(t,e)}var bl=t=>{let e=String(t);return"0000000".slice(e.length)+e};function li(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function _l(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var $e=Bf();function Bf(){let t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),s=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(i){let a=typeof i=="bigint"?i:BigInt(i);if(a>r||a<n)throw new Error(`invalid int64: ${i}`);return a},uParse(i){let a=typeof i=="bigint"?i:BigInt(i);if(a>s||a<o)throw new Error(`invalid uint64: ${i}`);return a},enc(i){return t.setBigInt64(0,this.parse(i),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(i){return t.setBigInt64(0,this.uParse(i),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(i,a){return t.setInt32(0,i,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(i,a){return t.setInt32(0,i,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),Sl(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),wl(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Sl(n),si(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),wl(n),si(n)},dec(n,r){return El(n,r)},uDec(n,r){return ii(n,r)}}}function Sl(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function wl(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var ci=Symbol.for("@bufbuild/protobuf/text-encoding");function ui(){if(globalThis[ci]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[ci]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[ci]}var bt;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(bt||(bt={}));var Vf=34028234663852886e22,jf=-34028234663852886e22,Wf=4294967295,Xf=2147483647,Zf=-2147483648,P=class{constructor(e=ui().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let o=0;o<this.chunks.length;o++)e+=this.chunks[o].length;let n=new Uint8Array(e),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Al(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return di(e),li(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.encodeUtf8(e);return this.uint32(n.byteLength),this.raw(n)}float(e){Kf(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){Al(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){di(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return di(e),e=(e<<1^e>>31)>>>0,li(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=$e.enc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=$e.uEnc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(e){let n=$e.enc(e);return uo(n.lo,n.hi,this.buf),this}sint64(e){let n=$e.enc(e),r=n.hi>>31,o=n.lo<<1^r,s=(n.hi<<1|n.lo>>>31)^r;return uo(o,s,this.buf),this}uint64(e){let n=$e.uEnc(e);return uo(n.lo,n.hi,this.buf),this}},_=class{constructor(e,n=ui().decodeUtf8){this.decodeUtf8=n,this.varint64=xl,this.uint32=_l,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,s=n&7;if(o<=0||s>5)throw new Error("illegal tag: field no "+o+" wire type "+s);return[o,s]}skip(e,n){let r=this.pos;switch(e){case bt.Varint:for(;this.buf[this.pos++]&128;);break;case bt.Bit64:this.pos+=4;case bt.Bit32:this.pos+=4;break;case bt.LengthDelimited:let o=this.uint32();this.pos+=o;break;case bt.StartGroup:for(;;){let[s,i]=this.tag();if(i===bt.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(i,s)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return $e.dec(...this.varint64())}uint64(){return $e.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,$e.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return $e.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return $e.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(e){return this.decodeUtf8(this.bytes(),e)}};function di(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid int32: "+typeof t);if(!Number.isInteger(t)||t>Xf||t<Zf)throw new Error("invalid int32: "+t)}function Al(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid uint32: "+typeof t);if(!Number.isInteger(t)||t>Wf||t<0)throw new Error("invalid uint32: "+t)}function Kf(t){if(typeof t=="string"){let e=t;if(t=Number(t),Number.isNaN(t)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof t!="number")throw new Error("invalid float32: "+typeof t);if(Number.isFinite(t)&&(t>Vf||t<jf))throw new Error("invalid float32: "+t)}var Yf=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function pi(){return{fields:{}}}var jn={encode(t,e=new P){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&mi.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=pi();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:{if(s!==10)break;let i=mi.decode(n,n.uint32());i.value!==void 0&&(o.fields[i.key]=i.value);continue}}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return jn.fromPartial(t??{})},fromPartial(t){let e=pi();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=pi();if(t!==void 0)for(let n of Object.keys(t))e.fields[n]=t[n];return e},unwrap(t){let e={};if(t.fields)for(let n of Object.keys(t.fields))e[n]=t.fields[n];return e}};function kl(){return{key:"",value:void 0}}var mi={encode(t,e=new P){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=kl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.key=n.string();continue;case 2:if(s!==18)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return mi.fromPartial(t??{})},fromPartial(t){let e=kl();return e.key=t.key??"",e.value=t.value??void 0,e}};function fi(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var N={encode(t,e=new P){return t.nullValue!==void 0&&e.uint32(8).int32(t.nullValue),t.numberValue!==void 0&&e.uint32(17).double(t.numberValue),t.stringValue!==void 0&&e.uint32(26).string(t.stringValue),t.boolValue!==void 0&&e.uint32(32).bool(t.boolValue),t.structValue!==void 0&&jn.encode(jn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Wn.encode(Wn.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=fi();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.nullValue=n.int32();continue;case 2:if(s!==17)break;o.numberValue=n.double();continue;case 3:if(s!==26)break;o.stringValue=n.string();continue;case 4:if(s!==32)break;o.boolValue=n.bool();continue;case 5:if(s!==42)break;o.structValue=jn.unwrap(jn.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.listValue=Wn.unwrap(Wn.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return N.fromPartial(t??{})},fromPartial(t){let e=fi();return e.nullValue=t.nullValue??void 0,e.numberValue=t.numberValue??void 0,e.stringValue=t.stringValue??void 0,e.boolValue=t.boolValue??void 0,e.structValue=t.structValue??void 0,e.listValue=t.listValue??void 0,e},wrap(t){let e=fi();if(t===null)e.nullValue=Yf.NULL_VALUE;else if(typeof t=="boolean")e.boolValue=t;else if(typeof t=="number")e.numberValue=t;else if(typeof t=="string")e.stringValue=t;else if(globalThis.Array.isArray(t))e.listValue=t;else if(typeof t=="object")e.structValue=t;else if(typeof t<"u")throw new globalThis.Error("Unsupported any value type: "+typeof t);return e},unwrap(t){if(t.stringValue!==void 0)return t.stringValue;if(t?.numberValue!==void 0)return t.numberValue;if(t?.boolValue!==void 0)return t.boolValue;if(t?.structValue!==void 0)return t.structValue;if(t?.listValue!==void 0)return t.listValue;if(t?.nullValue!==void 0)return null}};function hi(){return{values:[]}}var Wn={encode(t,e=new P){for(let n of t.values)N.encode(N.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=hi();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.values.push(N.unwrap(N.decode(n,n.uint32())));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Wn.fromPartial(t??{})},fromPartial(t){let e=hi();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=hi();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},qf=(function(t){return t[t.ADD=0]="ADD",t[t.REMOVE=1]="REMOVE",t[t.REPLACE=2]="REPLACE",t[t.MOVE=3]="MOVE",t[t.COPY=4]="COPY",t[t.TEST=5]="TEST",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Il(){return{op:0,path:"",from:void 0,value:void 0}}var fo={encode(t,e=new P){return t.op!==0&&e.uint32(8).int32(t.op),t.path!==""&&e.uint32(18).string(t.path),t.from!==void 0&&e.uint32(26).string(t.from),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Il();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.op=n.int32();continue;case 2:if(s!==18)break;o.path=n.string();continue;case 3:if(s!==26)break;o.from=n.string();continue;case 4:if(s!==34)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return fo.fromPartial(t??{})},fromPartial(t){let e=Il();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Cl(){return{id:"",type:"",function:void 0}}var ho={encode(t,e=new P){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&mo.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Cl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.type=n.string();continue;case 3:if(s!==26)break;o.function=mo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return ho.fromPartial(t??{})},fromPartial(t){let e=Cl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?mo.fromPartial(t.function):void 0,e}};function Nl(){return{name:"",arguments:""}}var mo={encode(t,e=new P){return t.name!==""&&e.uint32(10).string(t.name),t.arguments!==""&&e.uint32(18).string(t.arguments),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Nl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.name=n.string();continue;case 2:if(s!==18)break;o.arguments=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return mo.fromPartial(t??{})},fromPartial(t){let e=Nl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Rl(){return{value:"",mimeType:""}}var go={encode(t,e=new P){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==""&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Rl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.value=n.string();continue;case 2:if(s!==18)break;o.mimeType=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return go.fromPartial(t??{})},fromPartial(t){let e=Rl();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Ol(){return{value:"",mimeType:void 0}}var vo={encode(t,e=new P){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==void 0&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ol();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.value=n.string();continue;case 2:if(s!==18)break;o.mimeType=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return vo.fromPartial(t??{})},fromPartial(t){let e=Ol();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Ml(){return{data:void 0,url:void 0}}var Ie={encode(t,e=new P){return t.data!==void 0&&go.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&vo.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ml();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.data=go.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.url=vo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ie.fromPartial(t??{})},fromPartial(t){let e=Ml();return e.data=t.data!==void 0&&t.data!==null?go.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?vo.fromPartial(t.url):void 0,e}};function Ll(){return{text:""}}var yo={encode(t,e=new P){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ll();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return yo.fromPartial(t??{})},fromPartial(t){let e=Ll();return e.text=t.text??"",e}};function Pl(){return{source:void 0,metadata:void 0}}var bo={encode(t,e=new P){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Pl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return bo.fromPartial(t??{})},fromPartial(t){let e=Pl();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Dl(){return{source:void 0,metadata:void 0}}var xo={encode(t,e=new P){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Dl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return xo.fromPartial(t??{})},fromPartial(t){let e=Dl();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Ul(){return{source:void 0,metadata:void 0}}var Eo={encode(t,e=new P){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ul();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Eo.fromPartial(t??{})},fromPartial(t){let e=Ul();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Gl(){return{source:void 0,metadata:void 0}}var To={encode(t,e=new P){return t.source!==void 0&&Ie.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Gl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.source=Ie.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return To.fromPartial(t??{})},fromPartial(t){let e=Gl();return e.source=t.source!==void 0&&t.source!==null?Ie.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Hl(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var _o={encode(t,e=new P){return t.text!==void 0&&yo.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&bo.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&xo.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&Eo.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&To.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Hl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.text=yo.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.image=bo.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.audio=xo.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.video=Eo.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.document=To.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return _o.fromPartial(t??{})},fromPartial(t){let e=Hl();return e.text=t.text!==void 0&&t.text!==null?yo.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?bo.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?xo.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?Eo.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?To.fromPartial(t.document):void 0,e}};function Fl(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var So={encode(t,e=new P){t.id!==""&&e.uint32(10).string(t.id),t.role!==""&&e.uint32(18).string(t.role),t.content!==void 0&&e.uint32(26).string(t.content),t.name!==void 0&&e.uint32(34).string(t.name);for(let n of t.toolCalls)ho.encode(n,e.uint32(42).fork()).join();t.toolCallId!==void 0&&e.uint32(50).string(t.toolCallId),t.error!==void 0&&e.uint32(58).string(t.error);for(let n of t.contentParts)_o.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Fl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.role=n.string();continue;case 3:if(s!==26)break;o.content=n.string();continue;case 4:if(s!==34)break;o.name=n.string();continue;case 5:if(s!==42)break;o.toolCalls.push(ho.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.toolCallId=n.string();continue;case 7:if(s!==58)break;o.error=n.string();continue;case 8:if(s!==66)break;o.contentParts.push(_o.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return So.fromPartial(t??{})},fromPartial(t){let e=Fl();return e.id=t.id??"",e.role=t.role??"",e.content=t.content??void 0,e.name=t.name??void 0,e.toolCalls=t.toolCalls?.map(n=>ho.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>_o.fromPartial(n))||[],e}};function $l(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var wo={encode(t,e=new P){return t.id!==""&&e.uint32(10).string(t.id),t.reason!==""&&e.uint32(18).string(t.reason),t.message!==void 0&&e.uint32(26).string(t.message),t.toolCallId!==void 0&&e.uint32(34).string(t.toolCallId),t.responseSchema!==void 0&&N.encode(N.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=$l();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.id=n.string();continue;case 2:if(s!==18)break;o.reason=n.string();continue;case 3:if(s!==26)break;o.message=n.string();continue;case 4:if(s!==34)break;o.toolCallId=n.string();continue;case 5:if(s!==42)break;o.responseSchema=N.unwrap(N.decode(n,n.uint32()));continue;case 6:if(s!==50)break;o.expiresAt=n.string();continue;case 7:if(s!==58)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return wo.fromPartial(t??{})},fromPartial(t){let e=$l();return e.id=t.id??"",e.reason=t.reason??"",e.message=t.message??void 0,e.toolCallId=t.toolCallId??void 0,e.responseSchema=t.responseSchema??void 0,e.expiresAt=t.expiresAt??void 0,e.metadata=t.metadata??void 0,e}},Jf=(function(t){return t[t.TEXT_MESSAGE_START=0]="TEXT_MESSAGE_START",t[t.TEXT_MESSAGE_CONTENT=1]="TEXT_MESSAGE_CONTENT",t[t.TEXT_MESSAGE_END=2]="TEXT_MESSAGE_END",t[t.TOOL_CALL_START=3]="TOOL_CALL_START",t[t.TOOL_CALL_ARGS=4]="TOOL_CALL_ARGS",t[t.TOOL_CALL_END=5]="TOOL_CALL_END",t[t.STATE_SNAPSHOT=6]="STATE_SNAPSHOT",t[t.STATE_DELTA=7]="STATE_DELTA",t[t.MESSAGES_SNAPSHOT=8]="MESSAGES_SNAPSHOT",t[t.RAW=9]="RAW",t[t.CUSTOM=10]="CUSTOM",t[t.RUN_STARTED=11]="RUN_STARTED",t[t.RUN_FINISHED=12]="RUN_FINISHED",t[t.RUN_ERROR=13]="RUN_ERROR",t[t.STEP_STARTED=14]="STEP_STARTED",t[t.STEP_FINISHED=15]="STEP_FINISHED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function zl(){return{type:0,timestamp:void 0,rawEvent:void 0}}var R={encode(t,e=new P){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&N.encode(N.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=zl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==8)break;o.type=n.int32();continue;case 2:if(s!==16)break;o.timestamp=Qf(n.int64());continue;case 3:if(s!==26)break;o.rawEvent=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=zl();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function Bl(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Ao={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.name!==void 0&&e.uint32(34).string(t.name),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Bl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.role=n.string();continue;case 4:if(s!==34)break;o.name=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ao.fromPartial(t??{})},fromPartial(t){let e=Bl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function Vl(){return{baseEvent:void 0,messageId:"",delta:""}}var ko={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Vl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return ko.fromPartial(t??{})},fromPartial(t){let e=Vl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function jl(){return{baseEvent:void 0,messageId:""}}var Io={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=jl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Io.fromPartial(t??{})},fromPartial(t){let e=jl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function Wl(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Co={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.toolCallName!==""&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Wl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.toolCallName=n.string();continue;case 4:if(s!==34)break;o.parentMessageId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Co.fromPartial(t??{})},fromPartial(t){let e=Wl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function Xl(){return{baseEvent:void 0,toolCallId:"",delta:""}}var No={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Xl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return No.fromPartial(t??{})},fromPartial(t){let e=Xl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function Zl(){return{baseEvent:void 0,toolCallId:""}}var Ro={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Zl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ro.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function Kl(){return{baseEvent:void 0,snapshot:void 0}}var Oo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&N.encode(N.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Kl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.snapshot=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Oo.fromPartial(t??{})},fromPartial(t){let e=Kl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Yl(){return{baseEvent:void 0,delta:[]}}var Mo={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)fo.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Yl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.delta.push(fo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Mo.fromPartial(t??{})},fromPartial(t){let e=Yl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>fo.fromPartial(n))||[],e}};function ql(){return{baseEvent:void 0,messages:[]}}var Lo={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)So.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=ql();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messages.push(So.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=ql();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>So.fromPartial(n))||[],e}};function Jl(){return{baseEvent:void 0,event:void 0,source:void 0}}var Po={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&N.encode(N.wrap(t.event),e.uint32(18).fork()).join(),t.source!==void 0&&e.uint32(26).string(t.source),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Jl();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.event=N.unwrap(N.decode(n,n.uint32()));continue;case 3:if(s!==26)break;o.source=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Po.fromPartial(t??{})},fromPartial(t){let e=Jl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function Ql(){return{baseEvent:void 0,name:"",value:void 0}}var Do={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=Ql();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.name=n.string();continue;case 3:if(s!==26)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Do.fromPartial(t??{})},fromPartial(t){let e=Ql();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function ec(){return{baseEvent:void 0,threadId:"",runId:""}}var Uo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=ec();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.threadId=n.string();continue;case 3:if(s!==26)break;o.runId=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Uo.fromPartial(t??{})},fromPartial(t){let e=ec();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function tc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Go={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),t.result!==void 0&&N.encode(N.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)wo.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=tc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.threadId=n.string();continue;case 3:if(s!==26)break;o.runId=n.string();continue;case 4:if(s!==34)break;o.result=N.unwrap(N.decode(n,n.uint32()));continue;case 5:if(s!==42)break;o.outcome=n.string();continue;case 6:if(s!==50)break;o.interrupts.push(wo.decode(n,n.uint32()));continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=tc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e.result=t.result??void 0,e.outcome=t.outcome??"",e.interrupts=t.interrupts?.map(n=>wo.fromPartial(n))||[],e}};function nc(){return{baseEvent:void 0,code:void 0,message:""}}var Ho={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.code!==void 0&&e.uint32(18).string(t.code),t.message!==""&&e.uint32(26).string(t.message),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=nc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.code=n.string();continue;case 3:if(s!==26)break;o.message=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Ho.fromPartial(t??{})},fromPartial(t){let e=nc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function rc(){return{baseEvent:void 0,stepName:""}}var Fo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=rc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=rc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function oc(){return{baseEvent:void 0,stepName:""}}var $o={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=oc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.stepName=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return $o.fromPartial(t??{})},fromPartial(t){let e=oc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function sc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var zo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==void 0&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.delta!==void 0&&e.uint32(34).string(t.delta),t.name!==void 0&&e.uint32(42).string(t.name),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=sc();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.messageId=n.string();continue;case 3:if(s!==26)break;o.role=n.string();continue;case 4:if(s!==34)break;o.delta=n.string();continue;case 5:if(s!==42)break;o.name=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return zo.fromPartial(t??{})},fromPartial(t){let e=sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??void 0,e.role=t.role??void 0,e.delta=t.delta??void 0,e.name=t.name??void 0,e}};function ic(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Bo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==void 0&&e.uint32(18).string(t.toolCallId),t.toolCallName!==void 0&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),t.delta!==void 0&&e.uint32(42).string(t.delta),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=ic();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.toolCallId=n.string();continue;case 3:if(s!==26)break;o.toolCallName=n.string();continue;case 4:if(s!==34)break;o.parentMessageId=n.string();continue;case 5:if(s!==42)break;o.delta=n.string();continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return Bo.fromPartial(t??{})},fromPartial(t){let e=ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??void 0,e.toolCallName=t.toolCallName??void 0,e.parentMessageId=t.parentMessageId??void 0,e.delta=t.delta??void 0,e}};function ac(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0}}var lc={encode(t,e=new P){return t.textMessageStart!==void 0&&Ao.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&ko.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Io.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Co.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&No.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Ro.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Oo.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Mo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Lo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Po.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Do.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&Uo.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Go.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&Ho.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Fo.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&$o.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&zo.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&Bo.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof _?t:new _(t),r=e===void 0?n.len:n.pos+e,o=ac();for(;n.pos<r;){let s=n.uint32();switch(s>>>3){case 1:if(s!==10)break;o.textMessageStart=Ao.decode(n,n.uint32());continue;case 2:if(s!==18)break;o.textMessageContent=ko.decode(n,n.uint32());continue;case 3:if(s!==26)break;o.textMessageEnd=Io.decode(n,n.uint32());continue;case 4:if(s!==34)break;o.toolCallStart=Co.decode(n,n.uint32());continue;case 5:if(s!==42)break;o.toolCallArgs=No.decode(n,n.uint32());continue;case 6:if(s!==50)break;o.toolCallEnd=Ro.decode(n,n.uint32());continue;case 7:if(s!==58)break;o.stateSnapshot=Oo.decode(n,n.uint32());continue;case 8:if(s!==66)break;o.stateDelta=Mo.decode(n,n.uint32());continue;case 9:if(s!==74)break;o.messagesSnapshot=Lo.decode(n,n.uint32());continue;case 10:if(s!==82)break;o.raw=Po.decode(n,n.uint32());continue;case 11:if(s!==90)break;o.custom=Do.decode(n,n.uint32());continue;case 12:if(s!==98)break;o.runStarted=Uo.decode(n,n.uint32());continue;case 13:if(s!==106)break;o.runFinished=Go.decode(n,n.uint32());continue;case 14:if(s!==114)break;o.runError=Ho.decode(n,n.uint32());continue;case 15:if(s!==122)break;o.stepStarted=Fo.decode(n,n.uint32());continue;case 16:if(s!==130)break;o.stepFinished=$o.decode(n,n.uint32());continue;case 17:if(s!==138)break;o.textMessageChunk=zo.decode(n,n.uint32());continue;case 18:if(s!==146)break;o.toolCallChunk=Bo.decode(n,n.uint32());continue}if((s&7)===4||s===0)break;n.skip(s&7)}return o},create(t){return lc.fromPartial(t??{})},fromPartial(t){let e=ac();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Ao.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?ko.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Io.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Co.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?No.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Ro.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Oo.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Mo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Lo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Po.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Do.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?Uo.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Go.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?Ho.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Fo.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?$o.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?zo.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?Bo.fromPartial(t.toolCallChunk):void 0,e}};function Qf(t){let e=globalThis.Number(t.toString());if(e>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(e<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return e}var po=t=>{if(!(!t||typeof t!="object")){if(t.data)return{type:"data",value:t.data.value,mimeType:t.data.mimeType};if(t.url)return{type:"url",value:t.url.value,mimeType:t.url.mimeType}}},eh=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:po(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:po(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:po(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:po(t.document.source),metadata:t.document.metadata}}};function cc(t){let e=lc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=Jf[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let s=o.contentParts.map(i=>eh(i)).filter(i=>i!==void 0);s.length>0&&(o.content=s)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,s=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:s}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=qf[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Ir.parse(n)}var gi="application/vnd.ag-ui.event+proto";var nh=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,vi=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(nh);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},uc=t=>t==="*"||t==="x"||t==="X",dc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},rh=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],oh=(t,e)=>{if(uc(t)||uc(e))return 0;let[n,r]=rh(dc(t),dc(e));return n>r?1:n<r?-1:0},yi=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=oh(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Xn=(t,e)=>{let n=vi(t),r=vi(e),o=n.pop(),s=r.pop(),i=yi(n,r);return i!==0?i:o&&s?yi(o.split("."),s.split(".")):o||s?o?-1:1:0};var z=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Ce(){return ht()}function Ei(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Ei(e);return t}async function W(t,e,n,r){let o=typeof process<"u"&&process.env!==void 0,s=o&&!!process.env.VITEST_WORKER_ID,i=o&&!!process.env.VITEST_WORKER_ID,a=z(e),l=z(n),c=a,p=l,m;for(let x of t)try{i&&(Ei(c),Ei(p));let f=await r(x,c,p);if(f===void 0)continue;if(f.messages!==void 0&&f.messages!==c&&(c=z(f.messages)),f.state!==void 0&&f.state!==p&&(p=z(f.state)),m=f.stopPropagation,m===!0)break}catch(f){if(i&&f instanceof TypeError){if(s)throw f;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",f)}else s||console.error("Subscriber error:",f);continue}return{...c===a?{}:{messages:i&&Object.isFrozen(c)?z(c):c},...p===l?{}:{state:i&&Object.isFrozen(p)?z(p):p},...m===void 0?{}:{stopPropagation:m}}}function Vo(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,n=t.lifecycle??!0,r=t.verbose??!1;return{enabled:e||n,events:e,lifecycle:n,verbose:r}}function Zn(t){if(t instanceof Ti)return t;if(t===!0)return new Ti(Vo(!0))}var Ti=class{constructor(t){this.config=t}event(t,e,n,r){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof n=="string"?n:JSON.stringify(n)):console.debug(`[${t}] ${e}`,r??n))}lifecycle(t,e,n){this.config.lifecycle&&(n?console.debug(`[${t}] ${e}`,n):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function bi(t){return t.enabled?new Ti(t):void 0}function sh(t,e,n){if(e){let o=t.find(i=>i.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let s={id:o?n:e,role:"assistant",toolCalls:[]};return t.push(s),s}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var vc=(t,e,n,r,o)=>{let s=Zn(o),i=z(n.messages),a=z(t.state),l={},c=m=>{m.messages!==void 0&&(i=m.messages,l.messages=m.messages),m.state!==void 0&&(a=m.state,l.state=m.state)},p=()=>{let m=z(l);return l={},m.messages!==void 0||m.state!==void 0?te(m):jr};return e.pipe(io(async m=>{let x=await W(r,i,a,(f,h,g)=>f.onEvent?.({event:m,agent:n,input:t,messages:h,state:g}));if(c(x),x.stopPropagation===!0?s?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):s?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),x.stopPropagation===!0)return p();switch(m.type){case v.TEXT_MESSAGE_START:{let f=await W(r,i,a,(h,g,T)=>h.onTextMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:h,role:g="assistant",name:T}=m;if(!i.find(S=>S.id===h)){let S={id:h,role:g,content:"",...T!==void 0&&{name:T}};i.push(S),c({messages:i})}}return p()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=i.find(S=>S.id===f);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let T=await W(r,i,a,(S,b,H)=>S.onTextMessageContentEvent?.({event:m,messages:b,state:H,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(T),T.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,c({messages:i})),p()}case v.TEXT_MESSAGE_END:{let{messageId:f}=m,h=i.find(g=>g.id===f);return h?(c(await W(r,i,a,(g,T,S)=>g.onTextMessageEndEvent?.({event:m,messages:T,state:S,agent:n,input:t,textMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:i,state:a,agent:n,input:t})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${f}'`),p())}case v.TOOL_CALL_START:{let f=await W(r,i,a,(h,g,T)=>h.onToolCallStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{toolCallId:h,toolCallName:g,parentMessageId:T}=m,S=sh(i,T,h);S.toolCalls??=[],S.toolCalls.push({id:h,type:"function",function:{name:g,arguments:""}}),c({messages:i})}return p()}case v.TOOL_CALL_ARGS:{let{toolCallId:f,delta:h}=m,g=i.find(b=>b.toolCalls?.some(H=>H.id===f));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${f}'`),p();let T=g.toolCalls?.find(b=>b.id===f);if(!T)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${f}'`),p();let S=await W(r,i,a,(b,H,X)=>{let ae=T.function.arguments,ee=T.function.name,dt={};try{dt=lo(ae)}catch{}return b.onToolCallArgsEvent?.({event:m,messages:H,state:X,agent:n,input:t,toolCallBuffer:ae,toolCallName:ee,partialToolCallArgs:dt})});return c(S),S.stopPropagation!==!0&&(T.function.arguments+=h,c({messages:i})),p()}case v.TOOL_CALL_END:{let{toolCallId:f}=m,h=i.find(T=>T.toolCalls?.some(S=>S.id===f));if(!h)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${f}'`),p();let g=h.toolCalls?.find(T=>T.id===f);return g?(c(await W(r,i,a,(T,S,b)=>{let H=g.function.arguments,X=g.function.name,ae={};try{ae=JSON.parse(H)}catch{}return T.onToolCallEndEvent?.({event:m,messages:S,state:b,agent:n,input:t,toolCallName:X,toolCallArgs:ae})})),await Promise.all(r.map(T=>{T.onNewToolCall?.({toolCall:g,messages:i,state:a,agent:n,input:t})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${f}'`),p())}case v.TOOL_CALL_RESULT:{let f=await W(r,i,a,(h,g,T)=>h.onToolCallResultEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:h,toolCallId:g,content:T,role:S}=m,b={id:h,toolCallId:g,role:S||"tool",content:T};i.push(b),await Promise.all(r.map(H=>{H.onNewMessage?.({message:b,messages:i,state:a,agent:n,input:t})})),c({messages:i})}return p()}case v.STATE_SNAPSHOT:{let f=await W(r,i,a,(h,g,T)=>h.onStateSnapshotEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{snapshot:h}=m;a=h,c({state:a})}return p()}case v.STATE_DELTA:{let f=await W(r,i,a,(h,g,T)=>h.onStateDeltaEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{delta:h}=m;try{a=Dr.applyPatch(a,h,!0,!1).newDocument,c({state:a})}catch(g){let T=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
4
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function jn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var vn=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=pt(s),l=a.next();!l.done;l=a.next()){var c=l.value;c.remove(this)}}catch(g){e={error:g}}finally{try{l&&!l.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}else s.remove(this);var p=this.initialTeardown;if(G(p))try{p()}catch(g){i=g instanceof zr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var x=pt(m),f=x.next();!f.done;f=x.next()){var h=f.value;try{ll(h)}catch(g){i=i??[],g instanceof zr?i=mn(mn([],hn(i)),hn(g.errors)):i.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=x.return)&&o.call(x)}finally{if(r)throw r.error}}}if(i)throw new zr(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)ll(e);else{if(e instanceof t){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(n=this._finalizers)!==null&&n!==void 0?n:[]).push(e)}},t.prototype._hasParent=function(e){var n=this._parentage;return n===e||Array.isArray(n)&&n.includes(e)},t.prototype._addParent=function(e){var n=this._parentage;this._parentage=Array.isArray(n)?(n.push(e),n):n?[n,e]:e},t.prototype._removeParent=function(e){var n=this._parentage;n===e?this._parentage=null:Array.isArray(n)&&jn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&jn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var as=vn.EMPTY;function Br(t){return t instanceof vn||t&&"closed"in t&&G(t.remove)&&G(t.add)&&G(t.unsubscribe)}function ll(t){G(t)?t():t.unsubscribe()}var Be={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var yn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=yn.delegate;return o?.setTimeout?o.setTimeout.apply(o,mn([t,e],hn(n))):setTimeout.apply(void 0,mn([t,e],hn(n)))},clearTimeout:function(t){var e=yn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function jr(t){yn.setTimeout(function(){var e=Be.onUnhandledError;if(e)e(t);else throw t})}function Vn(){}var cl=(function(){return ls("C",void 0,void 0)})();function ul(t){return ls("E",void 0,t)}function dl(t){return ls("N",t,void 0)}function ls(t,e,n){return{kind:t,value:e,error:n}}var jt=null;function bn(t){if(Be.useDeprecatedSynchronousErrorHandling){var e=!jt;if(e&&(jt={errorThrown:!1,error:null}),t(),e){var n=jt,r=n.errorThrown,o=n.error;if(jt=null,r)throw o}}else t()}function pl(t){Be.useDeprecatedSynchronousErrorHandling&&jt&&(jt.errorThrown=!0,jt.error=t)}var Wn=(function(t){tt(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Br(n)&&n.add(r)):r.destination=Bf,r}return e.create=function(n,r,o){return new Wr(n,r,o)},e.prototype.next=function(n){this.isStopped?us(dl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?us(ul(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?us(cl,this):(this.isStopped=!0,this._complete())},e.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,t.prototype.unsubscribe.call(this),this.destination=null)},e.prototype._next=function(n){this.destination.next(n)},e.prototype._error=function(n){try{this.destination.error(n)}finally{this.unsubscribe()}},e.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},e})(vn);var Ff=Function.prototype.bind;function cs(t,e){return Ff.call(t,e)}var $f=(function(){function t(e){this.partialObserver=e}return t.prototype.next=function(e){var n=this.partialObserver;if(n.next)try{n.next(e)}catch(r){Vr(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){Vr(r)}else Vr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){Vr(n)}},t})(),Wr=(function(t){tt(e,t);function e(n,r,o){var i=t.call(this)||this,s;if(G(n)||!n)s={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;i&&Be.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return i.unsubscribe()},s={next:n.next&&cs(n.next,a),error:n.error&&cs(n.error,a),complete:n.complete&&cs(n.complete,a)}):s=n}return i.destination=new $f(s),i}return e})(Wn);function Vr(t){Be.useDeprecatedSynchronousErrorHandling?pl(t):jr(t)}function zf(t){throw t}function us(t,e){var n=Be.onStoppedNotification;n&&yn.setTimeout(function(){return n(t,e)})}var Bf={closed:!0,next:Vn,error:zf,complete:Vn};var xn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function En(t){return t}function Xr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return ds(t)}function ds(t){return t.length===0?En:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var J=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,i=Vf(e)?e:new Wr(e,n,r);return bn(function(){var s=o,a=s.operator,l=s.source;i.add(a?a.call(i,l):l?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=fl(n),new n(function(o,i){var s=new Wr({next:function(a){try{e(a)}catch(l){i(l),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[xn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return ds(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=fl(e),new e(function(r,o){var i;n.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},t.create=function(e){return new t(e)},t})();function fl(t){var e;return(e=t??Be.Promise)!==null&&e!==void 0?e:Promise}function jf(t){return t&&G(t.next)&&G(t.error)&&G(t.complete)}function Vf(t){return t&&t instanceof Wn||jf(t)&&Br(t)}function Wf(t){return G(t?.lift)}function ue(t){return function(e){if(Wf(e))return e.lift(function(n){try{return t(n,this)}catch(r){this.error(r)}});throw new TypeError("Unable to lift unknown Observable type")}}function he(t,e,n,r,o){return new Xf(t,e,n,r,o)}var Xf=(function(t){tt(e,t);function e(n,r,o,i,s,a){var l=t.call(this,n)||this;return l.onFinalize=s,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(p){n.error(p)}}:t.prototype._next,l._error=i?function(c){try{i(c)}catch(p){n.error(p)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(c){n.error(c)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e})(Wn);var hl=gn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var nt=(function(t){tt(e,t);function e(){var n=t.call(this)||this;return n.closed=!1,n.currentObservers=null,n.observers=[],n.isStopped=!1,n.hasError=!1,n.thrownError=null,n}return e.prototype.lift=function(n){var r=new ml(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new hl},e.prototype.next=function(n){var r=this;bn(function(){var o,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=pt(r.currentObservers),a=s.next();!a.done;a=s.next()){var l=a.value;l.next(n)}}catch(c){o={error:c}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;bn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;bn(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?as:(this.currentObservers=null,a.push(n),new vn(function(){r.currentObservers=null,jn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,i=r.thrownError,s=r.isStopped;o?n.error(i):s&&n.complete()},e.prototype.asObservable=function(){var n=new J;return n.source=this,n},e.create=function(n,r){return new ml(n,r)},e})(J);var ml=(function(t){tt(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:as},e})(nt);var ps={now:function(){return(ps.delegate||Date).now()},delegate:void 0};var Zr=(function(t){tt(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=ps);var i=t.call(this)||this;return i._bufferSize=n,i._windowTime=r,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,n),i._windowTime=Math.max(1,r),i}return e.prototype.next=function(n){var r=this,o=r.isStopped,i=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;o||(i.push(n),!s&&i.push(a.now()+l)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,i=o._infiniteTimeWindow,s=o._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=i?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,i=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<i.length&&i.splice(0,i.length-a),!s){for(var l=o.now(),c=0,p=1;p<i.length&&i[p]<=l;p+=2)c=p;c&&i.splice(0,c+1)}},e})(nt);var Kr=new J(function(t){return t.complete()});function gl(t){return t&&G(t.schedule)}function Zf(t){return t[t.length-1]}function vl(t){return gl(Zf(t))?t.pop():void 0}var Yr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function qr(t){return G(t?.then)}function Jr(t){return G(t[xn])}function Qr(t){return Symbol.asyncIterator&&G(t?.[Symbol.asyncIterator])}function eo(t){return new TypeError("You provided "+(t!==null&&typeof t=="object"?"an invalid object":"'"+t+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Kf(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var to=Kf();function no(t){return G(t?.[to])}function ro(t){return sl(this,arguments,function(){var n,r,o,i;return $r(this,function(s){switch(s.label){case 0:n=t.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,Bt(n.read())];case 3:return r=s.sent(),o=r.value,i=r.done,i?[4,Bt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Bt(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function oo(t){return G(t?.getReader)}function me(t){if(t instanceof J)return t;if(t!=null){if(Jr(t))return Yf(t);if(Yr(t))return qf(t);if(qr(t))return Jf(t);if(Qr(t))return yl(t);if(no(t))return Qf(t);if(oo(t))return eh(t)}throw eo(t)}function Yf(t){return new J(function(e){var n=t[xn]();if(G(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function qf(t){return new J(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Jf(t){return new J(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,jr)})}function Qf(t){return new J(function(e){var n,r;try{for(var o=pt(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function yl(t){return new J(function(e){th(t,e).catch(function(n){return e.error(n)})})}function eh(t){return yl(ro(t))}function th(t,e){var n,r,o,i;return il(this,void 0,void 0,function(){var s,a;return $r(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=al(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(s=r.value,e.next(s),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),o={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function De(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var i=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(i),!o)return i}function io(t,e){return e===void 0&&(e=0),ue(function(n,r){n.subscribe(he(r,function(o){return De(r,t,function(){return r.next(o)},e)},function(){return De(r,t,function(){return r.complete()},e)},function(o){return De(r,t,function(){return r.error(o)},e)}))})}function so(t,e){return e===void 0&&(e=0),ue(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function bl(t,e){return me(t).pipe(so(e),io(e))}function xl(t,e){return me(t).pipe(so(e),io(e))}function El(t,e){return new J(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Tl(t,e){return new J(function(n){var r;return De(n,e,function(){r=t[to](),De(n,e,function(){var o,i,s;try{o=r.next(),i=o.value,s=o.done}catch(a){n.error(a);return}s?n.complete():n.next(i)},0,!0)}),function(){return G(r?.return)&&r.return()}})}function ao(t,e){if(!t)throw new Error("Iterable cannot be null");return new J(function(n){De(n,e,function(){var r=t[Symbol.asyncIterator]();De(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function Sl(t,e){return ao(ro(t),e)}function _l(t,e){if(t!=null){if(Jr(t))return bl(t,e);if(Yr(t))return El(t,e);if(qr(t))return xl(t,e);if(Qr(t))return ao(t,e);if(no(t))return Tl(t,e);if(oo(t))return Sl(t,e)}throw eo(t)}function Vt(t,e){return e?_l(t,e):me(t)}function te(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=vl(t);return Vt(t,n)}function Q(t,e){var n=G(t)?t:function(){return t},r=function(o){return o.error(n())};return new J(e?function(o){return e.schedule(r,0,o)}:r)}var wl=gn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function lo(t,e){var n=typeof e=="object";return new Promise(function(r,o){var i=!1,s;t.subscribe({next:function(a){s=a,i=!0},error:o,complete:function(){i?r(s):n?r(e.defaultValue):o(new wl)}})})}function Wt(t,e){return ue(function(n,r){var o=0;n.subscribe(he(r,function(i){r.next(t.call(e,i,o++))}))})}function Al(t,e,n,r,o,i,s,a){var l=[],c=0,p=0,m=!1,x=function(){m&&!l.length&&!c&&e.complete()},f=function(g){return c<r?h(g):l.push(g)},h=function(g){i&&e.next(g),c++;var T=!1;me(n(g,p++)).subscribe(he(e,function(_){o?.(_),i?f(_):e.next(_)},function(){T=!0},void 0,function(){if(T)try{c--;for(var _=function(){var b=l.shift();s?De(e,s,function(){return h(b)}):h(b)};l.length&&c<r;)_();x()}catch(b){e.error(b)}}))};return t.subscribe(he(e,f,function(){m=!0,x()})),function(){a?.()}}function ke(t,e,n){return n===void 0&&(n=1/0),G(e)?ke(function(r,o){return Wt(function(i,s){return e(r,i,o,s)})(me(t(r,o)))},n):(typeof e=="number"&&(n=e),ue(function(r,o){return Al(r,o,t,n)}))}function fs(t){return t===void 0&&(t=1/0),ke(En,t)}function co(t){return new J(function(e){me(t()).subscribe(e)})}function Xn(t){return ue(function(e,n){var r=null,o=!1,i;r=e.subscribe(he(n,void 0,void 0,function(s){i=me(t(s,Xn(t)(e))),r?(r.unsubscribe(),r=null,i.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,i.subscribe(n))})}function uo(t,e){return G(e)?ke(t,e,1):ke(t,1)}function hs(t){return ue(function(e,n){var r=!1;e.subscribe(he(n,function(o){r=!0,n.next(o)},function(){r||n.next(t),n.complete()}))})}function Xt(t){return ue(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function ms(t,e){return ue(function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(he(r,function(l){o?.unsubscribe();var c=0,p=i++;me(t(l,p)).subscribe(o=he(r,function(m){return r.next(e?e(l,m,p,c++):m)},function(){o=null,a()}))},function(){s=!0,a()}))})}function po(t){return ue(function(e,n){me(t).subscribe(he(n,function(){return n.complete()},Vn)),!n.closed&&e.subscribe(n)})}function gs(t,e,n){var r=G(t)||e||n?{next:t,error:e,complete:n}:t;return r?ue(function(o,i){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;o.subscribe(he(i,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),i.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),i.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),i.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):En}function kl(t){return` \r
5
+ `.indexOf(t)>=0}function fo(t){for(var e=["topLevel"],n=0,r,o,i,s=function(b){return e.push(b)},a=function(b){return e[e.length-1]=b},l=function(b){r==null&&(r=n,o=e.length,i=b)},c=function(b){b===i&&(r=void 0,o=void 0,i=void 0)},p=function(){return e.pop()},m=function(){return n--},x=function(b){if("0"<=b&&b<="9"){s("number");return}switch(b){case'"':s("string");return;case"-":s("numberNeedsDigit");return;case"t":s("true");return;case"f":s("false");return;case"n":s("null");return;case"[":s("arrayNeedsValue");return;case"{":s("objectNeedsKey");return}},f=t.length;n<f;n++){var h=t[n];switch(e[e.length-1]){case"topLevel":x(h);break;case"string":switch(h){case'"':p();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":h==="u"?s("stringUnicode"):(c("stringEscape"),p());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),p());break;case"number":h==="."?a("numberNeedsDigit"):h==="e"||h==="E"?a("numberNeedsExponent"):(h<"0"||h>"9")&&(m(),p());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(h==="+"||h==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(h<"a"||h>"z")&&(m(),p());break;case"arrayNeedsValue":h==="]"?p():kl(h)||(c("collectionItem"),a("arrayNeedsComma"),x(h));break;case"arrayNeedsComma":h==="]"?p():h===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":h==="}"?p():h==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":h===":"&&a("objectNeedsValue");break;case"objectNeedsValue":kl(h)||(c("collectionItem"),a("objectNeedsComma"),x(h));break;case"objectNeedsComma":h==="}"?p():h===","&&(l("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var g=[r!=null?t.slice(0,r):t],T=function(b){return g.push(b.slice(t.length-t.lastIndexOf(b[0])))},_=e.length-1;_>=0;_--)switch(e[_]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":T("true");break;case"false":T("false");break;case"null":T("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function Cl(){let t=0,e=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function mo(t,e,n){for(let i=0;i<28;i=i+7){let s=t>>>i,a=!(!(s>>>7)&&e==0),l=(a?s|128:s)&255;if(n.push(l),!a)return}let r=t>>>28&15|(e&7)<<4,o=e>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let i=3;i<31;i=i+7){let s=e>>>i,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var ho=4294967296;function vs(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function i(s,a){let l=Number(t.slice(s,a));o*=n,r=r*n+l,r>=ho&&(o=o+(r/ho|0),r=r%ho)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),e?Rl(r,o):bs(r,o)}function Nl(t,e){let n=bs(t,e),r=n.hi&2147483648;r&&(n=Rl(n.lo,n.hi));let o=ys(n.lo,n.hi);return r?"-"+o:o}function ys(t,e){if({lo:t,hi:e}=nh(t,e),e<=2097151)return String(ho*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,o=e>>16&65535,i=n+r*6777216+o*6710656,s=r+o*8147497,a=o*2,l=1e7;return i>=l&&(s+=Math.floor(i/l),i%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Il(s)+Il(i)}function nh(t,e){return{lo:t>>>0,hi:e>>>0}}function bs(t,e){return{lo:t|0,hi:e|0}}function Rl(t,e){return e=~e,t?t=~t+1:e+=1,bs(t,e)}var Il=t=>{let e=String(t);return"0000000".slice(e.length)+e};function xs(t,e){if(t>=0){for(;t>127;)e.push(t&127|128),t=t>>>7;e.push(t)}else{for(let n=0;n<9;n++)e.push(t&127|128),t=t>>7;e.push(1)}}function Ol(){let t=this.buf[this.pos++],e=t&127;if((t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<7,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<14,(t&128)==0)return this.assertBounds(),e;if(t=this.buf[this.pos++],e|=(t&127)<<21,(t&128)==0)return this.assertBounds(),e;t=this.buf[this.pos++],e|=(t&15)<<28;for(let n=5;(t&128)!==0&&n<10;n++)t=this.buf[this.pos++];if((t&128)!=0)throw new Error("invalid varint");return this.assertBounds(),e>>>0}var je=rh();function rh(){let t=new DataView(new ArrayBuffer(8));if(typeof BigInt=="function"&&typeof t.getBigInt64=="function"&&typeof t.getBigUint64=="function"&&typeof t.setBigInt64=="function"&&typeof t.setBigUint64=="function"&&(!!globalThis.Deno||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),o=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>r||a<n)throw new Error(`invalid int64: ${s}`);return a},uParse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>i||a<o)throw new Error(`invalid uint64: ${s}`);return a},enc(s){return t.setBigInt64(0,this.parse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(s){return t.setBigInt64(0,this.uParse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),Ml(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),Ll(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Ml(n),vs(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),Ll(n),vs(n)},dec(n,r){return Nl(n,r)},uDec(n,r){return ys(n,r)}}}function Ml(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function Ll(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var Es=Symbol.for("@bufbuild/protobuf/text-encoding");function Ts(){if(globalThis[Es]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[Es]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[Es]}var Et;(function(t){t[t.Varint=0]="Varint",t[t.Bit64=1]="Bit64",t[t.LengthDelimited=2]="LengthDelimited",t[t.StartGroup=3]="StartGroup",t[t.EndGroup=4]="EndGroup",t[t.Bit32=5]="Bit32"})(Et||(Et={}));var oh=34028234663852886e22,ih=-34028234663852886e22,sh=4294967295,ah=2147483647,lh=-2147483648,P=class{constructor(e=Ts().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let o=0;o<this.chunks.length;o++)e+=this.chunks[o].length;let n=new Uint8Array(e),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Pl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Ss(e),xs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let n=this.encodeUtf8(e);return this.uint32(n.byteLength),this.raw(n)}float(e){ch(e);let n=new Uint8Array(4);return new DataView(n.buffer).setFloat32(0,e,!0),this.raw(n)}double(e){let n=new Uint8Array(8);return new DataView(n.buffer).setFloat64(0,e,!0),this.raw(n)}fixed32(e){Pl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Ss(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Ss(e),e=(e<<1^e>>31)>>>0,xs(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=je.enc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=je.uEnc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(e){let n=je.enc(e);return mo(n.lo,n.hi,this.buf),this}sint64(e){let n=je.enc(e),r=n.hi>>31,o=n.lo<<1^r,i=(n.hi<<1|n.lo>>>31)^r;return mo(o,i,this.buf),this}uint64(e){let n=je.uEnc(e);return mo(n.lo,n.hi,this.buf),this}},S=class{constructor(e,n=Ts().decodeUtf8){this.decodeUtf8=n,this.varint64=Cl,this.uint32=Ol,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,i=n&7;if(o<=0||i>5)throw new Error("illegal tag: field no "+o+" wire type "+i);return[o,i]}skip(e,n){let r=this.pos;switch(e){case Et.Varint:for(;this.buf[this.pos++]&128;);break;case Et.Bit64:this.pos+=4;case Et.Bit32:this.pos+=4;break;case Et.LengthDelimited:let o=this.uint32();this.pos+=o;break;case Et.StartGroup:for(;;){let[i,s]=this.tag();if(s===Et.EndGroup){if(n!==void 0&&i!==n)throw new Error("invalid end group tag");break}this.skip(s,i)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return je.dec(...this.varint64())}uint64(){return je.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,je.dec(e,n)}bool(){let[e,n]=this.varint64();return e!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return je.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return je.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),n=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(n,n+e)}string(e){return this.decodeUtf8(this.bytes(),e)}};function Ss(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid int32: "+typeof t);if(!Number.isInteger(t)||t>ah||t<lh)throw new Error("invalid int32: "+t)}function Pl(t){if(typeof t=="string")t=Number(t);else if(typeof t!="number")throw new Error("invalid uint32: "+typeof t);if(!Number.isInteger(t)||t>sh||t<0)throw new Error("invalid uint32: "+t)}function ch(t){if(typeof t=="string"){let e=t;if(t=Number(t),Number.isNaN(t)&&e!=="NaN")throw new Error("invalid float32: "+e)}else if(typeof t!="number")throw new Error("invalid float32: "+typeof t);if(Number.isFinite(t)&&(t>oh||t<ih))throw new Error("invalid float32: "+t)}var uh=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function _s(){return{fields:{}}}var Zn={encode(t,e=new P){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&ks.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=_s();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:{if(i!==10)break;let s=ks.decode(n,n.uint32());s.value!==void 0&&(o.fields[s.key]=s.value);continue}}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Zn.fromPartial(t??{})},fromPartial(t){let e=_s();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=_s();if(t!==void 0)for(let n of Object.keys(t))e.fields[n]=t[n];return e},unwrap(t){let e={};if(t.fields)for(let n of Object.keys(t.fields))e[n]=t.fields[n];return e}};function Dl(){return{key:"",value:void 0}}var ks={encode(t,e=new P){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Dl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.key=n.string();continue;case 2:if(i!==18)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ks.fromPartial(t??{})},fromPartial(t){let e=Dl();return e.key=t.key??"",e.value=t.value??void 0,e}};function ws(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var N={encode(t,e=new P){return t.nullValue!==void 0&&e.uint32(8).int32(t.nullValue),t.numberValue!==void 0&&e.uint32(17).double(t.numberValue),t.stringValue!==void 0&&e.uint32(26).string(t.stringValue),t.boolValue!==void 0&&e.uint32(32).bool(t.boolValue),t.structValue!==void 0&&Zn.encode(Zn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Kn.encode(Kn.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=ws();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.nullValue=n.int32();continue;case 2:if(i!==17)break;o.numberValue=n.double();continue;case 3:if(i!==26)break;o.stringValue=n.string();continue;case 4:if(i!==32)break;o.boolValue=n.bool();continue;case 5:if(i!==42)break;o.structValue=Zn.unwrap(Zn.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.listValue=Kn.unwrap(Kn.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return N.fromPartial(t??{})},fromPartial(t){let e=ws();return e.nullValue=t.nullValue??void 0,e.numberValue=t.numberValue??void 0,e.stringValue=t.stringValue??void 0,e.boolValue=t.boolValue??void 0,e.structValue=t.structValue??void 0,e.listValue=t.listValue??void 0,e},wrap(t){let e=ws();if(t===null)e.nullValue=uh.NULL_VALUE;else if(typeof t=="boolean")e.boolValue=t;else if(typeof t=="number")e.numberValue=t;else if(typeof t=="string")e.stringValue=t;else if(globalThis.Array.isArray(t))e.listValue=t;else if(typeof t=="object")e.structValue=t;else if(typeof t<"u")throw new globalThis.Error("Unsupported any value type: "+typeof t);return e},unwrap(t){if(t.stringValue!==void 0)return t.stringValue;if(t?.numberValue!==void 0)return t.numberValue;if(t?.boolValue!==void 0)return t.boolValue;if(t?.structValue!==void 0)return t.structValue;if(t?.listValue!==void 0)return t.listValue;if(t?.nullValue!==void 0)return null}};function As(){return{values:[]}}var Kn={encode(t,e=new P){for(let n of t.values)N.encode(N.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=As();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.values.push(N.unwrap(N.decode(n,n.uint32())));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Kn.fromPartial(t??{})},fromPartial(t){let e=As();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=As();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},dh=(function(t){return t[t.ADD=0]="ADD",t[t.REMOVE=1]="REMOVE",t[t.REPLACE=2]="REPLACE",t[t.MOVE=3]="MOVE",t[t.COPY=4]="COPY",t[t.TEST=5]="TEST",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Ul(){return{op:0,path:"",from:void 0,value:void 0}}var vo={encode(t,e=new P){return t.op!==0&&e.uint32(8).int32(t.op),t.path!==""&&e.uint32(18).string(t.path),t.from!==void 0&&e.uint32(26).string(t.from),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Ul();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.op=n.int32();continue;case 2:if(i!==18)break;o.path=n.string();continue;case 3:if(i!==26)break;o.from=n.string();continue;case 4:if(i!==34)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return vo.fromPartial(t??{})},fromPartial(t){let e=Ul();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Gl(){return{id:"",type:"",function:void 0}}var yo={encode(t,e=new P){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&bo.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Gl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.type=n.string();continue;case 3:if(i!==26)break;o.function=bo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return yo.fromPartial(t??{})},fromPartial(t){let e=Gl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?bo.fromPartial(t.function):void 0,e}};function Hl(){return{name:"",arguments:""}}var bo={encode(t,e=new P){return t.name!==""&&e.uint32(10).string(t.name),t.arguments!==""&&e.uint32(18).string(t.arguments),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Hl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.name=n.string();continue;case 2:if(i!==18)break;o.arguments=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return bo.fromPartial(t??{})},fromPartial(t){let e=Hl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Fl(){return{value:"",mimeType:""}}var xo={encode(t,e=new P){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==""&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Fl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return xo.fromPartial(t??{})},fromPartial(t){let e=Fl();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function $l(){return{value:"",mimeType:void 0}}var Eo={encode(t,e=new P){return t.value!==""&&e.uint32(10).string(t.value),t.mimeType!==void 0&&e.uint32(18).string(t.mimeType),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=$l();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Eo.fromPartial(t??{})},fromPartial(t){let e=$l();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function zl(){return{data:void 0,url:void 0}}var Ne={encode(t,e=new P){return t.data!==void 0&&xo.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Eo.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=zl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.data=xo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.url=Eo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ne.fromPartial(t??{})},fromPartial(t){let e=zl();return e.data=t.data!==void 0&&t.data!==null?xo.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Eo.fromPartial(t.url):void 0,e}};function Bl(){return{text:""}}var To={encode(t,e=new P){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Bl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return To.fromPartial(t??{})},fromPartial(t){let e=Bl();return e.text=t.text??"",e}};function jl(){return{source:void 0,metadata:void 0}}var So={encode(t,e=new P){return t.source!==void 0&&Ne.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=jl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Ne.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return So.fromPartial(t??{})},fromPartial(t){let e=jl();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Vl(){return{source:void 0,metadata:void 0}}var _o={encode(t,e=new P){return t.source!==void 0&&Ne.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Vl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Ne.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return _o.fromPartial(t??{})},fromPartial(t){let e=Vl();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Wl(){return{source:void 0,metadata:void 0}}var wo={encode(t,e=new P){return t.source!==void 0&&Ne.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Wl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Ne.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return wo.fromPartial(t??{})},fromPartial(t){let e=Wl();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Xl(){return{source:void 0,metadata:void 0}}var Ao={encode(t,e=new P){return t.source!==void 0&&Ne.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Xl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Ne.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ao.fromPartial(t??{})},fromPartial(t){let e=Xl();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Zl(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var ko={encode(t,e=new P){return t.text!==void 0&&To.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&So.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&_o.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&wo.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Ao.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Zl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=To.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.image=So.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.audio=_o.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.video=wo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.document=Ao.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ko.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.text=t.text!==void 0&&t.text!==null?To.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?So.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?_o.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?wo.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Ao.fromPartial(t.document):void 0,e}};function Kl(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Io={encode(t,e=new P){t.id!==""&&e.uint32(10).string(t.id),t.role!==""&&e.uint32(18).string(t.role),t.content!==void 0&&e.uint32(26).string(t.content),t.name!==void 0&&e.uint32(34).string(t.name);for(let n of t.toolCalls)yo.encode(n,e.uint32(42).fork()).join();t.toolCallId!==void 0&&e.uint32(50).string(t.toolCallId),t.error!==void 0&&e.uint32(58).string(t.error);for(let n of t.contentParts)ko.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Kl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.role=n.string();continue;case 3:if(i!==26)break;o.content=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue;case 5:if(i!==42)break;o.toolCalls.push(yo.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.toolCallId=n.string();continue;case 7:if(i!==58)break;o.error=n.string();continue;case 8:if(i!==66)break;o.contentParts.push(ko.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Io.fromPartial(t??{})},fromPartial(t){let e=Kl();return e.id=t.id??"",e.role=t.role??"",e.content=t.content??void 0,e.name=t.name??void 0,e.toolCalls=t.toolCalls?.map(n=>yo.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>ko.fromPartial(n))||[],e}};function Yl(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Co={encode(t,e=new P){return t.id!==""&&e.uint32(10).string(t.id),t.reason!==""&&e.uint32(18).string(t.reason),t.message!==void 0&&e.uint32(26).string(t.message),t.toolCallId!==void 0&&e.uint32(34).string(t.toolCallId),t.responseSchema!==void 0&&N.encode(N.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&N.encode(N.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Yl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.reason=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue;case 4:if(i!==34)break;o.toolCallId=n.string();continue;case 5:if(i!==42)break;o.responseSchema=N.unwrap(N.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.expiresAt=n.string();continue;case 7:if(i!==58)break;o.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Co.fromPartial(t??{})},fromPartial(t){let e=Yl();return e.id=t.id??"",e.reason=t.reason??"",e.message=t.message??void 0,e.toolCallId=t.toolCallId??void 0,e.responseSchema=t.responseSchema??void 0,e.expiresAt=t.expiresAt??void 0,e.metadata=t.metadata??void 0,e}},ph=(function(t){return t[t.TEXT_MESSAGE_START=0]="TEXT_MESSAGE_START",t[t.TEXT_MESSAGE_CONTENT=1]="TEXT_MESSAGE_CONTENT",t[t.TEXT_MESSAGE_END=2]="TEXT_MESSAGE_END",t[t.TOOL_CALL_START=3]="TOOL_CALL_START",t[t.TOOL_CALL_ARGS=4]="TOOL_CALL_ARGS",t[t.TOOL_CALL_END=5]="TOOL_CALL_END",t[t.STATE_SNAPSHOT=6]="STATE_SNAPSHOT",t[t.STATE_DELTA=7]="STATE_DELTA",t[t.MESSAGES_SNAPSHOT=8]="MESSAGES_SNAPSHOT",t[t.RAW=9]="RAW",t[t.CUSTOM=10]="CUSTOM",t[t.RUN_STARTED=11]="RUN_STARTED",t[t.RUN_FINISHED=12]="RUN_FINISHED",t[t.RUN_ERROR=13]="RUN_ERROR",t[t.STEP_STARTED=14]="STEP_STARTED",t[t.STEP_FINISHED=15]="STEP_FINISHED",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function ql(){return{type:0,timestamp:void 0,rawEvent:void 0}}var R={encode(t,e=new P){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&N.encode(N.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=ql();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.type=n.int32();continue;case 2:if(i!==16)break;o.timestamp=fh(n.int64());continue;case 3:if(i!==26)break;o.rawEvent=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=ql();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function Jl(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var No={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.name!==void 0&&e.uint32(34).string(t.name),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Jl();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return No.fromPartial(t??{})},fromPartial(t){let e=Jl();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function Ql(){return{baseEvent:void 0,messageId:"",delta:""}}var Ro={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=Ql();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ro.fromPartial(t??{})},fromPartial(t){let e=Ql();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function ec(){return{baseEvent:void 0,messageId:""}}var Oo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=ec();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Oo.fromPartial(t??{})},fromPartial(t){let e=ec();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function tc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Mo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.toolCallName!==""&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=tc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Mo.fromPartial(t??{})},fromPartial(t){let e=tc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function nc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Lo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),t.delta!==""&&e.uint32(26).string(t.delta),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=nc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=nc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function rc(){return{baseEvent:void 0,toolCallId:""}}var Po={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=rc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Po.fromPartial(t??{})},fromPartial(t){let e=rc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function oc(){return{baseEvent:void 0,snapshot:void 0}}var Do={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&N.encode(N.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=oc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.snapshot=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Do.fromPartial(t??{})},fromPartial(t){let e=oc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function ic(){return{baseEvent:void 0,delta:[]}}var Uo={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)vo.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=ic();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.delta.push(vo.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Uo.fromPartial(t??{})},fromPartial(t){let e=ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>vo.fromPartial(n))||[],e}};function sc(){return{baseEvent:void 0,messages:[]}}var Go={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Io.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=sc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messages.push(Io.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Io.fromPartial(n))||[],e}};function ac(){return{baseEvent:void 0,event:void 0,source:void 0}}var Ho={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&N.encode(N.wrap(t.event),e.uint32(18).fork()).join(),t.source!==void 0&&e.uint32(26).string(t.source),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=ac();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.event=N.unwrap(N.decode(n,n.uint32()));continue;case 3:if(i!==26)break;o.source=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ho.fromPartial(t??{})},fromPartial(t){let e=ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function lc(){return{baseEvent:void 0,name:"",value:void 0}}var Fo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&N.encode(N.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.name=n.string();continue;case 3:if(i!==26)break;o.value=N.unwrap(N.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function cc(){return{baseEvent:void 0,threadId:"",runId:""}}var $o={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=cc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return $o.fromPartial(t??{})},fromPartial(t){let e=cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function uc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var zo={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.threadId!==""&&e.uint32(18).string(t.threadId),t.runId!==""&&e.uint32(26).string(t.runId),t.result!==void 0&&N.encode(N.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Co.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=uc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue;case 4:if(i!==34)break;o.result=N.unwrap(N.decode(n,n.uint32()));continue;case 5:if(i!==42)break;o.outcome=n.string();continue;case 6:if(i!==50)break;o.interrupts.push(Co.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return zo.fromPartial(t??{})},fromPartial(t){let e=uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e.result=t.result??void 0,e.outcome=t.outcome??"",e.interrupts=t.interrupts?.map(n=>Co.fromPartial(n))||[],e}};function dc(){return{baseEvent:void 0,code:void 0,message:""}}var Bo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.code!==void 0&&e.uint32(18).string(t.code),t.message!==""&&e.uint32(26).string(t.message),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.code=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Bo.fromPartial(t??{})},fromPartial(t){let e=dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function pc(){return{baseEvent:void 0,stepName:""}}var jo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return jo.fromPartial(t??{})},fromPartial(t){let e=pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function fc(){return{baseEvent:void 0,stepName:""}}var Vo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=fc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Vo.fromPartial(t??{})},fromPartial(t){let e=fc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function hc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var Wo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==void 0&&e.uint32(18).string(t.messageId),t.role!==void 0&&e.uint32(26).string(t.role),t.delta!==void 0&&e.uint32(34).string(t.delta),t.name!==void 0&&e.uint32(42).string(t.name),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=hc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.delta=n.string();continue;case 5:if(i!==42)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Wo.fromPartial(t??{})},fromPartial(t){let e=hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??void 0,e.role=t.role??void 0,e.delta=t.delta??void 0,e.name=t.name??void 0,e}};function mc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Xo={encode(t,e=new P){return t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==void 0&&e.uint32(18).string(t.toolCallId),t.toolCallName!==void 0&&e.uint32(26).string(t.toolCallName),t.parentMessageId!==void 0&&e.uint32(34).string(t.parentMessageId),t.delta!==void 0&&e.uint32(42).string(t.delta),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=mc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=R.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue;case 5:if(i!==42)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Xo.fromPartial(t??{})},fromPartial(t){let e=mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??void 0,e.toolCallName=t.toolCallName??void 0,e.parentMessageId=t.parentMessageId??void 0,e.delta=t.delta??void 0,e}};function gc(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0}}var vc={encode(t,e=new P){return t.textMessageStart!==void 0&&No.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Ro.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Oo.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Mo.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Lo.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Po.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Do.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Uo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Go.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Ho.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Fo.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&$o.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&zo.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&Bo.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&jo.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&Vo.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&Wo.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&Xo.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof S?t:new S(t),r=e===void 0?n.len:n.pos+e,o=gc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.textMessageStart=No.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.textMessageContent=Ro.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.textMessageEnd=Oo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.toolCallStart=Mo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.toolCallArgs=Lo.decode(n,n.uint32());continue;case 6:if(i!==50)break;o.toolCallEnd=Po.decode(n,n.uint32());continue;case 7:if(i!==58)break;o.stateSnapshot=Do.decode(n,n.uint32());continue;case 8:if(i!==66)break;o.stateDelta=Uo.decode(n,n.uint32());continue;case 9:if(i!==74)break;o.messagesSnapshot=Go.decode(n,n.uint32());continue;case 10:if(i!==82)break;o.raw=Ho.decode(n,n.uint32());continue;case 11:if(i!==90)break;o.custom=Fo.decode(n,n.uint32());continue;case 12:if(i!==98)break;o.runStarted=$o.decode(n,n.uint32());continue;case 13:if(i!==106)break;o.runFinished=zo.decode(n,n.uint32());continue;case 14:if(i!==114)break;o.runError=Bo.decode(n,n.uint32());continue;case 15:if(i!==122)break;o.stepStarted=jo.decode(n,n.uint32());continue;case 16:if(i!==130)break;o.stepFinished=Vo.decode(n,n.uint32());continue;case 17:if(i!==138)break;o.textMessageChunk=Wo.decode(n,n.uint32());continue;case 18:if(i!==146)break;o.toolCallChunk=Xo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return vc.fromPartial(t??{})},fromPartial(t){let e=gc();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?No.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Ro.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Oo.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Mo.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Lo.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Po.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Do.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Uo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Go.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Ho.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Fo.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?$o.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?zo.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?Bo.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?jo.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?Vo.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?Wo.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?Xo.fromPartial(t.toolCallChunk):void 0,e}};function fh(t){let e=globalThis.Number(t.toString());if(e>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");if(e<globalThis.Number.MIN_SAFE_INTEGER)throw new globalThis.Error("Value is smaller than Number.MIN_SAFE_INTEGER");return e}var go=t=>{if(!(!t||typeof t!="object")){if(t.data)return{type:"data",value:t.data.value,mimeType:t.data.mimeType};if(t.url)return{type:"url",value:t.url.value,mimeType:t.url.mimeType}}},hh=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:go(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:go(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:go(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:go(t.document.source),metadata:t.document.metadata}}};function yc(t){let e=vc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=ph[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let i=o.contentParts.map(s=>hh(s)).filter(s=>s!==void 0);i.length>0&&(o.content=i)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,i=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:i}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=dh[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Or.parse(n)}var Is="application/vnd.ag-ui.event+proto";var gh=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Cs=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(gh);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},bc=t=>t==="*"||t==="x"||t==="X",xc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},vh=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],yh=(t,e)=>{if(bc(t)||bc(e))return 0;let[n,r]=vh(xc(t),xc(e));return n>r?1:n<r?-1:0},Ns=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=yh(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Yn=(t,e)=>{let n=Cs(t),r=Cs(e),o=n.pop(),i=r.pop(),s=Ns(n,r);return s!==0?s:o&&i?Ns(o.split("."),i.split(".")):o||i?o?-1:1:0};var z=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Re(){return gt()}function Ms(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Ms(e);return t}async function W(t,e,n,r){let o=typeof process<"u"&&process.env!==void 0,i=o&&!!process.env.VITEST_WORKER_ID,s=o&&!!process.env.VITEST_WORKER_ID,a=z(e),l=z(n),c=a,p=l,m;for(let x of t)try{s&&(Ms(c),Ms(p));let f=await r(x,c,p);if(f===void 0)continue;if(f.messages!==void 0&&f.messages!==c&&(c=z(f.messages)),f.state!==void 0&&f.state!==p&&(p=z(f.state)),m=f.stopPropagation,m===!0)break}catch(f){if(s&&f instanceof TypeError){if(i)throw f;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",f)}else i||console.error("Subscriber error:",f);continue}return{...c===a?{}:{messages:s&&Object.isFrozen(c)?z(c):c},...p===l?{}:{state:s&&Object.isFrozen(p)?z(p):p},...m===void 0?{}:{stopPropagation:m}}}function Zo(t){if(!t)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(t===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let e=t.events??!0,n=t.lifecycle??!0,r=t.verbose??!1;return{enabled:e||n,events:e,lifecycle:n,verbose:r}}function qn(t){if(t instanceof Ls)return t;if(t===!0)return new Ls(Zo(!0))}var Ls=class{constructor(t){this.config=t}event(t,e,n,r){this.config.events&&(this.config.verbose?console.debug(`[${t}] ${e}`,typeof n=="string"?n:JSON.stringify(n)):console.debug(`[${t}] ${e}`,r??n))}lifecycle(t,e,n){this.config.lifecycle&&(n?console.debug(`[${t}] ${e}`,n):console.debug(`[${t}] ${e}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function Rs(t){return t.enabled?new Ls(t):void 0}function bh(t,e,n){if(e){let o=t.find(s=>s.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let i={id:o?n:e,role:"assistant",toolCalls:[]};return t.push(i),i}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Ac=(t,e,n,r,o)=>{let i=qn(o),s=z(n.messages),a=z(t.state),l={},c=m=>{m.messages!==void 0&&(s=m.messages,l.messages=m.messages),m.state!==void 0&&(a=m.state,l.state=m.state)},p=()=>{let m=z(l);return l={},m.messages!==void 0||m.state!==void 0?te(m):Kr};return e.pipe(uo(async m=>{let x=await W(r,s,a,(f,h,g)=>f.onEvent?.({event:m,agent:n,input:t,messages:h,state:g}));if(c(x),x.stopPropagation===!0?i?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):i?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),x.stopPropagation===!0)return p();switch(m.type){case v.TEXT_MESSAGE_START:{let f=await W(r,s,a,(h,g,T)=>h.onTextMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:h,role:g="assistant",name:T}=m;if(!s.find(_=>_.id===h)){let _={id:h,role:g,content:"",...T!==void 0&&{name:T}};s.push(_),c({messages:s})}}return p()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=s.find(_=>_.id===f);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let T=await W(r,s,a,(_,b,H)=>_.onTextMessageContentEvent?.({event:m,messages:b,state:H,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(T),T.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,c({messages:s})),p()}case v.TEXT_MESSAGE_END:{let{messageId:f}=m,h=s.find(g=>g.id===f);return h?(c(await W(r,s,a,(g,T,_)=>g.onTextMessageEndEvent?.({event:m,messages:T,state:_,agent:n,input:t,textMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:s,state:a,agent:n,input:t})})),p()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${f}'`),p())}case v.TOOL_CALL_START:{let f=await W(r,s,a,(h,g,T)=>h.onToolCallStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{toolCallId:h,toolCallName:g,parentMessageId:T}=m,_=bh(s,T,h);_.toolCalls??=[],_.toolCalls.push({id:h,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return p()}case v.TOOL_CALL_ARGS:{let{toolCallId:f,delta:h}=m,g=s.find(b=>b.toolCalls?.some(H=>H.id===f));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${f}'`),p();let T=g.toolCalls?.find(b=>b.id===f);if(!T)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${f}'`),p();let _=await W(r,s,a,(b,H,X)=>{let ae=T.function.arguments,ee=T.function.name,ft={};try{ft=fo(ae)}catch{}return b.onToolCallArgsEvent?.({event:m,messages:H,state:X,agent:n,input:t,toolCallBuffer:ae,toolCallName:ee,partialToolCallArgs:ft})});return c(_),_.stopPropagation!==!0&&(T.function.arguments+=h,c({messages:s})),p()}case v.TOOL_CALL_END:{let{toolCallId:f}=m,h=s.find(T=>T.toolCalls?.some(_=>_.id===f));if(!h)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${f}'`),p();let g=h.toolCalls?.find(T=>T.id===f);return g?(c(await W(r,s,a,(T,_,b)=>{let H=g.function.arguments,X=g.function.name,ae={};try{ae=JSON.parse(H)}catch{}return T.onToolCallEndEvent?.({event:m,messages:_,state:b,agent:n,input:t,toolCallName:X,toolCallArgs:ae})})),await Promise.all(r.map(T=>{T.onNewToolCall?.({toolCall:g,messages:s,state:a,agent:n,input:t})})),p()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${f}'`),p())}case v.TOOL_CALL_RESULT:{let f=await W(r,s,a,(h,g,T)=>h.onToolCallResultEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:h,toolCallId:g,content:T,role:_}=m,b={id:h,toolCallId:g,role:_||"tool",content:T};s.push(b),await Promise.all(r.map(H=>{H.onNewMessage?.({message:b,messages:s,state:a,agent:n,input:t})})),c({messages:s})}return p()}case v.STATE_SNAPSHOT:{let f=await W(r,s,a,(h,g,T)=>h.onStateSnapshotEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{snapshot:h}=m;a=h,c({state:a})}return p()}case v.STATE_DELTA:{let f=await W(r,s,a,(h,g,T)=>h.onStateDeltaEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{delta:h}=m;try{a=Fr.applyPatch(a,h,!0,!1).newDocument,c({state:a})}catch(g){let T=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
6
6
  Current state: ${JSON.stringify(a,null,2)}
7
7
  Patch operations: ${JSON.stringify(h,null,2)}
8
- Error: ${T}`)}}return p()}case v.MESSAGES_SNAPSHOT:{let f=await W(r,i,a,(h,g,T)=>h.onMessagesSnapshotEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messages:h}=m,g=new Map(h.map(b=>[b.id,b])),T=b=>b==="activity"||b==="reasoning";i=i.filter(b=>T(b.role)||g.has(b.id)).map(b=>T(b.role)?b:g.get(b.id));let S=new Set(i.map(b=>b.id));for(let b of h)S.has(b.id)||i.push(b);c({messages:i})}return p()}case v.ACTIVITY_SNAPSHOT:{let f=m,h=i.findIndex(H=>H.id===f.messageId),g=h>=0?i[h]:void 0,T=g?.role==="activity"?g:void 0,S=f.replace??!0,b=await W(r,i,a,(H,X,ae)=>H.onActivitySnapshotEvent?.({event:f,messages:X,state:ae,agent:n,input:t,activityMessage:T,existingMessage:g}));if(c(b),b.stopPropagation!==!0){let H={id:f.messageId,role:"activity",activityType:f.activityType,content:z(f.content)},X;h===-1?(i.push(H),X=H):T?S&&(i[h]={...T,activityType:f.activityType,content:z(f.content)}):S&&(i[h]=H,X=H),c({messages:i}),X&&await Promise.all(r.map(ae=>ae.onNewMessage?.({message:X,messages:i,state:a,agent:n,input:t})))}return p()}case v.ACTIVITY_DELTA:{let f=m,h=i.findIndex(b=>b.id===f.messageId);if(h===-1)return p();let g=i[h];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${f.messageId}' is not an activity message`),p();let T=g,S=await W(r,i,a,(b,H,X)=>b.onActivityDeltaEvent?.({event:f,messages:H,state:X,agent:n,input:t,activityMessage:T}));if(c(S),S.stopPropagation!==!0)try{let b=z(T.content??{}),H=Dr.applyPatch(b,f.patch??[],!0,!1).newDocument;i[h]={...T,content:z(H),activityType:f.activityType},c({messages:i})}catch(b){let H=b instanceof Error?b.message:String(b);console.warn(`Failed to apply activity patch for '${f.messageId}': ${H}`)}return p()}case v.RAW:return c(await W(r,i,a,(f,h,g)=>f.onRawEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.CUSTOM:return c(await W(r,i,a,(f,h,g)=>f.onCustomEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.RUN_STARTED:{let f=await W(r,i,a,(h,g,T)=>h.onRunStartedEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let h=m;if(h.input?.messages){for(let g of h.input.messages)i.find(T=>T.id===g.id)||i.push(g);c({messages:i})}}return p()}case v.RUN_FINISHED:{let f=m,h=f.outcome?.type==="interrupt"?{event:f,outcome:"interrupt",interrupts:f.outcome.interrupts}:{event:f,outcome:"success",result:f.result},g=await W(r,i,a,(T,S,b)=>T.onRunFinishedEvent?.({...h,messages:S,state:b,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=h.outcome==="interrupt"?[...h.interrupts]:[]),p()}case v.RUN_ERROR:return c(await W(r,i,a,(f,h,g)=>f.onRunErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.STEP_STARTED:return c(await W(r,i,a,(f,h,g)=>f.onStepStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.STEP_FINISHED:return c(await W(r,i,a,(f,h,g)=>f.onStepFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return p();case v.THINKING_END:return p();case v.THINKING_TEXT_MESSAGE_START:return p();case v.THINKING_TEXT_MESSAGE_CONTENT:return p();case v.THINKING_TEXT_MESSAGE_END:return p();case v.REASONING_START:return c(await W(r,i,a,(f,h,g)=>f.onReasoningStartEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.REASONING_MESSAGE_START:{let f=await W(r,i,a,(h,g,T)=>h.onReasoningMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:h}=m;if(!i.find(g=>g.id===h)){let g={id:h,role:"reasoning",content:""};i.push(g),c({messages:i})}}return p()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=i.find(S=>S.id===f);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let T=await W(r,i,a,(S,b,H)=>S.onReasoningMessageContentEvent?.({event:m,messages:b,state:H,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(T),T.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,c({messages:i})),p()}case v.REASONING_MESSAGE_END:{let{messageId:f}=m,h=i.find(g=>g.id===f);return h?(c(await W(r,i,a,(g,T,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:T,state:S,agent:n,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:i,state:a,agent:n,input:t})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${f}'`),p())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return c(await W(r,i,a,(f,h,g)=>f.onReasoningEndEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:f,entityId:h,encryptedValue:g}=m,T=await W(r,i,a,(S,b,H)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:b,state:H,agent:n,input:t}));if(c(T),T.stopPropagation!==!0){let S=!1;if(f==="tool-call"){for(let b of i)if(b.role==="assistant"&&b.toolCalls){let H=b.toolCalls.find(X=>X.id===h);if(H){H.encryptedValue=g,S=!0;break}}}else{let b=i.find(H=>H.id===h);b?.role!=="activity"&&b&&(b.encryptedValue=g,S=!0)}S&&(l.messages=i)}return p()}}return m.type,p()}),ti(),r.length>0?ni({}):m=>m)},xi=t=>e=>{let n=Zn(t),r=new Map,o=new Map,s=!1,i=!1,a=!1,l=new Map,c=!1,p=!1,m=!1,x=()=>{r.clear(),o.clear(),l.clear(),c=!1,p=!1,s=!1,i=!1,m=!0};return e.pipe(ke(f=>{let h=f.type;if(n?.event("VERIFY","Event:",f,{type:f.type}),i)return Q(()=>new q(`Cannot send event type '${h}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(s&&h!==v.RUN_ERROR&&h!==v.RUN_STARTED)return Q(()=>new q(`Cannot send event type '${h}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(h===v.RUN_STARTED){if(m&&!s)return Q(()=>new q("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));s&&x()}}else if(a=!0,h!==v.RUN_STARTED&&h!==v.RUN_ERROR)return Q(()=>new q("First event must be 'RUN_STARTED'"));switch(h){case v.TEXT_MESSAGE_START:{let g=f.messageId;return r.has(g)?Q(()=>new q(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(g,!0),te(f))}case v.TEXT_MESSAGE_CONTENT:{let g=f.messageId;return r.has(g)?te(f):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case v.TEXT_MESSAGE_END:{let g=f.messageId;return r.has(g)?(r.delete(g),te(f)):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case v.TOOL_CALL_START:{let g=f.toolCallId;return o.has(g)?Q(()=>new q(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),te(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return o.has(g)?te(f):Q(()=>new q(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case v.TOOL_CALL_END:{let g=f.toolCallId;return o.has(g)?(o.delete(g),te(f)):Q(()=>new q(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case v.STEP_STARTED:{let g=f.stepName;return l.has(g)?Q(()=>new q(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),te(f))}case v.STEP_FINISHED:{let g=f.stepName;return l.has(g)?(l.delete(g),te(f)):Q(()=>new q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,te(f);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return s=!0,te(f);case v.RUN_ERROR:return i=!0,te(f);case v.CUSTOM:return te(f);case v.THINKING_TEXT_MESSAGE_START:return c?p?Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case v.THINKING_TEXT_MESSAGE_CONTENT:return p?te(f):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case v.THINKING_TEXT_MESSAGE_END:return p?(p=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case v.THINKING_START:return c?Q(()=>new q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,te(f));case v.THINKING_END:return c?(c=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return te(f)}}))},jt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),ih=t=>so(()=>zt(t())).pipe(ri(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return zt(e.text()).pipe(ke(s=>{let i=s;if(o.includes("application/json"))try{i=JSON.parse(s)}catch{}let a=Error(`HTTP ${e.status}: ${typeof i=="string"?i:JSON.stringify(i)}`);return a.status=e.status,a.payload=i,Q(()=>a)}))}let n={type:jt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new J(o=>(o.next(n),(async()=>{try{for(;;){let{done:s,value:i}=await r.read();if(s)break;let a={type:jt.DATA,data:i};o.next(a)}o.complete()}catch(s){o.error(s)}})(),()=>{r.cancel().catch(s=>{if(s?.name!=="AbortError")throw s})})):Q(()=>Error("Failed to getReader() from response"))})),ah=(t,e)=>{let n=Zn(e),r=new tt,o=new TextDecoder("utf-8",{fatal:!1}),s="";t.subscribe({next:a=>{if(a.type!==jt.HEADERS&&a.type===jt.DATA&&a.data){let l=o.decode(a.data,{stream:!0});s+=l;let c=s.split(/\n\n/);s=c.pop()||"";for(let p of c)i(p)}},error:a=>r.error(a),complete:()=>{s&&(s+=o.decode(),i(s)),r.complete()}});function i(a){let l=a.split(`
8
+ Error: ${T}`)}}return p()}case v.MESSAGES_SNAPSHOT:{let f=await W(r,s,a,(h,g,T)=>h.onMessagesSnapshotEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messages:h}=m,g=new Map(h.map(b=>[b.id,b])),T=b=>b==="activity"||b==="reasoning";s=s.filter(b=>T(b.role)||g.has(b.id)).map(b=>T(b.role)?b:g.get(b.id));let _=new Set(s.map(b=>b.id));for(let b of h)_.has(b.id)||s.push(b);c({messages:s})}return p()}case v.ACTIVITY_SNAPSHOT:{let f=m,h=s.findIndex(H=>H.id===f.messageId),g=h>=0?s[h]:void 0,T=g?.role==="activity"?g:void 0,_=f.replace??!0,b=await W(r,s,a,(H,X,ae)=>H.onActivitySnapshotEvent?.({event:f,messages:X,state:ae,agent:n,input:t,activityMessage:T,existingMessage:g}));if(c(b),b.stopPropagation!==!0){let H={id:f.messageId,role:"activity",activityType:f.activityType,content:z(f.content)},X;h===-1?(s.push(H),X=H):T?_&&(s[h]={...T,activityType:f.activityType,content:z(f.content)}):_&&(s[h]=H,X=H),c({messages:s}),X&&await Promise.all(r.map(ae=>ae.onNewMessage?.({message:X,messages:s,state:a,agent:n,input:t})))}return p()}case v.ACTIVITY_DELTA:{let f=m,h=s.findIndex(b=>b.id===f.messageId);if(h===-1)return p();let g=s[h];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${f.messageId}' is not an activity message`),p();let T=g,_=await W(r,s,a,(b,H,X)=>b.onActivityDeltaEvent?.({event:f,messages:H,state:X,agent:n,input:t,activityMessage:T}));if(c(_),_.stopPropagation!==!0)try{let b=z(T.content??{}),H=Fr.applyPatch(b,f.patch??[],!0,!1).newDocument;s[h]={...T,content:z(H),activityType:f.activityType},c({messages:s})}catch(b){let H=b instanceof Error?b.message:String(b);console.warn(`Failed to apply activity patch for '${f.messageId}': ${H}`)}return p()}case v.RAW:return c(await W(r,s,a,(f,h,g)=>f.onRawEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.CUSTOM:return c(await W(r,s,a,(f,h,g)=>f.onCustomEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.RUN_STARTED:{let f=await W(r,s,a,(h,g,T)=>h.onRunStartedEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let h=m;if(h.input?.messages){for(let g of h.input.messages)s.find(T=>T.id===g.id)||s.push(g);c({messages:s})}}return p()}case v.RUN_FINISHED:{let f=m,h=f.outcome?.type==="interrupt"?{event:f,outcome:"interrupt",interrupts:f.outcome.interrupts}:{event:f,outcome:"success",result:f.result},g=await W(r,s,a,(T,_,b)=>T.onRunFinishedEvent?.({...h,messages:_,state:b,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=h.outcome==="interrupt"?[...h.interrupts]:[]),p()}case v.RUN_ERROR:return c(await W(r,s,a,(f,h,g)=>f.onRunErrorEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.STEP_STARTED:return c(await W(r,s,a,(f,h,g)=>f.onStepStartedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.STEP_FINISHED:return c(await W(r,s,a,(f,h,g)=>f.onStepFinishedEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.TEXT_MESSAGE_CHUNK:throw Error("TEXT_MESSAGE_CHUNK must be tranformed before being applied");case v.TOOL_CALL_CHUNK:throw Error("TOOL_CALL_CHUNK must be tranformed before being applied");case v.THINKING_START:return p();case v.THINKING_END:return p();case v.THINKING_TEXT_MESSAGE_START:return p();case v.THINKING_TEXT_MESSAGE_CONTENT:return p();case v.THINKING_TEXT_MESSAGE_END:return p();case v.REASONING_START:return c(await W(r,s,a,(f,h,g)=>f.onReasoningStartEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.REASONING_MESSAGE_START:{let f=await W(r,s,a,(h,g,T)=>h.onReasoningMessageStartEvent?.({event:m,messages:g,state:T,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:h}=m;if(!s.find(g=>g.id===h)){let g={id:h,role:"reasoning",content:""};s.push(g),c({messages:s})}}return p()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:f,delta:h}=m,g=s.find(_=>_.id===f);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${f}'`),p();let T=await W(r,s,a,(_,b,H)=>_.onReasoningMessageContentEvent?.({event:m,messages:b,state:H,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(T),T.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${h}`,c({messages:s})),p()}case v.REASONING_MESSAGE_END:{let{messageId:f}=m,h=s.find(g=>g.id===f);return h?(c(await W(r,s,a,(g,T,_)=>g.onReasoningMessageEndEvent?.({event:m,messages:T,state:_,agent:n,input:t,reasoningMessageBuffer:typeof h.content=="string"?h.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:h,messages:s,state:a,agent:n,input:t})})),p()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${f}'`),p())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return c(await W(r,s,a,(f,h,g)=>f.onReasoningEndEvent?.({event:m,messages:h,state:g,agent:n,input:t}))),p();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:f,entityId:h,encryptedValue:g}=m,T=await W(r,s,a,(_,b,H)=>_.onReasoningEncryptedValueEvent?.({event:m,messages:b,state:H,agent:n,input:t}));if(c(T),T.stopPropagation!==!0){let _=!1;if(f==="tool-call"){for(let b of s)if(b.role==="assistant"&&b.toolCalls){let H=b.toolCalls.find(X=>X.id===h);if(H){H.encryptedValue=g,_=!0;break}}}else{let b=s.find(H=>H.id===h);b?.role!=="activity"&&b&&(b.encryptedValue=g,_=!0)}_&&(l.messages=s)}return p()}}return m.type,p()}),fs(),r.length>0?hs({}):m=>m)},Os=t=>e=>{let n=qn(t),r=new Map,o=new Map,i=!1,s=!1,a=!1,l=new Map,c=!1,p=!1,m=!1,x=()=>{r.clear(),o.clear(),l.clear(),c=!1,p=!1,i=!1,s=!1,m=!0};return e.pipe(ke(f=>{let h=f.type;if(n?.event("VERIFY","Event:",f,{type:f.type}),s)return Q(()=>new q(`Cannot send event type '${h}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(i&&h!==v.RUN_ERROR&&h!==v.RUN_STARTED)return Q(()=>new q(`Cannot send event type '${h}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(h===v.RUN_STARTED){if(m&&!i)return Q(()=>new q("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));i&&x()}}else if(a=!0,h!==v.RUN_STARTED&&h!==v.RUN_ERROR)return Q(()=>new q("First event must be 'RUN_STARTED'"));switch(h){case v.TEXT_MESSAGE_START:{let g=f.messageId;return r.has(g)?Q(()=>new q(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${g}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`)):(r.set(g,!0),te(f))}case v.TEXT_MESSAGE_CONTENT:{let g=f.messageId;return r.has(g)?te(f):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${g}'. Start a text message with 'TEXT_MESSAGE_START' first.`))}case v.TEXT_MESSAGE_END:{let g=f.messageId;return r.has(g)?(r.delete(g),te(f)):Q(()=>new q(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${g}'. A 'TEXT_MESSAGE_START' event must be sent first.`))}case v.TOOL_CALL_START:{let g=f.toolCallId;return o.has(g)?Q(()=>new q(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),te(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return o.has(g)?te(f):Q(()=>new q(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${g}'. Start a tool call with 'TOOL_CALL_START' first.`))}case v.TOOL_CALL_END:{let g=f.toolCallId;return o.has(g)?(o.delete(g),te(f)):Q(()=>new q(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${g}'. A 'TOOL_CALL_START' event must be sent first.`))}case v.STEP_STARTED:{let g=f.stepName;return l.has(g)?Q(()=>new q(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),te(f))}case v.STEP_FINISHED:{let g=f.stepName;return l.has(g)?(l.delete(g),te(f)):Q(()=>new q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,te(f);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return i=!0,te(f);case v.RUN_ERROR:return s=!0,te(f);case v.CUSTOM:return te(f);case v.THINKING_TEXT_MESSAGE_START:return c?p?Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(p=!0,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking step is not in progress. Create one with 'THINKING_START' first."));case v.THINKING_TEXT_MESSAGE_CONTENT:return p?te(f):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_CONTENT' event: No active thinking message found. Start a message with 'THINKING_TEXT_MESSAGE_START' first."));case v.THINKING_TEXT_MESSAGE_END:return p?(p=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_TEXT_MESSAGE_END' event: No active thinking message found. A 'THINKING_TEXT_MESSAGE_START' event must be sent first."));case v.THINKING_START:return c?Q(()=>new q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,te(f));case v.THINKING_END:return c?(c=!1,te(f)):Q(()=>new q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return te(f)}}))},Zt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),xh=t=>co(()=>Vt(t())).pipe(ms(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return Vt(e.text()).pipe(ke(i=>{let s=i;if(o.includes("application/json"))try{s=JSON.parse(i)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,Q(()=>a)}))}let n={type:Zt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new J(o=>(o.next(n),(async()=>{try{for(;;){let{done:i,value:s}=await r.read();if(i)break;let a={type:Zt.DATA,data:s};o.next(a)}o.complete()}catch(i){o.error(i)}})(),()=>{r.cancel().catch(i=>{if(i?.name!=="AbortError")throw i})})):Q(()=>Error("Failed to getReader() from response"))})),Eh=(t,e)=>{let n=qn(e),r=new nt,o=new TextDecoder("utf-8",{fatal:!1}),i="";t.subscribe({next:a=>{if(a.type!==Zt.HEADERS&&a.type===Zt.DATA&&a.data){let l=o.decode(a.data,{stream:!0});i+=l;let c=i.split(/\n\n/);i=c.pop()||"";for(let p of c)s(p)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
9
9
  `),c=[];for(let p of l)p.startsWith("data:")&&c.push(p.slice(5).replace(/^ /,""));if(c.length>0)try{let p=c.join(`
10
- `),m=JSON.parse(p);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(p){r.error(p)}}return r.asObservable()},lh=t=>{let e=new tt,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==jt.HEADERS&&o.type===jt.DATA&&o.data){let s=new Uint8Array(n.length+o.data.length);s.set(n,0),s.set(o.data,n.length),n=s,r()}},error:o=>e.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let s=n.slice(4,o),i=cc(s);e.next(i),n=n.slice(o)}catch(s){let i=s instanceof Error?s.message:String(s);e.error(Error(`Failed to decode protocol buffer message: ${i}`));return}}}return e.asObservable()},ch=(t,e)=>{let n=Zn(e),r=new tt,o=new Vr,s=!1;return t.subscribe({next:i=>{if(o.next(i),i.type===jt.HEADERS&&!s){s=!0;let a=i.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===gi?"protobuf":"sse"}),a===gi?lh(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):ah(o,n).subscribe({next:l=>{try{let c=Ir.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else s||r.error(Error("No headers event received before data events"))},error:i=>{o.error(i),r.error(i)},complete:()=>{o.complete()}}),r.asObservable()},K=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),uh=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),dh=u.object({type:u.literal(K.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),ph=u.object({type:u.literal(K.enum.TextMessageContent),messageId:u.string(),content:u.string()}),fh=u.object({type:u.literal(K.enum.TextMessageEnd),messageId:u.string()}),hh=u.object({type:u.literal(K.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),mh=u.object({type:u.literal(K.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),gh=u.object({type:u.literal(K.enum.ActionExecutionEnd),actionExecutionId:u.string()}),vh=u.object({type:u.literal(K.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),yh=u.object({type:u.literal(K.enum.AgentStateMessage),threadId:u.string(),agentName:u.string(),nodeName:u.string(),runId:u.string(),active:u.boolean(),role:u.string(),state:u.string(),running:u.boolean()}),bh=u.object({type:u.literal(K.enum.MetaEvent),name:uh,value:u.any()}),xh=u.object({type:u.literal(K.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[dh,ph,fh,hh,mh,gh,vh,yh,bh,xh]),u.object({id:u.string(),role:u.string(),content:u.string(),parentMessageId:u.string().optional()}),u.object({id:u.string(),name:u.string(),arguments:u.any(),parentMessageId:u.string().optional()}),u.object({id:u.string(),result:u.any(),actionExecutionId:u.string(),actionName:u.string()});var Eh=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(e.length!==0)return e.join(`
11
- `)},Th=(t,e,n)=>r=>{let o={},s=!0,i=!0,a="",l=null,c=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(ke(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let h=f;return[{type:K.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case v.TEXT_MESSAGE_CONTENT:{let h=f;return[{type:K.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case v.TEXT_MESSAGE_END:{let h=f;return[{type:K.enum.TextMessageEnd,messageId:h.messageId}]}case v.TOOL_CALL_START:{let h=f;return p.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),i=!0,m[h.toolCallId]=h.toolCallName,[{type:K.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case v.TOOL_CALL_ARGS:{let h=f,g=p.find(S=>S.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let T=!1;if(c){let S=c.find(b=>b.tool==g.function.name);if(S)try{let b=JSON.parse(lo(g.function.arguments));S.tool_argument&&S.tool_argument in b?(x({...o,[S.state_key]:b[S.tool_argument]}),T=!0):S.tool_argument||(x({...o,[S.state_key]:b}),T=!0)}catch{}}return[{type:K.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...T?[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:i}]:[]]}case v.TOOL_CALL_END:{let h=f;return[{type:K.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case v.TOOL_CALL_RESULT:{let h=f;return[{type:K.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let h=f;switch(h.name){case"Exit":s=!1;break;case"PredictState":c=h.value;break}return[{type:K.enum.MetaEvent,name:h.name,value:h.value}]}case v.STATE_SNAPSHOT:return x(f.snapshot),[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:i}];case v.STATE_DELTA:{let h=f,g=Dr.applyPatch(o,h.delta,!0,!1);return g?(x(g.newDocument),[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:i}]):[]}case v.MESSAGES_SNAPSHOT:return l=f.messages,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify({...o,...l?{messages:_h(l)}:{}}),active:!1}];case v.RUN_ERROR:{let h=f;return[{type:K.enum.RunError,message:h.message,code:h.code}]}case v.STEP_STARTED:return a=f.stepName,p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:s,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function _h(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Eh(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let s={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(s)}}else if(n.role==="tool"){let r="unknown";for(let s of t)if(s.role==="assistant"&&s.toolCalls?.length){for(let i of s.toolCalls)if(i.id===n.toolCallId){r=i.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var jo=t=>e=>{let n=Zn(t),r,o,s,i,a=()=>{if(!r||i!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return i=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},l=()=>{if(!o||i!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return i=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!s||i!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:s.messageId};return i=void 0,s=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},p=()=>i==="text"?[a()]:i==="tool"?[l()]:i==="reasoning"?[c()]:[];return e.pipe(ke(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...p(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let x=m,f=[];if((i!=="text"||x.messageId!==void 0&&x.messageId!==r?.messageId)&&f.push(...p()),i!=="text"){if(x.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:x.messageId,name:x.name},i="text";let b={type:v.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant",...x.name!==void 0&&{name:x.name}};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_START",b,{messageId:x.messageId})}if(x.delta!==void 0){let b={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:x.delta};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",b,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let h=m,g=[];if((i!=="tool"||h.toolCallId!==void 0&&h.toolCallId!==o?.toolCallId)&&g.push(...p()),i!=="tool"){if(h.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(h.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId},i="tool";let b={type:v.TOOL_CALL_START,toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId};g.push(b),n?.event("TRANSFORM","TOOL_CALL_START",b,{toolCallId:h.toolCallId,toolCallName:h.toolCallName})}if(h.delta!==void 0){let b={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:h.delta};g.push(b),n?.event("TRANSFORM","TOOL_CALL_ARGS",b,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let T=m,S=[];if((i!=="reasoning"||T.messageId&&T.messageId!==s?.messageId)&&S.push(...p()),i!=="reasoning"){if(T.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");s={messageId:T.messageId},i="reasoning";let b={type:v.REASONING_MESSAGE_START,messageId:T.messageId};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_START",b,{messageId:T.messageId})}if(T.delta!==void 0){let b={type:v.REASONING_MESSAGE_CONTENT,messageId:s.messageId,delta:T.delta};S.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",b,{messageId:s.messageId})}return S}return m.type,[]}),Vt(()=>{p()}))};function Sh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}var Wo=class{runNext(t,e){return e.run(t).pipe(jo(!1))}runNextWithState(t,e){let n=z(t.messages||[]),r=z(t.state||{}),o=new Vr;return vc(t,o,e,[]).subscribe(s=>{s.messages!==void 0&&(n=s.messages),s.state!==void 0&&(r=s.state)}),this.runNext(t,e).pipe(io(async s=>(o.next(s),await new Promise(i=>setTimeout(i,0)),{event:s,messages:z(n),state:z(r)})))}},wh=class extends Wo{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Ah(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var kh=class extends Wo{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Ah)};return this.runNext(o,e)}},pc="THINKING_START",fc="THINKING_END",hc="THINKING_TEXT_MESSAGE_START",mc="THINKING_TEXT_MESSAGE_CONTENT",gc="THINKING_TEXT_MESSAGE_END",Ih=class extends Wo{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Bt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case pc:{this.currentReasoningId=Ce();let{title:e,...n}=t;return this.warnAboutTransformation(pc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case hc:return this.currentMessageId=Ce(),this.warnAboutTransformation(hc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case mc:{let{delta:e,...n}=t;return this.warnAboutTransformation(mc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ce(),delta:e}}case gc:{let e=this.currentMessageId??Ce();return this.warnAboutTransformation(gc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case fc:{let e=this.currentReasoningId??Ce();return this.warnAboutTransformation(fc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Ch(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function Nh(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function Rh(t){let e=Ch(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function Oh(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>Nh(r)?Rh(r):r);return{...t,content:n}}var Mh=class extends Wo{run(t,e){let n={...t,messages:t.messages.map(Oh)};return this.runNext(n,e)}},Lh="0.0.54",Ph=class{get maxVersion(){return Lh}get debug(){return this._debug}set debug(t){this._debug=Vo(t),this._debugLogger=bi(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?bi(Vo(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:s}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??ht(),this.messages=z(r??[]),this.state=z(o??{}),this._debug=Vo(s),this._debugLogger=bi(this._debug),Xn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new kh),Xn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Ih),Xn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Mh)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new wh(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),s=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,s),this.activeRunDetach$=new tt;let i;this.activeRunCompletionPromise=new Promise(l=>{i=l}),await oo(Br(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:p=>c.run(p,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),jo(this.debugLogger),xi(this.debugLogger),l=>l.pipe(ao(this.activeRunDetach$)),l=>this.apply(n,l,s),l=>this.processApplyEvents(n,l,s),Vn(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,s))),Vt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=z(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new zs}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??ht();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),s=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,s),this.activeRunDetach$=new tt;let i;this.activeRunCompletionPromise=new Promise(l=>{i=l}),await oo(Br(()=>so(()=>this.connect(n)),jo(this.debugLogger),xi(this.debugLogger),l=>l.pipe(ao(this.activeRunDetach$)),l=>this.apply(n,l,s),l=>this.processApplyEvents(n,l,s),Vn(l=>(this.isRunning=!1,l instanceof zs?jr:this.onError(n,l,s))),Vt(()=>{this.isRunning=!1,this.onFinalize(n,s),i?.(),i=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=z(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return vc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(oi(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=z(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||ht(),tools:z(t?.tools??[]),context:z(t?.context??[]),forwardedProps:z(t?.forwardedProps??{}),state:z(this.state),messages:e,...t?.resume===void 0?{}:{resume:z(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(s=>s.interruptId)),o=this.pendingInterrupts.map(s=>s.id).filter(s=>!r.has(s));if(o.length>0)throw new q(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let s of this.pendingInterrupts)if(Sh(s))throw new q(`Interrupt ${s.id} expired at ${s.expiresAt}`)}let n=await W(e,this.messages,this.state,(r,o,s)=>r.onRunInitialized?.({messages:o,state:s,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return zt(W(n,this.messages,this.state,(r,o,s)=>r.onRunFailed?.({error:e,messages:o,state:s,agent:this,input:t}))).pipe(Bt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(s=>{s.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(s=>{s.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let s=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||s==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await W(e,this.messages,this.state,(r,o,s)=>r.onRunFinalized?.({messages:o,state:s,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=z(this.messages),t.state=z(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=z(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=z(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=z(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??ht();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(jo(this.debugLogger),xi(this.debugLogger),Th(this.threadId,e.runId,this.agentId),n=>n.pipe(Bt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},yc=class extends Ph{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=z(t.headers??{}),this.fetch=t.fetch??fetch}run(t){return ch(ih(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=z(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var Xo=class{element;#e;#t=[];constructor(e){this.#e=e,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.hidden=!0}add(e){let n={localId:Ce(),file:e,status:Ge.UPLOADING,progress:0,ref:null,error:""};this.#t.push(n);let r=this.#o(e);if(r!==null){n.status=Ge.ERROR,n.error=r,this.#r(),this.#e.onChange?.();return}this.#r(),this.#e.onChange?.(),this.#i(n)}readyRefs(){let e=[];for(let n of this.#t)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#t.some(e=>e.status===Ge.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Ge.UPLOADING),this.#r()}clear(){this.#t=[],this.#r()}#o(e){return this.#e.maxBytes>0&&e.size>this.#e.maxBytes?`Too large (max ${xr(this.#e.maxBytes)})`:Dh(this.#e.accept,e)?null:"File type not allowed"}#i(e){e.status=Ge.UPLOADING,e.progress=0,e.error="",this.#r(),this.#e.upload(e.file,n=>{e.progress=n,this.#r()}).then(n=>{e.status=Ge.READY,e.ref=n}).catch(n=>{e.status=Ge.ERROR,e.error=n instanceof Error?n.message:"upload failed"}).finally(()=>{this.#r(),this.#e.onChange?.()})}#a(e){this.#t=this.#t.filter(n=>n!==e),this.#r(),this.#e.onChange?.()}#r(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#n(e))}#n(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`;let r=document.createElement("span");r.className="attachment-chip-icon",r.textContent=Ps(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.textContent=e.file.name,o.title=e.file.name;let s=document.createElement("span");if(s.className="attachment-chip-size",s.textContent=e.status===Ge.ERROR?e.error:xr(e.file.size),n.append(r,o,s),e.status===Ge.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar";let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Ge.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.title="Retry",a.setAttribute("aria-label","Retry upload"),a.textContent="\u21BB",a.addEventListener("click",()=>this.#i(e)),n.appendChild(a)}let i=document.createElement("button");return i.type="button",i.className="attachment-chip-remove",i.title="Remove",i.setAttribute("aria-label","Remove attachment"),i.textContent="\u2715",i.addEventListener("click",()=>this.#a(e)),n.appendChild(i),n}};function Dh(t,e){let n=t.split(",").map(s=>s.trim().toLowerCase()).filter(s=>s!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(s=>s.startsWith(".")?o.endsWith(s):s.endsWith("/*")?r.startsWith(s.slice(0,-1)):r===s)}function bc(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.textContent=e,n}function _i(t,e,n={}){return new Promise(r=>{let o=document.createElement("div");o.className="confirm",o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.setAttribute("aria-label","Confirm action");let s=document.createElement("div");s.className="confirm-body",s.textContent=e.message??`Run \u201C${e.toolName}\u201D?`;let i=document.createElement("pre");i.className="confirm-args",i.textContent=JSON.stringify(e.args,null,2);let a=document.createElement("div");a.className="confirm-actions";let l=bc("cancel","Cancel"),c=bc("confirm","Confirm"),p=!1,m=x=>{p||(p=!0,l.disabled=!0,c.disabled=!0,o.setAttribute("data-resolved",x?"confirmed":"declined"),r(x))};if(l.addEventListener("click",()=>m(!1)),c.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(l,c),o.append(s,i,a),t.appendChild(o),n.signal?.aborted===!0){m(!1);return}c.focus()})}function Si(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function xc(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function Uh(t){if(Array.isArray(t))return t}function Gh(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,s,i,a=[],l=!0,c=!1;try{if(s=(n=n.call(t)).next,e!==0)for(;!(l=(r=s.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(p){c=!0,o=p}finally{try{if(!l&&n.return!=null&&(i=n.return(),Object(i)!==i))return}finally{if(c)throw o}}return a}}function Hh(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
12
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Fh(t,e){return Uh(t)||Gh(t,e)||$h(t,e)||Hh()}function $h(t,e){if(t){if(typeof t=="string")return xc(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?xc(t,e):void 0}}var Mc=Object.entries,Ec=Object.setPrototypeOf,zh=Object.isFrozen,Bh=Object.getPrototypeOf,Vh=Object.getOwnPropertyDescriptor,Se=Object.freeze,Pe=Object.seal,Sn=Object.create,Lc=typeof Reflect<"u"&&Reflect,Ni=Lc.apply,Ri=Lc.construct;Se||(Se=function(e){return e});Pe||(Pe=function(e){return e});Ni||(Ni=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),s=2;s<r;s++)o[s-2]=arguments[s];return e.apply(n,o)});Ri||(Ri=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var En=ue(Array.prototype.forEach),jh=ue(Array.prototype.lastIndexOf),Tc=ue(Array.prototype.pop),Tn=ue(Array.prototype.push),Wh=ue(Array.prototype.splice),_e=Array.isArray,qn=ue(String.prototype.toLowerCase),wi=ue(String.prototype.toString),_c=ue(String.prototype.match),_n=ue(String.prototype.replace),Sc=ue(String.prototype.indexOf),Xh=ue(String.prototype.trim),Zh=ue(Number.prototype.toString),Kh=ue(Boolean.prototype.toString),wc=typeof BigInt>"u"?null:ue(BigInt.prototype.toString),Ac=typeof Symbol>"u"?null:ue(Symbol.prototype.toString),re=ue(Object.prototype.hasOwnProperty),Kn=ue(Object.prototype.toString),be=ue(RegExp.prototype.test),Yn=Yh(TypeError);function ue(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Ni(t,e,r)}}function Yh(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Ri(t,n)}}function D(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:qn;if(Ec&&Ec(t,null),!_e(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let s=n(o);s!==o&&(zh(e)||(e[r]=s),o=s)}t[o]=!0}return t}function qh(t){for(let e=0;e<t.length;e++)re(t,e)||(t[e]=null);return t}function Ee(t){let e=Sn(null);for(let r of Mc(t)){var n=Fh(r,2);let o=n[0],s=n[1];re(t,o)&&(_e(s)?e[o]=qh(s):s&&typeof s=="object"&&s.constructor===Object?e[o]=Ee(s):e[o]=s)}return e}function Jh(t){switch(typeof t){case"string":return t;case"number":return Zh(t);case"boolean":return Kh(t);case"bigint":return wc?wc(t):"0";case"symbol":return Ac?Ac(t):"Symbol()";case"undefined":return Kn(t);case"function":case"object":{if(t===null)return Kn(t);let e=t,n=rt(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:Kn(r)}return Kn(t)}default:return Kn(t)}}function rt(t,e){for(;t!==null;){let r=Vh(t,e);if(r){if(r.get)return ue(r.get);if(typeof r.value=="function")return ue(r.value)}t=Bh(t)}function n(){return null}return n}function Qh(t){try{return be(t,""),!0}catch{return!1}}var kc=Se(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Ai=Se(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),ki=Se(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),em=Se(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Ii=Se(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),tm=Se(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Ic=Se(["#text"]),Cc=Se(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Ci=Se(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Nc=Se(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Zo=Se(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),nm=Pe(/{{[\w\W]*|^[\w\W]*}}/g),rm=Pe(/<%[\w\W]*|^[\w\W]*%>/g),om=Pe(/\${[\w\W]*/g),sm=Pe(/^data-[\-\w.\u00B7-\uFFFF]+$/),im=Pe(/^aria-[\-\w]+$/),Rc=Pe(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),am=Pe(/^(?:\w+script|data):/i),lm=Pe(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),cm=Pe(/^html$/i),um=Pe(/^[a-z][.\w]*(-[.\w]+)+$/i),nt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},dm=function(){return typeof window>"u"?null:window},pm=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let s="dompurify"+(r?"#"+r:"");try{return e.createPolicy(s,{createHTML(i){return i},createScriptURL(i){return i}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},Oc=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Pc(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dm(),e=C=>Pc(C);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==nt.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let s=t.HTMLTemplateElement,i=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let p=t.DOMParser,m=t.trustedTypes,x=a.prototype,f=rt(x,"cloneNode"),h=rt(x,"remove"),g=rt(x,"nextSibling"),T=rt(x,"childNodes"),S=rt(x,"parentNode"),b=rt(x,"shadowRoot"),H=rt(x,"attributes"),X=i&&i.prototype?rt(i.prototype,"nodeType"):null,ae=i&&i.prototype?rt(i.prototype,"nodeName"):null;if(typeof s=="function"){let C=n.createElement("template");C.content&&C.content.ownerDocument&&(n=C.content.ownerDocument)}let ee,dt="",ar=n,is=ar.implementation,oa=ar.createNodeIterator,hu=ar.createDocumentFragment,mu=ar.getElementsByTagName,gu=r.importNode,pe=Oc();e.isSupported=typeof Mc=="function"&&typeof S=="function"&&is&&is.createHTMLDocument!==void 0;let lr=nm,cr=rm,ur=om,vu=sm,yu=im,bu=am,sa=lm,xu=um,ia=Rc,oe=null,as=D({},[...kc,...Ai,...ki,...Ii,...Ic]),le=null,ls=D({},[...Cc,...Ci,...Nc,...Zo]),se=Object.seal(Sn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),kn=null,dr=null,pt=Object.seal(Sn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),aa=!0,cs=!0,la=!1,ca=!0,ft=!1,In=!0,Et=!1,us=!1,ds=!1,Jt=!1,pr=!1,fr=!1,ua=!0,da=!1,pa="user-content-",ps=!0,Cn=!1,Qt={},Ve=null,fs=D({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),fa=null,ha=D({},["audio","video","img","source","image","track"]),hs=null,ma=D({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),hr="http://www.w3.org/1998/Math/MathML",mr="http://www.w3.org/2000/svg",je="http://www.w3.org/1999/xhtml",en=je,ms=!1,gs=null,Eu=D({},[hr,mr,je],wi),vs=D({},["mi","mo","mn","ms","mtext"]),ys=D({},["annotation-xml"]),Tu=D({},["title","style","font","a","script"]),Nn=null,_u=["application/xhtml+xml","text/html"],Su="text/html",ie=null,tn=null,wu=n.createElement("form"),ga=function(d){return d instanceof RegExp||d instanceof Function},bs=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(tn&&tn===d)return;(!d||typeof d!="object")&&(d={}),d=Ee(d),Nn=_u.indexOf(d.PARSER_MEDIA_TYPE)===-1?Su:d.PARSER_MEDIA_TYPE,ie=Nn==="application/xhtml+xml"?wi:qn,oe=re(d,"ALLOWED_TAGS")&&_e(d.ALLOWED_TAGS)?D({},d.ALLOWED_TAGS,ie):as,le=re(d,"ALLOWED_ATTR")&&_e(d.ALLOWED_ATTR)?D({},d.ALLOWED_ATTR,ie):ls,gs=re(d,"ALLOWED_NAMESPACES")&&_e(d.ALLOWED_NAMESPACES)?D({},d.ALLOWED_NAMESPACES,wi):Eu,hs=re(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)?D(Ee(ma),d.ADD_URI_SAFE_ATTR,ie):ma,fa=re(d,"ADD_DATA_URI_TAGS")&&_e(d.ADD_DATA_URI_TAGS)?D(Ee(ha),d.ADD_DATA_URI_TAGS,ie):ha,Ve=re(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)?D({},d.FORBID_CONTENTS,ie):fs,kn=re(d,"FORBID_TAGS")&&_e(d.FORBID_TAGS)?D({},d.FORBID_TAGS,ie):Ee({}),dr=re(d,"FORBID_ATTR")&&_e(d.FORBID_ATTR)?D({},d.FORBID_ATTR,ie):Ee({}),Qt=re(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?Ee(d.USE_PROFILES):d.USE_PROFILES:!1,aa=d.ALLOW_ARIA_ATTR!==!1,cs=d.ALLOW_DATA_ATTR!==!1,la=d.ALLOW_UNKNOWN_PROTOCOLS||!1,ca=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,ft=d.SAFE_FOR_TEMPLATES||!1,In=d.SAFE_FOR_XML!==!1,Et=d.WHOLE_DOCUMENT||!1,Jt=d.RETURN_DOM||!1,pr=d.RETURN_DOM_FRAGMENT||!1,fr=d.RETURN_TRUSTED_TYPE||!1,ds=d.FORCE_BODY||!1,ua=d.SANITIZE_DOM!==!1,da=d.SANITIZE_NAMED_PROPS||!1,ps=d.KEEP_CONTENT!==!1,Cn=d.IN_PLACE||!1,ia=Qh(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Rc,en=typeof d.NAMESPACE=="string"?d.NAMESPACE:je,vs=re(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ee(d.MATHML_TEXT_INTEGRATION_POINTS):D({},["mi","mo","mn","ms","mtext"]),ys=re(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ee(d.HTML_INTEGRATION_POINTS):D({},["annotation-xml"]);let y=re(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ee(d.CUSTOM_ELEMENT_HANDLING):Sn(null);if(se=Sn(null),re(y,"tagNameCheck")&&ga(y.tagNameCheck)&&(se.tagNameCheck=y.tagNameCheck),re(y,"attributeNameCheck")&&ga(y.attributeNameCheck)&&(se.attributeNameCheck=y.attributeNameCheck),re(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(se.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),ft&&(cs=!1),pr&&(Jt=!0),Qt&&(oe=D({},Ic),le=Sn(null),Qt.html===!0&&(D(oe,kc),D(le,Cc)),Qt.svg===!0&&(D(oe,Ai),D(le,Ci),D(le,Zo)),Qt.svgFilters===!0&&(D(oe,ki),D(le,Ci),D(le,Zo)),Qt.mathMl===!0&&(D(oe,Ii),D(le,Nc),D(le,Zo))),pt.tagCheck=null,pt.attributeCheck=null,re(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?pt.tagCheck=d.ADD_TAGS:_e(d.ADD_TAGS)&&(oe===as&&(oe=Ee(oe)),D(oe,d.ADD_TAGS,ie))),re(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?pt.attributeCheck=d.ADD_ATTR:_e(d.ADD_ATTR)&&(le===ls&&(le=Ee(le)),D(le,d.ADD_ATTR,ie))),re(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)&&D(hs,d.ADD_URI_SAFE_ATTR,ie),re(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)&&(Ve===fs&&(Ve=Ee(Ve)),D(Ve,d.FORBID_CONTENTS,ie)),re(d,"ADD_FORBID_CONTENTS")&&_e(d.ADD_FORBID_CONTENTS)&&(Ve===fs&&(Ve=Ee(Ve)),D(Ve,d.ADD_FORBID_CONTENTS,ie)),ps&&(oe["#text"]=!0),Et&&D(oe,["html","head","body"]),oe.table&&(D(oe,["tbody"]),delete kn.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw Yn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Yn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=d.TRUSTED_TYPES_POLICY,dt=ee.createHTML("")}else ee===void 0&&(ee=pm(m,o)),ee!==null&&typeof dt=="string"&&(dt=ee.createHTML(""));(pe.uponSanitizeElement.length>0||pe.uponSanitizeAttribute.length>0)&&oe===as&&(oe=Ee(oe)),pe.uponSanitizeAttribute.length>0&&le===ls&&(le=Ee(le)),Se&&Se(d),tn=d},va=D({},[...Ai,...ki,...em]),ya=D({},[...Ii,...tm]),Au=function(d){let y=S(d);(!y||!y.tagName)&&(y={namespaceURI:en,tagName:"template"});let A=qn(d.tagName),j=qn(y.tagName);return gs[d.namespaceURI]?d.namespaceURI===mr?y.namespaceURI===je?A==="svg":y.namespaceURI===hr?A==="svg"&&(j==="annotation-xml"||vs[j]):!!va[A]:d.namespaceURI===hr?y.namespaceURI===je?A==="math":y.namespaceURI===mr?A==="math"&&ys[j]:!!ya[A]:d.namespaceURI===je?y.namespaceURI===mr&&!ys[j]||y.namespaceURI===hr&&!vs[j]?!1:!ya[A]&&(Tu[A]||!va[A]):!!(Nn==="application/xhtml+xml"&&gs[d.namespaceURI]):!1},De=function(d){Tn(e.removed,{element:d});try{S(d).removeChild(d)}catch{h(d)}},Tt=function(d,y){try{Tn(e.removed,{attribute:y.getAttributeNode(d),from:y})}catch{Tn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(d),d==="is")if(Jt||pr)try{De(y)}catch{}else try{y.setAttribute(d,"")}catch{}},ba=function(d){let y=null,A=null;if(ds)d="<remove></remove>"+d;else{let Y=_c(d,/^[\r\n\t ]+/);A=Y&&Y[0]}Nn==="application/xhtml+xml"&&en===je&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let j=ee?ee.createHTML(d):d;if(en===je)try{y=new p().parseFromString(j,Nn)}catch{}if(!y||!y.documentElement){y=is.createDocument(en,"template",null);try{y.documentElement.innerHTML=ms?dt:j}catch{}}let $=y.body||y.documentElement;return d&&A&&$.insertBefore(n.createTextNode(A),$.childNodes[0]||null),en===je?mu.call(y,Et?"html":"body")[0]:Et?y.documentElement:$},xa=function(d){return oa.call(d.ownerDocument||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ea=function(d){d.normalize();let y=oa.call(d.ownerDocument||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=y.nextNode();for(;A;){let j=A.data;En([lr,cr,ur],$=>{j=_n(j,$," ")}),A.data=j,A=y.nextNode()}},gr=function(d){let y=ae?ae(d):null;return typeof y!="string"||ie(y)!=="form"?!1:typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||d.attributes!==H(d)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function"||d.nodeType!==X(d)||d.childNodes!==T(d)},Rn=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return X(d)===nt.documentFragment}catch{return!1}},vr=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return typeof X(d)=="number"}catch{return!1}};function st(C,d,y){En(C,A=>{A.call(e,d,y,tn)})}let Ta=function(d){let y=null;if(st(pe.beforeSanitizeElements,d,null),gr(d))return De(d),!0;let A=ie(d.nodeName);if(st(pe.uponSanitizeElement,d,{tagName:A,allowedTags:oe}),In&&d.hasChildNodes()&&!vr(d.firstElementChild)&&be(/<[/\w!]/g,d.innerHTML)&&be(/<[/\w!]/g,d.textContent)||In&&d.namespaceURI===je&&A==="style"&&vr(d.firstElementChild)||d.nodeType===nt.progressingInstruction||In&&d.nodeType===nt.comment&&be(/<[/\w]/g,d.data))return De(d),!0;if(kn[A]||!(pt.tagCheck instanceof Function&&pt.tagCheck(A))&&!oe[A]){if(!kn[A]&&Sa(A)&&(se.tagNameCheck instanceof RegExp&&be(se.tagNameCheck,A)||se.tagNameCheck instanceof Function&&se.tagNameCheck(A)))return!1;if(ps&&!Ve[A]){let $=S(d),Y=T(d);if(Y&&$){let Ne=Y.length;for(let We=Ne-1;We>=0;--We){let Ue=f(Y[We],!0);$.insertBefore(Ue,g(d))}}}return De(d),!0}return(X?X(d):d.nodeType)===nt.element&&!Au(d)||(A==="noscript"||A==="noembed"||A==="noframes")&&be(/<\/no(script|embed|frames)/i,d.innerHTML)?(De(d),!0):(ft&&d.nodeType===nt.text&&(y=d.textContent,En([lr,cr,ur],$=>{y=_n(y,$," ")}),d.textContent!==y&&(Tn(e.removed,{element:d.cloneNode()}),d.textContent=y)),st(pe.afterSanitizeElements,d,null),!1)},_a=function(d,y,A){if(dr[y]||ua&&(y==="id"||y==="name")&&(A in n||A in wu))return!1;let j=le[y]||pt.attributeCheck instanceof Function&&pt.attributeCheck(y,d);if(!(cs&&!dr[y]&&be(vu,y))){if(!(aa&&be(yu,y))){if(!j||dr[y]){if(!(Sa(d)&&(se.tagNameCheck instanceof RegExp&&be(se.tagNameCheck,d)||se.tagNameCheck instanceof Function&&se.tagNameCheck(d))&&(se.attributeNameCheck instanceof RegExp&&be(se.attributeNameCheck,y)||se.attributeNameCheck instanceof Function&&se.attributeNameCheck(y,d))||y==="is"&&se.allowCustomizedBuiltInElements&&(se.tagNameCheck instanceof RegExp&&be(se.tagNameCheck,A)||se.tagNameCheck instanceof Function&&se.tagNameCheck(A))))return!1}else if(!hs[y]){if(!be(ia,_n(A,sa,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&Sc(A,"data:")===0&&fa[d])){if(!(la&&!be(bu,_n(A,sa,"")))){if(A)return!1}}}}}}return!0},ku=D({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Sa=function(d){return!ku[qn(d)]&&be(xu,d)},wa=function(d){st(pe.beforeSanitizeAttributes,d,null);let y=d.attributes;if(!y||gr(d))return;let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0},j=y.length;for(;j--;){let $=y[j],Y=$.name,Ne=$.namespaceURI,We=$.value,Ue=ie(Y),xs=We,fe=Y==="value"?xs:Xh(xs);if(A.attrName=Ue,A.attrValue=fe,A.keepAttr=!0,A.forceKeepAttr=void 0,st(pe.uponSanitizeAttribute,d,A),fe=A.attrValue,da&&(Ue==="id"||Ue==="name")&&Sc(fe,pa)!==0&&(Tt(Y,d),fe=pa+fe),In&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,fe)){Tt(Y,d);continue}if(Ue==="attributename"&&_c(fe,"href")){Tt(Y,d);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){Tt(Y,d);continue}if(!ca&&be(/\/>/i,fe)){Tt(Y,d);continue}ft&&En([lr,cr,ur],ka=>{fe=_n(fe,ka," ")});let Aa=ie(d.nodeName);if(!_a(Aa,Ue,fe)){Tt(Y,d);continue}if(ee&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ne)switch(m.getAttributeType(Aa,Ue)){case"TrustedHTML":{fe=ee.createHTML(fe);break}case"TrustedScriptURL":{fe=ee.createScriptURL(fe);break}}if(fe!==xs)try{Ne?d.setAttributeNS(Ne,Y,fe):d.setAttribute(Y,fe),gr(d)?De(d):Tc(e.removed)}catch{Tt(Y,d)}}st(pe.afterSanitizeAttributes,d,null)},yr=function(d){let y=null,A=xa(d);for(st(pe.beforeSanitizeShadowDOM,d,null);y=A.nextNode();)if(st(pe.uponSanitizeShadowNode,y,null),Ta(y),wa(y),Rn(y.content)&&yr(y.content),(X?X(y):y.nodeType)===nt.element){let $=b?b(y):y.shadowRoot;Rn($)&&(nn($),yr($))}st(pe.afterSanitizeShadowDOM,d,null)},nn=function(d){let y=X?X(d):d.nodeType;if(y===nt.element){let $=b?b(d):d.shadowRoot;Rn($)&&(nn($),yr($))}let A=T?T(d):d.childNodes;if(!A)return;let j=[];En(A,$=>{Tn(j,$)});for(let $ of j)nn($);if(y===nt.element){let $=ae?ae(d):null;if(typeof $=="string"&&ie($)==="template"){let Y=d.content;Rn(Y)&&nn(Y)}}};return e.sanitize=function(C){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,A=null,j=null,$=null;if(ms=!C,ms&&(C="<!-->"),typeof C!="string"&&!vr(C)&&(C=Jh(C),typeof C!="string"))throw Yn("dirty is not a string, aborting");if(!e.isSupported)return C;if(us||bs(d),e.removed=[],typeof C=="string"&&(Cn=!1),Cn){let We=ae?ae(C):C.nodeName;if(typeof We=="string"){let Ue=ie(We);if(!oe[Ue]||kn[Ue])throw Yn("root node is forbidden and cannot be sanitized in-place")}if(gr(C))throw Yn("root node is clobbered and cannot be sanitized in-place");nn(C)}else if(vr(C))y=ba("<!---->"),A=y.ownerDocument.importNode(C,!0),A.nodeType===nt.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?y=A:y.appendChild(A),nn(A);else{if(!Jt&&!ft&&!Et&&C.indexOf("<")===-1)return ee&&fr?ee.createHTML(C):C;if(y=ba(C),!y)return Jt?null:fr?dt:""}y&&ds&&De(y.firstChild);let Y=xa(Cn?C:y);for(;j=Y.nextNode();)Ta(j),wa(j),Rn(j.content)&&yr(j.content);if(Cn)return ft&&Ea(C),C;if(Jt){if(ft&&Ea(y),pr)for($=hu.call(y.ownerDocument);y.firstChild;)$.appendChild(y.firstChild);else $=y;return(le.shadowroot||le.shadowrootmode)&&($=gu.call(r,$,!0)),$}let Ne=Et?y.outerHTML:y.innerHTML;return Et&&oe["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&be(cm,y.ownerDocument.doctype.name)&&(Ne="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
13
- `+Ne),ft&&En([lr,cr,ur],We=>{Ne=_n(Ne,We," ")}),ee&&fr?ee.createHTML(Ne):Ne},e.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};bs(C),us=!0},e.clearConfig=function(){tn=null,us=!1},e.isValidAttribute=function(C,d,y){tn||bs({});let A=ie(C),j=ie(d);return _a(A,j,y)},e.addHook=function(C,d){typeof d=="function"&&Tn(pe[C],d)},e.removeHook=function(C,d){if(d!==void 0){let y=jh(pe[C],d);return y===-1?void 0:Wh(pe[C],y,1)[0]}return Tc(pe[C])},e.removeHooks=function(C){pe[C]=[]},e.removeAllHooks=function(){pe=Oc()},e}var Dc=Pc();function Pi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Zt=Pi();function Vc(t){Zt=t}var Wt={exec:()=>null};function wn(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=e[r];return o||(o=t(r),e[r]=o),o}}function B(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(o,s)=>{let i=typeof s=="string"?s:s.source;return i=i.replace(Te.caret,"$1"),n=n.replace(o,i),r},getRegex:()=>new RegExp(n,e)};return r}var fm=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Te={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:wn(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:wn(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:wn(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:wn(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:wn(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:wn(t=>new RegExp(`^ {0,${t}}>`))},hm=/^(?:[ \t]*(?:\n|$))+/,mm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,gm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,er=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,vm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Di=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,jc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Wc=B(jc).replace(/bull/g,Di).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),ym=B(jc).replace(/bull/g,Di).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ui=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,bm=/^[^\n]+/,Gi=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,xm=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Gi).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Em=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Di).getRegex(),Qo="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Hi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Tm=B("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Hi).replace("tag",Qo).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Xc=B(Ui).replace("hr",er).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qo).getRegex(),_m=B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Xc).getRegex(),Fi={blockquote:_m,code:mm,def:xm,fences:gm,heading:vm,hr:er,html:Tm,lheading:Wc,list:Em,newline:hm,paragraph:Xc,table:Wt,text:bm},Uc=B("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",er).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qo).getRegex(),Sm={...Fi,lheading:ym,table:Uc,paragraph:B(Ui).replace("hr",er).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Uc).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Qo).getRegex()},wm={...Fi,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Hi).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Wt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(Ui).replace("hr",er).replace("heading",` *#{1,6} *[^
14
- ]`).replace("lheading",Wc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Am=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,km=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Zc=/^( {2,}|\\)\n(?!\s*$)/,Im=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,An=/[\p{P}\p{S}]/u,es=/[\s\p{P}\p{S}]/u,$i=/[^\s\p{P}\p{S}]/u,Cm=B(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,es).getRegex(),Kc=/(?!~)[\p{P}\p{S}]/u,Nm=/(?!~)[\s\p{P}\p{S}]/u,Rm=/(?:[^\s\p{P}\p{S}]|~)/u,Om=B(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",fm?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Yc=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Mm=B(Yc,"u").replace(/punct/g,An).getRegex(),Lm=B(Yc,"u").replace(/punct/g,Kc).getRegex(),qc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Pm=B(qc,"gu").replace(/notPunctSpace/g,$i).replace(/punctSpace/g,es).replace(/punct/g,An).getRegex(),Dm=B(qc,"gu").replace(/notPunctSpace/g,Rm).replace(/punctSpace/g,Nm).replace(/punct/g,Kc).getRegex(),Um=B("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,$i).replace(/punctSpace/g,es).replace(/punct/g,An).getRegex(),Gm=B(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,An).getRegex(),Hm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Fm=B(Hm,"gu").replace(/notPunctSpace/g,$i).replace(/punctSpace/g,es).replace(/punct/g,An).getRegex(),$m=B(/\\(punct)/,"gu").replace(/punct/g,An).getRegex(),zm=B(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Bm=B(Hi).replace("(?:-->|$)","-->").getRegex(),Vm=B("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Bm).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Yo=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,jm=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Yo).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Jc=B(/^!?\[(label)\]\[(ref)\]/).replace("label",Yo).replace("ref",Gi).getRegex(),Qc=B(/^!?\[(ref)\](?:\[\])?/).replace("ref",Gi).getRegex(),Wm=B("reflink|nolink(?!\\()","g").replace("reflink",Jc).replace("nolink",Qc).getRegex(),Gc=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,zi={_backpedal:Wt,anyPunctuation:$m,autolink:zm,blockSkip:Om,br:Zc,code:km,del:Wt,delLDelim:Wt,delRDelim:Wt,emStrongLDelim:Mm,emStrongRDelimAst:Pm,emStrongRDelimUnd:Um,escape:Am,link:jm,nolink:Qc,punctuation:Cm,reflink:Jc,reflinkSearch:Wm,tag:Vm,text:Im,url:Wt},Xm={...zi,link:B(/^!?\[(label)\]\((.*?)\)/).replace("label",Yo).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Yo).getRegex()},Oi={...zi,emStrongRDelimAst:Dm,emStrongLDelim:Lm,delLDelim:Gm,delRDelim:Fm,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Gc).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:B(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Gc).getRegex()},Zm={...Oi,br:B(Zc).replace("{2,}","*").getRegex(),text:B(Oi.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ko={normal:Fi,gfm:Sm,pedantic:wm},Jn={normal:zi,gfm:Oi,breaks:Zm,pedantic:Xm},Km={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Hc=t=>Km[t];function ot(t,e){if(e){if(Te.escapeTest.test(t))return t.replace(Te.escapeReplace,Hc)}else if(Te.escapeTestNoEncode.test(t))return t.replace(Te.escapeReplaceNoEncode,Hc);return t}function Fc(t){try{t=encodeURI(t).replace(Te.percentDecode,"%")}catch{return null}return t}function $c(t,e){let n=t.replace(Te.findPipe,(s,i,a)=>{let l=!1,c=i;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Te.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(Te.slashPipe,"|");return r}function xt(t,e,n){let r=t.length;if(r===0)return"";let o=0;for(;o<r;){let s=t.charAt(r-o-1);if(s===e&&!n)o++;else if(s!==e&&n)o++;else break}return t.slice(0,r-o)}function zc(t){let e=t.split(`
10
+ `),m=JSON.parse(p);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(p){r.error(p)}}return r.asObservable()},Th=t=>{let e=new nt,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==Zt.HEADERS&&o.type===Zt.DATA&&o.data){let i=new Uint8Array(n.length+o.data.length);i.set(n,0),i.set(o.data,n.length),n=i,r()}},error:o=>e.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let i=n.slice(4,o),s=yc(i);e.next(s),n=n.slice(o)}catch(i){let s=i instanceof Error?i.message:String(i);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},Sh=(t,e)=>{let n=qn(e),r=new nt,o=new Zr,i=!1;return t.subscribe({next:s=>{if(o.next(s),s.type===Zt.HEADERS&&!i){i=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Is?"protobuf":"sse"}),a===Is?Th(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):Eh(o,n).subscribe({next:l=>{try{let c=Or.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else i||r.error(Error("No headers event received before data events"))},error:s=>{o.error(s),r.error(s)},complete:()=>{o.complete()}}),r.asObservable()},K=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),_h=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),wh=u.object({type:u.literal(K.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),Ah=u.object({type:u.literal(K.enum.TextMessageContent),messageId:u.string(),content:u.string()}),kh=u.object({type:u.literal(K.enum.TextMessageEnd),messageId:u.string()}),Ih=u.object({type:u.literal(K.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),Ch=u.object({type:u.literal(K.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),Nh=u.object({type:u.literal(K.enum.ActionExecutionEnd),actionExecutionId:u.string()}),Rh=u.object({type:u.literal(K.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),Oh=u.object({type:u.literal(K.enum.AgentStateMessage),threadId:u.string(),agentName:u.string(),nodeName:u.string(),runId:u.string(),active:u.boolean(),role:u.string(),state:u.string(),running:u.boolean()}),Mh=u.object({type:u.literal(K.enum.MetaEvent),name:_h,value:u.any()}),Lh=u.object({type:u.literal(K.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[wh,Ah,kh,Ih,Ch,Nh,Rh,Oh,Mh,Lh]),u.object({id:u.string(),role:u.string(),content:u.string(),parentMessageId:u.string().optional()}),u.object({id:u.string(),name:u.string(),arguments:u.any(),parentMessageId:u.string().optional()}),u.object({id:u.string(),result:u.any(),actionExecutionId:u.string(),actionName:u.string()});var Ph=t=>{if(typeof t=="string")return t;if(!Array.isArray(t))return;let e=t.filter(n=>n.type==="text").map(n=>n.text).filter(n=>n.length>0);if(e.length!==0)return e.join(`
11
+ `)},Dh=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(ke(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let h=f;return[{type:K.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case v.TEXT_MESSAGE_CONTENT:{let h=f;return[{type:K.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case v.TEXT_MESSAGE_END:{let h=f;return[{type:K.enum.TextMessageEnd,messageId:h.messageId}]}case v.TOOL_CALL_START:{let h=f;return p.push({id:h.toolCallId,type:"function",function:{name:h.toolCallName,arguments:""}}),s=!0,m[h.toolCallId]=h.toolCallName,[{type:K.enum.ActionExecutionStart,actionExecutionId:h.toolCallId,actionName:h.toolCallName,parentMessageId:h.parentMessageId}]}case v.TOOL_CALL_ARGS:{let h=f,g=p.find(_=>_.id===h.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h.toolCallId}'`),[];g.function.arguments+=h.delta;let T=!1;if(c){let _=c.find(b=>b.tool==g.function.name);if(_)try{let b=JSON.parse(fo(g.function.arguments));_.tool_argument&&_.tool_argument in b?(x({...o,[_.state_key]:b[_.tool_argument]}),T=!0):_.tool_argument||(x({...o,[_.state_key]:b}),T=!0)}catch{}}return[{type:K.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...T?[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case v.TOOL_CALL_END:{let h=f;return[{type:K.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case v.TOOL_CALL_RESULT:{let h=f;return[{type:K.enum.ActionExecutionResult,actionExecutionId:h.toolCallId,result:h.content,actionName:m[h.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let h=f;switch(h.name){case"Exit":i=!1;break;case"PredictState":c=h.value;break}return[{type:K.enum.MetaEvent,name:h.name,value:h.value}]}case v.STATE_SNAPSHOT:return x(f.snapshot),[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case v.STATE_DELTA:{let h=f,g=Fr.applyPatch(o,h.delta,!0,!1);return g?(x(g.newDocument),[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=f.messages,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:Uh(l)}:{}}),active:!1}];case v.RUN_ERROR:{let h=f;return[{type:K.enum.RunError,message:h.message,code:h.code}]}case v.STEP_STARTED:return a=f.stepName,p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return p=[],c=null,[{type:K.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Uh(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Ph(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var Ko=t=>e=>{let n=qn(t),r,o,i,s,a=()=>{if(!r||s!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return s=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},l=()=>{if(!o||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return s=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!i||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:i.messageId};return s=void 0,i=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},p=()=>s==="text"?[a()]:s==="tool"?[l()]:s==="reasoning"?[c()]:[];return e.pipe(ke(m=>{switch(m.type){case v.TEXT_MESSAGE_START:case v.TEXT_MESSAGE_CONTENT:case v.TEXT_MESSAGE_END:case v.TOOL_CALL_START:case v.TOOL_CALL_ARGS:case v.TOOL_CALL_END:case v.TOOL_CALL_RESULT:case v.STATE_SNAPSHOT:case v.STATE_DELTA:case v.MESSAGES_SNAPSHOT:case v.CUSTOM:case v.RUN_STARTED:case v.RUN_FINISHED:case v.RUN_ERROR:case v.STEP_STARTED:case v.STEP_FINISHED:case v.THINKING_START:case v.THINKING_END:case v.THINKING_TEXT_MESSAGE_START:case v.THINKING_TEXT_MESSAGE_CONTENT:case v.THINKING_TEXT_MESSAGE_END:case v.REASONING_START:case v.REASONING_MESSAGE_START:case v.REASONING_MESSAGE_CONTENT:case v.REASONING_MESSAGE_END:case v.REASONING_END:return[...p(),m];case v.RAW:case v.ACTIVITY_SNAPSHOT:case v.ACTIVITY_DELTA:case v.REASONING_ENCRYPTED_VALUE:return[m];case v.TEXT_MESSAGE_CHUNK:let x=m,f=[];if((s!=="text"||x.messageId!==void 0&&x.messageId!==r?.messageId)&&f.push(...p()),s!=="text"){if(x.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:x.messageId,name:x.name},s="text";let b={type:v.TEXT_MESSAGE_START,messageId:x.messageId,role:x.role||"assistant",...x.name!==void 0&&{name:x.name}};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_START",b,{messageId:x.messageId})}if(x.delta!==void 0){let b={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:x.delta};f.push(b),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",b,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let h=m,g=[];if((s!=="tool"||h.toolCallId!==void 0&&h.toolCallId!==o?.toolCallId)&&g.push(...p()),s!=="tool"){if(h.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(h.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId},s="tool";let b={type:v.TOOL_CALL_START,toolCallId:h.toolCallId,toolCallName:h.toolCallName,parentMessageId:h.parentMessageId};g.push(b),n?.event("TRANSFORM","TOOL_CALL_START",b,{toolCallId:h.toolCallId,toolCallName:h.toolCallName})}if(h.delta!==void 0){let b={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:h.delta};g.push(b),n?.event("TRANSFORM","TOOL_CALL_ARGS",b,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let T=m,_=[];if((s!=="reasoning"||T.messageId&&T.messageId!==i?.messageId)&&_.push(...p()),s!=="reasoning"){if(T.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");i={messageId:T.messageId},s="reasoning";let b={type:v.REASONING_MESSAGE_START,messageId:T.messageId};_.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_START",b,{messageId:T.messageId})}if(T.delta!==void 0){let b={type:v.REASONING_MESSAGE_CONTENT,messageId:i.messageId,delta:T.delta};_.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",b,{messageId:i.messageId})}return _}return m.type,[]}),Xt(()=>{p()}))};function Gh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}var Yo=class{runNext(t,e){return e.run(t).pipe(Ko(!1))}runNextWithState(t,e){let n=z(t.messages||[]),r=z(t.state||{}),o=new Zr;return Ac(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(uo(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:z(n),state:z(r)})))}},Hh=class extends Yo{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Fh(t){let e=t.content;if(Array.isArray(e)){let n=e.filter(r=>typeof r=="object"&&!!r&&"type"in r&&r.type==="text"&&typeof r.text=="string").map(r=>r.text).join("");return{...t,content:n}}return typeof e=="string"?t:{...t,content:""}}var $h=class extends Yo{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Fh)};return this.runNext(o,e)}},Ec="THINKING_START",Tc="THINKING_END",Sc="THINKING_TEXT_MESSAGE_START",_c="THINKING_TEXT_MESSAGE_CONTENT",wc="THINKING_TEXT_MESSAGE_END",zh=class extends Yo{constructor(...t){super(...t),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(t,e){typeof process<"u"&&process.env!==void 0&&process.env.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${t} to ${e}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(t,e){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(t,e).pipe(Wt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Ec:{this.currentReasoningId=Re();let{title:e,...n}=t;return this.warnAboutTransformation(Ec,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Sc:return this.currentMessageId=Re(),this.warnAboutTransformation(Sc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case _c:{let{delta:e,...n}=t;return this.warnAboutTransformation(_c,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Re(),delta:e}}case wc:{let e=this.currentMessageId??Re();return this.warnAboutTransformation(wc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Tc:{let e=this.currentReasoningId??Re();return this.warnAboutTransformation(Tc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Bh(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function jh(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function Vh(t){let e=Bh(t.mimeType);return t.data?{type:e,source:{type:"data",value:t.data,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t.url?{type:e,source:{type:"url",value:t.url,mimeType:t.mimeType},...t.filename?{metadata:{filename:t.filename}}:{}}:t}function Wh(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>jh(r)?Vh(r):r);return{...t,content:n}}var Xh=class extends Yo{run(t,e){let n={...t,messages:t.messages.map(Wh)};return this.runNext(n,e)}},Zh="0.0.54",Kh=class{get maxVersion(){return Zh}get debug(){return this._debug}set debug(t){this._debug=Zo(t),this._debugLogger=Rs(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Rs(Zo(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??gt(),this.messages=z(r??[]),this.state=z(o??{}),this._debug=Zo(i),this._debugLogger=Rs(this._debug),Yn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new $h),Yn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new zh),Yn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Xh)}subscribe(t){return this.subscribers.push(t),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(e=>e!==t)}}}use(...t){let e=t.map(n=>typeof n=="function"?new Hh(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??gt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new nt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await lo(Xr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:p=>c.run(p,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Ko(this.debugLogger),Os(this.debugLogger),l=>l.pipe(po(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),Xn(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),Xt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=z(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new es}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??gt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new nt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await lo(Xr(()=>co(()=>this.connect(n)),Ko(this.debugLogger),Os(this.debugLogger),l=>l.pipe(po(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),Xn(l=>(this.isRunning=!1,l instanceof es?Kr:this.onError(n,l,i))),Xt(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=z(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Ac(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(gs(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=z(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||gt(),tools:z(t?.tools??[]),context:z(t?.context??[]),forwardedProps:z(t?.forwardedProps??{}),state:z(this.state),messages:e,...t?.resume===void 0?{}:{resume:z(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new q(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(Gh(i))throw new q(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await W(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return Vt(W(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Wt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await W(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=z(this.messages),t.state=z(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=z(this.pendingInterrupts),t}addMessage(t){this.messages.push(t),(async()=>{for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role==="assistant"&&t.toolCalls)for(let e of t.toolCalls)for(let n of this.subscribers)await n.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(t){this.messages.push(...t),(async()=>{for(let e of t){for(let n of this.subscribers)await n.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role==="assistant"&&e.toolCalls)for(let n of e.toolCalls)for(let r of this.subscribers)await r.onNewToolCall?.({toolCall:n,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(t){this.messages=z(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=z(t),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(t){this.agentId=this.agentId??gt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Ko(this.debugLogger),Os(this.debugLogger),Dh(this.threadId,e.runId,this.agentId),n=>n.pipe(Wt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},kc=class extends Kh{requestInit(t){return{method:"POST",headers:{...this.headers,"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify(t),signal:this.abortController.signal}}runAgent(t,e){return this.abortController=t?.abortController??new AbortController,super.runAgent(t,e)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(t){super(t),this.abortController=new AbortController,this.url=t.url,this.headers=z(t.headers??{}),this.fetch=t.fetch??fetch}run(t){return Sh(xh(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=z(this.headers??{}),t.fetch=this.fetch;let e=new AbortController,n=this.abortController.signal;return n.aborted&&e.abort(n.reason),t.abortController=e,t}};var Ie={title:"Assistant",chatHistory:"Chat history",newChat:"New chat",collapse:"Collapse",expand:"Expand",conversation:"Conversation",thinking:"Assistant is thinking\u2026",stopped:"\u23F9 Stopped",connectionLost:"Connection lost",noResult:"No result returned.",declinedAction:"User declined the action.",navigating:"Navigating\u2026",skillNeeds:"\u201C{title}\u201D needs: {fields}",message:"Message",inputPlaceholder:"Ask anything\u2026",send:"Send",stop:"Stop",attachFiles:"Attach files",toolRunning:"running\u2026",toolDone:"\u2713 done",toolError:"\u26A0 error",toolDeclined:"\u2298 declined",resultLabel:"Result",errorLabel:"Error",declinedLabel:"Declined",details:"Details",confirmAction:"Confirm action",confirmRun:"Run \u201C{tool}\u201D?",confirm:"Confirm",cancel:"Cancel",chats:"Chats",noConversations:"No conversations yet.",rename:"Rename",renameConversation:"Rename conversation",delete:"Delete",deleteConversation:"Delete conversation",deletePrompt:"Delete?",tooLarge:"Too large (max {size})",fileTypeNotAllowed:"File type not allowed",uploadFailed:"upload failed",retry:"Retry",retryUpload:"Retry upload",remove:"Remove",removeAttachment:"Remove attachment",justNow:"just now",minutesAgo:"{n}m ago",hoursAgo:"{n}h ago",daysAgo:"{n}d ago",weeksAgo:"{n}w ago"};function Ps(t){let e={...Ie};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}var qo=class{element;#t;#e;#n=[];constructor(e){this.#t=e,this.#e=e.strings??Ie,this.element=document.createElement("div"),this.element.className="attachment-tray",this.element.setAttribute("part","attachment-tray"),this.element.hidden=!0}add(e){let n={localId:Re(),file:e,status:Fe.UPLOADING,progress:0,ref:null,error:""};this.#n.push(n);let r=this.#o(e);if(r!==null){n.status=Fe.ERROR,n.error=r,this.#s(),this.#t.onChange?.();return}this.#s(),this.#t.onChange?.(),this.#l(n)}readyRefs(){let e=[];for(let n of this.#n)n.ref!==null&&e.push(n.ref);return e}hasPending(){return this.#n.some(e=>e.status===Fe.UPLOADING)}isEmpty(){return this.#n.length===0}clearReady(){this.#n=this.#n.filter(e=>e.status===Fe.UPLOADING),this.#s()}clear(){this.#n=[],this.#s()}#o(e){return this.#t.maxBytes>0&&e.size>this.#t.maxBytes?this.#e.tooLarge.replace("{size}",_r(this.#t.maxBytes)):Yh(this.#t.accept,e)?null:this.#e.fileTypeNotAllowed}#l(e){e.status=Fe.UPLOADING,e.progress=0,e.error="",this.#s(),this.#t.upload(e.file,n=>{e.progress=n,this.#s()}).then(n=>{e.status=Fe.READY,e.ref=n}).catch(n=>{e.status=Fe.ERROR,e.error=n instanceof Error?n.message:this.#e.uploadFailed}).finally(()=>{this.#s(),this.#t.onChange?.()})}#i(e){this.#n=this.#n.filter(n=>n!==e),this.#s(),this.#t.onChange?.()}#s(){this.element.replaceChildren(),this.element.hidden=this.#n.length===0;for(let e of this.#n)this.element.appendChild(this.#r(e))}#r(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`;let r=document.createElement("span");r.className="attachment-chip-icon",r.textContent=Xi(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.textContent=e.status===Fe.ERROR?e.error:_r(e.file.size),n.append(r,o,i),e.status===Fe.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar";let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Fe.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.title=this.#e.retry,a.setAttribute("aria-label",this.#e.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#l(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.title=this.#e.remove,s.setAttribute("aria-label",this.#e.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#i(e)),n.appendChild(s),n}};function Yh(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}function Ic(t,e){let n=document.createElement("button");return n.type="button",n.className=`confirm-btn confirm-btn--${t}`,n.setAttribute("part",`confirm-button confirm-${t}`),n.textContent=e,n}function Ds(t,e,n={}){let r=n.strings??Ie;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2);let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=Ic("cancel",r.cancel),p=Ic("confirm",r.confirm),m=!1,x=f=>{m||(m=!0,c.disabled=!0,p.disabled=!0,i.setAttribute("data-resolved",f?"confirmed":"declined"),o(f))};if(c.addEventListener("click",()=>x(!1)),p.addEventListener("click",()=>x(!0)),n.signal?.addEventListener("abort",()=>x(!1),{once:!0}),l.append(c,p),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){x(!1);return}p.focus()})}function Us(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function Cc(t,e){(e==null||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n<e;n++)r[n]=t[n];return r}function qh(t){if(Array.isArray(t))return t}function Jh(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,s,a=[],l=!0,c=!1;try{if(i=(n=n.call(t)).next,e!==0)for(;!(l=(r=i.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(p){c=!0,o=p}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function Qh(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
12
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function em(t,e){return qh(t)||Jh(t,e)||tm(t,e)||Qh()}function tm(t,e){if(t){if(typeof t=="string")return Cc(t,e);var n={}.toString.call(t).slice(8,-1);return n==="Object"&&t.constructor&&(n=t.constructor.name),n==="Map"||n==="Set"?Array.from(t):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Cc(t,e):void 0}}var zc=Object.entries,Nc=Object.setPrototypeOf,nm=Object.isFrozen,rm=Object.getPrototypeOf,om=Object.getOwnPropertyDescriptor,_e=Object.freeze,Ue=Object.seal,wn=Object.create,Bc=typeof Reflect<"u"&&Reflect,Bs=Bc.apply,js=Bc.construct;_e||(_e=function(e){return e});Ue||(Ue=function(e){return e});Bs||(Bs=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(n,o)});js||(js=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var Tn=de(Array.prototype.forEach),im=de(Array.prototype.lastIndexOf),Rc=de(Array.prototype.pop),Sn=de(Array.prototype.push),sm=de(Array.prototype.splice),Se=Array.isArray,er=de(String.prototype.toLowerCase),Gs=de(String.prototype.toString),Oc=de(String.prototype.match),_n=de(String.prototype.replace),Mc=de(String.prototype.indexOf),am=de(String.prototype.trim),lm=de(Number.prototype.toString),cm=de(Boolean.prototype.toString),Lc=typeof BigInt>"u"?null:de(BigInt.prototype.toString),Pc=typeof Symbol>"u"?null:de(Symbol.prototype.toString),re=de(Object.prototype.hasOwnProperty),Jn=de(Object.prototype.toString),be=de(RegExp.prototype.test),Qn=um(TypeError);function de(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return Bs(t,e,r)}}function um(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return js(t,n)}}function D(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:er;if(Nc&&Nc(t,null),!Se(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=n(o);i!==o&&(nm(e)||(e[r]=i),o=i)}t[o]=!0}return t}function dm(t){for(let e=0;e<t.length;e++)re(t,e)||(t[e]=null);return t}function Ee(t){let e=wn(null);for(let r of zc(t)){var n=em(r,2);let o=n[0],i=n[1];re(t,o)&&(Se(i)?e[o]=dm(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ee(i):e[o]=i)}return e}function pm(t){switch(typeof t){case"string":return t;case"number":return lm(t);case"boolean":return cm(t);case"bigint":return Lc?Lc(t):"0";case"symbol":return Pc?Pc(t):"Symbol()";case"undefined":return Jn(t);case"function":case"object":{if(t===null)return Jn(t);let e=t,n=ot(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:Jn(r)}return Jn(t)}default:return Jn(t)}}function ot(t,e){for(;t!==null;){let r=om(t,e);if(r){if(r.get)return de(r.get);if(typeof r.value=="function")return de(r.value)}t=rm(t)}function n(){return null}return n}function fm(t){try{return be(t,""),!0}catch{return!1}}var Dc=_e(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Hs=_e(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Fs=_e(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),hm=_e(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),$s=_e(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),mm=_e(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Uc=_e(["#text"]),Gc=_e(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),zs=_e(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),Hc=_e(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),Jo=_e(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),gm=Ue(/{{[\w\W]*|^[\w\W]*}}/g),vm=Ue(/<%[\w\W]*|^[\w\W]*%>/g),ym=Ue(/\${[\w\W]*/g),bm=Ue(/^data-[\-\w.\u00B7-\uFFFF]+$/),xm=Ue(/^aria-[\-\w]+$/),Fc=Ue(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Em=Ue(/^(?:\w+script|data):/i),Tm=Ue(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Sm=Ue(/^html$/i),_m=Ue(/^[a-z][.\w]*(-[.\w]+)+$/i),rt={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},wm=function(){return typeof window>"u"?null:window},Am=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},$c=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function jc(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:wm(),e=C=>jc(C);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==rt.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let i=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let p=t.DOMParser,m=t.trustedTypes,x=a.prototype,f=ot(x,"cloneNode"),h=ot(x,"remove"),g=ot(x,"nextSibling"),T=ot(x,"childNodes"),_=ot(x,"parentNode"),b=ot(x,"shadowRoot"),H=ot(x,"attributes"),X=s&&s.prototype?ot(s.prototype,"nodeType"):null,ae=s&&s.prototype?ot(s.prototype,"nodeName"):null;if(typeof i=="function"){let C=n.createElement("template");C.content&&C.content.ownerDocument&&(n=C.content.ownerDocument)}let ee,ft="",cr=n,ci=cr.implementation,ua=cr.createNodeIterator,xu=cr.createDocumentFragment,Eu=cr.getElementsByTagName,Tu=r.importNode,pe=$c();e.isSupported=typeof zc=="function"&&typeof _=="function"&&ci&&ci.createHTMLDocument!==void 0;let ur=gm,dr=vm,pr=ym,Su=bm,_u=xm,wu=Em,da=Tm,Au=_m,pa=Fc,oe=null,ui=D({},[...Dc,...Hs,...Fs,...$s,...Uc]),le=null,di=D({},[...Gc,...zs,...Hc,...Jo]),ie=Object.seal(wn(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),In=null,fr=null,ht=Object.seal(wn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),fa=!0,pi=!0,ha=!1,ma=!0,mt=!1,Cn=!0,St=!1,fi=!1,hi=!1,Qt=!1,hr=!1,mr=!1,ga=!0,va=!1,ya="user-content-",mi=!0,Nn=!1,en={},Xe=null,gi=D({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),ba=null,xa=D({},["audio","video","img","source","image","track"]),vi=null,Ea=D({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),gr="http://www.w3.org/1998/Math/MathML",vr="http://www.w3.org/2000/svg",Ze="http://www.w3.org/1999/xhtml",tn=Ze,yi=!1,bi=null,ku=D({},[gr,vr,Ze],Gs),xi=D({},["mi","mo","mn","ms","mtext"]),Ei=D({},["annotation-xml"]),Iu=D({},["title","style","font","a","script"]),Rn=null,Cu=["application/xhtml+xml","text/html"],Nu="text/html",se=null,nn=null,Ru=n.createElement("form"),Ta=function(d){return d instanceof RegExp||d instanceof Function},Ti=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(nn&&nn===d)return;(!d||typeof d!="object")&&(d={}),d=Ee(d),Rn=Cu.indexOf(d.PARSER_MEDIA_TYPE)===-1?Nu:d.PARSER_MEDIA_TYPE,se=Rn==="application/xhtml+xml"?Gs:er,oe=re(d,"ALLOWED_TAGS")&&Se(d.ALLOWED_TAGS)?D({},d.ALLOWED_TAGS,se):ui,le=re(d,"ALLOWED_ATTR")&&Se(d.ALLOWED_ATTR)?D({},d.ALLOWED_ATTR,se):di,bi=re(d,"ALLOWED_NAMESPACES")&&Se(d.ALLOWED_NAMESPACES)?D({},d.ALLOWED_NAMESPACES,Gs):ku,vi=re(d,"ADD_URI_SAFE_ATTR")&&Se(d.ADD_URI_SAFE_ATTR)?D(Ee(Ea),d.ADD_URI_SAFE_ATTR,se):Ea,ba=re(d,"ADD_DATA_URI_TAGS")&&Se(d.ADD_DATA_URI_TAGS)?D(Ee(xa),d.ADD_DATA_URI_TAGS,se):xa,Xe=re(d,"FORBID_CONTENTS")&&Se(d.FORBID_CONTENTS)?D({},d.FORBID_CONTENTS,se):gi,In=re(d,"FORBID_TAGS")&&Se(d.FORBID_TAGS)?D({},d.FORBID_TAGS,se):Ee({}),fr=re(d,"FORBID_ATTR")&&Se(d.FORBID_ATTR)?D({},d.FORBID_ATTR,se):Ee({}),en=re(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?Ee(d.USE_PROFILES):d.USE_PROFILES:!1,fa=d.ALLOW_ARIA_ATTR!==!1,pi=d.ALLOW_DATA_ATTR!==!1,ha=d.ALLOW_UNKNOWN_PROTOCOLS||!1,ma=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,mt=d.SAFE_FOR_TEMPLATES||!1,Cn=d.SAFE_FOR_XML!==!1,St=d.WHOLE_DOCUMENT||!1,Qt=d.RETURN_DOM||!1,hr=d.RETURN_DOM_FRAGMENT||!1,mr=d.RETURN_TRUSTED_TYPE||!1,hi=d.FORCE_BODY||!1,ga=d.SANITIZE_DOM!==!1,va=d.SANITIZE_NAMED_PROPS||!1,mi=d.KEEP_CONTENT!==!1,Nn=d.IN_PLACE||!1,pa=fm(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Fc,tn=typeof d.NAMESPACE=="string"?d.NAMESPACE:Ze,xi=re(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ee(d.MATHML_TEXT_INTEGRATION_POINTS):D({},["mi","mo","mn","ms","mtext"]),Ei=re(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ee(d.HTML_INTEGRATION_POINTS):D({},["annotation-xml"]);let y=re(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ee(d.CUSTOM_ELEMENT_HANDLING):wn(null);if(ie=wn(null),re(y,"tagNameCheck")&&Ta(y.tagNameCheck)&&(ie.tagNameCheck=y.tagNameCheck),re(y,"attributeNameCheck")&&Ta(y.attributeNameCheck)&&(ie.attributeNameCheck=y.attributeNameCheck),re(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(ie.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),mt&&(pi=!1),hr&&(Qt=!0),en&&(oe=D({},Uc),le=wn(null),en.html===!0&&(D(oe,Dc),D(le,Gc)),en.svg===!0&&(D(oe,Hs),D(le,zs),D(le,Jo)),en.svgFilters===!0&&(D(oe,Fs),D(le,zs),D(le,Jo)),en.mathMl===!0&&(D(oe,$s),D(le,Hc),D(le,Jo))),ht.tagCheck=null,ht.attributeCheck=null,re(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?ht.tagCheck=d.ADD_TAGS:Se(d.ADD_TAGS)&&(oe===ui&&(oe=Ee(oe)),D(oe,d.ADD_TAGS,se))),re(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?ht.attributeCheck=d.ADD_ATTR:Se(d.ADD_ATTR)&&(le===di&&(le=Ee(le)),D(le,d.ADD_ATTR,se))),re(d,"ADD_URI_SAFE_ATTR")&&Se(d.ADD_URI_SAFE_ATTR)&&D(vi,d.ADD_URI_SAFE_ATTR,se),re(d,"FORBID_CONTENTS")&&Se(d.FORBID_CONTENTS)&&(Xe===gi&&(Xe=Ee(Xe)),D(Xe,d.FORBID_CONTENTS,se)),re(d,"ADD_FORBID_CONTENTS")&&Se(d.ADD_FORBID_CONTENTS)&&(Xe===gi&&(Xe=Ee(Xe)),D(Xe,d.ADD_FORBID_CONTENTS,se)),mi&&(oe["#text"]=!0),St&&D(oe,["html","head","body"]),oe.table&&(D(oe,["tbody"]),delete In.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw Qn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Qn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=d.TRUSTED_TYPES_POLICY,ft=ee.createHTML("")}else ee===void 0&&(ee=Am(m,o)),ee!==null&&typeof ft=="string"&&(ft=ee.createHTML(""));(pe.uponSanitizeElement.length>0||pe.uponSanitizeAttribute.length>0)&&oe===ui&&(oe=Ee(oe)),pe.uponSanitizeAttribute.length>0&&le===di&&(le=Ee(le)),_e&&_e(d),nn=d},Sa=D({},[...Hs,...Fs,...hm]),_a=D({},[...$s,...mm]),Ou=function(d){let y=_(d);(!y||!y.tagName)&&(y={namespaceURI:tn,tagName:"template"});let A=er(d.tagName),V=er(y.tagName);return bi[d.namespaceURI]?d.namespaceURI===vr?y.namespaceURI===Ze?A==="svg":y.namespaceURI===gr?A==="svg"&&(V==="annotation-xml"||xi[V]):!!Sa[A]:d.namespaceURI===gr?y.namespaceURI===Ze?A==="math":y.namespaceURI===vr?A==="math"&&Ei[V]:!!_a[A]:d.namespaceURI===Ze?y.namespaceURI===vr&&!Ei[V]||y.namespaceURI===gr&&!xi[V]?!1:!_a[A]&&(Iu[A]||!Sa[A]):!!(Rn==="application/xhtml+xml"&&bi[d.namespaceURI]):!1},Ge=function(d){Sn(e.removed,{element:d});try{_(d).removeChild(d)}catch{h(d)}},_t=function(d,y){try{Sn(e.removed,{attribute:y.getAttributeNode(d),from:y})}catch{Sn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(d),d==="is")if(Qt||hr)try{Ge(y)}catch{}else try{y.setAttribute(d,"")}catch{}},wa=function(d){let y=null,A=null;if(hi)d="<remove></remove>"+d;else{let Y=Oc(d,/^[\r\n\t ]+/);A=Y&&Y[0]}Rn==="application/xhtml+xml"&&tn===Ze&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let V=ee?ee.createHTML(d):d;if(tn===Ze)try{y=new p().parseFromString(V,Rn)}catch{}if(!y||!y.documentElement){y=ci.createDocument(tn,"template",null);try{y.documentElement.innerHTML=yi?ft:V}catch{}}let $=y.body||y.documentElement;return d&&A&&$.insertBefore(n.createTextNode(A),$.childNodes[0]||null),tn===Ze?Eu.call(y,St?"html":"body")[0]:St?y.documentElement:$},Aa=function(d){return ua.call(d.ownerDocument||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},ka=function(d){d.normalize();let y=ua.call(d.ownerDocument||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=y.nextNode();for(;A;){let V=A.data;Tn([ur,dr,pr],$=>{V=_n(V,$," ")}),A.data=V,A=y.nextNode()}},yr=function(d){let y=ae?ae(d):null;return typeof y!="string"||se(y)!=="form"?!1:typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||d.attributes!==H(d)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function"||d.nodeType!==X(d)||d.childNodes!==T(d)},On=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return X(d)===rt.documentFragment}catch{return!1}},br=function(d){if(!X||typeof d!="object"||d===null)return!1;try{return typeof X(d)=="number"}catch{return!1}};function st(C,d,y){Tn(C,A=>{A.call(e,d,y,nn)})}let Ia=function(d){let y=null;if(st(pe.beforeSanitizeElements,d,null),yr(d))return Ge(d),!0;let A=se(d.nodeName);if(st(pe.uponSanitizeElement,d,{tagName:A,allowedTags:oe}),Cn&&d.hasChildNodes()&&!br(d.firstElementChild)&&be(/<[/\w!]/g,d.innerHTML)&&be(/<[/\w!]/g,d.textContent)||Cn&&d.namespaceURI===Ze&&A==="style"&&br(d.firstElementChild)||d.nodeType===rt.progressingInstruction||Cn&&d.nodeType===rt.comment&&be(/<[/\w]/g,d.data))return Ge(d),!0;if(In[A]||!(ht.tagCheck instanceof Function&&ht.tagCheck(A))&&!oe[A]){if(!In[A]&&Na(A)&&(ie.tagNameCheck instanceof RegExp&&be(ie.tagNameCheck,A)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(A)))return!1;if(mi&&!Xe[A]){let $=_(d),Y=T(d);if(Y&&$){let Oe=Y.length;for(let Ke=Oe-1;Ke>=0;--Ke){let He=f(Y[Ke],!0);$.insertBefore(He,g(d))}}}return Ge(d),!0}return(X?X(d):d.nodeType)===rt.element&&!Ou(d)||(A==="noscript"||A==="noembed"||A==="noframes")&&be(/<\/no(script|embed|frames)/i,d.innerHTML)?(Ge(d),!0):(mt&&d.nodeType===rt.text&&(y=d.textContent,Tn([ur,dr,pr],$=>{y=_n(y,$," ")}),d.textContent!==y&&(Sn(e.removed,{element:d.cloneNode()}),d.textContent=y)),st(pe.afterSanitizeElements,d,null),!1)},Ca=function(d,y,A){if(fr[y]||ga&&(y==="id"||y==="name")&&(A in n||A in Ru))return!1;let V=le[y]||ht.attributeCheck instanceof Function&&ht.attributeCheck(y,d);if(!(pi&&!fr[y]&&be(Su,y))){if(!(fa&&be(_u,y))){if(!V||fr[y]){if(!(Na(d)&&(ie.tagNameCheck instanceof RegExp&&be(ie.tagNameCheck,d)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(d))&&(ie.attributeNameCheck instanceof RegExp&&be(ie.attributeNameCheck,y)||ie.attributeNameCheck instanceof Function&&ie.attributeNameCheck(y,d))||y==="is"&&ie.allowCustomizedBuiltInElements&&(ie.tagNameCheck instanceof RegExp&&be(ie.tagNameCheck,A)||ie.tagNameCheck instanceof Function&&ie.tagNameCheck(A))))return!1}else if(!vi[y]){if(!be(pa,_n(A,da,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&Mc(A,"data:")===0&&ba[d])){if(!(ha&&!be(wu,_n(A,da,"")))){if(A)return!1}}}}}}return!0},Mu=D({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Na=function(d){return!Mu[er(d)]&&be(Au,d)},Ra=function(d){st(pe.beforeSanitizeAttributes,d,null);let y=d.attributes;if(!y||yr(d))return;let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:le,forceKeepAttr:void 0},V=y.length;for(;V--;){let $=y[V],Y=$.name,Oe=$.namespaceURI,Ke=$.value,He=se(Y),Si=Ke,fe=Y==="value"?Si:am(Si);if(A.attrName=He,A.attrValue=fe,A.keepAttr=!0,A.forceKeepAttr=void 0,st(pe.uponSanitizeAttribute,d,A),fe=A.attrValue,va&&(He==="id"||He==="name")&&Mc(fe,ya)!==0&&(_t(Y,d),fe=ya+fe),Cn&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,fe)){_t(Y,d);continue}if(He==="attributename"&&Oc(fe,"href")){_t(Y,d);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){_t(Y,d);continue}if(!ma&&be(/\/>/i,fe)){_t(Y,d);continue}mt&&Tn([ur,dr,pr],Ma=>{fe=_n(fe,Ma," ")});let Oa=se(d.nodeName);if(!Ca(Oa,He,fe)){_t(Y,d);continue}if(ee&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Oe)switch(m.getAttributeType(Oa,He)){case"TrustedHTML":{fe=ee.createHTML(fe);break}case"TrustedScriptURL":{fe=ee.createScriptURL(fe);break}}if(fe!==Si)try{Oe?d.setAttributeNS(Oe,Y,fe):d.setAttribute(Y,fe),yr(d)?Ge(d):Rc(e.removed)}catch{_t(Y,d)}}st(pe.afterSanitizeAttributes,d,null)},xr=function(d){let y=null,A=Aa(d);for(st(pe.beforeSanitizeShadowDOM,d,null);y=A.nextNode();)if(st(pe.uponSanitizeShadowNode,y,null),Ia(y),Ra(y),On(y.content)&&xr(y.content),(X?X(y):y.nodeType)===rt.element){let $=b?b(y):y.shadowRoot;On($)&&(rn($),xr($))}st(pe.afterSanitizeShadowDOM,d,null)},rn=function(d){let y=X?X(d):d.nodeType;if(y===rt.element){let $=b?b(d):d.shadowRoot;On($)&&(rn($),xr($))}let A=T?T(d):d.childNodes;if(!A)return;let V=[];Tn(A,$=>{Sn(V,$)});for(let $ of V)rn($);if(y===rt.element){let $=ae?ae(d):null;if(typeof $=="string"&&se($)==="template"){let Y=d.content;On(Y)&&rn(Y)}}};return e.sanitize=function(C){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,A=null,V=null,$=null;if(yi=!C,yi&&(C="<!-->"),typeof C!="string"&&!br(C)&&(C=pm(C),typeof C!="string"))throw Qn("dirty is not a string, aborting");if(!e.isSupported)return C;if(fi||Ti(d),e.removed=[],typeof C=="string"&&(Nn=!1),Nn){let Ke=ae?ae(C):C.nodeName;if(typeof Ke=="string"){let He=se(Ke);if(!oe[He]||In[He])throw Qn("root node is forbidden and cannot be sanitized in-place")}if(yr(C))throw Qn("root node is clobbered and cannot be sanitized in-place");rn(C)}else if(br(C))y=wa("<!---->"),A=y.ownerDocument.importNode(C,!0),A.nodeType===rt.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?y=A:y.appendChild(A),rn(A);else{if(!Qt&&!mt&&!St&&C.indexOf("<")===-1)return ee&&mr?ee.createHTML(C):C;if(y=wa(C),!y)return Qt?null:mr?ft:""}y&&hi&&Ge(y.firstChild);let Y=Aa(Nn?C:y);for(;V=Y.nextNode();)Ia(V),Ra(V),On(V.content)&&xr(V.content);if(Nn)return mt&&ka(C),C;if(Qt){if(mt&&ka(y),hr)for($=xu.call(y.ownerDocument);y.firstChild;)$.appendChild(y.firstChild);else $=y;return(le.shadowroot||le.shadowrootmode)&&($=Tu.call(r,$,!0)),$}let Oe=St?y.outerHTML:y.innerHTML;return St&&oe["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&be(Sm,y.ownerDocument.doctype.name)&&(Oe="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
13
+ `+Oe),mt&&Tn([ur,dr,pr],Ke=>{Oe=_n(Oe,Ke," ")}),ee&&mr?ee.createHTML(Oe):Oe},e.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ti(C),fi=!0},e.clearConfig=function(){nn=null,fi=!1},e.isValidAttribute=function(C,d,y){nn||Ti({});let A=se(C),V=se(d);return Ca(A,V,y)},e.addHook=function(C,d){typeof d=="function"&&Sn(pe[C],d)},e.removeHook=function(C,d){if(d!==void 0){let y=im(pe[C],d);return y===-1?void 0:sm(pe[C],y,1)[0]}return Rc(pe[C])},e.removeHooks=function(C){pe[C]=[]},e.removeAllHooks=function(){pe=$c()},e}var Vc=jc();function Zs(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var qt=Zs();function Qc(t){qt=t}var Kt={exec:()=>null};function An(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=e[r];return o||(o=t(r),e[r]=o),o}}function B(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(o,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(Te.caret,"$1"),n=n.replace(o,s),r},getRegex:()=>new RegExp(n,e)};return r}var km=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Te={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:An(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:An(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:An(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:An(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:An(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:An(t=>new RegExp(`^ {0,${t}}>`))},Im=/^(?:[ \t]*(?:\n|$))+/,Cm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Nm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,rr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Rm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ks=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,eu=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,tu=B(eu).replace(/bull/g,Ks).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Om=B(eu).replace(/bull/g,Ks).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),Ys=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Mm=/^[^\n]+/,qs=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Lm=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",qs).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Pm=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Ks).getRegex(),ri="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Js=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Dm=B("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Js).replace("tag",ri).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),nu=B(Ys).replace("hr",rr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ri).getRegex(),Um=B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",nu).getRegex(),Qs={blockquote:Um,code:Cm,def:Lm,fences:Nm,heading:Rm,hr:rr,html:Dm,lheading:tu,list:Pm,newline:Im,paragraph:nu,table:Kt,text:Mm},Wc=B("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",rr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ri).getRegex(),Gm={...Qs,lheading:Om,table:Wc,paragraph:B(Ys).replace("hr",rr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Wc).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",ri).getRegex()},Hm={...Qs,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Js).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Kt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(Ys).replace("hr",rr).replace("heading",` *#{1,6} *[^
14
+ ]`).replace("lheading",tu).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Fm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,$m=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ru=/^( {2,}|\\)\n(?!\s*$)/,zm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,kn=/[\p{P}\p{S}]/u,oi=/[\s\p{P}\p{S}]/u,ea=/[^\s\p{P}\p{S}]/u,Bm=B(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,oi).getRegex(),ou=/(?!~)[\p{P}\p{S}]/u,jm=/(?!~)[\s\p{P}\p{S}]/u,Vm=/(?:[^\s\p{P}\p{S}]|~)/u,Wm=B(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",km?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),iu=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Xm=B(iu,"u").replace(/punct/g,kn).getRegex(),Zm=B(iu,"u").replace(/punct/g,ou).getRegex(),su="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Km=B(su,"gu").replace(/notPunctSpace/g,ea).replace(/punctSpace/g,oi).replace(/punct/g,kn).getRegex(),Ym=B(su,"gu").replace(/notPunctSpace/g,Vm).replace(/punctSpace/g,jm).replace(/punct/g,ou).getRegex(),qm=B("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ea).replace(/punctSpace/g,oi).replace(/punct/g,kn).getRegex(),Jm=B(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,kn).getRegex(),Qm="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",eg=B(Qm,"gu").replace(/notPunctSpace/g,ea).replace(/punctSpace/g,oi).replace(/punct/g,kn).getRegex(),tg=B(/\\(punct)/,"gu").replace(/punct/g,kn).getRegex(),ng=B(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),rg=B(Js).replace("(?:-->|$)","-->").getRegex(),og=B("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",rg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),ei=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ig=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",ei).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),au=B(/^!?\[(label)\]\[(ref)\]/).replace("label",ei).replace("ref",qs).getRegex(),lu=B(/^!?\[(ref)\](?:\[\])?/).replace("ref",qs).getRegex(),sg=B("reflink|nolink(?!\\()","g").replace("reflink",au).replace("nolink",lu).getRegex(),Xc=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ta={_backpedal:Kt,anyPunctuation:tg,autolink:ng,blockSkip:Wm,br:ru,code:$m,del:Kt,delLDelim:Kt,delRDelim:Kt,emStrongLDelim:Xm,emStrongRDelimAst:Km,emStrongRDelimUnd:qm,escape:Fm,link:ig,nolink:lu,punctuation:Bm,reflink:au,reflinkSearch:sg,tag:og,text:zm,url:Kt},ag={...ta,link:B(/^!?\[(label)\]\((.*?)\)/).replace("label",ei).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",ei).getRegex()},Vs={...ta,emStrongRDelimAst:Ym,emStrongLDelim:Zm,delLDelim:Jm,delRDelim:eg,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Xc).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:B(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Xc).getRegex()},lg={...Vs,br:B(ru).replace("{2,}","*").getRegex(),text:B(Vs.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Qo={normal:Qs,gfm:Gm,pedantic:Hm},tr={normal:ta,gfm:Vs,breaks:lg,pedantic:ag},cg={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Zc=t=>cg[t];function it(t,e){if(e){if(Te.escapeTest.test(t))return t.replace(Te.escapeReplace,Zc)}else if(Te.escapeTestNoEncode.test(t))return t.replace(Te.escapeReplaceNoEncode,Zc);return t}function Kc(t){try{t=encodeURI(t).replace(Te.percentDecode,"%")}catch{return null}return t}function Yc(t,e){let n=t.replace(Te.findPipe,(i,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Te.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(Te.slashPipe,"|");return r}function Tt(t,e,n){let r=t.length;if(r===0)return"";let o=0;for(;o<r;){let i=t.charAt(r-o-1);if(i===e&&!n)o++;else if(i!==e&&n)o++;else break}return t.slice(0,r-o)}function qc(t){let e=t.split(`
15
15
  `),n=e.length-1;for(;n>=0&&Te.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
16
- `)}function Ym(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function qm(t,e=0){let n=e,r="";for(let o of t)if(o===" "){let s=4-n%4;r+=" ".repeat(s),n+=s}else r+=o,n++;return r}function Bc(t,e,n,r,o){let s=e.href,i=e.title||null,a=t[1].replace(o.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:s,title:i,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function Jm(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
17
- `).map(s=>{let i=s.match(n.other.beginningSpace);if(i===null)return s;let[a]=i;return a.length>=o.length?s.slice(o.length):s}).join(`
18
- `)}var qo=class{options;rules;lexer;constructor(t){this.options=t||Zt}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:zc(e[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=Jm(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=xt(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:xt(e[0],`
19
- `),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:xt(e[0],`
20
- `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=xt(e[0],`
16
+ `)}function ug(t,e){if(t.indexOf(e[1])===-1)return-1;let n=0;for(let r=0;r<t.length;r++)if(t[r]==="\\")r++;else if(t[r]===e[0])n++;else if(t[r]===e[1]&&(n--,n<0))return r;return n>0?-2:-1}function dg(t,e=0){let n=e,r="";for(let o of t)if(o===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=o,n++;return r}function Jc(t,e,n,r,o){let i=e.href,s=e.title||null,a=t[1].replace(o.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function pg(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
17
+ `).map(i=>{let s=i.match(n.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=o.length?i.slice(o.length):i}).join(`
18
+ `)}var ti=class{options;rules;lexer;constructor(t){this.options=t||qt}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let n=this.options.pedantic?e[0]:qc(e[0]),r=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:r}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let n=e[0],r=pg(n,e[3]||"",this.rules);return{type:"code",raw:n,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:r}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let n=e[2].trim();if(this.rules.other.endingHash.test(n)){let r=Tt(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Tt(e[0],`
19
+ `),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Tt(e[0],`
20
+ `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=Tt(e[0],`
21
21
  `).split(`
22
- `),r="",o="",s=[];for(;n.length>0;){let i=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),i=!0;else if(!i)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
22
+ `),r="",o="",i=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
23
23
  `),p=c.replace(this.rules.other.blockquoteSetextReplace,`
24
24
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
25
25
  ${c}`:c,o=o?`${o}
26
- ${p}`:p;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,s,!0),this.lexer.state.top=m,n.length===0)break;let x=s.at(-1);if(x?.type==="code")break;if(x?.type==="blockquote"){let f=x,h=f.raw+`
26
+ ${p}`:p;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,i,!0),this.lexer.state.top=m,n.length===0)break;let x=i.at(-1);if(x?.type==="code")break;if(x?.type==="blockquote"){let f=x,h=f.raw+`
27
27
  `+n.join(`
28
- `),g=this.blockquote(h);s[s.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,o=o.substring(0,o.length-f.text.length)+g.text;break}else if(x?.type==="list"){let f=x,h=f.raw+`
28
+ `),g=this.blockquote(h);i[i.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,o=o.substring(0,o.length-f.text.length)+g.text;break}else if(x?.type==="list"){let f=x,h=f.raw+`
29
29
  `+n.join(`
30
- `),g=this.list(h);s[s.length-1]=g,r=r.substring(0,r.length-x.raw.length)+g.raw,o=o.substring(0,o.length-f.raw.length)+g.raw,n=h.substring(s.at(-1).raw.length).split(`
31
- `);continue}}return{type:"blockquote",raw:r,tokens:s,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let s=this.rules.other.listItemRegex(n),i=!1;for(;t;){let l=!1,c="",p="";if(!(e=s.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=qm(e[2].split(`
30
+ `),g=this.list(h);i[i.length-1]=g,r=r.substring(0,r.length-x.raw.length)+g.raw,o=o.substring(0,o.length-f.raw.length)+g.raw,n=h.substring(i.at(-1).raw.length).split(`
31
+ `);continue}}return{type:"blockquote",raw:r,tokens:i,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,c="",p="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=dg(e[2].split(`
32
32
  `,1)[0],e[1].length),x=t.split(`
33
33
  `,1)[0],f=!m.trim(),h=0;if(this.options.pedantic?(h=2,p=m.trimStart()):f?h=e[1].length+1:(h=m.search(this.rules.other.nonSpaceChar),h=h>4?1:h,p=m.slice(h),h+=e[1].length),f&&this.rules.other.blankLine.test(x)&&(c+=x+`
34
- `,t=t.substring(x.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(h),T=this.rules.other.hrRegex(h),S=this.rules.other.fencesBeginRegex(h),b=this.rules.other.headingBeginRegex(h),H=this.rules.other.htmlBeginRegex(h),X=this.rules.other.blockquoteBeginRegex(h);for(;t;){let ae=t.split(`
35
- `,1)[0],ee;if(x=ae,this.options.pedantic?(x=x.replace(this.rules.other.listReplaceNesting," "),ee=x):ee=x.replace(this.rules.other.tabCharGlobal," "),S.test(x)||b.test(x)||H.test(x)||X.test(x)||g.test(x)||T.test(x))break;if(ee.search(this.rules.other.nonSpaceChar)>=h||!x.trim())p+=`
36
- `+ee.slice(h);else{if(f||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(m)||b.test(m)||T.test(m))break;p+=`
34
+ `,t=t.substring(x.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(h),T=this.rules.other.hrRegex(h),_=this.rules.other.fencesBeginRegex(h),b=this.rules.other.headingBeginRegex(h),H=this.rules.other.htmlBeginRegex(h),X=this.rules.other.blockquoteBeginRegex(h);for(;t;){let ae=t.split(`
35
+ `,1)[0],ee;if(x=ae,this.options.pedantic?(x=x.replace(this.rules.other.listReplaceNesting," "),ee=x):ee=x.replace(this.rules.other.tabCharGlobal," "),_.test(x)||b.test(x)||H.test(x)||X.test(x)||g.test(x)||T.test(x))break;if(ee.search(this.rules.other.nonSpaceChar)>=h||!x.trim())p+=`
36
+ `+ee.slice(h);else{if(f||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(m)||b.test(m)||T.test(m))break;p+=`
37
37
  `+x}f=!x.trim(),c+=ae+`
38
- `,t=t.substring(ae.length+1),m=ee.slice(h)}}o.loose||(i?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(i=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let m={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=m.checked,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1);if(!o.loose){let p=l.tokens.filter(x=>x.type==="space"),m=p.length>0&&p.some(x=>this.rules.other.anyLine.test(x.raw));o.loose=m}}if(o.loose)for(let l of o.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=zc(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:xt(e[0],`
39
- `),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=$c(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
40
- `):[],s={type:"table",raw:xt(e[0],`
41
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let i of r)this.rules.other.tableAlignRight.test(i)?s.align.push("right"):this.rules.other.tableAlignCenter.test(i)?s.align.push("center"):this.rules.other.tableAlignLeft.test(i)?s.align.push("left"):s.align.push(null);for(let i=0;i<n.length;i++)s.header.push({text:n[i],tokens:this.lexer.inline(n[i]),header:!0,align:s.align[i]});for(let i of o)s.rows.push($c(i,s.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:s.align[l]})));return s}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:xt(e[0],`
38
+ `,t=t.substring(ae.length+1),m=ee.slice(h)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let p=this.rules.other.listTaskCheckbox.exec(l.raw);if(p){let m={type:"checkbox",raw:p[0]+" ",checked:p[0]!=="[ ]"};l.checked=m.checked,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1);if(!o.loose){let p=l.tokens.filter(x=>x.type==="space"),m=p.length>0&&p.some(x=>this.rules.other.anyLine.test(x.raw));o.loose=m}}if(o.loose)for(let l of o.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=qc(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:Tt(e[0],`
39
+ `),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Yc(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
40
+ `):[],i={type:"table",raw:Tt(e[0],`
41
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?i.align.push("right"):this.rules.other.tableAlignCenter.test(s)?i.align.push("center"):this.rules.other.tableAlignLeft.test(s)?i.align.push("left"):i.align.push(null);for(let s=0;s<n.length;s++)i.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:i.align[s]});for(let s of o)i.rows.push(Yc(s,i.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:i.align[l]})));return i}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:Tt(e[0],`
42
42
  `),depth:e[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let n=e[1].charAt(e[1].length-1)===`
43
- `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let s=xt(n.slice(0,-1),"\\");if((n.length-s.length)%2===0)return}else{let s=Ym(e[2],"()");if(s===-2)return;if(s>-1){let i=(e[0].indexOf("!")===0?5:4)+e[1].length+s;e[2]=e[2].substring(0,s),e[0]=e[0].substring(0,i).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let s=this.rules.other.pedanticHrefTitle.exec(r);s&&(r=s[1],o=s[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Bc(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[r.toLowerCase()];if(!o){let s=n[0].charAt(0);return{type:"text",raw:s,text:s}}return Bc(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,s,i,a=o,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+o);(r=c.exec(e))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s)continue;if(i=[...s].length,r[3]||r[4]){a+=i;continue}else if((r[5]||r[6])&&o%3&&!((o+i)%3)){l+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a+l);let p=[...r[0]][0].length,m=t.slice(0,o+r.index+p+i);if(Math.min(o,i)%2){let f=m.slice(1,-1);return{type:"em",raw:m,text:f,tokens:this.lexer.inlineTokens(f)}}let x=m.slice(2,-2);return{type:"strong",raw:m,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,s,i,a=o,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+o);(r=l.exec(e))!==null;){if(s=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!s||(i=[...s].length,i!==o))continue;if(r[3]||r[4]){a+=i;continue}if(a-=i,a>0)continue;i=Math.min(i,i+a);let c=[...r[0]][0].length,p=t.slice(0,o+r.index+c+i),m=p.slice(o,-o);return{type:"del",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},ze=class Mi{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Zt,this.options.tokenizer=this.options.tokenizer||new qo,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Te,block:Ko.normal,inline:Jn.normal};this.options.pedantic?(n.block=Ko.pedantic,n.inline=Jn.pedantic):this.options.gfm&&(n.block=Ko.gfm,this.options.breaks?n.inline=Jn.breaks:n.inline=Jn.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ko,inline:Jn}}static lex(e,n){return new Mi(n).lex(e)}static lexInline(e,n){return new Mi(n).inlineTokens(e)}lex(e){e=e.replace(Te.carriageReturn,`
44
- `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Te.tabCharGlobal," ").replace(Te.spaceLine,""));let o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let s;if(this.options.extensions?.block?.some(a=>(s=a.call({lexer:this},e,n))?(e=e.substring(s.raw.length),n.push(s),!0):!1))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);let a=n.at(-1);s.raw.length===1&&a!==void 0?a.raw+=`
45
- `:n.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
43
+ `?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=Tt(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=ug(e[2],"()");if(i===-2)return;if(i>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Jc(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[r.toLowerCase()];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Jc(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+o);(r=c.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(s=[...i].length,r[3]||r[4]){a+=s;continue}else if((r[5]||r[6])&&o%3&&!((o+s)%3)){l+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let p=[...r[0]][0].length,m=t.slice(0,o+r.index+p+s);if(Math.min(o,s)%2){let f=m.slice(1,-1);return{type:"em",raw:m,text:f,tokens:this.lexer.inlineTokens(f)}}let x=m.slice(2,-2);return{type:"strong",raw:m,text:x,tokens:this.lexer.inlineTokens(x)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+o);(r=l.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(s=[...i].length,s!==o))continue;if(r[3]||r[4]){a+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a);let c=[...r[0]][0].length,p=t.slice(0,o+r.index+c+s),m=p.slice(o,-o);return{type:"del",raw:p,text:m,tokens:this.lexer.inlineTokens(m)}}}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let n,r;return e[2]==="@"?(n=e[1],r="mailto:"+n):(n=e[1],r=n),{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let n,r;if(e[2]==="@")n=e[0],r="mailto:"+n;else{let o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},Ve=class Ws{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||qt,this.options.tokenizer=this.options.tokenizer||new ti,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:Te,block:Qo.normal,inline:tr.normal};this.options.pedantic?(n.block=Qo.pedantic,n.inline=tr.pedantic):this.options.gfm&&(n.block=Qo.gfm,this.options.breaks?n.inline=tr.breaks:n.inline=tr.gfm),this.tokenizer.rules=n}static get rules(){return{block:Qo,inline:tr}}static lex(e,n){return new Ws(n).lex(e)}static lexInline(e,n){return new Ws(n).inlineTokens(e)}lex(e){e=e.replace(Te.carriageReturn,`
44
+ `),this.blockTokens(e,this.tokens);for(let n=0;n<this.inlineQueue.length;n++){let r=this.inlineQueue[n];this.inlineTokens(r.src,r.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,n=[],r=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Te.tabCharGlobal," ").replace(Te.spaceLine,""));let o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(a=>(i=a.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let a=n.at(-1);i.raw.length===1&&a!==void 0?a.raw+=`
45
+ `:n.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
46
46
  `)?"":`
47
- `)+s.raw,a.text+=`
48
- `+s.text,this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
47
+ `)+i.raw,a.text+=`
48
+ `+i.text,this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
49
49
  `)?"":`
50
- `)+s.raw,a.text+=`
51
- `+s.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title},n.push(s));continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),n.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),n.push(s);continue}let i=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),c;this.options.extensions.startBlock.forEach(p=>{c=p.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(i=e.substring(0,a+1))}if(this.state.top&&(s=this.tokenizer.paragraph(i))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
50
+ `)+i.raw,a.text+=`
51
+ `+i.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),n.push(i);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),c;this.options.extensions.startBlock.forEach(p=>{c=p.call({lexer:this},l),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&a>=0&&(s=e.substring(0,a+1))}if(this.state.top&&(i=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
52
52
  `)?"":`
53
- `)+s.raw,a.text+=`
54
- `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s),r=i.length!==e.length,e=e.substring(s.raw.length);continue}if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
53
+ `)+i.raw,a.text+=`
54
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i),r=s.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
55
55
  `)?"":`
56
- `)+s.raw,a.text+=`
57
- `+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(s);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,o=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,o.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let s;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)s=o[2]?o[2].length:0,r=r.slice(0,o.index+s)+"["+"a".repeat(o[0].length-s-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let i=!1,a="",l=1/0;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(a=""),i=!1;let c;if(this.options.extensions?.inline?.some(m=>(c=m.call({lexer:this},e,n))?(e=e.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let m=n.at(-1);c.type==="text"&&m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),n.push(c);continue}let p=e;if(this.options.extensions?.startInline){let m=1/0,x=e.slice(1),f;this.options.extensions.startInline.forEach(h=>{f=h.call({lexer:this},x),typeof f=="number"&&f>=0&&(m=Math.min(m,f))}),m<1/0&&m>=0&&(p=e.substring(0,m+1))}if(c=this.tokenizer.inlineText(p)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),i=!0;let m=n.at(-1);m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},Jo=class{options;parser;constructor(t){this.options=t||Zt}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Te.notSpaceStart)?.[0],o=t.replace(Te.endingNewline,"")+`
58
- `;return r?'<pre><code class="language-'+ot(r)+'">'+(n?o:ot(o,!0))+`</code></pre>
59
- `:"<pre><code>"+(n?o:ot(o,!0))+`</code></pre>
56
+ `)+i.raw,a.text+=`
57
+ `+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e,o=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,o.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)i=o[2]?o[2].length:0,r=r.slice(0,o.index+i)+"["+"a".repeat(o[0].length-i-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let s=!1,a="",l=1/0;for(;e;){if(e.length<l)l=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(a=""),s=!1;let c;if(this.options.extensions?.inline?.some(m=>(c=m.call({lexer:this},e,n))?(e=e.substring(c.raw.length),n.push(c),!0):!1))continue;if(c=this.tokenizer.escape(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.tag(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.link(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(c.raw.length);let m=n.at(-1);c.type==="text"&&m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(c=this.tokenizer.emStrong(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.codespan(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.br(e)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.del(e,r,a)){e=e.substring(c.raw.length),n.push(c);continue}if(c=this.tokenizer.autolink(e)){e=e.substring(c.raw.length),n.push(c);continue}if(!this.state.inLink&&(c=this.tokenizer.url(e))){e=e.substring(c.raw.length),n.push(c);continue}let p=e;if(this.options.extensions?.startInline){let m=1/0,x=e.slice(1),f;this.options.extensions.startInline.forEach(h=>{f=h.call({lexer:this},x),typeof f=="number"&&f>=0&&(m=Math.min(m,f))}),m<1/0&&m>=0&&(p=e.substring(0,m+1))}if(c=this.tokenizer.inlineText(p)){e=e.substring(c.raw.length),c.raw.slice(-1)!=="_"&&(a=c.raw.slice(-1)),s=!0;let m=n.at(-1);m?.type==="text"?(m.raw+=c.raw,m.text+=c.text):n.push(c);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}infiniteLoopError(e){let n="Infinite loop on byte: "+e;if(this.options.silent)console.error(n);else throw new Error(n)}},ni=class{options;parser;constructor(t){this.options=t||qt}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Te.notSpaceStart)?.[0],o=t.replace(Te.endingNewline,"")+`
58
+ `;return r?'<pre><code class="language-'+it(r)+'">'+(n?o:it(o,!0))+`</code></pre>
59
+ `:"<pre><code>"+(n?o:it(o,!0))+`</code></pre>
60
60
  `}blockquote({tokens:t}){return`<blockquote>
61
61
  ${this.parser.parse(t)}</blockquote>
62
62
  `}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`<h${e}>${this.parser.parseInline(t)}</h${e}>
63
63
  `}hr(t){return`<hr>
64
- `}list(t){let e=t.ordered,n=t.start,r="";for(let i=0;i<t.items.length;i++){let a=t.items[i];r+=this.listitem(a)}let o=e?"ol":"ul",s=e&&n!==1?' start="'+n+'"':"";return"<"+o+s+`>
64
+ `}list(t){let e=t.ordered,n=t.start,r="";for(let s=0;s<t.items.length;s++){let a=t.items[s];r+=this.listitem(a)}let o=e?"ol":"ul",i=e&&n!==1?' start="'+n+'"':"";return"<"+o+i+`>
65
65
  `+r+"</"+o+`>
66
66
  `}listitem(t){return`<li>${this.parser.parse(t.tokens)}</li>
67
67
  `}checkbox({checked:t}){return"<input "+(t?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:t}){return`<p>${this.parser.parseInline(t)}</p>
68
- `}table(t){let e="",n="";for(let o=0;o<t.header.length;o++)n+=this.tablecell(t.header[o]);e+=this.tablerow({text:n});let r="";for(let o=0;o<t.rows.length;o++){let s=t.rows[o];n="";for(let i=0;i<s.length;i++)n+=this.tablecell(s[i]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
68
+ `}table(t){let e="",n="";for(let o=0;o<t.header.length;o++)n+=this.tablecell(t.header[o]);e+=this.tablerow({text:n});let r="";for(let o=0;o<t.rows.length;o++){let i=t.rows[o];n="";for(let s=0;s<i.length;s++)n+=this.tablecell(i[s]);r+=this.tablerow({text:n})}return r&&(r=`<tbody>${r}</tbody>`),`<table>
69
69
  <thead>
70
70
  `+e+`</thead>
71
71
  `+r+`</table>
72
72
  `}tablerow({text:t}){return`<tr>
73
73
  ${t}</tr>
74
74
  `}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
75
- `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${ot(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=Fc(t);if(o===null)return r;t=o;let s='<a href="'+t+'"';return e&&(s+=' title="'+ot(e)+'"'),s+=">"+r+"</a>",s}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Fc(t);if(o===null)return ot(n);t=o;let s=`<img src="${t}" alt="${ot(n)}"`;return e&&(s+=` title="${ot(e)}"`),s+=">",s}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:ot(t.text)}},Bi=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},Be=class Li{options;renderer;textRenderer;constructor(e){this.options=e||Zt,this.options.renderer=this.options.renderer||new Jo,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Bi}static parse(e,n){return new Li(n).parse(e)}static parseInline(e,n){return new Li(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let i=o,a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(i.type)){n+=a||"";continue}}let s=o;switch(s.type){case"space":{n+=this.renderer.space(s);break}case"hr":{n+=this.renderer.hr(s);break}case"heading":{n+=this.renderer.heading(s);break}case"code":{n+=this.renderer.code(s);break}case"table":{n+=this.renderer.table(s);break}case"blockquote":{n+=this.renderer.blockquote(s);break}case"list":{n+=this.renderer.list(s);break}case"checkbox":{n+=this.renderer.checkbox(s);break}case"html":{n+=this.renderer.html(s);break}case"def":{n+=this.renderer.def(s);break}case"paragraph":{n+=this.renderer.paragraph(s);break}case"text":{n+=this.renderer.text(s);break}default:{let i='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let s=e[o];if(this.options.extensions?.renderers?.[s.type]){let a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type)){r+=a||"";continue}}let i=s;switch(i.type){case"escape":{r+=n.text(i);break}case"html":{r+=n.html(i);break}case"link":{r+=n.link(i);break}case"image":{r+=n.image(i);break}case"checkbox":{r+=n.checkbox(i);break}case"strong":{r+=n.strong(i);break}case"em":{r+=n.em(i);break}case"codespan":{r+=n.codespan(i);break}case"br":{r+=n.br(i);break}case"del":{r+=n.del(i);break}case"text":{r+=n.text(i);break}default:{let a='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},Qn=class{options;block;constructor(t){this.options=t||Zt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?ze.lex:ze.lexInline}provideParser(t=this.block){return t?Be.parse:Be.parseInline}},Vi=class{defaults=Pi();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Be;Renderer=Jo;TextRenderer=Bi;Lexer=ze;Tokenizer=qo;Hooks=Qn;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let o=r;for(let s of o.header)n=n.concat(this.walkTokens(s.tokens,e));for(let s of o.rows)for(let i of s)n=n.concat(this.walkTokens(i.tokens,e));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(s=>{let i=o[s].flat(1/0);n=n.concat(this.walkTokens(i,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let s=e.renderers[o.name];s?e.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let s=e[o.level];s?s.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new Jo(this.defaults);for(let s in n.renderer){if(!(s in o))throw new Error(`renderer '${s}' does not exist`);if(["options","parser"].includes(s))continue;let i=s,a=n.renderer[i],l=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new qo(this.defaults);for(let s in n.tokenizer){if(!(s in o))throw new Error(`tokenizer '${s}' does not exist`);if(["options","rules","lexer"].includes(s))continue;let i=s,a=n.tokenizer[i],l=o[i];o[i]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Qn;for(let s in n.hooks){if(!(s in o))throw new Error(`hook '${s}' does not exist`);if(["options","block"].includes(s))continue;let i=s,a=n.hooks[i],l=o[i];Qn.passThroughHooks.has(s)?o[i]=c=>{if(this.defaults.async&&Qn.passThroughHooksRespectAsync.has(s))return(async()=>{let m=await a.call(o,c);return l.call(o,m)})();let p=a.call(o,c);return l.call(o,p)}:o[i]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await l.apply(o,c)),m})();let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,s=n.walkTokens;r.walkTokens=function(i){let a=[];return a.push(s.call(this,i)),o&&(a=a.concat(o.call(this,i))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return ze.lex(t,e??this.defaults)}parser(t,e){return Be.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},s=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return s(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return s(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return s(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let i=o.hooks?await o.hooks.preprocess(e):e,a=await(o.hooks?await o.hooks.provideLexer(t):t?ze.lex:ze.lexInline)(i,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(t):t?Be.parse:Be.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(s);try{o.hooks&&(e=o.hooks.preprocess(e));let i=(o.hooks?o.hooks.provideLexer(t):t?ze.lex:ze.lexInline)(e,o);o.hooks&&(i=o.hooks.processAllTokens(i)),o.walkTokens&&this.walkTokens(i,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(t):t?Be.parse:Be.parseInline)(i,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(i){return s(i)}}}onError(t,e){return n=>{if(n.message+=`
76
- Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+ot(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Xt=new Vi;function Z(t,e){return Xt.parse(t,e)}Z.options=Z.setOptions=function(t){return Xt.setOptions(t),Z.defaults=Xt.defaults,Vc(Z.defaults),Z};Z.getDefaults=Pi;Z.defaults=Zt;Z.use=function(...t){return Xt.use(...t),Z.defaults=Xt.defaults,Vc(Z.defaults),Z};Z.walkTokens=function(t,e){return Xt.walkTokens(t,e)};Z.parseInline=Xt.parseInline;Z.Parser=Be;Z.parser=Be.parse;Z.Renderer=Jo;Z.TextRenderer=Bi;Z.Lexer=ze;Z.lexer=ze.lex;Z.Tokenizer=qo;Z.Hooks=Qn;Z.parse=Z;var NT=Z.options,RT=Z.setOptions,OT=Z.use,MT=Z.walkTokens,LT=Z.parseInline;var PT=Be.parse,DT=ze.lex;var Qm=new Vi({gfm:!0,breaks:!0}),eu=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],tu=["href","title","class"],eg=[...eu,"img"],tg=[...tu,"src","alt","width","height"];function ts(t,e){let n=e?.allowImages===!0,r=Qm.parse(t,{async:!1}),o=Dc.sanitize(r,{ALLOWED_TAGS:n?eg:eu,ALLOWED_ATTR:n?tg:tu}),s=document.createElement("template");s.innerHTML=o;for(let i of s.content.querySelectorAll("a[href]"))i.setAttribute("target","_blank"),i.setAttribute("rel","noopener noreferrer");return s.innerHTML.trim()}function nu(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):nu(n,e)}function ru(t){let e=[];nu(t,e);let n=0;for(let{node:r,parent:o}of e){let s=document.createDocumentFragment();for(let i of r.data.split(/(\s+)/)){if(i==="")continue;if(/\s/.test(i)){s.appendChild(document.createTextNode(i));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=i,s.appendChild(a),n+=1}o.replaceChild(s,r)}}var ns=class{chips;palette;#e;#t=[];#o=!1;#i=!1;#a=[];#r=0;constructor(e){this.#e=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#t=e,this.#h()}enableChips(e){this.#o=e,this.#h()}enableSlash(e){this.#i=e}isOpen(){return!this.palette.hidden}onInput(e){this.#i&&e.startsWith("/")?this.#n(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#s(1),!0):e.key==="ArrowUp"?(this.#s(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#a.slice(this.#r,this.#r+1).forEach(n=>{this.#l(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#n(e){let n=e.trim().toLowerCase(),r=this.#t.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#a=r,this.#r=0,this.#u(),this.palette.hidden=!1}#s(e){let n=this.#a.length;this.#r=(this.#r+e+n)%n,this.#u()}#l(e){this.close(),this.#e(e)}#h(){this.chips.replaceChildren();let e=this.#o?this.#t.filter(n=>n.chip===!0):[];this.chips.hidden=e.length===0;for(let n of e){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.textContent=n.title,r.addEventListener("click",()=>this.#l(n)),this.chips.appendChild(r)}}#u(){this.palette.replaceChildren(),this.#a.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#r?"true":"false");let o=document.createElement("span");if(o.className="skill-item-title",o.textContent=e.title,r.appendChild(o),e.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.textContent=e.description,r.appendChild(s)}r.addEventListener("click",()=>this.#l(e)),this.palette.appendChild(r)})}};var ou=`
75
+ `}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${it(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=Kc(t);if(o===null)return r;t=o;let i='<a href="'+t+'"';return e&&(i+=' title="'+it(e)+'"'),i+=">"+r+"</a>",i}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Kc(t);if(o===null)return it(n);t=o;let i=`<img src="${t}" alt="${it(n)}"`;return e&&(i+=` title="${it(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:it(t.text)}},na=class{strong({text:t}){return t}em({text:t}){return t}codespan({text:t}){return t}del({text:t}){return t}html({text:t}){return t}text({text:t}){return t}link({text:t}){return""+t}image({text:t}){return""+t}br(){return""}checkbox({raw:t}){return t}},We=class Xs{options;renderer;textRenderer;constructor(e){this.options=e||qt,this.options.renderer=this.options.renderer||new ni,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new na}static parse(e,n){return new Xs(n).parse(e)}static parseInline(e,n){return new Xs(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let s=o,a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(s.type)){n+=a||"";continue}}let i=o;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let s='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let i=e[o];if(this.options.extensions?.renderers?.[i.type]){let a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(i.type)){r+=a||"";continue}}let s=i;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},nr=class{options;block;constructor(t){this.options=t||qt}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?Ve.lex:Ve.lexInline}provideParser(t=this.block){return t?We.parse:We.parseInline}},ra=class{defaults=Zs();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=We;Renderer=ni;TextRenderer=na;Lexer=Ve;Tokenizer=ti;Hooks=nr;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let o=r;for(let i of o.header)n=n.concat(this.walkTokens(i.tokens,e));for(let i of o.rows)for(let s of i)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(i=>{let s=o[i].flat(1/0);n=n.concat(this.walkTokens(s,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let i=e.renderers[o.name];i?e.renderers[o.name]=function(...s){let a=o.renderer.apply(this,s);return a===!1&&(a=i.apply(this,s)),a}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[o.level];i?i.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new ni(this.defaults);for(let i in n.renderer){if(!(i in o))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let s=i,a=n.renderer[s],l=o[s];o[s]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new ti(this.defaults);for(let i in n.tokenizer){if(!(i in o))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let s=i,a=n.tokenizer[s],l=o[s];o[s]=(...c)=>{let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new nr;for(let i in n.hooks){if(!(i in o))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let s=i,a=n.hooks[s],l=o[s];nr.passThroughHooks.has(i)?o[s]=c=>{if(this.defaults.async&&nr.passThroughHooksRespectAsync.has(i))return(async()=>{let m=await a.call(o,c);return l.call(o,m)})();let p=a.call(o,c);return l.call(o,p)}:o[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await l.apply(o,c)),m})();let p=a.apply(o,c);return p===!1&&(p=l.apply(o,c)),p}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(i.call(this,s)),o&&(a=a.concat(o.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Ve.lex(t,e??this.defaults)}parser(t,e){return We.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let s=o.hooks?await o.hooks.preprocess(e):e,a=await(o.hooks?await o.hooks.provideLexer(t):t?Ve.lex:Ve.lexInline)(s,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(t):t?We.parse:We.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(i);try{o.hooks&&(e=o.hooks.preprocess(e));let s=(o.hooks?o.hooks.provideLexer(t):t?Ve.lex:Ve.lexInline)(e,o);o.hooks&&(s=o.hooks.processAllTokens(s)),o.walkTokens&&this.walkTokens(s,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(t):t?We.parse:We.parseInline)(s,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(s){return i(s)}}}onError(t,e){return n=>{if(n.message+=`
76
+ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+it(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Yt=new ra;function Z(t,e){return Yt.parse(t,e)}Z.options=Z.setOptions=function(t){return Yt.setOptions(t),Z.defaults=Yt.defaults,Qc(Z.defaults),Z};Z.getDefaults=Zs;Z.defaults=qt;Z.use=function(...t){return Yt.use(...t),Z.defaults=Yt.defaults,Qc(Z.defaults),Z};Z.walkTokens=function(t,e){return Yt.walkTokens(t,e)};Z.parseInline=Yt.parseInline;Z.Parser=We;Z.parser=We.parse;Z.Renderer=ni;Z.TextRenderer=na;Z.Lexer=Ve;Z.lexer=Ve.lex;Z.Tokenizer=ti;Z.Hooks=nr;Z.parse=Z;var ZT=Z.options,KT=Z.setOptions,YT=Z.use,qT=Z.walkTokens,JT=Z.parseInline;var QT=We.parse,eS=Ve.lex;var fg=new ra({gfm:!0,breaks:!0}),cu=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],uu=["href","title","class"],hg=[...cu,"img"],mg=[...uu,"src","alt","width","height"];function ii(t,e){let n=e?.allowImages===!0,r=fg.parse(t,{async:!1}),o=Vc.sanitize(r,{ALLOWED_TAGS:n?hg:cu,ALLOWED_ATTR:n?mg:uu}),i=document.createElement("template");i.innerHTML=o;for(let s of i.content.querySelectorAll("a[href]"))s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer");return i.innerHTML.trim()}function du(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):du(n,e)}function pu(t){let e=[];du(t,e);let n=0;for(let{node:r,parent:o}of e){let i=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){i.appendChild(document.createTextNode(s));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=s,i.appendChild(a),n+=1}o.replaceChild(i,r)}}var si=class{chips;palette;#t;#e=[];#n=!1;#o=!1;#l=[];#i=0;constructor(e){this.#t=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#e=e,this.#c()}enableChips(e){this.#n=e,this.#c()}enableSlash(e){this.#o=e}isOpen(){return!this.palette.hidden}onInput(e){this.#o&&e.startsWith("/")?this.#s(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#r(1),!0):e.key==="ArrowUp"?(this.#r(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#l.slice(this.#i,this.#i+1).forEach(n=>{this.#a(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#s(e){let n=e.trim().toLowerCase(),r=this.#e.filter(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#l=r,this.#i=0,this.#h(),this.palette.hidden=!1}#r(e){let n=this.#l.length;this.#i=(this.#i+e+n)%n,this.#h()}#a(e){this.close(),this.#t(e)}#c(){this.chips.replaceChildren();let e=this.#n?this.#e.filter(n=>n.chip===!0):[];this.chips.hidden=e.length===0;for(let n of e){let r=document.createElement("button");r.type="button",r.className="skill-chip",r.textContent=n.title,r.addEventListener("click",()=>this.#a(n)),this.chips.appendChild(r)}}#h(){this.palette.replaceChildren(),this.#l.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#i?"true":"false");let o=document.createElement("span");if(o.className="skill-item-title",o.textContent=e.title,r.appendChild(o),e.description!==void 0){let i=document.createElement("span");i.className="skill-item-desc",i.textContent=e.description,r.appendChild(i)}r.addEventListener("click",()=>this.#a(e)),this.palette.appendChild(r)})}};var fu=`
77
77
  :host {
78
78
  /* Colors */
79
79
  --ag-ui-bg: #ffffff;
@@ -95,6 +95,17 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
95
95
  --ag-ui-danger: #b91c1c;
96
96
  --ag-ui-muted: #6b7280;
97
97
 
98
+ /* Tool-call status icon glyphs (override to re-theme) + spinner speed.
99
+ The pending state is the animated ring; the settled states use these. */
100
+ --ag-ui-tool-icon-done: "\u2713";
101
+ --ag-ui-tool-icon-error: "\u2715";
102
+ --ag-ui-tool-icon-declined: "\u2298";
103
+ --ag-ui-tool-spin-duration: 0.7s;
104
+
105
+ /* Answer well (opt-in via data-answer-well) \u2014 boxes a whole assistant turn. */
106
+ --ag-ui-well-bg: transparent;
107
+ --ag-ui-well-border: var(--ag-ui-border);
108
+
98
109
  /* Surface \u2014 set --ag-ui-shadow: none for a flush, embedded panel. */
99
110
  --ag-ui-shadow: 0 12px 32px rgba(20, 20, 50, 0.18);
100
111
  --ag-ui-font: inherit;
@@ -117,6 +128,8 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
117
128
  --ag-ui-inset: auto 24px 24px auto;
118
129
  --ag-ui-max-width: calc(100vw - 48px);
119
130
  --ag-ui-max-height: calc(100vh - 48px);
131
+ /* Reading-column width for placement="page" (full-bleed, centred content). */
132
+ --ag-ui-content-max-width: 820px;
120
133
 
121
134
  position: var(--ag-ui-position);
122
135
  inset: var(--ag-ui-inset);
@@ -204,6 +217,99 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
204
217
  --ag-ui-radius: 0;
205
218
  }
206
219
 
220
+ /* Page (PAGE-1): full-bleed background with a centred reading column. Unlike
221
+ "full" (edge-to-edge, left-aligned messages) the content sits in a column
222
+ capped at --ag-ui-content-max-width. The column is produced by symmetric auto
223
+ padding on the scroll area + composer (no per-row wrapper), so user pills
224
+ still right-align and the assistant well spans the column. */
225
+ :host([placement="page"]) {
226
+ --ag-ui-inset: 0;
227
+ --ag-ui-width: 100vw;
228
+ --ag-ui-height: 100vh;
229
+ --ag-ui-max-width: 100vw;
230
+ --ag-ui-max-height: 100vh;
231
+ --ag-ui-radius: 0;
232
+ }
233
+
234
+ :host([placement="page"]) .messages {
235
+ padding-inline: max(var(--ag-ui-pad), calc((100% - var(--ag-ui-content-max-width)) / 2));
236
+ }
237
+
238
+ :host([placement="page"]) .input-row {
239
+ padding-inline: max(12px, calc((100% - var(--ag-ui-content-max-width)) / 2));
240
+ }
241
+
242
+ /* In the reading column the assistant well uses the full width; the user
243
+ message stays a right-aligned pill (its default align-self + max-width). */
244
+ :host([placement="page"]) .message--assistant {
245
+ max-width: 100%;
246
+ }
247
+
248
+ /* Sidebar (CUST-3): a full-height docked panel that slides open/closed and
249
+ collapses to a slim icon rail (not the floating launcher). Docked right by
250
+ default; data-side="left" docks it left. Overlay by default \u2014 set
251
+ --ag-ui-position: static (and place this element in your own layout) for a
252
+ host-managed push instead. */
253
+ :host([placement="sidebar"]) {
254
+ --ag-ui-inset: 0 0 0 auto;
255
+ --ag-ui-width: 420px;
256
+ --ag-ui-height: 100vh;
257
+ --ag-ui-max-height: 100vh;
258
+ --ag-ui-radius: 0;
259
+ --ag-ui-rail-width: 52px;
260
+ transition: width 0.28s ease;
261
+ }
262
+
263
+ :host([placement="sidebar"][data-side="left"]) {
264
+ --ag-ui-inset: 0 auto 0 0;
265
+ }
266
+
267
+ :host([placement="sidebar"]) .chat {
268
+ transition: transform 0.28s ease;
269
+ }
270
+
271
+ /* Collapsed sidebar: shrink the host to the rail width, hide the panel, and
272
+ reveal the rail. Higher specificity than the generic collapse rules, so it
273
+ wins regardless of source order. */
274
+ :host([placement="sidebar"][collapsed]) {
275
+ width: var(--ag-ui-rail-width);
276
+ height: 100vh;
277
+ max-height: 100vh;
278
+ bottom: 0;
279
+ }
280
+
281
+ :host([placement="sidebar"][collapsed]) .chat {
282
+ display: none;
283
+ }
284
+
285
+ /* The rail is a sibling of the panel (so it survives the panel being hidden);
286
+ shown only for a collapsed sidebar. */
287
+ .rail {
288
+ display: none;
289
+ border: none;
290
+ font: inherit;
291
+ }
292
+
293
+ :host([placement="sidebar"][collapsed]) .rail {
294
+ display: flex;
295
+ position: absolute;
296
+ inset: 0;
297
+ align-items: flex-start;
298
+ justify-content: center;
299
+ padding-top: 16px;
300
+ border: 1px solid var(--ag-ui-border);
301
+ background: var(--ag-ui-header-bg);
302
+ color: var(--ag-ui-header-fg);
303
+ cursor: pointer;
304
+ }
305
+
306
+ @media (prefers-reduced-motion: reduce) {
307
+ :host([placement="sidebar"]),
308
+ :host([placement="sidebar"]) .chat {
309
+ transition: none;
310
+ }
311
+ }
312
+
207
313
  /* Embedded: drop the floating chrome and the high z-index stacking context so
208
314
  the widget lives in the host's own layout (fixes overlay/z-index clashes). */
209
315
  :host([placement="embedded"]) {
@@ -241,12 +347,33 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
241
347
  }
242
348
 
243
349
  .header-title {
350
+ flex: 1;
351
+ min-width: 0;
244
352
  font-weight: 600;
245
353
  overflow: hidden;
246
354
  text-overflow: ellipsis;
247
355
  white-space: nowrap;
248
356
  }
249
357
 
358
+ /* Header / launcher icon holder (CUST-2): a slot, with a data-icon-url <img>
359
+ fallback, sized via --ag-ui-icon-size. */
360
+ .icon-holder {
361
+ display: inline-flex;
362
+ align-items: center;
363
+ justify-content: center;
364
+ flex: none;
365
+ width: var(--ag-ui-icon-size, 22px);
366
+ height: var(--ag-ui-icon-size, 22px);
367
+ line-height: 1;
368
+ }
369
+
370
+ .icon-img {
371
+ width: 100%;
372
+ height: 100%;
373
+ object-fit: contain;
374
+ border-radius: var(--ag-ui-icon-radius, 4px);
375
+ }
376
+
250
377
  .header-controls {
251
378
  display: flex;
252
379
  gap: 2px;
@@ -302,6 +429,39 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
302
429
  gap: var(--ag-ui-space);
303
430
  }
304
431
 
432
+ /* Empty-state region (CUST-1 slot): centred while it's the only thing in the
433
+ list, hidden as soon as a message, card, or pending indicator renders. */
434
+ .empty {
435
+ margin: auto;
436
+ text-align: center;
437
+ color: var(--ag-ui-muted);
438
+ }
439
+
440
+ .empty[hidden] {
441
+ display: none;
442
+ }
443
+
444
+ /* \u2500\u2500 Answer group / well (WELL-1) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
445
+ One .answer per assistant turn wraps the streamed text, its tool cards,
446
+ and the pending indicator so a whole answer reads (and can be boxed) as one
447
+ unit. A flex column on the message-list gap, stretched to the list width so
448
+ its children keep their own left/right alignment. data-answer-well opts into
449
+ the bordered "well"; without it the layout is today's flat stack. */
450
+ .answer {
451
+ display: flex;
452
+ flex-direction: column;
453
+ gap: var(--ag-ui-space);
454
+ align-self: stretch;
455
+ min-width: 0;
456
+ }
457
+
458
+ :host([data-answer-well]) .answer {
459
+ padding: var(--ag-ui-pad);
460
+ background: var(--ag-ui-well-bg);
461
+ border: 1px solid var(--ag-ui-well-border);
462
+ border-radius: var(--ag-ui-radius);
463
+ }
464
+
305
465
  .message {
306
466
  max-width: 80%;
307
467
  padding: var(--ag-ui-msg-pad);
@@ -474,10 +634,71 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
474
634
  }
475
635
 
476
636
  .tool-call-name {
637
+ flex: 1;
638
+ min-width: 0;
477
639
  font-weight: 600;
478
640
  word-break: break-word;
479
641
  }
480
642
 
643
+ /* Leading status icon (CARD-1). Empty in the DOM \u2014 the glyph/spinner is drawn
644
+ here from the card's data-status, so it stays themeable. */
645
+ .tool-call-icon {
646
+ flex: none;
647
+ box-sizing: border-box;
648
+ display: inline-flex;
649
+ align-items: center;
650
+ justify-content: center;
651
+ width: 14px;
652
+ height: 14px;
653
+ font-size: 12px;
654
+ line-height: 1;
655
+ }
656
+
657
+ /* Pending: a real spinning ring. Speed is tunable; reduced motion stops it. */
658
+ .tool-call[data-status="pending"] .tool-call-icon {
659
+ border: 2px solid var(--ag-ui-muted);
660
+ border-top-color: transparent;
661
+ border-radius: 50%;
662
+ animation: ag-ui-tool-spin var(--ag-ui-tool-spin-duration) linear infinite;
663
+ }
664
+
665
+ @keyframes ag-ui-tool-spin {
666
+ to { transform: rotate(360deg); }
667
+ }
668
+
669
+ /* Settled: a themeable glyph coloured by outcome. */
670
+ .tool-call[data-status="done"] .tool-call-icon::before {
671
+ content: var(--ag-ui-tool-icon-done);
672
+ color: var(--ag-ui-success);
673
+ }
674
+
675
+ .tool-call[data-status="error"] .tool-call-icon::before {
676
+ content: var(--ag-ui-tool-icon-error);
677
+ color: var(--ag-ui-danger);
678
+ }
679
+
680
+ .tool-call[data-status="declined"] .tool-call-icon::before {
681
+ content: var(--ag-ui-tool-icon-declined);
682
+ color: var(--ag-ui-muted);
683
+ }
684
+
685
+ @media (prefers-reduced-motion: reduce) {
686
+ .tool-call[data-status="pending"] .tool-call-icon {
687
+ animation: none;
688
+ }
689
+ }
690
+
691
+ /* Inline display mode (CARD-1): the lightest card \u2014 drop the box chrome so the
692
+ status row reads as one line of the answer; the result toggle still expands
693
+ below it. */
694
+ .tool-call[data-display="inline"] {
695
+ max-width: 100%;
696
+ background: transparent;
697
+ border: none;
698
+ padding: 2px 0;
699
+ gap: 2px;
700
+ }
701
+
481
702
  .tool-call-status {
482
703
  flex: none;
483
704
  padding: 1px 8px;
@@ -1009,11 +1230,11 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
1009
1230
  border-right: none;
1010
1231
  box-shadow: none;
1011
1232
  }
1012
- `;function su(t,e=Date.now()){let n=Math.round((e-t)/1e3);if(n<60)return"just now";let r=Math.round(n/60);if(r<60)return`${r}m ago`;let o=Math.round(r/60);if(o<24)return`${o}h ago`;let s=Math.round(o/24);return s<7?`${s}d ago`:`${Math.round(s/7)}w ago`}var rs=class{element;#e;#t;#o=[];#i="";constructor(e){this.#e=e,this.element=document.createElement("div"),this.element.className="drawer",this.element.hidden=!0;let n=document.createElement("div");n.className="drawer-backdrop",n.addEventListener("click",()=>this.close());let r=document.createElement("div");r.className="drawer-panel",r.setAttribute("role","dialog"),r.setAttribute("aria-label","Chat history");let o=document.createElement("div");o.className="drawer-header";let s=document.createElement("span");s.className="drawer-title",s.textContent="Chats";let i=document.createElement("button");i.type="button",i.className="drawer-new",i.textContent="New chat",i.addEventListener("click",()=>{this.close(),this.#e.onNew()}),o.append(s,i),this.#t=document.createElement("div"),this.#t.className="drawer-list",r.append(o,this.#t),this.element.append(n,r)}isOpen(){return!this.element.hidden}open(){this.element.hidden=!1}close(){this.element.hidden=!0}toggle(){this.element.hidden=!this.element.hidden}setThreads(e,n){this.#o=e,this.#i=n,this.#a()}#a(){if(this.#t.replaceChildren(),this.#o.length===0){let e=document.createElement("div");e.className="drawer-empty",e.textContent="No conversations yet.",this.#t.appendChild(e);return}for(let e of this.#o)this.#t.appendChild(this.#r(e))}#r(e){let n=document.createElement("div");n.className="drawer-row",e.threadId===this.#i&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select";let o=document.createElement("span");o.className="drawer-row-title",o.textContent=e.title;let s=document.createElement("span");s.className="drawer-row-time",s.textContent=su(e.updatedAt);let i=document.createElement("span");i.className="drawer-row-preview",i.textContent=e.preview,r.append(o,s,i),r.addEventListener("click",()=>{this.close(),this.#e.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.title="Rename",a.setAttribute("aria-label","Rename conversation"),a.textContent="\u270E",a.addEventListener("click",()=>this.#n(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.title="Delete",l.setAttribute("aria-label","Delete conversation"),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#s(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.append(a,l),n.append(r,c),n}#n(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.value=n.title,r.addEventListener("keydown",o=>{if(o.key==="Enter"){let s=r.value.trim();s===""?this.#a():this.#e.onRename(n.threadId,s)}else o.key==="Escape"&&this.#a()}),e.replaceChildren(r),r.focus(),r.select()}#s(e,n){let r=document.createElement("div");r.className="drawer-confirm";let o=document.createElement("span");o.className="drawer-confirm-label",o.textContent="Delete?";let s=document.createElement("button");s.type="button",s.className="drawer-confirm-yes",s.textContent="Delete",s.addEventListener("click",()=>this.#e.onDelete(n.threadId));let i=document.createElement("button");i.type="button",i.className="drawer-confirm-no",i.textContent="Cancel",i.addEventListener("click",()=>this.#a()),r.append(o,s,i),e.replaceChildren(r)}};var iu={[de.PENDING]:"running\u2026",[de.DONE]:"\u2713 done",[de.ERROR]:"\u26A0 error",[de.DECLINED]:"\u2298 declined"},ng={[de.DONE]:"Result",[de.ERROR]:"Error",[de.DECLINED]:"Declined"},tr=class{element;#e;#t;#o;constructor(e,n,r=Ke.FULL,o){this.#t=r,this.#o=n,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",de.PENDING),this.element.setAttribute("data-display",r);let s=document.createElement("div");s.className="tool-call-head";let i=document.createElement("span");if(i.className="tool-call-name",i.textContent=`\u{1F527} ${o??e}`,this.#e=document.createElement("span"),this.#e.className="tool-call-status",this.#e.textContent=iu[de.PENDING],s.append(i,this.#e),this.element.append(s),r===Ke.FULL){let a=document.createElement("pre");a.className="tool-call-args",a.textContent=JSON.stringify(n,null,2),this.element.append(a)}}settle(e,n){if(this.element.setAttribute("data-status",e),this.#e.textContent=iu[e],this.#t===Ke.MINIMAL)return;let r=document.createElement("button");r.type="button",r.className="tool-call-toggle",r.setAttribute("aria-expanded","false");let o=document.createElement("pre");o.className="tool-call-result",o.hidden=!0,this.#t===Ke.COMPACT?(r.textContent="Details",o.textContent=`args: ${JSON.stringify(this.#o)}
1233
+ `;function hu(t,e=Date.now(),n=Ie){let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let o=Math.round(r/60);if(o<60)return n.minutesAgo.replace("{n}",String(o));let i=Math.round(o/60);if(i<24)return n.hoursAgo.replace("{n}",String(i));let s=Math.round(i/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}var ai=class{element;#t;#e;#n;#o;#l;#i;#s=[];#r="";constructor(e,n=Ie){this.#t=e,this.#i=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#e=document.createElement("div"),this.#e.className="drawer-panel",this.#e.setAttribute("part","drawer-panel"),this.#e.setAttribute("role","dialog"),this.#e.setAttribute("aria-label",n.chatHistory);let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#n=document.createElement("span"),this.#n.className="drawer-title",this.#n.setAttribute("part","drawer-title"),this.#n.textContent=n.chats,this.#o=document.createElement("button"),this.#o.type="button",this.#o.className="drawer-new",this.#o.setAttribute("part","drawer-new"),this.#o.textContent=n.newChat,this.#o.addEventListener("click",()=>{this.close(),this.#t.onNew()}),o.append(this.#n,this.#o),this.#l=document.createElement("div"),this.#l.className="drawer-list",this.#l.setAttribute("part","drawer-list"),this.#e.append(o,this.#l),this.element.append(r,this.#e)}setStrings(e){this.#i=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#n.textContent=e.chats,this.#o.textContent=e.newChat,this.#a()}isOpen(){return!this.element.hidden}open(){this.element.hidden=!1}close(){this.element.hidden=!0}toggle(){this.element.hidden=!this.element.hidden}setThreads(e,n){this.#s=e,this.#r=n,this.#a()}#a(){if(this.#l.replaceChildren(),this.#s.length===0){let e=document.createElement("div");e.className="drawer-empty",e.setAttribute("part","drawer-empty"),e.textContent=this.#i.noConversations,this.#l.appendChild(e);return}for(let e of this.#s)this.#l.appendChild(this.#c(e))}#c(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#r&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.textContent=hu(e.updatedAt,void 0,this.#i);let s=document.createElement("span");s.className="drawer-row-preview",s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#t.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.title=this.#i.rename,a.setAttribute("aria-label",this.#i.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#h(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.title=this.#i.delete,l.setAttribute("aria-label",this.#i.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#d(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.append(a,l),n.append(r,c),n}#h(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.value=n.title,r.addEventListener("keydown",o=>{if(o.key==="Enter"){let i=r.value.trim();i===""?this.#a():this.#t.onRename(n.threadId,i)}else o.key==="Escape"&&this.#a()}),e.replaceChildren(r),r.focus(),r.select()}#d(e,n){let r=document.createElement("div");r.className="drawer-confirm";let o=document.createElement("span");o.className="drawer-confirm-label",o.textContent=this.#i.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.textContent=this.#i.delete,i.addEventListener("click",()=>this.#t.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.textContent=this.#i.cancel,s.addEventListener("click",()=>this.#a()),r.append(o,i,s),e.replaceChildren(r)}};function mu(t){return{[ce.PENDING]:t.toolRunning,[ce.DONE]:t.toolDone,[ce.ERROR]:t.toolError,[ce.DECLINED]:t.toolDeclined}}function gg(t){return{[ce.DONE]:t.resultLabel,[ce.ERROR]:t.errorLabel,[ce.DECLINED]:t.declinedLabel}}var or=class{element;#t;#e;#n;#o;#l=!1;constructor(e,n,r=$e.FULL,o,i=Ie){this.#e=r,this.#n=n,this.#o=i,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",ce.PENDING),this.element.setAttribute("data-display",r);let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");if(l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=o??e,this.#t=document.createElement("span"),this.#t.className="tool-call-status",this.#t.setAttribute("part","tool-card-status"),this.#t.textContent=mu(i)[ce.PENDING],s.append(a,l,this.#t),this.element.append(s),r===$e.FULL){let c=document.createElement("pre");c.className="tool-call-args",c.setAttribute("part","tool-card-args"),c.textContent=JSON.stringify(n,null,2),this.element.append(c)}}get settled(){return this.#l}settle(e,n){if(this.#l=!0,this.element.setAttribute("data-status",e),this.#t.textContent=mu(this.#o)[e],this.#e===$e.MINIMAL)return;let r=document.createElement("button");r.type="button",r.className="tool-call-toggle",r.setAttribute("part","tool-card-toggle"),r.setAttribute("aria-expanded","false");let o=document.createElement("pre");o.className="tool-call-result",o.setAttribute("part","tool-card-result"),o.hidden=!0,this.#e===$e.COMPACT?(r.textContent=this.#o.details,o.textContent=`args: ${JSON.stringify(this.#n)}
1013
1234
 
1014
- ${n}`):(r.textContent=ng[e],o.textContent=n),r.addEventListener("click",()=>{let s=o.hidden;o.hidden=!s,r.setAttribute("aria-expanded",String(s))}),this.element.append(r,o)}};var nr=class{#e;#t;#o;#i;#a;#r;#n=!1;constructor(e){this.#e=e.agent,this.#t=e.handlers,this.#o=e.getTools??(()=>[]),this.#i=e.getContext??(()=>[]),this.#a=e.executeTool??null,this.#r=e.onPersist??(()=>{})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(e,n=[]){let r={id:Ce(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#e.addMessage(r),this.#r(this.#e.messages),await this.#s()}async resume(){await this.#s()}addToolResult(e,n){this.#e.addMessage({id:Ce(),role:"tool",content:n,toolCallId:e}),this.#r(this.#e.messages)}cancel(){this.#n=!0,this.#e.abortRun()}async#s(){this.#n=!1;try{await this.#h(),this.#n&&this.#l()}catch(e){this.#n||rg(e)?this.#l():this.#t.onError(e instanceof Error?e.message:String(e))}finally{this.#t.onSettled()}}#l(){this.#r(this.#e.messages),this.#t.onCancelled()}async#h(){for(let e=0;e<ws;e+=1){if(this.#n)return;let n=[];if(await this.#e.runAgent({tools:this.#o(),context:this.#i()},this.#u(n)),this.#r(this.#e.messages),this.#n||this.#a===null||n.length===0)return;let r=!1;for(let o of n){let s=await this.#a(o);if(s!==null){if(s.halt===!0)return;this.#e.addMessage({id:Ce(),role:"tool",content:s.content,toolCallId:o.id}),this.#r(this.#e.messages),r=!0}}if(!r)return}}#u(e){let n=this.#t;return{onRunInitialized(){n.onRunStart()},onTextMessageContentEvent({textMessageBuffer:r}){n.onTextDelta(r)},onTextMessageEndEvent({textMessageBuffer:r}){n.onTextEnd(r)},onToolCallEndEvent({event:r,toolCallName:o,toolCallArgs:s}){let i={id:r.toolCallId,name:o,args:s};e.push(i),n.onToolCall(i)},onToolCallResultEvent({event:r}){n.onToolResult(r.toolCallId,r.content)},onRunErrorEvent({event:r}){n.onError(r.message)},onRunFinalized(){n.onRunEnd()}}}};function rg(t){return t instanceof Error&&t.name==="AbortError"}function ji(t){let e=t.attachments;return Array.isArray(e)?e:[]}var rr="ag-ui-chat:thread",Wi="ag-ui-chat:threads",Xi="ag-ui-chat:messages:",Zi="ag-ui-chat:checkpoint:",og=60,sg=100,ig="New conversation",Kt=class{threadId(){let e=sessionStorage.getItem(rr);if(e!==null)return e;let n=Ce();return sessionStorage.setItem(rr,n),n}loadMessages(e){return Promise.resolve(this.#i(Xi+e))}saveMessages(e,n){sessionStorage.setItem(Xi+e,JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#i(Zi+e)}saveCheckpoint(e,n){let r=Zi+e;if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(Xi+e),sessionStorage.removeItem(Zi+e),this.#o(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(rr)===e&&sessionStorage.removeItem(rr)}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:s})=>({threadId:n,title:r,updatedAt:o,preview:s}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(rr,e)}renameThread(e,n){let r=this.#t(),o=r.find(s=>s.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#o(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),s=ag(n),i=Date.now();o===void 0?r.push({threadId:e,title:au(n),titleCustom:!1,preview:s,updatedAt:i}):(o.preview=s,o.updatedAt=i,o.titleCustom||(o.title=au(n))),this.#o(r)}#t(){return this.#i(Wi)??[]}#o(e){if(e.length===0){sessionStorage.removeItem(Wi);return}sessionStorage.setItem(Wi,JSON.stringify(e))}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function au(t){for(let e of t)if(e.role==="user"){let n=lu(e.content);if(n!=="")return cu(n,og)}return ig}function ag(t){for(let e of[...t].reverse()){let n=lu(e.content);if(n!=="")return cu(n,sg)}return""}function lu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function cu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Ki(t){return new yc({url:t.endpoint,headers:t.headers??{},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[s,i]of Object.entries(r))o.set(s,i);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var or=class{#e;#t;#o;#i=new Set;#a=new Map;constructor(e,n=()=>({}),r=new Kt){this.#e=e.endsWith("/")?e:`${e}/`,this.#t=n,this.#o=r}threadId(){return this.#o.threadId()}setActiveThread(e){this.#o.setActiveThread(e)}saveMessages(e,n){this.#o.saveMessages(e,n)}loadCheckpoint(e){return this.#o.loadCheckpoint(e)}saveCheckpoint(e,n){this.#o.saveCheckpoint(e,n)}renameThread(e,n){this.#o.renameThread(e,n),this.#a.set(e,n),this.#l(e,"PATCH",{title:n})}clear(e){this.#o.clear(e),this.#i.add(e),this.#l(e,"DELETE")}async listThreads(){let e=await this.#r();return e===null?this.#o.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#n(n))}async loadMessages(e){let n=await this.#s(this.#e+encodeURIComponent(e)+"/");return n===null||!n.ok?this.#o.loadMessages(e):(await n.json()).messages??null}async#r(){let e=await this.#s(this.#e);return e===null||!e.ok?null:(await e.json()).threads??[]}#n(e){return{threadId:e.thread_id,title:this.#a.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?0:Date.parse(e.updated_at),preview:e.preview}}async#s(e){try{return await fetch(e,{headers:this.#t()})}catch{return null}}async#l(e,n,r){let o=this.#t();try{await fetch(this.#e+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};function Yi(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let s=new XMLHttpRequest;s.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))s.setRequestHeader(l,c);let i=e.onProgress;i!==void 0&&s.upload.addEventListener("progress",l=>{l.lengthComputable&&i(l.total===0?0:l.loaded/l.total)}),s.addEventListener("load",()=>{if(s.status>=200&&s.status<300)try{n(lg(JSON.parse(s.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(cg(s)))}),s.addEventListener("error",()=>r(new Error("upload failed"))),s.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>s.abort()),s.send(o)})}function lg(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,s=e.size,i=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof s!="number")throw new Error("missing fields");return typeof i=="string"?{id:n,name:r,mime:o,size:s,url:i}:{id:n,name:r,mime:o,size:s}}function cg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var uu="ag-ui-chat:collapsed",sr=class extends HTMLElement{agentFactory=Ki;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#G().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...Ns(this.getPageMap,this.autoInjectPageMap),...this.#q()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Kt;uploadHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};#e={};#t=new Ln;#o=new Map;#i=new Set;#a;#r;#n;#s;#l;#h;#u;#T;#m;#p;#d;#_;#g=null;#y=[];#b=null;#I=!1;#S=null;#f=null;#C=0;#w=null;#c="";#N=[];#P=[];#D=[];#U=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#r=document.createElement("div"),this.#n=document.createElement("div"),this.#s=document.createElement("textarea"),this.#l=document.createElement("button"),this.#h=document.createElement("span"),this.#m=document.createElement("div"),this.#p=document.createElement("button"),this.#d=document.createElement("input"),this.#_=document.createElement("div"),this.#u=new ns(e=>this.#re(e)),this.#T=new rs({onSelect:e=>{this.#oe(e)},onNew:()=>{this.newChat(),this.#A()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#A()},onDelete:e=>{this.#se(e)}})}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#h.textContent=r??"Assistant"}registerTool(e){this.#t.register(e)}registerStateHook(e){for(let n of Ms(e))this.#t.register(n)}#V(){return this.routeMap.length===0?[]:Os(()=>this.routeMap,()=>this.navigate)}#j(){let e=this.getPageMap;return e===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Ze]:"Read the page"},handler:()=>e()}]}#G(){return[...this.#V(),...this.#j()]}#H(e){let n=this.#G().find(r=>r.name===e);return n!==void 0?n:this.#t.has(e)?this.#t.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===Ke.MINIMAL||e===Ke.COMPACT?e:Ke.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){this.#ce(),sessionStorage.getItem(uu)==="1"&&this.setAttribute("collapsed",""),this.#ee(),this.#Q(),this.#J(),this.#W(),this.#c=this.conversationStore.threadId(),this.#F()}#W(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#X(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#g=new Xo({upload:n,maxBytes:this.#Z(),accept:r}),this.#_.appendChild(this.#g.element),this.#d.accept=r,this.#p.hidden=!1,this.#Y()}#X(e){return e===null?null:(n,r)=>Yi(n,{url:e,headers:this.headers,onProgress:r})}#Z(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return As;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:As}#K(){let e=this.#d.files;if(e!==null)for(let n of Array.from(e))this.#g?.add(n);this.#d.value=""}#Y(){this.#r.addEventListener("dragover",e=>{e.preventDefault(),this.#r.classList.add("chat--dragover")}),this.#r.addEventListener("dragleave",()=>{this.#r.classList.remove("chat--dragover")}),this.#r.addEventListener("drop",e=>{e.preventDefault(),this.#r.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#g?.add(r)})}#q(){return this.#y.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#y.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1235
+ ${n}`):(r.textContent=gg(this.#o)[e],o.textContent=n),r.addEventListener("click",()=>{let i=o.hidden;o.hidden=!i,r.setAttribute("aria-expanded",String(i))}),this.element.append(r,o)}};var li=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},ir=class{#t;#e;#n;#o;#l;#i;#s;#r=!1;constructor(e){this.#t=e.agent,this.#e=e.handlers,this.#n=e.getTools??(()=>[]),this.#o=e.getContext??(()=>[]),this.#l=e.executeTool??null,this.#i=e.onPersist??(()=>{}),this.#s=e.connectionLostMessage??"Connection lost"}get running(){return this.#t.isRunning}get messages(){return this.#t.messages}async send(e,n=[]){let r={id:Re(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#t.addMessage(r),this.#i(this.#t.messages),await this.#a()}async resume(){await this.#a()}addToolResult(e,n){this.#t.addMessage({id:Re(),role:"tool",content:n,toolCallId:e}),this.#i(this.#t.messages)}cancel(){this.#r=!0,this.#t.abortRun()}async#a(){this.#r=!1;try{await this.#h(),this.#r&&this.#c()}catch(e){this.#r||vg(e)?this.#c():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#c(){this.#i(this.#t.messages),this.#e.onCancelled()}async#h(){for(let e=0;e<Ii;e+=1){if(this.#r)return;let n=[],r={terminal:!1};if(await this.#t.runAgent({tools:this.#n(),context:this.#o()},this.#d(n,r)),this.#i(this.#t.messages),this.#r)return;if(!r.terminal)throw new li(this.#s);if(this.#l===null||n.length===0)return;let o=!1;for(let i of n){let s=await this.#l(i);if(s!==null){if(s.halt===!0)return;this.#t.addMessage({id:Re(),role:"tool",content:s.content,toolCallId:i.id}),this.#i(this.#t.messages),o=!0}}if(!o)return}}#d(e,n){let r=this.#e;return{onRunInitialized(){r.onRunStart()},onTextMessageContentEvent({textMessageBuffer:o}){r.onTextDelta(o)},onTextMessageEndEvent({textMessageBuffer:o}){r.onTextEnd(o)},onToolCallEndEvent({event:o,toolCallName:i,toolCallArgs:s}){let a={id:o.toolCallId,name:i,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:o}){r.onToolResult(o.toolCallId,o.content)},onRunErrorEvent({event:o}){n.terminal=!0,r.onError(o.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function vg(t){return t instanceof Error&&t.name==="AbortError"}function oa(t){let e=t.attachments;return Array.isArray(e)?e:[]}var sr="ag-ui-chat:thread",ia="ag-ui-chat:threads",sa="ag-ui-chat:messages:",aa="ag-ui-chat:checkpoint:",yg=60,bg=100,xg="New conversation",Jt=class{threadId(){let e=sessionStorage.getItem(sr);if(e!==null)return e;let n=Re();return sessionStorage.setItem(sr,n),n}loadMessages(e){return Promise.resolve(this.#o(sa+e))}saveMessages(e,n){sessionStorage.setItem(sa+e,JSON.stringify(n)),this.#t(e,n)}loadCheckpoint(e){return this.#o(aa+e)}saveCheckpoint(e,n){let r=aa+e;if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(sa+e),sessionStorage.removeItem(aa+e),this.#n(this.#e().filter(n=>n.threadId!==e)),sessionStorage.getItem(sr)===e&&sessionStorage.removeItem(sr)}listThreads(){let e=this.#e().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(sr,e)}renameThread(e,n){let r=this.#e(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#n(r))}#t(e,n){let r=this.#e(),o=r.find(a=>a.threadId===e),i=Eg(n),s=Date.now();o===void 0?r.push({threadId:e,title:gu(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=gu(n))),this.#n(r)}#e(){return this.#o(ia)??[]}#n(e){if(e.length===0){sessionStorage.removeItem(ia);return}sessionStorage.setItem(ia,JSON.stringify(e))}#o(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function gu(t){for(let e of t)if(e.role==="user"){let n=vu(e.content);if(n!=="")return yu(n,yg)}return xg}function Eg(t){for(let e of[...t].reverse()){let n=vu(e.content);if(n!=="")return yu(n,bg)}return""}function vu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function yu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function la(t){return new kc({url:t.endpoint,headers:t.headers??{},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var ar=class{#t;#e;#n;#o=new Set;#l=new Map;constructor(e,n=()=>({}),r=new Jt){this.#t=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#n=r}threadId(){return this.#n.threadId()}setActiveThread(e){this.#n.setActiveThread(e)}saveMessages(e,n){this.#n.saveMessages(e,n)}loadCheckpoint(e){return this.#n.loadCheckpoint(e)}saveCheckpoint(e,n){this.#n.saveCheckpoint(e,n)}renameThread(e,n){this.#n.renameThread(e,n),this.#l.set(e,n),this.#a(e,"PATCH",{title:n})}clear(e){this.#n.clear(e),this.#o.add(e),this.#a(e,"DELETE")}async listThreads(){let e=await this.#i();return e===null?this.#n.listThreads():e.filter(n=>!this.#o.has(n.thread_id)).map(n=>this.#s(n))}async loadMessages(e){let n=await this.#r(this.#t+encodeURIComponent(e)+"/");return n===null||!n.ok?this.#n.loadMessages(e):(await n.json()).messages??null}async#i(){let e=await this.#r(this.#t);return e===null||!e.ok?null:(await e.json()).threads??[]}#s(e){return{threadId:e.thread_id,title:this.#l.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?0:Date.parse(e.updated_at),preview:e.preview}}async#r(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#a(e,n,r){let o=this.#e();try{await fetch(this.#t+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};function ca(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Tg(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Sg(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Tg(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Sg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var bu="ag-ui-chat:collapsed",lr=class extends HTMLElement{agentFactory=la;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#V().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#n.tools()];getContext=()=>[...zi(this.getPageMap,this.autoInjectPageMap),...this.#le()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Jt;uploadHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#t={};#e=Ie;#n=new Pn;#o=new Map;#l=new Set;#i;#s;#r;#a;#c;#h;#d;#S;#y;#p;#f;#C;#g;#x;#E=null;#_=[];#w=null;#L=!1;#N=null;#m=null;#P=0;#R=null;#v=null;#u="";#D=[];#z=[];#B=[];#j=[];constructor(){super(),this.#i=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#r=document.createElement("div"),this.#a=document.createElement("textarea"),this.#c=document.createElement("button"),this.#h=document.createElement("span"),this.#y=document.createElement("div"),this.#p=document.createElement("button"),this.#f=document.createElement("input"),this.#C=document.createElement("div"),this.#g=document.createElement("button"),this.#x=document.createElement("div"),this.#d=new si(e=>this.#he(e)),this.#S=new ai({onSelect:e=>{this.#me(e)},onNew:()=>{this.newChat(),this.#O()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#O()},onDelete:e=>{this.#ge(e)}})}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#h.textContent=r??this.#e.title}registerTool(e){this.#n.register(e)}registerStateHook(e){for(let n of Vi(e))this.#n.register(n)}#Q(){return this.routeMap.length===0?[]:ji(()=>this.routeMap,()=>this.navigate)}#ee(){let e=this.getPageMap;return e===null?[]:[{name:"read_page",description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Ce]:"Read the page"},handler:()=>e()}]}#te(){let e=this.getAttribute("data-page-actions");if(e===null)return[];let n=new Set(e.split(",").map(r=>r.trim()).filter(r=>r!==""));return $i(n,r=>this.resolvePageTarget(r))}#V(){return[...this.#Q(),...this.#ee(),...this.#te()]}#W(e){let n=this.#V().find(r=>r.name===e);return n!==void 0?n:this.#n.has(e)?this.#n.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===$e.INLINE||e===$e.MINIMAL||e===$e.COMPACT?e:$e.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){this.#e=Ps({...this.#ne(),...this.strings}),this.#xe(),this.#S.setStrings(this.#e),sessionStorage.getItem(bu)==="1"&&this.setAttribute("collapsed",""),this.#Y(),this.#de(),this.#ue(),this.#ce(),this.#re(),this.#u=this.conversationStore.threadId(),this.#X()}#ne(){let e=this.getAttribute("data-strings");if(e===null)return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#re(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#oe(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#E=new qo({upload:n,maxBytes:this.#ie(),accept:r,strings:this.#e}),this.#C.appendChild(this.#E.element),this.#f.accept=r,this.#p.hidden=!1,this.#ae()}#oe(e){return e===null?null:(n,r)=>ca(n,{url:e,headers:this.headers,onProgress:r})}#ie(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Ci;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Ci}#se(){let e=this.#f.files;if(e!==null)for(let n of Array.from(e))this.#E?.add(n);this.#f.value=""}#ae(){this.#s.addEventListener("dragover",e=>{e.preventDefault(),this.#s.classList.add("chat--dragover")}),this.#s.addEventListener("dragleave",()=>{this.#s.classList.remove("chat--dragover")}),this.#s.addEventListener("drop",e=>{e.preventDefault(),this.#s.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#E?.add(r)})}#le(){return this.#_.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#_.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1015
1236
  `)}
1016
- Use the read_attachment tool with an id to read a file's contents.`}]}#J(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new or(e,()=>this.headers,this.conversationStore))}async#Q(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#e=Rs(await n.json())}catch{}}setSkills(e){this.#U=e,this.#R()}#ee(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#D=this.#te(),this.#R(),this.#ne()}#te(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return ks(JSON.parse(e))}catch{return[]}}async#ne(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#P=ks(await n.json()),this.#R()}catch{}}#R(){let e=new Map;for(let n of[...this.#P,...this.#D,...this.#U])e.set(n.name,n);this.#u.setSkills([...e.values()])}#re(e){let{text:n,missing:r}=Ia(e.prompt,this.skillContext());if(r.length>0){this.#m.textContent=`\u201C${e.title}\u201D needs: ${r.join(", ")}`,this.#m.hidden=!1;return}this.#m.hidden=!0,this.#s.value=n,e.sendImmediately===!0?this.#M():this.#s.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(uu,e?"1":"0"),this.dispatchEvent(new CustomEvent(_s,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}newChat(){this.#x(),this.conversationStore.clear(this.#c),this.#O(),this.#c=this.conversationStore.threadId(),this.#E(!1)}#O(){this.#b=null,this.#f=null,this.#v(),this.#o.clear(),this.#i.clear(),this.#N=[],this.#y=[],this.#g?.clear(),this.#n.replaceChildren()}async#oe(e){e!==this.#c&&(this.#x(),this.#O(),this.conversationStore.setActiveThread(e),this.#c=e,this.#E(!1),await this.#F())}#se(e){let n=e===this.#c;n&&this.#x(),this.conversationStore.clear(e),n&&(this.#O(),this.#c=this.conversationStore.threadId(),this.#E(!1)),this.#A()}async#A(){this.#T.setThreads(await this.conversationStore.listThreads(),this.#c)}async#F(){let e=await this.conversationStore.loadMessages(this.#c);if(e!==null){this.#N=e;for(let r of e)this.#ie(r)}let n=this.conversationStore.loadCheckpoint(this.#c);n!==null&&await this.#le(n)}#ie(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Xe.USER){let r=ji(e);if(n!==""||r.length>0){let o=this.appendMessage(Xe.USER,n);r.length>0&&o.appendChild(Ls(r))}return}if(e.role===Xe.ASSISTANT){n!==""&&this.appendMessage(Xe.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r)this.#L({id:o.id,name:o.function.name,args:this.#ae(o.function.arguments)});return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(de.DONE,e.content)}}#ae(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#$(e){this.getAttribute("data-text-animation")==="word"&&ru(e)}async#le(e){this.conversationStore.saveCheckpoint(this.#c,null);let n=this.#z();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,e===Xe.ASSISTANT?r.innerHTML=ts(n,{allowImages:this.allowImages}):r.textContent=n,this.#n.appendChild(r),this.#n.scrollTop=this.#n.scrollHeight,r}#ce(){let e=document.createElement("style");e.textContent=ou,this.#r.className="chat";let n=document.createElement("div");n.className="header";let r=this.#h;r.className="header-title",r.textContent=this.getAttribute("title-text")??"Assistant";let o=document.createElement("div");o.className="header-controls";let s=document.createElement("button");s.type="button",s.className="header-btn header-btn--history",s.title="Chat history",s.setAttribute("aria-label","Chat history"),s.textContent="\u2630",s.addEventListener("click",()=>{this.#A(),this.#T.open()});let i=document.createElement("button");i.type="button",i.className="header-btn header-btn--new",i.title="New chat",i.setAttribute("aria-label","New chat"),i.textContent="\u271A",i.addEventListener("click",()=>this.newChat());let a=document.createElement("button");a.type="button",a.className="header-btn header-btn--collapse",a.title="Collapse",a.setAttribute("aria-label","Collapse"),a.textContent="\u2014",a.addEventListener("click",()=>this.toggleCollapsed()),o.append(s,i,a),n.append(r,o),this.#n.className="messages",this.#n.setAttribute("role","log"),this.#n.setAttribute("aria-live","polite"),this.#n.setAttribute("aria-label","Conversation");let l=document.createElement("div");l.className="input-row",this.#s.className="input",this.#s.setAttribute("aria-label","Message"),this.#s.rows=2,this.#s.placeholder="Ask anything\u2026",this.#s.addEventListener("keydown",c=>this.#de(c)),this.#s.addEventListener("input",()=>this.#ue()),this.#l.className="send",this.#l.type="button",this.#l.textContent="Send",this.#l.setAttribute("aria-label","Send"),this.#l.dataset.state="idle",this.#l.addEventListener("click",()=>{if(this.#I){this.#x();return}this.#M()}),this.#m.className="skill-hint",this.#m.hidden=!0,this.#p.className="attach-btn",this.#p.type="button",this.#p.textContent="\u{1F4CE}",this.#p.title="Attach files",this.#p.setAttribute("aria-label","Attach files"),this.#p.hidden=!0,this.#p.addEventListener("click",()=>this.#d.click()),this.#d.className="attach-input",this.#d.type="file",this.#d.multiple=!0,this.#d.hidden=!0,this.#d.addEventListener("change",()=>this.#K()),this.#_.className="attachment-slot",l.append(this.#p,this.#s,this.#l,this.#d),this.#r.append(n,this.#n,this.#u.palette,this.#u.chips,this.#m,this.#_,l,this.#T.element),this.#a.append(e,this.#r)}#ue(){this.#u.onInput(this.#s.value),this.#m.hidden=!0}#de(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#I){e.preventDefault(),this.#x();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#M())}#x(){this.#S?.abort(),this.#b?.cancel()}#E(e){this.#I=e;let n=e?"Stop":"Send";this.#l.textContent=n,this.#l.setAttribute("aria-label",n),this.#l.dataset.state=e?"running":"idle"}async#M(){let e=this.#s.value.trim(),n=this.#g?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Xe.USER,e);n.length>0&&r.appendChild(Ls(n)),this.#s.value="",this.#g?.clearReady(),this.#y=n,this.dispatchEvent(new CustomEvent(Ts,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#pe(e,n)}async#pe(e,n){this.endpoint!==""&&await this.#z().send(e,n)}#z(){if(this.#b===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#c,initialMessages:this.#N});this.#b=new nr({agent:e,handlers:this.#me(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#he(n),onPersist:n=>this.conversationStore.saveMessages(this.#c,n)})}return this.#b}async#fe(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Is(n.parameters)}async#he(e){let n=this.#L(e);this.#o.delete(e.id);let r=this.#H(e.name);if(r===null)return this.#i.has(e.id)||n.settle(de.DONE,"No result returned."),null;if(await this.#fe(e,r)){let s={toolName:e.name,args:e.args},i=r.parameters[Ss];typeof i=="string"&&(s.message=i),this.#S=new AbortController;let a=_i(this.#n,s,{signal:this.#S.signal});this.#n.scrollTop=this.#n.scrollHeight;let l=await a;if(this.#S=null,!l){let c="User declined the action.";return n.settle(de.DECLINED,c),this.#k(),{content:c}}}let o=Cs(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#c,{toolCallId:e.id});try{let s=await r.handler(e.args);if(o)return n.settle(de.DONE,"Navigating\u2026"),{content:"",halt:!0};let i=JSON.stringify(s??null);return n.settle(de.DONE,i),this.#k(),{content:i}}catch(s){o&&this.conversationStore.saveCheckpoint(this.#c,null);let i=s instanceof Error?s.message:String(s);return n.settle(de.ERROR,i),this.#k(),{content:`Error: ${i}`,error:i}}}#me(){return{onRunStart:()=>{this.#E(!0),this.#k()},onTextDelta:e=>{this.#v(),this.#B(e),this.#C+=1},onTextEnd:e=>{let n=this.#B(e);this.#C<=1&&this.#$(n),this.#f=null},onToolCall:e=>{this.#v(),this.#L(e)},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(de.DONE,n),this.#i.add(e))},onRunEnd:()=>{this.#v(),this.#f=null},onError:e=>{this.#v(),this.#$(this.appendMessage(Xe.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#f=null},onCancelled:()=>{this.#v(),this.#ge(),this.#f=null},onSettled:()=>{this.#v(),this.#E(!1),this.#f=null,this.#y=[]}}}#ge(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("role","status"),e.textContent="\u23F9 Stopped",this.#n.appendChild(e),this.#n.scrollTop=this.#n.scrollHeight}#k(){if(this.#w!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("role","status"),e.setAttribute("aria-label","Assistant is thinking\u2026");for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#w=e,this.#n.appendChild(e),this.#n.scrollTop=this.#n.scrollHeight}#v(){this.#w?.remove(),this.#w=null}#B(e){return this.#f===null&&(this.#f=this.appendMessage(Xe.ASSISTANT,""),this.#C=0),this.#f.innerHTML=ts(e,{allowImages:this.allowImages}),this.#n.scrollTop=this.#n.scrollHeight,this.#f}#L(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#H(e.name)?.parameters[Ze],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#e[e.name]??Si(e.name),s=new tr(e.name,e.args,this.toolDisplay,o);return this.#o.set(e.id,s),this.#n.appendChild(s.element),this.#n.scrollTop=this.#n.scrollHeight,s}};function ug(){customElements.get(br)===void 0&&customElements.define(br,sr)}function os(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var dg=os(HTMLInputElement.prototype,"value"),pg=os(HTMLTextAreaElement.prototype,"value"),fg=os(HTMLSelectElement.prototype,"value"),hg=os(HTMLInputElement.prototype,"checked");function Yt(t,e){t instanceof HTMLTextAreaElement?pg.call(t,e):t instanceof HTMLSelectElement?fg.call(t,e):dg.call(t,e)}function ir(t,e){hg.call(t,e)}var du="#4f46e5";function ss(t){return new Promise(e=>{setTimeout(e,t)})}async function qi(t,e,n={}){let r=n.charDelayMs??35;Yt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)Yt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await ss(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Ji(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${du}`,t.style.outlineOffset="2px",await ss(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function qt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function Qi(t,e={}){let n=e.flashMs??200;t.focus();let r=t.style.boxShadow;t.style.boxShadow="0 0 0 3px rgba(79, 70, 229, 0.4)",await ss(n),t.style.boxShadow=r}var pu="0 0 0 3px rgba(79, 70, 229, 0.4)";function fu(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ea(t){return t<=0||fu()?Promise.resolve():ss(t)}async function ta(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,s=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=pu,await ea(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=s,t.click()}function mg(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function na(t,e,n={}){let r=mg(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,s=t.style.outline,i=t.style.outlineOffset;t.style.outline=`2px solid ${du}`,t.style.outlineOffset="2px",await ea(o),Yt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=s,t.style.outlineOffset=i}async function ra(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=pu,await ea(r),ir(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}async function gg(t,e,n={}){qt(t),await Qi(t,{flashMs:n.flashMs??0}),await qi(t,e,n)}async function vg(t,e={}){qt(t),await Ji(t,e)}async function yg(t,e={}){qt(t),await ta(t,e)}async function bg(t,e,n={}){qt(t),await na(t,e,n)}async function xg(t,e,n={}){qt(t),await ra(t,e,n)}function Eg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?ir(t,!!e):Yt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Tg="0.6.0";export{sr as AgUiChat,nr as AgUiClient,Ln as ClientToolRegistry,br as ELEMENT_TAG,ws as MAX_TOOL_ROUNDS,Xe as MESSAGE_ROLE,or as RemoteConversationStore,Ts as SUBMIT_EVENT,Kt as SessionStorageStore,_s as TOGGLE_EVENT,de as TOOL_CALL_STATUS,Ke as TOOL_DISPLAY,tr as ToolCallCard,Tg as VERSION,Ss as X_CONFIRM_KEY,On as X_DESTRUCTIVE_KEY,Mn as X_NAVIGATES_KEY,Ze as X_SUMMARY_KEY,vg as clickElement,Ki as createHttpAgent,Ns as createPageMapContext,Os as createRouteTools,Ms as createStateHookTools,ug as defineAgUiChat,gg as fillField,Qi as focusWithFlash,Ji as highlightThenClick,Is as isDestructive,Cs as isNavigates,ji as messageAttachments,Rs as parseToolCatalog,fu as prefersReducedMotion,yg as pressButton,ta as pressThenClick,Si as prettifyToolName,ts as renderMarkdown,_i as requestConfirmation,qt as scrollIntoCenterView,bg as selectControl,na as selectOption,Eg as setControlValue,ir as setNativeChecked,Yt as setNativeValue,xg as toggleCheckbox,ra as toggleControl,qi as typeInto,Yi as uploadAttachment};
1237
+ Use the read_attachment tool with an id to read a file's contents.`}]}#ce(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new ar(e,()=>this.headers,this.conversationStore))}async#ue(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#t=Bi(await n.json())}catch{}}setSkills(e){this.#j=e,this.#U()}#de(){this.#d.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#d.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#B=this.#pe(),this.#U(),this.#fe()}#pe(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Ni(JSON.parse(e))}catch{return[]}}async#fe(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#z=Ni(await n.json()),this.#U()}catch{}}#U(){let e=new Map;for(let n of[...this.#z,...this.#B,...this.#j])e.set(n.name,n);this.#d.setSkills([...e.values()])}#he(e){let{text:n,missing:r}=La(e.prompt,this.skillContext());if(r.length>0){this.#y.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#y.hidden=!1;return}this.#y.hidden=!0,this.#a.value=n,e.sendImmediately===!0?this.#F():this.#a.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(bu,e?"1":"0"),this.#Y(),this.dispatchEvent(new CustomEvent(Ai,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}newChat(){this.#k(),this.conversationStore.clear(this.#u),this.#G(),this.#u=this.conversationStore.threadId(),this.#I(!1)}#G(){this.#w=null,this.#m=null,this.#v=null,this.#T(),this.#o.clear(),this.#l.clear(),this.#D=[],this.#_=[],this.#E?.clear(),this.#r.replaceChildren(this.#x),this.#b()}async#me(e){e!==this.#u&&(this.#k(),this.#G(),this.conversationStore.setActiveThread(e),this.#u=e,this.#I(!1),await this.#X())}#ge(e){let n=e===this.#u;n&&this.#k(),this.conversationStore.clear(e),n&&(this.#G(),this.#u=this.conversationStore.threadId(),this.#I(!1)),this.#O()}async#O(){this.#S.setThreads(await this.conversationStore.listThreads(),this.#u)}async#X(){let e=await this.conversationStore.loadMessages(this.#u);if(e!==null){this.#D=e;for(let r of e)this.#ve(r)}let n=this.conversationStore.loadCheckpoint(this.#u);n!==null&&await this.#be(n)}#ve(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ye.USER){let r=oa(e);if(n!==""||r.length>0){let o=this.appendMessage(Ye.USER,n);r.length>0&&o.appendChild(Wi(r))}return}if(e.role===Ye.ASSISTANT){n!==""&&this.appendMessage(Ye.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r)this.#$({id:o.id,name:o.function.name,args:this.#ye(o.function.arguments)});return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(ce.DONE,e.content)}}#ye(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Z(e){this.getAttribute("data-text-animation")==="word"&&pu(e)}async#be(e){this.conversationStore.saveCheckpoint(this.#u,null);let n=this.#q();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===Ye.ASSISTANT?(r.innerHTML=ii(n,{allowImages:this.allowImages}),this.#A().appendChild(r)):(this.#v=null,r.textContent=n,this.#r.appendChild(r)),this.#b(),this.#r.scrollTop=this.#r.scrollHeight,r}#A(){if(this.#v===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#v=e,this.#r.appendChild(e),this.#b()}return this.#v}#xe(){let e=document.createElement("style");e.textContent=fu,this.#s.className="chat",this.#s.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#h;r.className="header-title",r.setAttribute("part","title"),r.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&n.append(this.#K("icon","icon",null));let o=document.createElement("slot");o.name="header-actions";let i=document.createElement("div");i.className="header-controls",i.setAttribute("part","header-controls");let s=this.#H("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#O(),this.#S.open()});let a=this.#H("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#H("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),i.append(s,a,l),n.append(r,o,i),this.#r.className="messages",this.#r.setAttribute("part","messages"),this.#r.setAttribute("role","log"),this.#r.setAttribute("aria-live","polite"),this.#r.setAttribute("aria-label",this.#e.conversation),this.#x.className="empty",this.#x.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty",this.#x.append(c),this.#r.append(this.#x);let p=document.createElement("div");p.className="input-row",p.setAttribute("part","composer"),this.#a.className="input",this.#a.setAttribute("part","input"),this.#a.setAttribute("aria-label",this.#e.message),this.#a.rows=2,this.#a.placeholder=this.#e.inputPlaceholder,this.#a.addEventListener("keydown",x=>this.#Te(x)),this.#a.addEventListener("input",()=>this.#Ee()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.textContent=this.#e.send,this.#c.setAttribute("aria-label",this.#e.send),this.#c.dataset.state="idle",this.#c.addEventListener("click",()=>{if(this.#L){this.#k();return}this.#F()}),this.#y.className="skill-hint",this.#y.hidden=!0,this.#p.className="attach-btn",this.#p.type="button",this.#p.setAttribute("part","attach-button"),this.#p.textContent="\u{1F4CE}",this.#p.title=this.#e.attachFiles,this.#p.setAttribute("aria-label",this.#e.attachFiles),this.#p.hidden=!0,this.#p.addEventListener("click",()=>this.#f.click()),this.#f.className="attach-input",this.#f.type="file",this.#f.multiple=!0,this.#f.hidden=!0,this.#f.addEventListener("change",()=>this.#se()),this.#C.className="attachment-slot";let m=document.createElement("slot");m.name="footer",p.append(this.#p,this.#a,this.#c,this.#f),this.#s.append(n,this.#r,this.#d.palette,this.#d.chips,this.#y,this.#C,p,m,this.#S.element),this.#g.className="rail",this.#g.type="button",this.#g.setAttribute("part","launcher"),this.#g.setAttribute("aria-label",this.#e.expand),this.#g.append(this.#K("launcher","launcher-icon","\u{1F4AC}")),this.#g.addEventListener("click",()=>this.setCollapsed(!1)),this.#i.append(e,this.#s,this.#g)}#H(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n),o.textContent=r,o}#K(e,n,r){let o=document.createElement("span");o.className="icon-holder",o.setAttribute("part",n);let i=document.createElement("slot");i.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",i.append(a)}else r!==null&&i.append(document.createTextNode(r));return o.append(i),o}#Y(){this.#g.setAttribute("aria-expanded",String(!this.collapsed))}#b(){this.#x.hidden=this.#r.childElementCount>1}#Ee(){this.#d.onInput(this.#a.value),this.#y.hidden=!0}#Te(e){if(this.#d.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#L){e.preventDefault(),this.#k();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#F())}#k(){this.#N?.abort(),this.#w?.cancel()}#I(e){this.#L=e;let n=e?this.#e.stop:this.#e.send;this.#c.textContent=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}async#F(){let e=this.#a.value.trim(),n=this.#E?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Ye.USER,e);n.length>0&&r.appendChild(Wi(n)),this.#a.value="",this.#E?.clearReady(),this.#_=n,this.dispatchEvent(new CustomEvent(wi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#Se(e,n)}async#Se(e,n){this.endpoint!==""&&await this.#q().send(e,n)}#q(){if(this.#w===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#u,initialMessages:this.#D});this.#w=new ir({agent:e,handlers:this.#Ae(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#we(n),onPersist:n=>this.conversationStore.saveMessages(this.#u,n),connectionLostMessage:this.#e.connectionLost})}return this.#w}async#_e(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Ri(n.parameters)}async#we(e){let n=this.#$(e);this.#o.delete(e.id);let r=this.#W(e.name);if(r===null)return this.#l.has(e.id)||n.settle(ce.DONE,this.#e.noResult),null;if(await this.#_e(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[ki];typeof s=="string"&&(i.message=s),this.#N=new AbortController;let a=Ds(this.#r,i,{signal:this.#N.signal,strings:this.#e});this.#b(),this.#r.scrollTop=this.#r.scrollHeight;let l=await a;if(this.#N=null,!l){let c=this.#e.declinedAction;return n.settle(ce.DECLINED,c),this.#M(),{content:c}}}let o=Oi(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#u,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(ce.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(ce.DONE,s),this.#M(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#u,null);let s=i instanceof Error?i.message:String(i);return n.settle(ce.ERROR,s),this.#M(),{content:`Error: ${s}`,error:s}}}#Ae(){return{onRunStart:()=>{this.#I(!0),this.#A(),this.#M()},onTextDelta:e=>{this.#T(),this.#J(e),this.#P+=1},onTextEnd:e=>{let n=this.#J(e);this.#P<=1&&this.#Z(n),this.#m=null},onToolCall:e=>{this.#T(),this.#$(e)},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(ce.DONE,n),this.#l.add(e))},onRunEnd:()=>{this.#T(),this.#m=null},onError:e=>{this.#T(),this.#Z(this.appendMessage(Ye.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#m=null},onCancelled:()=>{this.#T(),this.#ke(),this.#m=null},onSettled:()=>{this.#T(),this.#I(!1),this.#m=null,this.#_=[];for(let e of this.#o.values())e.settled||e.settle(ce.DONE,this.#e.noResult);this.#v!==null&&this.#v.childElementCount===0&&(this.#v.remove(),this.#b()),this.#v=null}}}#ke(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#A().appendChild(e),this.#b(),this.#r.scrollTop=this.#r.scrollHeight}#M(){if(this.#R!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#R=e,this.#A().appendChild(e),this.#b(),this.#r.scrollTop=this.#r.scrollHeight}#T(){this.#R?.remove(),this.#R=null}#J(e){return this.#m===null&&(this.#m=this.appendMessage(Ye.ASSISTANT,""),this.#P=0),this.#m.innerHTML=ii(e,{allowImages:this.allowImages}),this.#r.scrollTop=this.#r.scrollHeight,this.#m}#$(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#W(e.name)?.parameters[Ce],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]??Us(e.name),i=new or(e.name,e.args,this.toolDisplay,o,this.#e);return this.#o.set(e.id,i),this.#A().appendChild(i.element),this.#b(),this.#r.scrollTop=this.#r.scrollHeight,i}};function _g(){customElements.get(Er)===void 0&&customElements.define(Er,lr)}async function wg(t,e,n={}){at(t),await Pi(t,{flashMs:n.flashMs??0}),await Mi(t,e,n)}async function Ag(t,e={}){at(t),await Li(t,e)}async function kg(t,e={}){at(t),await Ui(t,e)}async function Ig(t,e,n={}){at(t),await Gi(t,e,n)}async function Cg(t,e,n={}){at(t),await Hi(t,e,n)}function Ng(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Dn(t,!!e):wt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Rg="0.8.0";export{lr as AgUiChat,ir as AgUiClient,Pn as ClientToolRegistry,li as ConnectionLostError,Ie as DEFAULT_UI_STRINGS,Er as ELEMENT_TAG,Ii as MAX_TOOL_ROUNDS,Ye as MESSAGE_ROLE,Fi as PAGE_ACTIONS,ar as RemoteConversationStore,wi as SUBMIT_EVENT,Jt as SessionStorageStore,Ai as TOGGLE_EVENT,ce as TOOL_CALL_STATUS,$e as TOOL_DISPLAY,or as ToolCallCard,Rg as VERSION,ki as X_CONFIRM_KEY,Mn as X_DESTRUCTIVE_KEY,Ln as X_NAVIGATES_KEY,Ce as X_SUMMARY_KEY,Ag as clickElement,la as createHttpAgent,$i as createPageActionTools,zi as createPageMapContext,ji as createRouteTools,Vi as createStateHookTools,_g as defineAgUiChat,wg as fillField,Pi as focusWithFlash,Li as highlightThenClick,Ri as isDestructive,Oi as isNavigates,Ps as mergeUiStrings,oa as messageAttachments,Bi as parseToolCatalog,Ua as prefersReducedMotion,kg as pressButton,Ui as pressThenClick,Us as prettifyToolName,ii as renderMarkdown,Ds as requestConfirmation,at as scrollIntoCenterView,Ig as selectControl,Gi as selectOption,Ng as setControlValue,Dn as setNativeChecked,wt as setNativeValue,Cg as toggleCheckbox,Hi as toggleControl,Mi as typeInto,ca as uploadAttachment};
1017
1238
  /*! Bundled license information:
1018
1239
 
1019
1240
  fast-json-patch/module/helpers.mjs: