@artooi/ag-ui-web-component 0.10.0 → 0.12.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 (45) hide show
  1. package/CHANGELOG.md +78 -1
  2. package/README.md +144 -7
  3. package/dist/ag-ui-web-component.bundle.js +237 -40
  4. package/dist/ag-ui-web-component.bundle.js.map +4 -4
  5. package/dist/core/ag_ui_chat.d.ts +29 -0
  6. package/dist/core/ag_ui_chat.d.ts.map +1 -1
  7. package/dist/core/agui_client.d.ts +28 -1
  8. package/dist/core/agui_client.d.ts.map +1 -1
  9. package/dist/core/run_index.d.ts +50 -0
  10. package/dist/core/run_index.d.ts.map +1 -0
  11. package/dist/index.d.ts +5 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +942 -101
  14. package/dist/index.js.map +4 -4
  15. package/dist/ui/approval_card.d.ts +51 -0
  16. package/dist/ui/approval_card.d.ts.map +1 -0
  17. package/dist/ui/attachment_chips.d.ts.map +1 -1
  18. package/dist/ui/attachment_tray.d.ts.map +1 -1
  19. package/dist/ui/checkpoint_menu.d.ts +32 -0
  20. package/dist/ui/checkpoint_menu.d.ts.map +1 -0
  21. package/dist/ui/question_card.d.ts +52 -0
  22. package/dist/ui/question_card.d.ts.map +1 -0
  23. package/dist/ui/skills_menu.d.ts.map +1 -1
  24. package/dist/ui/styles.d.ts +1 -1
  25. package/dist/ui/styles.d.ts.map +1 -1
  26. package/dist/ui/thoughts_block.d.ts.map +1 -1
  27. package/dist/ui/thread_drawer.d.ts.map +1 -1
  28. package/dist/ui/ui_strings.d.ts +26 -0
  29. package/dist/ui/ui_strings.d.ts.map +1 -1
  30. package/package.json +4 -4
  31. package/src/core/ag_ui_chat.ts +263 -4
  32. package/src/core/agui_client.ts +86 -11
  33. package/src/core/run_index.ts +91 -0
  34. package/src/index.ts +16 -0
  35. package/src/ui/approval_card.ts +119 -0
  36. package/src/ui/attachment_chips.ts +5 -0
  37. package/src/ui/attachment_tray.ts +8 -0
  38. package/src/ui/checkpoint_menu.ts +153 -0
  39. package/src/ui/question_card.ts +216 -0
  40. package/src/ui/skills_menu.ts +6 -0
  41. package/src/ui/styles.ts +197 -0
  42. package/src/ui/thoughts_block.ts +1 -0
  43. package/src/ui/thread_drawer.ts +11 -0
  44. package/src/ui/ui_strings.ts +45 -0
  45. package/src/version.ts +1 -1
@@ -1,62 +1,62 @@
1
- var Gu=Object.defineProperty;var Io=(t,e)=>{for(var n in e)Gu(t,n,{get:e[n],enumerable:!0})};var Er="ag-ui-chat",Co="ag-ui-submit",No="ag-ui-toggle",Ye={USER:"user",ASSISTANT:"assistant"},Mn="x-destructive",Ro="x-confirm",Ce="x-summary",Ln="x-navigates",Oo=10,ce={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Me={UPLOADING:"uploading",READY:"ready",ERROR:"error"},Mo=10*1024*1024,$e={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Fu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function Ha(t,e){let n=[];return{text:t.replace(Fu,(i,o)=>{let s=e[o];return s==null||s===""?(n.includes(o)||n.push(o),i):String(s)}),missing:n}}function $u(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 Lo(t){return Array.isArray(t)?t.filter($u):[]}var Pn=class{#n=new Map;register(e){this.#n.set(e.name,e)}has(e){return this.#n.has(e)}get(e){let n=this.#n.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#n.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Po(t){return t[Mn]===!0}function Do(t){return t[Ln]===!0}function Tr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var zu=Tr(HTMLInputElement.prototype,"value"),Bu=Tr(HTMLTextAreaElement.prototype,"value"),Vu=Tr(HTMLSelectElement.prototype,"value"),ju=Tr(HTMLInputElement.prototype,"checked");function At(t,e){t instanceof HTMLTextAreaElement?Bu.call(t,e):t instanceof HTMLSelectElement?Vu.call(t,e):zu.call(t,e)}function Dn(t,e){ju.call(t,e)}var Ga="#4f46e5";function Sr(t){return new Promise(e=>{setTimeout(e,t)})}async function Uo(t,e,n={}){let r=n.charDelayMs??35;At(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let i of e)At(t,t.value+i),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Sr(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Ho(t,e={}){let n=e.highlightMs??280,r=t.style.outline,i=t.style.outlineOffset;t.style.outline=`2px solid ${Ga}`,t.style.outlineOffset="2px",await Sr(n),t.style.outline=r,t.style.outlineOffset=i,t.click()}function at(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function Go(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 Fa="0 0 0 3px rgba(79, 70, 229, 0.4)";function $a(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Fo(t){return t<=0||$a()?Promise.resolve():Sr(t)}async function $o(t,e={}){let n=e.pressMs??140,r=t.style.transform,i=t.style.transition,o=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=Fa,await Fo(n),t.style.transform=r,t.style.transition=i,t.style.boxShadow=o,t.click()}function Wu(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function zo(t,e,n={}){let r=Wu(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let i=n.highlightMs??220,o=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${Ga}`,t.style.outlineOffset="2px",await Fo(i),At(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=o,t.style.outlineOffset=s}async function Bo(t,e,n={}){let r=n.flashMs??200,i=t.style.boxShadow;t.style.boxShadow=Fa,await Fo(r),Dn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=i}var Vo={SCROLL:"scroll",DRAG:"drag"};function jo(t,e){let n=[];return t.has(Vo.SCROLL)&&n.push(Xu(e)),t.has(Vo.DRAG)&&n.push(Ku(e)),n}function Xu(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 i=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:i,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 Ku(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??""),i=t(n);if(i===null)throw new Error(`no element matching "${n}"`);let o=t(r);if(o===null)throw new Error(`no element matching "${r}"`);return Zu(i,o),{dragged:!0,from:n,to:r}}}}function Zu(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 Wo(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Xo(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,i=r.name,o=r.summary;typeof i=="string"&&typeof o=="string"&&(e[i]=o)}return e}var za=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Yu(t){let e=[];for(let n of t.matchAll(za)){let r=n[1];r!==void 0&&e.push(r)}return e}function qu(t,e,n){let r={...n};return{path:e.replace(za,(o,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 Ju(t,e){let n=new URLSearchParams;for(let[i,o]of Object.entries(e))n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}function Ko(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:Yu(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,i=t().find(p=>p.id===r);if(i===void 0)throw new Error(`unknown route "${String(r)}"`);let o=n.params??{},{path:s,leftover:a}=qu(i.id,i.path,o),l=Ju(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}function Zo(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 Yo(t){let e=document.createElement("div");e.className="attachment-chips";for(let n of t)e.appendChild(Qu(n));return e}function Qu(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=qo(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 i=document.createElement("span");return i.className="attachment-chip-size",i.textContent=_r(t.size),e.append(n,r,i),e}function qo(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 ve=[];for(let t=0;t<256;++t)ve.push((t+256).toString(16).slice(1));function Ba(t,e=0){return(ve[t[e+0]]+ve[t[e+1]]+ve[t[e+2]]+ve[t[e+3]]+"-"+ve[t[e+4]]+ve[t[e+5]]+"-"+ve[t[e+6]]+ve[t[e+7]]+"-"+ve[t[e+8]]+ve[t[e+9]]+"-"+ve[t[e+10]]+ve[t[e+11]]+ve[t[e+12]]+ve[t[e+13]]+ve[t[e+14]]+ve[t[e+15]]).toLowerCase()}var Jo,ed=new Uint8Array(16);function Qo(){if(!Jo){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Jo=crypto.getRandomValues.bind(crypto)}return Jo(ed)}var td=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),es={randomUUID:td};function nd(t,e,n){if(es.randomUUID&&!e&&!t)return es.randomUUID();t=t||{};let r=t.random??t.rng?.()??Qo();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 i=0;i<16;++i)e[n+i]=r[i];return e}return Ba(r)}var vt=nd;var u={};Io(u,{BRAND:()=>Id,DIRTY:()=>kt,EMPTY_PATH:()=>sd,INVALID:()=>O,NEVER:()=>pp,OK:()=>Ee,ParseStatus:()=>ye,Schema:()=>U,ZodAny:()=>xt,ZodArray:()=>dt,ZodBigInt:()=>Ct,ZodBoolean:()=>Nt,ZodBranded:()=>Gn,ZodCatch:()=>$t,ZodDate:()=>Rt,ZodDefault:()=>Ft,ZodDiscriminatedUnion:()=>kr,ZodEffects:()=>De,ZodEnum:()=>Ht,ZodError:()=>Ae,ZodFirstPartyTypeKind:()=>M,ZodFunction:()=>Cr,ZodIntersection:()=>Pt,ZodIssueCode:()=>E,ZodLazy:()=>Dt,ZodLiteral:()=>Ut,ZodMap:()=>un,ZodNaN:()=>pn,ZodNativeEnum:()=>Gt,ZodNever:()=>ze,ZodNull:()=>Mt,ZodNullable:()=>Qe,ZodNumber:()=>It,ZodObject:()=>ke,ZodOptional:()=>Le,ZodParsedType:()=>k,ZodPipeline:()=>Fn,ZodPromise:()=>Et,ZodReadonly:()=>zt,ZodRecord:()=>Ir,ZodSchema:()=>U,ZodSet:()=>dn,ZodString:()=>bt,ZodSymbol:()=>ln,ZodTransformer:()=>De,ZodTuple:()=>Je,ZodType:()=>U,ZodUndefined:()=>Ot,ZodUnion:()=>Lt,ZodUnknown:()=>ut,ZodVoid:()=>cn,addIssueToContext:()=>w,any:()=>Ud,array:()=>$d,bigint:()=>Od,boolean:()=>el,coerce:()=>dp,custom:()=>qa,date:()=>Md,datetimeRegex:()=>Za,defaultErrorMap:()=>lt,discriminatedUnion:()=>jd,effect:()=>rp,enum:()=>ep,function:()=>qd,getErrorMap:()=>on,getParsedType:()=>qe,instanceof:()=>Nd,intersection:()=>Wd,isAborted:()=>wr,isAsync:()=>sn,isDirty:()=>Ar,isValid:()=>yt,late:()=>Cd,lazy:()=>Jd,literal:()=>Qd,makeIssue:()=>Hn,map:()=>Zd,nan:()=>Rd,nativeEnum:()=>tp,never:()=>Gd,null:()=>Dd,nullable:()=>op,number:()=>Qa,object:()=>zd,objectUtil:()=>ts,oboolean:()=>up,onumber:()=>cp,optional:()=>ip,ostring:()=>lp,pipeline:()=>ap,preprocess:()=>sp,promise:()=>np,quotelessJson:()=>rd,record:()=>Kd,set:()=>Yd,setErrorMap:()=>od,strictObject:()=>Bd,string:()=>Ja,symbol:()=>Ld,transformer:()=>rp,tuple:()=>Xd,undefined:()=>Pd,union:()=>Vd,unknown:()=>Hd,util:()=>F,void:()=>Fd});var F;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(F||(F={}));var ts;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(ts||(ts={}));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"]),rd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ae=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(o){return o.message},r={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(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 i(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 i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Ae.create=t=>new Ae(t);var id=(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=id;var Va=lt;function od(t){Va=t}function on(){return Va}var Hn=t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,o=[...n,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},sd=[];function w(t,e){let n=on(),r=Hn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===lt?void 0:lt].filter(i=>!!i)});t.common.issues.push(r)}var ye=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 i of n){if(i.status==="aborted")return O;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let o=await i.key,s=await i.value;r.push({key:o,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return O;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(r[o.value]=s.value)}return{status:e.value,value:r}}},O=Object.freeze({status:"aborted"}),kt=t=>({status:"dirty",value:t}),Ee=t=>({status:"valid",value:t}),wr=t=>t.status==="aborted",Ar=t=>t.status==="dirty",yt=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 Pe=class{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ja=(t,e)=>{if(yt(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 Ae(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:i}=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:i}:{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:i}}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 ye,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)},i=this._parseSync({data:e,path:r.path,parent:r});return ja(r,i)}"~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 yt(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=>yt(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)},i=this._parse({data:e,path:r.path,parent:r}),o=await(sn(i)?i:Promise.resolve(i));return ja(r,o)}refine(e,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:E.custom,...r(i)});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,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new De({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 Le.create(this,this._def)}nullable(){return Qe.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return dt.create(this)}promise(){return Et.create(this,this._def)}or(e){return Lt.create([this,e],this._def)}and(e){return Pt.create(this,e,this._def)}transform(e){return new De({...L(this._def),schema:this,typeName:M.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ft({...L(this._def),innerType:this,defaultValue:n,typeName:M.ZodDefault})}brand(){return new Gn({typeName:M.ZodBranded,type:this,...L(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new $t({...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 zt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ad=/^c[^\s-]{8,}$/i,ld=/^[0-9a-z]+$/,cd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ud=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,dd=/^[a-z0-9_-]{21}$/i,pd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fd=/^[-+]?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)?)??$/,hd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,md="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ns,gd=/^(?:(?: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])$/,vd=/^(?:(?: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])$/,yd=/^(([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]))$/,bd=/^(([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])$/,xd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ed=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Xa="((\\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])))",Td=new RegExp(`^${Xa}$`);function Ka(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 Sd(t){return new RegExp(`^${Ka(t)}$`)}function Za(t){let e=`${Xa}T${Ka(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 _d(t,e){return!!((e==="v4"||!e)&&gd.test(t)||(e==="v6"||!e)&&yd.test(t))}function wd(t,e){if(!pd.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,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Ad(t,e){return!!((e==="v4"||!e)&&vd.test(t)||(e==="v6"||!e)&&bd.test(t))}var bt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let o=this._getOrReturnCtx(e);return w(o,{code:E.invalid_type,expected:k.string,received:o.parsedType}),O}let r=new ye,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),w(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),w(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?w(i,{code:E.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&w(i,{code:E.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")hd.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"email",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")ns||(ns=new RegExp(md,"u")),ns.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"emoji",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")ud.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"uuid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")dd.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"nanoid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")ad.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"cuid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")ld.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"cuid2",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")cd.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"ulid",code:E.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),w(i,{validation:"url",code:E.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"regex",code:E.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),w(i,{code:E.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),w(i,{code:E.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),w(i,{code:E.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?Za(o).test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{code:E.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Td.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{code:E.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Sd(o).test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{code:E.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?fd.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"duration",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?_d(e.data,o.version)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"ip",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?wd(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"jwt",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Ad(e.data,o.version)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"cidr",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?xd.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"base64",code:E.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Ed.test(e.data)||(i=this._getOrReturnCtx(e,i),w(i,{validation:"base64url",code:E.invalid_string,message:o.message}),r.dirty()):F.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{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}};bt.create=t=>new bt({checks:[],typeName:M.ZodString,coerce:t?.coerce??!1,...L(t)});function kd(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var It=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 o=this._getOrReturnCtx(e);return w(o,{code:E.invalid_type,expected:k.number,received:o.parsedType}),O}let r,i=new ye;for(let o of this._def.checks)o.kind==="int"?F.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?kd(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_finite,message:o.message}),i.dirty()):F.assertNever(o);return{status:i.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,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(i)}]})}_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)}};It.create=t=>new It({checks:[],typeName:M.ZodNumber,coerce:t?.coerce||!1,...L(t)});var Ct=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,i=new ye;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),w(r,{code:E.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):F.assertNever(o);return{status:i.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,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:I.toString(i)}]})}_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}};Ct.create=t=>new Ct({checks:[],typeName:M.ZodBigInt,coerce:t?.coerce??!1,...L(t)});var Nt=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 Ee(e.data)}};Nt.create=t=>new Nt({typeName:M.ZodBoolean,coerce:t?.coerce||!1,...L(t)});var Rt=class t extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let o=this._getOrReturnCtx(e);return w(o,{code:E.invalid_type,expected:k.date,received:o.parsedType}),O}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return w(o,{code:E.invalid_date}),O}let r=new ye,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),w(i,{code:E.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),w(i,{code:E.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):F.assertNever(o);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}};Rt.create=t=>new Rt({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 Ee(e.data)}};ln.create=t=>new ln({typeName:M.ZodSymbol,...L(t)});var Ot=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 Ee(e.data)}};Ot.create=t=>new Ot({typeName:M.ZodUndefined,...L(t)});var Mt=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 Ee(e.data)}};Mt.create=t=>new Mt({typeName:M.ZodNull,...L(t)});var xt=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return Ee(e.data)}};xt.create=t=>new xt({typeName:M.ZodAny,...L(t)});var ut=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ee(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 Ee(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),i=this._def;if(n.parsedType!==k.array)return w(n,{code:E.invalid_type,expected:k.array,received:n.parsedType}),O;if(i.exactLength!==null){let s=n.data.length>i.exactLength.value,a=n.data.length<i.exactLength.value;(s||a)&&(w(n,{code:s?E.too_big:E.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(w(n,{code:E.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(w(n,{code:E.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>i.type._parseAsync(new Pe(n,s,n.path,a)))).then(s=>ye.mergeArray(r,s));let o=[...n.data].map((s,a)=>i.type._parseSync(new Pe(n,s,n.path,a)));return ye.mergeArray(r,o)}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 ke){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Le.create(an(r))}return new ke({...t._def,shape:()=>e})}else return t instanceof dt?new dt({...t._def,type:an(t.element)}):t instanceof Le?Le.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 ke=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:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof ze&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let p=o[c],m=i.data[c];l.push({key:{status:"valid",value:c},value:p._parse(new Pe(i,m,i.path,c)),alwaysSet:c in i.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:i.data[p]}});else if(c==="strict")a.length>0&&(w(i,{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=i.data[p];l.push({key:{status:"valid",value:p},value:c._parse(new Pe(i,m,i.path,p)),alwaysSet:p in i.data})}}return i.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=>ye.mergeObjectSync(r,c)):ye.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 i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:I.errToObj(e).message??i}:{message:i}}}:{}})}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 i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.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 o=this.shape[r];for(;o instanceof Le;)o=o._def.innerType;n[r]=o}return new t({...this._def,shape:()=>n})}keyof(){return Ya(F.objectKeys(this.shape))}};ke.create=(t,e)=>new ke({shape:()=>t,unknownKeys:"strip",catchall:ze.create(),typeName:M.ZodObject,...L(e)});ke.strictCreate=(t,e)=>new ke({shape:()=>t,unknownKeys:"strict",catchall:ze.create(),typeName:M.ZodObject,...L(e)});ke.lazycreate=(t,e)=>new ke({shape:t,unknownKeys:"strip",catchall:ze.create(),typeName:M.ZodObject,...L(e)});var Lt=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new Ae(a.ctx.common.issues));return w(n,{code:E.invalid_union,unionErrors:s}),O}if(n.common.async)return Promise.all(r.map(async o=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(i);{let o,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"&&!o&&(o={result:p,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(l=>new Ae(l));return w(n,{code:E.invalid_union,unionErrors:a}),O}}get options(){return this._def.options}};Lt.create=(t,e)=>new Lt({options:t,typeName:M.ZodUnion,...L(e)});var ct=t=>t instanceof Dt?ct(t.schema):t instanceof De?ct(t.innerType()):t instanceof Ut?[t.value]:t instanceof Ht?t.options:t instanceof Gt?F.objectValues(t.enum):t instanceof Ft?ct(t._def.innerType):t instanceof Ot?[void 0]:t instanceof Mt?[null]:t instanceof Le?[void 0,...ct(t.unwrap())]:t instanceof Qe?[null,...ct(t.unwrap())]:t instanceof Gn||t instanceof zt?ct(t.unwrap()):t instanceof $t?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,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._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 i=new Map;for(let o of n){let s=ct(o.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(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:M.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...L(r)})}};function rs(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 i=F.objectKeys(e),o=F.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let l=rs(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 i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],l=rs(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Pt=class extends U{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=(o,s)=>{if(wr(o)||wr(s))return O;let a=rs(o.value,s.value);return a.valid?((Ar(o)||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(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Pt.create=(t,e,n)=>new Pt({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 o=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Pe(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(o).then(s=>ye.mergeArray(n,s)):ye.mergeArray(n,o)}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 i=[],o=this._def.keyType,s=this._def.valueType;for(let a in r.data)i.push({key:o._parse(new Pe(r,a,r.path,a)),value:s._parse(new Pe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ye.mergeObjectAsync(n,i):ye.mergeObjectSync(n,i)}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:bt.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 i=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:i._parse(new Pe(r,a,r.path,[c,"key"])),value:o._parse(new Pe(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 i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(w(r,{code:E.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(w(r,{code:E.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=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)=>o._parse(new Pe(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 Hn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,on(),lt].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function i(a,l){return Hn({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 o={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Et){let a=this;return Ee(async function(...l){let c=new Ae([]),p=await a._def.args.parseAsync(l,o).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,o).catch(f=>{throw c.addIssue(i(m,f)),c})})}else{let a=this;return Ee(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new Ae([r(l,c.error)]);let p=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(p,o);if(!m.success)throw new Ae([i(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)})}},Dt=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})}};Dt.create=(t,e)=>new Dt({getter:t,typeName:M.ZodLazy,...L(e)});var Ut=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}};Ut.create=(t,e)=>new Ut({value:t,typeName:M.ZodLiteral,...L(e)});function Ya(t,e){return new Ht({values:t,typeName:M.ZodEnum,...L(e)})}var Ht=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 Ee(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})}};Ht.create=Ya;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 i=F.objectValues(n);return w(r,{expected:F.joinValues(i),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 i=F.objectValues(n);return w(r,{received:r.data,code:E.invalid_enum_value,options:i}),O}return Ee(e.data)}get enum(){return this._def.values}};Gt.create=(t,e)=>new Gt({values:t,typeName:M.ZodNativeEnum,...L(e)});var Et=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 Ee(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Et.create=(t,e)=>new Et({type:t,typeName:M.ZodPromise,...L(e)});var De=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),i=this._def.effect||null,o={addIssue:s=>{w(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(r.data,o);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"?kt(l.value):n.value==="dirty"?kt(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"?kt(a.value):n.value==="dirty"?kt(a.value):a}}if(i.type==="refinement"){let s=a=>{let l=i.refinement(a,o);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(i.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!yt(s))return O;let a=i.transform(s.value,o);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=>yt(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:n.value,value:a})):O);F.assertNever(i)}};De.create=(t,e,n)=>new De({schema:t,typeName:M.ZodEffects,effect:e,...L(n)});De.createWithPreprocess=(t,e,n)=>new De({schema:e,effect:{type:"preprocess",transform:t},typeName:M.ZodEffects,...L(n)});var Le=class extends U{_parse(e){return this._getType(e)===k.undefined?Ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Le.create=(t,e)=>new Le({innerType:t,typeName:M.ZodOptional,...L(e)});var Qe=class extends U{_parse(e){return this._getType(e)===k.null?Ee(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 Ft=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}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:M.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...L(e)});var $t=class extends U{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return sn(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ae(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};$t.create=(t,e)=>new $t({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 Id=Symbol("zod_brand"),Gn=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 o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?O:o.status==="dirty"?(n.dirty(),kt(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?O:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:M.ZodPipeline})}},zt=class extends U{_parse(e){let n=this._def.innerType._parse(e),r=i=>(yt(i)&&(i.value=Object.freeze(i.value)),i);return sn(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:M.ZodReadonly,...L(e)});function Wa(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function qa(t,e={},n){return t?xt.create().superRefine((r,i)=>{let o=t(r);if(o instanceof Promise)return o.then(s=>{if(!s){let a=Wa(e,r),l=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:l})}});if(!o){let s=Wa(e,r),a=s.fatal??n??!0;i.addIssue({code:"custom",...s,fatal:a})}}):xt.create()}var Cd={object:ke.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 Nd=(t,e={message:`Input not instance of ${t.name}`})=>qa(n=>n instanceof t,e),Ja=bt.create,Qa=It.create,Rd=pn.create,Od=Ct.create,el=Nt.create,Md=Rt.create,Ld=ln.create,Pd=Ot.create,Dd=Mt.create,Ud=xt.create,Hd=ut.create,Gd=ze.create,Fd=cn.create,$d=dt.create,zd=ke.create,Bd=ke.strictCreate,Vd=Lt.create,jd=kr.create,Wd=Pt.create,Xd=Je.create,Kd=Ir.create,Zd=un.create,Yd=dn.create,qd=Cr.create,Jd=Dt.create,Qd=Ut.create,ep=Ht.create,tp=Gt.create,np=Et.create,rp=De.create,ip=Le.create,op=Qe.create,sp=De.createWithPreprocess,ap=Fn.create,lp=()=>Ja().optional(),cp=()=>Qa().optional(),up=()=>el().optional(),dp={string:(t=>bt.create({...t,coerce:!0})),number:(t=>It.create({...t,coerce:!0})),boolean:(t=>Nt.create({...t,coerce:!0})),bigint:(t=>Ct.create({...t,coerce:!0})),date:(t=>Rt.create({...t,coerce:!0}))};var pp=O;var fp=u.object({name:u.string(),arguments:u.string()}),hp=u.object({id:u.string(),type:u.literal("function"),function:fp,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()}),mp=u.object({type:u.literal("text"),text:u.string()}),gp=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),vp=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),Rr=u.discriminatedUnion("type",[gp,vp]),yp=u.object({type:u.literal("image"),source:Rr,metadata:u.unknown().optional()}),bp=u.object({type:u.literal("audio"),source:Rr,metadata:u.unknown().optional()}),xp=u.object({type:u.literal("video"),source:Rr,metadata:u.unknown().optional()}),Ep=u.object({type:u.literal("document"),source:Rr,metadata:u.unknown().optional()});var tl=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()}),nl=(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"]})},Vv=tl.superRefine((t,e)=>{nl(t,e)}),Tp=u.discriminatedUnion("type",[mp,yp,bp,xp,Ep,tl]),Sp=Tp.superRefine((t,e)=>{t.type==="binary"&&nl(t,e)}),_p=Nr.extend({role:u.literal("developer"),content:u.string()}),wp=Nr.extend({role:u.literal("system"),content:u.string()}),Ap=Nr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(hp).optional()}),kp=Nr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(Sp)])}),Ip=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),Cp=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),Np=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),rl=u.discriminatedUnion("role",[_p,wp,Ap,kp,Ip,Cp,Np]),jv=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),Rp=u.object({description:u.string(),value:u.string()}),il=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),Op=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()}),Mp=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Lp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(rl),tools:u.array(il),context:u.array(Rp),forwardedProps:u.any(),resume:u.array(Mp).optional()}),Pp=u.any(),q=class extends Error{constructor(t){super(t)}},is=class extends q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Dp=u.object({name:u.string(),description:u.string().optional()}),Up=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()}),Hp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),Gp=u.object({supported:u.boolean().optional(),items:u.array(il).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Fp=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),$p=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),zp=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(Dp).optional()}),Bp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),Vp=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),jp=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),Wp=u.object({input:Vp.optional(),output:jp.optional()}),Xp=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),Kp=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()}),Wv=u.object({identity:Up.optional(),transport:Hp.optional(),tools:Gp.optional(),output:Fp.optional(),state:$p.optional(),multiAgent:zp.optional(),reasoning:Bp.optional(),multimodal:Wp.optional(),execution:Xp.optional(),humanInTheLoop:Kp.optional(),custom:u.record(u.unknown()).optional()}),ol=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(),Zp=V.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:ol.default("assistant"),name:u.string().optional()}),sl=V.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Yp=V.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),qp=V.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:ol.optional(),delta:u.string().optional(),name:u.string().optional()}),Jp=V.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),Qp=sl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),ef=V.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),tf=V.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),nf=V.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),rf=V.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),of=V.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),sf=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()}),af=V.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),lf=V.extend({type:u.literal(v.THINKING_END)}),cf=V.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:Pp}),uf=V.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),df=V.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(rl)}),pf=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)}),ff=V.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),hf=V.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),mf=V.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),gf=V.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Lp.optional()}),vf=u.object({type:u.literal("success")}).strict(),yf=u.object({type:u.literal("interrupt"),interrupts:u.array(Op).min(1)}).strict(),bf=u.discriminatedUnion("type",[vf,yf]),xf=V.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:bf.nullable().optional().transform(t=>t??void 0)}),Ef=V.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),Tf=V.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),Sf=V.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),_f=u.union([u.literal("tool-call"),u.literal("message")]),wf=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")}),kf=V.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),If=V.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),Cf=V.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),Nf=V.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),Rf=V.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:_f,entityId:u.string(),encryptedValue:u.string()}),Or=u.discriminatedUnion("type",[Zp,sl,Yp,qp,af,lf,Jp,Qp,ef,tf,nf,rf,sf,of,cf,uf,df,pf,ff,hf,mf,gf,xf,Ef,Tf,Sf,wf,Af,kf,If,Cf,Nf,Rf]);var os={};Io(os,{JsonPatchError:()=>ne,_areEquals:()=>Bn,applyOperation:()=>Bt,applyPatch:()=>Gr,applyReducer:()=>Df,deepClone:()=>Lf,getValueByPointer:()=>Ur,validate:()=>ll,validator:()=>Hr});var Of=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var o in i)i.hasOwnProperty(o)&&(r[o]=i[o])},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)}})(),Mf=Object.prototype.hasOwnProperty;function Lr(t,e){return Mf.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 i in t)Lr(t,i)&&r.push(i);return r}function be(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),i=r.length,o=0;o<i;o++)if(Mr(t[r[o]]))return!0}}return!1}function al(t,e){var n=[t];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&n.push(r+": "+i)}return n.join(`
2
- `)}var zn=(function(t){Of(e,t);function e(n,r,i,o,s){var a=this.constructor,l=t.call(this,al(n,{name:r,index:i,operation:o,tree:s}))||this;return l.name=r,l.index=i,l.operation=o,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=al(n,{name:r,index:i,operation:o,tree:s}),l}return e})(Error);var ne=zn,Lf=be,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=be(r));var i=Bt(n,{op:"remove",path:this.from}).removed;return Bt(n,{op:"add",path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Ur(n,this.from);return Bt(n,{op:"add",path:this.path,value:be(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}}},Pf={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 Bt(t,n),n.value}function Bt(t,e,n,r,i,o){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),o===void 0&&(o=0),n&&(typeof n=="function"?n(e,0,t,e.path):Hr(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",o,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",o,e,t);return s}}else{r||(t=be(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=Hr;;){if(f=l[p],f&&f.indexOf("~")!=-1&&(f=$n(f)),i&&(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",o,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",o,e,t);var s=Pf[e.op].call(e,c,f,t);if(s.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",o,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",o,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",o,e,t)}}}function Gr(t,e,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(e))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=be(t));for(var o=new Array(e.length),s=0,a=e.length;s<a;s++)o[s]=Bt(t,e[s],n,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function Df(t,e,n){var r=Bt(t,e);if(r.test===!1)throw new ne("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Hr(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 i=t.path.split("/").length,o=r.split("/").length;if(i!==o+1&&i!==o)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=ll([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 ll(t,e,n){try{if(!Array.isArray(t))throw new ne("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Gr(be(e),be(t),n||!0);else{n=n||Hr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(i){if(i instanceof ne)return i;throw i}}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),i,o,s;if(n&&r){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!Bn(t[i],e[i]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(o=a.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(a[i]))return!1;for(i=o;i--!==0;)if(s=a[i],!Bn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var cs={};Io(cs,{compare:()=>Vf,generate:()=>ss,observe:()=>Bf,unobserve:()=>zf});var as=new WeakMap,Uf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Hf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function Gf(t){return as.get(t)}function Ff(t,e){return t.observers.get(e)}function $f(t,e){t.observers.delete(e.callback)}function zf(t,e){e.unobserve()}function Bf(t,e){var n=[],r,i=Gf(t);if(!i)i=new Uf(t),as.set(t,i);else{var o=Ff(i,e);r=o&&o.observer}if(r)return r;if(r={},i.value=be(t),e){r.callback=e,r.next=null;var s=function(){ss(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(){ss(r),clearTimeout(r.next),$f(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},i.observers.set(e,new Hf(e,r)),r}function ss(t,e){e===void 0&&(e=!1);var n=as.get(t.object);ls(n.value,t.object,t.patches,"",e),t.patches.length&&Gr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function ls(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=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)?ls(m,x,n,r+"/"+et(p),i):m!==x&&(a=!0,i&&n.push({op:"test",path:r+"/"+et(p),value:be(m)}),n.push({op:"replace",path:r+"/"+et(p),value:be(x)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+et(p),value:be(m)}),n.push({op:"remove",path:r+"/"+et(p)}),l=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&o.length==s.length))for(var c=0;c<o.length;c++){var p=o[c];!Lr(t,p)&&e[p]!==void 0&&n.push({op:"add",path:r+"/"+et(p),value:be(e[p])})}}}function Vf(t,e,n){n===void 0&&(n=!1);var r=[];return ls(t,e,r,"",n),r}var Fr=Object.assign({},os,cs,{JsonPatchError:zn,deepClone:be,escapePathComponent:et,unescapePathComponent:$n});var us=function(t,e){return us=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},us(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");us(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function cl(t,e,n,r){function i(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,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?o(p.value):i(p.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function $r(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,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,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,i=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){n.label=c[1];break}if(c[0]===6&&n.label<o[1]){n.label=o[1],o=c;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(c);break}o[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(p){c=[6,p],i=0}finally{r=o=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),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function mn(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,o;r<i;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}function Vt(t){return this instanceof Vt?(this.v=t,this):new Vt(t)}function ul(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(f){return function(h){return Promise.resolve(h).then(f,m)}}function a(f,h){r[f]&&(i[f]=function(g){return new Promise(function(T,_){o.push([f,g,T,_])>1||l(f,g)})},h&&(i[f]=h(i[f])))}function l(f,h){try{c(r[f](h))}catch(g){x(o[0][3],g)}}function c(f){f.value instanceof Vt?Promise.resolve(f.value.v).then(p,m):x(o[0][2],f)}function p(f){l("next",f)}function m(f){l("throw",f)}function x(f,h){f(h),o.shift(),o.length&&l(o[0][0],o[0][1])}}function dl(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(o){n[o]=t[o]&&function(s){return new Promise(function(a,l){s=t[o](s),i(a,l,s.done,s.value)})}}function i(o,s,a,l){Promise.resolve(l).then(function(c){o({value:c,done:a})},s)}}function H(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:
1
+ var qu=Object.defineProperty;var Ro=(t,e)=>{for(var n in e)qu(t,n,{get:e[n],enumerable:!0})};var wr="ag-ui-chat",Oo="ag-ui-submit",Mo="ag-ui-toggle",Ye={USER:"user",ASSISTANT:"assistant"},Pn="x-destructive",Lo="x-confirm",Ne="x-summary",Dn="x-navigates",Po=10,ce={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Le={UPLOADING:"uploading",READY:"ready",ERROR:"error"},Do=10*1024*1024,ze={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"};var Xu=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function Ba(t,e){let n=[];return{text:t.replace(Xu,(i,o)=>{let s=e[o];return s==null||s===""?(n.includes(o)||n.push(o),i):String(s)}),missing:n}}function Ku(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 Uo(t){return Array.isArray(t)?t.filter(Ku):[]}var Un=class{#n=new Map;register(e){this.#n.set(e.name,e)}has(e){return this.#n.has(e)}get(e){let n=this.#n.get(e);if(n===void 0)throw new Error(`tool "${e}" is not registered`);return n}tools(){return[...this.#n.values()].map(e=>({name:e.name,description:e.description,parameters:e.parameters}))}};function Ho(t){return t[Pn]===!0}function Go(t){return t[Dn]===!0}function Sr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Zu=Sr(HTMLInputElement.prototype,"value"),Yu=Sr(HTMLTextAreaElement.prototype,"value"),Ju=Sr(HTMLSelectElement.prototype,"value"),Qu=Sr(HTMLInputElement.prototype,"checked");function kt(t,e){t instanceof HTMLTextAreaElement?Yu.call(t,e):t instanceof HTMLSelectElement?Ju.call(t,e):Zu.call(t,e)}function Hn(t,e){Qu.call(t,e)}var ja="#4f46e5";function _r(t){return new Promise(e=>{setTimeout(e,t)})}async function Fo(t,e,n={}){let r=n.charDelayMs??35;kt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let i of e)kt(t,t.value+i),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await _r(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function $o(t,e={}){let n=e.highlightMs??280,r=t.style.outline,i=t.style.outlineOffset;t.style.outline=`2px solid ${ja}`,t.style.outlineOffset="2px",await _r(n),t.style.outline=r,t.style.outlineOffset=i,t.click()}function lt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function zo(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 _r(n),t.style.boxShadow=r}var Va="0 0 0 3px rgba(79, 70, 229, 0.4)";function Wa(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Bo(t){return t<=0||Wa()?Promise.resolve():_r(t)}async function jo(t,e={}){let n=e.pressMs??140,r=t.style.transform,i=t.style.transition,o=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=Va,await Bo(n),t.style.transform=r,t.style.transition=i,t.style.boxShadow=o,t.click()}function ed(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function Vo(t,e,n={}){let r=ed(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let i=n.highlightMs??220,o=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${ja}`,t.style.outlineOffset="2px",await Bo(i),kt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=o,t.style.outlineOffset=s}async function Wo(t,e,n={}){let r=n.flashMs??200,i=t.style.boxShadow;t.style.boxShadow=Va,await Bo(r),Hn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=i}var qo={SCROLL:"scroll",DRAG:"drag"};function Xo(t,e){let n=[];return t.has(qo.SCROLL)&&n.push(td(e)),t.has(qo.DRAG)&&n.push(nd(e)),n}function td(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"],[Ne]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let i=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:i,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return lt(r),{scrolled:!0,target:n}}}}function nd(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"],[Ne]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),i=t(n);if(i===null)throw new Error(`no element matching "${n}"`);let o=t(r);if(o===null)throw new Error(`no element matching "${r}"`);return rd(i,o),{dragged:!0,from:n,to:r}}}}function rd(t,e){let n=new DataTransfer;Gn(t,"dragstart",n),Gn(e,"dragenter",n),Gn(e,"dragover",n),Gn(e,"drop",n),Gn(t,"dragend",n)}function Gn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function Ko(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Zo(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,i=r.name,o=r.summary;typeof i=="string"&&typeof o=="string"&&(e[i]=o)}return e}var qa=/:([A-Za-z_][A-Za-z0-9_]*)/g;function id(t){let e=[];for(let n of t.matchAll(qa)){let r=n[1];r!==void 0&&e.push(r)}return e}function od(t,e,n){let r={...n};return{path:e.replace(qa,(o,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 sd(t,e){let n=new URLSearchParams;for(let[i,o]of Object.entries(e))n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}function Yo(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:[],[Ne]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:id(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"],[Dn]:!0,[Ne]:"Navigate"},handler:n=>{let r=n.route_id,i=t().find(f=>f.id===r);if(i===void 0)throw new Error(`unknown route "${String(r)}"`);let o=n.params??{},{path:s,leftover:a}=od(i.id,i.path,o),l=sd(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}function Jo(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Ne]:`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"},[Pn]:!0,[Ne]:`Update ${t.name}`},handler:r=>n(r)}),e}var ne={title:"Assistant",chatHistory:"Chat history",newChat:"New chat",collapse:"Collapse",expand:"Expand",toggleTheme:"Toggle theme",checkpoints:"Continue a run",noCheckpoints:"Nothing to continue yet.",resumeRun:"Resume",forkRun:"Fork",forkedRun:"branched",conversation:"Conversation",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",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",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",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",approveAction:"Approve action",approvalPrompt:"Approve this action?",approve:"Approve",deny:"Deny",askUserAction:"Question",otherOption:"Other\u2026",answerPlaceholder:"Type your answer\u2026",submit:"Submit",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 Qo(t){let e={...ne};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function Xa(t,e){let n=document.createElement("button");return n.type="button",n.className=`approval-btn approval-btn--${t}`,n.setAttribute("part",`approval-button approval-${t}`),n.textContent=e,n}function es(t,e,n={}){let r=n.strings??ne;return new Promise(i=>{let o=document.createElement("div");o.className="approval",o.setAttribute("part","approval"),e.toolName!==void 0&&o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.setAttribute("aria-label",r.approveAction);let s=document.createElement("div");s.className="approval-body",s.setAttribute("part","approval-body"),s.textContent=e.message??r.approvalPrompt;let a=document.createElement("div");a.className="approval-actions",a.setAttribute("part","approval-actions");let l=Xa("deny",r.deny),c=Xa("approve",r.approve),f=!1,m=b=>{f||(f=!0,l.disabled=!0,c.disabled=!0,o.setAttribute("data-resolved",b?"approved":"denied"),i(b))};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,a),t.appendChild(o),n.signal?.aborted===!0){m(!1);return}c.focus()})}function ts(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(ad(n));return e}function ad(t){let e=document.createElement("div");e.className="attachment-chip attachment-chip--ready",e.setAttribute("part","attachment-chip");let n=document.createElement("span");n.className="attachment-chip-icon",n.setAttribute("part","attachment-chip-icon"),n.textContent=ns(t.mime),n.setAttribute("aria-hidden","true");let r=document.createElement("span");r.className="attachment-chip-name",r.setAttribute("part","attachment-chip-name"),r.textContent=t.name,r.title=t.name;let i=document.createElement("span");return i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=Ar(t.size),e.append(n,r,i),e}function ns(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function Ar(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 ve=[];for(let t=0;t<256;++t)ve.push((t+256).toString(16).slice(1));function Ka(t,e=0){return(ve[t[e+0]]+ve[t[e+1]]+ve[t[e+2]]+ve[t[e+3]]+"-"+ve[t[e+4]]+ve[t[e+5]]+"-"+ve[t[e+6]]+ve[t[e+7]]+"-"+ve[t[e+8]]+ve[t[e+9]]+"-"+ve[t[e+10]]+ve[t[e+11]]+ve[t[e+12]]+ve[t[e+13]]+ve[t[e+14]]+ve[t[e+15]]).toLowerCase()}var rs,ld=new Uint8Array(16);function is(){if(!rs){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rs=crypto.getRandomValues.bind(crypto)}return rs(ld)}var cd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),os={randomUUID:cd};function ud(t,e,n){if(os.randomUUID&&!e&&!t)return os.randomUUID();t=t||{};let r=t.random??t.rng?.()??is();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 i=0;i<16;++i)e[n+i]=r[i];return e}return Ka(r)}var bt=ud;var u={};Ro(u,{BRAND:()=>Dd,DIRTY:()=>It,EMPTY_PATH:()=>hd,INVALID:()=>M,NEVER:()=>xp,OK:()=>Ee,ParseStatus:()=>be,Schema:()=>$,ZodAny:()=>Et,ZodArray:()=>pt,ZodBigInt:()=>Nt,ZodBoolean:()=>Rt,ZodBranded:()=>$n,ZodCatch:()=>zt,ZodDate:()=>Ot,ZodDefault:()=>$t,ZodDiscriminatedUnion:()=>Cr,ZodEffects:()=>Ue,ZodEnum:()=>Gt,ZodError:()=>ke,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Rr,ZodIntersection:()=>Dt,ZodIssueCode:()=>T,ZodLazy:()=>Ut,ZodLiteral:()=>Ht,ZodMap:()=>dn,ZodNaN:()=>fn,ZodNativeEnum:()=>Ft,ZodNever:()=>Be,ZodNull:()=>Lt,ZodNullable:()=>et,ZodNumber:()=>Ct,ZodObject:()=>Ie,ZodOptional:()=>Pe,ZodParsedType:()=>k,ZodPipeline:()=>zn,ZodPromise:()=>Tt,ZodReadonly:()=>Bt,ZodRecord:()=>Nr,ZodSchema:()=>$,ZodSet:()=>pn,ZodString:()=>xt,ZodSymbol:()=>cn,ZodTransformer:()=>Ue,ZodTuple:()=>Qe,ZodType:()=>$,ZodUndefined:()=>Mt,ZodUnion:()=>Pt,ZodUnknown:()=>dt,ZodVoid:()=>un,addIssueToContext:()=>_,any:()=>Vd,array:()=>Kd,bigint:()=>Fd,boolean:()=>sl,coerce:()=>yp,custom:()=>rl,date:()=>$d,datetimeRegex:()=>tl,defaultErrorMap:()=>ct,discriminatedUnion:()=>Qd,effect:()=>dp,enum:()=>lp,function:()=>op,getErrorMap:()=>sn,getParsedType:()=>Je,instanceof:()=>Hd,intersection:()=>ep,isAborted:()=>kr,isAsync:()=>an,isDirty:()=>Ir,isValid:()=>yt,late:()=>Ud,lazy:()=>sp,literal:()=>ap,makeIssue:()=>Fn,map:()=>rp,nan:()=>Gd,nativeEnum:()=>cp,never:()=>qd,null:()=>jd,nullable:()=>fp,number:()=>ol,object:()=>Zd,objectUtil:()=>ss,oboolean:()=>bp,onumber:()=>vp,optional:()=>pp,ostring:()=>gp,pipeline:()=>mp,preprocess:()=>hp,promise:()=>up,quotelessJson:()=>dd,record:()=>np,set:()=>ip,setErrorMap:()=>fd,strictObject:()=>Yd,string:()=>il,symbol:()=>zd,transformer:()=>dp,tuple:()=>tp,undefined:()=>Bd,union:()=>Jd,unknown:()=>Wd,util:()=>B,void:()=>Xd});var B;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},t.getValidEnumValues=i=>{let o=t.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return t.objectValues(s)},t.objectValues=i=>t.objectKeys(i).map(function(o){return i[o]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},t.find=(i,o)=>{for(let s of i)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=r,t.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(B||(B={}));var ss;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(ss||(ss={}));var k=B.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Je=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 T=B.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),dd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ke=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(o){return o.message},r={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(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 i(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,B.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};ke.create=t=>new ke(t);var pd=(t,e)=>{let n;switch(t.code){case T.invalid_type:t.received===k.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,B.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${B.joinValues(t.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${B.joinValues(t.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${B.joinValues(t.options)}, received '${t.received}'`;break;case T.invalid_arguments:n="Invalid function arguments";break;case T.invalid_return_type:n="Invalid function return type";break;case T.invalid_date:n="Invalid date";break;case T.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:B.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case T.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 T.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 T.custom:n="Invalid input";break;case T.invalid_intersection_types:n="Intersection results could not be merged";break;case T.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case T.not_finite:n="Number must be finite";break;default:n=e.defaultError,B.assertNever(t)}return{message:n}},ct=pd;var Za=ct;function fd(t){Za=t}function sn(){return Za}var Fn=t=>{let{data:e,path:n,errorMaps:r,issueData:i}=t,o=[...n,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...i,path:o,message:a}},hd=[];function _(t,e){let n=sn(),r=Fn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ct?void 0:ct].filter(i=>!!i)});t.common.issues.push(r)}var be=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 i of n){if(i.status==="aborted")return M;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let i of n){let o=await i.key,s=await i.value;r.push({key:o,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let i of n){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return M;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(r[o.value]=s.value)}return{status:e.value,value:r}}},M=Object.freeze({status:"aborted"}),It=t=>({status:"dirty",value:t}),Ee=t=>({status:"valid",value:t}),kr=t=>t.status==="aborted",Ir=t=>t.status==="dirty",yt=t=>t.status==="valid",an=t=>typeof Promise<"u"&&t instanceof Promise;var C;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(C||(C={}));var De=class{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ya=(t,e)=>{if(yt(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 ke(t.common.issues);return this._error=n,this._error}}};function H(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:i}=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:i}:{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:i}}var $=class{get description(){return this._def.description}_getType(e){return Je(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new be,ctx:{common:e.parent.common,data:e.data,parsedType:Je(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(an(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:Je(e)},i=this._parseSync({data:e,path:r.path,parent:r});return Ya(r,i)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Je(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return yt(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=>yt(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:Je(e)},i=this._parse({data:e,path:r.path,parent:r}),o=await(an(i)?i:Promise.resolve(i));return Ya(r,o)}refine(e,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,o)=>{let s=e(i),a=()=>o.addIssue({code:T.custom,...r(i)});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,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new Ue({schema:this,typeName:L.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 Pe.create(this,this._def)}nullable(){return et.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Tt.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return Dt.create(this,e,this._def)}transform(e){return new Ue({...H(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new $t({...H(this._def),innerType:this,defaultValue:n,typeName:L.ZodDefault})}brand(){return new $n({typeName:L.ZodBranded,type:this,...H(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new zt({...H(this._def),innerType:this,catchValue:n,typeName:L.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return zn.create(this,e)}readonly(){return Bt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},md=/^c[^\s-]{8,}$/i,gd=/^[0-9a-z]+$/,vd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,bd=/^[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,yd=/^[a-z0-9_-]{21}$/i,xd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Ed=/^[-+]?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)?)??$/,Td=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",as,Sd=/^(?:(?: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])$/,_d=/^(?:(?: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])$/,Ad=/^(([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]))$/,kd=/^(([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])$/,Id=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Qa="((\\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])))",Nd=new RegExp(`^${Qa}$`);function el(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 Rd(t){return new RegExp(`^${el(t)}$`)}function tl(t){let e=`${Qa}T${el(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 Od(t,e){return!!((e==="v4"||!e)&&Sd.test(t)||(e==="v6"||!e)&&Ad.test(t))}function Md(t,e){if(!xd.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,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function Ld(t,e){return!!((e==="v4"||!e)&&_d.test(t)||(e==="v6"||!e)&&kd.test(t))}var xt=class t extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_type,expected:k.string,received:o.parsedType}),M}let r=new be,i;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")e.data.length>o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,a=e.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(e,i),s?_(i,{code:T.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&_(i,{code:T.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")Td.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"email",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")as||(as=new RegExp(wd,"u")),as.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"emoji",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")bd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"uuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")yd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"nanoid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")md.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"cuid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")gd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"cuid2",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")vd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"ulid",code:T.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),_(i,{validation:"url",code:T.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"regex",code:T.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?tl(o).test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?Nd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?Rd(o).test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{code:T.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?Ed.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"duration",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?Od(e.data,o.version)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"ip",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?Md(e.data,o.alg)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"jwt",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?Ld(e.data,o.version)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"cidr",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?Id.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"base64",code:T.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?Cd.test(e.data)||(i=this._getOrReturnCtx(e,i),_(i,{validation:"base64url",code:T.invalid_string,message:o.message}),r.dirty()):B.assertNever(o);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:T.invalid_string,...C.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...C.errToObj(e)})}url(e){return this._addCheck({kind:"url",...C.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...C.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...C.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...C.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...C.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...C.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...C.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...C.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...C.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...C.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...C.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...C.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,...C.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,...C.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...C.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...C.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...C.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...C.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...C.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...C.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...C.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...C.errToObj(n)})}nonempty(e){return this.min(1,C.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}};xt.create=t=>new xt({checks:[],typeName:L.ZodString,coerce:t?.coerce??!1,...H(t)});function Pd(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(t.toFixed(i).replace(".","")),s=Number.parseInt(e.toFixed(i).replace(".",""));return o%s/10**i}var Ct=class t extends ${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 o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_type,expected:k.number,received:o.parsedType}),M}let r,i=new be;for(let o of this._def.checks)o.kind==="int"?B.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:T.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Pd(e.data,o.value)!==0&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_finite,message:o.message}),i.dirty()):B.assertNever(o);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,C.toString(n))}gt(e,n){return this.setLimit("min",e,!1,C.toString(n))}lte(e,n){return this.setLimit("max",e,!0,C.toString(n))}lt(e,n){return this.setLimit("max",e,!1,C.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:C.toString(i)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:C.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:C.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:C.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:C.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:C.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:C.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"&&B.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)}};Ct.create=t=>new Ct({checks:[],typeName:L.ZodNumber,coerce:t?.coerce||!1,...H(t)});var Nt=class t extends ${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,i=new be;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),_(r,{code:T.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):B.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return _(n,{code:T.invalid_type,expected:k.bigint,received:n.parsedType}),M}gte(e,n){return this.setLimit("min",e,!0,C.toString(n))}gt(e,n){return this.setLimit("min",e,!1,C.toString(n))}lte(e,n){return this.setLimit("max",e,!0,C.toString(n))}lt(e,n){return this.setLimit("max",e,!1,C.toString(n))}setLimit(e,n,r,i){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:C.toString(i)}]})}_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:C.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:C.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:C.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:C.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:C.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}};Nt.create=t=>new Nt({checks:[],typeName:L.ZodBigInt,coerce:t?.coerce??!1,...H(t)});var Rt=class extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.boolean,received:r.parsedType}),M}return Ee(e.data)}};Rt.create=t=>new Rt({typeName:L.ZodBoolean,coerce:t?.coerce||!1,...H(t)});var Ot=class t extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_type,expected:k.date,received:o.parsedType}),M}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return _(o,{code:T.invalid_date}),M}let r=new be,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(i=this._getOrReturnCtx(e,i),_(i,{code:T.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):B.assertNever(o);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:C.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:C.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}};Ot.create=t=>new Ot({checks:[],coerce:t?.coerce||!1,typeName:L.ZodDate,...H(t)});var cn=class extends ${_parse(e){if(this._getType(e)!==k.symbol){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.symbol,received:r.parsedType}),M}return Ee(e.data)}};cn.create=t=>new cn({typeName:L.ZodSymbol,...H(t)});var Mt=class extends ${_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.undefined,received:r.parsedType}),M}return Ee(e.data)}};Mt.create=t=>new Mt({typeName:L.ZodUndefined,...H(t)});var Lt=class extends ${_parse(e){if(this._getType(e)!==k.null){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.null,received:r.parsedType}),M}return Ee(e.data)}};Lt.create=t=>new Lt({typeName:L.ZodNull,...H(t)});var Et=class extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Ee(e.data)}};Et.create=t=>new Et({typeName:L.ZodAny,...H(t)});var dt=class extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ee(e.data)}};dt.create=t=>new dt({typeName:L.ZodUnknown,...H(t)});var Be=class extends ${_parse(e){let n=this._getOrReturnCtx(e);return _(n,{code:T.invalid_type,expected:k.never,received:n.parsedType}),M}};Be.create=t=>new Be({typeName:L.ZodNever,...H(t)});var un=class extends ${_parse(e){if(this._getType(e)!==k.undefined){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.void,received:r.parsedType}),M}return Ee(e.data)}};un.create=t=>new un({typeName:L.ZodVoid,...H(t)});var pt=class t extends ${_parse(e){let{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==k.array)return _(n,{code:T.invalid_type,expected:k.array,received:n.parsedType}),M;if(i.exactLength!==null){let s=n.data.length>i.exactLength.value,a=n.data.length<i.exactLength.value;(s||a)&&(_(n,{code:s?T.too_big:T.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(_(n,{code:T.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(_(n,{code:T.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>i.type._parseAsync(new De(n,s,n.path,a)))).then(s=>be.mergeArray(r,s));let o=[...n.data].map((s,a)=>i.type._parseSync(new De(n,s,n.path,a)));return be.mergeArray(r,o)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:C.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:C.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:C.toString(n)}})}nonempty(e){return this.min(1,e)}};pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...H(e)});function ln(t){if(t instanceof Ie){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Pe.create(ln(r))}return new Ie({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:ln(t.element)}):t instanceof Pe?Pe.create(ln(t.unwrap())):t instanceof et?et.create(ln(t.unwrap())):t instanceof Qe?Qe.create(t.items.map(e=>ln(e))):t}var Ie=class t extends ${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=B.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 _(c,{code:T.invalid_type,expected:k.object,received:c.parsedType}),M}let{status:r,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Be&&this._def.unknownKeys==="strip"))for(let c in i.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let f=o[c],m=i.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new De(i,m,i.path,c)),alwaysSet:c in i.data})}if(this._def.catchall instanceof Be){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:i.data[f]}});else if(c==="strict")a.length>0&&(_(i,{code:T.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 f of a){let m=i.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new De(i,m,i.path,f)),alwaysSet:f in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let m=await f.key,b=await f.value;c.push({key:m,value:b,alwaysSet:f.alwaysSet})}return c}).then(c=>be.mergeObjectSync(r,c)):be.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return C.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:C.errToObj(e).message??i}:{message:i}}}:{}})}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:L.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 B.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 B.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return ln(this)}partial(e){let n={};for(let r of B.objectKeys(this.shape)){let i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of B.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Pe;)o=o._def.innerType;n[r]=o}return new t({...this._def,shape:()=>n})}keyof(){return nl(B.objectKeys(this.shape))}};Ie.create=(t,e)=>new Ie({shape:()=>t,unknownKeys:"strip",catchall:Be.create(),typeName:L.ZodObject,...H(e)});Ie.strictCreate=(t,e)=>new Ie({shape:()=>t,unknownKeys:"strict",catchall:Be.create(),typeName:L.ZodObject,...H(e)});Ie.lazycreate=(t,e)=>new Ie({shape:t,unknownKeys:"strip",catchall:Be.create(),typeName:L.ZodObject,...H(e)});var Pt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new ke(a.ctx.common.issues));return _(n,{code:T.invalid_union,unionErrors:s}),M}if(n.common.async)return Promise.all(r.map(async o=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!o&&(o={result:f,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(l=>new ke(l));return _(n,{code:T.invalid_union,unionErrors:a}),M}}get options(){return this._def.options}};Pt.create=(t,e)=>new Pt({options:t,typeName:L.ZodUnion,...H(e)});var ut=t=>t instanceof Ut?ut(t.schema):t instanceof Ue?ut(t.innerType()):t instanceof Ht?[t.value]:t instanceof Gt?t.options:t instanceof Ft?B.objectValues(t.enum):t instanceof $t?ut(t._def.innerType):t instanceof Mt?[void 0]:t instanceof Lt?[null]:t instanceof Pe?[void 0,...ut(t.unwrap())]:t instanceof et?[null,...ut(t.unwrap())]:t instanceof $n||t instanceof Bt?ut(t.unwrap()):t instanceof zt?ut(t._def.innerType):[],Cr=class t extends ${_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.object)return _(n,{code:T.invalid_type,expected:k.object,received:n.parsedType}),M;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(_(n,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),M)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let i=new Map;for(let o of n){let s=ut(o.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(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,o)}}return new t({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...H(r)})}};function ls(t,e){let n=Je(t),r=Je(e);if(t===e)return{valid:!0,data:t};if(n===k.object&&r===k.object){let i=B.objectKeys(e),o=B.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(let a of o){let l=ls(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 i=[];for(let o=0;o<t.length;o++){let s=t[o],a=e[o],l=ls(s,a);if(!l.valid)return{valid:!1};i.push(l.data)}return{valid:!0,data:i}}else return n===k.date&&r===k.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Dt=class extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=(o,s)=>{if(kr(o)||kr(s))return M;let a=ls(o.value,s.value);return a.valid?((Ir(o)||Ir(s))&&n.dirty(),{status:n.value,value:a.data}):(_(r,{code:T.invalid_intersection_types}),M)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Dt.create=(t,e,n)=>new Dt({left:t,right:e,typeName:L.ZodIntersection,...H(n)});var Qe=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.array)return _(r,{code:T.invalid_type,expected:k.array,received:r.parsedType}),M;if(r.data.length<this._def.items.length)return _(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),M;!this._def.rest&&r.data.length>this._def.items.length&&(_(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new De(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(o).then(s=>be.mergeArray(n,s)):be.mergeArray(n,o)}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:L.ZodTuple,rest:null,...H(e)})};var Nr=class t extends ${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 _(r,{code:T.invalid_type,expected:k.object,received:r.parsedType}),M;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in r.data)i.push({key:o._parse(new De(r,a,r.path,a)),value:s._parse(new De(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?be.mergeObjectAsync(n,i):be.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof $?new t({keyType:e,valueType:n,typeName:L.ZodRecord,...H(r)}):new t({keyType:xt.create(),valueType:e,typeName:L.ZodRecord,...H(n)})}},dn=class extends ${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 _(r,{code:T.invalid_type,expected:k.map,received:r.parsedType}),M;let i=this._def.keyType,o=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:i._parse(new De(r,a,r.path,[c,"key"])),value:o._parse(new De(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,f=await l.value;if(c.status==="aborted"||f.status==="aborted")return M;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(c.value,f.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,f=l.value;if(c.status==="aborted"||f.status==="aborted")return M;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(c.value,f.value)}return{status:n.value,value:a}}}};dn.create=(t,e,n)=>new dn({valueType:e,keyType:t,typeName:L.ZodMap,...H(n)});var pn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==k.set)return _(r,{code:T.invalid_type,expected:k.set,received:r.parsedType}),M;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(_(r,{code:T.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(_(r,{code:T.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function s(l){let c=new Set;for(let f of l){if(f.status==="aborted")return M;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>o._parse(new De(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:C.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:C.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};pn.create=(t,e)=>new pn({valueType:t,minSize:null,maxSize:null,typeName:L.ZodSet,...H(e)});var Rr=class t extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.function)return _(n,{code:T.invalid_type,expected:k.function,received:n.parsedType}),M;function r(a,l){return Fn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),ct].filter(c=>!!c),issueData:{code:T.invalid_arguments,argumentsError:l}})}function i(a,l){return Fn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,sn(),ct].filter(c=>!!c),issueData:{code:T.invalid_return_type,returnTypeError:l}})}let o={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Tt){let a=this;return Ee(async function(...l){let c=new ke([]),f=await a._def.args.parseAsync(l,o).catch(h=>{throw c.addIssue(r(l,h)),c}),m=await Reflect.apply(s,this,f);return await a._def.returns._def.type.parseAsync(m,o).catch(h=>{throw c.addIssue(i(m,h)),c})})}else{let a=this;return Ee(function(...l){let c=a._def.args.safeParse(l,o);if(!c.success)throw new ke([r(l,c.error)]);let f=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(f,o);if(!m.success)throw new ke([i(f,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(dt.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(dt.create()),returns:n||dt.create(),typeName:L.ZodFunction,...H(r)})}},Ut=class extends ${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})}};Ut.create=(t,e)=>new Ut({getter:t,typeName:L.ZodLazy,...H(e)});var Ht=class extends ${_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return _(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),M}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ht.create=(t,e)=>new Ht({value:t,typeName:L.ZodLiteral,...H(e)});function nl(t,e){return new Gt({values:t,typeName:L.ZodEnum,...H(e)})}var Gt=class t extends ${_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return _(n,{expected:B.joinValues(r),received:n.parsedType,code:T.invalid_type}),M}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 _(n,{received:n.data,code:T.invalid_enum_value,options:r}),M}return Ee(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})}};Gt.create=nl;var Ft=class extends ${_parse(e){let n=B.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==k.string&&r.parsedType!==k.number){let i=B.objectValues(n);return _(r,{expected:B.joinValues(i),received:r.parsedType,code:T.invalid_type}),M}if(this._cache||(this._cache=new Set(B.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let i=B.objectValues(n);return _(r,{received:r.data,code:T.invalid_enum_value,options:i}),M}return Ee(e.data)}get enum(){return this._def.values}};Ft.create=(t,e)=>new Ft({values:t,typeName:L.ZodNativeEnum,...H(e)});var Tt=class extends ${unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==k.promise&&n.common.async===!1)return _(n,{code:T.invalid_type,expected:k.promise,received:n.parsedType}),M;let r=n.parsedType===k.promise?n.data:Promise.resolve(n.data);return Ee(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tt.create=(t,e)=>new Tt({type:t,typeName:L.ZodPromise,...H(e)});var Ue=class extends ${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{_(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(r.data,o);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return M;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?M:l.status==="dirty"?It(l.value):n.value==="dirty"?It(l.value):l});{if(n.value==="aborted")return M;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?M:a.status==="dirty"?It(a.value):n.value==="dirty"?It(a.value):a}}if(i.type==="refinement"){let s=a=>{let l=i.refinement(a,o);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"?M:(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"?M:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(i.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!yt(s))return M;let a=i.transform(s.value,o);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=>yt(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:n.value,value:a})):M);B.assertNever(i)}};Ue.create=(t,e,n)=>new Ue({schema:t,typeName:L.ZodEffects,effect:e,...H(n)});Ue.createWithPreprocess=(t,e,n)=>new Ue({schema:e,effect:{type:"preprocess",transform:t},typeName:L.ZodEffects,...H(n)});var Pe=class extends ${_parse(e){return this._getType(e)===k.undefined?Ee(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Pe.create=(t,e)=>new Pe({innerType:t,typeName:L.ZodOptional,...H(e)});var et=class extends ${_parse(e){return this._getType(e)===k.null?Ee(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};et.create=(t,e)=>new et({innerType:t,typeName:L.ZodNullable,...H(e)});var $t=class extends ${_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}};$t.create=(t,e)=>new $t({innerType:t,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...H(e)});var zt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return an(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ke(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};zt.create=(t,e)=>new zt({innerType:t,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...H(e)});var fn=class extends ${_parse(e){if(this._getType(e)!==k.nan){let r=this._getOrReturnCtx(e);return _(r,{code:T.invalid_type,expected:k.nan,received:r.parsedType}),M}return{status:"valid",value:e.data}}};fn.create=t=>new fn({typeName:L.ZodNaN,...H(t)});var Dd=Symbol("zod_brand"),$n=class extends ${_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}},zn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?M:o.status==="dirty"?(n.dirty(),It(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?M:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:L.ZodPipeline})}},Bt=class extends ${_parse(e){let n=this._def.innerType._parse(e),r=i=>(yt(i)&&(i.value=Object.freeze(i.value)),i);return an(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:L.ZodReadonly,...H(e)});function Ja(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function rl(t,e={},n){return t?Et.create().superRefine((r,i)=>{let o=t(r);if(o instanceof Promise)return o.then(s=>{if(!s){let a=Ja(e,r),l=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:l})}});if(!o){let s=Ja(e,r),a=s.fatal??n??!0;i.addIssue({code:"custom",...s,fatal:a})}}):Et.create()}var Ud={object:Ie.lazycreate},L;(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"})(L||(L={}));var Hd=(t,e={message:`Input not instance of ${t.name}`})=>rl(n=>n instanceof t,e),il=xt.create,ol=Ct.create,Gd=fn.create,Fd=Nt.create,sl=Rt.create,$d=Ot.create,zd=cn.create,Bd=Mt.create,jd=Lt.create,Vd=Et.create,Wd=dt.create,qd=Be.create,Xd=un.create,Kd=pt.create,Zd=Ie.create,Yd=Ie.strictCreate,Jd=Pt.create,Qd=Cr.create,ep=Dt.create,tp=Qe.create,np=Nr.create,rp=dn.create,ip=pn.create,op=Rr.create,sp=Ut.create,ap=Ht.create,lp=Gt.create,cp=Ft.create,up=Tt.create,dp=Ue.create,pp=Pe.create,fp=et.create,hp=Ue.createWithPreprocess,mp=zn.create,gp=()=>il().optional(),vp=()=>ol().optional(),bp=()=>sl().optional(),yp={string:(t=>xt.create({...t,coerce:!0})),number:(t=>Ct.create({...t,coerce:!0})),boolean:(t=>Rt.create({...t,coerce:!0})),bigint:(t=>Nt.create({...t,coerce:!0})),date:(t=>Ot.create({...t,coerce:!0}))};var xp=M;var Ep=u.object({name:u.string(),arguments:u.string()}),Tp=u.object({id:u.string(),type:u.literal("function"),function:Ep,encryptedValue:u.string().optional()}),Or=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),wp=u.object({type:u.literal("text"),text:u.string()}),Sp=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),_p=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),Mr=u.discriminatedUnion("type",[Sp,_p]),Ap=u.object({type:u.literal("image"),source:Mr,metadata:u.unknown().optional()}),kp=u.object({type:u.literal("audio"),source:Mr,metadata:u.unknown().optional()}),Ip=u.object({type:u.literal("video"),source:Mr,metadata:u.unknown().optional()}),Cp=u.object({type:u.literal("document"),source:Mr,metadata:u.unknown().optional()});var al=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()}),ll=(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"]})},nb=al.superRefine((t,e)=>{ll(t,e)}),Np=u.discriminatedUnion("type",[wp,Ap,kp,Ip,Cp,al]),Rp=Np.superRefine((t,e)=>{t.type==="binary"&&ll(t,e)}),Op=Or.extend({role:u.literal("developer"),content:u.string()}),Mp=Or.extend({role:u.literal("system"),content:u.string()}),Lp=Or.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(Tp).optional()}),Pp=Or.extend({role:u.literal("user"),content:u.union([u.string(),u.array(Rp)])}),Dp=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())}),Hp=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),cl=u.discriminatedUnion("role",[Op,Mp,Lp,Pp,Dp,Up,Hp]),rb=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),Gp=u.object({description:u.string(),value:u.string()}),ul=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()}),$p=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),zp=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(cl),tools:u.array(ul),context:u.array(Gp),forwardedProps:u.any(),resume:u.array($p).optional()}),Bp=u.any(),Q=class extends Error{constructor(t){super(t)}},cs=class extends Q{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},jp=u.object({name:u.string(),description:u.string().optional()}),Vp=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()}),Wp=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),qp=u.object({supported:u.boolean().optional(),items:u.array(ul).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),Xp=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),Kp=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),Zp=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(jp).optional()}),Yp=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),Jp=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),Qp=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),ef=u.object({input:Jp.optional(),output:Qp.optional()}),tf=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),nf=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()}),ib=u.object({identity:Vp.optional(),transport:Wp.optional(),tools:qp.optional(),output:Xp.optional(),state:Kp.optional(),multiAgent:Zp.optional(),reasoning:Yp.optional(),multimodal:ef.optional(),execution:tf.optional(),humanInTheLoop:nf.optional(),custom:u.record(u.unknown()).optional()}),dl=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})({}),q=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),rf=q.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:dl.default("assistant"),name:u.string().optional()}),pl=q.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),of=q.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),sf=q.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:dl.optional(),delta:u.string().optional(),name:u.string().optional()}),af=q.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),lf=pl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),cf=q.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),uf=q.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),df=q.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),pf=q.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),ff=q.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),hf=q.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),mf=q.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),gf=q.extend({type:u.literal(v.THINKING_END)}),vf=q.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:Bp}),bf=q.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),yf=q.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(cl)}),xf=q.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),Ef=q.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),Tf=q.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),wf=q.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Sf=q.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:zp.optional()}),_f=u.object({type:u.literal("success")}).strict(),Af=u.object({type:u.literal("interrupt"),interrupts:u.array(Fp).min(1)}).strict(),kf=u.discriminatedUnion("type",[_f,Af]),If=q.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:kf.nullable().optional().transform(t=>t??void 0)}),Cf=q.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),Nf=q.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),Rf=q.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),Of=u.union([u.literal("tool-call"),u.literal("message")]),Mf=q.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),Lf=q.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),Pf=q.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Df=q.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),Uf=q.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),Hf=q.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),Gf=q.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:Of,entityId:u.string(),encryptedValue:u.string()}),Lr=u.discriminatedUnion("type",[rf,pl,of,sf,mf,gf,af,lf,cf,uf,df,pf,hf,ff,vf,bf,yf,xf,Ef,Tf,wf,Sf,If,Cf,Nf,Rf,Mf,Lf,Pf,Df,Uf,Hf,Gf]);var us={};Ro(us,{JsonPatchError:()=>ie,_areEquals:()=>Vn,applyOperation:()=>jt,applyPatch:()=>$r,applyReducer:()=>jf,deepClone:()=>zf,getValueByPointer:()=>Gr,validate:()=>hl,validator:()=>Fr});var Ff=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var o in i)i.hasOwnProperty(o)&&(r[o]=i[o])},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)}})(),$f=Object.prototype.hasOwnProperty;function Dr(t,e){return $f.call(t,e)}function Ur(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 i in t)Dr(t,i)&&r.push(i);return r}function ye(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Hr(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 tt(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Bn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Pr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Pr(t[e]))return!0}else if(typeof t=="object"){for(var r=Ur(t),i=r.length,o=0;o<i;o++)if(Pr(t[r[o]]))return!0}}return!1}function fl(t,e){var n=[t];for(var r in e){var i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&n.push(r+": "+i)}return n.join(`
2
+ `)}var jn=(function(t){Ff(e,t);function e(n,r,i,o,s){var a=this.constructor,l=t.call(this,fl(n,{name:r,index:i,operation:o,tree:s}))||this;return l.name=r,l.index=i,l.operation=o,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=fl(n,{name:r,index:i,operation:o,tree:s}),l}return e})(Error);var ie=jn,zf=ye,hn={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=Gr(n,this.path);r&&(r=ye(r));var i=jt(n,{op:"remove",path:this.from}).removed;return jt(n,{op:"add",path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Gr(n,this.from);return jt(n,{op:"add",path:this.path,value:ye(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Vn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},Bf={add:function(t,e,n){return Hr(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:hn.move,copy:hn.copy,test:hn.test,_get:hn._get};function Gr(t,e){if(e=="")return t;var n={op:"_get",path:e};return jt(t,n),n.value}function jt(t,e,n,r,i,o){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),o===void 0&&(o=0),n&&(typeof n=="function"?n(e,0,t,e.path):Fr(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=Gr(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Vn(t,e.value),s.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",o,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 ie("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",o,e,t);return s}}else{r||(t=ye(t));var a=e.path||"",l=a.split("/"),c=t,f=1,m=l.length,b=void 0,h=void 0,d=void 0;for(typeof n=="function"?d=n:d=Fr;;){if(h=l[f],h&&h.indexOf("~")!=-1&&(h=Bn(h)),i&&(h=="__proto__"||h=="prototype"&&f>0&&l[f-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&&b===void 0&&(c[h]===void 0?b=l.slice(0,f).join("/"):f==m-1&&(b=e.path),b!==void 0&&d(e,0,t,b)),f++,Array.isArray(c)){if(h==="-")h=c.length;else{if(n&&!Hr(h))throw new ie("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",o,e,t);Hr(h)&&(h=~~h)}if(f>=m){if(n&&e.op==="add"&&h>c.length)throw new ie("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",o,e,t);var s=Bf[e.op].call(e,c,h,t);if(s.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}}else if(f>=m){var s=hn[e.op].call(e,c,h,t);if(s.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",o,e,t);return s}if(c=c[h],n&&f<m&&(!c||typeof c!="object"))throw new ie("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",o,e,t)}}}function $r(t,e,n,r,i){if(r===void 0&&(r=!0),i===void 0&&(i=!0),n&&!Array.isArray(e))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=ye(t));for(var o=new Array(e.length),s=0,a=e.length;s<a;s++)o[s]=jt(t,e[s],n,!0,i,s),t=o[s].newDocument;return o.newDocument=t,o}function jf(t,e,n){var r=jt(t,e);if(r.test===!1)throw new ie("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Fr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new ie("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(hn[t.op]){if(typeof t.path!="string")throw new ie("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new ie('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 ie("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 ie("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")&&Pr(t.value))throw new ie("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 i=t.path.split("/").length,o=r.split("/").length;if(i!==o+1&&i!==o)throw new ie("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 ie("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=hl([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new ie("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new ie("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function hl(t,e,n){try{if(!Array.isArray(t))throw new ie("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)$r(ye(e),ye(t),n||!0);else{n=n||Fr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(i){if(i instanceof ie)return i;throw i}}function Vn(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),i,o,s;if(n&&r){if(o=t.length,o!=e.length)return!1;for(i=o;i--!==0;)if(!Vn(t[i],e[i]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(o=a.length,o!==Object.keys(e).length)return!1;for(i=o;i--!==0;)if(!e.hasOwnProperty(a[i]))return!1;for(i=o;i--!==0;)if(s=a[i],!Vn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var hs={};Ro(hs,{compare:()=>Jf,generate:()=>ds,observe:()=>Yf,unobserve:()=>Zf});var ps=new WeakMap,Vf=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Wf=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function qf(t){return ps.get(t)}function Xf(t,e){return t.observers.get(e)}function Kf(t,e){t.observers.delete(e.callback)}function Zf(t,e){e.unobserve()}function Yf(t,e){var n=[],r,i=qf(t);if(!i)i=new Vf(t),ps.set(t,i);else{var o=Xf(i,e);r=o&&o.observer}if(r)return r;if(r={},i.value=ye(t),e){r.callback=e,r.next=null;var s=function(){ds(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(){ds(r),clearTimeout(r.next),Kf(i,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},i.observers.set(e,new Wf(e,r)),r}function ds(t,e){e===void 0&&(e=!1);var n=ps.get(t.object);fs(n.value,t.object,t.patches,"",e),t.patches.length&&$r(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function fs(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var o=Ur(e),s=Ur(t),a=!1,l=!1,c=s.length-1;c>=0;c--){var f=s[c],m=t[f];if(Dr(e,f)&&!(e[f]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var b=e[f];typeof m=="object"&&m!=null&&typeof b=="object"&&b!=null&&Array.isArray(m)===Array.isArray(b)?fs(m,b,n,r+"/"+tt(f),i):m!==b&&(a=!0,i&&n.push({op:"test",path:r+"/"+tt(f),value:ye(m)}),n.push({op:"replace",path:r+"/"+tt(f),value:ye(b)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+tt(f),value:ye(m)}),n.push({op:"remove",path:r+"/"+tt(f)}),l=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&o.length==s.length))for(var c=0;c<o.length;c++){var f=o[c];!Dr(t,f)&&e[f]!==void 0&&n.push({op:"add",path:r+"/"+tt(f),value:ye(e[f])})}}}function Jf(t,e,n){n===void 0&&(n=!1);var r=[];return fs(t,e,r,"",n),r}var zr=Object.assign({},us,hs,{JsonPatchError:jn,deepClone:ye,escapePathComponent:tt,unescapePathComponent:Bn});var ms=function(t,e){return ms=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[i]=r[i])},ms(t,e)};function nt(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");ms(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function ml(t,e,n,r){function i(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function a(f){try{c(r.next(f))}catch(m){s(m)}}function l(f){try{c(r.throw(f))}catch(m){s(m)}}function c(f){f.done?o(f.value):i(f.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function Br(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,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(f){return l([c,f])}}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,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,i=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){n.label=c[1];break}if(c[0]===6&&n.label<o[1]){n.label=o[1],o=c;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(c);break}o[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(f){c=[6,f],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ft(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 mn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(a){s={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function gn(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,o;r<i;r++)(o||!(r in e))&&(o||(o=Array.prototype.slice.call(e,0,r)),o[r]=e[r]);return t.concat(o||Array.prototype.slice.call(e))}function Vt(t){return this instanceof Vt?(this.v=t,this):new Vt(t)}function gl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,o=[];return i=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),i[Symbol.asyncIterator]=function(){return this},i;function s(h){return function(d){return Promise.resolve(d).then(h,m)}}function a(h,d){r[h]&&(i[h]=function(g){return new Promise(function(x,w){o.push([h,g,x,w])>1||l(h,g)})},d&&(i[h]=d(i[h])))}function l(h,d){try{c(r[h](d))}catch(g){b(o[0][3],g)}}function c(h){h.value instanceof Vt?Promise.resolve(h.value.v).then(f,m):b(o[0][2],h)}function f(h){l("next",h)}function m(h){l("throw",h)}function b(h,d){h(d),o.shift(),o.length&&l(o[0][0],o[0][1])}}function vl(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 ft=="function"?ft(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=t[o]&&function(s){return new Promise(function(a,l){s=t[o](s),i(a,l,s.done,s.value)})}}function i(o,s,a,l){Promise.resolve(l).then(function(c){o({value:c,done:a})},s)}}function z(t){return typeof t=="function"}function vn(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 jr=vn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
3
3
  `+n.map(function(r,i){return i+1+") "+r.toString()}).join(`
4
- `):"",this.name="UnsubscriptionError",this.errors=n}});function Vn(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,i,o;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(H(p))try{p()}catch(g){o=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{pl(h)}catch(g){o=o??[],g instanceof zr?o=mn(mn([],hn(o)),hn(g.errors)):o.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(i=x.return)&&i.call(x)}finally{if(r)throw r.error}}}if(o)throw new zr(o)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)pl(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)&&Vn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Vn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var ds=vn.EMPTY;function Br(t){return t instanceof vn||t&&"closed"in t&&H(t.remove)&&H(t.add)&&H(t.unsubscribe)}function pl(t){H(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 i=yn.delegate;return i?.setTimeout?i.setTimeout.apply(i,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 Vr(t){yn.setTimeout(function(){var e=Be.onUnhandledError;if(e)e(t);else throw t})}function jn(){}var fl=(function(){return ps("C",void 0,void 0)})();function hl(t){return ps("E",void 0,t)}function ml(t){return ps("N",t,void 0)}function ps(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,i=n.error;if(jt=null,r)throw i}}else t()}function gl(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=Kf,r}return e.create=function(n,r,i){return new Wr(n,r,i)},e.prototype.next=function(n){this.isStopped?hs(ml(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?hs(hl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?hs(fl,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 jf=Function.prototype.bind;function fs(t,e){return jf.call(t,e)}var Wf=(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){jr(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){jr(r)}else jr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){jr(n)}},t})(),Wr=(function(t){tt(e,t);function e(n,r,i){var o=t.call(this)||this,s;if(H(n)||!n)s={next:n??void 0,error:r??void 0,complete:i??void 0};else{var a;o&&Be.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return o.unsubscribe()},s={next:n.next&&fs(n.next,a),error:n.error&&fs(n.error,a),complete:n.complete&&fs(n.complete,a)}):s=n}return o.destination=new Wf(s),o}return e})(Wn);function jr(t){Be.useDeprecatedSynchronousErrorHandling?gl(t):Vr(t)}function Xf(t){throw t}function hs(t,e){var n=Be.onStoppedNotification;n&&yn.setTimeout(function(){return n(t,e)})}var Kf={closed:!0,next:jn,error:Xf,complete:jn};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 ms(t)}function ms(t){return t.length===0?En:t.length===1?t[0]:function(n){return t.reduce(function(r,i){return i(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 i=this,o=Yf(e)?e:new Wr(e,n,r);return bn(function(){var s=i,a=s.operator,l=s.source;o.add(a?a.call(o,l):l?i._subscribe(o):i._trySubscribe(o))}),o},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=vl(n),new n(function(i,o){var s=new Wr({next:function(a){try{e(a)}catch(l){o(l),s.unsubscribe()}},error:o,complete:i});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 ms(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=vl(e),new e(function(r,i){var o;n.subscribe(function(s){return o=s},function(s){return i(s)},function(){return r(o)})})},t.create=function(e){return new t(e)},t})();function vl(t){var e;return(e=t??Be.Promise)!==null&&e!==void 0?e:Promise}function Zf(t){return t&&H(t.next)&&H(t.error)&&H(t.complete)}function Yf(t){return t&&t instanceof Wn||Zf(t)&&Br(t)}function qf(t){return H(t?.lift)}function ue(t){return function(e){if(qf(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,i){return new Jf(t,e,n,r,i)}var Jf=(function(t){tt(e,t);function e(n,r,i,o,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=o?function(c){try{o(c)}catch(p){n.error(p)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=i?function(){try{i()}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 yl=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 bl(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new yl},e.prototype.next=function(n){var r=this;bn(function(){var i,o;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){i={error:c}}finally{try{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.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 i=r.observers;i.length;)i.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,i=this,o=i.hasError,s=i.isStopped,a=i.observers;return o||s?ds:(this.currentObservers=null,a.push(n),new vn(function(){r.currentObservers=null,Vn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,i=r.hasError,o=r.thrownError,s=r.isStopped;i?n.error(o):s&&n.complete()},e.prototype.asObservable=function(){var n=new J;return n.source=this,n},e.create=function(n,r){return new bl(n,r)},e})(J);var bl=(function(t){tt(e,t);function e(n,r){var i=t.call(this)||this;return i.destination=n,i.source=r,i}return e.prototype.next=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,n)},e.prototype.error=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.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,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&i!==void 0?i:ds},e})(nt);var gs={now:function(){return(gs.delegate||Date).now()},delegate:void 0};var Kr=(function(t){tt(e,t);function e(n,r,i){n===void 0&&(n=1/0),r===void 0&&(r=1/0),i===void 0&&(i=gs);var o=t.call(this)||this;return o._bufferSize=n,o._windowTime=r,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=r===1/0,o._bufferSize=Math.max(1,n),o._windowTime=Math.max(1,r),o}return e.prototype.next=function(n){var r=this,i=r.isStopped,o=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;i||(o.push(n),!s&&o.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),i=this,o=i._infiniteTimeWindow,s=i._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=o?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,i=n._timestampProvider,o=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<o.length&&o.splice(0,o.length-a),!s){for(var l=i.now(),c=0,p=1;p<o.length&&o[p]<=l;p+=2)c=p;c&&o.splice(0,c+1)}},e})(nt);var Zr=new J(function(t){return t.complete()});function xl(t){return t&&H(t.schedule)}function Qf(t){return t[t.length-1]}function El(t){return xl(Qf(t))?t.pop():void 0}var Yr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function qr(t){return H(t?.then)}function Jr(t){return H(t[xn])}function Qr(t){return Symbol.asyncIterator&&H(t?.[Symbol.asyncIterator])}function ei(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 eh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ti=eh();function ni(t){return H(t?.[ti])}function ri(t){return ul(this,arguments,function(){var n,r,i,o;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,Vt(n.read())];case 3:return r=s.sent(),i=r.value,o=r.done,o?[4,Vt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Vt(i)];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 ii(t){return H(t?.getReader)}function me(t){if(t instanceof J)return t;if(t!=null){if(Jr(t))return th(t);if(Yr(t))return nh(t);if(qr(t))return rh(t);if(Qr(t))return Tl(t);if(ni(t))return ih(t);if(ii(t))return oh(t)}throw ei(t)}function th(t){return new J(function(e){var n=t[xn]();if(H(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function nh(t){return new J(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function rh(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,Vr)})}function ih(t){return new J(function(e){var n,r;try{for(var i=pt(t),o=i.next();!o.done;o=i.next()){var s=o.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()})}function Tl(t){return new J(function(e){sh(t,e).catch(function(n){return e.error(n)})})}function oh(t){return Tl(ri(t))}function sh(t,e){var n,r,i,o;return cl(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=dl(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(),i={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(o=n.return)?[4,o.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function Ue(t,e,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var o=e.schedule(function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(o),!i)return o}function oi(t,e){return e===void 0&&(e=0),ue(function(n,r){n.subscribe(he(r,function(i){return Ue(r,t,function(){return r.next(i)},e)},function(){return Ue(r,t,function(){return r.complete()},e)},function(i){return Ue(r,t,function(){return r.error(i)},e)}))})}function si(t,e){return e===void 0&&(e=0),ue(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Sl(t,e){return me(t).pipe(si(e),oi(e))}function _l(t,e){return me(t).pipe(si(e),oi(e))}function wl(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 Al(t,e){return new J(function(n){var r;return Ue(n,e,function(){r=t[ti](),Ue(n,e,function(){var i,o,s;try{i=r.next(),o=i.value,s=i.done}catch(a){n.error(a);return}s?n.complete():n.next(o)},0,!0)}),function(){return H(r?.return)&&r.return()}})}function ai(t,e){if(!t)throw new Error("Iterable cannot be null");return new J(function(n){Ue(n,e,function(){var r=t[Symbol.asyncIterator]();Ue(n,e,function(){r.next().then(function(i){i.done?n.complete():n.next(i.value)})},0,!0)})})}function kl(t,e){return ai(ri(t),e)}function Il(t,e){if(t!=null){if(Jr(t))return Sl(t,e);if(Yr(t))return wl(t,e);if(qr(t))return _l(t,e);if(Qr(t))return ai(t,e);if(ni(t))return Al(t,e);if(ii(t))return kl(t,e)}throw ei(t)}function Wt(t,e){return e?Il(t,e):me(t)}function te(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=El(t);return Wt(t,n)}function Q(t,e){var n=H(t)?t:function(){return t},r=function(i){return i.error(n())};return new J(e?function(i){return e.schedule(r,0,i)}:r)}var Cl=gn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function li(t,e){var n=typeof e=="object";return new Promise(function(r,i){var o=!1,s;t.subscribe({next:function(a){s=a,o=!0},error:i,complete:function(){o?r(s):n?r(e.defaultValue):i(new Cl)}})})}function Xt(t,e){return ue(function(n,r){var i=0;n.subscribe(he(r,function(o){r.next(t.call(e,o,i++))}))})}function Nl(t,e,n,r,i,o,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){o&&e.next(g),c++;var T=!1;me(n(g,p++)).subscribe(he(e,function(_){i?.(_),o?f(_):e.next(_)},function(){T=!0},void 0,function(){if(T)try{c--;for(var _=function(){var b=l.shift();s?Ue(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 Ie(t,e,n){return n===void 0&&(n=1/0),H(e)?Ie(function(r,i){return Xt(function(o,s){return e(r,o,i,s)})(me(t(r,i)))},n):(typeof e=="number"&&(n=e),ue(function(r,i){return Nl(r,i,t,n)}))}function vs(t){return t===void 0&&(t=1/0),Ie(En,t)}function ci(t){return new J(function(e){me(t()).subscribe(e)})}function Xn(t){return ue(function(e,n){var r=null,i=!1,o;r=e.subscribe(he(n,void 0,void 0,function(s){o=me(t(s,Xn(t)(e))),r?(r.unsubscribe(),r=null,o.subscribe(n)):i=!0})),i&&(r.unsubscribe(),r=null,o.subscribe(n))})}function ui(t,e){return H(e)?Ie(t,e,1):Ie(t,1)}function ys(t){return ue(function(e,n){var r=!1;e.subscribe(he(n,function(i){r=!0,n.next(i)},function(){r||n.next(t),n.complete()}))})}function Kt(t){return ue(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function bs(t,e){return ue(function(n,r){var i=null,o=0,s=!1,a=function(){return s&&!i&&r.complete()};n.subscribe(he(r,function(l){i?.unsubscribe();var c=0,p=o++;me(t(l,p)).subscribe(i=he(r,function(m){return r.next(e?e(l,m,p,c++):m)},function(){i=null,a()}))},function(){s=!0,a()}))})}function di(t){return ue(function(e,n){me(t).subscribe(he(n,function(){return n.complete()},jn)),!n.closed&&e.subscribe(n)})}function xs(t,e,n){var r=H(t)||e||n?{next:t,error:e,complete:n}:t;return r?ue(function(i,o){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;i.subscribe(he(o,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),o.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),o.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),o.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 Rl(t){return` \r
5
- `.indexOf(t)>=0}function pi(t){for(var e=["topLevel"],n=0,r,i,o,s=function(b){return e.push(b)},a=function(b){return e[e.length-1]=b},l=function(b){r==null&&(r=n,i=e.length,o=b)},c=function(b){b===o&&(r=void 0,i=void 0,o=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():Rl(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":Rl(h)||(c("collectionItem"),a("objectNeedsComma"),x(h));break;case"objectNeedsComma":h==="}"?p():h===","&&(l("collectionItem"),a("objectNeedsKey"));break}}i!=null&&(e.length=i);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 Ml(){let t=0,e=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,(i&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 i=this.buf[this.pos++];if(e|=(i&127)<<r,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function hi(t,e,n){for(let o=0;o<28;o=o+7){let s=t>>>o,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,i=e>>3!=0;if(n.push((i?r|128:r)&255),!!i){for(let o=3;o<31;o=o+7){let s=e>>>o,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var fi=4294967296;function Es(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,i=0;function o(s,a){let l=Number(t.slice(s,a));i*=n,r=r*n+l,r>=fi&&(i=i+(r/fi|0),r=r%fi)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?Pl(r,i):Ss(r,i)}function Ll(t,e){let n=Ss(t,e),r=n.hi&2147483648;r&&(n=Pl(n.lo,n.hi));let i=Ts(n.lo,n.hi);return r?"-"+i:i}function Ts(t,e){if({lo:t,hi:e}=ah(t,e),e<=2097151)return String(fi*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,i=e>>16&65535,o=n+r*6777216+i*6710656,s=r+i*8147497,a=i*2,l=1e7;return o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Ol(s)+Ol(o)}function ah(t,e){return{lo:t>>>0,hi:e>>>0}}function Ss(t,e){return{lo:t|0,hi:e|0}}function Pl(t,e){return e=~e,t?t=~t+1:e+=1,Ss(t,e)}var Ol=t=>{let e=String(t);return"0000000".slice(e.length)+e};function _s(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 Dl(){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 Ve=lh();function lh(){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"),i=BigInt("0"),o=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>o||a<i)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()),Ul(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),Hl(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Ul(n),Es(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),Hl(n),Es(n)},dec(n,r){return Ll(n,r)},uDec(n,r){return Ts(n,r)}}}function Ul(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function Hl(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var ws=Symbol.for("@bufbuild/protobuf/text-encoding");function As(){if(globalThis[ws]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[ws]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,i){return i?(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[ws]}var Tt;(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"})(Tt||(Tt={}));var ch=34028234663852886e22,uh=-34028234663852886e22,dh=4294967295,ph=2147483647,fh=-2147483648,P=class{constructor(e=As().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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let n=new Uint8Array(e),r=0;for(let i=0;i<this.chunks.length;i++)n.set(this.chunks[i],r),r+=this.chunks[i].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(Gl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return ks(e),_s(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){hh(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){Gl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){ks(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return ks(e),e=(e<<1^e>>31)>>>0,_s(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=Ve.enc(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=Ve.uEnc(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}int64(e){let n=Ve.enc(e);return hi(n.lo,n.hi,this.buf),this}sint64(e){let n=Ve.enc(e),r=n.hi>>31,i=n.lo<<1^r,o=(n.hi<<1|n.lo>>>31)^r;return hi(i,o,this.buf),this}uint64(e){let n=Ve.uEnc(e);return hi(n.lo,n.hi,this.buf),this}},S=class{constructor(e,n=As().decodeUtf8){this.decodeUtf8=n,this.varint64=Ml,this.uint32=Dl,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 i=n>>>3,o=n&7;if(i<=0||o>5)throw new Error("illegal tag: field no "+i+" wire type "+o);return[i,o]}skip(e,n){let r=this.pos;switch(e){case Tt.Varint:for(;this.buf[this.pos++]&128;);break;case Tt.Bit64:this.pos+=4;case Tt.Bit32:this.pos+=4;break;case Tt.LengthDelimited:let i=this.uint32();this.pos+=i;break;case Tt.StartGroup:for(;;){let[o,s]=this.tag();if(s===Tt.EndGroup){if(n!==void 0&&o!==n)throw new Error("invalid end group tag");break}this.skip(s,o)}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 Ve.dec(...this.varint64())}uint64(){return Ve.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,Ve.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 Ve.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ve.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 ks(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>ph||t<fh)throw new Error("invalid int32: "+t)}function Gl(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>dh||t<0)throw new Error("invalid uint32: "+t)}function hh(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>ch||t<uh))throw new Error("invalid float32: "+t)}var mh=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Is(){return{fields:{}}}var Kn={encode(t,e=new P){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Rs.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,i=Is();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:{if(o!==10)break;let s=Rs.decode(n,n.uint32());s.value!==void 0&&(i.fields[s.key]=s.value);continue}}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Kn.fromPartial(t??{})},fromPartial(t){let e=Is();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,i])=>(i!==void 0&&(n[r]=i),n),{}),e},wrap(t){let e=Is();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 Fl(){return{key:"",value:void 0}}var Rs={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,i=Fl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.key=n.string();continue;case 2:if(o!==18)break;i.value=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Rs.fromPartial(t??{})},fromPartial(t){let e=Fl();return e.key=t.key??"",e.value=t.value??void 0,e}};function Cs(){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&&Kn.encode(Kn.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&Zn.encode(Zn.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,i=Cs();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.nullValue=n.int32();continue;case 2:if(o!==17)break;i.numberValue=n.double();continue;case 3:if(o!==26)break;i.stringValue=n.string();continue;case 4:if(o!==32)break;i.boolValue=n.bool();continue;case 5:if(o!==42)break;i.structValue=Kn.unwrap(Kn.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.listValue=Zn.unwrap(Zn.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return N.fromPartial(t??{})},fromPartial(t){let e=Cs();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=Cs();if(t===null)e.nullValue=mh.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 Ns(){return{values:[]}}var Zn={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,i=Ns();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.values.push(N.unwrap(N.decode(n,n.uint32())));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Zn.fromPartial(t??{})},fromPartial(t){let e=Ns();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=Ns();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},gh=(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 $l(){return{op:0,path:"",from:void 0,value:void 0}}var gi={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,i=$l();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.op=n.int32();continue;case 2:if(o!==18)break;i.path=n.string();continue;case 3:if(o!==26)break;i.from=n.string();continue;case 4:if(o!==34)break;i.value=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return gi.fromPartial(t??{})},fromPartial(t){let e=$l();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function zl(){return{id:"",type:"",function:void 0}}var vi={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&&yi.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,i=zl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.type=n.string();continue;case 3:if(o!==26)break;i.function=yi.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return vi.fromPartial(t??{})},fromPartial(t){let e=zl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?yi.fromPartial(t.function):void 0,e}};function Bl(){return{name:"",arguments:""}}var yi={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,i=Bl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.name=n.string();continue;case 2:if(o!==18)break;i.arguments=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return yi.fromPartial(t??{})},fromPartial(t){let e=Bl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Vl(){return{value:"",mimeType:""}}var bi={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,i=Vl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.value=n.string();continue;case 2:if(o!==18)break;i.mimeType=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return bi.fromPartial(t??{})},fromPartial(t){let e=Vl();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function jl(){return{value:"",mimeType:void 0}}var xi={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,i=jl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.value=n.string();continue;case 2:if(o!==18)break;i.mimeType=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return xi.fromPartial(t??{})},fromPartial(t){let e=jl();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Wl(){return{data:void 0,url:void 0}}var Ne={encode(t,e=new P){return t.data!==void 0&&bi.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&xi.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,i=Wl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.data=bi.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.url=xi.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ne.fromPartial(t??{})},fromPartial(t){let e=Wl();return e.data=t.data!==void 0&&t.data!==null?bi.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?xi.fromPartial(t.url):void 0,e}};function Xl(){return{text:""}}var Ei={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,i=Xl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.text=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ei.fromPartial(t??{})},fromPartial(t){let e=Xl();return e.text=t.text??"",e}};function Kl(){return{source:void 0,metadata:void 0}}var Ti={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,i=Kl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Ne.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ti.fromPartial(t??{})},fromPartial(t){let e=Kl();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{source:void 0,metadata:void 0}}var Si={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,i=Zl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Ne.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Si.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Yl(){return{source:void 0,metadata:void 0}}var _i={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,i=Yl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Ne.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return _i.fromPartial(t??{})},fromPartial(t){let e=Yl();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function ql(){return{source:void 0,metadata:void 0}}var wi={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,i=ql();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Ne.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return wi.fromPartial(t??{})},fromPartial(t){let e=ql();return e.source=t.source!==void 0&&t.source!==null?Ne.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Jl(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Ai={encode(t,e=new P){return t.text!==void 0&&Ei.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Ti.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Si.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&_i.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&wi.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,i=Jl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.text=Ei.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.image=Ti.decode(n,n.uint32());continue;case 3:if(o!==26)break;i.audio=Si.decode(n,n.uint32());continue;case 4:if(o!==34)break;i.video=_i.decode(n,n.uint32());continue;case 5:if(o!==42)break;i.document=wi.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ai.fromPartial(t??{})},fromPartial(t){let e=Jl();return e.text=t.text!==void 0&&t.text!==null?Ei.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Ti.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Si.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?_i.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?wi.fromPartial(t.document):void 0,e}};function Ql(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var ki={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)vi.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)Ai.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,i=Ql();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.role=n.string();continue;case 3:if(o!==26)break;i.content=n.string();continue;case 4:if(o!==34)break;i.name=n.string();continue;case 5:if(o!==42)break;i.toolCalls.push(vi.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.toolCallId=n.string();continue;case 7:if(o!==58)break;i.error=n.string();continue;case 8:if(o!==66)break;i.contentParts.push(Ai.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return ki.fromPartial(t??{})},fromPartial(t){let e=Ql();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=>vi.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Ai.fromPartial(n))||[],e}};function ec(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Ii={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,i=ec();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.reason=n.string();continue;case 3:if(o!==26)break;i.message=n.string();continue;case 4:if(o!==34)break;i.toolCallId=n.string();continue;case 5:if(o!==42)break;i.responseSchema=N.unwrap(N.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.expiresAt=n.string();continue;case 7:if(o!==58)break;i.metadata=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ii.fromPartial(t??{})},fromPartial(t){let e=ec();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}},vh=(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 tc(){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,i=tc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.type=n.int32();continue;case 2:if(o!==16)break;i.timestamp=yh(n.int64());continue;case 3:if(o!==26)break;i.rawEvent=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=tc();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function nc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Ci={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,i=nc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.role=n.string();continue;case 4:if(o!==34)break;i.name=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ci.fromPartial(t??{})},fromPartial(t){let e=nc();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 rc(){return{baseEvent:void 0,messageId:"",delta:""}}var Ni={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,i=rc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ni.fromPartial(t??{})},fromPartial(t){let e=rc();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 ic(){return{baseEvent:void 0,messageId:""}}var Ri={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,i=ic();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ri.fromPartial(t??{})},fromPartial(t){let e=ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function oc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Oi={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,i=oc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.toolCallName=n.string();continue;case 4:if(o!==34)break;i.parentMessageId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Oi.fromPartial(t??{})},fromPartial(t){let e=oc();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 sc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Mi={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,i=sc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Mi.fromPartial(t??{})},fromPartial(t){let e=sc();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 ac(){return{baseEvent:void 0,toolCallId:""}}var Li={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,i=ac();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Li.fromPartial(t??{})},fromPartial(t){let e=ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function lc(){return{baseEvent:void 0,snapshot:void 0}}var Pi={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,i=lc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.snapshot=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Pi.fromPartial(t??{})},fromPartial(t){let e=lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function cc(){return{baseEvent:void 0,delta:[]}}var Di={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)gi.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,i=cc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.delta.push(gi.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Di.fromPartial(t??{})},fromPartial(t){let e=cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>gi.fromPartial(n))||[],e}};function uc(){return{baseEvent:void 0,messages:[]}}var Ui={encode(t,e=new P){t.baseEvent!==void 0&&R.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)ki.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,i=uc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messages.push(ki.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ui.fromPartial(t??{})},fromPartial(t){let e=uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>ki.fromPartial(n))||[],e}};function dc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Hi={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,i=dc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.event=N.unwrap(N.decode(n,n.uint32()));continue;case 3:if(o!==26)break;i.source=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Hi.fromPartial(t??{})},fromPartial(t){let e=dc();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 pc(){return{baseEvent:void 0,name:"",value:void 0}}var Gi={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,i=pc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.name=n.string();continue;case 3:if(o!==26)break;i.value=N.unwrap(N.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Gi.fromPartial(t??{})},fromPartial(t){let e=pc();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 fc(){return{baseEvent:void 0,threadId:"",runId:""}}var Fi={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,i=fc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.threadId=n.string();continue;case 3:if(o!==26)break;i.runId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Fi.fromPartial(t??{})},fromPartial(t){let e=fc();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 hc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var $i={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)Ii.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,i=hc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.threadId=n.string();continue;case 3:if(o!==26)break;i.runId=n.string();continue;case 4:if(o!==34)break;i.result=N.unwrap(N.decode(n,n.uint32()));continue;case 5:if(o!==42)break;i.outcome=n.string();continue;case 6:if(o!==50)break;i.interrupts.push(Ii.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return $i.fromPartial(t??{})},fromPartial(t){let e=hc();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=>Ii.fromPartial(n))||[],e}};function mc(){return{baseEvent:void 0,code:void 0,message:""}}var zi={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,i=mc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.code=n.string();continue;case 3:if(o!==26)break;i.message=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return zi.fromPartial(t??{})},fromPartial(t){let e=mc();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 gc(){return{baseEvent:void 0,stepName:""}}var Bi={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,i=gc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.stepName=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Bi.fromPartial(t??{})},fromPartial(t){let e=gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function vc(){return{baseEvent:void 0,stepName:""}}var Vi={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,i=vc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.stepName=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Vi.fromPartial(t??{})},fromPartial(t){let e=vc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?R.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function yc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var ji={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,i=yc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.role=n.string();continue;case 4:if(o!==34)break;i.delta=n.string();continue;case 5:if(o!==42)break;i.name=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return ji.fromPartial(t??{})},fromPartial(t){let e=yc();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 bc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Wi={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,i=bc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=R.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.toolCallName=n.string();continue;case 4:if(o!==34)break;i.parentMessageId=n.string();continue;case 5:if(o!==42)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Wi.fromPartial(t??{})},fromPartial(t){let e=bc();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 xc(){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 Ec={encode(t,e=new P){return t.textMessageStart!==void 0&&Ci.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Ni.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Ri.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Oi.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Mi.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Li.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Pi.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Di.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Ui.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Hi.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Gi.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&Fi.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&$i.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&zi.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Bi.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&Vi.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&ji.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&Wi.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,i=xc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.textMessageStart=Ci.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.textMessageContent=Ni.decode(n,n.uint32());continue;case 3:if(o!==26)break;i.textMessageEnd=Ri.decode(n,n.uint32());continue;case 4:if(o!==34)break;i.toolCallStart=Oi.decode(n,n.uint32());continue;case 5:if(o!==42)break;i.toolCallArgs=Mi.decode(n,n.uint32());continue;case 6:if(o!==50)break;i.toolCallEnd=Li.decode(n,n.uint32());continue;case 7:if(o!==58)break;i.stateSnapshot=Pi.decode(n,n.uint32());continue;case 8:if(o!==66)break;i.stateDelta=Di.decode(n,n.uint32());continue;case 9:if(o!==74)break;i.messagesSnapshot=Ui.decode(n,n.uint32());continue;case 10:if(o!==82)break;i.raw=Hi.decode(n,n.uint32());continue;case 11:if(o!==90)break;i.custom=Gi.decode(n,n.uint32());continue;case 12:if(o!==98)break;i.runStarted=Fi.decode(n,n.uint32());continue;case 13:if(o!==106)break;i.runFinished=$i.decode(n,n.uint32());continue;case 14:if(o!==114)break;i.runError=zi.decode(n,n.uint32());continue;case 15:if(o!==122)break;i.stepStarted=Bi.decode(n,n.uint32());continue;case 16:if(o!==130)break;i.stepFinished=Vi.decode(n,n.uint32());continue;case 17:if(o!==138)break;i.textMessageChunk=ji.decode(n,n.uint32());continue;case 18:if(o!==146)break;i.toolCallChunk=Wi.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ec.fromPartial(t??{})},fromPartial(t){let e=xc();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Ci.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Ni.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Ri.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Oi.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Mi.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Li.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Pi.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Di.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Ui.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Hi.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Gi.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?Fi.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?$i.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?zi.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Bi.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?Vi.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?ji.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?Wi.fromPartial(t.toolCallChunk):void 0,e}};function yh(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 mi=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}}},bh=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:mi(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:mi(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:mi(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:mi(t.document.source),metadata:t.document.metadata}}};function Tc(t){let e=Ec.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=vh[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 i=r;if(i.role==="user"&&Array.isArray(i.contentParts)){let o=i.contentParts.map(s=>bh(s)).filter(s=>s!==void 0);o.length>0&&(i.content=o)}Array.isArray(i.contentParts)&&i.contentParts.length===0&&(i.contentParts=void 0),i.toolCalls?.length===0&&(i.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,i=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,o=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,i==="interrupt"?r.outcome={type:"interrupt",interrupts:o}:i==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=gh[r.op].toLowerCase(),Object.keys(r).forEach(i=>{r[i]===void 0&&delete r[i]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Or.parse(n)}var Os="application/vnd.ag-ui.event+proto";var Eh=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ms=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(Eh);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Sc=t=>t==="*"||t==="x"||t==="X",_c=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},Th=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Sh=(t,e)=>{if(Sc(t)||Sc(e))return 0;let[n,r]=Th(_c(t),_c(e));return n>r?1:n<r?-1:0},Ls=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=Sh(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Yn=(t,e)=>{let n=Ms(t),r=Ms(e),i=n.pop(),o=r.pop(),s=Ls(n,r);return s!==0?s:i&&o?Ls(i.split("."),o.split(".")):i||o?i?-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 vt()}function Us(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Us(e);return t}async function W(t,e,n,r){let i=typeof process<"u"&&process.env!==void 0,o=i&&!!process.env.VITEST_WORKER_ID,s=i&&!!process.env.VITEST_WORKER_ID,a=z(e),l=z(n),c=a,p=l,m;for(let x of t)try{s&&(Us(c),Us(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(o)throw f;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",f)}else o||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 Xi(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 Hs)return t;if(t===!0)return new Hs(Xi(!0))}var Hs=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 Ps(t){return t.enabled?new Hs(t):void 0}function _h(t,e,n){if(e){let i=t.find(s=>s.id===e);if(i?.role==="assistant")return i;i&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${i.role}' message, not assistant \u2014 falling back to toolCallId`);let o={id:i?n:e,role:"assistant",toolCalls:[]};return t.push(o),o}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Nc=(t,e,n,r,i)=>{let o=qn(i),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):Zr};return e.pipe(ui(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?o?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):o?.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,G)=>_.onTextMessageContentEvent?.({event:m,messages:b,state:G,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,_=_h(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(G=>G.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,G,X)=>{let ae=T.function.arguments,ee=T.function.name,ht={};try{ht=pi(ae)}catch{}return b.onToolCallArgsEvent?.({event:m,messages:G,state:X,agent:n,input:t,toolCallBuffer:ae,toolCallName:ee,partialToolCallArgs:ht})});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 G=g.function.arguments,X=g.function.name,ae={};try{ae=JSON.parse(G)}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(G=>{G.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:
4
+ `):"",this.name="UnsubscriptionError",this.errors=n}});function Wn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var bn=(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,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=ft(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 f=this.initialTeardown;if(z(f))try{f()}catch(g){o=g instanceof jr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var b=ft(m),h=b.next();!h.done;h=b.next()){var d=h.value;try{bl(d)}catch(g){o=o??[],g instanceof jr?o=gn(gn([],mn(o)),mn(g.errors)):o.push(g)}}}catch(g){r={error:g}}finally{try{h&&!h.done&&(i=b.return)&&i.call(b)}finally{if(r)throw r.error}}}if(o)throw new jr(o)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)bl(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)&&Wn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Wn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var gs=bn.EMPTY;function Vr(t){return t instanceof bn||t&&"closed"in t&&z(t.remove)&&z(t.add)&&z(t.unsubscribe)}function bl(t){z(t)?t():t.unsubscribe()}var je={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 i=yn.delegate;return i?.setTimeout?i.setTimeout.apply(i,gn([t,e],mn(n))):setTimeout.apply(void 0,gn([t,e],mn(n)))},clearTimeout:function(t){var e=yn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function Wr(t){yn.setTimeout(function(){var e=je.onUnhandledError;if(e)e(t);else throw t})}function qn(){}var yl=(function(){return vs("C",void 0,void 0)})();function xl(t){return vs("E",void 0,t)}function El(t){return vs("N",t,void 0)}function vs(t,e,n){return{kind:t,value:e,error:n}}var Wt=null;function xn(t){if(je.useDeprecatedSynchronousErrorHandling){var e=!Wt;if(e&&(Wt={errorThrown:!1,error:null}),t(),e){var n=Wt,r=n.errorThrown,i=n.error;if(Wt=null,r)throw i}}else t()}function Tl(t){je.useDeprecatedSynchronousErrorHandling&&Wt&&(Wt.errorThrown=!0,Wt.error=t)}var Xn=(function(t){nt(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Vr(n)&&n.add(r)):r.destination=nh,r}return e.create=function(n,r,i){return new Xr(n,r,i)},e.prototype.next=function(n){this.isStopped?ys(El(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?ys(xl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?ys(yl,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})(bn);var Qf=Function.prototype.bind;function bs(t,e){return Qf.call(t,e)}var eh=(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){qr(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){qr(r)}else qr(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){qr(n)}},t})(),Xr=(function(t){nt(e,t);function e(n,r,i){var o=t.call(this)||this,s;if(z(n)||!n)s={next:n??void 0,error:r??void 0,complete:i??void 0};else{var a;o&&je.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return o.unsubscribe()},s={next:n.next&&bs(n.next,a),error:n.error&&bs(n.error,a),complete:n.complete&&bs(n.complete,a)}):s=n}return o.destination=new eh(s),o}return e})(Xn);function qr(t){je.useDeprecatedSynchronousErrorHandling?Tl(t):Wr(t)}function th(t){throw t}function ys(t,e){var n=je.onStoppedNotification;n&&yn.setTimeout(function(){return n(t,e)})}var nh={closed:!0,next:qn,error:th,complete:qn};var En=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Tn(t){return t}function Kr(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return xs(t)}function xs(t){return t.length===0?Tn:t.length===1?t[0]:function(n){return t.reduce(function(r,i){return i(r)},n)}}var ee=(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 i=this,o=ih(e)?e:new Xr(e,n,r);return xn(function(){var s=i,a=s.operator,l=s.source;o.add(a?a.call(o,l):l?i._subscribe(o):i._trySubscribe(o))}),o},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=wl(n),new n(function(i,o){var s=new Xr({next:function(a){try{e(a)}catch(l){o(l),s.unsubscribe()}},error:o,complete:i});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[En]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return xs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=wl(e),new e(function(r,i){var o;n.subscribe(function(s){return o=s},function(s){return i(s)},function(){return r(o)})})},t.create=function(e){return new t(e)},t})();function wl(t){var e;return(e=t??je.Promise)!==null&&e!==void 0?e:Promise}function rh(t){return t&&z(t.next)&&z(t.error)&&z(t.complete)}function ih(t){return t&&t instanceof Xn||rh(t)&&Vr(t)}function oh(t){return z(t?.lift)}function de(t){return function(e){if(oh(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 me(t,e,n,r,i){return new sh(t,e,n,r,i)}var sh=(function(t){nt(e,t);function e(n,r,i,o,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(f){n.error(f)}}:t.prototype._next,l._error=o?function(c){try{o(c)}catch(f){n.error(f)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=i?function(){try{i()}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})(Xn);var Sl=vn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var rt=(function(t){nt(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 _l(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;xn(function(){var i,o;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=ft(r.currentObservers),a=s.next();!a.done;a=s.next()){var l=a.value;l.next(n)}}catch(c){i={error:c}}finally{try{a&&!a.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}}})},e.prototype.error=function(n){var r=this;xn(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var i=r.observers;i.length;)i.shift().error(n)}})},e.prototype.complete=function(){var n=this;xn(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,i=this,o=i.hasError,s=i.isStopped,a=i.observers;return o||s?gs:(this.currentObservers=null,a.push(n),new bn(function(){r.currentObservers=null,Wn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,i=r.hasError,o=r.thrownError,s=r.isStopped;i?n.error(o):s&&n.complete()},e.prototype.asObservable=function(){var n=new ee;return n.source=this,n},e.create=function(n,r){return new _l(n,r)},e})(ee);var _l=(function(t){nt(e,t);function e(n,r){var i=t.call(this)||this;return i.destination=n,i.source=r,i}return e.prototype.next=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.next)===null||i===void 0||i.call(r,n)},e.prototype.error=function(n){var r,i;(i=(r=this.destination)===null||r===void 0?void 0:r.error)===null||i===void 0||i.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,i;return(i=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&i!==void 0?i:gs},e})(rt);var Es={now:function(){return(Es.delegate||Date).now()},delegate:void 0};var Zr=(function(t){nt(e,t);function e(n,r,i){n===void 0&&(n=1/0),r===void 0&&(r=1/0),i===void 0&&(i=Es);var o=t.call(this)||this;return o._bufferSize=n,o._windowTime=r,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=r===1/0,o._bufferSize=Math.max(1,n),o._windowTime=Math.max(1,r),o}return e.prototype.next=function(n){var r=this,i=r.isStopped,o=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;i||(o.push(n),!s&&o.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),i=this,o=i._infiniteTimeWindow,s=i._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=o?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,i=n._timestampProvider,o=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<o.length&&o.splice(0,o.length-a),!s){for(var l=i.now(),c=0,f=1;f<o.length&&o[f]<=l;f+=2)c=f;c&&o.splice(0,c+1)}},e})(rt);var Yr=new ee(function(t){return t.complete()});function Al(t){return t&&z(t.schedule)}function ah(t){return t[t.length-1]}function kl(t){return Al(ah(t))?t.pop():void 0}var Jr=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function Qr(t){return z(t?.then)}function ei(t){return z(t[En])}function ti(t){return Symbol.asyncIterator&&z(t?.[Symbol.asyncIterator])}function ni(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 lh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var ri=lh();function ii(t){return z(t?.[ri])}function oi(t){return gl(this,arguments,function(){var n,r,i,o;return Br(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,Vt(n.read())];case 3:return r=s.sent(),i=r.value,o=r.done,o?[4,Vt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Vt(i)];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 si(t){return z(t?.getReader)}function ge(t){if(t instanceof ee)return t;if(t!=null){if(ei(t))return ch(t);if(Jr(t))return uh(t);if(Qr(t))return dh(t);if(ti(t))return Il(t);if(ii(t))return ph(t);if(si(t))return fh(t)}throw ni(t)}function ch(t){return new ee(function(e){var n=t[En]();if(z(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function uh(t){return new ee(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function dh(t){return new ee(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Wr)})}function ph(t){return new ee(function(e){var n,r;try{for(var i=ft(t),o=i.next();!o.done;o=i.next()){var s=o.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()})}function Il(t){return new ee(function(e){hh(t,e).catch(function(n){return e.error(n)})})}function fh(t){return Il(oi(t))}function hh(t,e){var n,r,i,o;return ml(this,void 0,void 0,function(){var s,a;return Br(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=vl(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(),i={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(o=n.return)?[4,o.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function He(t,e,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var o=e.schedule(function(){n(),i?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(o),!i)return o}function ai(t,e){return e===void 0&&(e=0),de(function(n,r){n.subscribe(me(r,function(i){return He(r,t,function(){return r.next(i)},e)},function(){return He(r,t,function(){return r.complete()},e)},function(i){return He(r,t,function(){return r.error(i)},e)}))})}function li(t,e){return e===void 0&&(e=0),de(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Cl(t,e){return ge(t).pipe(li(e),ai(e))}function Nl(t,e){return ge(t).pipe(li(e),ai(e))}function Rl(t,e){return new ee(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Ol(t,e){return new ee(function(n){var r;return He(n,e,function(){r=t[ri](),He(n,e,function(){var i,o,s;try{i=r.next(),o=i.value,s=i.done}catch(a){n.error(a);return}s?n.complete():n.next(o)},0,!0)}),function(){return z(r?.return)&&r.return()}})}function ci(t,e){if(!t)throw new Error("Iterable cannot be null");return new ee(function(n){He(n,e,function(){var r=t[Symbol.asyncIterator]();He(n,e,function(){r.next().then(function(i){i.done?n.complete():n.next(i.value)})},0,!0)})})}function Ml(t,e){return ci(oi(t),e)}function Ll(t,e){if(t!=null){if(ei(t))return Cl(t,e);if(Jr(t))return Rl(t,e);if(Qr(t))return Nl(t,e);if(ti(t))return ci(t,e);if(ii(t))return Ol(t,e);if(si(t))return Ml(t,e)}throw ni(t)}function qt(t,e){return e?Ll(t,e):ge(t)}function re(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=kl(t);return qt(t,n)}function te(t,e){var n=z(t)?t:function(){return t},r=function(i){return i.error(n())};return new ee(e?function(i){return e.schedule(r,0,i)}:r)}var Pl=vn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function ui(t,e){var n=typeof e=="object";return new Promise(function(r,i){var o=!1,s;t.subscribe({next:function(a){s=a,o=!0},error:i,complete:function(){o?r(s):n?r(e.defaultValue):i(new Pl)}})})}function Xt(t,e){return de(function(n,r){var i=0;n.subscribe(me(r,function(o){r.next(t.call(e,o,i++))}))})}function Dl(t,e,n,r,i,o,s,a){var l=[],c=0,f=0,m=!1,b=function(){m&&!l.length&&!c&&e.complete()},h=function(g){return c<r?d(g):l.push(g)},d=function(g){o&&e.next(g),c++;var x=!1;ge(n(g,f++)).subscribe(me(e,function(w){i?.(w),o?h(w):e.next(w)},function(){x=!0},void 0,function(){if(x)try{c--;for(var w=function(){var E=l.shift();s?He(e,s,function(){return d(E)}):d(E)};l.length&&c<r;)w();b()}catch(E){e.error(E)}}))};return t.subscribe(me(e,h,function(){m=!0,b()})),function(){a?.()}}function Ce(t,e,n){return n===void 0&&(n=1/0),z(e)?Ce(function(r,i){return Xt(function(o,s){return e(r,o,i,s)})(ge(t(r,i)))},n):(typeof e=="number"&&(n=e),de(function(r,i){return Dl(r,i,t,n)}))}function Ts(t){return t===void 0&&(t=1/0),Ce(Tn,t)}function di(t){return new ee(function(e){ge(t()).subscribe(e)})}function Kn(t){return de(function(e,n){var r=null,i=!1,o;r=e.subscribe(me(n,void 0,void 0,function(s){o=ge(t(s,Kn(t)(e))),r?(r.unsubscribe(),r=null,o.subscribe(n)):i=!0})),i&&(r.unsubscribe(),r=null,o.subscribe(n))})}function pi(t,e){return z(e)?Ce(t,e,1):Ce(t,1)}function ws(t){return de(function(e,n){var r=!1;e.subscribe(me(n,function(i){r=!0,n.next(i)},function(){r||n.next(t),n.complete()}))})}function Kt(t){return de(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function Ss(t,e){return de(function(n,r){var i=null,o=0,s=!1,a=function(){return s&&!i&&r.complete()};n.subscribe(me(r,function(l){i?.unsubscribe();var c=0,f=o++;ge(t(l,f)).subscribe(i=me(r,function(m){return r.next(e?e(l,m,f,c++):m)},function(){i=null,a()}))},function(){s=!0,a()}))})}function fi(t){return de(function(e,n){ge(t).subscribe(me(n,function(){return n.complete()},qn)),!n.closed&&e.subscribe(n)})}function _s(t,e,n){var r=z(t)||e||n?{next:t,error:e,complete:n}:t;return r?de(function(i,o){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;i.subscribe(me(o,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),o.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),o.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),o.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)}))}):Tn}function Ul(t){return` \r
5
+ `.indexOf(t)>=0}function hi(t){for(var e=["topLevel"],n=0,r,i,o,s=function(E){return e.push(E)},a=function(E){return e[e.length-1]=E},l=function(E){r==null&&(r=n,i=e.length,o=E)},c=function(E){E===o&&(r=void 0,i=void 0,o=void 0)},f=function(){return e.pop()},m=function(){return n--},b=function(E){if("0"<=E&&E<="9"){s("number");return}switch(E){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}},h=t.length;n<h;n++){var d=t[n];switch(e[e.length-1]){case"topLevel":b(d);break;case"string":switch(d){case'"':f();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":d==="u"?s("stringUnicode"):(c("stringEscape"),f());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),f());break;case"number":d==="."?a("numberNeedsDigit"):d==="e"||d==="E"?a("numberNeedsExponent"):(d<"0"||d>"9")&&(m(),f());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(d==="+"||d==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(d<"a"||d>"z")&&(m(),f());break;case"arrayNeedsValue":d==="]"?f():Ul(d)||(c("collectionItem"),a("arrayNeedsComma"),b(d));break;case"arrayNeedsComma":d==="]"?f():d===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":d==="}"?f():d==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":d===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Ul(d)||(c("collectionItem"),a("objectNeedsComma"),b(d));break;case"objectNeedsComma":d==="}"?f():d===","&&(l("collectionItem"),a("objectNeedsKey"));break}}i!=null&&(e.length=i);for(var g=[r!=null?t.slice(0,r):t],x=function(E){return g.push(E.slice(t.length-t.lastIndexOf(E[0])))},w=e.length-1;w>=0;w--)switch(e[w]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":x("true");break;case"false":x("false");break;case"null":x("null");break;case"arrayNeedsValue":case"arrayNeedsComma":g.push("]");break;case"objectNeedsKey":case"objectNeedsColon":case"objectNeedsValue":case"objectNeedsComma":g.push("}");break}return g.join("")}function Gl(){let t=0,e=0;for(let r=0;r<28;r+=7){let i=this.buf[this.pos++];if(t|=(i&127)<<r,(i&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 i=this.buf[this.pos++];if(e|=(i&127)<<r,(i&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function gi(t,e,n){for(let o=0;o<28;o=o+7){let s=t>>>o,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,i=e>>3!=0;if(n.push((i?r|128:r)&255),!!i){for(let o=3;o<31;o=o+7){let s=e>>>o,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var mi=4294967296;function As(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,i=0;function o(s,a){let l=Number(t.slice(s,a));i*=n,r=r*n+l,r>=mi&&(i=i+(r/mi|0),r=r%mi)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),e?$l(r,i):Is(r,i)}function Fl(t,e){let n=Is(t,e),r=n.hi&2147483648;r&&(n=$l(n.lo,n.hi));let i=ks(n.lo,n.hi);return r?"-"+i:i}function ks(t,e){if({lo:t,hi:e}=mh(t,e),e<=2097151)return String(mi*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,i=e>>16&65535,o=n+r*6777216+i*6710656,s=r+i*8147497,a=i*2,l=1e7;return o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Hl(s)+Hl(o)}function mh(t,e){return{lo:t>>>0,hi:e>>>0}}function Is(t,e){return{lo:t|0,hi:e|0}}function $l(t,e){return e=~e,t?t=~t+1:e+=1,Is(t,e)}var Hl=t=>{let e=String(t);return"0000000".slice(e.length)+e};function Cs(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 zl(){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 Ve=gh();function gh(){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||!!globalThis.Bun||typeof process!="object"||typeof process.env!="object"||process.env.BUF_BIGINT_DISABLE!=="1")){let n=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),i=BigInt("0"),o=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>o||a<i)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()),Bl(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),jl(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),Bl(n),As(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),jl(n),As(n)},dec(n,r){return Fl(n,r)},uDec(n,r){return ks(n,r)}}}function Bl(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function jl(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var Ns=Symbol.for("@bufbuild/protobuf/text-encoding");function Rs(){if(globalThis[Ns]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[Ns]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,i){return i?(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[Ns]}var wt;(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"})(wt||(wt={}));var vh=34028234663852886e22,bh=-34028234663852886e22,yh=4294967295,xh=2147483647,Eh=-2147483648,G=class{constructor(e=Rs().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 i=0;i<this.chunks.length;i++)e+=this.chunks[i].length;let n=new Uint8Array(e),r=0;for(let i=0;i<this.chunks.length;i++)n.set(this.chunks[i],r),r+=this.chunks[i].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(Vl(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Os(e),Cs(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){Th(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){Vl(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Os(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Os(e),e=(e<<1^e>>31)>>>0,Cs(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=Ve.enc(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),i=Ve.uEnc(e);return r.setInt32(0,i.lo,!0),r.setInt32(4,i.hi,!0),this.raw(n)}int64(e){let n=Ve.enc(e);return gi(n.lo,n.hi,this.buf),this}sint64(e){let n=Ve.enc(e),r=n.hi>>31,i=n.lo<<1^r,o=(n.hi<<1|n.lo>>>31)^r;return gi(i,o,this.buf),this}uint64(e){let n=Ve.uEnc(e);return gi(n.lo,n.hi,this.buf),this}},S=class{constructor(e,n=Rs().decodeUtf8){this.decodeUtf8=n,this.varint64=Gl,this.uint32=zl,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 i=n>>>3,o=n&7;if(i<=0||o>5)throw new Error("illegal tag: field no "+i+" wire type "+o);return[i,o]}skip(e,n,r=100){let i=this.pos;switch(e){case wt.Varint:for(;this.buf[this.pos++]&128;);break;case wt.Bit64:this.pos+=4;case wt.Bit32:this.pos+=4;break;case wt.LengthDelimited:let o=this.uint32();this.pos+=o;break;case wt.StartGroup:if(r<=0)throw new Error("maximum recursion depth reached");for(;;){let[s,a]=this.tag();if(a===wt.EndGroup){if(n!==void 0&&s!==n)throw new Error("invalid end group tag");break}this.skip(a,s,r-1)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(i,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 Ve.dec(...this.varint64())}uint64(){return Ve.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,Ve.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 Ve.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Ve.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 Os(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>xh||t<Eh)throw new Error("invalid int32: "+t)}function Vl(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>yh||t<0)throw new Error("invalid uint32: "+t)}function Th(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>vh||t<bh))throw new Error("invalid float32: "+t)}var wh=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Ms(){return{fields:{}}}var Zn={encode(t,e=new G){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Ds.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,i=Ms();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:{if(o!==10)break;let s=Ds.decode(n,n.uint32());s.value!==void 0&&(i.fields[s.key]=s.value);continue}}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Zn.fromPartial(t??{})},fromPartial(t){let e=Ms();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,i])=>(i!==void 0&&(n[r]=i),n),{}),e},wrap(t){let e=Ms();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 Wl(){return{key:"",value:void 0}}var Ds={encode(t,e=new G){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&R.encode(R.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,i=Wl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.key=n.string();continue;case 2:if(o!==18)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ds.fromPartial(t??{})},fromPartial(t){let e=Wl();return e.key=t.key??"",e.value=t.value??void 0,e}};function Ls(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var R={encode(t,e=new G){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&&Yn.encode(Yn.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,i=Ls();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.nullValue=n.int32();continue;case 2:if(o!==17)break;i.numberValue=n.double();continue;case 3:if(o!==26)break;i.stringValue=n.string();continue;case 4:if(o!==32)break;i.boolValue=n.bool();continue;case 5:if(o!==42)break;i.structValue=Zn.unwrap(Zn.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.listValue=Yn.unwrap(Yn.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return R.fromPartial(t??{})},fromPartial(t){let e=Ls();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=Ls();if(t===null)e.nullValue=wh.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 Ps(){return{values:[]}}var Yn={encode(t,e=new G){for(let n of t.values)R.encode(R.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,i=Ps();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.values.push(R.unwrap(R.decode(n,n.uint32())));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Yn.fromPartial(t??{})},fromPartial(t){let e=Ps();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=Ps();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},Sh=(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 ql(){return{op:0,path:"",from:void 0,value:void 0}}var bi={encode(t,e=new G){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&&R.encode(R.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,i=ql();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.op=n.int32();continue;case 2:if(o!==18)break;i.path=n.string();continue;case 3:if(o!==26)break;i.from=n.string();continue;case 4:if(o!==34)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return bi.fromPartial(t??{})},fromPartial(t){let e=ql();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Xl(){return{id:"",type:"",function:void 0}}var yi={encode(t,e=new G){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&xi.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,i=Xl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.type=n.string();continue;case 3:if(o!==26)break;i.function=xi.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return yi.fromPartial(t??{})},fromPartial(t){let e=Xl();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?xi.fromPartial(t.function):void 0,e}};function Kl(){return{name:"",arguments:""}}var xi={encode(t,e=new G){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,i=Kl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.name=n.string();continue;case 2:if(o!==18)break;i.arguments=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return xi.fromPartial(t??{})},fromPartial(t){let e=Kl();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Zl(){return{value:"",mimeType:""}}var Ei={encode(t,e=new G){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,i=Zl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.value=n.string();continue;case 2:if(o!==18)break;i.mimeType=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ei.fromPartial(t??{})},fromPartial(t){let e=Zl();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Yl(){return{value:"",mimeType:void 0}}var Ti={encode(t,e=new G){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,i=Yl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.value=n.string();continue;case 2:if(o!==18)break;i.mimeType=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ti.fromPartial(t??{})},fromPartial(t){let e=Yl();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Jl(){return{data:void 0,url:void 0}}var Re={encode(t,e=new G){return t.data!==void 0&&Ei.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Ti.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,i=Jl();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.data=Ei.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.url=Ti.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Re.fromPartial(t??{})},fromPartial(t){let e=Jl();return e.data=t.data!==void 0&&t.data!==null?Ei.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Ti.fromPartial(t.url):void 0,e}};function Ql(){return{text:""}}var wi={encode(t,e=new G){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,i=Ql();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.text=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return wi.fromPartial(t??{})},fromPartial(t){let e=Ql();return e.text=t.text??"",e}};function ec(){return{source:void 0,metadata:void 0}}var Si={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.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,i=ec();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Si.fromPartial(t??{})},fromPartial(t){let e=ec();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function tc(){return{source:void 0,metadata:void 0}}var _i={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.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,i=tc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return _i.fromPartial(t??{})},fromPartial(t){let e=tc();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function nc(){return{source:void 0,metadata:void 0}}var Ai={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.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,i=nc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ai.fromPartial(t??{})},fromPartial(t){let e=nc();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function rc(){return{source:void 0,metadata:void 0}}var ki={encode(t,e=new G){return t.source!==void 0&&Re.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&R.encode(R.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,i=rc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.source=Re.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return ki.fromPartial(t??{})},fromPartial(t){let e=rc();return e.source=t.source!==void 0&&t.source!==null?Re.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function ic(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Ii={encode(t,e=new G){return t.text!==void 0&&wi.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Si.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&_i.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&Ai.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&ki.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,i=ic();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.text=wi.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.image=Si.decode(n,n.uint32());continue;case 3:if(o!==26)break;i.audio=_i.decode(n,n.uint32());continue;case 4:if(o!==34)break;i.video=Ai.decode(n,n.uint32());continue;case 5:if(o!==42)break;i.document=ki.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ii.fromPartial(t??{})},fromPartial(t){let e=ic();return e.text=t.text!==void 0&&t.text!==null?wi.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Si.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?_i.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?Ai.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?ki.fromPartial(t.document):void 0,e}};function oc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Ci={encode(t,e=new G){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)yi.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)Ii.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,i=oc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.role=n.string();continue;case 3:if(o!==26)break;i.content=n.string();continue;case 4:if(o!==34)break;i.name=n.string();continue;case 5:if(o!==42)break;i.toolCalls.push(yi.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.toolCallId=n.string();continue;case 7:if(o!==58)break;i.error=n.string();continue;case 8:if(o!==66)break;i.contentParts.push(Ii.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ci.fromPartial(t??{})},fromPartial(t){let e=oc();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=>yi.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Ii.fromPartial(n))||[],e}};function sc(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Ni={encode(t,e=new G){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&&R.encode(R.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&R.encode(R.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,i=sc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.id=n.string();continue;case 2:if(o!==18)break;i.reason=n.string();continue;case 3:if(o!==26)break;i.message=n.string();continue;case 4:if(o!==34)break;i.toolCallId=n.string();continue;case 5:if(o!==42)break;i.responseSchema=R.unwrap(R.decode(n,n.uint32()));continue;case 6:if(o!==50)break;i.expiresAt=n.string();continue;case 7:if(o!==58)break;i.metadata=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ni.fromPartial(t??{})},fromPartial(t){let e=sc();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}},_h=(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 ac(){return{type:0,timestamp:void 0,rawEvent:void 0}}var O={encode(t,e=new G){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&R.encode(R.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,i=ac();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==8)break;i.type=n.int32();continue;case 2:if(o!==16)break;i.timestamp=Ah(n.int64());continue;case 3:if(o!==26)break;i.rawEvent=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return O.fromPartial(t??{})},fromPartial(t){let e=ac();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function lc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Ri={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=lc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.role=n.string();continue;case 4:if(o!==34)break;i.name=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ri.fromPartial(t??{})},fromPartial(t){let e=lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function cc(){return{baseEvent:void 0,messageId:"",delta:""}}var Oi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=cc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Oi.fromPartial(t??{})},fromPartial(t){let e=cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function uc(){return{baseEvent:void 0,messageId:""}}var Mi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=uc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Mi.fromPartial(t??{})},fromPartial(t){let e=uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function dc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Li={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=dc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.toolCallName=n.string();continue;case 4:if(o!==34)break;i.parentMessageId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Li.fromPartial(t??{})},fromPartial(t){let e=dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function pc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Pi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=pc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Pi.fromPartial(t??{})},fromPartial(t){let e=pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function fc(){return{baseEvent:void 0,toolCallId:""}}var Di={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=fc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Di.fromPartial(t??{})},fromPartial(t){let e=fc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function hc(){return{baseEvent:void 0,snapshot:void 0}}var Ui={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&R.encode(R.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,i=hc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.snapshot=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Ui.fromPartial(t??{})},fromPartial(t){let e=hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function mc(){return{baseEvent:void 0,delta:[]}}var Hi={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)bi.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,i=mc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.delta.push(bi.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Hi.fromPartial(t??{})},fromPartial(t){let e=mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>bi.fromPartial(n))||[],e}};function gc(){return{baseEvent:void 0,messages:[]}}var Gi={encode(t,e=new G){t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Ci.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,i=gc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messages.push(Ci.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Gi.fromPartial(t??{})},fromPartial(t){let e=gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Ci.fromPartial(n))||[],e}};function vc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Fi={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&R.encode(R.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,i=vc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.event=R.unwrap(R.decode(n,n.uint32()));continue;case 3:if(o!==26)break;i.source=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Fi.fromPartial(t??{})},fromPartial(t){let e=vc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function bc(){return{baseEvent:void 0,name:"",value:void 0}}var $i={encode(t,e=new G){return t.baseEvent!==void 0&&O.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&R.encode(R.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,i=bc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.name=n.string();continue;case 3:if(o!==26)break;i.value=R.unwrap(R.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return $i.fromPartial(t??{})},fromPartial(t){let e=bc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function yc(){return{baseEvent:void 0,threadId:"",runId:""}}var zi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=yc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.threadId=n.string();continue;case 3:if(o!==26)break;i.runId=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return zi.fromPartial(t??{})},fromPartial(t){let e=yc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function xc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Bi={encode(t,e=new G){t.baseEvent!==void 0&&O.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&&R.encode(R.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Ni.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,i=xc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.threadId=n.string();continue;case 3:if(o!==26)break;i.runId=n.string();continue;case 4:if(o!==34)break;i.result=R.unwrap(R.decode(n,n.uint32()));continue;case 5:if(o!==42)break;i.outcome=n.string();continue;case 6:if(o!==50)break;i.interrupts.push(Ni.decode(n,n.uint32()));continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Bi.fromPartial(t??{})},fromPartial(t){let e=xc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.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=>Ni.fromPartial(n))||[],e}};function Ec(){return{baseEvent:void 0,code:void 0,message:""}}var ji={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=Ec();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.code=n.string();continue;case 3:if(o!==26)break;i.message=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return ji.fromPartial(t??{})},fromPartial(t){let e=Ec();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function Tc(){return{baseEvent:void 0,stepName:""}}var Vi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=Tc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.stepName=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Vi.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function wc(){return{baseEvent:void 0,stepName:""}}var Wi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=wc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.stepName=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Wi.fromPartial(t??{})},fromPartial(t){let e=wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.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 qi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=Sc();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.messageId=n.string();continue;case 3:if(o!==26)break;i.role=n.string();continue;case 4:if(o!==34)break;i.delta=n.string();continue;case 5:if(o!==42)break;i.name=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return qi.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.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 _c(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var Xi={encode(t,e=new G){return t.baseEvent!==void 0&&O.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,i=_c();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.baseEvent=O.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.toolCallId=n.string();continue;case 3:if(o!==26)break;i.toolCallName=n.string();continue;case 4:if(o!==34)break;i.parentMessageId=n.string();continue;case 5:if(o!==42)break;i.delta=n.string();continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return Xi.fromPartial(t??{})},fromPartial(t){let e=_c();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?O.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 kc={encode(t,e=new G){return t.textMessageStart!==void 0&&Ri.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Oi.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Mi.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Li.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Pi.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Di.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Ui.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Hi.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Gi.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Fi.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&$i.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&zi.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Bi.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&ji.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Vi.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&Wi.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&qi.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&Xi.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,i=Ac();for(;n.pos<r;){let o=n.uint32();switch(o>>>3){case 1:if(o!==10)break;i.textMessageStart=Ri.decode(n,n.uint32());continue;case 2:if(o!==18)break;i.textMessageContent=Oi.decode(n,n.uint32());continue;case 3:if(o!==26)break;i.textMessageEnd=Mi.decode(n,n.uint32());continue;case 4:if(o!==34)break;i.toolCallStart=Li.decode(n,n.uint32());continue;case 5:if(o!==42)break;i.toolCallArgs=Pi.decode(n,n.uint32());continue;case 6:if(o!==50)break;i.toolCallEnd=Di.decode(n,n.uint32());continue;case 7:if(o!==58)break;i.stateSnapshot=Ui.decode(n,n.uint32());continue;case 8:if(o!==66)break;i.stateDelta=Hi.decode(n,n.uint32());continue;case 9:if(o!==74)break;i.messagesSnapshot=Gi.decode(n,n.uint32());continue;case 10:if(o!==82)break;i.raw=Fi.decode(n,n.uint32());continue;case 11:if(o!==90)break;i.custom=$i.decode(n,n.uint32());continue;case 12:if(o!==98)break;i.runStarted=zi.decode(n,n.uint32());continue;case 13:if(o!==106)break;i.runFinished=Bi.decode(n,n.uint32());continue;case 14:if(o!==114)break;i.runError=ji.decode(n,n.uint32());continue;case 15:if(o!==122)break;i.stepStarted=Vi.decode(n,n.uint32());continue;case 16:if(o!==130)break;i.stepFinished=Wi.decode(n,n.uint32());continue;case 17:if(o!==138)break;i.textMessageChunk=qi.decode(n,n.uint32());continue;case 18:if(o!==146)break;i.toolCallChunk=Xi.decode(n,n.uint32());continue}if((o&7)===4||o===0)break;n.skip(o&7)}return i},create(t){return kc.fromPartial(t??{})},fromPartial(t){let e=Ac();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Ri.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Oi.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Mi.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Li.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Pi.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Di.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Ui.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Hi.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Gi.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Fi.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?$i.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?zi.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Bi.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?ji.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Vi.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?Wi.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?qi.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?Xi.fromPartial(t.toolCallChunk):void 0,e}};function Ah(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 vi=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}}},kh=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:vi(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:vi(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:vi(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:vi(t.document.source),metadata:t.document.metadata}}};function Ic(t){let e=kc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=_h[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 i=r;if(i.role==="user"&&Array.isArray(i.contentParts)){let o=i.contentParts.map(s=>kh(s)).filter(s=>s!==void 0);o.length>0&&(i.content=o)}Array.isArray(i.contentParts)&&i.contentParts.length===0&&(i.contentParts=void 0),i.toolCalls?.length===0&&(i.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,i=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,o=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,i==="interrupt"?r.outcome={type:"interrupt",interrupts:o}:i==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=Sh[r.op].toLowerCase(),Object.keys(r).forEach(i=>{r[i]===void 0&&delete r[i]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Lr.parse(n)}var Us="application/vnd.ag-ui.event+proto";var Ch=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Hs=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(Ch);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Cc=t=>t==="*"||t==="x"||t==="X",Nc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},Nh=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Rh=(t,e)=>{if(Cc(t)||Cc(e))return 0;let[n,r]=Nh(Nc(t),Nc(e));return n>r?1:n<r?-1:0},Gs=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=Rh(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var Jn=(t,e)=>{let n=Hs(t),r=Hs(e),i=n.pop(),o=r.pop(),s=Gs(n,r);return s!==0?s:i&&o?Gs(i.split("."),o.split(".")):i||o?i?-1:1:0};var V=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function Oe(){return bt()}function zs(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&zs(e);return t}var Rc=512*1024;function Oc(t,e,n){let r=0,i=[t,e],o=new WeakSet;for(;i.length>0;){let s=i.pop();if(typeof s=="string"){if(r+=s.length,r>n)return!0}else if(typeof s=="object"&&s){if(o.has(s))continue;if(o.add(s),Array.isArray(s))for(let a=0;a<s.length;a++)i.push(s[a]);else{let a=Object.keys(s);for(let l=0;l<a.length;l++){let c=a[l];if(r+=c.length,r>n)return!0;i.push(s[c])}}}}return!1}async function K(t,e,n,r){let i=typeof process<"u"&&process.env!==void 0,o=i&&!!process.env.VITEST_WORKER_ID,s=i&&!!process.env.VITEST_WORKER_ID,a=s&&!Oc(e,n,Rc),l=a?V(e):e,c=a?V(n):n,f=!1,m=!1,b;for(let h of t)try{a&&(zs(l),zs(c));let d=await r(h,l,c);if(d===void 0)continue;let g=!1;if(d.messages!==void 0&&d.messages!==l&&(l=V(d.messages),f=!0,g=!0),d.state!==void 0&&d.state!==c&&(c=V(d.state),m=!0,g=!0),a&&g&&Oc(l,c,Rc)&&(a=!1),b=d.stopPropagation,b===!0)break}catch(d){if(s&&d instanceof TypeError){if(o)throw d;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",d)}else o||console.error("Subscriber error:",d);continue}return{...f?{messages:Object.isFrozen(l)?V(l):l}:{},...m?{state:Object.isFrozen(c)?V(c):c}:{},...b===void 0?{}:{stopPropagation:b}}}function Ki(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 Bs)return t;if(t===!0)return new Bs(Ki(!0))}var Bs=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 Fs(t){return t.enabled?new Bs(t):void 0}function Oh(t,e,n){if(e){let i=t.find(s=>s.id===e);if(i?.role==="assistant")return i;i&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${i.role}' message, not assistant \u2014 falling back to toolCallId`);let o={id:i?n:e,role:"assistant",toolCalls:[]};return t.push(o),o}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Hc=(t,e,n,r,i)=>{let o=Qn(i),s=V(n.messages),a=V(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)},f=()=>{let m=V(l);return l={},m.messages!==void 0||m.state!==void 0?re(m):Yr};return e.pipe(pi(async m=>{let b=await K(r,s,a,(h,d,g)=>h.onEvent?.({event:m,agent:n,input:t,messages:d,state:g}));if(c(b),b.stopPropagation===!0?o?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):o?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),b.stopPropagation===!0)return f();switch(m.type){case v.TEXT_MESSAGE_START:{let h=await K(r,s,a,(d,g,x)=>d.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d,role:g="assistant",name:x}=m;if(!s.find(w=>w.id===d)){let w={id:d,role:g,content:"",...x!==void 0&&{name:x}};s.push(w),c({messages:s})}}return f()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:h,delta:d}=m,g=s.find(w=>w.id===h);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${h}'`),f();let x=await K(r,s,a,(w,E,I)=>w.onTextMessageContentEvent?.({event:m,messages:E,state:I,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${d}`,c({messages:s})),f()}case v.TEXT_MESSAGE_END:{let{messageId:h}=m,d=s.find(g=>g.id===h);return d?(c(await K(r,s,a,(g,x,w)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:w,agent:n,input:t,textMessageBuffer:typeof d.content=="string"?d.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:d,messages:s,state:a,agent:n,input:t})})),f()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${h}'`),f())}case v.TOOL_CALL_START:{let h=await K(r,s,a,(d,g,x)=>d.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{toolCallId:d,toolCallName:g,parentMessageId:x}=m,w=Oh(s,x,d);w.toolCalls??=[],w.toolCalls.push({id:d,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return f()}case v.TOOL_CALL_ARGS:{let{toolCallId:h,delta:d}=m,g=s.find(E=>E.toolCalls?.some(I=>I.id===h));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${h}'`),f();let x=g.toolCalls?.find(E=>E.id===h);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h}'`),f();let w=await K(r,s,a,(E,I,D)=>{let P=x.function.arguments,U=x.function.name,Se={};try{Se=hi(P)}catch{}return E.onToolCallArgsEvent?.({event:m,messages:I,state:D,agent:n,input:t,toolCallBuffer:P,toolCallName:U,partialToolCallArgs:Se})});return c(w),w.stopPropagation!==!0&&(x.function.arguments+=d,c({messages:s})),f()}case v.TOOL_CALL_END:{let{toolCallId:h}=m,d=s.find(x=>x.toolCalls?.some(w=>w.id===h));if(!d)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${h}'`),f();let g=d.toolCalls?.find(x=>x.id===h);return g?(c(await K(r,s,a,(x,w,E)=>{let I=g.function.arguments,D=g.function.name,P={};try{P=JSON.parse(I)}catch{}return x.onToolCallEndEvent?.({event:m,messages:w,state:E,agent:n,input:t,toolCallName:D,toolCallArgs:P})})),await Promise.all(r.map(x=>{x.onNewToolCall?.({toolCall:g,messages:s,state:a,agent:n,input:t})})),f()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${h}'`),f())}case v.TOOL_CALL_RESULT:{let h=await K(r,s,a,(d,g,x)=>d.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d,toolCallId:g,content:x,role:w}=m,E={id:d,toolCallId:g,role:w||"tool",content:x},I=s.findIndex(D=>D.role==="assistant"&&D.toolCalls?.some(P=>P.id===g));if(I===-1)s.push(E);else{let D=I+1;for(;D<s.length&&s[D].role==="tool";)D++;s.splice(D,0,E)}await Promise.all(r.map(D=>{D.onNewMessage?.({message:E,messages:s,state:a,agent:n,input:t})})),c({messages:s})}return f()}case v.STATE_SNAPSHOT:{let h=await K(r,s,a,(d,g,x)=>d.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{snapshot:d}=m;a=d,c({state:a})}return f()}case v.STATE_DELTA:{let h=await K(r,s,a,(d,g,x)=>d.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{delta:d}=m;try{a=zr.applyPatch(a,d,!0,!1).newDocument,c({state:a})}catch(g){let x=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
6
6
  Current state: ${JSON.stringify(a,null,2)}
7
- Patch operations: ${JSON.stringify(h,null,2)}
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(G=>G.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,(G,X,ae)=>G.onActivitySnapshotEvent?.({event:f,messages:X,state:ae,agent:n,input:t,activityMessage:T,existingMessage:g}));if(c(b),b.stopPropagation!==!0){let G={id:f.messageId,role:"activity",activityType:f.activityType,content:z(f.content)},X;h===-1?(s.push(G),X=G):T?_&&(s[h]={...T,activityType:f.activityType,content:z(f.content)}):_&&(s[h]=G,X=G),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,G,X)=>b.onActivityDeltaEvent?.({event:f,messages:G,state:X,agent:n,input:t,activityMessage:T}));if(c(_),_.stopPropagation!==!0)try{let b=z(T.content??{}),G=Fr.applyPatch(b,f.patch??[],!0,!1).newDocument;s[h]={...T,content:z(G),activityType:f.activityType},c({messages:s})}catch(b){let G=b instanceof Error?b.message:String(b);console.warn(`Failed to apply activity patch for '${f.messageId}': ${G}`)}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,G)=>_.onReasoningMessageContentEvent?.({event:m,messages:b,state:G,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,G)=>_.onReasoningEncryptedValueEvent?.({event:m,messages:b,state:G,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 G=b.toolCalls.find(X=>X.id===h);if(G){G.encryptedValue=g,_=!0;break}}}else{let b=s.find(G=>G.id===h);b?.role!=="activity"&&b&&(b.encryptedValue=g,_=!0)}_&&(l.messages=s)}return p()}}return m.type,p()}),vs(),r.length>0?ys({}):m=>m)},Ds=t=>e=>{let n=qn(t),r=new Map,i=new Map,o=!1,s=!1,a=!1,l=new Map,c=!1,p=!1,m=!1,x=()=>{r.clear(),i.clear(),l.clear(),c=!1,p=!1,o=!1,s=!1,m=!0};return e.pipe(Ie(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(o&&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&&!o)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."));o&&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 i.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.`)):(i.set(g,!0),te(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return i.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 i.has(g)?(i.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(i.size>0){let g=Array.from(i.keys()).join(", ");return Q(()=>new q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return o=!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})({}),wh=t=>ci(()=>Wt(t())).pipe(bs(e=>{if(!e.ok){let i=e.headers.get("content-type")||"";return Wt(e.text()).pipe(Ie(o=>{let s=o;if(i.includes("application/json"))try{s=JSON.parse(o)}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(i=>(i.next(n),(async()=>{try{for(;;){let{done:o,value:s}=await r.read();if(o)break;let a={type:Zt.DATA,data:s};i.next(a)}i.complete()}catch(o){i.error(o)}})(),()=>{r.cancel().catch(o=>{if(o?.name!=="AbortError")throw o})})):Q(()=>Error("Failed to getReader() from response"))})),Ah=(t,e)=>{let n=qn(e),r=new nt,i=new TextDecoder("utf-8",{fatal:!1}),o="";t.subscribe({next:a=>{if(a.type!==Zt.HEADERS&&a.type===Zt.DATA&&a.data){let l=i.decode(a.data,{stream:!0});o+=l;let c=o.split(/\n\n/);o=c.pop()||"";for(let p of c)s(p)}},error:a=>r.error(a),complete:()=>{o&&(o+=i.decode(),s(o)),r.complete()}});function s(a){let l=a.split(`
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()},kh=t=>{let e=new nt,n=new Uint8Array;t.subscribe({next:i=>{if(i.type!==Zt.HEADERS&&i.type===Zt.DATA&&i.data){let o=new Uint8Array(n.length+i.data.length);o.set(n,0),o.set(i.data,n.length),n=o,r()}},error:i=>e.error(i),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 i=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<i)break;try{let o=n.slice(4,i),s=Tc(o);e.next(s),n=n.slice(i)}catch(o){let s=o instanceof Error?o.message:String(o);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},Ih=(t,e)=>{let n=qn(e),r=new nt,i=new Kr,o=!1;return t.subscribe({next:s=>{if(i.next(s),s.type===Zt.HEADERS&&!o){o=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Os?"protobuf":"sse"}),a===Os?kh(i).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):Ah(i,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 o||r.error(Error("No headers event received before data events"))},error:s=>{i.error(s),r.error(s)},complete:()=>{i.complete()}}),r.asObservable()},Z=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Ch=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Nh=u.object({type:u.literal(Z.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),Rh=u.object({type:u.literal(Z.enum.TextMessageContent),messageId:u.string(),content:u.string()}),Oh=u.object({type:u.literal(Z.enum.TextMessageEnd),messageId:u.string()}),Mh=u.object({type:u.literal(Z.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),Lh=u.object({type:u.literal(Z.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),Ph=u.object({type:u.literal(Z.enum.ActionExecutionEnd),actionExecutionId:u.string()}),Dh=u.object({type:u.literal(Z.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),Uh=u.object({type:u.literal(Z.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()}),Hh=u.object({type:u.literal(Z.enum.MetaEvent),name:Ch,value:u.any()}),Gh=u.object({type:u.literal(Z.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[Nh,Rh,Oh,Mh,Lh,Ph,Dh,Uh,Hh,Gh]),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 Fh=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
- `)},$h=(t,e,n)=>r=>{let i={},o=!0,s=!0,a="",l=null,c=null,p=[],m={},x=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,i=f)};return r.pipe(Ie(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let h=f;return[{type:Z.enum.TextMessageStart,messageId:h.messageId,role:h.role}]}case v.TEXT_MESSAGE_CONTENT:{let h=f;return[{type:Z.enum.TextMessageContent,messageId:h.messageId,content:h.delta}]}case v.TEXT_MESSAGE_END:{let h=f;return[{type:Z.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:Z.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(pi(g.function.arguments));_.tool_argument&&_.tool_argument in b?(x({...i,[_.state_key]:b[_.tool_argument]}),T=!0):_.tool_argument||(x({...i,[_.state_key]:b}),T=!0)}catch{}}return[{type:Z.enum.ActionExecutionArgs,actionExecutionId:h.toolCallId,args:h.delta},...T?[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}]:[]]}case v.TOOL_CALL_END:{let h=f;return[{type:Z.enum.ActionExecutionEnd,actionExecutionId:h.toolCallId}]}case v.TOOL_CALL_RESULT:{let h=f;return[{type:Z.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":o=!1;break;case"PredictState":c=h.value;break}return[{type:Z.enum.MetaEvent,name:h.name,value:h.value}]}case v.STATE_SNAPSHOT:return x(f.snapshot),[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}];case v.STATE_DELTA:{let h=f,g=Fr.applyPatch(i,h.delta,!0,!1);return g?(x(g.newDocument),[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=f.messages,[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify({...i,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(i.messages=l),Object.keys(i).length===0?[]:[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify({...i,...l?{messages:zh(l)}:{}}),active:!1}];case v.RUN_ERROR:{let h=f;return[{type:Z.enum.RunError,message:h.message,code:h.code}]}case v.STEP_STARTED:return a=f.stepName,p=[],c=null,[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:!0}];case v.STEP_FINISHED:return p=[],c=null,[{type:Z.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:!1}];default:return[]}}))};function zh(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Fh(n.content);if(r){let i={id:n.id,role:n.role,content:r};e.push(i)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let i of n.toolCalls){let o={id:i.id,name:i.function.name,arguments:JSON.parse(i.function.arguments),parentMessageId:n.id};e.push(o)}}else if(n.role==="tool"){let r="unknown";for(let o of t)if(o.role==="assistant"&&o.toolCalls?.length){for(let s of o.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(i)}return e}var Ki=t=>e=>{let n=qn(t),r,i,o,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(!i||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:i.toolCallId};return s=void 0,i=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!o||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:o.messageId};return s=void 0,o=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(Ie(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!==i?.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");i={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:i.toolCallId,delta:h.delta};g.push(b),n?.event("TRANSFORM","TOOL_CALL_ARGS",b,{toolCallId:i.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let T=m,_=[];if((s!=="reasoning"||T.messageId&&T.messageId!==o?.messageId)&&_.push(...p()),s!=="reasoning"){if(T.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");o={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:o.messageId,delta:T.delta};_.push(b),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",b,{messageId:o.messageId})}return _}return m.type,[]}),Kt(()=>{p()}))};function Bh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}var Zi=class{runNext(t,e){return e.run(t).pipe(Ki(!1))}runNextWithState(t,e){let n=z(t.messages||[]),r=z(t.state||{}),i=new Kr;return Nc(t,i,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(r=o.state)}),this.runNext(t,e).pipe(ui(async o=>(i.next(o),await new Promise(s=>setTimeout(s,0)),{event:o,messages:z(n),state:z(r)})))}},Vh=class extends Zi{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function jh(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 Wh=class extends Zi{run(t,e){let{parentRunId:n,...r}=t,i={...r,messages:r.messages.map(jh)};return this.runNext(i,e)}},wc="THINKING_START",Ac="THINKING_END",kc="THINKING_TEXT_MESSAGE_START",Ic="THINKING_TEXT_MESSAGE_CONTENT",Cc="THINKING_TEXT_MESSAGE_END",Xh=class extends Zi{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(Xt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case wc:{this.currentReasoningId=Re();let{title:e,...n}=t;return this.warnAboutTransformation(wc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case kc:return this.currentMessageId=Re(),this.warnAboutTransformation(kc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Ic:{let{delta:e,...n}=t;return this.warnAboutTransformation(Ic,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Re(),delta:e}}case Cc:{let e=this.currentMessageId??Re();return this.warnAboutTransformation(Cc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Ac:{let e=this.currentReasoningId??Re();return this.warnAboutTransformation(Ac,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Kh(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function Zh(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function Yh(t){let e=Kh(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 qh(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>Zh(r)?Yh(r):r);return{...t,content:n}}var Jh=class extends Zi{run(t,e){let n={...t,messages:t.messages.map(qh)};return this.runNext(n,e)}},Qh="0.0.54",em=class{get maxVersion(){return Qh}get debug(){return this._debug}set debug(t){this._debug=Xi(t),this._debugLogger=Ps(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Ps(Xi(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:i,debug:o}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??vt(),this.messages=z(r??[]),this.state=z(i??{}),this._debug=Xi(o),this._debugLogger=Ps(this._debug),Yn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Wh),Yn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Xh),Yn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Jh)}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 Vh(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??vt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,i=new Set(this.messages.map(l=>l.id)),o=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,o),this.activeRunDetach$=new nt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await li(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),Ki(this.debugLogger),Ds(this.debugLogger),l=>l.pipe(di(this.activeRunDetach$)),l=>this.apply(n,l,o),l=>this.processApplyEvents(n,l,o),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,o))),Kt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)));let a=z(this.messages).filter(l=>!i.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new is}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??vt();let n=this.prepareRunAgentInput(t),r,i=new Set(this.messages.map(l=>l.id)),o=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,o),this.activeRunDetach$=new nt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await li(Xr(()=>ci(()=>this.connect(n)),Ki(this.debugLogger),Ds(this.debugLogger),l=>l.pipe(di(this.activeRunDetach$)),l=>this.apply(n,l,o),l=>this.processApplyEvents(n,l,o),Xn(l=>(this.isRunning=!1,l instanceof is?Zr:this.onError(n,l,o))),Kt(()=>{this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(te(null)),{defaultValue:void 0});let a=z(this.messages).filter(l=>!i.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 Nc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(xs(r=>{r.messages&&(this.messages=r.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(i=>{i.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||vt(),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(o=>o.interruptId)),i=this.pendingInterrupts.map(o=>o.id).filter(o=>!r.has(o));if(i.length>0)throw new q(`Thread has ${i.length} pending interrupt(s) not addressed by resume: ${i.join(", ")}`);for(let o of this.pendingInterrupts)if(Bh(o))throw new q(`Interrupt ${o.id} expired at ${o.expiresAt}`)}let n=await W(e,this.messages,this.state,(r,i,o)=>r.onRunInitialized?.({messages:i,state:o,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 Wt(W(n,this.messages,this.state,(r,i,o)=>r.onRunFailed?.({error:e,messages:i,state:o,agent:this,input:t}))).pipe(Xt(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),i.state!==void 0&&(this.state=i.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),i.stopPropagation!==!0){let o=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||o==="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,i,o)=>r.onRunFinalized?.({messages:i,state:o,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??vt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:i=>r.run(i,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Ki(this.debugLogger),Ds(this.debugLogger),$h(this.threadId,e.runId,this.agentId),n=>n.pipe(Xt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},Rc=class extends em{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 Ih(wh(()=>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 ge={title:"Assistant",chatHistory:"Chat history",newChat:"New chat",collapse:"Collapse",expand:"Expand",toggleTheme:"Toggle theme",conversation:"Conversation",thinking:"Assistant is thinking\u2026",thoughts:"Thoughts",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",recordVoice:"Record voice",stopRecording:"Stop recording",transcribing:"Transcribing\u2026",transcriptionFailed:"Transcription failed",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 Gs(t){let e={...ge};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}var Yi=class{element;#n;#e;#t=[];constructor(e){this.#n=e,this.#e=e.strings??ge,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:Me.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#o(e);if(r!==null){n.status=Me.ERROR,n.error=r,this.#a(),this.#n.onChange?.();return}this.#a(),this.#n.onChange?.(),this.#r(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===Me.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Me.UPLOADING),this.#a()}clear(){for(let e of this.#t)e.controller?.abort();this.#t=[],this.#a()}dispose(){for(let e of this.#t)e.controller?.abort()}#o(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",_r(this.#n.maxBytes)):tm(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#o(e.file);if(n!==null){e.status=Me.ERROR,e.error=n,this.#a(),this.#n.onChange?.();return}e.status=Me.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#a(),this.#n.upload(e.file,i=>{e.progress=i,this.#a()},r.signal).then(i=>{e.status=Me.READY,e.ref=i}).catch(i=>{e.status=Me.ERROR,e.error=i instanceof Error?i.message:this.#e.uploadFailed}).finally(()=>{e.controller=null,this.#a(),this.#n.onChange?.()})}#s(e){e.controller?.abort(),this.#t=this.#t.filter(n=>n!==e),this.#a(),this.#n.onChange?.()}#a(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#i(e))}#i(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=qo(e.file.type),r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.className="attachment-chip-name",i.textContent=e.file.name,i.title=e.file.name;let o=document.createElement("span");if(o.className="attachment-chip-size",o.textContent=e.status===Me.ERROR?e.error:_r(e.file.size),n.append(r,i,o),e.status===Me.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===Me.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.#r(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.#s(e)),n.appendChild(s),n}};function tm(t,e){let n=t.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),i=e.name.toLowerCase();return n.some(o=>o.startsWith(".")?i.endsWith(o):o.endsWith("/*")?r.startsWith(o.slice(0,-1)):r===o)}function Oc(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 Fs(t,e,n={}){let r=n.strings??ge;return new Promise(i=>{let o=document.createElement("div");o.className="confirm",o.setAttribute("part","confirm"),o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.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=Oc("cancel",r.cancel),p=Oc("confirm",r.confirm),m=!1,x=f=>{m||(m=!0,c.disabled=!0,p.disabled=!0,o.setAttribute("data-resolved",f?"confirmed":"declined"),i(f))};if(c.addEventListener("click",()=>x(!1)),p.addEventListener("click",()=>x(!0)),n.signal?.addEventListener("abort",()=>x(!1),{once:!0}),l.append(c,p),o.append(s,a,l),t.appendChild(o),n.signal?.aborted===!0){x(!1);return}p.focus()})}function $s(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function Mc(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 nm(t){if(Array.isArray(t))return t}function rm(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,o,s,a=[],l=!0,c=!1;try{if(o=(n=n.call(t)).next,e!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(p){c=!0,i=p}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function im(){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 om(t,e){return nm(t)||rm(t,e)||sm(t,e)||im()}function sm(t,e){if(t){if(typeof t=="string")return Mc(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)?Mc(t,e):void 0}}var Wc=Object.entries,Lc=Object.setPrototypeOf,am=Object.isFrozen,lm=Object.getPrototypeOf,cm=Object.getOwnPropertyDescriptor,we=Object.freeze,He=Object.seal,wn=Object.create,Xc=typeof Reflect<"u"&&Reflect,Xs=Xc.apply,Ks=Xc.construct;we||(we=function(e){return e});He||(He=function(e){return e});Xs||(Xs=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return e.apply(n,i)});Ks||(Ks=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new e(...r)});var Tn=de(Array.prototype.forEach),um=de(Array.prototype.lastIndexOf),Pc=de(Array.prototype.pop),Sn=de(Array.prototype.push),dm=de(Array.prototype.splice),_e=Array.isArray,er=de(String.prototype.toLowerCase),zs=de(String.prototype.toString),Dc=de(String.prototype.match),_n=de(String.prototype.replace),Uc=de(String.prototype.indexOf),pm=de(String.prototype.trim),fm=de(Number.prototype.toString),hm=de(Boolean.prototype.toString),Hc=typeof BigInt>"u"?null:de(BigInt.prototype.toString),Gc=typeof Symbol>"u"?null:de(Symbol.prototype.toString),re=de(Object.prototype.hasOwnProperty),Jn=de(Object.prototype.toString),xe=de(RegExp.prototype.test),Qn=mm(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),i=1;i<n;i++)r[i-1]=arguments[i];return Xs(t,e,r)}}function mm(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Ks(t,n)}}function D(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:er;if(Lc&&Lc(t,null),!_e(e))return t;let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){let o=n(i);o!==i&&(am(e)||(e[r]=o),i=o)}t[i]=!0}return t}function gm(t){for(let e=0;e<t.length;e++)re(t,e)||(t[e]=null);return t}function Te(t){let e=wn(null);for(let r of Wc(t)){var n=om(r,2);let i=n[0],o=n[1];re(t,i)&&(_e(o)?e[i]=gm(o):o&&typeof o=="object"&&o.constructor===Object?e[i]=Te(o):e[i]=o)}return e}function vm(t){switch(typeof t){case"string":return t;case"number":return fm(t);case"boolean":return hm(t);case"bigint":return Hc?Hc(t):"0";case"symbol":return Gc?Gc(t):"Symbol()";case"undefined":return Jn(t);case"function":case"object":{if(t===null)return Jn(t);let e=t,n=it(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 it(t,e){for(;t!==null;){let r=cm(t,e);if(r){if(r.get)return de(r.get);if(typeof r.value=="function")return de(r.value)}t=lm(t)}function n(){return null}return n}function ym(t){try{return xe(t,""),!0}catch{return!1}}var Fc=we(["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"]),Bs=we(["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"]),Vs=we(["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"]),bm=we(["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"]),js=we(["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"]),xm=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),$c=we(["#text"]),zc=we(["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"]),Ws=we(["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"]),Bc=we(["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"]),qi=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Em=He(/{{[\w\W]*|^[\w\W]*}}/g),Tm=He(/<%[\w\W]*|^[\w\W]*%>/g),Sm=He(/\${[\w\W]*/g),_m=He(/^data-[\-\w.\u00B7-\uFFFF]+$/),wm=He(/^aria-[\-\w]+$/),Vc=He(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Am=He(/^(?:\w+script|data):/i),km=He(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Im=He(/^html$/i),Cm=He(/^[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},Nm=function(){return typeof window>"u"?null:window},Rm=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));let o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},jc=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function Kc(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Nm(),e=C=>Kc(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,i=r.currentScript;t.DocumentFragment;let o=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=it(x,"cloneNode"),h=it(x,"remove"),g=it(x,"nextSibling"),T=it(x,"childNodes"),_=it(x,"parentNode"),b=it(x,"shadowRoot"),G=it(x,"attributes"),X=s&&s.prototype?it(s.prototype,"nodeType"):null,ae=s&&s.prototype?it(s.prototype,"nodeName"):null;if(typeof o=="function"){let C=n.createElement("template");C.content&&C.content.ownerDocument&&(n=C.content.ownerDocument)}let ee,ht="",cr=n,fo=cr.implementation,ha=cr.createNodeIterator,wu=cr.createDocumentFragment,Au=cr.getElementsByTagName,ku=r.importNode,pe=jc();e.isSupported=typeof Wc=="function"&&typeof _=="function"&&fo&&fo.createHTMLDocument!==void 0;let ur=Em,dr=Tm,pr=Sm,Iu=_m,Cu=wm,Nu=Am,ma=km,Ru=Cm,ga=Vc,ie=null,ho=D({},[...Fc,...Bs,...Vs,...js,...$c]),le=null,mo=D({},[...zc,...Ws,...Bc,...qi]),oe=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,mt=Object.seal(wn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),va=!0,go=!0,ya=!1,ba=!0,gt=!1,Cn=!0,_t=!1,vo=!1,yo=!1,Qt=!1,hr=!1,mr=!1,xa=!0,Ea=!1,Ta="user-content-",bo=!0,Nn=!1,en={},Xe=null,xo=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"]),Sa=null,_a=D({},["audio","video","img","source","image","track"]),Eo=null,wa=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",Ke="http://www.w3.org/1999/xhtml",tn=Ke,To=!1,So=null,Ou=D({},[gr,vr,Ke],zs),_o=D({},["mi","mo","mn","ms","mtext"]),wo=D({},["annotation-xml"]),Mu=D({},["title","style","font","a","script"]),Rn=null,Lu=["application/xhtml+xml","text/html"],Pu="text/html",se=null,nn=null,Du=n.createElement("form"),Aa=function(d){return d instanceof RegExp||d instanceof Function},Ao=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(nn&&nn===d)return;(!d||typeof d!="object")&&(d={}),d=Te(d),Rn=Lu.indexOf(d.PARSER_MEDIA_TYPE)===-1?Pu:d.PARSER_MEDIA_TYPE,se=Rn==="application/xhtml+xml"?zs:er,ie=re(d,"ALLOWED_TAGS")&&_e(d.ALLOWED_TAGS)?D({},d.ALLOWED_TAGS,se):ho,le=re(d,"ALLOWED_ATTR")&&_e(d.ALLOWED_ATTR)?D({},d.ALLOWED_ATTR,se):mo,So=re(d,"ALLOWED_NAMESPACES")&&_e(d.ALLOWED_NAMESPACES)?D({},d.ALLOWED_NAMESPACES,zs):Ou,Eo=re(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)?D(Te(wa),d.ADD_URI_SAFE_ATTR,se):wa,Sa=re(d,"ADD_DATA_URI_TAGS")&&_e(d.ADD_DATA_URI_TAGS)?D(Te(_a),d.ADD_DATA_URI_TAGS,se):_a,Xe=re(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)?D({},d.FORBID_CONTENTS,se):xo,In=re(d,"FORBID_TAGS")&&_e(d.FORBID_TAGS)?D({},d.FORBID_TAGS,se):Te({}),fr=re(d,"FORBID_ATTR")&&_e(d.FORBID_ATTR)?D({},d.FORBID_ATTR,se):Te({}),en=re(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?Te(d.USE_PROFILES):d.USE_PROFILES:!1,va=d.ALLOW_ARIA_ATTR!==!1,go=d.ALLOW_DATA_ATTR!==!1,ya=d.ALLOW_UNKNOWN_PROTOCOLS||!1,ba=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,gt=d.SAFE_FOR_TEMPLATES||!1,Cn=d.SAFE_FOR_XML!==!1,_t=d.WHOLE_DOCUMENT||!1,Qt=d.RETURN_DOM||!1,hr=d.RETURN_DOM_FRAGMENT||!1,mr=d.RETURN_TRUSTED_TYPE||!1,yo=d.FORCE_BODY||!1,xa=d.SANITIZE_DOM!==!1,Ea=d.SANITIZE_NAMED_PROPS||!1,bo=d.KEEP_CONTENT!==!1,Nn=d.IN_PLACE||!1,ga=ym(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Vc,tn=typeof d.NAMESPACE=="string"?d.NAMESPACE:Ke,_o=re(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?Te(d.MATHML_TEXT_INTEGRATION_POINTS):D({},["mi","mo","mn","ms","mtext"]),wo=re(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Te(d.HTML_INTEGRATION_POINTS):D({},["annotation-xml"]);let y=re(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Te(d.CUSTOM_ELEMENT_HANDLING):wn(null);if(oe=wn(null),re(y,"tagNameCheck")&&Aa(y.tagNameCheck)&&(oe.tagNameCheck=y.tagNameCheck),re(y,"attributeNameCheck")&&Aa(y.attributeNameCheck)&&(oe.attributeNameCheck=y.attributeNameCheck),re(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(oe.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),gt&&(go=!1),hr&&(Qt=!0),en&&(ie=D({},$c),le=wn(null),en.html===!0&&(D(ie,Fc),D(le,zc)),en.svg===!0&&(D(ie,Bs),D(le,Ws),D(le,qi)),en.svgFilters===!0&&(D(ie,Vs),D(le,Ws),D(le,qi)),en.mathMl===!0&&(D(ie,js),D(le,Bc),D(le,qi))),mt.tagCheck=null,mt.attributeCheck=null,re(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?mt.tagCheck=d.ADD_TAGS:_e(d.ADD_TAGS)&&(ie===ho&&(ie=Te(ie)),D(ie,d.ADD_TAGS,se))),re(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?mt.attributeCheck=d.ADD_ATTR:_e(d.ADD_ATTR)&&(le===mo&&(le=Te(le)),D(le,d.ADD_ATTR,se))),re(d,"ADD_URI_SAFE_ATTR")&&_e(d.ADD_URI_SAFE_ATTR)&&D(Eo,d.ADD_URI_SAFE_ATTR,se),re(d,"FORBID_CONTENTS")&&_e(d.FORBID_CONTENTS)&&(Xe===xo&&(Xe=Te(Xe)),D(Xe,d.FORBID_CONTENTS,se)),re(d,"ADD_FORBID_CONTENTS")&&_e(d.ADD_FORBID_CONTENTS)&&(Xe===xo&&(Xe=Te(Xe)),D(Xe,d.ADD_FORBID_CONTENTS,se)),bo&&(ie["#text"]=!0),_t&&D(ie,["html","head","body"]),ie.table&&(D(ie,["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,ht=ee.createHTML("")}else ee===void 0&&(ee=Rm(m,i)),ee!==null&&typeof ht=="string"&&(ht=ee.createHTML(""));(pe.uponSanitizeElement.length>0||pe.uponSanitizeAttribute.length>0)&&ie===ho&&(ie=Te(ie)),pe.uponSanitizeAttribute.length>0&&le===mo&&(le=Te(le)),we&&we(d),nn=d},ka=D({},[...Bs,...Vs,...bm]),Ia=D({},[...js,...xm]),Uu=function(d){let y=_(d);(!y||!y.tagName)&&(y={namespaceURI:tn,tagName:"template"});let A=er(d.tagName),j=er(y.tagName);return So[d.namespaceURI]?d.namespaceURI===vr?y.namespaceURI===Ke?A==="svg":y.namespaceURI===gr?A==="svg"&&(j==="annotation-xml"||_o[j]):!!ka[A]:d.namespaceURI===gr?y.namespaceURI===Ke?A==="math":y.namespaceURI===vr?A==="math"&&wo[j]:!!Ia[A]:d.namespaceURI===Ke?y.namespaceURI===vr&&!wo[j]||y.namespaceURI===gr&&!_o[j]?!1:!Ia[A]&&(Mu[A]||!ka[A]):!!(Rn==="application/xhtml+xml"&&So[d.namespaceURI]):!1},Ge=function(d){Sn(e.removed,{element:d});try{_(d).removeChild(d)}catch{h(d)}},wt=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{}},Ca=function(d){let y=null,A=null;if(yo)d="<remove></remove>"+d;else{let Y=Dc(d,/^[\r\n\t ]+/);A=Y&&Y[0]}Rn==="application/xhtml+xml"&&tn===Ke&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let j=ee?ee.createHTML(d):d;if(tn===Ke)try{y=new p().parseFromString(j,Rn)}catch{}if(!y||!y.documentElement){y=fo.createDocument(tn,"template",null);try{y.documentElement.innerHTML=To?ht:j}catch{}}let $=y.body||y.documentElement;return d&&A&&$.insertBefore(n.createTextNode(A),$.childNodes[0]||null),tn===Ke?Au.call(y,_t?"html":"body")[0]:_t?y.documentElement:$},Na=function(d){return ha.call(d.ownerDocument||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ra=function(d){d.normalize();let y=ha.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;Tn([ur,dr,pr],$=>{j=_n(j,$," ")}),A.data=j,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!==G(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 Oa=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:ie}),Cn&&d.hasChildNodes()&&!br(d.firstElementChild)&&xe(/<[/\w!]/g,d.innerHTML)&&xe(/<[/\w!]/g,d.textContent)||Cn&&d.namespaceURI===Ke&&A==="style"&&br(d.firstElementChild)||d.nodeType===rt.progressingInstruction||Cn&&d.nodeType===rt.comment&&xe(/<[/\w]/g,d.data))return Ge(d),!0;if(In[A]||!(mt.tagCheck instanceof Function&&mt.tagCheck(A))&&!ie[A]){if(!In[A]&&La(A)&&(oe.tagNameCheck instanceof RegExp&&xe(oe.tagNameCheck,A)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(A)))return!1;if(bo&&!Xe[A]){let $=_(d),Y=T(d);if(Y&&$){let Oe=Y.length;for(let Ze=Oe-1;Ze>=0;--Ze){let Fe=f(Y[Ze],!0);$.insertBefore(Fe,g(d))}}}return Ge(d),!0}return(X?X(d):d.nodeType)===rt.element&&!Uu(d)||(A==="noscript"||A==="noembed"||A==="noframes")&&xe(/<\/no(script|embed|frames)/i,d.innerHTML)?(Ge(d),!0):(gt&&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)},Ma=function(d,y,A){if(fr[y]||xa&&(y==="id"||y==="name")&&(A in n||A in Du))return!1;let j=le[y]||mt.attributeCheck instanceof Function&&mt.attributeCheck(y,d);if(!(go&&!fr[y]&&xe(Iu,y))){if(!(va&&xe(Cu,y))){if(!j||fr[y]){if(!(La(d)&&(oe.tagNameCheck instanceof RegExp&&xe(oe.tagNameCheck,d)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(d))&&(oe.attributeNameCheck instanceof RegExp&&xe(oe.attributeNameCheck,y)||oe.attributeNameCheck instanceof Function&&oe.attributeNameCheck(y,d))||y==="is"&&oe.allowCustomizedBuiltInElements&&(oe.tagNameCheck instanceof RegExp&&xe(oe.tagNameCheck,A)||oe.tagNameCheck instanceof Function&&oe.tagNameCheck(A))))return!1}else if(!Eo[y]){if(!xe(ga,_n(A,ma,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&d!=="script"&&Uc(A,"data:")===0&&Sa[d])){if(!(ya&&!xe(Nu,_n(A,ma,"")))){if(A)return!1}}}}}}return!0},Hu=D({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),La=function(d){return!Hu[er(d)]&&xe(Ru,d)},Pa=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},j=y.length;for(;j--;){let $=y[j],Y=$.name,Oe=$.namespaceURI,Ze=$.value,Fe=se(Y),ko=Ze,fe=Y==="value"?ko:pm(ko);if(A.attrName=Fe,A.attrValue=fe,A.keepAttr=!0,A.forceKeepAttr=void 0,st(pe.uponSanitizeAttribute,d,A),fe=A.attrValue,Ea&&(Fe==="id"||Fe==="name")&&Uc(fe,Ta)!==0&&(wt(Y,d),fe=Ta+fe),Cn&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,fe)){wt(Y,d);continue}if(Fe==="attributename"&&Dc(fe,"href")){wt(Y,d);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){wt(Y,d);continue}if(!ba&&xe(/\/>/i,fe)){wt(Y,d);continue}gt&&Tn([ur,dr,pr],Ua=>{fe=_n(fe,Ua," ")});let Da=se(d.nodeName);if(!Ma(Da,Fe,fe)){wt(Y,d);continue}if(ee&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Oe)switch(m.getAttributeType(Da,Fe)){case"TrustedHTML":{fe=ee.createHTML(fe);break}case"TrustedScriptURL":{fe=ee.createScriptURL(fe);break}}if(fe!==ko)try{Oe?d.setAttributeNS(Oe,Y,fe):d.setAttribute(Y,fe),yr(d)?Ge(d):Pc(e.removed)}catch{wt(Y,d)}}st(pe.afterSanitizeAttributes,d,null)},xr=function(d){let y=null,A=Na(d);for(st(pe.beforeSanitizeShadowDOM,d,null);y=A.nextNode();)if(st(pe.uponSanitizeShadowNode,y,null),Oa(y),Pa(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 j=[];Tn(A,$=>{Sn(j,$)});for(let $ of j)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,j=null,$=null;if(To=!C,To&&(C="<!-->"),typeof C!="string"&&!br(C)&&(C=vm(C),typeof C!="string"))throw Qn("dirty is not a string, aborting");if(!e.isSupported)return C;if(vo||Ao(d),e.removed=[],typeof C=="string"&&(Nn=!1),Nn){let Ze=ae?ae(C):C.nodeName;if(typeof Ze=="string"){let Fe=se(Ze);if(!ie[Fe]||In[Fe])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=Ca("<!---->"),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&&!gt&&!_t&&C.indexOf("<")===-1)return ee&&mr?ee.createHTML(C):C;if(y=Ca(C),!y)return Qt?null:mr?ht:""}y&&yo&&Ge(y.firstChild);let Y=Na(Nn?C:y);for(;j=Y.nextNode();)Oa(j),Pa(j),On(j.content)&&xr(j.content);if(Nn)return gt&&Ra(C),C;if(Qt){if(gt&&Ra(y),hr)for($=wu.call(y.ownerDocument);y.firstChild;)$.appendChild(y.firstChild);else $=y;return(le.shadowroot||le.shadowrootmode)&&($=ku.call(r,$,!0)),$}let Oe=_t?y.outerHTML:y.innerHTML;return _t&&ie["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Im,y.ownerDocument.doctype.name)&&(Oe="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
13
- `+Oe),gt&&Tn([ur,dr,pr],Ze=>{Oe=_n(Oe,Ze," ")}),ee&&mr?ee.createHTML(Oe):Oe},e.setConfig=function(){let C=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Ao(C),vo=!0},e.clearConfig=function(){nn=null,vo=!1},e.isValidAttribute=function(C,d,y){nn||Ao({});let A=se(C),j=se(d);return Ma(A,j,y)},e.addHook=function(C,d){typeof d=="function"&&Sn(pe[C],d)},e.removeHook=function(C,d){if(d!==void 0){let y=um(pe[C],d);return y===-1?void 0:dm(pe[C],y,1)[0]}return Pc(pe[C])},e.removeHooks=function(C){pe[C]=[]},e.removeAllHooks=function(){pe=jc()},e}var Zc=Kc();function Js(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Jt=Js();function ru(t){Jt=t}var Yt={exec:()=>null};function An(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=e[r];return i||(i=t(r),e[r]=i),i}}function B(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(Se.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,e)};return r}var Om=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Se={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}}>`))},Mm=/^(?:[ \t]*(?:\n|$))+/,Lm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Pm=/^ {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+|$)/,Dm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Qs=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,iu=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ou=B(iu).replace(/bull/g,Qs).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(),Um=B(iu).replace(/bull/g,Qs).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(),ea=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Hm=/^[^\n]+/,ta=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Gm=B(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ta).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Fm=B(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Qs).getRegex(),no="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",na=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,$m=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",na).replace("tag",no).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),su=B(ea).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",no).getRegex(),zm=B(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",su).getRegex(),ra={blockquote:zm,code:Lm,def:Gm,fences:Pm,heading:Dm,hr:rr,html:$m,lheading:ou,list:Fm,newline:Mm,paragraph:su,table:Yt,text:Hm},Yc=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",no).getRegex(),Bm={...ra,lheading:Um,table:Yc,paragraph:B(ea).replace("hr",rr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Yc).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",no).getRegex()},Vm={...ra,html:B(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",na).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:Yt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:B(ea).replace("hr",rr).replace("heading",` *#{1,6} *[^
14
- ]`).replace("lheading",ou).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},jm=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Wm=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,au=/^( {2,}|\\)\n(?!\s*$)/,Xm=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,kn=/[\p{P}\p{S}]/u,ro=/[\s\p{P}\p{S}]/u,ia=/[^\s\p{P}\p{S}]/u,Km=B(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,ro).getRegex(),lu=/(?!~)[\p{P}\p{S}]/u,Zm=/(?!~)[\s\p{P}\p{S}]/u,Ym=/(?:[^\s\p{P}\p{S}]|~)/u,qm=B(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Om?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),cu=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Jm=B(cu,"u").replace(/punct/g,kn).getRegex(),Qm=B(cu,"u").replace(/punct/g,lu).getRegex(),uu="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",eg=B(uu,"gu").replace(/notPunctSpace/g,ia).replace(/punctSpace/g,ro).replace(/punct/g,kn).getRegex(),tg=B(uu,"gu").replace(/notPunctSpace/g,Ym).replace(/punctSpace/g,Zm).replace(/punct/g,lu).getRegex(),ng=B("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ia).replace(/punctSpace/g,ro).replace(/punct/g,kn).getRegex(),rg=B(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,kn).getRegex(),ig="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",og=B(ig,"gu").replace(/notPunctSpace/g,ia).replace(/punctSpace/g,ro).replace(/punct/g,kn).getRegex(),sg=B(/\\(punct)/,"gu").replace(/punct/g,kn).getRegex(),ag=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(),lg=B(na).replace("(?:-->|$)","-->").getRegex(),cg=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",lg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Qi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,ug=B(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",Qi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),du=B(/^!?\[(label)\]\[(ref)\]/).replace("label",Qi).replace("ref",ta).getRegex(),pu=B(/^!?\[(ref)\](?:\[\])?/).replace("ref",ta).getRegex(),dg=B("reflink|nolink(?!\\()","g").replace("reflink",du).replace("nolink",pu).getRegex(),qc=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,oa={_backpedal:Yt,anyPunctuation:sg,autolink:ag,blockSkip:qm,br:au,code:Wm,del:Yt,delLDelim:Yt,delRDelim:Yt,emStrongLDelim:Jm,emStrongRDelimAst:eg,emStrongRDelimUnd:ng,escape:jm,link:ug,nolink:pu,punctuation:Km,reflink:du,reflinkSearch:dg,tag:cg,text:Xm,url:Yt},pg={...oa,link:B(/^!?\[(label)\]\((.*?)\)/).replace("label",Qi).getRegex(),reflink:B(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Qi).getRegex()},Zs={...oa,emStrongRDelimAst:tg,emStrongLDelim:Qm,delLDelim:rg,delRDelim:og,url:B(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",qc).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",qc).getRegex()},fg={...Zs,br:B(au).replace("{2,}","*").getRegex(),text:B(Zs.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ji={normal:ra,gfm:Bm,pedantic:Vm},tr={normal:oa,gfm:Zs,breaks:fg,pedantic:pg},hg={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Jc=t=>hg[t];function ot(t,e){if(e){if(Se.escapeTest.test(t))return t.replace(Se.escapeReplace,Jc)}else if(Se.escapeTestNoEncode.test(t))return t.replace(Se.escapeReplaceNoEncode,Jc);return t}function Qc(t){try{t=encodeURI(t).replace(Se.percentDecode,"%")}catch{return null}return t}function eu(t,e){let n=t.replace(Se.findPipe,(o,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(Se.splitPipe),i=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(;i<r.length;i++)r[i]=r[i].trim().replace(Se.slashPipe,"|");return r}function St(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r;){let o=t.charAt(r-i-1);if(o===e&&!n)i++;else if(o!==e&&n)i++;else break}return t.slice(0,r-i)}function tu(t){let e=t.split(`
15
- `),n=e.length-1;for(;n>=0&&Se.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
16
- `)}function mg(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 gg(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function nu(t,e,n,r,i){let o=e.href,s=e.title||null,a=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function vg(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
7
+ Patch operations: ${JSON.stringify(d,null,2)}
8
+ Error: ${x}`)}}return f()}case v.MESSAGES_SNAPSHOT:{let h=await K(r,s,a,(d,g,x)=>d.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messages:d}=m,g=new Map(d.map(I=>[I.id,I])),x=d.some(I=>I.role==="reasoning"),w=I=>I.role==="activity"||I.role==="reasoning"&&!x;s=s.filter(I=>w(I)||g.has(I.id)).map(I=>w(I)?I:g.get(I.id));let E=new Set(s.map(I=>I.id));for(let I of d)E.has(I.id)||s.push(I);c({messages:s})}return f()}case v.ACTIVITY_SNAPSHOT:{let h=m,d=s.findIndex(I=>I.id===h.messageId),g=d>=0?s[d]:void 0,x=g?.role==="activity"?g:void 0,w=h.replace??!0,E=await K(r,s,a,(I,D,P)=>I.onActivitySnapshotEvent?.({event:h,messages:D,state:P,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(E),E.stopPropagation!==!0){let I={id:h.messageId,role:"activity",activityType:h.activityType,content:V(h.content)},D;d===-1?(s.push(I),D=I):x?w&&(s[d]={...x,activityType:h.activityType,content:V(h.content)}):w&&(s[d]=I,D=I),c({messages:s}),D&&await Promise.all(r.map(P=>P.onNewMessage?.({message:D,messages:s,state:a,agent:n,input:t})))}return f()}case v.ACTIVITY_DELTA:{let h=m,d=s.findIndex(E=>E.id===h.messageId);if(d===-1)return f();let g=s[d];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${h.messageId}' is not an activity message`),f();let x=g,w=await K(r,s,a,(E,I,D)=>E.onActivityDeltaEvent?.({event:h,messages:I,state:D,agent:n,input:t,activityMessage:x}));if(c(w),w.stopPropagation!==!0)try{let E=V(x.content??{}),I=zr.applyPatch(E,h.patch??[],!0,!1).newDocument;s[d]={...x,content:V(I),activityType:h.activityType},c({messages:s})}catch(E){let I=E instanceof Error?E.message:String(E);console.warn(`Failed to apply activity patch for '${h.messageId}': ${I}`)}return f()}case v.RAW:return c(await K(r,s,a,(h,d,g)=>h.onRawEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.CUSTOM:return c(await K(r,s,a,(h,d,g)=>h.onCustomEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.RUN_STARTED:{let h=await K(r,s,a,(d,g,x)=>d.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let d=m;if(d.input?.messages){for(let g of d.input.messages)s.find(x=>x.id===g.id)||s.push(g);c({messages:s})}}return f()}case v.RUN_FINISHED:{let h=m,d=h.outcome?.type==="interrupt"?{event:h,outcome:"interrupt",interrupts:h.outcome.interrupts}:{event:h,outcome:"success",result:h.result},g=await K(r,s,a,(x,w,E)=>x.onRunFinishedEvent?.({...d,messages:w,state:E,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=d.outcome==="interrupt"?[...d.interrupts]:[]),f()}case v.RUN_ERROR:return c(await K(r,s,a,(h,d,g)=>h.onRunErrorEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.STEP_STARTED:return c(await K(r,s,a,(h,d,g)=>h.onStepStartedEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.STEP_FINISHED:return c(await K(r,s,a,(h,d,g)=>h.onStepFinishedEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();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 f();case v.THINKING_END:return f();case v.THINKING_TEXT_MESSAGE_START:return f();case v.THINKING_TEXT_MESSAGE_CONTENT:return f();case v.THINKING_TEXT_MESSAGE_END:return f();case v.REASONING_START:return c(await K(r,s,a,(h,d,g)=>h.onReasoningStartEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.REASONING_MESSAGE_START:{let h=await K(r,s,a,(d,g,x)=>d.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:d}=m;if(!s.find(g=>g.id===d)){let g={id:d,role:"reasoning",content:""};s.push(g),c({messages:s})}}return f()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:h,delta:d}=m,g=s.find(w=>w.id===h);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${h}'`),f();let x=await K(r,s,a,(w,E,I)=>w.onReasoningMessageContentEvent?.({event:m,messages:E,state:I,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${d}`,c({messages:s})),f()}case v.REASONING_MESSAGE_END:{let{messageId:h}=m,d=s.find(g=>g.id===h);return d?(c(await K(r,s,a,(g,x,w)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:w,agent:n,input:t,reasoningMessageBuffer:typeof d.content=="string"?d.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:d,messages:s,state:a,agent:n,input:t})})),f()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${h}'`),f())}case v.REASONING_MESSAGE_CHUNK:throw Error("REASONING_MESSAGE_CHUNK must be transformed before being applied");case v.REASONING_END:return c(await K(r,s,a,(h,d,g)=>h.onReasoningEndEvent?.({event:m,messages:d,state:g,agent:n,input:t}))),f();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:h,entityId:d,encryptedValue:g}=m,x=await K(r,s,a,(w,E,I)=>w.onReasoningEncryptedValueEvent?.({event:m,messages:E,state:I,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let w=!1;if(h==="tool-call"){for(let E of s)if(E.role==="assistant"&&E.toolCalls){let I=E.toolCalls.find(D=>D.id===d);if(I){I.encryptedValue=g,w=!0;break}}}else{let E=s.find(I=>I.id===d);E?.role!=="activity"&&E&&(E.encryptedValue=g,w=!0)}w&&(l.messages=s)}return f()}}return m.type,f()}),Ts(),r.length>0?ws({}):m=>m)},$s=t=>e=>{let n=Qn(t),r=new Map,i=new Map,o=!1,s=!1,a=!1,l=new Map,c=!1,f=!1,m=!1,b=()=>{r.clear(),i.clear(),l.clear(),c=!1,f=!1,o=!1,s=!1,m=!0};return e.pipe(Ce(h=>{let d=h.type;if(n?.event("VERIFY","Event:",h,{type:h.type}),s)return te(()=>new Q(`Cannot send event type '${d}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(o&&d!==v.RUN_ERROR&&d!==v.RUN_STARTED)return te(()=>new Q(`Cannot send event type '${d}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(d===v.RUN_STARTED){if(m&&!o)return te(()=>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."));o&&b()}}else if(a=!0,d!==v.RUN_STARTED&&d!==v.RUN_ERROR)return te(()=>new Q("First event must be 'RUN_STARTED'"));switch(d){case v.TEXT_MESSAGE_START:{let g=h.messageId;return r.has(g)?te(()=>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),re(h))}case v.TEXT_MESSAGE_CONTENT:{let g=h.messageId;return r.has(g)?re(h):te(()=>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=h.messageId;return r.has(g)?(r.delete(g),re(h)):te(()=>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=h.toolCallId;return i.has(g)?te(()=>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.`)):(i.set(g,!0),re(h))}case v.TOOL_CALL_ARGS:{let g=h.toolCallId;return i.has(g)?re(h):te(()=>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=h.toolCallId;return i.has(g)?(i.delete(g),re(h)):te(()=>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=h.stepName;return l.has(g)?te(()=>new Q(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),re(h))}case v.STEP_FINISHED:{let g=h.stepName;return l.has(g)?(l.delete(g),re(h)):te(()=>new Q(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,re(h);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(i.size>0){let g=Array.from(i.keys()).join(", ");return te(()=>new Q(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return o=!0,re(h);case v.RUN_ERROR:return s=!0,re(h);case v.CUSTOM:return re(h);case v.THINKING_TEXT_MESSAGE_START:return c?f?te(()=>new Q("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(f=!0,re(h)):te(()=>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 f?re(h):te(()=>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 f?(f=!1,re(h)):te(()=>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?te(()=>new Q("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,re(h));case v.THINKING_END:return c?(c=!1,re(h)):te(()=>new Q("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return re(h)}}))},Zt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),Mh=t=>di(()=>qt(t())).pipe(Ss(e=>{if(!e.ok){let i=e.headers.get("content-type")||"";return qt(e.text()).pipe(Ce(o=>{let s=o;if(i.includes("application/json"))try{s=JSON.parse(o)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,te(()=>a)}))}let n={type:Zt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new ee(i=>(i.next(n),(async()=>{try{for(;;){let{done:o,value:s}=await r.read();if(o)break;let a={type:Zt.DATA,data:s};i.next(a)}i.complete()}catch(o){i.error(o)}})(),()=>{r.cancel().catch(o=>{if(o?.name!=="AbortError")throw o})})):te(()=>Error("Failed to getReader() from response"))})),Lh=(t,e)=>{let n=Qn(e),r=new rt,i=new TextDecoder("utf-8",{fatal:!1}),o="";t.subscribe({next:a=>{if(a.type!==Zt.HEADERS&&a.type===Zt.DATA&&a.data){let l=i.decode(a.data,{stream:!0});o+=l;let c=o.split(/\n\n/);o=c.pop()||"";for(let f of c)s(f)}},error:a=>r.error(a),complete:()=>{o&&(o+=i.decode(),s(o)),r.complete()}});function s(a){let l=a.split(`
9
+ `),c=[];for(let f of l)f.startsWith("data:")&&c.push(f.slice(5).replace(/^ /,""));if(c.length>0)try{let f=c.join(`
10
+ `),m=JSON.parse(f);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(f){r.error(f)}}return r.asObservable()},Ph=t=>{let e=new rt,n=new Uint8Array;t.subscribe({next:i=>{if(i.type!==Zt.HEADERS&&i.type===Zt.DATA&&i.data){let o=new Uint8Array(n.length+i.data.length);o.set(n,0),o.set(i.data,n.length),n=o,r()}},error:i=>e.error(i),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 i=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<i)break;try{let o=n.slice(4,i),s=Ic(o);e.next(s),n=n.slice(i)}catch(o){let s=o instanceof Error?o.message:String(o);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},Dh=(t,e)=>{let n=Qn(e),r=new rt,i=new Zr,o=!1;return t.subscribe({next:s=>{if(i.next(s),s.type===Zt.HEADERS&&!o){o=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Us?"protobuf":"sse"}),a===Us?Ph(i).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):Lh(i,n).subscribe({next:l=>{try{let c=Lr.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 o||r.error(Error("No headers event received before data events"))},error:s=>{i.error(s),r.error(s)},complete:()=>{i.complete()}}),r.asObservable()},Y=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),Uh=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Hh=u.object({type:u.literal(Y.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),Gh=u.object({type:u.literal(Y.enum.TextMessageContent),messageId:u.string(),content:u.string()}),Fh=u.object({type:u.literal(Y.enum.TextMessageEnd),messageId:u.string()}),$h=u.object({type:u.literal(Y.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),zh=u.object({type:u.literal(Y.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),Bh=u.object({type:u.literal(Y.enum.ActionExecutionEnd),actionExecutionId:u.string()}),jh=u.object({type:u.literal(Y.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),Vh=u.object({type:u.literal(Y.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()}),Wh=u.object({type:u.literal(Y.enum.MetaEvent),name:Uh,value:u.any()}),qh=u.object({type:u.literal(Y.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[Hh,Gh,Fh,$h,zh,Bh,jh,Vh,Wh,qh]),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 Xh=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
+ `)},Kh=(t,e,n)=>r=>{let i={},o=!0,s=!0,a="",l=null,c=null,f=[],m={},b=h=>{typeof h=="object"&&h&&("messages"in h&&delete h.messages,i=h)};return r.pipe(Ce(h=>{switch(h.type){case v.TEXT_MESSAGE_START:{let d=h;return[{type:Y.enum.TextMessageStart,messageId:d.messageId,role:d.role}]}case v.TEXT_MESSAGE_CONTENT:{let d=h;return[{type:Y.enum.TextMessageContent,messageId:d.messageId,content:d.delta}]}case v.TEXT_MESSAGE_END:{let d=h;return[{type:Y.enum.TextMessageEnd,messageId:d.messageId}]}case v.TOOL_CALL_START:{let d=h;return f.push({id:d.toolCallId,type:"function",function:{name:d.toolCallName,arguments:""}}),s=!0,m[d.toolCallId]=d.toolCallName,[{type:Y.enum.ActionExecutionStart,actionExecutionId:d.toolCallId,actionName:d.toolCallName,parentMessageId:d.parentMessageId}]}case v.TOOL_CALL_ARGS:{let d=h,g=f.find(w=>w.id===d.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${d.toolCallId}'`),[];g.function.arguments+=d.delta;let x=!1;if(c){let w=c.find(E=>E.tool==g.function.name);if(w)try{let E=JSON.parse(hi(g.function.arguments));w.tool_argument&&w.tool_argument in E?(b({...i,[w.state_key]:E[w.tool_argument]}),x=!0):w.tool_argument||(b({...i,[w.state_key]:E}),x=!0)}catch{}}return[{type:Y.enum.ActionExecutionArgs,actionExecutionId:d.toolCallId,args:d.delta},...x?[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}]:[]]}case v.TOOL_CALL_END:{let d=h;return[{type:Y.enum.ActionExecutionEnd,actionExecutionId:d.toolCallId}]}case v.TOOL_CALL_RESULT:{let d=h;return[{type:Y.enum.ActionExecutionResult,actionExecutionId:d.toolCallId,result:d.content,actionName:m[d.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let d=h;switch(d.name){case"Exit":o=!1;break;case"PredictState":c=d.value;break}return[{type:Y.enum.MetaEvent,name:d.name,value:d.value}]}case v.STATE_SNAPSHOT:return b(h.snapshot),[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}];case v.STATE_DELTA:{let d=h,g=zr.applyPatch(i,d.delta,!0,!1);return g?(b(g.newDocument),[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=h.messages,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify({...i,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(i.messages=l),Object.keys(i).length===0?[]:[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify({...i,...l?{messages:Zh(l)}:{}}),active:!1}];case v.RUN_ERROR:{let d=h;return[{type:Y.enum.RunError,message:d.message,code:d.code}]}case v.STEP_STARTED:return a=h.stepName,f=[],c=null,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:!0}];case v.STEP_FINISHED:return f=[],c=null,[{type:Y.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:o,role:"assistant",state:JSON.stringify(i),active:!1}];default:return[]}}))};function Zh(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Xh(n.content);if(r){let i={id:n.id,role:n.role,content:r};e.push(i)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let i of n.toolCalls){let o={id:i.id,name:i.function.name,arguments:JSON.parse(i.function.arguments),parentMessageId:n.id};e.push(o)}}else if(n.role==="tool"){let r="unknown";for(let o of t)if(o.role==="assistant"&&o.toolCalls?.length){for(let s of o.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let i={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(i)}return e}var Zi=t=>e=>{let n=Qn(t),r,i,o,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(!i||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:i.toolCallId};return s=void 0,i=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!o||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:o.messageId};return s=void 0,o=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},f=()=>s==="text"?[a()]:s==="tool"?[l()]:s==="reasoning"?[c()]:[];return e.pipe(Ce(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[...f(),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 b=m,h=[];if((s!=="text"||b.messageId!==void 0&&b.messageId!==r?.messageId)&&h.push(...f()),s!=="text"){if(b.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:b.messageId,name:b.name},s="text";let E={type:v.TEXT_MESSAGE_START,messageId:b.messageId,role:b.role||"assistant",...b.name!==void 0&&{name:b.name}};h.push(E),n?.event("TRANSFORM","TEXT_MESSAGE_START",E,{messageId:b.messageId})}if(b.delta!==void 0){let E={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:b.delta};h.push(E),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",E,{messageId:r.messageId})}return h;case v.TOOL_CALL_CHUNK:let d=m,g=[];if((s!=="tool"||d.toolCallId!==void 0&&d.toolCallId!==i?.toolCallId)&&g.push(...f()),s!=="tool"){if(d.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(d.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");i={toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId},s="tool";let E={type:v.TOOL_CALL_START,toolCallId:d.toolCallId,toolCallName:d.toolCallName,parentMessageId:d.parentMessageId};g.push(E),n?.event("TRANSFORM","TOOL_CALL_START",E,{toolCallId:d.toolCallId,toolCallName:d.toolCallName})}if(d.delta!==void 0){let E={type:v.TOOL_CALL_ARGS,toolCallId:i.toolCallId,delta:d.delta};g.push(E),n?.event("TRANSFORM","TOOL_CALL_ARGS",E,{toolCallId:i.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let x=m,w=[];if((s!=="reasoning"||x.messageId&&x.messageId!==o?.messageId)&&w.push(...f()),s!=="reasoning"){if(x.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");o={messageId:x.messageId},s="reasoning";let E={type:v.REASONING_MESSAGE_START,messageId:x.messageId};w.push(E),n?.event("TRANSFORM","REASONING_MESSAGE_START",E,{messageId:x.messageId})}if(x.delta!==void 0){let E={type:v.REASONING_MESSAGE_CONTENT,messageId:o.messageId,delta:x.delta};w.push(E),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",E,{messageId:o.messageId})}return w}return m.type,[]}),Kt(()=>{f()}))};function Yh(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function Gc(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),i=[...n].filter(s=>!r.has(s));if(i.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${i.join(", ")}`);let o=[...r].filter(s=>!n.has(s));if(o.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${o.join(", ")}`);return t.map(s=>{let a=e[s.id];if(a.status==="resolved"){let l={interruptId:s.id,status:"resolved"};return a.payload!==void 0&&(l.payload=a.payload),l}return{interruptId:s.id,status:"cancelled"}})}var Yi=class{runNext(t,e){return e.run(t).pipe(Zi(!1))}runNextWithState(t,e){let n=V(t.messages||[]),r=V(t.state||{}),i=new Zr;return Hc(t,i,e,[]).subscribe(o=>{o.messages!==void 0&&(n=o.messages),o.state!==void 0&&(r=o.state)}),this.runNext(t,e).pipe(pi(async o=>(i.next(o),await new Promise(s=>setTimeout(s,0)),{event:o,messages:V(n),state:V(r)})))}},Jh=class extends Yi{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Qh(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 em=class extends Yi{run(t,e){let{parentRunId:n,...r}=t,i={...r,messages:r.messages.map(Qh)};return this.runNext(i,e)}},Mc="THINKING_START",Lc="THINKING_END",Pc="THINKING_TEXT_MESSAGE_START",Dc="THINKING_TEXT_MESSAGE_CONTENT",Uc="THINKING_TEXT_MESSAGE_END",tm=class extends Yi{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(Xt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Mc:{this.currentReasoningId=Oe();let{title:e,...n}=t;return this.warnAboutTransformation(Mc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Pc:return this.currentMessageId=Oe(),this.warnAboutTransformation(Pc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Dc:{let{delta:e,...n}=t;return this.warnAboutTransformation(Dc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Oe(),delta:e}}case Uc:{let e=this.currentMessageId??Oe();return this.warnAboutTransformation(Uc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Lc:{let e=this.currentReasoningId??Oe();return this.warnAboutTransformation(Lc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function nm(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function rm(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function im(t){let e=nm(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 om(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>rm(r)?im(r):r);return{...t,content:n}}var sm=class extends Yi{run(t,e){let n={...t,messages:t.messages.map(om)};return this.runNext(n,e)}},am="0.0.57",lm=class{get maxVersion(){return am}get debug(){return this._debug}set debug(t){this._debug=Ki(t),this._debugLogger=Fs(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Fs(Ki(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:i,debug:o}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??bt(),this.messages=V(r??[]),this.state=V(i??{}),this._debug=Ki(o),this._debugLogger=Fs(this._debug),Jn(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new em),Jn(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new tm),Jn(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new sm)}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 Jh(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??bt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,i=new Set(this.messages.map(l=>l.id)),o=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,o),this.activeRunDetach$=new rt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ui(Kr(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:f=>c.run(f,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),Zi(this.debugLogger),$s(this.debugLogger),l=>l.pipe(fi(this.activeRunDetach$)),l=>this.apply(n,l,o),l=>this.processApplyEvents(n,l,o),Kn(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,o))),Kt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(re(null)));let a=V(this.messages).filter(l=>!i.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new cs}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??bt();let n=this.prepareRunAgentInput(t),r,i=new Set(this.messages.map(l=>l.id)),o=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,o),this.activeRunDetach$=new rt;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await ui(Kr(()=>di(()=>this.connect(n)),Zi(this.debugLogger),$s(this.debugLogger),l=>l.pipe(fi(this.activeRunDetach$)),l=>this.apply(n,l,o),l=>this.processApplyEvents(n,l,o),Kn(l=>(this.isRunning=!1,l instanceof cs?Yr:this.onError(n,l,o))),Kt(()=>{this.isRunning=!1,this.onFinalize(n,o),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(re(null)),{defaultValue:void 0});let a=V(this.messages).filter(l=>!i.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 Hc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(_s(r=>{r.messages&&(this.messages=r.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=V(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||bt(),tools:V(t?.tools??[]),context:V(t?.context??[]),forwardedProps:V(t?.forwardedProps??{}),state:V(this.state),messages:e,...t?.resume===void 0?{}:{resume:V(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(o=>o.interruptId)),i=this.pendingInterrupts.map(o=>o.id).filter(o=>!r.has(o));if(i.length>0)throw new Q(`Thread has ${i.length} pending interrupt(s) not addressed by resume: ${i.join(", ")}`);for(let o of this.pendingInterrupts)if(Yh(o))throw new Q(`Interrupt ${o.id} expired at ${o.expiresAt}`)}let n=await K(e,this.messages,this.state,(r,i,o)=>r.onRunInitialized?.({messages:i,state:o,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 qt(K(n,this.messages,this.state,(r,i,o)=>r.onRunFailed?.({error:e,messages:i,state:o,agent:this,input:t}))).pipe(Xt(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),i.state!==void 0&&(this.state=i.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),i.stopPropagation!==!0){let o=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||o==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await K(e,this.messages,this.state,(r,i,o)=>r.onRunFinalized?.({messages:i,state:o,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=V(this.messages),t.state=V(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=V(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=V(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=V(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??bt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:i=>r.run(i,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(Zi(this.debugLogger),$s(this.debugLogger),Kh(this.threadId,e.runId,this.agentId),n=>n.pipe(Xt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},Fc=class extends lm{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=V(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return Dh(Mh(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=V(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 Ji=class{element;#n;#e;#t=[];constructor(e){this.#n=e,this.#e=e.strings??ne,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:Oe(),file:e,status:Le.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#i(e);if(r!==null){n.status=Le.ERROR,n.error=r,this.#s(),this.#n.onChange?.();return}this.#s(),this.#n.onChange?.(),this.#r(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===Le.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Le.UPLOADING),this.#s()}clear(){for(let e of this.#t)e.controller?.abort();this.#t=[],this.#s()}dispose(){for(let e of this.#t)e.controller?.abort()}#i(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",Ar(this.#n.maxBytes)):cm(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#i(e.file);if(n!==null){e.status=Le.ERROR,e.error=n,this.#s(),this.#n.onChange?.();return}e.status=Le.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#s(),this.#n.upload(e.file,i=>{e.progress=i,this.#s()},r.signal).then(i=>{e.status=Le.READY,e.ref=i}).catch(i=>{e.status=Le.ERROR,e.error=i instanceof Error?i.message:this.#e.uploadFailed}).finally(()=>{e.controller=null,this.#s(),this.#n.onChange?.()})}#a(e){e.controller?.abort(),this.#t=this.#t.filter(n=>n!==e),this.#s(),this.#n.onChange?.()}#s(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#o(e))}#o(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.textContent=ns(e.file.type),r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.className="attachment-chip-name",i.setAttribute("part","attachment-chip-name"),i.textContent=e.file.name,i.title=e.file.name;let o=document.createElement("span");if(o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=e.status===Le.ERROR?e.error:Ar(e.file.size),n.append(r,i,o),e.status===Le.UPLOADING){let a=document.createElement("div");a.className="attachment-chip-bar",a.setAttribute("part","attachment-chip-bar");let l=document.createElement("div");l.className="attachment-chip-bar-fill",l.setAttribute("part","attachment-chip-bar-fill"),l.style.width=`${Math.round(e.progress*100)}%`,a.appendChild(l),n.appendChild(a)}if(e.status===Le.ERROR){let a=document.createElement("button");a.type="button",a.className="attachment-chip-retry",a.setAttribute("part","attachment-chip-retry"),a.title=this.#e.retry,a.setAttribute("aria-label",this.#e.retryUpload),a.textContent="\u21BB",a.addEventListener("click",()=>this.#r(e)),n.appendChild(a)}let s=document.createElement("button");return s.type="button",s.className="attachment-chip-remove",s.setAttribute("part","attachment-chip-remove"),s.title=this.#e.remove,s.setAttribute("aria-label",this.#e.removeAttachment),s.textContent="\u2715",s.addEventListener("click",()=>this.#a(e)),n.appendChild(s),n}};function cm(t,e){let n=t.split(",").map(o=>o.trim().toLowerCase()).filter(o=>o!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),i=e.name.toLowerCase();return n.some(o=>o.startsWith(".")?i.endsWith(o):o.endsWith("/*")?r.startsWith(o.slice(0,-1)):r===o)}function Qi(t,e=Date.now(),n=ne){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let i=Math.round(r/60);if(i<60)return n.minutesAgo.replace("{n}",String(i));let o=Math.round(i/60);if(o<24)return n.hoursAgo.replace("{n}",String(o));let s=Math.round(o/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}var er=class{element;#n;#e;#t;#i;#r=[];constructor(e,n=ne){this.#n=e,this.#i=n,this.element=document.createElement("div"),this.element.className="checkpoints",this.element.setAttribute("part","checkpoints"),this.element.setAttribute("role","dialog"),this.element.setAttribute("aria-label",n.checkpoints),this.element.hidden=!0;let r=document.createElement("div");r.className="checkpoints-header",r.setAttribute("part","checkpoints-header"),this.#t=document.createElement("span"),this.#t.className="checkpoints-title",this.#t.textContent=n.checkpoints,r.append(this.#t),this.#e=document.createElement("div"),this.#e.className="checkpoints-list",this.#e.setAttribute("part","checkpoints-list"),this.element.append(r,this.#e),this.element.addEventListener("keydown",i=>{i.key==="Escape"&&(i.stopPropagation(),this.close())})}setRuns(e){this.#r=e,this.#a()}setStrings(e){this.#i=e,this.element.setAttribute("aria-label",e.checkpoints),this.#t.textContent=e.checkpoints,this.#a()}open(){this.element.hidden=!1}close(){this.element.hidden=!0}get open_(){return!this.element.hidden}#a(){if(this.#e.replaceChildren(),this.#r.length===0){let e=document.createElement("div");e.className="checkpoints-empty",e.setAttribute("part","checkpoints-empty"),e.textContent=this.#i.noCheckpoints,this.#e.append(e);return}for(let e of this.#r)this.#e.append(this.#s(e))}#s(e){let n=document.createElement("div");n.className="checkpoint-row",n.setAttribute("part","checkpoint-row");let r=document.createElement("span");if(r.className="checkpoint-label",r.textContent=e.started_at===null?e.run_id:Qi(Date.parse(e.started_at),Date.now(),this.#i),r.title=e.run_id,n.append(r),e.parent_run_id!==null){let i=document.createElement("span");i.className="checkpoint-branch",i.setAttribute("part","checkpoint-branch"),i.textContent=this.#i.forkedRun,i.title=e.parent_run_id,n.append(i)}return n.append(this.#o(e.run_id,"resume",this.#i.resumeRun),this.#o(e.run_id,"fork",this.#i.forkRun)),n}#o(e,n,r){let i=document.createElement("button");return i.type="button",i.className=`checkpoint-action checkpoint-${n}`,i.setAttribute("part",`checkpoint-action checkpoint-${n}`),i.textContent=r,i.addEventListener("click",()=>{this.close(),this.#n(e,n)}),i}};function $c(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 js(t,e,n={}){let r=n.strings??ne;return new Promise(i=>{let o=document.createElement("div");o.className="confirm",o.setAttribute("part","confirm"),o.setAttribute("data-tool-name",e.toolName),o.setAttribute("role","group"),o.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=$c("cancel",r.cancel),f=$c("confirm",r.confirm),m=!1,b=h=>{m||(m=!0,c.disabled=!0,f.disabled=!0,o.setAttribute("data-resolved",h?"confirmed":"declined"),i(h))};if(c.addEventListener("click",()=>b(!1)),f.addEventListener("click",()=>b(!0)),n.signal?.addEventListener("abort",()=>b(!1),{once:!0}),l.append(c,f),o.append(s,a,l),t.appendChild(o),n.signal?.aborted===!0){b(!1);return}f.focus()})}function Vs(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function um(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function Ws(t,e,n={}){let r=n.strings??ne,i=e.options??[],o=i.length>0,s=!o||e.allowCustom===!0;return new Promise(a=>{let l=document.createElement("div");l.className="question",l.setAttribute("part","question"),l.setAttribute("role","group"),l.setAttribute("aria-label",r.askUserAction);let c=document.createElement("div");c.className="question-body",c.setAttribute("part","question-body"),c.textContent=e.question;let f=document.createElement("div");f.className="question-options",f.setAttribute("part","question-options");let m=`q-${i.length}-${e.question.length}`,b=[];for(let P of i){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice");let Se=document.createElement("input");Se.type="radio",Se.name=m,Se.value=P,Se.setAttribute("part","question-radio");let mt=document.createElement("span");mt.setAttribute("part","question-choice-text"),mt.textContent=P,U.append(Se,mt),f.appendChild(U),b.push(Se)}let h=null,d=null;if(s){if(d=um(r.answerPlaceholder),o){let P=document.createElement("label");P.className="question-choice",P.setAttribute("part","question-choice"),h=document.createElement("input"),h.type="radio",h.name=m,h.value="",h.setAttribute("part","question-radio");let U=document.createElement("span");U.setAttribute("part","question-choice-text"),U.textContent=r.otherOption,P.append(h,U),f.appendChild(P),d.disabled=!0}f.appendChild(d)}let g=document.createElement("div");g.className="question-actions",g.setAttribute("part","question-actions");let x=document.createElement("button");x.type="button",x.className="question-btn",x.setAttribute("part","question-button"),x.textContent=r.submit,g.appendChild(x);let w=!1,E=()=>{let P=b.find(U=>U.checked);if(P!==void 0)return P.value;if(d!==null&&(h===null||h.checked)){let U=d.value.trim();return U===""?null:U}return null},I=()=>{d!==null&&h!==null&&(d.disabled=!h.checked),x.disabled=E()===null},D=P=>{if(!w){w=!0,x.disabled=!0;for(let U of b)U.disabled=!0;h!==null&&(h.disabled=!0),d!==null&&(d.disabled=!0),l.setAttribute("data-resolved",P===""?"cancelled":"answered"),a(P)}};for(let P of[...b,...h!==null?[h]:[]])P.addEventListener("change",I);if(d?.addEventListener("input",I),d?.addEventListener("keydown",P=>{if(P.key==="Enter"){P.preventDefault();let U=E();U!==null&&D(U)}}),x.addEventListener("click",()=>{let P=E();P!==null&&D(P)}),n.signal?.addEventListener("abort",()=>D(""),{once:!0}),l.append(c,f,g),t.appendChild(l),n.signal?.aborted===!0){D("");return}I(),(o?b[0]:d)?.focus()})}function zc(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 dm(t){if(Array.isArray(t))return t}function pm(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,i,o,s,a=[],l=!0,c=!1;try{if(o=(n=n.call(t)).next,e!==0)for(;!(l=(r=o.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(f){c=!0,i=f}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw i}}return a}}function fm(){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 hm(t,e){return dm(t)||pm(t,e)||mm(t,e)||fm()}function mm(t,e){if(t){if(typeof t=="string")return zc(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)?zc(t,e):void 0}}var tu=Object.entries,Bc=Object.setPrototypeOf,gm=Object.isFrozen,vm=Object.getPrototypeOf,bm=Object.getOwnPropertyDescriptor,Ae=Object.freeze,Ge=Object.seal,An=Object.create,nu=typeof Reflect<"u"&&Reflect,Js=nu.apply,Qs=nu.construct;Ae||(Ae=function(e){return e});Ge||(Ge=function(e){return e});Js||(Js=function(e,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),o=2;o<r;o++)i[o-2]=arguments[o];return e.apply(n,i)});Qs||(Qs=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return new e(...r)});var wn=pe(Array.prototype.forEach),ym=pe(Array.prototype.lastIndexOf),jc=pe(Array.prototype.pop),Sn=pe(Array.prototype.push),xm=pe(Array.prototype.splice),_e=Array.isArray,rr=pe(String.prototype.toLowerCase),qs=pe(String.prototype.toString),Vc=pe(String.prototype.match),_n=pe(String.prototype.replace),Wc=pe(String.prototype.indexOf),Em=pe(String.prototype.trim),Tm=pe(Number.prototype.toString),wm=pe(Boolean.prototype.toString),qc=typeof BigInt>"u"?null:pe(BigInt.prototype.toString),Xc=typeof Symbol>"u"?null:pe(Symbol.prototype.toString),oe=pe(Object.prototype.hasOwnProperty),tr=pe(Object.prototype.toString),xe=pe(RegExp.prototype.test),nr=Sm(TypeError);function pe(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return Js(t,e,r)}}function Sm(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return Qs(t,n)}}function F(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:rr;if(Bc&&Bc(t,null),!_e(e))return t;let r=e.length;for(;r--;){let i=e[r];if(typeof i=="string"){let o=n(i);o!==i&&(gm(e)||(e[r]=o),i=o)}t[i]=!0}return t}function _m(t){for(let e=0;e<t.length;e++)oe(t,e)||(t[e]=null);return t}function Te(t){let e=An(null);for(let r of tu(t)){var n=hm(r,2);let i=n[0],o=n[1];oe(t,i)&&(_e(o)?e[i]=_m(o):o&&typeof o=="object"&&o.constructor===Object?e[i]=Te(o):e[i]=o)}return e}function Am(t){switch(typeof t){case"string":return t;case"number":return Tm(t);case"boolean":return wm(t);case"bigint":return qc?qc(t):"0";case"symbol":return Xc?Xc(t):"Symbol()";case"undefined":return tr(t);case"function":case"object":{if(t===null)return tr(t);let e=t,n=ot(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:tr(r)}return tr(t)}default:return tr(t)}}function ot(t,e){for(;t!==null;){let r=bm(t,e);if(r){if(r.get)return pe(r.get);if(typeof r.value=="function")return pe(r.value)}t=vm(t)}function n(){return null}return n}function km(t){try{return xe(t,""),!0}catch{return!1}}var Kc=Ae(["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"]),Xs=Ae(["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"]),Ks=Ae(["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"]),Im=Ae(["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"]),Zs=Ae(["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"]),Cm=Ae(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Zc=Ae(["#text"]),Yc=Ae(["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"]),Ys=Ae(["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"]),Jc=Ae(["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"]),eo=Ae(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Nm=Ge(/{{[\w\W]*|^[\w\W]*}}/g),Rm=Ge(/<%[\w\W]*|^[\w\W]*%>/g),Om=Ge(/\${[\w\W]*/g),Mm=Ge(/^data-[\-\w.\u00B7-\uFFFF]+$/),Lm=Ge(/^aria-[\-\w]+$/),Qc=Ge(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Pm=Ge(/^(?:\w+script|data):/i),Dm=Ge(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Um=Ge(/^html$/i),Hm=Ge(/^[a-z][.\w]*(-[.\w]+)+$/i),it={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Gm=function(){return typeof window>"u"?null:window},Fm=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,i="data-tt-policy-suffix";n&&n.hasAttribute(i)&&(r=n.getAttribute(i));let o="dompurify"+(r?"#"+r:"");try{return e.createPolicy(o,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+o+" could not be created."),null}},eu=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function ru(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Gm(),e=N=>ru(N);if(e.version="3.4.7",e.removed=[],!t||!t.document||t.document.nodeType!==it.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,i=r.currentScript;t.DocumentFragment;let o=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let f=t.DOMParser,m=t.trustedTypes,b=a.prototype,h=ot(b,"cloneNode"),d=ot(b,"remove"),g=ot(b,"nextSibling"),x=ot(b,"childNodes"),w=ot(b,"parentNode"),E=ot(b,"shadowRoot"),I=ot(b,"attributes"),D=s&&s.prototype?ot(s.prototype,"nodeType"):null,P=s&&s.prototype?ot(s.prototype,"nodeName"):null;if(typeof o=="function"){let N=n.createElement("template");N.content&&N.content.ownerDocument&&(n=N.content.ownerDocument)}let U,Se="",mt=n,go=mt.implementation,ya=mt.createNodeIterator,Mu=mt.createDocumentFragment,Lu=mt.getElementsByTagName,Pu=r.importNode,fe=eu();e.isSupported=typeof tu=="function"&&typeof w=="function"&&go&&go.createHTMLDocument!==void 0;let pr=Nm,fr=Rm,hr=Om,Du=Mm,Uu=Lm,Hu=Pm,xa=Dm,Gu=Hm,Ea=Qc,se=null,vo=F({},[...Kc,...Xs,...Ks,...Zs,...Zc]),ue=null,bo=F({},[...Yc,...Ys,...Jc,...eo]),ae=Object.seal(An(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}})),Nn=null,mr=null,gt=Object.seal(An(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Ta=!0,yo=!0,wa=!1,Sa=!0,vt=!1,Rn=!0,_t=!1,xo=!1,Eo=!1,en=!1,gr=!1,vr=!1,_a=!0,Aa=!1,ka="user-content-",To=!0,On=!1,tn={},Xe=null,wo=F({},["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"]),Ia=null,Ca=F({},["audio","video","img","source","image","track"]),So=null,Na=F({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),br="http://www.w3.org/1998/Math/MathML",yr="http://www.w3.org/2000/svg",Ke="http://www.w3.org/1999/xhtml",nn=Ke,_o=!1,Ao=null,Fu=F({},[br,yr,Ke],qs),ko=F({},["mi","mo","mn","ms","mtext"]),Io=F({},["annotation-xml"]),$u=F({},["title","style","font","a","script"]),Mn=null,zu=["application/xhtml+xml","text/html"],Bu="text/html",le=null,rn=null,ju=n.createElement("form"),Ra=function(p){return p instanceof RegExp||p instanceof Function},Co=function(){let p=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(rn&&rn===p)return;(!p||typeof p!="object")&&(p={}),p=Te(p),Mn=zu.indexOf(p.PARSER_MEDIA_TYPE)===-1?Bu:p.PARSER_MEDIA_TYPE,le=Mn==="application/xhtml+xml"?qs:rr,se=oe(p,"ALLOWED_TAGS")&&_e(p.ALLOWED_TAGS)?F({},p.ALLOWED_TAGS,le):vo,ue=oe(p,"ALLOWED_ATTR")&&_e(p.ALLOWED_ATTR)?F({},p.ALLOWED_ATTR,le):bo,Ao=oe(p,"ALLOWED_NAMESPACES")&&_e(p.ALLOWED_NAMESPACES)?F({},p.ALLOWED_NAMESPACES,qs):Fu,So=oe(p,"ADD_URI_SAFE_ATTR")&&_e(p.ADD_URI_SAFE_ATTR)?F(Te(Na),p.ADD_URI_SAFE_ATTR,le):Na,Ia=oe(p,"ADD_DATA_URI_TAGS")&&_e(p.ADD_DATA_URI_TAGS)?F(Te(Ca),p.ADD_DATA_URI_TAGS,le):Ca,Xe=oe(p,"FORBID_CONTENTS")&&_e(p.FORBID_CONTENTS)?F({},p.FORBID_CONTENTS,le):wo,Nn=oe(p,"FORBID_TAGS")&&_e(p.FORBID_TAGS)?F({},p.FORBID_TAGS,le):Te({}),mr=oe(p,"FORBID_ATTR")&&_e(p.FORBID_ATTR)?F({},p.FORBID_ATTR,le):Te({}),tn=oe(p,"USE_PROFILES")?p.USE_PROFILES&&typeof p.USE_PROFILES=="object"?Te(p.USE_PROFILES):p.USE_PROFILES:!1,Ta=p.ALLOW_ARIA_ATTR!==!1,yo=p.ALLOW_DATA_ATTR!==!1,wa=p.ALLOW_UNKNOWN_PROTOCOLS||!1,Sa=p.ALLOW_SELF_CLOSE_IN_ATTR!==!1,vt=p.SAFE_FOR_TEMPLATES||!1,Rn=p.SAFE_FOR_XML!==!1,_t=p.WHOLE_DOCUMENT||!1,en=p.RETURN_DOM||!1,gr=p.RETURN_DOM_FRAGMENT||!1,vr=p.RETURN_TRUSTED_TYPE||!1,Eo=p.FORCE_BODY||!1,_a=p.SANITIZE_DOM!==!1,Aa=p.SANITIZE_NAMED_PROPS||!1,To=p.KEEP_CONTENT!==!1,On=p.IN_PLACE||!1,Ea=km(p.ALLOWED_URI_REGEXP)?p.ALLOWED_URI_REGEXP:Qc,nn=typeof p.NAMESPACE=="string"?p.NAMESPACE:Ke,ko=oe(p,"MATHML_TEXT_INTEGRATION_POINTS")&&p.MATHML_TEXT_INTEGRATION_POINTS&&typeof p.MATHML_TEXT_INTEGRATION_POINTS=="object"?Te(p.MATHML_TEXT_INTEGRATION_POINTS):F({},["mi","mo","mn","ms","mtext"]),Io=oe(p,"HTML_INTEGRATION_POINTS")&&p.HTML_INTEGRATION_POINTS&&typeof p.HTML_INTEGRATION_POINTS=="object"?Te(p.HTML_INTEGRATION_POINTS):F({},["annotation-xml"]);let y=oe(p,"CUSTOM_ELEMENT_HANDLING")&&p.CUSTOM_ELEMENT_HANDLING&&typeof p.CUSTOM_ELEMENT_HANDLING=="object"?Te(p.CUSTOM_ELEMENT_HANDLING):An(null);if(ae=An(null),oe(y,"tagNameCheck")&&Ra(y.tagNameCheck)&&(ae.tagNameCheck=y.tagNameCheck),oe(y,"attributeNameCheck")&&Ra(y.attributeNameCheck)&&(ae.attributeNameCheck=y.attributeNameCheck),oe(y,"allowCustomizedBuiltInElements")&&typeof y.allowCustomizedBuiltInElements=="boolean"&&(ae.allowCustomizedBuiltInElements=y.allowCustomizedBuiltInElements),vt&&(yo=!1),gr&&(en=!0),tn&&(se=F({},Zc),ue=An(null),tn.html===!0&&(F(se,Kc),F(ue,Yc)),tn.svg===!0&&(F(se,Xs),F(ue,Ys),F(ue,eo)),tn.svgFilters===!0&&(F(se,Ks),F(ue,Ys),F(ue,eo)),tn.mathMl===!0&&(F(se,Zs),F(ue,Jc),F(ue,eo))),gt.tagCheck=null,gt.attributeCheck=null,oe(p,"ADD_TAGS")&&(typeof p.ADD_TAGS=="function"?gt.tagCheck=p.ADD_TAGS:_e(p.ADD_TAGS)&&(se===vo&&(se=Te(se)),F(se,p.ADD_TAGS,le))),oe(p,"ADD_ATTR")&&(typeof p.ADD_ATTR=="function"?gt.attributeCheck=p.ADD_ATTR:_e(p.ADD_ATTR)&&(ue===bo&&(ue=Te(ue)),F(ue,p.ADD_ATTR,le))),oe(p,"ADD_URI_SAFE_ATTR")&&_e(p.ADD_URI_SAFE_ATTR)&&F(So,p.ADD_URI_SAFE_ATTR,le),oe(p,"FORBID_CONTENTS")&&_e(p.FORBID_CONTENTS)&&(Xe===wo&&(Xe=Te(Xe)),F(Xe,p.FORBID_CONTENTS,le)),oe(p,"ADD_FORBID_CONTENTS")&&_e(p.ADD_FORBID_CONTENTS)&&(Xe===wo&&(Xe=Te(Xe)),F(Xe,p.ADD_FORBID_CONTENTS,le)),To&&(se["#text"]=!0),_t&&F(se,["html","head","body"]),se.table&&(F(se,["tbody"]),delete Nn.tbody),p.TRUSTED_TYPES_POLICY){if(typeof p.TRUSTED_TYPES_POLICY.createHTML!="function")throw nr('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof p.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw nr('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');U=p.TRUSTED_TYPES_POLICY,Se=U.createHTML("")}else U===void 0&&(U=Fm(m,i)),U!==null&&typeof Se=="string"&&(Se=U.createHTML(""));(fe.uponSanitizeElement.length>0||fe.uponSanitizeAttribute.length>0)&&se===vo&&(se=Te(se)),fe.uponSanitizeAttribute.length>0&&ue===bo&&(ue=Te(ue)),Ae&&Ae(p),rn=p},Oa=F({},[...Xs,...Ks,...Im]),Ma=F({},[...Zs,...Cm]),Vu=function(p){let y=w(p);(!y||!y.tagName)&&(y={namespaceURI:nn,tagName:"template"});let A=rr(p.tagName),X=rr(y.tagName);return Ao[p.namespaceURI]?p.namespaceURI===yr?y.namespaceURI===Ke?A==="svg":y.namespaceURI===br?A==="svg"&&(X==="annotation-xml"||ko[X]):!!Oa[A]:p.namespaceURI===br?y.namespaceURI===Ke?A==="math":y.namespaceURI===yr?A==="math"&&Io[X]:!!Ma[A]:p.namespaceURI===Ke?y.namespaceURI===yr&&!Io[X]||y.namespaceURI===br&&!ko[X]?!1:!Ma[A]&&($u[A]||!Oa[A]):!!(Mn==="application/xhtml+xml"&&Ao[p.namespaceURI]):!1},Fe=function(p){Sn(e.removed,{element:p});try{w(p).removeChild(p)}catch{d(p)}},At=function(p,y){try{Sn(e.removed,{attribute:y.getAttributeNode(p),from:y})}catch{Sn(e.removed,{attribute:null,from:y})}if(y.removeAttribute(p),p==="is")if(en||gr)try{Fe(y)}catch{}else try{y.setAttribute(p,"")}catch{}},La=function(p){let y=null,A=null;if(Eo)p="<remove></remove>"+p;else{let J=Vc(p,/^[\r\n\t ]+/);A=J&&J[0]}Mn==="application/xhtml+xml"&&nn===Ke&&(p='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+p+"</body></html>");let X=U?U.createHTML(p):p;if(nn===Ke)try{y=new f().parseFromString(X,Mn)}catch{}if(!y||!y.documentElement){y=go.createDocument(nn,"template",null);try{y.documentElement.innerHTML=_o?Se:X}catch{}}let j=y.body||y.documentElement;return p&&A&&j.insertBefore(n.createTextNode(A),j.childNodes[0]||null),nn===Ke?Lu.call(y,_t?"html":"body")[0]:_t?y.documentElement:j},Pa=function(p){return ya.call(p.ownerDocument||p,p,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Da=function(p){p.normalize();let y=ya.call(p.ownerDocument||p,p,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),A=y.nextNode();for(;A;){let X=A.data;wn([pr,fr,hr],j=>{X=_n(X,j," ")}),A.data=X,A=y.nextNode()}},xr=function(p){let y=P?P(p):null;return typeof y!="string"||le(y)!=="form"?!1:typeof p.nodeName!="string"||typeof p.textContent!="string"||typeof p.removeChild!="function"||p.attributes!==I(p)||typeof p.removeAttribute!="function"||typeof p.setAttribute!="function"||typeof p.namespaceURI!="string"||typeof p.insertBefore!="function"||typeof p.hasChildNodes!="function"||p.nodeType!==D(p)||p.childNodes!==x(p)},Ln=function(p){if(!D||typeof p!="object"||p===null)return!1;try{return D(p)===it.documentFragment}catch{return!1}},Er=function(p){if(!D||typeof p!="object"||p===null)return!1;try{return typeof D(p)=="number"}catch{return!1}};function at(N,p,y){wn(N,A=>{A.call(e,p,y,rn)})}let Ua=function(p){let y=null;if(at(fe.beforeSanitizeElements,p,null),xr(p))return Fe(p),!0;let A=le(p.nodeName);if(at(fe.uponSanitizeElement,p,{tagName:A,allowedTags:se}),Rn&&p.hasChildNodes()&&!Er(p.firstElementChild)&&xe(/<[/\w!]/g,p.innerHTML)&&xe(/<[/\w!]/g,p.textContent)||Rn&&p.namespaceURI===Ke&&A==="style"&&Er(p.firstElementChild)||p.nodeType===it.progressingInstruction||Rn&&p.nodeType===it.comment&&xe(/<[/\w]/g,p.data))return Fe(p),!0;if(Nn[A]||!(gt.tagCheck instanceof Function&&gt.tagCheck(A))&&!se[A]){if(!Nn[A]&&Ga(A)&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,A)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(A)))return!1;if(To&&!Xe[A]){let j=w(p),J=x(p);if(J&&j){let Me=J.length;for(let Ze=Me-1;Ze>=0;--Ze){let $e=h(J[Ze],!0);j.insertBefore($e,g(p))}}}return Fe(p),!0}return(D?D(p):p.nodeType)===it.element&&!Vu(p)||(A==="noscript"||A==="noembed"||A==="noframes")&&xe(/<\/no(script|embed|frames)/i,p.innerHTML)?(Fe(p),!0):(vt&&p.nodeType===it.text&&(y=p.textContent,wn([pr,fr,hr],j=>{y=_n(y,j," ")}),p.textContent!==y&&(Sn(e.removed,{element:p.cloneNode()}),p.textContent=y)),at(fe.afterSanitizeElements,p,null),!1)},Ha=function(p,y,A){if(mr[y]||_a&&(y==="id"||y==="name")&&(A in n||A in ju))return!1;let X=ue[y]||gt.attributeCheck instanceof Function&&gt.attributeCheck(y,p);if(!(yo&&!mr[y]&&xe(Du,y))){if(!(Ta&&xe(Uu,y))){if(!X||mr[y]){if(!(Ga(p)&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,p)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(p))&&(ae.attributeNameCheck instanceof RegExp&&xe(ae.attributeNameCheck,y)||ae.attributeNameCheck instanceof Function&&ae.attributeNameCheck(y,p))||y==="is"&&ae.allowCustomizedBuiltInElements&&(ae.tagNameCheck instanceof RegExp&&xe(ae.tagNameCheck,A)||ae.tagNameCheck instanceof Function&&ae.tagNameCheck(A))))return!1}else if(!So[y]){if(!xe(Ea,_n(A,xa,""))){if(!((y==="src"||y==="xlink:href"||y==="href")&&p!=="script"&&Wc(A,"data:")===0&&Ia[p])){if(!(wa&&!xe(Hu,_n(A,xa,"")))){if(A)return!1}}}}}}return!0},Wu=F({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),Ga=function(p){return!Wu[rr(p)]&&xe(Gu,p)},Fa=function(p){at(fe.beforeSanitizeAttributes,p,null);let y=p.attributes;if(!y||xr(p))return;let A={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:ue,forceKeepAttr:void 0},X=y.length;for(;X--;){let j=y[X],J=j.name,Me=j.namespaceURI,Ze=j.value,$e=le(J),No=Ze,he=J==="value"?No:Em(No);if(A.attrName=$e,A.attrValue=he,A.keepAttr=!0,A.forceKeepAttr=void 0,at(fe.uponSanitizeAttribute,p,A),he=A.attrValue,Aa&&($e==="id"||$e==="name")&&Wc(he,ka)!==0&&(At(J,p),he=ka+he),Rn&&xe(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,he)){At(J,p);continue}if($e==="attributename"&&Vc(he,"href")){At(J,p);continue}if(A.forceKeepAttr)continue;if(!A.keepAttr){At(J,p);continue}if(!Sa&&xe(/\/>/i,he)){At(J,p);continue}vt&&wn([pr,fr,hr],za=>{he=_n(he,za," ")});let $a=le(p.nodeName);if(!Ha($a,$e,he)){At(J,p);continue}if(U&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Me)switch(m.getAttributeType($a,$e)){case"TrustedHTML":{he=U.createHTML(he);break}case"TrustedScriptURL":{he=U.createScriptURL(he);break}}if(he!==No)try{Me?p.setAttributeNS(Me,J,he):p.setAttribute(J,he),xr(p)?Fe(p):jc(e.removed)}catch{At(J,p)}}at(fe.afterSanitizeAttributes,p,null)},Tr=function(p){let y=null,A=Pa(p);for(at(fe.beforeSanitizeShadowDOM,p,null);y=A.nextNode();)if(at(fe.uponSanitizeShadowNode,y,null),Ua(y),Fa(y),Ln(y.content)&&Tr(y.content),(D?D(y):y.nodeType)===it.element){let j=E?E(y):y.shadowRoot;Ln(j)&&(on(j),Tr(j))}at(fe.afterSanitizeShadowDOM,p,null)},on=function(p){let y=D?D(p):p.nodeType;if(y===it.element){let j=E?E(p):p.shadowRoot;Ln(j)&&(on(j),Tr(j))}let A=x?x(p):p.childNodes;if(!A)return;let X=[];wn(A,j=>{Sn(X,j)});for(let j of X)on(j);if(y===it.element){let j=P?P(p):null;if(typeof j=="string"&&le(j)==="template"){let J=p.content;Ln(J)&&on(J)}}};return e.sanitize=function(N){let p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},y=null,A=null,X=null,j=null;if(_o=!N,_o&&(N="<!-->"),typeof N!="string"&&!Er(N)&&(N=Am(N),typeof N!="string"))throw nr("dirty is not a string, aborting");if(!e.isSupported)return N;if(xo||Co(p),e.removed=[],typeof N=="string"&&(On=!1),On){let Ze=P?P(N):N.nodeName;if(typeof Ze=="string"){let $e=le(Ze);if(!se[$e]||Nn[$e])throw nr("root node is forbidden and cannot be sanitized in-place")}if(xr(N))throw nr("root node is clobbered and cannot be sanitized in-place");on(N)}else if(Er(N))y=La("<!---->"),A=y.ownerDocument.importNode(N,!0),A.nodeType===it.element&&A.nodeName==="BODY"||A.nodeName==="HTML"?y=A:y.appendChild(A),on(A);else{if(!en&&!vt&&!_t&&N.indexOf("<")===-1)return U&&vr?U.createHTML(N):N;if(y=La(N),!y)return en?null:vr?Se:""}y&&Eo&&Fe(y.firstChild);let J=Pa(On?N:y);for(;X=J.nextNode();)Ua(X),Fa(X),Ln(X.content)&&Tr(X.content);if(On)return vt&&Da(N),N;if(en){if(vt&&Da(y),gr)for(j=Mu.call(y.ownerDocument);y.firstChild;)j.appendChild(y.firstChild);else j=y;return(ue.shadowroot||ue.shadowrootmode)&&(j=Pu.call(r,j,!0)),j}let Me=_t?y.outerHTML:y.innerHTML;return _t&&se["!doctype"]&&y.ownerDocument&&y.ownerDocument.doctype&&y.ownerDocument.doctype.name&&xe(Um,y.ownerDocument.doctype.name)&&(Me="<!DOCTYPE "+y.ownerDocument.doctype.name+`>
13
+ `+Me),vt&&wn([pr,fr,hr],Ze=>{Me=_n(Me,Ze," ")}),U&&vr?U.createHTML(Me):Me},e.setConfig=function(){let N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Co(N),xo=!0},e.clearConfig=function(){rn=null,xo=!1},e.isValidAttribute=function(N,p,y){rn||Co({});let A=le(N),X=le(p);return Ha(A,X,y)},e.addHook=function(N,p){typeof p=="function"&&Sn(fe[N],p)},e.removeHook=function(N,p){if(p!==void 0){let y=ym(fe[N],p);return y===-1?void 0:xm(fe[N],y,1)[0]}return jc(fe[N])},e.removeHooks=function(N){fe[N]=[]},e.removeAllHooks=function(){fe=eu()},e}var iu=ru();function ra(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Qt=ra();function pu(t){Qt=t}var Yt={exec:()=>null};function kn(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=e[r];return i||(i=t(r),e[r]=i),i}}function W(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(i,o)=>{let s=typeof o=="string"?o:o.source;return s=s.replace(we.caret,"$1"),n=n.replace(i,s),r},getRegex:()=>new RegExp(n,e)};return r}var $m=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),we={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:kn(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:kn(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:kn(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:kn(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:kn(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:kn(t=>new RegExp(`^ {0,${t}}>`))},zm=/^(?:[ \t]*(?:\n|$))+/,Bm=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,jm=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,sr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Vm=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ia=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,fu=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,hu=W(fu).replace(/bull/g,ia).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(),Wm=W(fu).replace(/bull/g,ia).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(),oa=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,qm=/^[^\n]+/,sa=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Xm=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",sa).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Km=W(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ia).getRegex(),oo="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",aa=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Zm=W("^ {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",aa).replace("tag",oo).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mu=W(oa).replace("hr",sr).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]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",oo).getRegex(),Ym=W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",mu).getRegex(),la={blockquote:Ym,code:Bm,def:Xm,fences:jm,heading:Vm,hr:sr,html:Zm,lheading:hu,list:Km,newline:zm,paragraph:mu,table:Yt,text:qm},ou=W("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",sr).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",oo).getRegex(),Jm={...la,lheading:Wm,table:ou,paragraph:W(oa).replace("hr",sr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ou).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",oo).getRegex()},Qm={...la,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",aa).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:Yt,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(oa).replace("hr",sr).replace("heading",` *#{1,6} *[^
14
+ ]`).replace("lheading",hu).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},eg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,tg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,gu=/^( {2,}|\\)\n(?!\s*$)/,ng=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,In=/[\p{P}\p{S}]/u,so=/[\s\p{P}\p{S}]/u,ca=/[^\s\p{P}\p{S}]/u,rg=W(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,so).getRegex(),vu=/(?!~)[\p{P}\p{S}]/u,ig=/(?!~)[\s\p{P}\p{S}]/u,og=/(?:[^\s\p{P}\p{S}]|~)/u,sg=W(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",$m?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),bu=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ag=W(bu,"u").replace(/punct/g,In).getRegex(),lg=W(bu,"u").replace(/punct/g,vu).getRegex(),yu="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",cg=W(yu,"gu").replace(/notPunctSpace/g,ca).replace(/punctSpace/g,so).replace(/punct/g,In).getRegex(),ug=W(yu,"gu").replace(/notPunctSpace/g,og).replace(/punctSpace/g,ig).replace(/punct/g,vu).getRegex(),dg=W("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,ca).replace(/punctSpace/g,so).replace(/punct/g,In).getRegex(),pg=W(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,In).getRegex(),fg="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",hg=W(fg,"gu").replace(/notPunctSpace/g,ca).replace(/punctSpace/g,so).replace(/punct/g,In).getRegex(),mg=W(/\\(punct)/,"gu").replace(/punct/g,In).getRegex(),gg=W(/^<(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(),vg=W(aa).replace("(?:-->|$)","-->").getRegex(),bg=W("^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",vg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),no=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,yg=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",no).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),xu=W(/^!?\[(label)\]\[(ref)\]/).replace("label",no).replace("ref",sa).getRegex(),Eu=W(/^!?\[(ref)\](?:\[\])?/).replace("ref",sa).getRegex(),xg=W("reflink|nolink(?!\\()","g").replace("reflink",xu).replace("nolink",Eu).getRegex(),su=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ua={_backpedal:Yt,anyPunctuation:mg,autolink:gg,blockSkip:sg,br:gu,code:tg,del:Yt,delLDelim:Yt,delRDelim:Yt,emStrongLDelim:ag,emStrongRDelimAst:cg,emStrongRDelimUnd:dg,escape:eg,link:yg,nolink:Eu,punctuation:rg,reflink:xu,reflinkSearch:xg,tag:bg,text:ng,url:Yt},Eg={...ua,link:W(/^!?\[(label)\]\((.*?)\)/).replace("label",no).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",no).getRegex()},ea={...ua,emStrongRDelimAst:ug,emStrongLDelim:lg,delLDelim:pg,delRDelim:hg,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",su).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:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",su).getRegex()},Tg={...ea,br:W(gu).replace("{2,}","*").getRegex(),text:W(ea.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},to={normal:la,gfm:Jm,pedantic:Qm},ir={normal:ua,gfm:ea,breaks:Tg,pedantic:Eg},wg={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},au=t=>wg[t];function st(t,e){if(e){if(we.escapeTest.test(t))return t.replace(we.escapeReplace,au)}else if(we.escapeTestNoEncode.test(t))return t.replace(we.escapeReplaceNoEncode,au);return t}function lu(t){try{t=encodeURI(t).replace(we.percentDecode,"%")}catch{return null}return t}function cu(t,e){let n=t.replace(we.findPipe,(o,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)l=!l;return l?"|":" |"}),r=n.split(we.splitPipe),i=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(;i<r.length;i++)r[i]=r[i].trim().replace(we.slashPipe,"|");return r}function St(t,e,n){let r=t.length;if(r===0)return"";let i=0;for(;i<r;){let o=t.charAt(r-i-1);if(o===e&&!n)i++;else if(o!==e&&n)i++;else break}return t.slice(0,r-i)}function uu(t){let e=t.split(`
15
+ `),n=e.length-1;for(;n>=0&&we.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
16
+ `)}function Sg(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 _g(t,e=0){let n=e,r="";for(let i of t)if(i===" "){let o=4-n%4;r+=" ".repeat(o),n+=o}else r+=i,n++;return r}function du(t,e,n,r,i){let o=e.href,s=e.title||null,a=t[1].replace(i.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:o,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function Ag(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let i=r[1];return e.split(`
17
17
  `).map(o=>{let s=o.match(n.other.beginningSpace);if(s===null)return o;let[a]=s;return a.length>=i.length?o.slice(i.length):o}).join(`
18
- `)}var eo=class{options;rules;lexer;constructor(t){this.options=t||Jt}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]:tu(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=vg(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=St(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:St(e[0],`
18
+ `)}var ro=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]:uu(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=Ag(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=St(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:St(e[0],`
19
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:St(e[0],`
20
20
  `)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=St(e[0],`
21
21
  `).split(`
22
22
  `),r="",i="",o=[];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
- `),p=c.replace(this.rules.other.blockquoteSetextReplace,`
23
+ `),f=c.replace(this.rules.other.blockquoteSetextReplace,`
24
24
  $1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
25
25
  ${c}`:c,i=i?`${i}
26
- ${p}`:p;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,o,!0),this.lexer.state.top=m,n.length===0)break;let x=o.at(-1);if(x?.type==="code")break;if(x?.type==="blockquote"){let f=x,h=f.raw+`
26
+ ${f}`:f;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,o,!0),this.lexer.state.top=m,n.length===0)break;let b=o.at(-1);if(b?.type==="code")break;if(b?.type==="blockquote"){let h=b,d=h.raw+`
27
27
  `+n.join(`
28
- `),g=this.blockquote(h);o[o.length-1]=g,r=r.substring(0,r.length-f.raw.length)+g.raw,i=i.substring(0,i.length-f.text.length)+g.text;break}else if(x?.type==="list"){let f=x,h=f.raw+`
28
+ `),g=this.blockquote(d);o[o.length-1]=g,r=r.substring(0,r.length-h.raw.length)+g.raw,i=i.substring(0,i.length-h.text.length)+g.text;break}else if(b?.type==="list"){let h=b,d=h.raw+`
29
29
  `+n.join(`
30
- `),g=this.list(h);o[o.length-1]=g,r=r.substring(0,r.length-x.raw.length)+g.raw,i=i.substring(0,i.length-f.raw.length)+g.raw,n=h.substring(o.at(-1).raw.length).split(`
31
- `);continue}}return{type:"blockquote",raw:r,tokens:o,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,i={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 o=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,c="",p="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=gg(e[2].split(`
32
- `,1)[0],e[1].length),x=t.split(`
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),_=this.rules.other.fencesBeginRegex(h),b=this.rules.other.headingBeginRegex(h),G=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)||G.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
- `+x}f=!x.trim(),c+=ae+`
38
- `,t=t.substring(ae.length+1),m=ee.slice(h)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),i.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),i.raw+=c}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.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,i.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(!i.loose){let p=l.tokens.filter(x=>x.type==="space"),m=p.length>0&&p.some(x=>this.rules.other.anyLine.test(x.raw));i.loose=m}}if(i.loose)for(let l of i.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=tu(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"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:St(e[0],`
39
- `),href:r,title:i}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=eu(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
30
+ `),g=this.list(d);o[o.length-1]=g,r=r.substring(0,r.length-b.raw.length)+g.raw,i=i.substring(0,i.length-h.raw.length)+g.raw,n=d.substring(o.at(-1).raw.length).split(`
31
+ `);continue}}return{type:"blockquote",raw:r,tokens:o,text:i}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,i={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 o=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,c="",f="";if(!(e=o.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=_g(e[2].split(`
32
+ `,1)[0],e[1].length),b=t.split(`
33
+ `,1)[0],h=!m.trim(),d=0;if(this.options.pedantic?(d=2,f=m.trimStart()):h?d=e[1].length+1:(d=m.search(this.rules.other.nonSpaceChar),d=d>4?1:d,f=m.slice(d),d+=e[1].length),h&&this.rules.other.blankLine.test(b)&&(c+=b+`
34
+ `,t=t.substring(b.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(d),x=this.rules.other.hrRegex(d),w=this.rules.other.fencesBeginRegex(d),E=this.rules.other.headingBeginRegex(d),I=this.rules.other.htmlBeginRegex(d),D=this.rules.other.blockquoteBeginRegex(d);for(;t;){let P=t.split(`
35
+ `,1)[0],U;if(b=P,this.options.pedantic?(b=b.replace(this.rules.other.listReplaceNesting," "),U=b):U=b.replace(this.rules.other.tabCharGlobal," "),w.test(b)||E.test(b)||I.test(b)||D.test(b)||g.test(b)||x.test(b))break;if(U.search(this.rules.other.nonSpaceChar)>=d||!b.trim())f+=`
36
+ `+U.slice(d);else{if(h||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||w.test(m)||E.test(m)||x.test(m))break;f+=`
37
+ `+b}h=!b.trim(),c+=P+`
38
+ `,t=t.substring(P.length+1),m=U.slice(d)}}i.loose||(s?i.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),i.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(f),loose:!1,text:f,tokens:[]}),i.raw+=c}let a=i.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let l of i.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 f=this.rules.other.listTaskCheckbox.exec(l.raw);if(f){let m={type:"checkbox",raw:f[0]+" ",checked:f[0]!=="[ ]"};l.checked=m.checked,i.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(!i.loose){let f=l.tokens.filter(b=>b.type==="space"),m=f.length>0&&f.some(b=>this.rules.other.anyLine.test(b.raw));i.loose=m}}if(i.loose)for(let l of i.items){l.loose=!0;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return i}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=uu(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"):"",i=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:St(e[0],`
39
+ `),href:r,title:i}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=cu(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
40
40
  `):[],o={type:"table",raw:St(e[0],`
41
- `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(eu(s,o.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[l]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:St(e[0],`
41
+ `),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?o.align.push("right"):this.rules.other.tableAlignCenter.test(s)?o.align.push("center"):this.rules.other.tableAlignLeft.test(s)?o.align.push("left"):o.align.push(null);for(let s=0;s<n.length;s++)o.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:o.align[s]});for(let s of i)o.rows.push(cu(s,o.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:o.align[l]})));return o}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:St(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 o=St(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=mg(e[2],"()");if(o===-2)return;if(o>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=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)),nu(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.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," "),i=e[r.toLowerCase()];if(!i){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return nu(n,i,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 i=[...r[0]].length-1,o,s,a=i,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+i);(r=c.exec(e))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){a+=s;continue}else if((r[5]||r[6])&&i%3&&!((i+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,i+r.index+p+s);if(Math.min(i,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),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(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 i=[...r[0]].length-1,o,s,a=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+i);(r=l.exec(e))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))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,i+r.index+c+s),m=p.slice(i,-i);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 i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==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}}}},je=class Ys{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Jt,this.options.tokenizer=this.options.tokenizer||new eo,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:Se,block:Ji.normal,inline:tr.normal};this.options.pedantic?(n.block=Ji.pedantic,n.inline=tr.pedantic):this.options.gfm&&(n.block=Ji.gfm,this.options.breaks?n.inline=tr.breaks:n.inline=tr.gfm),this.tokenizer.rules=n}static get rules(){return{block:Ji,inline:tr}}static lex(e,n){return new Ys(n).lex(e)}static lexInline(e,n){return new Ys(n).inlineTokens(e)}lex(e){e=e.replace(Se.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(Se.tabCharGlobal," ").replace(Se.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},e,n))?(e=e.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let a=n.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
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 o=St(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=Sg(e[2],"()");if(o===-2)return;if(o>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+o;e[2]=e[2].substring(0,o),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],i="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],i=o[3])}else i=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)),du(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.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," "),i=e[r.toLowerCase()];if(!i){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return du(n,i,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 i=[...r[0]].length-1,o,s,a=i,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,e=e.slice(-1*t.length+i);(r=c.exec(e))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(s=[...o].length,r[3]||r[4]){a+=s;continue}else if((r[5]||r[6])&&i%3&&!((i+s)%3)){l+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let f=[...r[0]][0].length,m=t.slice(0,i+r.index+f+s);if(Math.min(i,s)%2){let h=m.slice(1,-1);return{type:"em",raw:m,text:h,tokens:this.lexer.inlineTokens(h)}}let b=m.slice(2,-2);return{type:"strong",raw:m,text:b,tokens:this.lexer.inlineTokens(b)}}}}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),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&i&&(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 i=[...r[0]].length-1,o,s,a=i,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+i);(r=l.exec(e))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(s=[...o].length,s!==i))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,f=t.slice(0,i+r.index+c+s),m=f.slice(i,-i);return{type:"del",raw:f,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 i;do i=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(i!==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}}}},We=class ta{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 ro,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:we,block:to.normal,inline:ir.normal};this.options.pedantic?(n.block=to.pedantic,n.inline=ir.pedantic):this.options.gfm&&(n.block=to.gfm,this.options.breaks?n.inline=ir.breaks:n.inline=ir.gfm),this.tokenizer.rules=n}static get rules(){return{block:to,inline:ir}}static lex(e,n){return new ta(n).lex(e)}static lexInline(e,n){return new ta(n).inlineTokens(e)}lex(e){e=e.replace(we.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(we.tabCharGlobal," ").replace(we.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let o;if(this.options.extensions?.block?.some(a=>(o=a.call({lexer:this},e,n))?(e=e.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.space(e)){e=e.substring(o.raw.length);let a=n.at(-1);o.raw.length===1&&a!==void 0?a.raw+=`
45
45
  `:n.push(o);continue}if(o=this.tokenizer.code(e)){e=e.substring(o.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
46
46
  `)?"":`
47
47
  `)+o.raw,a.text+=`
48
48
  `+o.text,this.inlineQueue.at(-1).src=a.text):n.push(o);continue}if(o=this.tokenizer.fences(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.heading(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.hr(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.blockquote(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.list(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.html(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.def(e)){e=e.substring(o.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
49
49
  `)?"":`
50
50
  `)+o.raw,a.text+=`
51
- `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),n.push(o);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&&(o=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
51
+ `+o.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[o.tag]||(this.tokens.links[o.tag]={href:o.href,title:o.title},n.push(o));continue}if(o=this.tokenizer.table(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.lheading(e)){e=e.substring(o.raw.length),n.push(o);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),c;this.options.extensions.startBlock.forEach(f=>{c=f.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&&(o=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
52
52
  `)?"":`
53
53
  `)+o.raw,a.text+=`
54
54
  `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(o),r=s.length!==e.length,e=e.substring(o.raw.length);continue}if(o=this.tokenizer.text(e)){e=e.substring(o.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
55
55
  `)?"":`
56
56
  `)+o.raw,a.text+=`
57
- `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(o);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,i=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-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)}},to=class{options;parser;constructor(t){this.options=t||Jt}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(Se.notSpaceStart)?.[0],i=t.replace(Se.endingNewline,"")+`
58
- `;return r?'<pre><code class="language-'+ot(r)+'">'+(n?i:ot(i,!0))+`</code></pre>
59
- `:"<pre><code>"+(n?i:ot(i,!0))+`</code></pre>
57
+ `+o.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(o);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,i=null;if(this.tokens.links){let c=Object.keys(this.tokens.links);if(c.length>0)for(;(i=this.tokenizer.rules.inline.reflinkSearch.exec(r))!==null;)c.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(i=this.tokenizer.rules.inline.anyPunctuation.exec(r))!==null;)r=r.slice(0,i.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let o;for(;(i=this.tokenizer.rules.inline.blockSkip.exec(r))!==null;)o=i[2]?i[2].length:0,r=r.slice(0,i.index+o)+"["+"a".repeat(i[0].length-o-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 f=e;if(this.options.extensions?.startInline){let m=1/0,b=e.slice(1),h;this.options.extensions.startInline.forEach(d=>{h=d.call({lexer:this},b),typeof h=="number"&&h>=0&&(m=Math.min(m,h))}),m<1/0&&m>=0&&(f=e.substring(0,m+1))}if(c=this.tokenizer.inlineText(f)){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)}},io=class{options;parser;constructor(t){this.options=t||Qt}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(we.notSpaceStart)?.[0],i=t.replace(we.endingNewline,"")+`
58
+ `;return r?'<pre><code class="language-'+st(r)+'">'+(n?i:st(i,!0))+`</code></pre>
59
+ `:"<pre><code>"+(n?i:st(i,!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}>
@@ -72,8 +72,8 @@ ${this.parser.parse(t)}</blockquote>
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),i=Qc(t);if(i===null)return r;t=i;let o='<a href="'+t+'"';return e&&(o+=' title="'+ot(e)+'"'),o+=">"+r+"</a>",o}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Qc(t);if(i===null)return ot(n);t=i;let o=`<img src="${t}" alt="${ot(n)}"`;return e&&(o+=` title="${ot(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:ot(t.text)}},sa=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 qs{options;renderer;textRenderer;constructor(e){this.options=e||Jt,this.options.renderer=this.options.renderer||new to,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new sa}static parse(e,n){return new qs(n).parse(e)}static parseInline(e,n){return new qs(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,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 o=i;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let s='Token with "'+o.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 i=0;i<e.length;i++){let o=e[i];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=a||"";continue}}let s=o;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||Jt}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?je.lex:je.lexInline}provideParser(t=this.block){return t?We.parse:We.parseInline}},aa=class{defaults=Js();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=We;Renderer=to;TextRenderer=sa;Lexer=je;Tokenizer=eo;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 i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.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(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=e.renderers[i.name];o?e.renderers[i.name]=function(...s){let a=i.renderer.apply(this,s);return a===!1&&(a=o.apply(this,s)),a}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[i.level];o?o.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new to(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,a=n.renderer[s],l=i[s];i[s]=(...c)=>{let p=a.apply(i,c);return p===!1&&(p=l.apply(i,c)),p||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new eo(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,a=n.tokenizer[s],l=i[s];i[s]=(...c)=>{let p=a.apply(i,c);return p===!1&&(p=l.apply(i,c)),p}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new nr;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,a=n.hooks[s],l=i[s];nr.passThroughHooks.has(o)?i[s]=c=>{if(this.defaults.async&&nr.passThroughHooksRespectAsync.has(o))return(async()=>{let m=await a.call(i,c);return l.call(i,m)})();let p=a.call(i,c);return l.call(i,p)}:i[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(i,c);return m===!1&&(m=await l.apply(i,c)),m})();let p=a.apply(i,c);return p===!1&&(p=l.apply(i,c)),p}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(o.call(this,s)),i&&(a=a.concat(i.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return je.lex(t,e??this.defaults)}parser(t,e){return We.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(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 o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(e):e,a=await(i.hooks?await i.hooks.provideLexer(t):t?je.lex:je.lexInline)(s,i),l=i.hooks?await i.hooks.processAllTokens(a):a;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let c=await(i.hooks?await i.hooks.provideParser(t):t?We.parse:We.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(c):c})().catch(o);try{i.hooks&&(e=i.hooks.preprocess(e));let s=(i.hooks?i.hooks.provideLexer(t):t?je.lex:je.lexInline)(e,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let a=(i.hooks?i.hooks.provideParser(t):t?We.parse:We.parseInline)(s,i);return i.hooks&&(a=i.hooks.postprocess(a)),a}catch(s){return o(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>"+ot(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},qt=new aa;function K(t,e){return qt.parse(t,e)}K.options=K.setOptions=function(t){return qt.setOptions(t),K.defaults=qt.defaults,ru(K.defaults),K};K.getDefaults=Js;K.defaults=Jt;K.use=function(...t){return qt.use(...t),K.defaults=qt.defaults,ru(K.defaults),K};K.walkTokens=function(t,e){return qt.walkTokens(t,e)};K.parseInline=qt.parseInline;K.Parser=We;K.parser=We.parse;K.Renderer=to;K.TextRenderer=sa;K.Lexer=je;K.lexer=je.lex;K.Tokenizer=eo;K.Hooks=nr;K.parse=K;var nS=K.options,rS=K.setOptions,iS=K.use,oS=K.walkTokens,sS=K.parseInline;var aS=We.parse,lS=je.lex;var yg=new aa({gfm:!0,breaks:!0}),fu=["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"],hu=["href","title","class"],bg=[...fu,"img"],xg=[...hu,"src","alt","width","height"];function io(t,e){let n=e?.allowImages===!0,r=yg.parse(t,{async:!1}),i=Zc.sanitize(r,{ALLOWED_TAGS:n?bg:fu,ALLOWED_ATTR:n?xg:hu}),o=document.createElement("template");o.innerHTML=i;for(let s of o.content.querySelectorAll("a[href]"))s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer");return o.innerHTML.trim()}function mu(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):mu(n,e)}function gu(t){let e=[];mu(t,e);let n=0;for(let{node:r,parent:i}of e){let o=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){o.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,o.appendChild(a),n+=1}i.replaceChild(o,r)}}var oo=class{chips;palette;#n;#e=[];#t=!1;#o=!1;#r=[];#s=0;constructor(e){this.#n=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.#t=e,this.#c()}enableSlash(e){this.#o=e}isOpen(){return!this.palette.hidden}onInput(e){this.#o&&e.startsWith("/")?this.#a(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#i(1),!0):e.key==="ArrowUp"?(this.#i(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#r.slice(this.#s,this.#s+1).forEach(n=>{this.#l(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#a(e){let n=e.trim().toLowerCase(),r=this.#e.filter(i=>i.name.toLowerCase().includes(n)||i.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#r=r,this.#s=0,this.#h(),this.palette.hidden=!1}#i(e){let n=this.#r.length;this.#s=(this.#s+e+n)%n,this.#h()}#l(e){this.close(),this.#n(e)}#c(){this.chips.replaceChildren();let e=this.#t?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.#l(n)),this.chips.appendChild(r)}}#h(){this.palette.replaceChildren(),this.#r.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.#s?"true":"false");let i=document.createElement("span");if(i.className="skill-item-title",i.textContent=e.title,r.appendChild(i),e.description!==void 0){let o=document.createElement("span");o.className="skill-item-desc",o.textContent=e.description,r.appendChild(o)}r.addEventListener("click",()=>this.#l(e)),this.palette.appendChild(r)})}};var vu=`
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>${st(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),i=lu(t);if(i===null)return r;t=i;let o='<a href="'+t+'"';return e&&(o+=' title="'+st(e)+'"'),o+=">"+r+"</a>",o}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=lu(t);if(i===null)return st(n);t=i;let o=`<img src="${t}" alt="${st(n)}"`;return e&&(o+=` title="${st(e)}"`),o+=">",o}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:st(t.text)}},da=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}},qe=class na{options;renderer;textRenderer;constructor(e){this.options=e||Qt,this.options.renderer=this.options.renderer||new io,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new da}static parse(e,n){return new na(n).parse(e)}static parseInline(e,n){return new na(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let s=i,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 o=i;switch(o.type){case"space":{n+=this.renderer.space(o);break}case"hr":{n+=this.renderer.hr(o);break}case"heading":{n+=this.renderer.heading(o);break}case"code":{n+=this.renderer.code(o);break}case"table":{n+=this.renderer.table(o);break}case"blockquote":{n+=this.renderer.blockquote(o);break}case"list":{n+=this.renderer.list(o);break}case"checkbox":{n+=this.renderer.checkbox(o);break}case"html":{n+=this.renderer.html(o);break}case"def":{n+=this.renderer.def(o);break}case"paragraph":{n+=this.renderer.paragraph(o);break}case"text":{n+=this.renderer.text(o);break}default:{let s='Token with "'+o.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 i=0;i<e.length;i++){let o=e[i];if(this.options.extensions?.renderers?.[o.type]){let a=this.options.extensions.renderers[o.type].call({parser:this},o);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(o.type)){r+=a||"";continue}}let s=o;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}},or=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?We.lex:We.lexInline}provideParser(t=this.block){return t?qe.parse:qe.parseInline}},pa=class{defaults=ra();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=qe;Renderer=io;TextRenderer=da;Lexer=We;Tokenizer=ro;Hooks=or;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 i=r;for(let o of i.header)n=n.concat(this.walkTokens(o.tokens,e));for(let o of i.rows)for(let s of o)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let i=r;n=n.concat(this.walkTokens(i.items,e));break}default:{let i=r;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.type].forEach(o=>{let s=i[o].flat(1/0);n=n.concat(this.walkTokens(s,e))}):i.tokens&&(n=n.concat(this.walkTokens(i.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(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let o=e.renderers[i.name];o?e.renderers[i.name]=function(...s){let a=i.renderer.apply(this,s);return a===!1&&(a=o.apply(this,s)),a}:e.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=e[i.level];o?o.unshift(i.tokenizer):e[i.level]=[i.tokenizer],i.start&&(i.level==="block"?e.startBlock?e.startBlock.push(i.start):e.startBlock=[i.start]:i.level==="inline"&&(e.startInline?e.startInline.push(i.start):e.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(e.childTokens[i.name]=i.childTokens)}),r.extensions=e),n.renderer){let i=this.defaults.renderer||new io(this.defaults);for(let o in n.renderer){if(!(o in i))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let s=o,a=n.renderer[s],l=i[s];i[s]=(...c)=>{let f=a.apply(i,c);return f===!1&&(f=l.apply(i,c)),f||""}}r.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new ro(this.defaults);for(let o in n.tokenizer){if(!(o in i))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let s=o,a=n.tokenizer[s],l=i[s];i[s]=(...c)=>{let f=a.apply(i,c);return f===!1&&(f=l.apply(i,c)),f}}r.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new or;for(let o in n.hooks){if(!(o in i))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let s=o,a=n.hooks[s],l=i[s];or.passThroughHooks.has(o)?i[s]=c=>{if(this.defaults.async&&or.passThroughHooksRespectAsync.has(o))return(async()=>{let m=await a.call(i,c);return l.call(i,m)})();let f=a.call(i,c);return l.call(i,f)}:i[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(i,c);return m===!1&&(m=await l.apply(i,c)),m})();let f=a.apply(i,c);return f===!1&&(f=l.apply(i,c)),f}}r.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,o=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(o.call(this,s)),i&&(a=a.concat(i.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return We.lex(t,e??this.defaults)}parser(t,e){return qe.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(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 o(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=t),i.async)return(async()=>{let s=i.hooks?await i.hooks.preprocess(e):e,a=await(i.hooks?await i.hooks.provideLexer(t):t?We.lex:We.lexInline)(s,i),l=i.hooks?await i.hooks.processAllTokens(a):a;i.walkTokens&&await Promise.all(this.walkTokens(l,i.walkTokens));let c=await(i.hooks?await i.hooks.provideParser(t):t?qe.parse:qe.parseInline)(l,i);return i.hooks?await i.hooks.postprocess(c):c})().catch(o);try{i.hooks&&(e=i.hooks.preprocess(e));let s=(i.hooks?i.hooks.provideLexer(t):t?We.lex:We.lexInline)(e,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let a=(i.hooks?i.hooks.provideParser(t):t?qe.parse:qe.parseInline)(s,i);return i.hooks&&(a=i.hooks.postprocess(a)),a}catch(s){return o(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>"+st(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Jt=new pa;function Z(t,e){return Jt.parse(t,e)}Z.options=Z.setOptions=function(t){return Jt.setOptions(t),Z.defaults=Jt.defaults,pu(Z.defaults),Z};Z.getDefaults=ra;Z.defaults=Qt;Z.use=function(...t){return Jt.use(...t),Z.defaults=Jt.defaults,pu(Z.defaults),Z};Z.walkTokens=function(t,e){return Jt.walkTokens(t,e)};Z.parseInline=Jt.parseInline;Z.Parser=qe;Z.parser=qe.parse;Z.Renderer=io;Z.TextRenderer=da;Z.Lexer=We;Z.lexer=We.lex;Z.Tokenizer=ro;Z.Hooks=or;Z.parse=Z;var xw=Z.options,Ew=Z.setOptions,Tw=Z.use,ww=Z.walkTokens,Sw=Z.parseInline;var _w=qe.parse,Aw=We.lex;var kg=new pa({gfm:!0,breaks:!0}),Tu=["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"],wu=["href","title","class"],Ig=[...Tu,"img"],Cg=[...wu,"src","alt","width","height"];function ao(t,e){let n=e?.allowImages===!0,r=kg.parse(t,{async:!1}),i=iu.sanitize(r,{ALLOWED_TAGS:n?Ig:Tu,ALLOWED_ATTR:n?Cg:wu}),o=document.createElement("template");o.innerHTML=i;for(let s of o.content.querySelectorAll("a[href]"))s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer");return o.innerHTML.trim()}function Su(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):Su(n,e)}function _u(t){let e=[];Su(t,e);let n=0;for(let{node:r,parent:i}of e){let o=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){o.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,o.appendChild(a),n+=1}i.replaceChild(o,r)}}var lo=class{chips;palette;#n;#e=[];#t=!1;#i=!1;#r=[];#a=0;constructor(e){this.#n=e,this.chips=document.createElement("div"),this.chips.className="skill-chips",this.chips.setAttribute("part","skill-chips"),this.chips.hidden=!0,this.palette=document.createElement("div"),this.palette.className="skill-palette",this.palette.setAttribute("part","skill-palette"),this.palette.setAttribute("role","listbox"),this.palette.hidden=!0}setSkills(e){this.#e=e,this.#c()}enableChips(e){this.#t=e,this.#c()}enableSlash(e){this.#i=e}isOpen(){return!this.palette.hidden}onInput(e){this.#i&&e.startsWith("/")?this.#s(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#o(1),!0):e.key==="ArrowUp"?(this.#o(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#r.slice(this.#a,this.#a+1).forEach(n=>{this.#l(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#s(e){let n=e.trim().toLowerCase(),r=this.#e.filter(i=>i.name.toLowerCase().includes(n)||i.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#r=r,this.#a=0,this.#p(),this.palette.hidden=!1}#o(e){let n=this.#r.length;this.#a=(this.#a+e+n)%n,this.#p()}#l(e){this.close(),this.#n(e)}#c(){this.chips.replaceChildren();let e=this.#t?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.setAttribute("part","skill-chip"),r.textContent=n.title,r.addEventListener("click",()=>this.#l(n)),this.chips.appendChild(r)}}#p(){this.palette.replaceChildren(),this.#r.forEach((e,n)=>{let r=document.createElement("button");r.type="button",r.className="skill-item",r.setAttribute("part","skill-item"),r.setAttribute("role","option"),r.setAttribute("aria-selected",n===this.#a?"true":"false");let i=document.createElement("span");if(i.className="skill-item-title",i.setAttribute("part","skill-item-title"),i.textContent=e.title,r.appendChild(i),e.description!==void 0){let o=document.createElement("span");o.className="skill-item-desc",o.setAttribute("part","skill-item-desc"),o.textContent=e.description,r.appendChild(o)}r.addEventListener("click",()=>this.#l(e)),this.palette.appendChild(r)})}};var Au=`
77
77
  :host {
78
78
  /* Colors */
79
79
  --ag-ui-bg: #ffffff;
@@ -1099,6 +1099,127 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
1099
1099
  color: #ffffff;
1100
1100
  }
1101
1101
 
1102
+ /* Approval card \u2014 the server-side-tool gate (approve/deny an interrupt). */
1103
+ .approval {
1104
+ align-self: stretch;
1105
+ box-sizing: border-box;
1106
+ display: flex;
1107
+ flex-direction: column;
1108
+ gap: 8px;
1109
+ padding: 12px;
1110
+ background: var(--ag-ui-bg);
1111
+ border: 1px solid var(--ag-ui-accent);
1112
+ border-radius: 10px;
1113
+ }
1114
+
1115
+ .approval[data-resolved] {
1116
+ opacity: 0.7;
1117
+ border-color: var(--ag-ui-border);
1118
+ }
1119
+
1120
+ .approval-body {
1121
+ font-weight: 600;
1122
+ }
1123
+
1124
+ .approval-actions {
1125
+ display: flex;
1126
+ gap: 8px;
1127
+ justify-content: flex-end;
1128
+ }
1129
+
1130
+ .approval-btn {
1131
+ border: 1px solid var(--ag-ui-border);
1132
+ border-radius: 8px;
1133
+ padding: 8px 14px;
1134
+ font: inherit;
1135
+ font-weight: 600;
1136
+ cursor: pointer;
1137
+ background: var(--ag-ui-bg);
1138
+ color: var(--ag-ui-fg);
1139
+ }
1140
+
1141
+ .approval-btn:disabled {
1142
+ cursor: default;
1143
+ opacity: 0.6;
1144
+ }
1145
+
1146
+ .approval-btn--approve {
1147
+ border-color: var(--ag-ui-accent);
1148
+ background: var(--ag-ui-accent);
1149
+ color: #ffffff;
1150
+ }
1151
+
1152
+ /* Question card \u2014 the built-in ask_user prompt (radios and/or free text). */
1153
+ .question {
1154
+ align-self: stretch;
1155
+ box-sizing: border-box;
1156
+ display: flex;
1157
+ flex-direction: column;
1158
+ gap: 8px;
1159
+ padding: 12px;
1160
+ background: var(--ag-ui-bg);
1161
+ border: 1px solid var(--ag-ui-accent);
1162
+ border-radius: 10px;
1163
+ }
1164
+
1165
+ .question[data-resolved] {
1166
+ opacity: 0.7;
1167
+ border-color: var(--ag-ui-border);
1168
+ }
1169
+
1170
+ .question-body {
1171
+ font-weight: 600;
1172
+ }
1173
+
1174
+ .question-options {
1175
+ display: flex;
1176
+ flex-direction: column;
1177
+ gap: 6px;
1178
+ }
1179
+
1180
+ .question-choice {
1181
+ display: flex;
1182
+ align-items: center;
1183
+ gap: 8px;
1184
+ cursor: pointer;
1185
+ }
1186
+
1187
+ .question-input {
1188
+ box-sizing: border-box;
1189
+ width: 100%;
1190
+ padding: 8px 10px;
1191
+ font: inherit;
1192
+ color: var(--ag-ui-fg);
1193
+ background: var(--ag-ui-bg);
1194
+ border: 1px solid var(--ag-ui-border);
1195
+ border-radius: 8px;
1196
+ }
1197
+
1198
+ .question-input:disabled {
1199
+ opacity: 0.6;
1200
+ }
1201
+
1202
+ .question-actions {
1203
+ display: flex;
1204
+ justify-content: flex-end;
1205
+ }
1206
+
1207
+ .question-btn {
1208
+ border: 1px solid var(--ag-ui-accent);
1209
+ border-radius: 8px;
1210
+ padding: 8px 14px;
1211
+ font: inherit;
1212
+ font-weight: 600;
1213
+ cursor: pointer;
1214
+ background: var(--ag-ui-accent);
1215
+ color: #ffffff;
1216
+ }
1217
+
1218
+ .question-btn:disabled {
1219
+ cursor: default;
1220
+ opacity: 0.6;
1221
+ }
1222
+
1102
1223
  /* Skills \u2014 chips row + the /-command palette, above the input. */
1103
1224
  .skill-chips {
1104
1225
  display: flex;
@@ -1179,6 +1300,82 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
1179
1300
  display: none;
1180
1301
  }
1181
1302
 
1303
+ .checkpoints {
1304
+ position: absolute;
1305
+ inset-block-start: 3rem;
1306
+ inset-inline: 0.75rem;
1307
+ z-index: 6;
1308
+ display: flex;
1309
+ flex-direction: column;
1310
+ gap: 0.25rem;
1311
+ padding: 0.5rem;
1312
+ border: 1px solid var(--agui-border, #d7d7dc);
1313
+ border-radius: 0.5rem;
1314
+ background: var(--agui-surface, #fff);
1315
+ box-shadow: 0 6px 24px rgb(0 0 0 / 12%);
1316
+ max-height: 60%;
1317
+ overflow-y: auto;
1318
+ }
1319
+
1320
+ .checkpoints[hidden] {
1321
+ display: none;
1322
+ }
1323
+
1324
+ .checkpoints-title {
1325
+ font-size: 0.75rem;
1326
+ font-weight: 600;
1327
+ opacity: 0.7;
1328
+ }
1329
+
1330
+ .checkpoints-empty {
1331
+ padding: 0.5rem 0.25rem;
1332
+ font-size: 0.8125rem;
1333
+ opacity: 0.7;
1334
+ }
1335
+
1336
+ .checkpoint-row {
1337
+ display: flex;
1338
+ align-items: center;
1339
+ gap: 0.5rem;
1340
+ padding: 0.25rem;
1341
+ border-radius: 0.375rem;
1342
+ }
1343
+
1344
+ .checkpoint-row:hover {
1345
+ background: var(--agui-hover, #f3f3f5);
1346
+ }
1347
+
1348
+ .checkpoint-label {
1349
+ flex: 1;
1350
+ font-size: 0.8125rem;
1351
+ white-space: nowrap;
1352
+ overflow: hidden;
1353
+ text-overflow: ellipsis;
1354
+ }
1355
+
1356
+ .checkpoint-branch {
1357
+ font-size: 0.6875rem;
1358
+ padding: 0 0.375rem;
1359
+ border-radius: 999px;
1360
+ background: var(--agui-hover, #f3f3f5);
1361
+ opacity: 0.8;
1362
+ }
1363
+
1364
+ .checkpoint-action {
1365
+ font: inherit;
1366
+ font-size: 0.75rem;
1367
+ cursor: pointer;
1368
+ padding: 0.125rem 0.5rem;
1369
+ border: 1px solid var(--agui-border, #d7d7dc);
1370
+ border-radius: 0.375rem;
1371
+ background: transparent;
1372
+ color: inherit;
1373
+ }
1374
+
1375
+ .checkpoint-action:hover {
1376
+ background: var(--agui-hover, #f3f3f5);
1377
+ }
1378
+
1182
1379
  .drawer-backdrop {
1183
1380
  position: absolute;
1184
1381
  inset: 0;
@@ -1350,11 +1547,11 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
1350
1547
  border-right: none;
1351
1548
  box-shadow: none;
1352
1549
  }
1353
- `;var so=class{element;#n;#e;#t;#o;#r=!1;constructor(e=ge){this.#o=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#s(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#o.thoughts,this.#s(!0))}#s(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};function yu(t,e=Date.now(),n=ge){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let i=Math.round(r/60);if(i<60)return n.minutesAgo.replace("{n}",String(i));let o=Math.round(i/60);if(o<24)return n.hoursAgo.replace("{n}",String(o));let s=Math.round(o/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}var ao=class{element;#n;#e;#t;#o;#r;#s;#a=[];#i="";#l=null;constructor(e,n=ge){this.#n=e,this.#s=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-modal","true"),this.#e.setAttribute("aria-label",n.chatHistory),this.#e.addEventListener("keydown",o=>this.#h(o));let i=document.createElement("div");i.className="drawer-header",i.setAttribute("part","drawer-header"),this.#t=document.createElement("span"),this.#t.className="drawer-title",this.#t.setAttribute("part","drawer-title"),this.#t.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.#n.onNew()}),i.append(this.#t,this.#o),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(i,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#s=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#o.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#o.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#l?.focus(),this.#l=null)}toggle(){this.isOpen()?this.close():this.open()}#c(){return this.element.getRootNode().activeElement}#h(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let n=Array.from(this.#e.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],i=n[n.length-1],o=this.#c();e.shiftKey&&o===r?(e.preventDefault(),i?.focus()):!e.shiftKey&&o===i&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#a=e,this.#i=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#a.length===0){let e=document.createElement("div");e.className="drawer-empty",e.setAttribute("part","drawer-empty"),e.textContent=this.#s.noConversations,this.#r.appendChild(e);return}for(let e of this.#a)this.#r.appendChild(this.#g(e))}#g(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","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",r.setAttribute("part","drawer-row-select");let i=document.createElement("span");i.className="drawer-row-title",i.textContent=e.title;let o=document.createElement("span");o.className="drawer-row-time",o.textContent=yu(e.updatedAt,void 0,this.#s);let s=document.createElement("span");s.className="drawer-row-preview",s.textContent=e.preview,r.append(i,o,s),r.addEventListener("click",()=>{this.close(),this.#n.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.title=this.#s.rename,a.setAttribute("aria-label",this.#s.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#d(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.title=this.#s.delete,l.setAttribute("aria-label",this.#s.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#p(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.append(a,l),n.append(r,c),n}#d(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.value=n.title;let i=!1,o=()=>{if(i)return;i=!0;let a=r.value.trim();a===""||a===n.title?this.#u():this.#n.onRename(n.threadId,a)},s=()=>{i||(i=!0,this.#u())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),o()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>o()),e.replaceChildren(r),r.focus(),r.select()}#p(e,n){let r=document.createElement("div");r.className="drawer-confirm";let i=document.createElement("span");i.className="drawer-confirm-label",i.textContent=this.#s.deletePrompt;let o=document.createElement("button");o.type="button",o.className="drawer-confirm-yes",o.textContent=this.#s.delete,o.addEventListener("click",()=>this.#n.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.textContent=this.#s.cancel,s.addEventListener("click",()=>this.#u()),r.append(i,o,s),e.replaceChildren(r)}};function bu(t){return{[ce.PENDING]:t.toolRunning,[ce.DONE]:t.toolDone,[ce.ERROR]:t.toolError,[ce.DECLINED]:t.toolDeclined}}function Eg(t){return{[ce.DONE]:t.resultLabel,[ce.ERROR]:t.errorLabel,[ce.DECLINED]:t.declinedLabel}}var ir=class{element;#n;#e;#t;#o;#r=!1;constructor(e,n,r=$e.FULL,i,o=ge){this.#e=r,this.#t=n,this.#o=o,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=i??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=bu(o)[ce.PENDING],s.append(a,l,this.#n),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.#r}settle(e,n){if(this.#r||(this.#r=!0,this.element.setAttribute("data-status",e),this.#n.textContent=bu(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 i=document.createElement("pre");i.className="tool-call-result",i.setAttribute("part","tool-card-result"),i.hidden=!0,this.#e===$e.COMPACT?(r.textContent=this.#o.details,i.textContent=`args: ${JSON.stringify(this.#t)}
1550
+ `;var co=class{element;#n;#e;#t;#i;#r=!1;constructor(e=ne){this.#i=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.setAttribute("part","thoughts-label"),this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#a(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#i.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var uo=class{element;#n;#e;#t;#i;#r;#a;#s=[];#o="";#l=null;constructor(e,n=ne){this.#n=e,this.#a=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-modal","true"),this.#e.setAttribute("aria-label",n.chatHistory),this.#e.addEventListener("keydown",o=>this.#p(o));let i=document.createElement("div");i.className="drawer-header",i.setAttribute("part","drawer-header"),this.#t=document.createElement("span"),this.#t.className="drawer-title",this.#t.setAttribute("part","drawer-title"),this.#t.textContent=n.chats,this.#i=document.createElement("button"),this.#i.type="button",this.#i.className="drawer-new",this.#i.setAttribute("part","drawer-new"),this.#i.textContent=n.newChat,this.#i.addEventListener("click",()=>{this.close(),this.#n.onNew()}),i.append(this.#t,this.#i),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(i,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#a=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#i.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#i.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#l?.focus(),this.#l=null)}toggle(){this.isOpen()?this.close():this.open()}#c(){return this.element.getRootNode().activeElement}#p(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let n=Array.from(this.#e.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],i=n[n.length-1],o=this.#c();e.shiftKey&&o===r?(e.preventDefault(),i?.focus()):!e.shiftKey&&o===i&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#s=e,this.#o=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#s.length===0){let e=document.createElement("div");e.className="drawer-empty",e.setAttribute("part","drawer-empty"),e.textContent=this.#a.noConversations,this.#r.appendChild(e);return}for(let e of this.#s)this.#r.appendChild(this.#h(e))}#h(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#o&&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 i=document.createElement("span");i.className="drawer-row-title",i.setAttribute("part","drawer-row-title"),i.textContent=e.title;let o=document.createElement("span");o.className="drawer-row-time",o.setAttribute("part","drawer-row-time"),o.textContent=Qi(e.updatedAt,void 0,this.#a);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(i,o,s),r.addEventListener("click",()=>{this.close(),this.#n.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#a.rename,a.setAttribute("aria-label",this.#a.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#f(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#a.delete,l.setAttribute("aria-label",this.#a.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#k(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#f(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let i=!1,o=()=>{if(i)return;i=!0;let a=r.value.trim();a===""||a===n.title?this.#u():this.#n.onRename(n.threadId,a)},s=()=>{i||(i=!0,this.#u())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),o()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>o()),e.replaceChildren(r),r.focus(),r.select()}#k(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let i=document.createElement("span");i.className="drawer-confirm-label",i.setAttribute("part","drawer-confirm-label"),i.textContent=this.#a.deletePrompt;let o=document.createElement("button");o.type="button",o.className="drawer-confirm-yes",o.setAttribute("part","drawer-confirm-yes"),o.textContent=this.#a.delete,o.addEventListener("click",()=>this.#n.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#a.cancel,s.addEventListener("click",()=>this.#u()),r.append(i,o,s),e.replaceChildren(r)}};function ku(t){return{[ce.PENDING]:t.toolRunning,[ce.DONE]:t.toolDone,[ce.ERROR]:t.toolError,[ce.DECLINED]:t.toolDeclined}}function Ng(t){return{[ce.DONE]:t.resultLabel,[ce.ERROR]:t.errorLabel,[ce.DECLINED]:t.declinedLabel}}var ar=class{element;#n;#e;#t;#i;#r=!1;constructor(e,n,r=ze.FULL,i,o=ne){this.#e=r,this.#t=n,this.#i=o,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=i??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=ku(o)[ce.PENDING],s.append(a,l,this.#n),this.element.append(s),r===ze.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.#r}settle(e,n){if(this.#r||(this.#r=!0,this.element.setAttribute("data-status",e),this.#n.textContent=ku(this.#i)[e],this.#e===ze.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 i=document.createElement("pre");i.className="tool-call-result",i.setAttribute("part","tool-card-result"),i.hidden=!0,this.#e===ze.COMPACT?(r.textContent=this.#i.details,i.textContent=`args: ${JSON.stringify(this.#t)}
1354
1551
 
1355
- ${n}`):(r.textContent=Eg(this.#o)[e],i.textContent=n),r.addEventListener("click",()=>{let o=i.hidden;i.hidden=!o,r.setAttribute("aria-expanded",String(o))}),this.element.append(r,i)}};var lo=class{element;#n;#e;#t;#o="idle";#r=null;#s=null;#a=[];#i=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ge,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button"),this.element.textContent="\u{1F3A4}",this.#d("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#o==="recording"){this.#c();return}this.#o!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#g(this.#t.transcriptionFailed);return}this.#s=e,this.#a=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#a.push(r.data)}),n.addEventListener("stop",()=>{this.#h(n.mimeType)}),this.#r=n,n.start(),this.#d("recording")}#c(){this.#r?.stop()}dispose(){this.#i=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#h(e){if(this.#i)return;this.#u(),this.#d("transcribing");let n=new Blob(this.#a,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#d("idle"),r!==""&&this.#e(r)}catch(r){this.#g(r instanceof Error?r.message:this.#t.transcriptionFailed)}finally{this.#r=null}}#u(){for(let e of this.#s?.getTracks()??[])e.stop();this.#s=null}#g(e){this.#u(),this.#r=null,this.#d("idle"),this.element.title=e}#d(e){this.#o=e,this.element.dataset.state=e;let n=this.#p(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#p(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var co=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},or=class{#n;#e;#t;#o;#r;#s;#a;#i=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#o=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#s=e.onPersist??(()=>{}),this.#a=e.connectionLostMessage??"Connection lost"}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Re(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#s(this.#n.messages),await this.#l()}async resume(){await this.#l()}addToolResult(e,n){this.#n.addMessage({id:Re(),role:"tool",content:n,toolCallId:e}),this.#s(this.#n.messages)}cancel(){this.#i=!0,this.#n.abortRun()}async#l(){this.#i=!1;try{await this.#h(),this.#i&&this.#c()}catch(e){this.#i||Tg(e)?this.#c():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#c(){this.#s(this.#n.messages),this.#e.onCancelled()}async#h(){for(let e=0;e<Oo;e+=1){if(this.#i)return;let n=[],r={terminal:!1,errored:!1};if(await this.#n.runAgent({tools:this.#t(),context:this.#o()},this.#u(n,r)),this.#s(this.#n.messages),this.#i)return;if(!r.terminal)throw new co(this.#a);if(r.errored||this.#r===null||n.length===0)return;let i=!1;for(let o of n){let s=await this.#r(o);if(s!==null){if(s.halt===!0)return;this.#n.addMessage({id:Re(),role:"tool",content:s.content,toolCallId:o.id}),this.#s(this.#n.messages),i=!0}}if(!i)return}}#u(e,n){let r=this.#e;return{onRunInitialized(){r.onRunStart()},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({textMessageBuffer:i}){r.onTextEnd(i)},onToolCallEndEvent({event:i,toolCallName:o,toolCallArgs:s}){let a={id:i.toolCallId,name:o,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Tg(t){return t instanceof Error&&t.name==="AbortError"}function la(t){let e=t.attachments;return Array.isArray(e)?e.filter(Sg):[]}function Sg(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var ca="ag-ui-chat",sr="thread",ua="threads",uo="messages:",po="checkpoint:",_g=60,wg=100,Ag="New conversation",ft=class{#n;constructor(e=""){this.#n=e===""?ca:`${ca}@${e}`,e!==""&&this.#s()}threadId(){let e=this.#r(sr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Re();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#a(this.#r(uo+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(uo+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#a(this.#r(po+e))}saveCheckpoint(e,n){let r=this.#r(po+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(uo+e)),sessionStorage.removeItem(this.#r(po+e)),this.#o(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(sr))===e&&sessionStorage.removeItem(this.#r(sr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:i,preview:o})=>({threadId:n,title:r,updatedAt:i,preview:o}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(sr),e)}renameThread(e,n){let r=this.#t(),i=r.find(o=>o.threadId===e);i!==void 0&&(i.title=n,i.titleCustom=!0,this.#o(r))}#e(e,n){let r=this.#t(),i=r.find(a=>a.threadId===e),o=Ig(n),s=Date.now();i===void 0?r.push({threadId:e,title:xu(n),titleCustom:!1,preview:o,updatedAt:s}):(i.preview=o,i.updatedAt=s,i.titleCustom||(i.title=xu(n))),this.#o(r)}#t(){return this.#a(this.#r(ua))??[]}#o(e){let n=this.#r(ua);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#s(){let e=`${ca}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let i=sessionStorage.key(r);if(i===null||!i.startsWith(e))continue;let o=i.slice(e.length);kg(o)&&n.push([i,this.#r(o)])}for(let[r,i]of n){let o=sessionStorage.getItem(r);o!==null&&sessionStorage.getItem(i)===null&&sessionStorage.setItem(i,o),sessionStorage.removeItem(r)}}#a(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function kg(t){return t===sr||t===ua||t.startsWith(uo)||t.startsWith(po)}function xu(t){for(let e of t)if(e.role==="user"){let n=Eu(e.content);if(n!=="")return Tu(n,_g)}return Ag}function Ig(t){for(let e of[...t].reverse()){let n=Eu(e.content);if(n!=="")return Tu(n,wg)}return""}function Eu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Tu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function da(t){return new Rc({url:t.endpoint,headers:t.headers??{},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let i=new Headers(n?.headers);for(let[o,s]of Object.entries(r))i.set(o,s);return fetch(e,{...n,headers:i})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var ar=class{#n;#e;#t;#o=new Set;#r=new Map;constructor(e,n=()=>({}),r=new ft){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}saveMessages(e,n){this.#t.saveMessages(e,n)}loadCheckpoint(e){return this.#t.loadCheckpoint(e)}saveCheckpoint(e,n){this.#t.saveCheckpoint(e,n)}renameThread(e,n){this.#t.renameThread(e,n),this.#r.set(e,n),this.#c(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#o.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#s();return e===null?this.#t.listThreads():e.filter(n=>!this.#o.has(n.thread_id)).map(n=>this.#i(n))}async loadMessages(e){let n=await this.#l(this.#n+encodeURIComponent(e)+"/");if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#a(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#s(){let e=await this.#l(this.#n);if(e===null||!e.ok)return null;let n=await this.#a(e);return n===null?null:n.threads??[]}async#a(e){try{return await e.json()}catch{return null}}#i(e){return{threadId:e.thread_id,title:this.#r.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#l(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#c(e,n,r){let i=this.#e();try{await fetch(this.#n+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?i:{...i,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};async function pa(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,{method:"POST",headers:{...e.headers??{}},body:n});if(!r.ok)throw new Error(await Cg(r));let i=await r.json();if(typeof i=="object"&&i!==null&&typeof i.text=="string")return i.text;throw new Error("transcription returned an unreadable response")}async function Cg(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function fa(t,e){return new Promise((n,r)=>{let i=new FormData;i.append("file",t);let o=new XMLHttpRequest;o.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))o.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&o.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),o.addEventListener("load",()=>{if(o.status>=200&&o.status<300)try{n(Ng(JSON.parse(o.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Rg(o)))}),o.addEventListener("error",()=>r(new Error("upload failed"))),o.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>o.abort()),o.send(i)})}function Ng(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,i=e.mime,o=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof i!="string"||typeof o!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:i,size:o,url:s}:{id:n,name:r,mime:i,size:o}}function Rg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Su="ag-ui-chat:collapsed",_u="ag-ui-chat:theme",lr=class extends HTMLElement{agentFactory=da;headers={};allowImages=!1;autoConfirm=!1;confirmPredicate=null;getTools=()=>[...this.#J().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...Wo(this.getPageMap,this.autoInjectPageMap),...this.#Te()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new ft;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=ge;#t=new Pn;#o=new Map;#r=new Set;#s;#a;#i;#l;#c;#h;#u;#g;#d;#p;#m;#O;#y;#b;#_;#T=null;#M;#G=null;#C=[];#N=null;#L=!1;#P=null;#v=null;#F=0;#D=null;#x=null;#w=null;#f="";#A="";#$=0;#z=[];#Z=[];#Y=[];#q=[];constructor(){super(),this.#s=this.attachShadow({mode:"open"}),this.#a=document.createElement("div"),this.#i=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#h=document.createElement("span"),this.#d=document.createElement("div"),this.#p=document.createElement("button"),this.#m=document.createElement("input"),this.#O=document.createElement("div"),this.#M=document.createElement("span"),this.#y=document.createElement("button"),this.#b=document.createElement("button"),this.#_=document.createElement("div"),this.#u=new oo(e=>this.#Ie(e)),this.#g=new ao({onSelect:e=>{this.#Ce(e)},onNew:()=>{this.newChat(),this.#U()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#U()},onDelete:e=>{this.#Ne(e)}})}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#h.textContent=r??this.#e.title}registerTool(e){this.#t.register(e)}registerStateHook(e){for(let n of Zo(e))this.#t.register(n)}#ue(){return this.routeMap.length===0?[]:Ko(()=>this.routeMap,()=>this.navigate)}#de(){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()}]}#pe(){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 jo(n,r=>this.resolvePageTarget(r))}#J(){return[...this.#ue(),...this.#de(),...this.#pe()]}#Q(e){let n=this.#J().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===$e.INLINE||e===$e.MINIMAL||e===$e.COMPACT?e:$e.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#A=this.id!==""?this.id:this.endpoint,this.#e=Gs({...this.#fe(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#ee(_u);e!==null&&this.setAttribute("theme",e)}this.#Le(),this.#g.setStrings(this.#e),this.#ee(Su)==="1"&&this.setAttribute("collapsed",""),this.#oe(),this.#we(),this.#_e(),this.#A!==""&&this.conversationStore instanceof ft&&(this.conversationStore=new ft(this.#A)),this.#Se(),this.#he(),this.#ge(),this.#f=this.conversationStore.threadId(),this.#ne()}disconnectedCallback(){this.#I(),this.#T?.dispose(),this.#G?.dispose()}#fe(){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{}}#he(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#me(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#T=new Yi({upload:n,maxBytes:this.#be(),accept:r,strings:this.#e}),this.#O.appendChild(this.#T.element),this.#m.accept=r,this.#p.hidden=!1,this.#Ee()}#me(e){return e===null?null:(n,r,i)=>fa(n,{url:e,headers:this.headers,onProgress:r,signal:i})}#ge(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#ve(e);n!==null&&(this.#G=new lo({transcribe:n,onText:r=>this.#ye(r),strings:this.#e}),this.#M.appendChild(this.#G.element))}#ve(e){return e===null?null:n=>pa(n,{url:e,headers:this.headers})}#ye(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#se(),this.#l.focus()}#be(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Mo;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Mo}#xe(){let e=this.#m.files;if(e!==null)for(let n of Array.from(e))this.#T?.add(n);this.#m.value=""}#Ee(){this.#a.addEventListener("dragover",e=>{e.preventDefault(),this.#a.classList.add("chat--dragover")}),this.#a.addEventListener("dragleave",()=>{this.#a.classList.remove("chat--dragover")}),this.#a.addEventListener("drop",e=>{e.preventDefault(),this.#a.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#T?.add(r)})}#Te(){return this.#C.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#C.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1552
+ ${n}`):(r.textContent=Ng(this.#i)[e],i.textContent=n),r.addEventListener("click",()=>{let o=i.hidden;i.hidden=!o,r.setAttribute("aria-expanded",String(o))}),this.element.append(r,i)}};var po=class{element;#n;#e;#t;#i="idle";#r=null;#a=null;#s=[];#o=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ne,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button"),this.element.textContent="\u{1F3A4}",this.#f("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#i==="recording"){this.#c();return}this.#i!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#h(this.#t.transcriptionFailed);return}this.#a=e,this.#s=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#s.push(r.data)}),n.addEventListener("stop",()=>{this.#p(n.mimeType)}),this.#r=n,n.start(),this.#f("recording")}#c(){this.#r?.stop()}dispose(){this.#o=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#p(e){if(this.#o)return;this.#u(),this.#f("transcribing");let n=new Blob(this.#s,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#f("idle"),r!==""&&this.#e(r)}catch(r){this.#h(r instanceof Error?r.message:this.#t.transcriptionFailed)}finally{this.#r=null}}#u(){for(let e of this.#a?.getTracks()??[])e.stop();this.#a=null}#h(e){this.#u(),this.#r=null,this.#f("idle"),this.element.title=e}#f(e){this.#i=e,this.element.dataset.state=e;let n=this.#k(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#k(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var fo=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Cn=class{#n;#e;#t;#i;#r;#a;#s;#o;#l=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#i=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#s=e.onPersist??(()=>{}),this.#o=e.connectionLostMessage??"Connection lost"}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Oe(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#s(this.#n.messages),await this.#c()}async resume(){await this.#c()}addToolResult(e,n){this.#n.addMessage({id:Oe(),role:"tool",content:n,toolCallId:e}),this.#s(this.#n.messages)}cancel(){this.#l=!0,this.#n.abortRun()}async#c(){this.#l=!1;try{await this.#u(),this.#l&&this.#p()}catch(e){this.#l||Rg(e)?this.#p():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#p(){this.#s(this.#n.messages),this.#e.onCancelled()}async#u(){let e;for(let n=0;n<Po;n+=1){if(this.#l)return;let r=[],i={terminal:!1,errored:!1,interrupts:[]},o={tools:this.#t(),context:this.#i()};if(e!==void 0&&(o.resume=e),await this.#n.runAgent(o,this.#h(r,i)),e=void 0,this.#s(this.#n.messages),this.#l)return;if(!i.terminal)throw new fo(this.#o);if(i.errored)return;if(i.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(i.interrupts);if(this.#l)return;e=Gc(i.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;this.#n.addMessage({id:Oe(),role:"tool",content:l.content,toolCallId:a.id}),this.#s(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e;return{onRunInitialized(){r.onRunStart()},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({textMessageBuffer:i}){r.onTextEnd(i)},onToolCallEndEvent({event:i,toolCallName:o,toolCallArgs:s}){let a={id:i.toolCallId,name:o,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(i){n.terminal=!0,i.outcome==="interrupt"&&(n.interrupts=i.interrupts)},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Rg(t){return t instanceof Error&&t.name==="AbortError"}function fa(t){let e=t.attachments;return Array.isArray(e)?e.filter(Og):[]}function Og(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.name=="string"&&typeof e.mime=="string"&&typeof e.size=="number"&&(e.url===void 0||typeof e.url=="string")}var ha="ag-ui-chat",lr="thread",ma="threads",ho="messages:",mo="checkpoint:",Mg=60,Lg=100,Pg="New conversation",ht=class{#n;constructor(e=""){this.#n=e===""?ha:`${ha}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(lr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Oe();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#s(this.#r(ho+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(ho+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#s(this.#r(mo+e))}saveCheckpoint(e,n){let r=this.#r(mo+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(ho+e)),sessionStorage.removeItem(this.#r(mo+e)),this.#i(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(lr))===e&&sessionStorage.removeItem(this.#r(lr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:i,preview:o})=>({threadId:n,title:r,updatedAt:i,preview:o}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(lr),e)}renameThread(e,n){let r=this.#t(),i=r.find(o=>o.threadId===e);i!==void 0&&(i.title=n,i.titleCustom=!0,this.#i(r))}#e(e,n){let r=this.#t(),i=r.find(a=>a.threadId===e),o=Ug(n),s=Date.now();i===void 0?r.push({threadId:e,title:Iu(n),titleCustom:!1,preview:o,updatedAt:s}):(i.preview=o,i.updatedAt=s,i.titleCustom||(i.title=Iu(n))),this.#i(r)}#t(){return this.#s(this.#r(ma))??[]}#i(e){let n=this.#r(ma);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${ha}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let i=sessionStorage.key(r);if(i===null||!i.startsWith(e))continue;let o=i.slice(e.length);Dg(o)&&n.push([i,this.#r(o)])}for(let[r,i]of n){let o=sessionStorage.getItem(r);o!==null&&sessionStorage.getItem(i)===null&&sessionStorage.setItem(i,o),sessionStorage.removeItem(r)}}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Dg(t){return t===lr||t===ma||t.startsWith(ho)||t.startsWith(mo)}function Iu(t){for(let e of t)if(e.role==="user"){let n=Cu(e.content);if(n!=="")return Nu(n,Mg)}return Pg}function Ug(t){for(let e of[...t].reverse()){let n=Cu(e.content);if(n!=="")return Nu(n,Lg)}return""}function Cu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Nu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function ga(t){return new Fc({url:t.endpoint,headers:t.headers??{},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let i=new Headers(n?.headers);for(let[o,s]of Object.entries(r))i.set(o,s);return fetch(e,{...n,headers:i})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var cr=class{#n;#e;#t;#i=new Set;#r=new Map;constructor(e,n=()=>({}),r=new ht){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}saveMessages(e,n){this.#t.saveMessages(e,n)}loadCheckpoint(e){return this.#t.loadCheckpoint(e)}saveCheckpoint(e,n){this.#t.saveCheckpoint(e,n)}renameThread(e,n){this.#t.renameThread(e,n),this.#r.set(e,n),this.#c(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#i.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#a();return e===null?this.#t.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#o(n))}async loadMessages(e){let n=await this.#l(this.#n+encodeURIComponent(e)+"/");if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#s(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#a(){let e=await this.#l(this.#n);if(e===null||!e.ok)return null;let n=await this.#s(e);return n===null?null:n.threads??[]}async#s(e){try{return await e.json()}catch{return null}}#o(e){return{threadId:e.thread_id,title:this.#r.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#l(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#c(e,n,r){let i=this.#e();try{await fetch(this.#n+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?i:{...i,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var ur=class{#n;#e;constructor(e,n=()=>({})){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n}async list(){try{let e=await fetch(this.#n,{method:"GET",headers:{Accept:"application/json",...this.#e()}});return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#t("resume",e)}forkUrl(e){return this.#t("fork",e)}#t(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function va(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,{method:"POST",headers:{...e.headers??{}},body:n});if(!r.ok)throw new Error(await Hg(r));let i=await r.json();if(typeof i=="object"&&i!==null&&typeof i.text=="string")return i.text;throw new Error("transcription returned an unreadable response")}async function Hg(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function ba(t,e){return new Promise((n,r)=>{let i=new FormData;i.append("file",t);let o=new XMLHttpRequest;o.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))o.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&o.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),o.addEventListener("load",()=>{if(o.status>=200&&o.status<300)try{n(Gg(JSON.parse(o.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Fg(o)))}),o.addEventListener("error",()=>r(new Error("upload failed"))),o.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>o.abort()),o.send(i)})}function Gg(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,i=e.mime,o=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof i!="string"||typeof o!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:i,size:o,url:s}:{id:n,name:r,mime:i,size:o}}function Fg(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Ru="ag-ui-chat:collapsed",Ou="ag-ui-chat:theme",dr=class extends HTMLElement{agentFactory=ga;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#te().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...Ko(this.getPageMap,this.autoInjectPageMap),...this.#Oe()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new ht;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=ne;#t=new Un;#i=new Map;#r=new Set;#a;#s;#o;#l;#c;#p;#u;#h;#f;#k=null;#E;#m;#g;#P;#T;#w;#I;#_=null;#D;#z=null;#O=[];#M=null;#U=!1;#b=null;#y=null;#B=0;#H=null;#S=null;#C=null;#d="";#N="";#j=0;#V=[];#J=[];#Q=[];#ee=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#o=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#p=document.createElement("span"),this.#E=document.createElement("div"),this.#m=document.createElement("button"),this.#g=document.createElement("input"),this.#P=document.createElement("div"),this.#D=document.createElement("span"),this.#T=document.createElement("button"),this.#w=document.createElement("button"),this.#I=document.createElement("div"),this.#u=new lo(e=>this.#He(e)),this.#h=new uo({onSelect:e=>{this.#Ge(e)},onNew:()=>{this.newChat(),this.#G()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#G()},onDelete:e=>{this.#Fe(e)}}),this.#f=new er((e,n)=>{this.#ge(e,n)})}#W(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#k===null&&(this.#k=new ur(e,()=>this.headers)),this.#k)}async#ge(e,n){let r=this.#W();if(r===null)return;let i=this.#l.value.trim();if(i==="")return;this.#l.value="";let o=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:o,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:[]});await new Cn({agent:s,handlers:this.#fe(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:l=>this.#de(l),resolveInterrupts:l=>this.#pe(l),connectionLostMessage:this.#e.connectionLost}).send(i)}async#ve(){let e=this.#W();this.#f.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text"]}attributeChangedCallback(e,n,r){this.#p.textContent=r??this.#e.title}registerTool(e){this.#t.register(e)}registerStateHook(e){for(let n of Jo(e))this.#t.register(n)}#be(){return this.routeMap.length===0?[]:Yo(()=>this.routeMap,()=>this.navigate)}#ye(){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:[],[Ne]:"Read the page"},handler:()=>e()}]}#xe(){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 Xo(n,r=>this.resolvePageTarget(r))}#te(){return[...this.#be(),...this.#ye(),...this.#xe(),...this.#Ee()]}#Ee(){return this.askUser?[{name:"ask_user",description:"Ask the user a question and wait for their answer. Provide `options` for a multiple-choice prompt; set `allow_custom` to also accept a free-text answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user."},options:{type:"array",items:{type:"string"},description:"Preset choices offered as radio buttons."},allow_custom:{type:"boolean",description:"Allow a free-text answer in addition to any options."}},required:["question"]},handler:e=>this.#Te(e)}]:[]}async#Te(e){let r={question:typeof e.question=="string"?e.question:""},i=e.options;Array.isArray(i)&&(r.options=i.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#b=new AbortController;let o=this.#b.signal;this.#x();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:o}):await Ws(this.#A(),r,{signal:o,strings:this.#e});return this.#b=null,this.#v(),this.#o.scrollTop=this.#o.scrollHeight,s}#ne(e){let n=this.#te().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===ze.INLINE||e===ze.MINIMAL||e===ze.COMPACT?e:ze.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#N=this.id!==""?this.id:this.endpoint,this.#e=Qo({...this.#we(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#re(Ou);e!==null&&this.setAttribute("theme",e)}this.#je(),this.#h.setStrings(this.#e),this.#f.setStrings(this.#e),this.#re(Ru)==="1"&&this.setAttribute("collapsed",""),this.#le(),this.#Pe(),this.#Le(),this.#N!==""&&this.conversationStore instanceof ht&&(this.conversationStore=new ht(this.#N)),this.#Me(),this.#Se(),this.#Ae(),this.#d=this.conversationStore.threadId(),this.#oe()}disconnectedCallback(){this.#R(),this.#_?.dispose(),this.#z?.dispose()}#we(){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{}}#Se(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#_e(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#_=new Ji({upload:n,maxBytes:this.#Ce(),accept:r,strings:this.#e}),this.#P.appendChild(this.#_.element),this.#g.accept=r,this.#m.hidden=!1,this.#Re()}#_e(e){return e===null?null:(n,r,i)=>ba(n,{url:e,headers:this.headers,onProgress:r,signal:i})}#Ae(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#ke(e);n!==null&&(this.#z=new po({transcribe:n,onText:r=>this.#Ie(r),strings:this.#e}),this.#D.appendChild(this.#z.element))}#ke(e){return e===null?null:n=>va(n,{url:e,headers:this.headers})}#Ie(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#ce(),this.#l.focus()}#Ce(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Do;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Do}#Ne(){let e=this.#g.files;if(e!==null)for(let n of Array.from(e))this.#_?.add(n);this.#g.value=""}#Re(){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.#_?.add(r)})}#Oe(){return this.#O.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#O.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1356
1553
  `)}
1357
- Use the read_attachment tool with an id to read a file's contents.`}]}#Se(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new ar(e,()=>this.headers,this.conversationStore))}async#_e(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=Xo(await n.json())}catch{}}setSkills(e){this.#q=e,this.#B()}#we(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#Y=this.#Ae(),this.#B(),this.#ke()}#Ae(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Lo(JSON.parse(e))}catch{return[]}}async#ke(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#Z=Lo(await n.json()),this.#B()}catch{}}#B(){let e=new Map;for(let n of[...this.#Z,...this.#Y,...this.#q])e.set(n.name,n);this.#u.setSkills([...e.values()])}#Ie(e){let{text:n,missing:r}=Ha(e.prompt,this.skillContext());if(r.length>0){this.#d.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#d.hidden=!1;return}this.#d.hidden=!0,this.#l.value=n,e.sendImmediately===!0?this.#X():this.#l.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#V(Su),e?"1":"0"),this.#oe(),this.dispatchEvent(new CustomEvent(No,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#V(_u),e),this.#te()}#V(e){return this.#A===""?e:`${e}:${this.#A}`}#ee(e){let n=sessionStorage.getItem(this.#V(e));return n!==null||this.#A===""?n:sessionStorage.getItem(e)}#te(){let e=this.getAttribute("theme")==="dark";this.#y.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#I(),this.conversationStore.clear(this.#f),this.#j(),this.#f=this.conversationStore.threadId(),this.#R(!1)}#j(){this.#N=null,this.#v=null,this.#x=null,this.#w=null,this.#S(),this.#o.clear(),this.#r.clear(),this.#z=[],this.#C=[],this.#T?.clear(),this.#i.replaceChildren(this.#_),this.#E()}async#Ce(e){e!==this.#f&&(this.#I(),this.#j(),this.conversationStore.setActiveThread(e),this.#f=e,this.#R(!1),await this.#ne())}#Ne(e){let n=e===this.#f;n&&this.#I(),this.conversationStore.clear(e),n&&(this.#j(),this.#f=this.conversationStore.threadId(),this.#R(!1)),this.#U()}async#U(){this.#g.setThreads(await this.conversationStore.listThreads(),this.#f)}async#ne(){this.#$+=1;let e=this.#$,n=await this.conversationStore.loadMessages(this.#f);if(e!==this.#$)return;if(n!==null){this.#z=n;for(let i of n)this.#Re(i)}let r=this.conversationStore.loadCheckpoint(this.#f);r!==null&&await this.#Me(r)}#Re(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ye.USER){let r=la(e);if(n!==""||r.length>0){let i=this.appendMessage(Ye.USER,n);r.length>0&&i.appendChild(Yo(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 i of r)this.#K({id:i.id,name:i.function.name,args:this.#Oe(i.function.arguments)});return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(ce.DONE,e.content)}}#Oe(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#re(e){this.getAttribute("data-text-animation")==="word"&&gu(e)}async#Me(e){this.conversationStore.saveCheckpoint(this.#f,null);let n=this.#ae();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=io(n,{allowImages:this.allowImages}),this.#k().appendChild(r)):(this.#x=null,r.textContent=n,this.#i.appendChild(r)),this.#E(),this.#i.scrollTop=this.#i.scrollHeight,r}#k(){if(this.#x===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#x=e,this.#i.appendChild(e),this.#E()}return this.#x}#Le(){let e=document.createElement("style");e.textContent=vu,this.#a.className="chat",this.#a.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.#ie("icon","icon",null));let i=document.createElement("slot");i.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let s=this.#W("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#U(),this.#g.open()});let a=this.#W("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#W("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),o.append(s,a),this.getAttribute("data-theme-toggle")!==null&&(this.#y.type="button",this.#y.className="header-btn header-btn--theme",this.#y.setAttribute("part","header-button theme-toggle"),this.#y.title=this.#e.toggleTheme,this.#y.setAttribute("aria-label",this.#e.toggleTheme),this.#y.addEventListener("click",()=>this.toggleTheme()),this.#te(),o.append(this.#y)),o.append(l),n.append(r,i,o),this.#i.className="messages",this.#i.setAttribute("part","messages"),this.#i.setAttribute("role","log"),this.#i.setAttribute("aria-live","polite"),this.#i.setAttribute("aria-label",this.#e.conversation),this.#_.className="empty",this.#_.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty",this.#_.append(c),this.#i.append(this.#_);let p=document.createElement("div");p.className="input-row",p.setAttribute("part","composer"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=2,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",x=>this.#Pe(x)),this.#l.addEventListener("input",()=>this.#se()),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.#I();return}this.#X()}),this.#d.className="skill-hint",this.#d.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.#m.click()),this.#m.className="attach-input",this.#m.type="file",this.#m.multiple=!0,this.#m.hidden=!0,this.#m.addEventListener("change",()=>this.#xe()),this.#O.className="attachment-slot",this.#M.className="voice-slot";let m=document.createElement("slot");m.name="footer",p.append(this.#p,this.#M,this.#l,this.#c,this.#m),this.#a.append(n,this.#i,this.#u.palette,this.#u.chips,this.#d,this.#O,p,m,this.#g.element),this.#b.className="rail",this.#b.type="button",this.#b.setAttribute("part","launcher"),this.#b.setAttribute("aria-label",this.#e.expand),this.#b.append(this.#ie("launcher","launcher-icon","\u{1F4AC}")),this.#b.addEventListener("click",()=>this.setCollapsed(!1)),this.#s.append(e,this.#a,this.#b)}#W(e,n,r){let i=document.createElement("button");return i.type="button",i.className=`header-btn header-btn--${e}`,i.setAttribute("part",`header-button ${e}-button`),i.title=n,i.setAttribute("aria-label",n),i.textContent=r,i}#ie(e,n,r){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let o=document.createElement("slot");o.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="",o.append(a)}else r!==null&&o.append(document.createTextNode(r));return i.append(o),i}#oe(){this.#b.setAttribute("aria-expanded",String(!this.collapsed))}#E(){this.#_.hidden=this.#i.childElementCount>1}#se(){this.#u.onInput(this.#l.value),this.#d.hidden=!0}#Pe(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#L){e.preventDefault(),this.#I();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#X())}#I(){this.#P?.abort(),this.#N?.cancel()}#R(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#X(){if(this.#L)return;let e=this.#l.value.trim(),n=this.#T?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Ye.USER,e);n.length>0&&r.appendChild(Yo(n)),this.#l.value="",this.#T?.clearReady(),this.#C=n,this.dispatchEvent(new CustomEvent(Co,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#De(e,n)}async#De(e,n){this.endpoint!==""&&await this.#ae().send(e,n)}#ae(){if(this.#N===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#f,initialMessages:this.#z});this.#N=new or({agent:e,handlers:this.#Ge(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#He(n),onPersist:n=>this.conversationStore.saveMessages(this.#f,n),connectionLostMessage:this.#e.connectionLost})}return this.#N}async#Ue(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Po(n.parameters)}async#He(e){let n=this.#K(e);this.#o.delete(e.id);let r=this.#Q(e.name);if(r===null)return this.#r.has(e.id)||n.settle(ce.DONE,this.#e.noResult),null;if(await this.#Ue(e,r)){let o={toolName:e.name,args:e.args},s=r.parameters[Ro];typeof s=="string"&&(o.message=s),this.#P=new AbortController;let a=Fs(this.#i,o,{signal:this.#P.signal,strings:this.#e});this.#E(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#P=null,!l){let c=this.#e.declinedAction;return n.settle(ce.DECLINED,c),this.#H(),{content:c}}}let i=Do(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#f,{toolCallId:e.id});try{let o=await r.handler(e.args);if(i)return n.settle(ce.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(o??null);return n.settle(ce.DONE,s),this.#H(),{content:s}}catch(o){i&&this.conversationStore.saveCheckpoint(this.#f,null);let s=o instanceof Error?o.message:String(o);return n.settle(ce.ERROR,s),this.#H(),{content:`Error: ${s}`,error:s}}}#Ge(){return{onRunStart:()=>{this.#R(!0),this.#k(),this.#H()},onReasoningStart:()=>{this.#S(),this.#le()},onReasoningDelta:e=>{this.#le().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#S(),this.#w?.collapse(),this.#ce(e),this.#F+=1},onTextEnd:e=>{let n=this.#ce(e);this.#F<=1&&this.#re(n),this.#v=null},onToolCall:e=>{this.#S(),this.#K(e)},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(ce.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#S(),this.#v=null},onError:e=>{this.#S(),this.#re(this.appendMessage(Ye.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#v=null},onCancelled:()=>{this.#S(),this.#Fe(),this.#v=null},onSettled:()=>{this.#S(),this.#R(!1),this.#v=null,this.#C=[];for(let e of this.#o.values())e.settled||e.settle(ce.DONE,this.#e.noResult);this.#x!==null&&this.#x.childElementCount===0&&(this.#x.remove(),this.#E()),this.#x=null,this.#w=null}}}#Fe(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#k().appendChild(e),this.#E(),this.#i.scrollTop=this.#i.scrollHeight}#H(){if(this.#D!==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.#D=e,this.#k().appendChild(e),this.#E(),this.#i.scrollTop=this.#i.scrollHeight}#S(){this.#D?.remove(),this.#D=null}#le(){if(this.#w===null){this.#w=new so(this.#e);let e=this.#k();e.insertBefore(this.#w.element,e.firstChild),this.#E(),this.#i.scrollTop=this.#i.scrollHeight}return this.#w}#ce(e){return this.#v===null&&(this.#v=this.appendMessage(Ye.ASSISTANT,""),this.#F=0),this.#v.innerHTML=io(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#v}#K(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#Q(e.name)?.parameters[Ce],i=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??$s(e.name),o=new ir(e.name,e.args,this.toolDisplay,i,this.#e);return this.#o.set(e.id,o),this.#k().appendChild(o.element),this.#E(),this.#i.scrollTop=this.#i.scrollHeight,o}};function Og(){customElements.get(Er)===void 0&&customElements.define(Er,lr)}async function Mg(t,e,n={}){at(t),await Go(t,{flashMs:n.flashMs??0}),await Uo(t,e,n)}async function Lg(t,e={}){at(t),await Ho(t,e)}async function Pg(t,e={}){at(t),await $o(t,e)}async function Dg(t,e,n={}){at(t),await zo(t,e,n)}async function Ug(t,e,n={}){at(t),await Bo(t,e,n)}function Hg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Dn(t,!!e):At(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Gg="0.10.0";export{lr as AgUiChat,or as AgUiClient,Pn as ClientToolRegistry,co as ConnectionLostError,ge as DEFAULT_UI_STRINGS,Er as ELEMENT_TAG,Oo as MAX_TOOL_ROUNDS,Ye as MESSAGE_ROLE,Vo as PAGE_ACTIONS,ar as RemoteConversationStore,Co as SUBMIT_EVENT,ft as SessionStorageStore,No as TOGGLE_EVENT,ce as TOOL_CALL_STATUS,$e as TOOL_DISPLAY,ir as ToolCallCard,Gg as VERSION,Ro as X_CONFIRM_KEY,Mn as X_DESTRUCTIVE_KEY,Ln as X_NAVIGATES_KEY,Ce as X_SUMMARY_KEY,Lg as clickElement,da as createHttpAgent,jo as createPageActionTools,Wo as createPageMapContext,Ko as createRouteTools,Zo as createStateHookTools,Og as defineAgUiChat,Mg as fillField,Go as focusWithFlash,Ho as highlightThenClick,Po as isDestructive,Do as isNavigates,Gs as mergeUiStrings,la as messageAttachments,Xo as parseToolCatalog,$a as prefersReducedMotion,Pg as pressButton,$o as pressThenClick,$s as prettifyToolName,io as renderMarkdown,Fs as requestConfirmation,at as scrollIntoCenterView,Dg as selectControl,zo as selectOption,Hg as setControlValue,Dn as setNativeChecked,At as setNativeValue,Ug as toggleCheckbox,Bo as toggleControl,pa as transcribeAudio,Uo as typeInto,fa as uploadAttachment};
1554
+ Use the read_attachment tool with an id to read a file's contents.`}]}#Me(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new cr(e,()=>this.headers,this.conversationStore))}async#Le(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=Zo(await n.json())}catch{}}setSkills(e){this.#ee=e,this.#q()}#Pe(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#Q=this.#De(),this.#q(),this.#Ue()}#De(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Uo(JSON.parse(e))}catch{return[]}}async#Ue(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#J=Uo(await n.json()),this.#q()}catch{}}#q(){let e=new Map;for(let n of[...this.#J,...this.#Q,...this.#ee])e.set(n.name,n);this.#u.setSkills([...e.values()])}#He(e){let{text:n,missing:r}=Ba(e.prompt,this.skillContext());if(r.length>0){this.#E.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#E.hidden=!1;return}this.#E.hidden=!0,this.#l.value=n,e.sendImmediately===!0?this.#Z():this.#l.focus()}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#X(Ru),e?"1":"0"),this.#le(),this.dispatchEvent(new CustomEvent(Mo,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#X(Ou),e),this.#ie()}#X(e){return this.#N===""?e:`${e}:${this.#N}`}#re(e){let n=sessionStorage.getItem(this.#X(e));return n!==null||this.#N===""?n:sessionStorage.getItem(e)}#ie(){let e=this.getAttribute("theme")==="dark";this.#T.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#R(),this.conversationStore.clear(this.#d),this.#K(),this.#d=this.conversationStore.threadId(),this.#L(!1)}#K(){this.#M=null,this.#y=null,this.#S=null,this.#C=null,this.#x(),this.#i.clear(),this.#r.clear(),this.#V=[],this.#O=[],this.#_?.clear(),this.#o.replaceChildren(this.#I),this.#v()}async#Ge(e){e!==this.#d&&(this.#R(),this.#K(),this.conversationStore.setActiveThread(e),this.#d=e,this.#L(!1),await this.#oe())}#Fe(e){let n=e===this.#d;n&&this.#R(),this.conversationStore.clear(e),n&&(this.#K(),this.#d=this.conversationStore.threadId(),this.#L(!1)),this.#G()}async#G(){this.#h.setThreads(await this.conversationStore.listThreads(),this.#d)}async#oe(){this.#j+=1;let e=this.#j,n=await this.conversationStore.loadMessages(this.#d);if(e!==this.#j)return;if(n!==null){this.#V=n;for(let i of n)this.#$e(i)}let r=this.conversationStore.loadCheckpoint(this.#d);r!==null&&await this.#Be(r)}#$e(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ye.USER){let r=fa(e);if(n!==""||r.length>0){let i=this.appendMessage(Ye.USER,n);r.length>0&&i.appendChild(ts(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 i of r)this.#Y({id:i.id,name:i.function.name,args:this.#ze(i.function.arguments)});return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(ce.DONE,e.content)}}#ze(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#se(e){this.getAttribute("data-text-animation")==="word"&&_u(e)}async#Be(e){this.conversationStore.saveCheckpoint(this.#d,null);let n=this.#ue();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=ao(n,{allowImages:this.allowImages}),this.#A().appendChild(r)):(this.#S=null,r.textContent=n,this.#o.appendChild(r)),this.#v(),this.#o.scrollTop=this.#o.scrollHeight,r}#A(){if(this.#S===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#S=e,this.#o.appendChild(e),this.#v()}return this.#S}#je(){let e=document.createElement("style");e.textContent=Au,this.#s.className="chat",this.#s.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#p;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.#ae("icon","icon",null));let i=document.createElement("slot");i.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let s=this.#F("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#G(),this.#h.open()});let a=this.#F("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>{this.#ve(),this.#f.open()});let l=this.#F("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#F("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#W()!==null?o.append(s,a,l):o.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#T.type="button",this.#T.className="header-btn header-btn--theme",this.#T.setAttribute("part","header-button theme-toggle"),this.#T.title=this.#e.toggleTheme,this.#T.setAttribute("aria-label",this.#e.toggleTheme),this.#T.addEventListener("click",()=>this.toggleTheme()),this.#ie(),o.append(this.#T)),o.append(c),n.append(r,i,o),this.#o.className="messages",this.#o.setAttribute("part","messages"),this.#o.setAttribute("role","log"),this.#o.setAttribute("aria-live","polite"),this.#o.setAttribute("aria-label",this.#e.conversation),this.#I.className="empty",this.#I.setAttribute("part","empty");let f=document.createElement("slot");f.name="empty",this.#I.append(f),this.#o.append(this.#I);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=2,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",h=>this.#Ve(h)),this.#l.addEventListener("input",()=>this.#ce()),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.#U){this.#R();return}this.#Z()}),this.#E.className="skill-hint",this.#E.setAttribute("part","skill-hint"),this.#E.hidden=!0,this.#m.className="attach-btn",this.#m.type="button",this.#m.setAttribute("part","attach-button"),this.#m.textContent="\u{1F4CE}",this.#m.title=this.#e.attachFiles,this.#m.setAttribute("aria-label",this.#e.attachFiles),this.#m.hidden=!0,this.#m.addEventListener("click",()=>this.#g.click()),this.#g.className="attach-input",this.#g.type="file",this.#g.multiple=!0,this.#g.hidden=!0,this.#g.addEventListener("change",()=>this.#Ne()),this.#P.className="attachment-slot",this.#D.className="voice-slot";let b=document.createElement("slot");b.name="footer",m.append(this.#m,this.#D,this.#l,this.#c,this.#g),this.#s.append(n,this.#o,this.#u.palette,this.#u.chips,this.#E,this.#P,m,b,this.#h.element,this.#f.element),this.#w.className="rail",this.#w.type="button",this.#w.setAttribute("part","launcher"),this.#w.setAttribute("aria-label",this.#e.expand),this.#w.append(this.#ae("launcher","launcher-icon","\u{1F4AC}")),this.#w.addEventListener("click",()=>this.setCollapsed(!1)),this.#a.append(e,this.#s,this.#w)}#F(e,n,r){let i=document.createElement("button");return i.type="button",i.className=`header-btn header-btn--${e}`,i.setAttribute("part",`header-button ${e}-button`),i.title=n,i.setAttribute("aria-label",n),i.textContent=r,i}#ae(e,n,r){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let o=document.createElement("slot");o.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="",o.append(a)}else r!==null&&o.append(document.createTextNode(r));return i.append(o),i}#le(){this.#w.setAttribute("aria-expanded",String(!this.collapsed))}#v(){this.#I.hidden=this.#o.childElementCount>1}#ce(){this.#u.onInput(this.#l.value),this.#E.hidden=!0}#Ve(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#U){e.preventDefault(),this.#R();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#Z())}#R(){this.#b?.abort(),this.#M?.cancel()}#L(e){this.#U=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#Z(){if(this.#U)return;let e=this.#l.value.trim(),n=this.#_?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Ye.USER,e);n.length>0&&r.appendChild(ts(n)),this.#l.value="",this.#_?.clearReady(),this.#O=n,this.dispatchEvent(new CustomEvent(Oo,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#We(e,n)}async#We(e,n){this.endpoint!==""&&await this.#ue().send(e,n)}#ue(){if(this.#M===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:this.#V});this.#M=new Cn({agent:e,handlers:this.#fe(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#de(n),resolveInterrupts:n=>this.#pe(n),onPersist:n=>this.conversationStore.saveMessages(this.#d,n),connectionLostMessage:this.#e.connectionLost})}return this.#M}async#qe(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Ho(n.parameters)}async#de(e){let n=this.#Y(e);this.#i.delete(e.id);let r=this.#ne(e.name);if(r===null)return this.#r.has(e.id)||n.settle(ce.DONE,this.#e.noResult),null;if(await this.#qe(e,r)){let o={toolName:e.name,args:e.args},s=r.parameters[Lo];typeof s=="string"&&(o.message=s),this.#b=new AbortController;let a=js(this.#o,o,{signal:this.#b.signal,strings:this.#e});this.#v(),this.#o.scrollTop=this.#o.scrollHeight;let l=await a;if(this.#b=null,!l){let c=this.#e.declinedAction;return n.settle(ce.DECLINED,c),this.#$(),{content:c}}}let i=Go(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#d,{toolCallId:e.id});try{let o=await r.handler(e.args);if(i)return n.settle(ce.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(o??null);return n.settle(ce.DONE,s),this.#$(),{content:s}}catch(o){i&&this.conversationStore.saveCheckpoint(this.#d,null);let s=o instanceof Error?o.message:String(o);return n.settle(ce.ERROR,s),this.#$(),{content:`Error: ${s}`,error:s}}}async#pe(e){let n={};this.#b=new AbortController,this.#x();for(let r of e){let i={};r.message!==void 0&&(i.message=r.message);let o=r.toolCallId!==void 0?this.#i.get(r.toolCallId):void 0,s=o?.element.getAttribute("data-tool-name");s!=null&&(i.toolName=s);let a=this.#b.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(i,{signal:a}):await es(this.#A(),i,{signal:a,strings:this.#e});this.#v(),this.#o.scrollTop=this.#o.scrollHeight,l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},o?.settle(ce.DECLINED,this.#e.declinedAction))}return this.#b=null,n}#fe(){return{onRunStart:()=>{this.#L(!0),this.#A(),this.#$()},onReasoningStart:()=>{this.#x(),this.#he()},onReasoningDelta:e=>{this.#he().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#x(),this.#C?.collapse(),this.#me(e),this.#B+=1},onTextEnd:e=>{let n=this.#me(e);this.#B<=1&&this.#se(n),this.#y=null},onToolCall:e=>{this.#x(),this.#Y(e)},onToolResult:(e,n)=>{let r=this.#i.get(e);r!==void 0&&(r.settle(ce.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#x(),this.#y=null},onError:e=>{this.#x(),this.#se(this.appendMessage(Ye.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#y=null},onCancelled:()=>{this.#x(),this.#Xe(),this.#y=null},onSettled:()=>{this.#x(),this.#L(!1),this.#y=null,this.#O=[];for(let e of this.#i.values())e.settled||e.settle(ce.DONE,this.#e.noResult);this.#S!==null&&this.#S.childElementCount===0&&(this.#S.remove(),this.#v()),this.#S=null,this.#C=null}}}#Xe(){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.#v(),this.#o.scrollTop=this.#o.scrollHeight}#$(){if(this.#H!==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.#H=e,this.#A().appendChild(e),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}#x(){this.#H?.remove(),this.#H=null}#he(){if(this.#C===null){this.#C=new co(this.#e);let e=this.#A();e.insertBefore(this.#C.element,e.firstChild),this.#v(),this.#o.scrollTop=this.#o.scrollHeight}return this.#C}#me(e){return this.#y===null&&(this.#y=this.appendMessage(Ye.ASSISTANT,""),this.#B=0),this.#y.innerHTML=ao(e,{allowImages:this.allowImages}),this.#o.scrollTop=this.#o.scrollHeight,this.#y}#Y(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#ne(e.name)?.parameters[Ne],i=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??Vs(e.name),o=new ar(e.name,e.args,this.toolDisplay,i,this.#e);return this.#i.set(e.id,o),this.#A().appendChild(o.element),this.#v(),this.#o.scrollTop=this.#o.scrollHeight,o}};function $g(){customElements.get(wr)===void 0&&customElements.define(wr,dr)}async function zg(t,e,n={}){lt(t),await zo(t,{flashMs:n.flashMs??0}),await Fo(t,e,n)}async function Bg(t,e={}){lt(t),await $o(t,e)}async function jg(t,e={}){lt(t),await jo(t,e)}async function Vg(t,e,n={}){lt(t),await Vo(t,e,n)}async function Wg(t,e,n={}){lt(t),await Wo(t,e,n)}function qg(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Hn(t,!!e):kt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Xg="0.12.0";export{dr as AgUiChat,Cn as AgUiClient,er as CheckpointMenu,Un as ClientToolRegistry,fo as ConnectionLostError,ne as DEFAULT_UI_STRINGS,wr as ELEMENT_TAG,Po as MAX_TOOL_ROUNDS,Ye as MESSAGE_ROLE,qo as PAGE_ACTIONS,cr as RemoteConversationStore,ur as RunIndex,Oo as SUBMIT_EVENT,ht as SessionStorageStore,Mo as TOGGLE_EVENT,ce as TOOL_CALL_STATUS,ze as TOOL_DISPLAY,ar as ToolCallCard,Xg as VERSION,Lo as X_CONFIRM_KEY,Pn as X_DESTRUCTIVE_KEY,Dn as X_NAVIGATES_KEY,Ne as X_SUMMARY_KEY,Bg as clickElement,ga as createHttpAgent,Xo as createPageActionTools,Ko as createPageMapContext,Yo as createRouteTools,Jo as createStateHookTools,$g as defineAgUiChat,zg as fillField,zo as focusWithFlash,$o as highlightThenClick,Ho as isDestructive,Go as isNavigates,Qo as mergeUiStrings,fa as messageAttachments,Zo as parseToolCatalog,Wa as prefersReducedMotion,jg as pressButton,jo as pressThenClick,Vs as prettifyToolName,ao as renderMarkdown,es as requestApproval,js as requestConfirmation,Ws as requestQuestion,lt as scrollIntoCenterView,Vg as selectControl,Vo as selectOption,qg as setControlValue,Hn as setNativeChecked,kt as setNativeValue,Wg as toggleCheckbox,Wo as toggleControl,va as transcribeAudio,Fo as typeInto,ba as uploadAttachment};
1358
1555
  /*! Bundled license information:
1359
1556
 
1360
1557
  fast-json-patch/module/helpers.mjs: