@artooi/ag-ui-web-component 0.15.0 → 0.16.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.
- package/CHANGELOG.md +72 -1
- package/README.md +13 -2
- package/dist/ag-ui-web-component.bundle.js +40 -39
- package/dist/ag-ui-web-component.bundle.js.map +4 -4
- package/dist/constants.d.ts +9 -0
- package/dist/constants.d.ts.map +1 -1
- package/dist/core/ag_ui_chat.d.ts.map +1 -1
- package/dist/core/agui_client.d.ts.map +1 -1
- package/dist/core/conversation_store.d.ts.map +1 -1
- package/dist/core/remote_conversation_store.d.ts.map +1 -1
- package/dist/core/run_index.d.ts.map +1 -1
- package/dist/index.js +382 -311
- package/dist/index.js.map +4 -4
- package/dist/tools/client_tool_registry.d.ts.map +1 -1
- package/dist/tools/page_action_tools.d.ts.map +1 -1
- package/dist/tools/route_map.d.ts.map +1 -1
- package/dist/ui/attachment_tray.d.ts.map +1 -1
- package/dist/ui/checkpoint_menu.d.ts.map +1 -1
- package/dist/ui/skills_menu.d.ts.map +1 -1
- package/dist/ui/thoughts_block.d.ts.map +1 -1
- package/dist/ui/thread_drawer.d.ts.map +1 -1
- package/dist/ui/tool_call_card.d.ts.map +1 -1
- package/dist/ui/ui_strings.d.ts +4 -0
- package/dist/ui/ui_strings.d.ts.map +1 -1
- package/dist/ui/voice_input.d.ts.map +1 -1
- package/package.json +9 -8
- package/src/constants.ts +10 -0
- package/src/core/ag_ui_chat.ts +86 -3
- package/src/core/remote_conversation_store.ts +2 -2
- package/src/tools/route_map.ts +5 -8
- package/src/ui/ui_strings.ts +7 -0
- package/src/version.ts +1 -1
|
@@ -1,46 +1,47 @@
|
|
|
1
|
-
var _d=Object.defineProperty;var Fi=(t,e)=>{for(var n in e)_d(t,n,{get:e[n],enumerable:!0})};var Ir="ag-ui-chat",$i="ag-ui-submit",zi="ag-ui-toggle",Bi="ag-ui-state",et={USER:"user",ASSISTANT:"assistant"},Gn="x-destructive",Vi="x-confirm",Le="x-summary",Fn="x-navigates",ji=10,fe={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},He={UPLOADING:"uploading",READY:"ready",ERROR:"error"},qi=10*1024*1024,Ve={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"},Wi="compaction",Xi="load_capability";var Ad=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function rl(t,e){let n=[];return{text:t.replace(Ad,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function kd(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 Yi(t){return Array.isArray(t)?t.filter(kd):[]}var $n=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 Ki(t){return t[Gn]===!0}function Zi(t){return t[Fn]===!0}function Cr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Id=Cr(HTMLInputElement.prototype,"value"),Cd=Cr(HTMLTextAreaElement.prototype,"value"),Nd=Cr(HTMLSelectElement.prototype,"value"),Rd=Cr(HTMLInputElement.prototype,"checked");function Nt(t,e){t instanceof HTMLTextAreaElement?Cd.call(t,e):t instanceof HTMLSelectElement?Nd.call(t,e):Id.call(t,e)}function zn(t,e){Rd.call(t,e)}var ol="#4f46e5";function Nr(t){return new Promise(e=>{setTimeout(e,t)})}async function Ji(t,e,n={}){let r=n.charDelayMs??35;Nt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)Nt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Nr(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function Qi(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${ol}`,t.style.outlineOffset="2px",await Nr(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function lt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function es(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 Nr(n),t.style.boxShadow=r}var il="0 0 0 3px rgba(79, 70, 229, 0.4)";function sl(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ts(t){return t<=0||sl()?Promise.resolve():Nr(t)}async function ns(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=il,await ts(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Od(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function rs(t,e,n={}){let r=Od(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${ol}`,t.style.outlineOffset="2px",await ts(o),Nt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function os(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=il,await ts(r),zn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var is={SCROLL:"scroll",DRAG:"drag"};function ss(t,e){let n=[];return t.has(is.SCROLL)&&n.push(Md(e)),t.has(is.DRAG)&&n.push(Ld(e)),n}function Md(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"],[Le]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return lt(r),{scrolled:!0,target:n}}}}function Ld(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"],[Le]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return Pd(o,i),{dragged:!0,from:n,to:r}}}}function Pd(t,e){let n=new DataTransfer;Bn(t,"dragstart",n),Bn(e,"dragenter",n),Bn(e,"dragover",n),Bn(e,"drop",n),Bn(t,"dragend",n)}function Bn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function as(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Rr(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Le]:`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"},[Gn]:!0,[Le]:`Update ${t.name}`},handler:r=>n(r)}),e}var Dd=Rr;function ls(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary;typeof o=="string"&&typeof i=="string"&&(e[o]=i)}return e}var al=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Ud(t){let e=[];for(let n of t.matchAll(al)){let r=n[1];r!==void 0&&e.push(r)}return e}function Hd(t,e,n){let r={...n};return{path:e.replace(al,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function Gd(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function cs(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:[],[Le]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Ud(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"],[Fn]:!0,[Le]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(f=>f.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=Hd(o.id,o.path,i),l=Gd(s,a),c=e();return c!==null?c(l):window.location.assign(l),{navigated:!0,path:l}}}]}var ae={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",historyCompacted:"Earlier turns condensed to fit the context window ({count} removed)",usingSkill:"Using skill {name}",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 us(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function ll(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 ds(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.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=ll("deny",r.deny),c=ll("approve",r.approve),f=!1,m=y=>{f||(f=!0,l.disabled=!0,c.disabled=!0,i.setAttribute("data-resolved",y?"approved":"denied"),o(y))};if(l.addEventListener("click",()=>m(!1)),c.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(l,c),i.append(s,a),t.appendChild(i),n.signal?.aborted===!0){m(!1);return}c.focus()})}function ps(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(Fd(n));return e}function Fd(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=fs(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 o=document.createElement("span");return o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=Or(t.size),e.append(n,r,o),e}function fs(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function Or(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 xe=[];for(let t=0;t<256;++t)xe.push((t+256).toString(16).slice(1));function cl(t,e=0){return(xe[t[e+0]]+xe[t[e+1]]+xe[t[e+2]]+xe[t[e+3]]+"-"+xe[t[e+4]]+xe[t[e+5]]+"-"+xe[t[e+6]]+xe[t[e+7]]+"-"+xe[t[e+8]]+xe[t[e+9]]+"-"+xe[t[e+10]]+xe[t[e+11]]+xe[t[e+12]]+xe[t[e+13]]+xe[t[e+14]]+xe[t[e+15]]).toLowerCase()}var hs,$d=new Uint8Array(16);function ms(){if(!hs){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");hs=crypto.getRandomValues.bind(crypto)}return hs($d)}var zd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),gs={randomUUID:zd};function Bd(t,e,n){if(gs.randomUUID&&!e&&!t)return gs.randomUUID();t=t||{};let r=t.random??t.rng?.()??ms();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return cl(r)}var yt=Bd;var u={};Fi(u,{BRAND:()=>mp,DIRTY:()=>Rt,EMPTY_PATH:()=>Wd,INVALID:()=>P,NEVER:()=>Qp,OK:()=>_e,ParseStatus:()=>Ee,Schema:()=>z,ZodAny:()=>Tt,ZodArray:()=>pt,ZodBigInt:()=>Mt,ZodBoolean:()=>Lt,ZodBranded:()=>jn,ZodCatch:()=>jt,ZodDate:()=>Pt,ZodDefault:()=>Vt,ZodDiscriminatedUnion:()=>Pr,ZodEffects:()=>$e,ZodEnum:()=>zt,ZodError:()=>Re,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Ur,ZodIntersection:()=>Gt,ZodIssueCode:()=>T,ZodLazy:()=>Ft,ZodLiteral:()=>$t,ZodMap:()=>gn,ZodNaN:()=>bn,ZodNativeEnum:()=>Bt,ZodNever:()=>je,ZodNull:()=>Ut,ZodNullable:()=>rt,ZodNumber:()=>Ot,ZodObject:()=>Oe,ZodOptional:()=>Ge,ZodParsedType:()=>I,ZodPipeline:()=>qn,ZodPromise:()=>wt,ZodReadonly:()=>qt,ZodRecord:()=>Dr,ZodSchema:()=>z,ZodSet:()=>vn,ZodString:()=>Et,ZodSymbol:()=>hn,ZodTransformer:()=>$e,ZodTuple:()=>nt,ZodType:()=>z,ZodUndefined:()=>Dt,ZodUnion:()=>Ht,ZodUnknown:()=>dt,ZodVoid:()=>mn,addIssueToContext:()=>k,any:()=>Sp,array:()=>Ip,bigint:()=>yp,boolean:()=>xl,coerce:()=>Jp,custom:()=>vl,date:()=>xp,datetimeRegex:()=>ml,defaultErrorMap:()=>ct,discriminatedUnion:()=>Op,effect:()=>Vp,enum:()=>$p,function:()=>Hp,getErrorMap:()=>dn,getParsedType:()=>tt,instanceof:()=>vp,intersection:()=>Mp,isAborted:()=>Mr,isAsync:()=>pn,isDirty:()=>Lr,isValid:()=>xt,late:()=>gp,lazy:()=>Gp,literal:()=>Fp,makeIssue:()=>Vn,map:()=>Dp,nan:()=>bp,nativeEnum:()=>zp,never:()=>Ap,null:()=>wp,nullable:()=>qp,number:()=>yl,object:()=>Cp,objectUtil:()=>vs,oboolean:()=>Zp,onumber:()=>Kp,optional:()=>jp,ostring:()=>Yp,pipeline:()=>Xp,preprocess:()=>Wp,promise:()=>Bp,quotelessJson:()=>Vd,record:()=>Pp,set:()=>Up,setErrorMap:()=>qd,strictObject:()=>Np,string:()=>bl,symbol:()=>Ep,transformer:()=>Vp,tuple:()=>Lp,undefined:()=>Tp,union:()=>Rp,unknown:()=>_p,util:()=>V,void:()=>kp});var V;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(V||(V={}));var vs;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(vs||(vs={}));var I=V.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=t=>{switch(typeof t){case"undefined":return I.undefined;case"string":return I.string;case"number":return Number.isNaN(t)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":return Array.isArray(t)?I.array:t===null?I.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?I.promise:typeof Map<"u"&&t instanceof Map?I.map:typeof Set<"u"&&t instanceof Set?I.set:typeof Date<"u"&&t instanceof Date?I.date:I.object;default:return I.unknown}};var T=V.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"]),Vd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Re=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let c=s.path[l];l===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Re.create=t=>new Re(t);var jd=(t,e)=>{let n;switch(t.code){case T.invalid_type:t.received===I.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,V.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(t.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(t.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${V.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}"`:V.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,V.assertNever(t)}return{message:n}},ct=jd;var ul=ct;function qd(t){ul=t}function dn(){return ul}var Vn=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(c=>!!c).slice().reverse();for(let c of l)a=c(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},Wd=[];function k(t,e){let n=dn(),r=Vn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ct?void 0:ct].filter(o=>!!o)});t.common.issues.push(r)}var Ee=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return P;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return P;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},P=Object.freeze({status:"aborted"}),Rt=t=>({status:"dirty",value:t}),_e=t=>({status:"valid",value:t}),Mr=t=>t.status==="aborted",Lr=t=>t.status==="dirty",xt=t=>t.status==="valid",pn=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));var Fe=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},dl=(t,e)=>{if(xt(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 Re(t.common.issues);return this._error=n,this._error}}};function F(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var z=class{get description(){return this._def.description}_getType(e){return tt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(pn(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:tt(e)},o=this._parseSync({data:e,path:r.path,parent:r});return dl(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return xt(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=>xt(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:tt(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(pn(o)?o:Promise.resolve(o));return dl(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:T.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new $e({schema:this,typeName:D.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 Ge.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return wt.create(this,this._def)}or(e){return Ht.create([this,e],this._def)}and(e){return Gt.create(this,e,this._def)}transform(e){return new $e({...F(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Vt({...F(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new jn({typeName:D.ZodBranded,type:this,...F(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new jt({...F(this._def),innerType:this,catchValue:n,typeName:D.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return qn.create(this,e)}readonly(){return qt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Xd=/^c[^\s-]{8,}$/i,Yd=/^[0-9a-z]+$/,Kd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Zd=/^[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,Jd=/^[a-z0-9_-]{21}$/i,Qd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ep=/^[-+]?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)?)??$/,tp=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,np="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",bs,rp=/^(?:(?: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])$/,op=/^(?:(?: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])$/,ip=/^(([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]))$/,sp=/^(([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])$/,ap=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,fl="((\\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])))",cp=new RegExp(`^${fl}$`);function hl(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 up(t){return new RegExp(`^${hl(t)}$`)}function ml(t){let e=`${fl}T${hl(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 dp(t,e){return!!((e==="v4"||!e)&&rp.test(t)||(e==="v6"||!e)&&ip.test(t))}function pp(t,e){if(!Qd.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function fp(t,e){return!!((e==="v4"||!e)&&op.test(t)||(e==="v6"||!e)&&sp.test(t))}var Et=class t extends z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.string){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_type,expected:I.string,received:i.parsedType}),P}let r=new Ee,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?k(o,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&k(o,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")tp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"email",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")bs||(bs=new RegExp(np,"u")),bs.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Zd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Jd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Xd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Yd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Kd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:T.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:T.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?ml(i).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?cp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?up(i).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?ep.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?dp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?pp(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?fp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?ap.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?lp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:T.invalid_string,message:i.message}),r.dirty()):V.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:T.invalid_string,...N.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...N.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...N.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...N.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...N.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...N.errToObj(n)})}nonempty(e){return this.min(1,N.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}};Et.create=t=>new Et({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...F(t)});function hp(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}var Ot=class t extends z{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)!==I.number){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_type,expected:I.number,received:i.parsedType}),P}let r,o=new Ee;for(let i of this._def.checks)i.kind==="int"?V.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?hp(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:T.not_finite,message:i.message}),o.dirty()):V.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&V.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)}};Ot.create=t=>new Ot({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...F(t)});var Mt=class t extends z{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)!==I.bigint)return this._getInvalidInput(e);let r,o=new Ee;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):V.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return k(n,{code:T.invalid_type,expected:I.bigint,received:n.parsedType}),P}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.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}};Mt.create=t=>new Mt({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...F(t)});var Lt=class extends z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.boolean,received:r.parsedType}),P}return _e(e.data)}};Lt.create=t=>new Lt({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...F(t)});var Pt=class t extends z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.date){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_type,expected:I.date,received:i.parsedType}),P}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_date}),P}let r=new Ee,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):V.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:N.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}};Pt.create=t=>new Pt({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...F(t)});var hn=class extends z{_parse(e){if(this._getType(e)!==I.symbol){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.symbol,received:r.parsedType}),P}return _e(e.data)}};hn.create=t=>new hn({typeName:D.ZodSymbol,...F(t)});var Dt=class extends z{_parse(e){if(this._getType(e)!==I.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.undefined,received:r.parsedType}),P}return _e(e.data)}};Dt.create=t=>new Dt({typeName:D.ZodUndefined,...F(t)});var Ut=class extends z{_parse(e){if(this._getType(e)!==I.null){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.null,received:r.parsedType}),P}return _e(e.data)}};Ut.create=t=>new Ut({typeName:D.ZodNull,...F(t)});var Tt=class extends z{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};Tt.create=t=>new Tt({typeName:D.ZodAny,...F(t)});var dt=class extends z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};dt.create=t=>new dt({typeName:D.ZodUnknown,...F(t)});var je=class extends z{_parse(e){let n=this._getOrReturnCtx(e);return k(n,{code:T.invalid_type,expected:I.never,received:n.parsedType}),P}};je.create=t=>new je({typeName:D.ZodNever,...F(t)});var mn=class extends z{_parse(e){if(this._getType(e)!==I.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.void,received:r.parsedType}),P}return _e(e.data)}};mn.create=t=>new mn({typeName:D.ZodVoid,...F(t)});var pt=class t extends z{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==I.array)return k(n,{code:T.invalid_type,expected:I.array,received:n.parsedType}),P;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(k(n,{code:s?T.too_big:T.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(k(n,{code:T.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(k(n,{code:T.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Fe(n,s,n.path,a)))).then(s=>Ee.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Fe(n,s,n.path,a)));return Ee.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:N.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:N.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:N.toString(n)}})}nonempty(e){return this.min(1,e)}};pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...F(e)});function fn(t){if(t instanceof Oe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Ge.create(fn(r))}return new Oe({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:fn(t.element)}):t instanceof Ge?Ge.create(fn(t.unwrap())):t instanceof rt?rt.create(fn(t.unwrap())):t instanceof nt?nt.create(t.items.map(e=>fn(e))):t}var Oe=class t extends z{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=V.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==I.object){let c=this._getOrReturnCtx(e);return k(c,{code:T.invalid_type,expected:I.object,received:c.parsedType}),P}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof je&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let f=i[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:f._parse(new Fe(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof je){let c=this._def.unknownKeys;if(c==="passthrough")for(let f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:o.data[f]}});else if(c==="strict")a.length>0&&(k(o,{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=o.data[f];l.push({key:{status:"valid",value:f},value:c._parse(new Fe(o,m,o.path,f)),alwaysSet:f in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let f of l){let m=await f.key,y=await f.value;c.push({key:m,value:y,alwaysSet:f.alwaysSet})}return c}).then(c=>Ee.mergeObjectSync(r,c)):Ee.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:N.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.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 V.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 V.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return fn(this)}partial(e){let n={};for(let r of V.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of V.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ge;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return gl(V.objectKeys(this.shape))}};Oe.create=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strip",catchall:je.create(),typeName:D.ZodObject,...F(e)});Oe.strictCreate=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strict",catchall:je.create(),typeName:D.ZodObject,...F(e)});Oe.lazycreate=(t,e)=>new Oe({shape:t,unknownKeys:"strip",catchall:je.create(),typeName:D.ZodObject,...F(e)});var Ht=class extends z{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Re(a.ctx.common.issues));return k(n,{code:T.invalid_union,unionErrors:s}),P}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let c={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:c});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:c}),c.common.issues.length&&s.push(c.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new Re(l));return k(n,{code:T.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};Ht.create=(t,e)=>new Ht({options:t,typeName:D.ZodUnion,...F(e)});var ut=t=>t instanceof Ft?ut(t.schema):t instanceof $e?ut(t.innerType()):t instanceof $t?[t.value]:t instanceof zt?t.options:t instanceof Bt?V.objectValues(t.enum):t instanceof Vt?ut(t._def.innerType):t instanceof Dt?[void 0]:t instanceof Ut?[null]:t instanceof Ge?[void 0,...ut(t.unwrap())]:t instanceof rt?[null,...ut(t.unwrap())]:t instanceof jn||t instanceof qt?ut(t.unwrap()):t instanceof jt?ut(t._def.innerType):[],Pr=class t extends z{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.object)return k(n,{code:T.invalid_type,expected:I.object,received:n.parsedType}),P;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(k(n,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=ut(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...F(r)})}};function ys(t,e){let n=tt(t),r=tt(e);if(t===e)return{valid:!0,data:t};if(n===I.object&&r===I.object){let o=V.objectKeys(e),i=V.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=ys(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===I.array&&r===I.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=ys(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===I.date&&r===I.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Gt=class extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(Mr(i)||Mr(s))return P;let a=ys(i.value,s.value);return a.valid?((Lr(i)||Lr(s))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:T.invalid_intersection_types}),P)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Gt.create=(t,e,n)=>new Gt({left:t,right:e,typeName:D.ZodIntersection,...F(n)});var nt=class t extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.array)return k(r,{code:T.invalid_type,expected:I.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return k(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(k(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Fe(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>Ee.mergeArray(n,s)):Ee.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};nt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nt({items:t,typeName:D.ZodTuple,rest:null,...F(e)})};var Dr=class t extends z{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!==I.object)return k(r,{code:T.invalid_type,expected:I.object,received:r.parsedType}),P;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new Fe(r,a,r.path,a)),value:s._parse(new Fe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ee.mergeObjectAsync(n,o):Ee.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof z?new t({keyType:e,valueType:n,typeName:D.ZodRecord,...F(r)}):new t({keyType:Et.create(),valueType:e,typeName:D.ZodRecord,...F(n)})}},gn=class extends z{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!==I.map)return k(r,{code:T.invalid_type,expected:I.map,received:r.parsedType}),P;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],c)=>({key:o._parse(new Fe(r,a,r.path,[c,"key"])),value:i._parse(new Fe(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 P;(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 P;(c.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(c.value,f.value)}return{status:n.value,value:a}}}};gn.create=(t,e,n)=>new gn({valueType:e,keyType:t,typeName:D.ZodMap,...F(n)});var vn=class t extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.set)return k(r,{code:T.invalid_type,expected:I.set,received:r.parsedType}),P;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(k(r,{code:T.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(k(r,{code:T.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let f of l){if(f.status==="aborted")return P;f.status==="dirty"&&n.dirty(),c.add(f.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new Fe(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:N.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:N.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};vn.create=(t,e)=>new vn({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...F(e)});var Ur=class t extends z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.function)return k(n,{code:T.invalid_type,expected:I.function,received:n.parsedType}),P;function r(a,l){return Vn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,dn(),ct].filter(c=>!!c),issueData:{code:T.invalid_arguments,argumentsError:l}})}function o(a,l){return Vn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,dn(),ct].filter(c=>!!c),issueData:{code:T.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof wt){let a=this;return _e(async function(...l){let c=new Re([]),f=await a._def.args.parseAsync(l,i).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,i).catch(h=>{throw c.addIssue(o(m,h)),c})})}else{let a=this;return _e(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new Re([r(l,c.error)]);let f=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(f,i);if(!m.success)throw new Re([o(f,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:nt.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||nt.create([]).rest(dt.create()),returns:n||dt.create(),typeName:D.ZodFunction,...F(r)})}},Ft=class extends z{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})}};Ft.create=(t,e)=>new Ft({getter:t,typeName:D.ZodLazy,...F(e)});var $t=class extends z{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return k(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:e.data}}get value(){return this._def.value}};$t.create=(t,e)=>new $t({value:t,typeName:D.ZodLiteral,...F(e)});function gl(t,e){return new zt({values:t,typeName:D.ZodEnum,...F(e)})}var zt=class t extends z{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return k(n,{expected:V.joinValues(r),received:n.parsedType,code:T.invalid_type}),P}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 k(n,{received:n.data,code:T.invalid_enum_value,options:r}),P}return _e(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})}};zt.create=gl;var Bt=class extends z{_parse(e){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==I.string&&r.parsedType!==I.number){let o=V.objectValues(n);return k(r,{expected:V.joinValues(o),received:r.parsedType,code:T.invalid_type}),P}if(this._cache||(this._cache=new Set(V.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=V.objectValues(n);return k(r,{received:r.data,code:T.invalid_enum_value,options:o}),P}return _e(e.data)}get enum(){return this._def.values}};Bt.create=(t,e)=>new Bt({values:t,typeName:D.ZodNativeEnum,...F(e)});var wt=class extends z{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.promise&&n.common.async===!1)return k(n,{code:T.invalid_type,expected:I.promise,received:n.parsedType}),P;let r=n.parsedType===I.promise?n.data:Promise.resolve(n.data);return _e(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};wt.create=(t,e)=>new wt({type:t,typeName:D.ZodPromise,...F(e)});var $e=class extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{k(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return P;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?P:l.status==="dirty"?Rt(l.value):n.value==="dirty"?Rt(l.value):l});{if(n.value==="aborted")return P;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?P:a.status==="dirty"?Rt(a.value):n.value==="dirty"?Rt(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?P:(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"?P:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!xt(s))return P;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>xt(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):P);V.assertNever(o)}};$e.create=(t,e,n)=>new $e({schema:t,typeName:D.ZodEffects,effect:e,...F(n)});$e.createWithPreprocess=(t,e,n)=>new $e({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...F(n)});var Ge=class extends z{_parse(e){return this._getType(e)===I.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(t,e)=>new Ge({innerType:t,typeName:D.ZodOptional,...F(e)});var rt=class extends z{_parse(e){return this._getType(e)===I.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(t,e)=>new rt({innerType:t,typeName:D.ZodNullable,...F(e)});var Vt=class extends z{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===I.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Vt.create=(t,e)=>new Vt({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...F(e)});var jt=class extends z{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return pn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Re(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Re(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};jt.create=(t,e)=>new jt({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...F(e)});var bn=class extends z{_parse(e){if(this._getType(e)!==I.nan){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.nan,received:r.parsedType}),P}return{status:"valid",value:e.data}}};bn.create=t=>new bn({typeName:D.ZodNaN,...F(t)});var mp=Symbol("zod_brand"),jn=class extends z{_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}},qn=class t extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?P:i.status==="dirty"?(n.dirty(),Rt(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?P:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:D.ZodPipeline})}},qt=class extends z{_parse(e){let n=this._def.innerType._parse(e),r=o=>(xt(o)&&(o.value=Object.freeze(o.value)),o);return pn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};qt.create=(t,e)=>new qt({innerType:t,typeName:D.ZodReadonly,...F(e)});function pl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function vl(t,e={},n){return t?Tt.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=pl(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=pl(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):Tt.create()}var gp={object:Oe.lazycreate},D;(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"})(D||(D={}));var vp=(t,e={message:`Input not instance of ${t.name}`})=>vl(n=>n instanceof t,e),bl=Et.create,yl=Ot.create,bp=bn.create,yp=Mt.create,xl=Lt.create,xp=Pt.create,Ep=hn.create,Tp=Dt.create,wp=Ut.create,Sp=Tt.create,_p=dt.create,Ap=je.create,kp=mn.create,Ip=pt.create,Cp=Oe.create,Np=Oe.strictCreate,Rp=Ht.create,Op=Pr.create,Mp=Gt.create,Lp=nt.create,Pp=Dr.create,Dp=gn.create,Up=vn.create,Hp=Ur.create,Gp=Ft.create,Fp=$t.create,$p=zt.create,zp=Bt.create,Bp=wt.create,Vp=$e.create,jp=Ge.create,qp=rt.create,Wp=$e.createWithPreprocess,Xp=qn.create,Yp=()=>bl().optional(),Kp=()=>yl().optional(),Zp=()=>xl().optional(),Jp={string:(t=>Et.create({...t,coerce:!0})),number:(t=>Ot.create({...t,coerce:!0})),boolean:(t=>Lt.create({...t,coerce:!0})),bigint:(t=>Mt.create({...t,coerce:!0})),date:(t=>Pt.create({...t,coerce:!0}))};var Qp=P;var ef=u.object({name:u.string(),arguments:u.string()}),tf=u.object({id:u.string(),type:u.literal("function"),function:ef,encryptedValue:u.string().optional()}),Hr=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),nf=u.object({type:u.literal("text"),text:u.string()}),rf=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),of=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),Gr=u.discriminatedUnion("type",[rf,of]),sf=u.object({type:u.literal("image"),source:Gr,metadata:u.unknown().optional()}),af=u.object({type:u.literal("audio"),source:Gr,metadata:u.unknown().optional()}),lf=u.object({type:u.literal("video"),source:Gr,metadata:u.unknown().optional()}),cf=u.object({type:u.literal("document"),source:Gr,metadata:u.unknown().optional()});var El=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()}),Tl=(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"]})},Hb=El.superRefine((t,e)=>{Tl(t,e)}),uf=u.discriminatedUnion("type",[nf,sf,af,lf,cf,El]),df=uf.superRefine((t,e)=>{t.type==="binary"&&Tl(t,e)}),pf=Hr.extend({role:u.literal("developer"),content:u.string()}),ff=Hr.extend({role:u.literal("system"),content:u.string()}),hf=Hr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(tf).optional()}),mf=Hr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(df)])}),gf=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),vf=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),bf=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),wl=u.discriminatedUnion("role",[pf,ff,hf,mf,gf,vf,bf]),Gb=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),yf=u.object({description:u.string(),value:u.string()}),Sl=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),xf=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()}),Ef=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Tf=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(wl),tools:u.array(Sl),context:u.array(yf),forwardedProps:u.any(),resume:u.array(Ef).optional()}),wf=u.any(),ee=class extends Error{constructor(t){super(t)}},xs=class extends ee{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Sf=u.object({name:u.string(),description:u.string().optional()}),_f=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()}),Af=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),kf=u.object({supported:u.boolean().optional(),items:u.array(Sl).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),If=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),Cf=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),Nf=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(Sf).optional()}),Rf=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),Of=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),Mf=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),Lf=u.object({input:Of.optional(),output:Mf.optional()}),Pf=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),Df=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()}),Fb=u.object({identity:_f.optional(),transport:Af.optional(),tools:kf.optional(),output:If.optional(),state:Cf.optional(),multiAgent:Nf.optional(),reasoning:Rf.optional(),multimodal:Lf.optional(),execution:Pf.optional(),humanInTheLoop:Df.optional(),custom:u.record(u.unknown()).optional()}),_l=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})({}),X=u.object({type:u.nativeEnum(v),timestamp:u.number().optional(),rawEvent:u.any().optional()}).passthrough(),Uf=X.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:_l.default("assistant"),name:u.string().optional()}),Al=X.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),Hf=X.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),Gf=X.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:_l.optional(),delta:u.string().optional(),name:u.string().optional()}),Ff=X.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),$f=Al.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),zf=X.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),Bf=X.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),Vf=X.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),jf=X.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),qf=X.extend({messageId:u.string(),type:u.literal(v.TOOL_CALL_RESULT),toolCallId:u.string(),content:u.string(),role:u.literal("tool").optional()}),Wf=X.extend({type:u.literal(v.TOOL_CALL_CHUNK),toolCallId:u.string().optional(),toolCallName:u.string().optional(),parentMessageId:u.string().optional(),delta:u.string().optional()}),Xf=X.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),Yf=X.extend({type:u.literal(v.THINKING_END)}),Kf=X.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:wf}),Zf=X.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),Jf=X.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(wl)}),Qf=X.extend({type:u.literal(v.ACTIVITY_SNAPSHOT),messageId:u.string(),activityType:u.string(),content:u.record(u.any()),replace:u.boolean().optional().default(!0)}),eh=X.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),th=X.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),nh=X.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),rh=X.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Tf.optional()}),oh=u.object({type:u.literal("success")}).strict(),ih=u.object({type:u.literal("interrupt"),interrupts:u.array(xf).min(1)}).strict(),sh=u.discriminatedUnion("type",[oh,ih]),ah=X.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:sh.nullable().optional().transform(t=>t??void 0)}),lh=X.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),ch=X.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),uh=X.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),dh=u.union([u.literal("tool-call"),u.literal("message")]),ph=X.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),fh=X.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),hh=X.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),mh=X.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),gh=X.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),vh=X.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),bh=X.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:dh,entityId:u.string(),encryptedValue:u.string()}),Fr=u.discriminatedUnion("type",[Uf,Al,Hf,Gf,Xf,Yf,Ff,$f,zf,Bf,Vf,jf,Wf,qf,Kf,Zf,Jf,Qf,eh,th,nh,rh,ah,lh,ch,uh,ph,fh,hh,mh,gh,vh,bh]);var Es={};Fi(Es,{JsonPatchError:()=>pe,_areEquals:()=>Yn,applyOperation:()=>Wt,applyPatch:()=>Wr,applyReducer:()=>wh,deepClone:()=>Eh,getValueByPointer:()=>jr,validate:()=>Il,validator:()=>qr});var yh=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)o.hasOwnProperty(i)&&(r[i]=o[i])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),xh=Object.prototype.hasOwnProperty;function zr(t,e){return xh.call(t,e)}function Br(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var o in t)zr(t,o)&&r.push(o);return r}function Te(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Vr(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 ot(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Wn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function $r(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if($r(t[e]))return!0}else if(typeof t=="object"){for(var r=Br(t),o=r.length,i=0;i<o;i++)if($r(t[r[i]]))return!0}}return!1}function kl(t,e){var n=[t];for(var r in e){var o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
|
|
2
|
-
`)}var Xn=(function(t){yh(e,t);function e(n,r,o,i,s){var a=this.constructor,l=t.call(this,kl(n,{name:r,index:o,operation:i,tree:s}))||this;return l.name=r,l.index=o,l.operation=i,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=kl(n,{name:r,index:o,operation:i,tree:s}),l}return e})(Error);var pe=Xn,Eh=Te,yn={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=jr(n,this.path);r&&(r=Te(r));var o=Wt(n,{op:"remove",path:this.from}).removed;return Wt(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=jr(n,this.from);return Wt(n,{op:"add",path:this.path,value:Te(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Yn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},Th={add:function(t,e,n){return Vr(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:yn.move,copy:yn.copy,test:yn.test,_get:yn._get};function jr(t,e){if(e=="")return t;var n={op:"_get",path:e};return Wt(t,n),n.value}function Wt(t,e,n,r,o,i){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),i===void 0&&(i=0),n&&(typeof n=="function"?n(e,0,t,e.path):qr(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=jr(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Yn(t,e.value),s.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new pe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=Te(t));var a=e.path||"",l=a.split("/"),c=t,f=1,m=l.length,y=void 0,h=void 0,p=void 0;for(typeof n=="function"?p=n:p=qr;;){if(h=l[f],h&&h.indexOf("~")!=-1&&(h=Wn(h)),o&&(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&&y===void 0&&(c[h]===void 0?y=l.slice(0,f).join("/"):f==m-1&&(y=e.path),y!==void 0&&p(e,0,t,y)),f++,Array.isArray(c)){if(h==="-")h=c.length;else{if(n&&!Vr(h))throw new pe("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Vr(h)&&(h=~~h)}if(f>=m){if(n&&e.op==="add"&&h>c.length)throw new pe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);var s=Th[e.op].call(e,c,h,t);if(s.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}}else if(f>=m){var s=yn[e.op].call(e,c,h,t);if(s.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}if(c=c[h],n&&f<m&&(!c||typeof c!="object"))throw new pe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Wr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new pe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Te(t));for(var i=new Array(e.length),s=0,a=e.length;s<a;s++)i[s]=Wt(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function wh(t,e,n){var r=Wt(t,e);if(r.test===!1)throw new pe("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function qr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new pe("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(yn[t.op]){if(typeof t.path!="string")throw new pe("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new pe('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 pe("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 pe("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")&&$r(t.value))throw new pe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new pe("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 pe("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=Il([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new pe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new pe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function Il(t,e,n){try{if(!Array.isArray(t))throw new pe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Wr(Te(e),Te(t),n||!0);else{n=n||qr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof pe)return o;throw o}}function Yn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,i,s;if(n&&r){if(i=t.length,i!=e.length)return!1;for(o=i;o--!==0;)if(!Yn(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(i=a.length,i!==Object.keys(e).length)return!1;for(o=i;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=i;o--!==0;)if(s=a[o],!Yn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var _s={};Fi(_s,{compare:()=>Rh,generate:()=>Ts,observe:()=>Nh,unobserve:()=>Ch});var ws=new WeakMap,Sh=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),_h=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function Ah(t){return ws.get(t)}function kh(t,e){return t.observers.get(e)}function Ih(t,e){t.observers.delete(e.callback)}function Ch(t,e){e.unobserve()}function Nh(t,e){var n=[],r,o=Ah(t);if(!o)o=new Sh(t),ws.set(t,o);else{var i=kh(o,e);r=i&&i.observer}if(r)return r;if(r={},o.value=Te(t),e){r.callback=e,r.next=null;var s=function(){Ts(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(){Ts(r),clearTimeout(r.next),Ih(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new _h(e,r)),r}function Ts(t,e){e===void 0&&(e=!1);var n=ws.get(t.object);Ss(n.value,t.object,t.patches,"",e),t.patches.length&&Wr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function Ss(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=Br(e),s=Br(t),a=!1,l=!1,c=s.length-1;c>=0;c--){var f=s[c],m=t[f];if(zr(e,f)&&!(e[f]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var y=e[f];typeof m=="object"&&m!=null&&typeof y=="object"&&y!=null&&Array.isArray(m)===Array.isArray(y)?Ss(m,y,n,r+"/"+ot(f),o):m!==y&&(a=!0,o&&n.push({op:"test",path:r+"/"+ot(f),value:Te(m)}),n.push({op:"replace",path:r+"/"+ot(f),value:Te(y)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+ot(f),value:Te(m)}),n.push({op:"remove",path:r+"/"+ot(f)}),l=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&i.length==s.length))for(var c=0;c<i.length;c++){var f=i[c];!zr(t,f)&&e[f]!==void 0&&n.push({op:"add",path:r+"/"+ot(f),value:Te(e[f])})}}}function Rh(t,e,n){n===void 0&&(n=!1);var r=[];return Ss(t,e,r,"",n),r}var Xr=Object.assign({},Es,_s,{JsonPatchError:Xn,deepClone:Te,escapePathComponent:ot,unescapePathComponent:Wn});var As=function(t,e){return As=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},As(t,e)};function it(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");As(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 o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,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?i(f.value):o(f.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function Yr(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,o,i,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(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,o&&(i=c[0]&2?o.return:c[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,c[1])).done)return i;switch(o=0,i&&(c=[c[0]&2,i.value]),c[0]){case 0:case 1:i=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,o=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!i||c[1]>i[0]&&c[1]<i[3])){n.label=c[1];break}if(c[0]===6&&n.label<i[1]){n.label=i[1],i=c;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(c);break}i[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(f){c=[6,f],o=0}finally{r=i=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 xn(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return i}function En(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}function Xt(t){return this instanceof Xt?(this.v=t,this):new Xt(t)}function Nl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),o[Symbol.asyncIterator]=function(){return this},o;function s(h){return function(p){return Promise.resolve(p).then(h,m)}}function a(h,p){r[h]&&(o[h]=function(g){return new Promise(function(x,_){i.push([h,g,x,_])>1||l(h,g)})},p&&(o[h]=p(o[h])))}function l(h,p){try{c(r[h](p))}catch(g){y(i[0][3],g)}}function c(h){h.value instanceof Xt?Promise.resolve(h.value.v).then(f,m):y(i[0][2],h)}function f(h){l("next",h)}function m(h){l("throw",h)}function y(h,p){h(p),i.shift(),i.length&&l(i[0][0],i[0][1])}}function Rl(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(i){n[i]=t[i]&&function(s){return new Promise(function(a,l){s=t[i](s),o(a,l,s.done,s.value)})}}function o(i,s,a,l){Promise.resolve(l).then(function(c){i({value:c,done:a})},s)}}function B(t){return typeof t=="function"}function Tn(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 Kr=Tn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
1
|
+
var Ad=Object.defineProperty;var zi=(t,e)=>{for(var n in e)Ad(t,n,{get:e[n],enumerable:!0})};var Nr="ag-ui-chat",Bi="ag-ui-submit",Vi="ag-ui-toggle",ji="ag-ui-state",Ve={USER:"user",ASSISTANT:"assistant"},Fn="x-destructive",qi="x-confirm",Le="x-summary",$n="x-navigates",Wi="read_page",Xi=10,pe={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},He={UPLOADING:"uploading",READY:"ready",ERROR:"error"},Yi=10*1024*1024,je={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"},Ki="compaction",Zi="load_capability";var kd=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function ol(t,e){let n=[];return{text:t.replace(kd,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Id(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 Ji(t){return Array.isArray(t)?t.filter(Id):[]}var zn=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 Qi(t){return t[Fn]===!0}function Rr(t){return t[$n]===!0}function Or(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Cd=Or(HTMLInputElement.prototype,"value"),Nd=Or(HTMLTextAreaElement.prototype,"value"),Rd=Or(HTMLSelectElement.prototype,"value"),Od=Or(HTMLInputElement.prototype,"checked");function Rt(t,e){t instanceof HTMLTextAreaElement?Nd.call(t,e):t instanceof HTMLSelectElement?Rd.call(t,e):Cd.call(t,e)}function Bn(t,e){Od.call(t,e)}var il="#4f46e5";function Mr(t){return new Promise(e=>{setTimeout(e,t)})}async function es(t,e,n={}){let r=n.charDelayMs??35;Rt(t,""),t.dispatchEvent(new Event("input",{bubbles:!0}));for(let o of e)Rt(t,t.value+o),t.dispatchEvent(new Event("input",{bubbles:!0})),r>0&&await Mr(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function ts(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${il}`,t.style.outlineOffset="2px",await Mr(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}function lt(t){t.scrollIntoView({block:"center",inline:"nearest",behavior:"smooth"})}async function ns(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 Mr(n),t.style.boxShadow=r}var sl="0 0 0 3px rgba(79, 70, 229, 0.4)";function al(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function rs(t){return t<=0||al()?Promise.resolve():Mr(t)}async function os(t,e={}){let n=e.pressMs??140,r=t.style.transform,o=t.style.transition,i=t.style.boxShadow;t.style.transition="transform 80ms ease",t.style.transform="scale(0.96)",t.style.boxShadow=sl,await rs(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function Md(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function is(t,e,n={}){let r=Md(t,e);if(r===null)throw new Error(`no <option> matching "${e}"`);let o=n.highlightMs??220,i=t.style.outline,s=t.style.outlineOffset;t.style.outline=`2px solid ${il}`,t.style.outlineOffset="2px",await rs(o),Rt(t,r.value),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.outline=i,t.style.outlineOffset=s}async function ss(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=sl,await rs(r),Bn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var as={SCROLL:"scroll",DRAG:"drag"};function ls(t,e){let n=[];return t.has(as.SCROLL)&&n.push(Ld(e)),t.has(as.DRAG)&&n.push(Pd(e)),n}function Ld(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"],[Le]:"Scroll into view"},handler:e=>{let n=String(e.target??"");if(n==="top"||n==="bottom"){let o=n==="top"?0:document.body.scrollHeight;return window.scrollTo({top:o,behavior:"smooth"}),{scrolled:!0,target:n}}let r=t(n);if(r===null)throw new Error(`no element matching "${n}"`);return lt(r),{scrolled:!0,target:n}}}}function Pd(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"],[Le]:"Drag and drop"},handler:e=>{let n=String(e.from??""),r=String(e.to??""),o=t(n);if(o===null)throw new Error(`no element matching "${n}"`);let i=t(r);if(i===null)throw new Error(`no element matching "${r}"`);return Dd(o,i),{dragged:!0,from:n,to:r}}}}function Dd(t,e){let n=new DataTransfer;Vn(t,"dragstart",n),Vn(e,"dragenter",n),Vn(e,"dragover",n),Vn(e,"drop",n),Vn(t,"dragend",n)}function Vn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function cs(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Lr(t){let e=[{name:`read_${t.name}`,description:`Read the "${t.name}" state.`,parameters:{type:"object",properties:{},required:[],[Le]:`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"},[Fn]:!0,[Le]:`Update ${t.name}`},handler:r=>n(r)}),e}var Ud=Lr;function us(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(n===null||typeof n!="object")continue;let r=n,o=r.name,i=r.summary;typeof o=="string"&&typeof i=="string"&&(e[o]=i)}return e}var ll=/:([A-Za-z_][A-Za-z0-9_]*)/g;function Hd(t){return[...t.matchAll(ll)].map(e=>e[0].slice(1))}function Gd(t,e,n){let r={...n};return{path:e.replace(ll,(i,s)=>{let a=n[s];if(a==null||String(a)==="")throw new Error(`route "${t}" requires path param "${s}"`);return delete r[s],encodeURIComponent(String(a))}),leftover:r}}function Fd(t,e){let n=new URLSearchParams;for(let[o,i]of Object.entries(e))n.set(o,String(i));let r=n.toString();return r===""?t:`${t}?${r}`}function ds(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:[],[Le]:"List pages"},handler:()=>t().map(n=>({...n,pathParams:Hd(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"],[$n]:!0,[Le]:"Navigate"},handler:n=>{let r=n.route_id,o=t().find(f=>f.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=Gd(o.id,o.path,i),l=Fd(s,a),u=e();return u!==null?u(l):window.location.assign(l),{navigated:!0,path:l}}}]}var ae={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",historyCompacted:"Earlier turns condensed to fit the context window ({count} removed)",usingSkill:"Using skill {name}",runInterrupted:"The previous response didn\u2019t finish \u2014 the page changed before it arrived.",pageMoved:"The page changed since you last looked at it. Call read_page to see the current page, then retry.",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 ps(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function cl(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 fs(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="approval",i.setAttribute("part","approval"),e.toolName!==void 0&&i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.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=cl("deny",r.deny),u=cl("approve",r.approve),f=!1,m=y=>{f||(f=!0,l.disabled=!0,u.disabled=!0,i.setAttribute("data-resolved",y?"approved":"denied"),o(y))};if(l.addEventListener("click",()=>m(!1)),u.addEventListener("click",()=>m(!0)),n.signal?.addEventListener("abort",()=>m(!1),{once:!0}),a.append(l,u),i.append(s,a),t.appendChild(i),n.signal?.aborted===!0){m(!1);return}u.focus()})}function hs(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild($d(n));return e}function $d(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=ms(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 o=document.createElement("span");return o.className="attachment-chip-size",o.setAttribute("part","attachment-chip-size"),o.textContent=Pr(t.size),e.append(n,r,o),e}function ms(t){return t.startsWith("image/")?"\u{1F5BC}":t==="application/pdf"?"\u{1F4D5}":t.startsWith("text/")?"\u{1F4C4}":"\u{1F4CE}"}function Pr(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 xe=[];for(let t=0;t<256;++t)xe.push((t+256).toString(16).slice(1));function ul(t,e=0){return(xe[t[e+0]]+xe[t[e+1]]+xe[t[e+2]]+xe[t[e+3]]+"-"+xe[t[e+4]]+xe[t[e+5]]+"-"+xe[t[e+6]]+xe[t[e+7]]+"-"+xe[t[e+8]]+xe[t[e+9]]+"-"+xe[t[e+10]]+xe[t[e+11]]+xe[t[e+12]]+xe[t[e+13]]+xe[t[e+14]]+xe[t[e+15]]).toLowerCase()}var gs,zd=new Uint8Array(16);function vs(){if(!gs){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");gs=crypto.getRandomValues.bind(crypto)}return gs(zd)}var Bd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),bs={randomUUID:Bd};function Vd(t,e,n){if(bs.randomUUID&&!e&&!t)return bs.randomUUID();t=t||{};let r=t.random??t.rng?.()??vs();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let o=0;o<16;++o)e[n+o]=r[o];return e}return ul(r)}var xt=Vd;var c={};zi(c,{BRAND:()=>gp,DIRTY:()=>Ot,EMPTY_PATH:()=>Xd,INVALID:()=>P,NEVER:()=>ef,OK:()=>_e,ParseStatus:()=>Ee,Schema:()=>z,ZodAny:()=>St,ZodArray:()=>pt,ZodBigInt:()=>Lt,ZodBoolean:()=>Pt,ZodBranded:()=>qn,ZodCatch:()=>qt,ZodDate:()=>Dt,ZodDefault:()=>jt,ZodDiscriminatedUnion:()=>Hr,ZodEffects:()=>$e,ZodEnum:()=>Bt,ZodError:()=>Re,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Fr,ZodIntersection:()=>Ft,ZodIssueCode:()=>T,ZodLazy:()=>$t,ZodLiteral:()=>zt,ZodMap:()=>vn,ZodNaN:()=>yn,ZodNativeEnum:()=>Vt,ZodNever:()=>qe,ZodNull:()=>Ht,ZodNullable:()=>rt,ZodNumber:()=>Mt,ZodObject:()=>Oe,ZodOptional:()=>Ge,ZodParsedType:()=>I,ZodPipeline:()=>Wn,ZodPromise:()=>wt,ZodReadonly:()=>Wt,ZodRecord:()=>Gr,ZodSchema:()=>z,ZodSet:()=>bn,ZodString:()=>Tt,ZodSymbol:()=>mn,ZodTransformer:()=>$e,ZodTuple:()=>nt,ZodType:()=>z,ZodUndefined:()=>Ut,ZodUnion:()=>Gt,ZodUnknown:()=>dt,ZodVoid:()=>gn,addIssueToContext:()=>k,any:()=>_p,array:()=>Cp,bigint:()=>xp,boolean:()=>El,coerce:()=>Qp,custom:()=>bl,date:()=>Ep,datetimeRegex:()=>gl,defaultErrorMap:()=>ct,discriminatedUnion:()=>Mp,effect:()=>jp,enum:()=>zp,function:()=>Gp,getErrorMap:()=>pn,getParsedType:()=>tt,instanceof:()=>bp,intersection:()=>Lp,isAborted:()=>Dr,isAsync:()=>fn,isDirty:()=>Ur,isValid:()=>Et,late:()=>vp,lazy:()=>Fp,literal:()=>$p,makeIssue:()=>jn,map:()=>Up,nan:()=>yp,nativeEnum:()=>Bp,never:()=>kp,null:()=>wp,nullable:()=>Wp,number:()=>xl,object:()=>Np,objectUtil:()=>ys,oboolean:()=>Jp,onumber:()=>Zp,optional:()=>qp,ostring:()=>Kp,pipeline:()=>Yp,preprocess:()=>Xp,promise:()=>Vp,quotelessJson:()=>jd,record:()=>Dp,set:()=>Hp,setErrorMap:()=>Wd,strictObject:()=>Rp,string:()=>yl,symbol:()=>Tp,transformer:()=>jp,tuple:()=>Pp,undefined:()=>Sp,union:()=>Op,unknown:()=>Ap,util:()=>V,void:()=>Ip});var V;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let i={};for(let s of o)i[s]=s;return i},t.getValidEnumValues=o=>{let i=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),s={};for(let a of i)s[a]=o[a];return t.objectValues(s)},t.objectValues=o=>t.objectKeys(o).map(function(i){return o[i]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},t.find=(o,i)=>{for(let s of o)if(i(s))return s},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(V||(V={}));var ys;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(ys||(ys={}));var I=V.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),tt=t=>{switch(typeof t){case"undefined":return I.undefined;case"string":return I.string;case"number":return Number.isNaN(t)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":return Array.isArray(t)?I.array:t===null?I.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?I.promise:typeof Map<"u"&&t instanceof Map?I.map:typeof Set<"u"&&t instanceof Set?I.set:typeof Date<"u"&&t instanceof Date?I.date:I.object;default:return I.unknown}};var T=V.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"]),jd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Re=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(i){return i.message},r={_errors:[]},o=i=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(o);else if(s.code==="invalid_return_type")o(s.returnTypeError);else if(s.code==="invalid_arguments")o(s.argumentsError);else if(s.path.length===0)r._errors.push(n(s));else{let a=r,l=0;for(;l<s.path.length;){let u=s.path[l];l===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(n(s))):a[u]=a[u]||{_errors:[]},a=a[u],l++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,V.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let i=o.path[0];n[i]=n[i]||[],n[i].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};Re.create=t=>new Re(t);var qd=(t,e)=>{let n;switch(t.code){case T.invalid_type:t.received===I.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,V.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(t.keys,", ")}`;break;case T.invalid_union:n="Invalid input";break;case T.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(t.options)}`;break;case T.invalid_enum_value:n=`Invalid enum value. Expected ${V.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}"`:V.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,V.assertNever(t)}return{message:n}},ct=qd;var dl=ct;function Wd(t){dl=t}function pn(){return dl}var jn=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,i=[...n,...o.path||[]],s={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let a="",l=r.filter(u=>!!u).slice().reverse();for(let u of l)a=u(s,{data:e,defaultError:a}).message;return{...o,path:i,message:a}},Xd=[];function k(t,e){let n=pn(),r=jn({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===ct?void 0:ct].filter(o=>!!o)});t.common.issues.push(r)}var Ee=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return P;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let i=await o.key,s=await o.value;r.push({key:i,value:s})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return P;i.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:e.value,value:r}}},P=Object.freeze({status:"aborted"}),Ot=t=>({status:"dirty",value:t}),_e=t=>({status:"valid",value:t}),Dr=t=>t.status==="aborted",Ur=t=>t.status==="dirty",Et=t=>t.status==="valid",fn=t=>typeof Promise<"u"&&t instanceof Promise;var N;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(N||(N={}));var Fe=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pl=(t,e)=>{if(Et(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 Re(t.common.issues);return this._error=n,this._error}}};function F(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(s,a)=>{let{message:l}=t;return s.code==="invalid_enum_value"?{message:l??a.defaultError}:typeof a.data>"u"?{message:l??r??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:l??n??a.defaultError}},description:o}}var z=class{get description(){return this._def.description}_getType(e){return tt(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ee,ctx:{common:e.parent.common,data:e.data,parsedType:tt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(fn(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:tt(e)},o=this._parseSync({data:e,path:r.path,parent:r});return pl(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:tt(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Et(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=>Et(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:tt(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(fn(o)?o:Promise.resolve(o));return pl(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:T.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new $e({schema:this,typeName:D.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 Ge.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return wt.create(this,this._def)}or(e){return Gt.create([this,e],this._def)}and(e){return Ft.create(this,e,this._def)}transform(e){return new $e({...F(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new jt({...F(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new qn({typeName:D.ZodBranded,type:this,...F(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new qt({...F(this._def),innerType:this,catchValue:n,typeName:D.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Wn.create(this,e)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Yd=/^c[^\s-]{8,}$/i,Kd=/^[0-9a-z]+$/,Zd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Jd=/^[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,Qd=/^[a-z0-9_-]{21}$/i,ep=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tp=/^[-+]?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)?)??$/,np=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xs,op=/^(?:(?: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])$/,ip=/^(?:(?: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])$/,sp=/^(([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]))$/,ap=/^(([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])$/,lp=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,cp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hl="((\\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])))",up=new RegExp(`^${hl}$`);function ml(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 dp(t){return new RegExp(`^${ml(t)}$`)}function gl(t){let e=`${hl}T${ml(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 pp(t,e){return!!((e==="v4"||!e)&&op.test(t)||(e==="v6"||!e)&&sp.test(t))}function fp(t,e){if(!ep.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function hp(t,e){return!!((e==="v4"||!e)&&ip.test(t)||(e==="v6"||!e)&&ap.test(t))}var Tt=class t extends z{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.string){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_type,expected:I.string,received:i.parsedType}),P}let r=new Ee,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?k(o,{code:T.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&k(o,{code:T.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")np.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"email",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")xs||(xs=new RegExp(rp,"u")),xs.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Jd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Qd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Yd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Kd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Zd.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:T.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:T.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:T.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?gl(i).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?up.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?dp(i).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:T.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?tp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?pp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?fp(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?hp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?lp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:T.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?cp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:T.invalid_string,message:i.message}),r.dirty()):V.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:T.invalid_string,...N.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...N.errToObj(e)})}url(e){return this._addCheck({kind:"url",...N.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...N.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...N.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...N.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...N.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...N.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...N.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...N.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...N.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...N.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...N.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...N.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...N.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...N.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...N.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...N.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...N.errToObj(n)})}nonempty(e){return this.min(1,N.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}};Tt.create=t=>new Tt({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...F(t)});function mp(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,i=Number.parseInt(t.toFixed(o).replace(".","")),s=Number.parseInt(e.toFixed(o).replace(".",""));return i%s/10**o}var Mt=class t extends z{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)!==I.number){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_type,expected:I.number,received:i.parsedType}),P}let r,o=new Ee;for(let i of this._def.checks)i.kind==="int"?V.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:T.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?mp(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:T.not_finite,message:i.message}),o.dirty()):V.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:N.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:N.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:N.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:N.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"&&V.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)}};Mt.create=t=>new Mt({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...F(t)});var Lt=class t extends z{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)!==I.bigint)return this._getInvalidInput(e);let r,o=new Ee;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),k(r,{code:T.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):V.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return k(n,{code:T.invalid_type,expected:I.bigint,received:n.parsedType}),P}gte(e,n){return this.setLimit("min",e,!0,N.toString(n))}gt(e,n){return this.setLimit("min",e,!1,N.toString(n))}lte(e,n){return this.setLimit("max",e,!0,N.toString(n))}lt(e,n){return this.setLimit("max",e,!1,N.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:N.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:N.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}};Lt.create=t=>new Lt({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...F(t)});var Pt=class extends z{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.boolean,received:r.parsedType}),P}return _e(e.data)}};Pt.create=t=>new Pt({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...F(t)});var Dt=class t extends z{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.date){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_type,expected:I.date,received:i.parsedType}),P}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return k(i,{code:T.invalid_date}),P}let r=new Ee,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:T.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):V.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:N.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:N.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}};Dt.create=t=>new Dt({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...F(t)});var mn=class extends z{_parse(e){if(this._getType(e)!==I.symbol){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.symbol,received:r.parsedType}),P}return _e(e.data)}};mn.create=t=>new mn({typeName:D.ZodSymbol,...F(t)});var Ut=class extends z{_parse(e){if(this._getType(e)!==I.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.undefined,received:r.parsedType}),P}return _e(e.data)}};Ut.create=t=>new Ut({typeName:D.ZodUndefined,...F(t)});var Ht=class extends z{_parse(e){if(this._getType(e)!==I.null){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.null,received:r.parsedType}),P}return _e(e.data)}};Ht.create=t=>new Ht({typeName:D.ZodNull,...F(t)});var St=class extends z{constructor(){super(...arguments),this._any=!0}_parse(e){return _e(e.data)}};St.create=t=>new St({typeName:D.ZodAny,...F(t)});var dt=class extends z{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _e(e.data)}};dt.create=t=>new dt({typeName:D.ZodUnknown,...F(t)});var qe=class extends z{_parse(e){let n=this._getOrReturnCtx(e);return k(n,{code:T.invalid_type,expected:I.never,received:n.parsedType}),P}};qe.create=t=>new qe({typeName:D.ZodNever,...F(t)});var gn=class extends z{_parse(e){if(this._getType(e)!==I.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.void,received:r.parsedType}),P}return _e(e.data)}};gn.create=t=>new gn({typeName:D.ZodVoid,...F(t)});var pt=class t extends z{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==I.array)return k(n,{code:T.invalid_type,expected:I.array,received:n.parsedType}),P;if(o.exactLength!==null){let s=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(s||a)&&(k(n,{code:s?T.too_big:T.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(k(n,{code:T.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(k(n,{code:T.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Fe(n,s,n.path,a)))).then(s=>Ee.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Fe(n,s,n.path,a)));return Ee.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:N.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:N.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:N.toString(n)}})}nonempty(e){return this.min(1,e)}};pt.create=(t,e)=>new pt({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...F(e)});function hn(t){if(t instanceof Oe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=Ge.create(hn(r))}return new Oe({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:hn(t.element)}):t instanceof Ge?Ge.create(hn(t.unwrap())):t instanceof rt?rt.create(hn(t.unwrap())):t instanceof nt?nt.create(t.items.map(e=>hn(e))):t}var Oe=class t extends z{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=V.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==I.object){let u=this._getOrReturnCtx(e);return k(u,{code:T.invalid_type,expected:I.object,received:u.parsedType}),P}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof qe&&this._def.unknownKeys==="strip"))for(let u in o.data)s.includes(u)||a.push(u);let l=[];for(let u of s){let f=i[u],m=o.data[u];l.push({key:{status:"valid",value:u},value:f._parse(new Fe(o,m,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof qe){let u=this._def.unknownKeys;if(u==="passthrough")for(let f of a)l.push({key:{status:"valid",value:f},value:{status:"valid",value:o.data[f]}});else if(u==="strict")a.length>0&&(k(o,{code:T.unrecognized_keys,keys:a}),r.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let f of a){let m=o.data[f];l.push({key:{status:"valid",value:f},value:u._parse(new Fe(o,m,o.path,f)),alwaysSet:f in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let f of l){let m=await f.key,y=await f.value;u.push({key:m,value:y,alwaysSet:f.alwaysSet})}return u}).then(u=>Ee.mergeObjectSync(r,u)):Ee.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return N.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:N.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.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 V.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 V.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return hn(this)}partial(e){let n={};for(let r of V.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of V.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ge;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return vl(V.objectKeys(this.shape))}};Oe.create=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strip",catchall:qe.create(),typeName:D.ZodObject,...F(e)});Oe.strictCreate=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strict",catchall:qe.create(),typeName:D.ZodObject,...F(e)});Oe.lazycreate=(t,e)=>new Oe({shape:t,unknownKeys:"strip",catchall:qe.create(),typeName:D.ZodObject,...F(e)});var Gt=class extends z{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(i){for(let a of i)if(a.result.status==="valid")return a.result;for(let a of i)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(a=>new Re(a.ctx.common.issues));return k(n,{code:T.invalid_union,unionErrors:s}),P}if(n.common.async)return Promise.all(r.map(async i=>{let s={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:s}),ctx:s}})).then(o);{let i,s=[];for(let l of r){let u={...n,common:{...n.common,issues:[]},parent:null},f=l._parseSync({data:n.data,path:n.path,parent:u});if(f.status==="valid")return f;f.status==="dirty"&&!i&&(i={result:f,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;let a=s.map(l=>new Re(l));return k(n,{code:T.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};Gt.create=(t,e)=>new Gt({options:t,typeName:D.ZodUnion,...F(e)});var ut=t=>t instanceof $t?ut(t.schema):t instanceof $e?ut(t.innerType()):t instanceof zt?[t.value]:t instanceof Bt?t.options:t instanceof Vt?V.objectValues(t.enum):t instanceof jt?ut(t._def.innerType):t instanceof Ut?[void 0]:t instanceof Ht?[null]:t instanceof Ge?[void 0,...ut(t.unwrap())]:t instanceof rt?[null,...ut(t.unwrap())]:t instanceof qn||t instanceof Wt?ut(t.unwrap()):t instanceof qt?ut(t._def.innerType):[],Hr=class t extends z{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.object)return k(n,{code:T.invalid_type,expected:I.object,received:n.parsedType}),P;let r=this.discriminator,o=n.data[r],i=this.optionsMap.get(o);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(k(n,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),P)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let i of n){let s=ut(i.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of s){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,i)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...F(r)})}};function Es(t,e){let n=tt(t),r=tt(e);if(t===e)return{valid:!0,data:t};if(n===I.object&&r===I.object){let o=V.objectKeys(e),i=V.objectKeys(t).filter(a=>o.indexOf(a)!==-1),s={...t,...e};for(let a of i){let l=Es(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===I.array&&r===I.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<t.length;i++){let s=t[i],a=e[i],l=Es(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===I.date&&r===I.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ft=class extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(Dr(i)||Dr(s))return P;let a=Es(i.value,s.value);return a.valid?((Ur(i)||Ur(s))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:T.invalid_intersection_types}),P)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>o(i,s)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ft.create=(t,e,n)=>new Ft({left:t,right:e,typeName:D.ZodIntersection,...F(n)});var nt=class t extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.array)return k(r,{code:T.invalid_type,expected:I.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return k(r,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),P;!this._def.rest&&r.data.length>this._def.items.length&&(k(r,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Fe(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>Ee.mergeArray(n,s)):Ee.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};nt.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new nt({items:t,typeName:D.ZodTuple,rest:null,...F(e)})};var Gr=class t extends z{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!==I.object)return k(r,{code:T.invalid_type,expected:I.object,received:r.parsedType}),P;let o=[],i=this._def.keyType,s=this._def.valueType;for(let a in r.data)o.push({key:i._parse(new Fe(r,a,r.path,a)),value:s._parse(new Fe(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ee.mergeObjectAsync(n,o):Ee.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof z?new t({keyType:e,valueType:n,typeName:D.ZodRecord,...F(r)}):new t({keyType:Tt.create(),valueType:e,typeName:D.ZodRecord,...F(n)})}},vn=class extends z{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!==I.map)return k(r,{code:T.invalid_type,expected:I.map,received:r.parsedType}),P;let o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([a,l],u)=>({key:o._parse(new Fe(r,a,r.path,[u,"key"])),value:i._parse(new Fe(r,l,r.path,[u,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let l of s){let u=await l.key,f=await l.value;if(u.status==="aborted"||f.status==="aborted")return P;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let u=l.key,f=l.value;if(u.status==="aborted"||f.status==="aborted")return P;(u.status==="dirty"||f.status==="dirty")&&n.dirty(),a.set(u.value,f.value)}return{status:n.value,value:a}}}};vn.create=(t,e,n)=>new vn({valueType:e,keyType:t,typeName:D.ZodMap,...F(n)});var bn=class t extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.set)return k(r,{code:T.invalid_type,expected:I.set,received:r.parsedType}),P;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(k(r,{code:T.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(k(r,{code:T.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let u=new Set;for(let f of l){if(f.status==="aborted")return P;f.status==="dirty"&&n.dirty(),u.add(f.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((l,u)=>i._parse(new Fe(r,l,r.path,u)));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:N.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:N.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};bn.create=(t,e)=>new bn({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...F(e)});var Fr=class t extends z{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.function)return k(n,{code:T.invalid_type,expected:I.function,received:n.parsedType}),P;function r(a,l){return jn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),ct].filter(u=>!!u),issueData:{code:T.invalid_arguments,argumentsError:l}})}function o(a,l){return jn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,pn(),ct].filter(u=>!!u),issueData:{code:T.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof wt){let a=this;return _e(async function(...l){let u=new Re([]),f=await a._def.args.parseAsync(l,i).catch(h=>{throw u.addIssue(r(l,h)),u}),m=await Reflect.apply(s,this,f);return await a._def.returns._def.type.parseAsync(m,i).catch(h=>{throw u.addIssue(o(m,h)),u})})}else{let a=this;return _e(function(...l){let u=a._def.args.safeParse(l,i);if(!u.success)throw new Re([r(l,u.error)]);let f=Reflect.apply(s,this,u.data),m=a._def.returns.safeParse(f,i);if(!m.success)throw new Re([o(f,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:nt.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||nt.create([]).rest(dt.create()),returns:n||dt.create(),typeName:D.ZodFunction,...F(r)})}},$t=class extends z{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})}};$t.create=(t,e)=>new $t({getter:t,typeName:D.ZodLazy,...F(e)});var zt=class extends z{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return k(n,{received:n.data,code:T.invalid_literal,expected:this._def.value}),P}return{status:"valid",value:e.data}}get value(){return this._def.value}};zt.create=(t,e)=>new zt({value:t,typeName:D.ZodLiteral,...F(e)});function vl(t,e){return new Bt({values:t,typeName:D.ZodEnum,...F(e)})}var Bt=class t extends z{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return k(n,{expected:V.joinValues(r),received:n.parsedType,code:T.invalid_type}),P}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 k(n,{received:n.data,code:T.invalid_enum_value,options:r}),P}return _e(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})}};Bt.create=vl;var Vt=class extends z{_parse(e){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==I.string&&r.parsedType!==I.number){let o=V.objectValues(n);return k(r,{expected:V.joinValues(o),received:r.parsedType,code:T.invalid_type}),P}if(this._cache||(this._cache=new Set(V.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=V.objectValues(n);return k(r,{received:r.data,code:T.invalid_enum_value,options:o}),P}return _e(e.data)}get enum(){return this._def.values}};Vt.create=(t,e)=>new Vt({values:t,typeName:D.ZodNativeEnum,...F(e)});var wt=class extends z{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.promise&&n.common.async===!1)return k(n,{code:T.invalid_type,expected:I.promise,received:n.parsedType}),P;let r=n.parsedType===I.promise?n.data:Promise.resolve(n.data);return _e(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};wt.create=(t,e)=>new wt({type:t,typeName:D.ZodPromise,...F(e)});var $e=class extends z{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s=>{k(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let s=o.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async a=>{if(n.value==="aborted")return P;let l=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return l.status==="aborted"?P:l.status==="dirty"?Ot(l.value):n.value==="dirty"?Ot(l.value):l});{if(n.value==="aborted")return P;let a=this._def.schema._parseSync({data:s,path:r.path,parent:r});return a.status==="aborted"?P:a.status==="dirty"?Ot(a.value):n.value==="dirty"?Ot(a.value):a}}if(o.type==="refinement"){let s=a=>{let l=o.refinement(a,i);if(r.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?P:(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"?P:(a.status==="dirty"&&n.dirty(),s(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Et(s))return P;let a=o.transform(s.value,i);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Et(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):P);V.assertNever(o)}};$e.create=(t,e,n)=>new $e({schema:t,typeName:D.ZodEffects,effect:e,...F(n)});$e.createWithPreprocess=(t,e,n)=>new $e({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...F(n)});var Ge=class extends z{_parse(e){return this._getType(e)===I.undefined?_e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(t,e)=>new Ge({innerType:t,typeName:D.ZodOptional,...F(e)});var rt=class extends z{_parse(e){return this._getType(e)===I.null?_e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(t,e)=>new rt({innerType:t,typeName:D.ZodNullable,...F(e)});var jt=class extends z{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===I.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};jt.create=(t,e)=>new jt({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...F(e)});var qt=class extends z{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return fn(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Re(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Re(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};qt.create=(t,e)=>new qt({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...F(e)});var yn=class extends z{_parse(e){if(this._getType(e)!==I.nan){let r=this._getOrReturnCtx(e);return k(r,{code:T.invalid_type,expected:I.nan,received:r.parsedType}),P}return{status:"valid",value:e.data}}};yn.create=t=>new yn({typeName:D.ZodNaN,...F(t)});var gp=Symbol("zod_brand"),qn=class extends z{_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}},Wn=class t extends z{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?P:i.status==="dirty"?(n.dirty(),Ot(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?P:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:D.ZodPipeline})}},Wt=class extends z{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Et(o)&&(o.value=Object.freeze(o.value)),o);return fn(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Wt.create=(t,e)=>new Wt({innerType:t,typeName:D.ZodReadonly,...F(e)});function fl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function bl(t,e={},n){return t?St.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=fl(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=fl(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):St.create()}var vp={object:Oe.lazycreate},D;(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"})(D||(D={}));var bp=(t,e={message:`Input not instance of ${t.name}`})=>bl(n=>n instanceof t,e),yl=Tt.create,xl=Mt.create,yp=yn.create,xp=Lt.create,El=Pt.create,Ep=Dt.create,Tp=mn.create,Sp=Ut.create,wp=Ht.create,_p=St.create,Ap=dt.create,kp=qe.create,Ip=gn.create,Cp=pt.create,Np=Oe.create,Rp=Oe.strictCreate,Op=Gt.create,Mp=Hr.create,Lp=Ft.create,Pp=nt.create,Dp=Gr.create,Up=vn.create,Hp=bn.create,Gp=Fr.create,Fp=$t.create,$p=zt.create,zp=Bt.create,Bp=Vt.create,Vp=wt.create,jp=$e.create,qp=Ge.create,Wp=rt.create,Xp=$e.createWithPreprocess,Yp=Wn.create,Kp=()=>yl().optional(),Zp=()=>xl().optional(),Jp=()=>El().optional(),Qp={string:(t=>Tt.create({...t,coerce:!0})),number:(t=>Mt.create({...t,coerce:!0})),boolean:(t=>Pt.create({...t,coerce:!0})),bigint:(t=>Lt.create({...t,coerce:!0})),date:(t=>Dt.create({...t,coerce:!0}))};var ef=P;var tf=c.object({name:c.string(),arguments:c.string()}),nf=c.object({id:c.string(),type:c.literal("function"),function:tf,encryptedValue:c.string().optional()}),$r=c.object({id:c.string(),role:c.string(),content:c.string().optional(),name:c.string().optional(),encryptedValue:c.string().optional()}),rf=c.object({type:c.literal("text"),text:c.string()}),of=c.object({type:c.literal("data"),value:c.string(),mimeType:c.string()}),sf=c.object({type:c.literal("url"),value:c.string(),mimeType:c.string().optional()}),zr=c.discriminatedUnion("type",[of,sf]),af=c.object({type:c.literal("image"),source:zr,metadata:c.unknown().optional()}),lf=c.object({type:c.literal("audio"),source:zr,metadata:c.unknown().optional()}),cf=c.object({type:c.literal("video"),source:zr,metadata:c.unknown().optional()}),uf=c.object({type:c.literal("document"),source:zr,metadata:c.unknown().optional()});var Tl=c.object({type:c.literal("binary"),mimeType:c.string(),id:c.string().optional(),url:c.string().optional(),data:c.string().optional(),filename:c.string().optional()}),Sl=(t,e)=>{!t.id&&!t.url&&!t.data&&e.addIssue({code:c.ZodIssueCode.custom,message:"BinaryInputContent requires at least one of id, url, or data.",path:["id"]})},Yb=Tl.superRefine((t,e)=>{Sl(t,e)}),df=c.discriminatedUnion("type",[rf,af,lf,cf,uf,Tl]),pf=df.superRefine((t,e)=>{t.type==="binary"&&Sl(t,e)}),ff=$r.extend({role:c.literal("developer"),content:c.string()}),hf=$r.extend({role:c.literal("system"),content:c.string()}),mf=$r.extend({role:c.literal("assistant"),content:c.string().optional(),toolCalls:c.array(nf).optional()}),gf=$r.extend({role:c.literal("user"),content:c.union([c.string(),c.array(pf)])}),vf=c.object({id:c.string(),content:c.string(),role:c.literal("tool"),toolCallId:c.string(),error:c.string().optional(),encryptedValue:c.string().optional()}),bf=c.object({id:c.string(),role:c.literal("activity"),activityType:c.string(),content:c.record(c.any())}),yf=c.object({id:c.string(),role:c.literal("reasoning"),content:c.string(),encryptedValue:c.string().optional()}),wl=c.discriminatedUnion("role",[ff,hf,mf,gf,vf,bf,yf]),Kb=c.union([c.literal("developer"),c.literal("system"),c.literal("assistant"),c.literal("user"),c.literal("tool"),c.literal("activity"),c.literal("reasoning")]),xf=c.object({description:c.string(),value:c.string()}),_l=c.object({name:c.string(),description:c.string(),parameters:c.any(),metadata:c.record(c.any()).optional()}),Ef=c.object({id:c.string(),reason:c.string(),message:c.string().optional(),toolCallId:c.string().optional(),responseSchema:c.record(c.any()).optional(),expiresAt:c.string().optional(),metadata:c.record(c.any()).optional()}),Tf=c.object({interruptId:c.string(),status:c.enum(["resolved","cancelled"]),payload:c.any().optional()}),Sf=c.object({threadId:c.string(),runId:c.string(),parentRunId:c.string().optional(),state:c.any(),messages:c.array(wl),tools:c.array(_l),context:c.array(xf),forwardedProps:c.any(),resume:c.array(Tf).optional()}),wf=c.any(),ee=class extends Error{constructor(t){super(t)}},Ts=class extends ee{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},_f=c.object({name:c.string(),description:c.string().optional()}),Af=c.object({name:c.string().optional(),type:c.string().optional(),description:c.string().optional(),version:c.string().optional(),provider:c.string().optional(),documentationUrl:c.string().optional(),metadata:c.record(c.unknown()).optional()}),kf=c.object({streaming:c.boolean().optional(),websocket:c.boolean().optional(),httpBinary:c.boolean().optional(),pushNotifications:c.boolean().optional(),resumable:c.boolean().optional()}),If=c.object({supported:c.boolean().optional(),items:c.array(_l).optional(),parallelCalls:c.boolean().optional(),clientProvided:c.boolean().optional()}),Cf=c.object({structuredOutput:c.boolean().optional(),supportedMimeTypes:c.array(c.string()).optional()}),Nf=c.object({snapshots:c.boolean().optional(),deltas:c.boolean().optional(),memory:c.boolean().optional(),persistentState:c.boolean().optional()}),Rf=c.object({supported:c.boolean().optional(),delegation:c.boolean().optional(),handoffs:c.boolean().optional(),subAgents:c.array(_f).optional()}),Of=c.object({supported:c.boolean().optional(),streaming:c.boolean().optional(),encrypted:c.boolean().optional()}),Mf=c.object({image:c.boolean().optional(),audio:c.boolean().optional(),video:c.boolean().optional(),pdf:c.boolean().optional(),file:c.boolean().optional()}),Lf=c.object({image:c.boolean().optional(),audio:c.boolean().optional()}),Pf=c.object({input:Mf.optional(),output:Lf.optional()}),Df=c.object({codeExecution:c.boolean().optional(),sandboxed:c.boolean().optional(),maxIterations:c.number().optional(),maxExecutionTime:c.number().optional()}),Uf=c.object({supported:c.boolean().optional(),approvals:c.boolean().optional(),interventions:c.boolean().optional(),feedback:c.boolean().optional(),interrupts:c.boolean().optional(),approveWithEdits:c.boolean().optional()}),Zb=c.object({identity:Af.optional(),transport:kf.optional(),tools:If.optional(),output:Cf.optional(),state:Nf.optional(),multiAgent:Rf.optional(),reasoning:Of.optional(),multimodal:Pf.optional(),execution:Df.optional(),humanInTheLoop:Uf.optional(),custom:c.record(c.unknown()).optional()}),Al=c.union([c.literal("developer"),c.literal("system"),c.literal("assistant"),c.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})({}),X=c.object({type:c.nativeEnum(v),timestamp:c.number().optional(),rawEvent:c.any().optional()}).passthrough(),Hf=X.extend({type:c.literal(v.TEXT_MESSAGE_START),messageId:c.string(),role:Al.default("assistant"),name:c.string().optional()}),kl=X.extend({type:c.literal(v.TEXT_MESSAGE_CONTENT),messageId:c.string(),delta:c.string()}),Gf=X.extend({type:c.literal(v.TEXT_MESSAGE_END),messageId:c.string()}),Ff=X.extend({type:c.literal(v.TEXT_MESSAGE_CHUNK),messageId:c.string().optional(),role:Al.optional(),delta:c.string().optional(),name:c.string().optional()}),$f=X.extend({type:c.literal(v.THINKING_TEXT_MESSAGE_START)}),zf=kl.omit({messageId:!0,type:!0}).extend({type:c.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),Bf=X.extend({type:c.literal(v.THINKING_TEXT_MESSAGE_END)}),Vf=X.extend({type:c.literal(v.TOOL_CALL_START),toolCallId:c.string(),toolCallName:c.string(),parentMessageId:c.string().optional()}),jf=X.extend({type:c.literal(v.TOOL_CALL_ARGS),toolCallId:c.string(),delta:c.string()}),qf=X.extend({type:c.literal(v.TOOL_CALL_END),toolCallId:c.string()}),Wf=X.extend({messageId:c.string(),type:c.literal(v.TOOL_CALL_RESULT),toolCallId:c.string(),content:c.string(),role:c.literal("tool").optional()}),Xf=X.extend({type:c.literal(v.TOOL_CALL_CHUNK),toolCallId:c.string().optional(),toolCallName:c.string().optional(),parentMessageId:c.string().optional(),delta:c.string().optional()}),Yf=X.extend({type:c.literal(v.THINKING_START),title:c.string().optional()}),Kf=X.extend({type:c.literal(v.THINKING_END)}),Zf=X.extend({type:c.literal(v.STATE_SNAPSHOT),snapshot:wf}),Jf=X.extend({type:c.literal(v.STATE_DELTA),delta:c.array(c.any())}),Qf=X.extend({type:c.literal(v.MESSAGES_SNAPSHOT),messages:c.array(wl)}),eh=X.extend({type:c.literal(v.ACTIVITY_SNAPSHOT),messageId:c.string(),activityType:c.string(),content:c.record(c.any()),replace:c.boolean().optional().default(!0)}),th=X.extend({type:c.literal(v.ACTIVITY_DELTA),messageId:c.string(),activityType:c.string(),patch:c.array(c.any())}),nh=X.extend({type:c.literal(v.RAW),event:c.any(),source:c.string().optional()}),rh=X.extend({type:c.literal(v.CUSTOM),name:c.string(),value:c.any()}),oh=X.extend({type:c.literal(v.RUN_STARTED),threadId:c.string(),runId:c.string(),parentRunId:c.string().optional(),input:Sf.optional()}),ih=c.object({type:c.literal("success")}).strict(),sh=c.object({type:c.literal("interrupt"),interrupts:c.array(Ef).min(1)}).strict(),ah=c.discriminatedUnion("type",[ih,sh]),lh=X.extend({type:c.literal(v.RUN_FINISHED),threadId:c.string(),runId:c.string(),result:c.any().optional(),outcome:ah.nullable().optional().transform(t=>t??void 0)}),ch=X.extend({type:c.literal(v.RUN_ERROR),message:c.string(),code:c.string().optional()}),uh=X.extend({type:c.literal(v.STEP_STARTED),stepName:c.string()}),dh=X.extend({type:c.literal(v.STEP_FINISHED),stepName:c.string()}),ph=c.union([c.literal("tool-call"),c.literal("message")]),fh=X.extend({type:c.literal(v.REASONING_START),messageId:c.string()}),hh=X.extend({type:c.literal(v.REASONING_MESSAGE_START),messageId:c.string(),role:c.literal("reasoning")}),mh=X.extend({type:c.literal(v.REASONING_MESSAGE_CONTENT),messageId:c.string(),delta:c.string()}),gh=X.extend({type:c.literal(v.REASONING_MESSAGE_END),messageId:c.string()}),vh=X.extend({type:c.literal(v.REASONING_MESSAGE_CHUNK),messageId:c.string().optional(),delta:c.string().optional()}),bh=X.extend({type:c.literal(v.REASONING_END),messageId:c.string()}),yh=X.extend({type:c.literal(v.REASONING_ENCRYPTED_VALUE),subtype:ph,entityId:c.string(),encryptedValue:c.string()}),Br=c.discriminatedUnion("type",[Hf,kl,Gf,Ff,Yf,Kf,$f,zf,Bf,Vf,jf,qf,Xf,Wf,Zf,Jf,Qf,eh,th,nh,rh,oh,lh,ch,uh,dh,fh,hh,mh,gh,vh,bh,yh]);var Ss={};zi(Ss,{JsonPatchError:()=>fe,_areEquals:()=>Kn,applyOperation:()=>Xt,applyPatch:()=>Kr,applyReducer:()=>wh,deepClone:()=>Th,getValueByPointer:()=>Xr,validate:()=>Cl,validator:()=>Yr});var xh=(function(){var t=function(e,n){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,o){r.__proto__=o}||function(r,o){for(var i in o)o.hasOwnProperty(i)&&(r[i]=o[i])},t(e,n)};return function(e,n){t(e,n);function r(){this.constructor=e}e.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Eh=Object.prototype.hasOwnProperty;function jr(t,e){return Eh.call(t,e)}function qr(t){if(Array.isArray(t)){for(var e=new Array(t.length),n=0;n<e.length;n++)e[n]=""+n;return e}if(Object.keys)return Object.keys(t);var r=[];for(var o in t)jr(t,o)&&r.push(o);return r}function Te(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Wr(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 ot(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function Xn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Vr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Vr(t[e]))return!0}else if(typeof t=="object"){for(var r=qr(t),o=r.length,i=0;i<o;i++)if(Vr(t[r[i]]))return!0}}return!1}function Il(t,e){var n=[t];for(var r in e){var o=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof o<"u"&&n.push(r+": "+o)}return n.join(`
|
|
2
|
+
`)}var Yn=(function(t){xh(e,t);function e(n,r,o,i,s){var a=this.constructor,l=t.call(this,Il(n,{name:r,index:o,operation:i,tree:s}))||this;return l.name=r,l.index=o,l.operation=i,l.tree=s,Object.setPrototypeOf(l,a.prototype),l.message=Il(n,{name:r,index:o,operation:i,tree:s}),l}return e})(Error);var fe=Yn,Th=Te,xn={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=Xr(n,this.path);r&&(r=Te(r));var o=Xt(n,{op:"remove",path:this.from}).removed;return Xt(n,{op:"add",path:this.path,value:o}),{newDocument:n,removed:r}},copy:function(t,e,n){var r=Xr(n,this.from);return Xt(n,{op:"add",path:this.path,value:Te(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Kn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},Sh={add:function(t,e,n){return Wr(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:xn.move,copy:xn.copy,test:xn.test,_get:xn._get};function Xr(t,e){if(e=="")return t;var n={op:"_get",path:e};return Xt(t,n),n.value}function Xt(t,e,n,r,o,i){if(n===void 0&&(n=!1),r===void 0&&(r=!0),o===void 0&&(o=!0),i===void 0&&(i=0),n&&(typeof n=="function"?n(e,0,t,e.path):Yr(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=Xr(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Kn(t,e.value),s.test===!1)throw new fe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s.newDocument=t,s}else{if(e.op==="remove")return s.removed=t,s.newDocument=null,s;if(e.op==="_get")return e.value=t,s;if(n)throw new fe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=Te(t));var a=e.path||"",l=a.split("/"),u=t,f=1,m=l.length,y=void 0,h=void 0,p=void 0;for(typeof n=="function"?p=n:p=Yr;;){if(h=l[f],h&&h.indexOf("~")!=-1&&(h=Xn(h)),o&&(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&&y===void 0&&(u[h]===void 0?y=l.slice(0,f).join("/"):f==m-1&&(y=e.path),y!==void 0&&p(e,0,t,y)),f++,Array.isArray(u)){if(h==="-")h=u.length;else{if(n&&!Wr(h))throw new fe("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",i,e,t);Wr(h)&&(h=~~h)}if(f>=m){if(n&&e.op==="add"&&h>u.length)throw new fe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);var s=Sh[e.op].call(e,u,h,t);if(s.test===!1)throw new fe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}}else if(f>=m){var s=xn[e.op].call(e,u,h,t);if(s.test===!1)throw new fe("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}if(u=u[h],n&&f<m&&(!u||typeof u!="object"))throw new fe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Kr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new fe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Te(t));for(var i=new Array(e.length),s=0,a=e.length;s<a;s++)i[s]=Xt(t,e[s],n,!0,o,s),t=i[s].newDocument;return i.newDocument=t,i}function wh(t,e,n){var r=Xt(t,e);if(r.test===!1)throw new fe("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Yr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new fe("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(xn[t.op]){if(typeof t.path!="string")throw new fe("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new fe('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 fe("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 fe("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")&&Vr(t.value))throw new fe("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var o=t.path.split("/").length,i=r.split("/").length;if(o!==i+1&&o!==i)throw new fe("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 fe("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=Cl([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new fe("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new fe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function Cl(t,e,n){try{if(!Array.isArray(t))throw new fe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Kr(Te(e),Te(t),n||!0);else{n=n||Yr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof fe)return o;throw o}}function Kn(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),o,i,s;if(n&&r){if(i=t.length,i!=e.length)return!1;for(o=i;o--!==0;)if(!Kn(t[o],e[o]))return!1;return!0}if(n!=r)return!1;var a=Object.keys(t);if(i=a.length,i!==Object.keys(e).length)return!1;for(o=i;o--!==0;)if(!e.hasOwnProperty(a[o]))return!1;for(o=i;o--!==0;)if(s=a[o],!Kn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var ks={};zi(ks,{compare:()=>Oh,generate:()=>ws,observe:()=>Rh,unobserve:()=>Nh});var _s=new WeakMap,_h=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),Ah=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function kh(t){return _s.get(t)}function Ih(t,e){return t.observers.get(e)}function Ch(t,e){t.observers.delete(e.callback)}function Nh(t,e){e.unobserve()}function Rh(t,e){var n=[],r,o=kh(t);if(!o)o=new _h(t),_s.set(t,o);else{var i=Ih(o,e);r=i&&i.observer}if(r)return r;if(r={},o.value=Te(t),e){r.callback=e,r.next=null;var s=function(){ws(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(){ws(r),clearTimeout(r.next),Ch(o,r),typeof window<"u"&&(window.removeEventListener("mouseup",a),window.removeEventListener("keyup",a),window.removeEventListener("mousedown",a),window.removeEventListener("keydown",a),window.removeEventListener("change",a))},o.observers.set(e,new Ah(e,r)),r}function ws(t,e){e===void 0&&(e=!1);var n=_s.get(t.object);As(n.value,t.object,t.patches,"",e),t.patches.length&&Kr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function As(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=qr(e),s=qr(t),a=!1,l=!1,u=s.length-1;u>=0;u--){var f=s[u],m=t[f];if(jr(e,f)&&!(e[f]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var y=e[f];typeof m=="object"&&m!=null&&typeof y=="object"&&y!=null&&Array.isArray(m)===Array.isArray(y)?As(m,y,n,r+"/"+ot(f),o):m!==y&&(a=!0,o&&n.push({op:"test",path:r+"/"+ot(f),value:Te(m)}),n.push({op:"replace",path:r+"/"+ot(f),value:Te(y)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+ot(f),value:Te(m)}),n.push({op:"remove",path:r+"/"+ot(f)}),l=!0):(o&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}),a=!0)}if(!(!l&&i.length==s.length))for(var u=0;u<i.length;u++){var f=i[u];!jr(t,f)&&e[f]!==void 0&&n.push({op:"add",path:r+"/"+ot(f),value:Te(e[f])})}}}function Oh(t,e,n){n===void 0&&(n=!1);var r=[];return As(t,e,r,"",n),r}var Zr=Object.assign({},Ss,ks,{JsonPatchError:Yn,deepClone:Te,escapePathComponent:ot,unescapePathComponent:Xn});var Is=function(t,e){return Is=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(n[o]=r[o])},Is(t,e)};function it(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Is(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Nl(t,e,n,r){function o(i){return i instanceof n?i:new n(function(s){s(i)})}return new(n||(n=Promise))(function(i,s){function a(f){try{u(r.next(f))}catch(m){s(m)}}function l(f){try{u(r.throw(f))}catch(m){s(m)}}function u(f){f.done?i(f.value):o(f.value).then(a,l)}u((r=r.apply(t,e||[])).next())})}function Jr(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,o,i,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(u){return function(f){return l([u,f])}}function l(u){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(n=0)),n;)try{if(r=1,o&&(i=u[0]&2?o.return:u[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,u[1])).done)return i;switch(o=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,o=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){n.label=u[1];break}if(u[0]===6&&n.label<i[1]){n.label=i[1],i=u;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(u);break}i[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(f){u=[6,f],o=0}finally{r=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[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 En(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),o,i=[],s;try{for(;(e===void 0||e-- >0)&&!(o=r.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return i}function Tn(t,e,n){if(n||arguments.length===2)for(var r=0,o=e.length,i;r<o;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))}function Yt(t){return this instanceof Yt?(this.v=t,this):new Yt(t)}function Rl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),o[Symbol.asyncIterator]=function(){return this},o;function s(h){return function(p){return Promise.resolve(p).then(h,m)}}function a(h,p){r[h]&&(o[h]=function(g){return new Promise(function(x,_){i.push([h,g,x,_])>1||l(h,g)})},p&&(o[h]=p(o[h])))}function l(h,p){try{u(r[h](p))}catch(g){y(i[0][3],g)}}function u(h){h.value instanceof Yt?Promise.resolve(h.value.v).then(f,m):y(i[0][2],h)}function f(h){l("next",h)}function m(h){l("throw",h)}function y(h,p){h(p),i.shift(),i.length&&l(i[0][0],i[0][1])}}function Ol(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(i){n[i]=t[i]&&function(s){return new Promise(function(a,l){s=t[i](s),o(a,l,s.done,s.value)})}}function o(i,s,a,l){Promise.resolve(l).then(function(u){i({value:u,done:a})},s)}}function B(t){return typeof t=="function"}function Sn(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 Qr=Sn(function(t){return function(n){t(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
3
3
|
`+n.map(function(r,o){return o+1+") "+r.toString()}).join(`
|
|
4
|
-
`):"",this.name="UnsubscriptionError",this.errors=n}});function Kn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var wn=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=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(B(f))try{f()}catch(g){i=g instanceof Kr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=ft(m),h=y.next();!h.done;h=y.next()){var p=h.value;try{Ol(p)}catch(g){i=i??[],g instanceof Kr?i=En(En([],xn(i)),xn(g.errors)):i.push(g)}}}catch(g){r={error:g}}finally{try{h&&!h.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(i)throw new Kr(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Ol(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)&&Kn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Kn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var ks=wn.EMPTY;function Zr(t){return t instanceof wn||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function Ol(t){B(t)?t():t.unsubscribe()}var qe={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Sn={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=Sn.delegate;return o?.setTimeout?o.setTimeout.apply(o,En([t,e],xn(n))):setTimeout.apply(void 0,En([t,e],xn(n)))},clearTimeout:function(t){var e=Sn.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function Jr(t){Sn.setTimeout(function(){var e=qe.onUnhandledError;if(e)e(t);else throw t})}function Zn(){}var Ml=(function(){return Is("C",void 0,void 0)})();function Ll(t){return Is("E",void 0,t)}function Pl(t){return Is("N",t,void 0)}function Is(t,e,n){return{kind:t,value:e,error:n}}var Yt=null;function _n(t){if(qe.useDeprecatedSynchronousErrorHandling){var e=!Yt;if(e&&(Yt={errorThrown:!1,error:null}),t(),e){var n=Yt,r=n.errorThrown,o=n.error;if(Yt=null,r)throw o}}else t()}function Dl(t){qe.useDeprecatedSynchronousErrorHandling&&Yt&&(Yt.errorThrown=!0,Yt.error=t)}var Jn=(function(t){it(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,Zr(n)&&n.add(r)):r.destination=Ph,r}return e.create=function(n,r,o){return new eo(n,r,o)},e.prototype.next=function(n){this.isStopped?Ns(Pl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?Ns(Ll(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?Ns(Ml,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})(wn);var Oh=Function.prototype.bind;function Cs(t,e){return Oh.call(t,e)}var Mh=(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})(),eo=(function(t){it(e,t);function e(n,r,o){var i=t.call(this)||this,s;if(B(n)||!n)s={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;i&&qe.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return i.unsubscribe()},s={next:n.next&&Cs(n.next,a),error:n.error&&Cs(n.error,a),complete:n.complete&&Cs(n.complete,a)}):s=n}return i.destination=new Mh(s),i}return e})(Jn);function Qr(t){qe.useDeprecatedSynchronousErrorHandling?Dl(t):Jr(t)}function Lh(t){throw t}function Ns(t,e){var n=qe.onStoppedNotification;n&&Sn.setTimeout(function(){return n(t,e)})}var Ph={closed:!0,next:Zn,error:Lh,complete:Zn};var An=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function kn(t){return t}function to(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Rs(t)}function Rs(t){return t.length===0?kn:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var te=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,i=Uh(e)?e:new eo(e,n,r);return _n(function(){var s=o,a=s.operator,l=s.source;i.add(a?a.call(i,l):l?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=Ul(n),new n(function(o,i){var s=new eo({next:function(a){try{e(a)}catch(l){i(l),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[An]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Rs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=Ul(e),new e(function(r,o){var i;n.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},t.create=function(e){return new t(e)},t})();function Ul(t){var e;return(e=t??qe.Promise)!==null&&e!==void 0?e:Promise}function Dh(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function Uh(t){return t&&t instanceof Jn||Dh(t)&&Zr(t)}function Hh(t){return B(t?.lift)}function he(t){return function(e){if(Hh(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 ge(t,e,n,r,o){return new Gh(t,e,n,r,o)}var Gh=(function(t){it(e,t);function e(n,r,o,i,s,a){var l=t.call(this,n)||this;return l.onFinalize=s,l.shouldUnsubscribe=a,l._next=r?function(c){try{r(c)}catch(f){n.error(f)}}:t.prototype._next,l._error=i?function(c){try{i(c)}catch(f){n.error(f)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(c){n.error(c)}finally{this.unsubscribe()}}:t.prototype._complete,l}return e.prototype.unsubscribe=function(){var n;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;t.prototype.unsubscribe.call(this),!r&&((n=this.onFinalize)===null||n===void 0||n.call(this))}},e})(Jn);var Hl=Tn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var st=(function(t){it(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 Gl(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Hl},e.prototype.next=function(n){var r=this;_n(function(){var o,i;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){o={error:c}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;_n(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;_n(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?ks:(this.currentObservers=null,a.push(n),new wn(function(){r.currentObservers=null,Kn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,i=r.thrownError,s=r.isStopped;o?n.error(i):s&&n.complete()},e.prototype.asObservable=function(){var n=new te;return n.source=this,n},e.create=function(n,r){return new Gl(n,r)},e})(te);var Gl=(function(t){it(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:ks},e})(st);var Os={now:function(){return(Os.delegate||Date).now()},delegate:void 0};var no=(function(t){it(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=Os);var i=t.call(this)||this;return i._bufferSize=n,i._windowTime=r,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,n),i._windowTime=Math.max(1,r),i}return e.prototype.next=function(n){var r=this,o=r.isStopped,i=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;o||(i.push(n),!s&&i.push(a.now()+l)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,i=o._infiniteTimeWindow,s=o._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=i?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,i=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<i.length&&i.splice(0,i.length-a),!s){for(var l=o.now(),c=0,f=1;f<i.length&&i[f]<=l;f+=2)c=f;c&&i.splice(0,c+1)}},e})(st);var ro=new te(function(t){return t.complete()});function Fl(t){return t&&B(t.schedule)}function Fh(t){return t[t.length-1]}function $l(t){return Fl(Fh(t))?t.pop():void 0}var oo=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function io(t){return B(t?.then)}function so(t){return B(t[An])}function ao(t){return Symbol.asyncIterator&&B(t?.[Symbol.asyncIterator])}function lo(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 $h(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var co=$h();function uo(t){return B(t?.[co])}function po(t){return Nl(this,arguments,function(){var n,r,o,i;return Yr(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,Xt(n.read())];case 3:return r=s.sent(),o=r.value,i=r.done,i?[4,Xt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Xt(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function fo(t){return B(t?.getReader)}function ve(t){if(t instanceof te)return t;if(t!=null){if(so(t))return zh(t);if(oo(t))return Bh(t);if(io(t))return Vh(t);if(ao(t))return zl(t);if(uo(t))return jh(t);if(fo(t))return qh(t)}throw lo(t)}function zh(t){return new te(function(e){var n=t[An]();if(B(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Bh(t){return new te(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function Vh(t){return new te(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,Jr)})}function jh(t){return new te(function(e){var n,r;try{for(var o=ft(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function zl(t){return new te(function(e){Wh(t,e).catch(function(n){return e.error(n)})})}function qh(t){return zl(po(t))}function Wh(t,e){var n,r,o,i;return Cl(this,void 0,void 0,function(){var s,a;return Yr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Rl(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(s=r.value,e.next(s),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),o={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function ze(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var i=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(i),!o)return i}function ho(t,e){return e===void 0&&(e=0),he(function(n,r){n.subscribe(ge(r,function(o){return ze(r,t,function(){return r.next(o)},e)},function(){return ze(r,t,function(){return r.complete()},e)},function(o){return ze(r,t,function(){return r.error(o)},e)}))})}function mo(t,e){return e===void 0&&(e=0),he(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Bl(t,e){return ve(t).pipe(mo(e),ho(e))}function Vl(t,e){return ve(t).pipe(mo(e),ho(e))}function jl(t,e){return new te(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function ql(t,e){return new te(function(n){var r;return ze(n,e,function(){r=t[co](),ze(n,e,function(){var o,i,s;try{o=r.next(),i=o.value,s=o.done}catch(a){n.error(a);return}s?n.complete():n.next(i)},0,!0)}),function(){return B(r?.return)&&r.return()}})}function go(t,e){if(!t)throw new Error("Iterable cannot be null");return new te(function(n){ze(n,e,function(){var r=t[Symbol.asyncIterator]();ze(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function Wl(t,e){return go(po(t),e)}function Xl(t,e){if(t!=null){if(so(t))return Bl(t,e);if(oo(t))return jl(t,e);if(io(t))return Vl(t,e);if(ao(t))return go(t,e);if(uo(t))return ql(t,e);if(fo(t))return Wl(t,e)}throw lo(t)}function Kt(t,e){return e?Xl(t,e):ve(t)}function ue(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=$l(t);return Kt(t,n)}function ne(t,e){var n=B(t)?t:function(){return t},r=function(o){return o.error(n())};return new te(e?function(o){return e.schedule(r,0,o)}:r)}var Yl=Tn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function vo(t,e){var n=typeof e=="object";return new Promise(function(r,o){var i=!1,s;t.subscribe({next:function(a){s=a,i=!0},error:o,complete:function(){i?r(s):n?r(e.defaultValue):o(new Yl)}})})}function Zt(t,e){return he(function(n,r){var o=0;n.subscribe(ge(r,function(i){r.next(t.call(e,i,o++))}))})}function Kl(t,e,n,r,o,i,s,a){var l=[],c=0,f=0,m=!1,y=function(){m&&!l.length&&!c&&e.complete()},h=function(g){return c<r?p(g):l.push(g)},p=function(g){i&&e.next(g),c++;var x=!1;ve(n(g,f++)).subscribe(ge(e,function(_){o?.(_),i?h(_):e.next(_)},function(){x=!0},void 0,function(){if(x)try{c--;for(var _=function(){var w=l.shift();s?ze(e,s,function(){return p(w)}):p(w)};l.length&&c<r;)_();y()}catch(w){e.error(w)}}))};return t.subscribe(ge(e,h,function(){m=!0,y()})),function(){a?.()}}function Me(t,e,n){return n===void 0&&(n=1/0),B(e)?Me(function(r,o){return Zt(function(i,s){return e(r,i,o,s)})(ve(t(r,o)))},n):(typeof e=="number"&&(n=e),he(function(r,o){return Kl(r,o,t,n)}))}function Ms(t){return t===void 0&&(t=1/0),Me(kn,t)}function bo(t){return new te(function(e){ve(t()).subscribe(e)})}function Qn(t){return he(function(e,n){var r=null,o=!1,i;r=e.subscribe(ge(n,void 0,void 0,function(s){i=ve(t(s,Qn(t)(e))),r?(r.unsubscribe(),r=null,i.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,i.subscribe(n))})}function yo(t,e){return B(e)?Me(t,e,1):Me(t,1)}function Ls(t){return he(function(e,n){var r=!1;e.subscribe(ge(n,function(o){r=!0,n.next(o)},function(){r||n.next(t),n.complete()}))})}function Jt(t){return he(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function Ps(t,e){return he(function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(ge(r,function(l){o?.unsubscribe();var c=0,f=i++;ve(t(l,f)).subscribe(o=ge(r,function(m){return r.next(e?e(l,m,f,c++):m)},function(){o=null,a()}))},function(){s=!0,a()}))})}function xo(t){return he(function(e,n){ve(t).subscribe(ge(n,function(){return n.complete()},Zn)),!n.closed&&e.subscribe(n)})}function Ds(t,e,n){var r=B(t)||e||n?{next:t,error:e,complete:n}:t;return r?he(function(o,i){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;o.subscribe(ge(i,function(l){var c;(c=r.next)===null||c===void 0||c.call(r,l),i.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),i.complete()},function(l){var c;a=!1,(c=r.error)===null||c===void 0||c.call(r,l),i.error(l)},function(){var l,c;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(c=r.finalize)===null||c===void 0||c.call(r)}))}):kn}function Zl(t){return` \r
|
|
5
|
-
`.indexOf(t)>=0}function Eo(t){for(var e=["topLevel"],n=0,r,o,i,s=function(w){return e.push(w)},a=function(w){return e[e.length-1]=w},l=function(w){r==null&&(r=n,o=e.length,i=w)},c=function(w){w===i&&(r=void 0,o=void 0,i=void 0)},f=function(){return e.pop()},m=function(){return n--},y=function(w){if("0"<=w&&w<="9"){s("number");return}switch(w){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 p=t[n];switch(e[e.length-1]){case"topLevel":y(p);break;case"string":switch(p){case'"':f();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":p==="u"?s("stringUnicode"):(c("stringEscape"),f());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),f());break;case"number":p==="."?a("numberNeedsDigit"):p==="e"||p==="E"?a("numberNeedsExponent"):(p<"0"||p>"9")&&(m(),f());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(p==="+"||p==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(p<"a"||p>"z")&&(m(),f());break;case"arrayNeedsValue":p==="]"?f():Zl(p)||(c("collectionItem"),a("arrayNeedsComma"),y(p));break;case"arrayNeedsComma":p==="]"?f():p===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":p==="}"?f():p==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":p===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Zl(p)||(c("collectionItem"),a("objectNeedsComma"),y(p));break;case"objectNeedsComma":p==="}"?f():p===","&&(l("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var g=[r!=null?t.slice(0,r):t],x=function(w){return g.push(w.slice(t.length-t.lastIndexOf(w[0])))},_=e.length-1;_>=0;_--)switch(e[_]){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 Ql(){let t=0,e=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function wo(t,e,n){for(let i=0;i<28;i=i+7){let s=t>>>i,a=!(!(s>>>7)&&e==0),l=(a?s|128:s)&255;if(n.push(l),!a)return}let r=t>>>28&15|(e&7)<<4,o=e>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let i=3;i<31;i=i+7){let s=e>>>i,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var To=4294967296;function Us(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function i(s,a){let l=Number(t.slice(s,a));o*=n,r=r*n+l,r>=To&&(o=o+(r/To|0),r=r%To)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),e?tc(r,o):Gs(r,o)}function ec(t,e){let n=Gs(t,e),r=n.hi&2147483648;r&&(n=tc(n.lo,n.hi));let o=Hs(n.lo,n.hi);return r?"-"+o:o}function Hs(t,e){if({lo:t,hi:e}=Xh(t,e),e<=2097151)return String(To*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,o=e>>16&65535,i=n+r*6777216+o*6710656,s=r+o*8147497,a=o*2,l=1e7;return i>=l&&(s+=Math.floor(i/l),i%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Jl(s)+Jl(i)}function Xh(t,e){return{lo:t>>>0,hi:e>>>0}}function Gs(t,e){return{lo:t|0,hi:e|0}}function tc(t,e){return e=~e,t?t=~t+1:e+=1,Gs(t,e)}var Jl=t=>{let e=String(t);return"0000000".slice(e.length)+e};function Fs(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 nc(){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 We=Yh();function Yh(){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"),o=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>r||a<n)throw new Error(`invalid int64: ${s}`);return a},uParse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>i||a<o)throw new Error(`invalid uint64: ${s}`);return a},enc(s){return t.setBigInt64(0,this.parse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(s){return t.setBigInt64(0,this.uParse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),rc(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),oc(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),rc(n),Us(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),oc(n),Us(n)},dec(n,r){return ec(n,r)},uDec(n,r){return Hs(n,r)}}}function rc(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function oc(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var $s=Symbol.for("@bufbuild/protobuf/text-encoding");function zs(){if(globalThis[$s]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[$s]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[$s]}var St;(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"})(St||(St={}));var Kh=34028234663852886e22,Zh=-34028234663852886e22,Jh=4294967295,Qh=2147483647,em=-2147483648,$=class{constructor(e=zs().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let o=0;o<this.chunks.length;o++)e+=this.chunks[o].length;let n=new Uint8Array(e),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(ic(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Bs(e),Fs(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){tm(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){ic(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){Bs(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return Bs(e),e=(e<<1^e>>31)>>>0,Fs(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=We.enc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=We.uEnc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(e){let n=We.enc(e);return wo(n.lo,n.hi,this.buf),this}sint64(e){let n=We.enc(e),r=n.hi>>31,o=n.lo<<1^r,i=(n.hi<<1|n.lo>>>31)^r;return wo(o,i,this.buf),this}uint64(e){let n=We.uEnc(e);return wo(n.lo,n.hi,this.buf),this}},A=class{constructor(e,n=zs().decodeUtf8){this.decodeUtf8=n,this.varint64=Ql,this.uint32=nc,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,i=n&7;if(o<=0||i>5)throw new Error("illegal tag: field no "+o+" wire type "+i);return[o,i]}skip(e,n,r=100){let o=this.pos;switch(e){case St.Varint:for(;this.buf[this.pos++]&128;);break;case St.Bit64:this.pos+=4;case St.Bit32:this.pos+=4;break;case St.LengthDelimited:let i=this.uint32();this.pos+=i;break;case St.StartGroup:if(r<=0)throw new Error("maximum recursion depth reached");for(;;){let[s,a]=this.tag();if(a===St.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(o,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 We.dec(...this.varint64())}uint64(){return We.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,We.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 We.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return We.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 Bs(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>Qh||t<em)throw new Error("invalid int32: "+t)}function ic(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>Jh||t<0)throw new Error("invalid uint32: "+t)}function tm(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>Kh||t<Zh))throw new Error("invalid float32: "+t)}var nm=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Vs(){return{fields:{}}}var er={encode(t,e=new $){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Ws.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Vs();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:{if(i!==10)break;let s=Ws.decode(n,n.uint32());s.value!==void 0&&(o.fields[s.key]=s.value);continue}}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return er.fromPartial(t??{})},fromPartial(t){let e=Vs();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=Vs();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 sc(){return{key:"",value:void 0}}var Ws={encode(t,e=new $){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&O.encode(O.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=sc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.key=n.string();continue;case 2:if(i!==18)break;o.value=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ws.fromPartial(t??{})},fromPartial(t){let e=sc();return e.key=t.key??"",e.value=t.value??void 0,e}};function js(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var O={encode(t,e=new $){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&&er.encode(er.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&tr.encode(tr.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=js();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.nullValue=n.int32();continue;case 2:if(i!==17)break;o.numberValue=n.double();continue;case 3:if(i!==26)break;o.stringValue=n.string();continue;case 4:if(i!==32)break;o.boolValue=n.bool();continue;case 5:if(i!==42)break;o.structValue=er.unwrap(er.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.listValue=tr.unwrap(tr.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return O.fromPartial(t??{})},fromPartial(t){let e=js();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=js();if(t===null)e.nullValue=nm.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 qs(){return{values:[]}}var tr={encode(t,e=new $){for(let n of t.values)O.encode(O.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=qs();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.values.push(O.unwrap(O.decode(n,n.uint32())));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return tr.fromPartial(t??{})},fromPartial(t){let e=qs();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=qs();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},rm=(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 ac(){return{op:0,path:"",from:void 0,value:void 0}}var _o={encode(t,e=new $){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&&O.encode(O.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=ac();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.op=n.int32();continue;case 2:if(i!==18)break;o.path=n.string();continue;case 3:if(i!==26)break;o.from=n.string();continue;case 4:if(i!==34)break;o.value=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return _o.fromPartial(t??{})},fromPartial(t){let e=ac();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function lc(){return{id:"",type:"",function:void 0}}var Ao={encode(t,e=new $){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&ko.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.type=n.string();continue;case 3:if(i!==26)break;o.function=ko.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ao.fromPartial(t??{})},fromPartial(t){let e=lc();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?ko.fromPartial(t.function):void 0,e}};function cc(){return{name:"",arguments:""}}var ko={encode(t,e=new $){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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=cc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.name=n.string();continue;case 2:if(i!==18)break;o.arguments=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ko.fromPartial(t??{})},fromPartial(t){let e=cc();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function uc(){return{value:"",mimeType:""}}var Io={encode(t,e=new $){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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=uc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Io.fromPartial(t??{})},fromPartial(t){let e=uc();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function dc(){return{value:"",mimeType:void 0}}var Co={encode(t,e=new $){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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Co.fromPartial(t??{})},fromPartial(t){let e=dc();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function pc(){return{data:void 0,url:void 0}}var Pe={encode(t,e=new $){return t.data!==void 0&&Io.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Co.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.data=Io.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.url=Co.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Pe.fromPartial(t??{})},fromPartial(t){let e=pc();return e.data=t.data!==void 0&&t.data!==null?Io.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Co.fromPartial(t.url):void 0,e}};function fc(){return{text:""}}var No={encode(t,e=new $){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=fc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return No.fromPartial(t??{})},fromPartial(t){let e=fc();return e.text=t.text??"",e}};function hc(){return{source:void 0,metadata:void 0}}var Ro={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=hc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ro.fromPartial(t??{})},fromPartial(t){let e=hc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function mc(){return{source:void 0,metadata:void 0}}var Oo={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=mc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Oo.fromPartial(t??{})},fromPartial(t){let e=mc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function gc(){return{source:void 0,metadata:void 0}}var Mo={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=gc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Mo.fromPartial(t??{})},fromPartial(t){let e=gc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function vc(){return{source:void 0,metadata:void 0}}var Lo={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=vc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=vc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function bc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Po={encode(t,e=new $){return t.text!==void 0&&No.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Ro.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Oo.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&Mo.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Lo.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=bc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=No.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.image=Ro.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.audio=Oo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.video=Mo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.document=Lo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Po.fromPartial(t??{})},fromPartial(t){let e=bc();return e.text=t.text!==void 0&&t.text!==null?No.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Ro.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Oo.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?Mo.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Lo.fromPartial(t.document):void 0,e}};function yc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Do={encode(t,e=new $){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)Ao.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)Po.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=yc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.role=n.string();continue;case 3:if(i!==26)break;o.content=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue;case 5:if(i!==42)break;o.toolCalls.push(Ao.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.toolCallId=n.string();continue;case 7:if(i!==58)break;o.error=n.string();continue;case 8:if(i!==66)break;o.contentParts.push(Po.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Do.fromPartial(t??{})},fromPartial(t){let e=yc();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=>Ao.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Po.fromPartial(n))||[],e}};function xc(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Uo={encode(t,e=new $){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&&O.encode(O.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=xc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.reason=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue;case 4:if(i!==34)break;o.toolCallId=n.string();continue;case 5:if(i!==42)break;o.responseSchema=O.unwrap(O.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.expiresAt=n.string();continue;case 7:if(i!==58)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Uo.fromPartial(t??{})},fromPartial(t){let e=xc();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}},om=(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 Ec(){return{type:0,timestamp:void 0,rawEvent:void 0}}var M={encode(t,e=new $){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&O.encode(O.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ec();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.type=n.int32();continue;case 2:if(i!==16)break;o.timestamp=im(n.int64());continue;case 3:if(i!==26)break;o.rawEvent=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return M.fromPartial(t??{})},fromPartial(t){let e=Ec();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function Tc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Ho={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Tc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ho.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function wc(){return{baseEvent:void 0,messageId:"",delta:""}}var Go={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=wc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function Sc(){return{baseEvent:void 0,messageId:""}}var Fo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Sc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function _c(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var $o={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=_c();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return $o.fromPartial(t??{})},fromPartial(t){let e=_c();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function Ac(){return{baseEvent:void 0,toolCallId:"",delta:""}}var zo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ac();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return zo.fromPartial(t??{})},fromPartial(t){let e=Ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function kc(){return{baseEvent:void 0,toolCallId:""}}var Bo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=kc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Bo.fromPartial(t??{})},fromPartial(t){let e=kc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function Ic(){return{baseEvent:void 0,snapshot:void 0}}var Vo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&O.encode(O.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ic();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.snapshot=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Vo.fromPartial(t??{})},fromPartial(t){let e=Ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Cc(){return{baseEvent:void 0,delta:[]}}var jo={encode(t,e=new $){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)_o.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Cc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.delta.push(_o.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return jo.fromPartial(t??{})},fromPartial(t){let e=Cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>_o.fromPartial(n))||[],e}};function Nc(){return{baseEvent:void 0,messages:[]}}var qo={encode(t,e=new $){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Do.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Nc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messages.push(Do.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return qo.fromPartial(t??{})},fromPartial(t){let e=Nc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Do.fromPartial(n))||[],e}};function Rc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Wo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&O.encode(O.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Rc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.event=O.unwrap(O.decode(n,n.uint32()));continue;case 3:if(i!==26)break;o.source=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Wo.fromPartial(t??{})},fromPartial(t){let e=Rc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function Oc(){return{baseEvent:void 0,name:"",value:void 0}}var Xo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&O.encode(O.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Oc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.name=n.string();continue;case 3:if(i!==26)break;o.value=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Xo.fromPartial(t??{})},fromPartial(t){let e=Oc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function Mc(){return{baseEvent:void 0,threadId:"",runId:""}}var Yo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Mc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Yo.fromPartial(t??{})},fromPartial(t){let e=Mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function Lc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Ko={encode(t,e=new $){t.baseEvent!==void 0&&M.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&&O.encode(O.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Uo.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue;case 4:if(i!==34)break;o.result=O.unwrap(O.decode(n,n.uint32()));continue;case 5:if(i!==42)break;o.outcome=n.string();continue;case 6:if(i!==50)break;o.interrupts.push(Uo.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ko.fromPartial(t??{})},fromPartial(t){let e=Lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.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=>Uo.fromPartial(n))||[],e}};function Pc(){return{baseEvent:void 0,code:void 0,message:""}}var Zo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.code=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Zo.fromPartial(t??{})},fromPartial(t){let e=Pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function Dc(){return{baseEvent:void 0,stepName:""}}var Jo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Jo.fromPartial(t??{})},fromPartial(t){let e=Dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Uc(){return{baseEvent:void 0,stepName:""}}var Qo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Uc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Qo.fromPartial(t??{})},fromPartial(t){let e=Uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Hc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var ei={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Hc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.delta=n.string();continue;case 5:if(i!==42)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ei.fromPartial(t??{})},fromPartial(t){let e=Hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.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 Gc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var ti={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Gc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue;case 5:if(i!==42)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ti.fromPartial(t??{})},fromPartial(t){let e=Gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.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 Fc(){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 $c={encode(t,e=new $){return t.textMessageStart!==void 0&&Ho.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&Go.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Fo.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&$o.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&zo.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Bo.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Vo.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&jo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&qo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Wo.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Xo.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&Yo.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Ko.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&Zo.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&Jo.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&Qo.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&ei.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&ti.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Fc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.textMessageStart=Ho.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.textMessageContent=Go.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.textMessageEnd=Fo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.toolCallStart=$o.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.toolCallArgs=zo.decode(n,n.uint32());continue;case 6:if(i!==50)break;o.toolCallEnd=Bo.decode(n,n.uint32());continue;case 7:if(i!==58)break;o.stateSnapshot=Vo.decode(n,n.uint32());continue;case 8:if(i!==66)break;o.stateDelta=jo.decode(n,n.uint32());continue;case 9:if(i!==74)break;o.messagesSnapshot=qo.decode(n,n.uint32());continue;case 10:if(i!==82)break;o.raw=Wo.decode(n,n.uint32());continue;case 11:if(i!==90)break;o.custom=Xo.decode(n,n.uint32());continue;case 12:if(i!==98)break;o.runStarted=Yo.decode(n,n.uint32());continue;case 13:if(i!==106)break;o.runFinished=Ko.decode(n,n.uint32());continue;case 14:if(i!==114)break;o.runError=Zo.decode(n,n.uint32());continue;case 15:if(i!==122)break;o.stepStarted=Jo.decode(n,n.uint32());continue;case 16:if(i!==130)break;o.stepFinished=Qo.decode(n,n.uint32());continue;case 17:if(i!==138)break;o.textMessageChunk=ei.decode(n,n.uint32());continue;case 18:if(i!==146)break;o.toolCallChunk=ti.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return $c.fromPartial(t??{})},fromPartial(t){let e=Fc();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Ho.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?Go.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Fo.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?$o.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?zo.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Bo.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Vo.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?jo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?qo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Wo.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Xo.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?Yo.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Ko.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?Zo.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?Jo.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?Qo.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?ei.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?ti.fromPartial(t.toolCallChunk):void 0,e}};function im(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 So=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}}},sm=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:So(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:So(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:So(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:So(t.document.source),metadata:t.document.metadata}}};function zc(t){let e=$c.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=om[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let i=o.contentParts.map(s=>sm(s)).filter(s=>s!==void 0);i.length>0&&(o.content=i)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,i=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:i}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=rm[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Fr.parse(n)}var Xs="application/vnd.ag-ui.event+proto";var lm=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Ys=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(lm);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Bc=t=>t==="*"||t==="x"||t==="X",Vc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},cm=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],um=(t,e)=>{if(Bc(t)||Bc(e))return 0;let[n,r]=cm(Vc(t),Vc(e));return n>r?1:n<r?-1:0},Ks=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=um(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var nr=(t,e)=>{let n=Ys(t),r=Ys(e),o=n.pop(),i=r.pop(),s=Ks(n,r);return s!==0?s:o&&i?Ks(o.split("."),i.split(".")):o||i?o?-1:1:0};var j=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function De(){return yt()}function Qs(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&Qs(e);return t}var jc=512*1024;function qc(t,e,n){let r=0,o=[t,e],i=new WeakSet;for(;o.length>0;){let s=o.pop();if(typeof s=="string"){if(r+=s.length,r>n)return!0}else if(typeof s=="object"&&s){if(i.has(s))continue;if(i.add(s),Array.isArray(s))for(let a=0;a<s.length;a++)o.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;o.push(s[c])}}}}return!1}async function K(t,e,n,r){let o=typeof process<"u"&&process.env!==void 0,i=o&&!!process.env.VITEST_WORKER_ID,s=o&&!!process.env.VITEST_WORKER_ID,a=s&&!qc(e,n,jc),l=a?j(e):e,c=a?j(n):n,f=!1,m=!1,y;for(let h of t)try{a&&(Qs(l),Qs(c));let p=await r(h,l,c);if(p===void 0)continue;let g=!1;if(p.messages!==void 0&&p.messages!==l&&(l=j(p.messages),f=!0,g=!0),p.state!==void 0&&p.state!==c&&(c=j(p.state),m=!0,g=!0),a&&g&&qc(l,c,jc)&&(a=!1),y=p.stopPropagation,y===!0)break}catch(p){if(s&&p instanceof TypeError){if(i)throw p;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",p)}else i||console.error("Subscriber error:",p);continue}return{...f?{messages:Object.isFrozen(l)?j(l):l}:{},...m?{state:Object.isFrozen(c)?j(c):c}:{},...y===void 0?{}:{stopPropagation:y}}}function ni(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 rr(t){if(t instanceof ea)return t;if(t===!0)return new ea(ni(!0))}var ea=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 Zs(t){return t.enabled?new ea(t):void 0}function dm(t,e,n){if(e){let o=t.find(s=>s.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let i={id:o?n:e,role:"assistant",toolCalls:[]};return t.push(i),i}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Jc=(t,e,n,r,o)=>{let i=rr(o),s=j(n.messages),a=j(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=j(l);return l={},m.messages!==void 0||m.state!==void 0?ue(m):ro};return e.pipe(yo(async m=>{let y=await K(r,s,a,(h,p,g)=>h.onEvent?.({event:m,agent:n,input:t,messages:p,state:g}));if(c(y),y.stopPropagation===!0?i?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):i?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),y.stopPropagation===!0)return f();switch(m.type){case v.TEXT_MESSAGE_START:{let h=await K(r,s,a,(p,g,x)=>p.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:p,role:g="assistant",name:x}=m;if(!s.find(_=>_.id===p)){let _={id:p,role:g,content:"",...x!==void 0&&{name:x}};s.push(_),c({messages:s})}}return f()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:h,delta:p}=m,g=s.find(_=>_.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,C)=>_.onTextMessageContentEvent?.({event:m,messages:w,state:C,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:""}${p}`,c({messages:s})),f()}case v.TEXT_MESSAGE_END:{let{messageId:h}=m,p=s.find(g=>g.id===h);return p?(c(await K(r,s,a,(g,x,_)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:_,agent:n,input:t,textMessageBuffer:typeof p.content=="string"?p.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:p,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,(p,g,x)=>p.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{toolCallId:p,toolCallName:g,parentMessageId:x}=m,_=dm(s,x,p);_.toolCalls??=[],_.toolCalls.push({id:p,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return f()}case v.TOOL_CALL_ARGS:{let{toolCallId:h,delta:p}=m,g=s.find(w=>w.toolCalls?.some(C=>C.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(w=>w.id===h);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h}'`),f();let _=await K(r,s,a,(w,C,H)=>{let U=x.function.arguments,Y=x.function.name,re={};try{re=Eo(U)}catch{}return w.onToolCallArgsEvent?.({event:m,messages:C,state:H,agent:n,input:t,toolCallBuffer:U,toolCallName:Y,partialToolCallArgs:re})});return c(_),_.stopPropagation!==!0&&(x.function.arguments+=p,c({messages:s})),f()}case v.TOOL_CALL_END:{let{toolCallId:h}=m,p=s.find(x=>x.toolCalls?.some(_=>_.id===h));if(!p)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${h}'`),f();let g=p.toolCalls?.find(x=>x.id===h);return g?(c(await K(r,s,a,(x,_,w)=>{let C=g.function.arguments,H=g.function.name,U={};try{U=JSON.parse(C)}catch{}return x.onToolCallEndEvent?.({event:m,messages:_,state:w,agent:n,input:t,toolCallName:H,toolCallArgs:U})})),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,(p,g,x)=>p.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:p,toolCallId:g,content:x,role:_}=m,w={id:p,toolCallId:g,role:_||"tool",content:x},C=s.findIndex(H=>H.role==="assistant"&&H.toolCalls?.some(U=>U.id===g));if(C===-1)s.push(w);else{let H=C+1;for(;H<s.length&&s[H].role==="tool";)H++;s.splice(H,0,w)}await Promise.all(r.map(H=>{H.onNewMessage?.({message:w,messages:s,state:a,agent:n,input:t})})),c({messages:s})}return f()}case v.STATE_SNAPSHOT:{let h=await K(r,s,a,(p,g,x)=>p.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{snapshot:p}=m;a=p,c({state:a})}return f()}case v.STATE_DELTA:{let h=await K(r,s,a,(p,g,x)=>p.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{delta:p}=m;try{a=Xr.applyPatch(a,p,!0,!1).newDocument,c({state:a})}catch(g){let x=g instanceof Error?g.message:String(g);console.warn(`Failed to apply state patch:
|
|
4
|
+
`):"",this.name="UnsubscriptionError",this.errors=n}});function Zn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var wn=(function(){function t(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return t.prototype.unsubscribe=function(){var e,n,r,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=ft(s),l=a.next();!l.done;l=a.next()){var u=l.value;u.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(B(f))try{f()}catch(g){i=g instanceof Qr?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=ft(m),h=y.next();!h.done;h=y.next()){var p=h.value;try{Ml(p)}catch(g){i=i??[],g instanceof Qr?i=Tn(Tn([],En(i)),En(g.errors)):i.push(g)}}}catch(g){r={error:g}}finally{try{h&&!h.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(i)throw new Qr(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Ml(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)&&Zn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Zn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Cs=wn.EMPTY;function eo(t){return t instanceof wn||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function Ml(t){B(t)?t():t.unsubscribe()}var We={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var _n={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=_n.delegate;return o?.setTimeout?o.setTimeout.apply(o,Tn([t,e],En(n))):setTimeout.apply(void 0,Tn([t,e],En(n)))},clearTimeout:function(t){var e=_n.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function to(t){_n.setTimeout(function(){var e=We.onUnhandledError;if(e)e(t);else throw t})}function Jn(){}var Ll=(function(){return Ns("C",void 0,void 0)})();function Pl(t){return Ns("E",void 0,t)}function Dl(t){return Ns("N",t,void 0)}function Ns(t,e,n){return{kind:t,value:e,error:n}}var Kt=null;function An(t){if(We.useDeprecatedSynchronousErrorHandling){var e=!Kt;if(e&&(Kt={errorThrown:!1,error:null}),t(),e){var n=Kt,r=n.errorThrown,o=n.error;if(Kt=null,r)throw o}}else t()}function Ul(t){We.useDeprecatedSynchronousErrorHandling&&Kt&&(Kt.errorThrown=!0,Kt.error=t)}var Qn=(function(t){it(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,eo(n)&&n.add(r)):r.destination=Dh,r}return e.create=function(n,r,o){return new ro(n,r,o)},e.prototype.next=function(n){this.isStopped?Os(Dl(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?Os(Pl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?Os(Ll,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})(wn);var Mh=Function.prototype.bind;function Rs(t,e){return Mh.call(t,e)}var Lh=(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){no(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){no(r)}else no(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){no(n)}},t})(),ro=(function(t){it(e,t);function e(n,r,o){var i=t.call(this)||this,s;if(B(n)||!n)s={next:n??void 0,error:r??void 0,complete:o??void 0};else{var a;i&&We.useDeprecatedNextContext?(a=Object.create(n),a.unsubscribe=function(){return i.unsubscribe()},s={next:n.next&&Rs(n.next,a),error:n.error&&Rs(n.error,a),complete:n.complete&&Rs(n.complete,a)}):s=n}return i.destination=new Lh(s),i}return e})(Qn);function no(t){We.useDeprecatedSynchronousErrorHandling?Ul(t):to(t)}function Ph(t){throw t}function Os(t,e){var n=We.onStoppedNotification;n&&_n.setTimeout(function(){return n(t,e)})}var Dh={closed:!0,next:Jn,error:Ph,complete:Jn};var kn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function In(t){return t}function oo(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Ms(t)}function Ms(t){return t.length===0?In:t.length===1?t[0]:function(n){return t.reduce(function(r,o){return o(r)},n)}}var te=(function(){function t(e){e&&(this._subscribe=e)}return t.prototype.lift=function(e){var n=new t;return n.source=this,n.operator=e,n},t.prototype.subscribe=function(e,n,r){var o=this,i=Hh(e)?e:new ro(e,n,r);return An(function(){var s=o,a=s.operator,l=s.source;i.add(a?a.call(i,l):l?o._subscribe(i):o._trySubscribe(i))}),i},t.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(n){e.error(n)}},t.prototype.forEach=function(e,n){var r=this;return n=Hl(n),new n(function(o,i){var s=new ro({next:function(a){try{e(a)}catch(l){i(l),s.unsubscribe()}},error:i,complete:o});r.subscribe(s)})},t.prototype._subscribe=function(e){var n;return(n=this.source)===null||n===void 0?void 0:n.subscribe(e)},t.prototype[kn]=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=Hl(e),new e(function(r,o){var i;n.subscribe(function(s){return i=s},function(s){return o(s)},function(){return r(i)})})},t.create=function(e){return new t(e)},t})();function Hl(t){var e;return(e=t??We.Promise)!==null&&e!==void 0?e:Promise}function Uh(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function Hh(t){return t&&t instanceof Qn||Uh(t)&&eo(t)}function Gh(t){return B(t?.lift)}function he(t){return function(e){if(Gh(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 ge(t,e,n,r,o){return new Fh(t,e,n,r,o)}var Fh=(function(t){it(e,t);function e(n,r,o,i,s,a){var l=t.call(this,n)||this;return l.onFinalize=s,l.shouldUnsubscribe=a,l._next=r?function(u){try{r(u)}catch(f){n.error(f)}}:t.prototype._next,l._error=i?function(u){try{i(u)}catch(f){n.error(f)}finally{this.unsubscribe()}}:t.prototype._error,l._complete=o?function(){try{o()}catch(u){n.error(u)}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})(Qn);var Gl=Sn(function(t){return function(){t(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}});var st=(function(t){it(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 Fl(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new Gl},e.prototype.next=function(n){var r=this;An(function(){var o,i;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(u){o={error:u}}finally{try{a&&!a.done&&(i=s.return)&&i.call(s)}finally{if(o)throw o.error}}}})},e.prototype.error=function(n){var r=this;An(function(){if(r._throwIfClosed(),!r.isStopped){r.hasError=r.isStopped=!0,r.thrownError=n;for(var o=r.observers;o.length;)o.shift().error(n)}})},e.prototype.complete=function(){var n=this;An(function(){if(n._throwIfClosed(),!n.isStopped){n.isStopped=!0;for(var r=n.observers;r.length;)r.shift().complete()}})},e.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(e.prototype,"observed",{get:function(){var n;return((n=this.observers)===null||n===void 0?void 0:n.length)>0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(n){return this._throwIfClosed(),t.prototype._trySubscribe.call(this,n)},e.prototype._subscribe=function(n){return this._throwIfClosed(),this._checkFinalizedStatuses(n),this._innerSubscribe(n)},e.prototype._innerSubscribe=function(n){var r=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?Cs:(this.currentObservers=null,a.push(n),new wn(function(){r.currentObservers=null,Zn(a,n)}))},e.prototype._checkFinalizedStatuses=function(n){var r=this,o=r.hasError,i=r.thrownError,s=r.isStopped;o?n.error(i):s&&n.complete()},e.prototype.asObservable=function(){var n=new te;return n.source=this,n},e.create=function(n,r){return new Fl(n,r)},e})(te);var Fl=(function(t){it(e,t);function e(n,r){var o=t.call(this)||this;return o.destination=n,o.source=r,o}return e.prototype.next=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.next)===null||o===void 0||o.call(r,n)},e.prototype.error=function(n){var r,o;(o=(r=this.destination)===null||r===void 0?void 0:r.error)===null||o===void 0||o.call(r,n)},e.prototype.complete=function(){var n,r;(r=(n=this.destination)===null||n===void 0?void 0:n.complete)===null||r===void 0||r.call(n)},e.prototype._subscribe=function(n){var r,o;return(o=(r=this.source)===null||r===void 0?void 0:r.subscribe(n))!==null&&o!==void 0?o:Cs},e})(st);var Ls={now:function(){return(Ls.delegate||Date).now()},delegate:void 0};var io=(function(t){it(e,t);function e(n,r,o){n===void 0&&(n=1/0),r===void 0&&(r=1/0),o===void 0&&(o=Ls);var i=t.call(this)||this;return i._bufferSize=n,i._windowTime=r,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,n),i._windowTime=Math.max(1,r),i}return e.prototype.next=function(n){var r=this,o=r.isStopped,i=r._buffer,s=r._infiniteTimeWindow,a=r._timestampProvider,l=r._windowTime;o||(i.push(n),!s&&i.push(a.now()+l)),this._trimBuffer(),t.prototype.next.call(this,n)},e.prototype._subscribe=function(n){this._throwIfClosed(),this._trimBuffer();for(var r=this._innerSubscribe(n),o=this,i=o._infiniteTimeWindow,s=o._buffer,a=s.slice(),l=0;l<a.length&&!n.closed;l+=i?1:2)n.next(a[l]);return this._checkFinalizedStatuses(n),r},e.prototype._trimBuffer=function(){var n=this,r=n._bufferSize,o=n._timestampProvider,i=n._buffer,s=n._infiniteTimeWindow,a=(s?1:2)*r;if(r<1/0&&a<i.length&&i.splice(0,i.length-a),!s){for(var l=o.now(),u=0,f=1;f<i.length&&i[f]<=l;f+=2)u=f;u&&i.splice(0,u+1)}},e})(st);var so=new te(function(t){return t.complete()});function $l(t){return t&&B(t.schedule)}function $h(t){return t[t.length-1]}function zl(t){return $l($h(t))?t.pop():void 0}var ao=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function lo(t){return B(t?.then)}function co(t){return B(t[kn])}function uo(t){return Symbol.asyncIterator&&B(t?.[Symbol.asyncIterator])}function po(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 zh(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var fo=zh();function ho(t){return B(t?.[fo])}function mo(t){return Rl(this,arguments,function(){var n,r,o,i;return Jr(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,Yt(n.read())];case 3:return r=s.sent(),o=r.value,i=r.done,i?[4,Yt(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,Yt(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return n.releaseLock(),[7];case 10:return[2]}})})}function go(t){return B(t?.getReader)}function ve(t){if(t instanceof te)return t;if(t!=null){if(co(t))return Bh(t);if(ao(t))return Vh(t);if(lo(t))return jh(t);if(uo(t))return Bl(t);if(ho(t))return qh(t);if(go(t))return Wh(t)}throw po(t)}function Bh(t){return new te(function(e){var n=t[kn]();if(B(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Vh(t){return new te(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function jh(t){return new te(function(e){t.then(function(n){e.closed||(e.next(n),e.complete())},function(n){return e.error(n)}).then(null,to)})}function qh(t){return new te(function(e){var n,r;try{for(var o=ft(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(a){n={error:a}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()})}function Bl(t){return new te(function(e){Xh(t,e).catch(function(n){return e.error(n)})})}function Wh(t){return Bl(mo(t))}function Xh(t,e){var n,r,o,i;return Nl(this,void 0,void 0,function(){var s,a;return Jr(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Ol(t),l.label=1;case 1:return[4,n.next()];case 2:if(r=l.sent(),!!r.done)return[3,4];if(s=r.value,e.next(s),e.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=l.sent(),o={error:a},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return e.complete(),[2]}})})}function ze(t,e,n,r,o){r===void 0&&(r=0),o===void 0&&(o=!1);var i=e.schedule(function(){n(),o?t.add(this.schedule(null,r)):this.unsubscribe()},r);if(t.add(i),!o)return i}function vo(t,e){return e===void 0&&(e=0),he(function(n,r){n.subscribe(ge(r,function(o){return ze(r,t,function(){return r.next(o)},e)},function(){return ze(r,t,function(){return r.complete()},e)},function(o){return ze(r,t,function(){return r.error(o)},e)}))})}function bo(t,e){return e===void 0&&(e=0),he(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function Vl(t,e){return ve(t).pipe(bo(e),vo(e))}function jl(t,e){return ve(t).pipe(bo(e),vo(e))}function ql(t,e){return new te(function(n){var r=0;return e.schedule(function(){r===t.length?n.complete():(n.next(t[r++]),n.closed||this.schedule())})})}function Wl(t,e){return new te(function(n){var r;return ze(n,e,function(){r=t[fo](),ze(n,e,function(){var o,i,s;try{o=r.next(),i=o.value,s=o.done}catch(a){n.error(a);return}s?n.complete():n.next(i)},0,!0)}),function(){return B(r?.return)&&r.return()}})}function yo(t,e){if(!t)throw new Error("Iterable cannot be null");return new te(function(n){ze(n,e,function(){var r=t[Symbol.asyncIterator]();ze(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function Xl(t,e){return yo(mo(t),e)}function Yl(t,e){if(t!=null){if(co(t))return Vl(t,e);if(ao(t))return ql(t,e);if(lo(t))return jl(t,e);if(uo(t))return yo(t,e);if(ho(t))return Wl(t,e);if(go(t))return Xl(t,e)}throw po(t)}function Zt(t,e){return e?Yl(t,e):ve(t)}function ue(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=zl(t);return Zt(t,n)}function ne(t,e){var n=B(t)?t:function(){return t},r=function(o){return o.error(n())};return new te(e?function(o){return e.schedule(r,0,o)}:r)}var Kl=Sn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function xo(t,e){var n=typeof e=="object";return new Promise(function(r,o){var i=!1,s;t.subscribe({next:function(a){s=a,i=!0},error:o,complete:function(){i?r(s):n?r(e.defaultValue):o(new Kl)}})})}function Jt(t,e){return he(function(n,r){var o=0;n.subscribe(ge(r,function(i){r.next(t.call(e,i,o++))}))})}function Zl(t,e,n,r,o,i,s,a){var l=[],u=0,f=0,m=!1,y=function(){m&&!l.length&&!u&&e.complete()},h=function(g){return u<r?p(g):l.push(g)},p=function(g){i&&e.next(g),u++;var x=!1;ve(n(g,f++)).subscribe(ge(e,function(_){o?.(_),i?h(_):e.next(_)},function(){x=!0},void 0,function(){if(x)try{u--;for(var _=function(){var S=l.shift();s?ze(e,s,function(){return p(S)}):p(S)};l.length&&u<r;)_();y()}catch(S){e.error(S)}}))};return t.subscribe(ge(e,h,function(){m=!0,y()})),function(){a?.()}}function Me(t,e,n){return n===void 0&&(n=1/0),B(e)?Me(function(r,o){return Jt(function(i,s){return e(r,i,o,s)})(ve(t(r,o)))},n):(typeof e=="number"&&(n=e),he(function(r,o){return Zl(r,o,t,n)}))}function Ps(t){return t===void 0&&(t=1/0),Me(In,t)}function Eo(t){return new te(function(e){ve(t()).subscribe(e)})}function er(t){return he(function(e,n){var r=null,o=!1,i;r=e.subscribe(ge(n,void 0,void 0,function(s){i=ve(t(s,er(t)(e))),r?(r.unsubscribe(),r=null,i.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,i.subscribe(n))})}function To(t,e){return B(e)?Me(t,e,1):Me(t,1)}function Ds(t){return he(function(e,n){var r=!1;e.subscribe(ge(n,function(o){r=!0,n.next(o)},function(){r||n.next(t),n.complete()}))})}function Qt(t){return he(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function Us(t,e){return he(function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(ge(r,function(l){o?.unsubscribe();var u=0,f=i++;ve(t(l,f)).subscribe(o=ge(r,function(m){return r.next(e?e(l,m,f,u++):m)},function(){o=null,a()}))},function(){s=!0,a()}))})}function So(t){return he(function(e,n){ve(t).subscribe(ge(n,function(){return n.complete()},Jn)),!n.closed&&e.subscribe(n)})}function Hs(t,e,n){var r=B(t)||e||n?{next:t,error:e,complete:n}:t;return r?he(function(o,i){var s;(s=r.subscribe)===null||s===void 0||s.call(r);var a=!0;o.subscribe(ge(i,function(l){var u;(u=r.next)===null||u===void 0||u.call(r,l),i.next(l)},function(){var l;a=!1,(l=r.complete)===null||l===void 0||l.call(r),i.complete()},function(l){var u;a=!1,(u=r.error)===null||u===void 0||u.call(r,l),i.error(l)},function(){var l,u;a&&((l=r.unsubscribe)===null||l===void 0||l.call(r)),(u=r.finalize)===null||u===void 0||u.call(r)}))}):In}function Jl(t){return` \r
|
|
5
|
+
`.indexOf(t)>=0}function wo(t){for(var e=["topLevel"],n=0,r,o,i,s=function(S){return e.push(S)},a=function(S){return e[e.length-1]=S},l=function(S){r==null&&(r=n,o=e.length,i=S)},u=function(S){S===i&&(r=void 0,o=void 0,i=void 0)},f=function(){return e.pop()},m=function(){return n--},y=function(S){if("0"<=S&&S<="9"){s("number");return}switch(S){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 p=t[n];switch(e[e.length-1]){case"topLevel":y(p);break;case"string":switch(p){case'"':f();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":p==="u"?s("stringUnicode"):(u("stringEscape"),f());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(u("stringEscape"),f());break;case"number":p==="."?a("numberNeedsDigit"):p==="e"||p==="E"?a("numberNeedsExponent"):(p<"0"||p>"9")&&(m(),f());break;case"numberNeedsDigit":a("number");break;case"numberNeedsExponent":a(p==="+"||p==="-"?"numberNeedsDigit":"number");break;case"true":case"false":case"null":(p<"a"||p>"z")&&(m(),f());break;case"arrayNeedsValue":p==="]"?f():Jl(p)||(u("collectionItem"),a("arrayNeedsComma"),y(p));break;case"arrayNeedsComma":p==="]"?f():p===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":p==="}"?f():p==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":p===":"&&a("objectNeedsValue");break;case"objectNeedsValue":Jl(p)||(u("collectionItem"),a("objectNeedsComma"),y(p));break;case"objectNeedsComma":p==="}"?f():p===","&&(l("collectionItem"),a("objectNeedsKey"));break}}o!=null&&(e.length=o);for(var g=[r!=null?t.slice(0,r):t],x=function(S){return g.push(S.slice(t.length-t.lastIndexOf(S[0])))},_=e.length-1;_>=0;_--)switch(e[_]){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 ec(){let t=0,e=0;for(let r=0;r<28;r+=7){let o=this.buf[this.pos++];if(t|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}let n=this.buf[this.pos++];if(t|=(n&15)<<28,e=(n&112)>>4,(n&128)==0)return this.assertBounds(),[t,e];for(let r=3;r<=31;r+=7){let o=this.buf[this.pos++];if(e|=(o&127)<<r,(o&128)==0)return this.assertBounds(),[t,e]}throw new Error("invalid varint")}function Ao(t,e,n){for(let i=0;i<28;i=i+7){let s=t>>>i,a=!(!(s>>>7)&&e==0),l=(a?s|128:s)&255;if(n.push(l),!a)return}let r=t>>>28&15|(e&7)<<4,o=e>>3!=0;if(n.push((o?r|128:r)&255),!!o){for(let i=3;i<31;i=i+7){let s=e>>>i,a=!!(s>>>7),l=(a?s|128:s)&255;if(n.push(l),!a)return}n.push(e>>>31&1)}}var _o=4294967296;function Gs(t){let e=t[0]==="-";e&&(t=t.slice(1));let n=1e6,r=0,o=0;function i(s,a){let l=Number(t.slice(s,a));o*=n,r=r*n+l,r>=_o&&(o=o+(r/_o|0),r=r%_o)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),e?nc(r,o):$s(r,o)}function tc(t,e){let n=$s(t,e),r=n.hi&2147483648;r&&(n=nc(n.lo,n.hi));let o=Fs(n.lo,n.hi);return r?"-"+o:o}function Fs(t,e){if({lo:t,hi:e}=Yh(t,e),e<=2097151)return String(_o*e+t);let n=t&16777215,r=(t>>>24|e<<8)&16777215,o=e>>16&65535,i=n+r*6777216+o*6710656,s=r+o*8147497,a=o*2,l=1e7;return i>=l&&(s+=Math.floor(i/l),i%=l),s>=l&&(a+=Math.floor(s/l),s%=l),a.toString()+Ql(s)+Ql(i)}function Yh(t,e){return{lo:t>>>0,hi:e>>>0}}function $s(t,e){return{lo:t|0,hi:e|0}}function nc(t,e){return e=~e,t?t=~t+1:e+=1,$s(t,e)}var Ql=t=>{let e=String(t);return"0000000".slice(e.length)+e};function zs(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 rc(){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 Xe=Kh();function Kh(){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"),o=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>r||a<n)throw new Error(`invalid int64: ${s}`);return a},uParse(s){let a=typeof s=="bigint"?s:BigInt(s);if(a>i||a<o)throw new Error(`invalid uint64: ${s}`);return a},enc(s){return t.setBigInt64(0,this.parse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},uEnc(s){return t.setBigInt64(0,this.uParse(s),!0),{lo:t.getInt32(0,!0),hi:t.getInt32(4,!0)}},dec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigInt64(0,!0)},uDec(s,a){return t.setInt32(0,s,!0),t.setInt32(4,a,!0),t.getBigUint64(0,!0)}}}return{zero:"0",supported:!1,parse(n){return typeof n!="string"&&(n=n.toString()),oc(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),ic(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),oc(n),Gs(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),ic(n),Gs(n)},dec(n,r){return tc(n,r)},uDec(n,r){return Fs(n,r)}}}function oc(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function ic(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var Bs=Symbol.for("@bufbuild/protobuf/text-encoding");function Vs(){if(globalThis[Bs]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[Bs]={encodeUtf8(r){return t.encode(r)},decodeUtf8(r,o){return o?(n===void 0&&(n=new globalThis.TextDecoder("utf-8",{fatal:!0})),n.decode(r)):e.decode(r)},checkUtf8(r){try{return encodeURIComponent(r),!0}catch{return!1}}}}return globalThis[Bs]}var _t;(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"})(_t||(_t={}));var Zh=34028234663852886e22,Jh=-34028234663852886e22,Qh=4294967295,em=2147483647,tm=-2147483648,$=class{constructor(e=Vs().encodeUtf8){this.encodeUtf8=e,this.stack=[],this.chunks=[],this.buf=[]}finish(){this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]);let e=0;for(let o=0;o<this.chunks.length;o++)e+=this.chunks[o].length;let n=new Uint8Array(e),r=0;for(let o=0;o<this.chunks.length;o++)n.set(this.chunks[o],r),r+=this.chunks[o].length;return this.chunks=[],n}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),n=this.stack.pop();if(!n)throw new Error("invalid state, fork stack empty");return this.chunks=n.chunks,this.buf=n.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,n){return this.uint32((e<<3|n)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(sc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return js(e),zs(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){nm(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){sc(e);let n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,e,!0),this.raw(n)}sfixed32(e){js(e);let n=new Uint8Array(4);return new DataView(n.buffer).setInt32(0,e,!0),this.raw(n)}sint32(e){return js(e),e=(e<<1^e>>31)>>>0,zs(e,this.buf),this}sfixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=Xe.enc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}fixed64(e){let n=new Uint8Array(8),r=new DataView(n.buffer),o=Xe.uEnc(e);return r.setInt32(0,o.lo,!0),r.setInt32(4,o.hi,!0),this.raw(n)}int64(e){let n=Xe.enc(e);return Ao(n.lo,n.hi,this.buf),this}sint64(e){let n=Xe.enc(e),r=n.hi>>31,o=n.lo<<1^r,i=(n.hi<<1|n.lo>>>31)^r;return Ao(o,i,this.buf),this}uint64(e){let n=Xe.uEnc(e);return Ao(n.lo,n.hi,this.buf),this}},A=class{constructor(e,n=Vs().decodeUtf8){this.decodeUtf8=n,this.varint64=ec,this.uint32=rc,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,n=this.uint32(),r=this.pos-e;if(r>5||r==5&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");let o=n>>>3,i=n&7;if(o<=0||i>5)throw new Error("illegal tag: field no "+o+" wire type "+i);return[o,i]}skip(e,n,r=100){let o=this.pos;switch(e){case _t.Varint:for(;this.buf[this.pos++]&128;);break;case _t.Bit64:this.pos+=4;case _t.Bit32:this.pos+=4;break;case _t.LengthDelimited:let i=this.uint32();this.pos+=i;break;case _t.StartGroup:if(r<=0)throw new Error("maximum recursion depth reached");for(;;){let[s,a]=this.tag();if(a===_t.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(o,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 Xe.dec(...this.varint64())}uint64(){return Xe.uDec(...this.varint64())}sint64(){let[e,n]=this.varint64(),r=-(e&1);return e=(e>>>1|(n&1)<<31)^r,n=n>>>1^r,Xe.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 Xe.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Xe.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 js(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>em||t<tm)throw new Error("invalid int32: "+t)}function sc(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>Qh||t<0)throw new Error("invalid uint32: "+t)}function nm(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>Zh||t<Jh))throw new Error("invalid float32: "+t)}var rm=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function qs(){return{fields:{}}}var tr={encode(t,e=new $){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&Ys.encode({key:n,value:r},e.uint32(10).fork()).join()}),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=qs();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:{if(i!==10)break;let s=Ys.decode(n,n.uint32());s.value!==void 0&&(o.fields[s.key]=s.value);continue}}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return tr.fromPartial(t??{})},fromPartial(t){let e=qs();return e.fields=Object.entries(t.fields??{}).reduce((n,[r,o])=>(o!==void 0&&(n[r]=o),n),{}),e},wrap(t){let e=qs();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 ac(){return{key:"",value:void 0}}var Ys={encode(t,e=new $){return t.key!==""&&e.uint32(10).string(t.key),t.value!==void 0&&O.encode(O.wrap(t.value),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=ac();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.key=n.string();continue;case 2:if(i!==18)break;o.value=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ys.fromPartial(t??{})},fromPartial(t){let e=ac();return e.key=t.key??"",e.value=t.value??void 0,e}};function Ws(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var O={encode(t,e=new $){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&&tr.encode(tr.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&nr.encode(nr.wrap(t.listValue),e.uint32(50).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ws();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.nullValue=n.int32();continue;case 2:if(i!==17)break;o.numberValue=n.double();continue;case 3:if(i!==26)break;o.stringValue=n.string();continue;case 4:if(i!==32)break;o.boolValue=n.bool();continue;case 5:if(i!==42)break;o.structValue=tr.unwrap(tr.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.listValue=nr.unwrap(nr.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return O.fromPartial(t??{})},fromPartial(t){let e=Ws();return e.nullValue=t.nullValue??void 0,e.numberValue=t.numberValue??void 0,e.stringValue=t.stringValue??void 0,e.boolValue=t.boolValue??void 0,e.structValue=t.structValue??void 0,e.listValue=t.listValue??void 0,e},wrap(t){let e=Ws();if(t===null)e.nullValue=rm.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 Xs(){return{values:[]}}var nr={encode(t,e=new $){for(let n of t.values)O.encode(O.wrap(n),e.uint32(10).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Xs();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.values.push(O.unwrap(O.decode(n,n.uint32())));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return nr.fromPartial(t??{})},fromPartial(t){let e=Xs();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=Xs();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},om=(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 lc(){return{op:0,path:"",from:void 0,value:void 0}}var Io={encode(t,e=new $){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&&O.encode(O.wrap(t.value),e.uint32(34).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.op=n.int32();continue;case 2:if(i!==18)break;o.path=n.string();continue;case 3:if(i!==26)break;o.from=n.string();continue;case 4:if(i!==34)break;o.value=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Io.fromPartial(t??{})},fromPartial(t){let e=lc();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function cc(){return{id:"",type:"",function:void 0}}var Co={encode(t,e=new $){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&No.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=cc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.type=n.string();continue;case 3:if(i!==26)break;o.function=No.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Co.fromPartial(t??{})},fromPartial(t){let e=cc();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?No.fromPartial(t.function):void 0,e}};function uc(){return{name:"",arguments:""}}var No={encode(t,e=new $){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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=uc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.name=n.string();continue;case 2:if(i!==18)break;o.arguments=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return No.fromPartial(t??{})},fromPartial(t){let e=uc();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function dc(){return{value:"",mimeType:""}}var Ro={encode(t,e=new $){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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ro.fromPartial(t??{})},fromPartial(t){let e=dc();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function pc(){return{value:"",mimeType:void 0}}var Oo={encode(t,e=new $){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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.value=n.string();continue;case 2:if(i!==18)break;o.mimeType=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Oo.fromPartial(t??{})},fromPartial(t){let e=pc();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function fc(){return{data:void 0,url:void 0}}var Pe={encode(t,e=new $){return t.data!==void 0&&Ro.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Oo.encode(t.url,e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=fc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.data=Ro.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.url=Oo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Pe.fromPartial(t??{})},fromPartial(t){let e=fc();return e.data=t.data!==void 0&&t.data!==null?Ro.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Oo.fromPartial(t.url):void 0,e}};function hc(){return{text:""}}var Mo={encode(t,e=new $){return t.text!==""&&e.uint32(10).string(t.text),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=hc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Mo.fromPartial(t??{})},fromPartial(t){let e=hc();return e.text=t.text??"",e}};function mc(){return{source:void 0,metadata:void 0}}var Lo={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=mc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Lo.fromPartial(t??{})},fromPartial(t){let e=mc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function gc(){return{source:void 0,metadata:void 0}}var Po={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=gc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Po.fromPartial(t??{})},fromPartial(t){let e=gc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function vc(){return{source:void 0,metadata:void 0}}var Do={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=vc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Do.fromPartial(t??{})},fromPartial(t){let e=vc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function bc(){return{source:void 0,metadata:void 0}}var Uo={encode(t,e=new $){return t.source!==void 0&&Pe.encode(t.source,e.uint32(10).fork()).join(),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=bc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=Pe.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Uo.fromPartial(t??{})},fromPartial(t){let e=bc();return e.source=t.source!==void 0&&t.source!==null?Pe.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function yc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Ho={encode(t,e=new $){return t.text!==void 0&&Mo.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Lo.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Po.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&Do.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Uo.encode(t.document,e.uint32(42).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=yc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=Mo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.image=Lo.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.audio=Po.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.video=Do.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.document=Uo.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ho.fromPartial(t??{})},fromPartial(t){let e=yc();return e.text=t.text!==void 0&&t.text!==null?Mo.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Lo.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Po.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?Do.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Uo.fromPartial(t.document):void 0,e}};function xc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var Go={encode(t,e=new $){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)Co.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)Ho.encode(n,e.uint32(66).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=xc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.role=n.string();continue;case 3:if(i!==26)break;o.content=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue;case 5:if(i!==42)break;o.toolCalls.push(Co.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.toolCallId=n.string();continue;case 7:if(i!==58)break;o.error=n.string();continue;case 8:if(i!==66)break;o.contentParts.push(Ho.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Go.fromPartial(t??{})},fromPartial(t){let e=xc();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=>Co.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Ho.fromPartial(n))||[],e}};function Ec(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Fo={encode(t,e=new $){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&&O.encode(O.wrap(t.responseSchema),e.uint32(42).fork()).join(),t.expiresAt!==void 0&&e.uint32(50).string(t.expiresAt),t.metadata!==void 0&&O.encode(O.wrap(t.metadata),e.uint32(58).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ec();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.id=n.string();continue;case 2:if(i!==18)break;o.reason=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue;case 4:if(i!==34)break;o.toolCallId=n.string();continue;case 5:if(i!==42)break;o.responseSchema=O.unwrap(O.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.expiresAt=n.string();continue;case 7:if(i!==58)break;o.metadata=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Fo.fromPartial(t??{})},fromPartial(t){let e=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}},im=(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 M={encode(t,e=new $){return t.type!==0&&e.uint32(8).int32(t.type),t.timestamp!==void 0&&e.uint32(16).int64(t.timestamp),t.rawEvent!==void 0&&O.encode(O.wrap(t.rawEvent),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Tc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==8)break;o.type=n.int32();continue;case 2:if(i!==16)break;o.timestamp=sm(n.int64());continue;case 3:if(i!==26)break;o.rawEvent=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return M.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 Sc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var $o={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Sc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return $o.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.role=t.role??void 0,e.name=t.name??void 0,e}};function wc(){return{baseEvent:void 0,messageId:"",delta:""}}var zo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=wc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return zo.fromPartial(t??{})},fromPartial(t){let e=wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e.delta=t.delta??"",e}};function _c(){return{baseEvent:void 0,messageId:""}}var Bo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.messageId!==""&&e.uint32(18).string(t.messageId),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=_c();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Bo.fromPartial(t??{})},fromPartial(t){let e=_c();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messageId=t.messageId??"",e}};function Ac(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Vo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ac();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Vo.fromPartial(t??{})},fromPartial(t){let e=Ac();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.toolCallName=t.toolCallName??"",e.parentMessageId=t.parentMessageId??void 0,e}};function kc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var jo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=kc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return jo.fromPartial(t??{})},fromPartial(t){let e=kc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e.delta=t.delta??"",e}};function Ic(){return{baseEvent:void 0,toolCallId:""}}var qo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.toolCallId!==""&&e.uint32(18).string(t.toolCallId),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Ic();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return qo.fromPartial(t??{})},fromPartial(t){let e=Ic();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function Cc(){return{baseEvent:void 0,snapshot:void 0}}var Wo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.snapshot!==void 0&&O.encode(O.wrap(t.snapshot),e.uint32(18).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Cc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.snapshot=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Wo.fromPartial(t??{})},fromPartial(t){let e=Cc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Nc(){return{baseEvent:void 0,delta:[]}}var Xo={encode(t,e=new $){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)Io.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Nc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.delta.push(Io.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Xo.fromPartial(t??{})},fromPartial(t){let e=Nc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>Io.fromPartial(n))||[],e}};function Rc(){return{baseEvent:void 0,messages:[]}}var Yo={encode(t,e=new $){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)Go.encode(n,e.uint32(18).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Rc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messages.push(Go.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Yo.fromPartial(t??{})},fromPartial(t){let e=Rc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>Go.fromPartial(n))||[],e}};function Oc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Ko={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.event!==void 0&&O.encode(O.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Oc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.event=O.unwrap(O.decode(n,n.uint32()));continue;case 3:if(i!==26)break;o.source=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Ko.fromPartial(t??{})},fromPartial(t){let e=Oc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.event=t.event??void 0,e.source=t.source??void 0,e}};function Mc(){return{baseEvent:void 0,name:"",value:void 0}}var Zo={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.name!==""&&e.uint32(18).string(t.name),t.value!==void 0&&O.encode(O.wrap(t.value),e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Mc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.name=n.string();continue;case 3:if(i!==26)break;o.value=O.unwrap(O.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Zo.fromPartial(t??{})},fromPartial(t){let e=Mc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.name=t.name??"",e.value=t.value??void 0,e}};function Lc(){return{baseEvent:void 0,threadId:"",runId:""}}var Jo={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Jo.fromPartial(t??{})},fromPartial(t){let e=Lc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.threadId=t.threadId??"",e.runId=t.runId??"",e}};function Pc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var Qo={encode(t,e=new $){t.baseEvent!==void 0&&M.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&&O.encode(O.wrap(t.result),e.uint32(34).fork()).join(),t.outcome!==""&&e.uint32(42).string(t.outcome);for(let n of t.interrupts)Fo.encode(n,e.uint32(50).fork()).join();return e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.threadId=n.string();continue;case 3:if(i!==26)break;o.runId=n.string();continue;case 4:if(i!==34)break;o.result=O.unwrap(O.decode(n,n.uint32()));continue;case 5:if(i!==42)break;o.outcome=n.string();continue;case 6:if(i!==50)break;o.interrupts.push(Fo.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return Qo.fromPartial(t??{})},fromPartial(t){let e=Pc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.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=>Fo.fromPartial(n))||[],e}};function Dc(){return{baseEvent:void 0,code:void 0,message:""}}var ei={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.code=n.string();continue;case 3:if(i!==26)break;o.message=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ei.fromPartial(t??{})},fromPartial(t){let e=Dc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.code=t.code??void 0,e.message=t.message??"",e}};function Uc(){return{baseEvent:void 0,stepName:""}}var ti={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Uc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ti.fromPartial(t??{})},fromPartial(t){let e=Uc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Hc(){return{baseEvent:void 0,stepName:""}}var ni={encode(t,e=new $){return t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join(),t.stepName!==""&&e.uint32(18).string(t.stepName),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Hc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.stepName=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ni.fromPartial(t??{})},fromPartial(t){let e=Hc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function Gc(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var ri={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Gc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.messageId=n.string();continue;case 3:if(i!==26)break;o.role=n.string();continue;case 4:if(i!==34)break;o.delta=n.string();continue;case 5:if(i!==42)break;o.name=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ri.fromPartial(t??{})},fromPartial(t){let e=Gc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.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 Fc(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var oi={encode(t,e=new $){return t.baseEvent!==void 0&&M.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 A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=Fc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.baseEvent=M.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.toolCallId=n.string();continue;case 3:if(i!==26)break;o.toolCallName=n.string();continue;case 4:if(i!==34)break;o.parentMessageId=n.string();continue;case 5:if(i!==42)break;o.delta=n.string();continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return oi.fromPartial(t??{})},fromPartial(t){let e=Fc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.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 $c(){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 zc={encode(t,e=new $){return t.textMessageStart!==void 0&&$o.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&zo.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&Bo.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Vo.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&jo.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&qo.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Wo.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Xo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Yo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Ko.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&Zo.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&Jo.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&Qo.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&ei.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&ti.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&ni.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&ri.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&oi.encode(t.toolCallChunk,e.uint32(146).fork()).join(),e},decode(t,e){let n=t instanceof A?t:new A(t),r=e===void 0?n.len:n.pos+e,o=$c();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.textMessageStart=$o.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.textMessageContent=zo.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.textMessageEnd=Bo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.toolCallStart=Vo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.toolCallArgs=jo.decode(n,n.uint32());continue;case 6:if(i!==50)break;o.toolCallEnd=qo.decode(n,n.uint32());continue;case 7:if(i!==58)break;o.stateSnapshot=Wo.decode(n,n.uint32());continue;case 8:if(i!==66)break;o.stateDelta=Xo.decode(n,n.uint32());continue;case 9:if(i!==74)break;o.messagesSnapshot=Yo.decode(n,n.uint32());continue;case 10:if(i!==82)break;o.raw=Ko.decode(n,n.uint32());continue;case 11:if(i!==90)break;o.custom=Zo.decode(n,n.uint32());continue;case 12:if(i!==98)break;o.runStarted=Jo.decode(n,n.uint32());continue;case 13:if(i!==106)break;o.runFinished=Qo.decode(n,n.uint32());continue;case 14:if(i!==114)break;o.runError=ei.decode(n,n.uint32());continue;case 15:if(i!==122)break;o.stepStarted=ti.decode(n,n.uint32());continue;case 16:if(i!==130)break;o.stepFinished=ni.decode(n,n.uint32());continue;case 17:if(i!==138)break;o.textMessageChunk=ri.decode(n,n.uint32());continue;case 18:if(i!==146)break;o.toolCallChunk=oi.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return zc.fromPartial(t??{})},fromPartial(t){let e=$c();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?$o.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?zo.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?Bo.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Vo.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?jo.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?qo.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Wo.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Xo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Yo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Ko.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?Zo.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?Jo.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?Qo.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?ei.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?ti.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?ni.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?ri.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?oi.fromPartial(t.toolCallChunk):void 0,e}};function sm(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 ko=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}}},am=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:ko(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:ko(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:ko(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:ko(t.document.source),metadata:t.document.metadata}}};function Bc(t){let e=zc.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=im[n.baseEvent.type],n.timestamp=n.baseEvent.timestamp,n.rawEvent=n.baseEvent.rawEvent,delete n.baseEvent,n.type===v.MESSAGES_SNAPSHOT)for(let r of n.messages){let o=r;if(o.role==="user"&&Array.isArray(o.contentParts)){let i=o.contentParts.map(s=>am(s)).filter(s=>s!==void 0);i.length>0&&(o.content=i)}Array.isArray(o.contentParts)&&o.contentParts.length===0&&(o.contentParts=void 0),o.toolCalls?.length===0&&(o.toolCalls=void 0)}if(n.type===v.RUN_FINISHED){let r=n,o=typeof r.outcome=="string"&&r.outcome!==""?r.outcome:void 0,i=Array.isArray(r.interrupts)?r.interrupts:[];delete r.interrupts,o==="interrupt"?r.outcome={type:"interrupt",interrupts:i}:o==="success"?r.outcome={type:"success"}:delete r.outcome}if(n.type===v.STATE_DELTA)for(let r of n.delta)r.op=om[r.op].toLowerCase(),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]});return Object.keys(n).forEach(r=>{n[r]===void 0&&delete n[r]}),Br.parse(n)}var Ks="application/vnd.ag-ui.event+proto";var cm=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,Zs=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(cm);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},Vc=t=>t==="*"||t==="x"||t==="X",jc=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},um=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],dm=(t,e)=>{if(Vc(t)||Vc(e))return 0;let[n,r]=um(jc(t),jc(e));return n>r?1:n<r?-1:0},Js=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=dm(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var rr=(t,e)=>{let n=Zs(t),r=Zs(e),o=n.pop(),i=r.pop(),s=Js(n,r);return s!==0?s:o&&i?Js(o.split("."),i.split(".")):o||i?o?-1:1:0};var q=t=>{if(typeof structuredClone=="function")return structuredClone(t);try{return JSON.parse(JSON.stringify(t))}catch{return Array.isArray(t)?[...t]:{...t}}};function De(){return xt()}function ta(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&ta(e);return t}var qc=512*1024;function Wc(t,e,n){let r=0,o=[t,e],i=new WeakSet;for(;o.length>0;){let s=o.pop();if(typeof s=="string"){if(r+=s.length,r>n)return!0}else if(typeof s=="object"&&s){if(i.has(s))continue;if(i.add(s),Array.isArray(s))for(let a=0;a<s.length;a++)o.push(s[a]);else{let a=Object.keys(s);for(let l=0;l<a.length;l++){let u=a[l];if(r+=u.length,r>n)return!0;o.push(s[u])}}}}return!1}async function K(t,e,n,r){let o=typeof process<"u"&&process.env!==void 0,i=o&&!!process.env.VITEST_WORKER_ID,s=o&&!!process.env.VITEST_WORKER_ID,a=s&&!Wc(e,n,qc),l=a?q(e):e,u=a?q(n):n,f=!1,m=!1,y;for(let h of t)try{a&&(ta(l),ta(u));let p=await r(h,l,u);if(p===void 0)continue;let g=!1;if(p.messages!==void 0&&p.messages!==l&&(l=q(p.messages),f=!0,g=!0),p.state!==void 0&&p.state!==u&&(u=q(p.state),m=!0,g=!0),a&&g&&Wc(l,u,qc)&&(a=!1),y=p.stopPropagation,y===!0)break}catch(p){if(s&&p instanceof TypeError){if(i)throw p;console.error("AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.",p)}else i||console.error("Subscriber error:",p);continue}return{...f?{messages:Object.isFrozen(l)?q(l):l}:{},...m?{state:Object.isFrozen(u)?q(u):u}:{},...y===void 0?{}:{stopPropagation:y}}}function ii(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 or(t){if(t instanceof na)return t;if(t===!0)return new na(ii(!0))}var na=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 Qs(t){return t.enabled?new na(t):void 0}function pm(t,e,n){if(e){let o=t.find(s=>s.id===e);if(o?.role==="assistant")return o;o&&console.warn(`TOOL_CALL_START: parentMessageId '${e}' matches a '${o.role}' message, not assistant \u2014 falling back to toolCallId`);let i={id:o?n:e,role:"assistant",toolCalls:[]};return t.push(i),i}let r={id:n,role:"assistant",toolCalls:[]};return t.push(r),r}var Qc=(t,e,n,r,o)=>{let i=or(o),s=q(n.messages),a=q(t.state),l={},u=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=q(l);return l={},m.messages!==void 0||m.state!==void 0?ue(m):so};return e.pipe(To(async m=>{let y=await K(r,s,a,(h,p,g)=>h.onEvent?.({event:m,agent:n,input:t,messages:p,state:g}));if(u(y),y.stopPropagation===!0?i?.event("APPLY","Event dropped:",m,{type:m.type,reason:"stopPropagation by subscriber"}):i?.event("APPLY","Event applied:",m,{type:m.type,subscribers:r.length}),y.stopPropagation===!0)return f();switch(m.type){case v.TEXT_MESSAGE_START:{let h=await K(r,s,a,(p,g,x)=>p.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{messageId:p,role:g="assistant",name:x}=m;if(!s.find(_=>_.id===p)){let _={id:p,role:g,content:"",...x!==void 0&&{name:x}};s.push(_),u({messages:s})}}return f()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:h,delta:p}=m,g=s.find(_=>_.id===h);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${h}'`),f();let x=await K(r,s,a,(_,S,C)=>_.onTextMessageContentEvent?.({event:m,messages:S,state:C,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return u(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${p}`,u({messages:s})),f()}case v.TEXT_MESSAGE_END:{let{messageId:h}=m,p=s.find(g=>g.id===h);return p?(u(await K(r,s,a,(g,x,_)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:_,agent:n,input:t,textMessageBuffer:typeof p.content=="string"?p.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:p,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,(p,g,x)=>p.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{toolCallId:p,toolCallName:g,parentMessageId:x}=m,_=pm(s,x,p);_.toolCalls??=[],_.toolCalls.push({id:p,type:"function",function:{name:g,arguments:""}}),u({messages:s})}return f()}case v.TOOL_CALL_ARGS:{let{toolCallId:h,delta:p}=m,g=s.find(S=>S.toolCalls?.some(C=>C.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(S=>S.id===h);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${h}'`),f();let _=await K(r,s,a,(S,C,H)=>{let U=x.function.arguments,Y=x.function.name,re={};try{re=wo(U)}catch{}return S.onToolCallArgsEvent?.({event:m,messages:C,state:H,agent:n,input:t,toolCallBuffer:U,toolCallName:Y,partialToolCallArgs:re})});return u(_),_.stopPropagation!==!0&&(x.function.arguments+=p,u({messages:s})),f()}case v.TOOL_CALL_END:{let{toolCallId:h}=m,p=s.find(x=>x.toolCalls?.some(_=>_.id===h));if(!p)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${h}'`),f();let g=p.toolCalls?.find(x=>x.id===h);return g?(u(await K(r,s,a,(x,_,S)=>{let C=g.function.arguments,H=g.function.name,U={};try{U=JSON.parse(C)}catch{}return x.onToolCallEndEvent?.({event:m,messages:_,state:S,agent:n,input:t,toolCallName:H,toolCallArgs:U})})),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,(p,g,x)=>p.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{messageId:p,toolCallId:g,content:x,role:_}=m,S={id:p,toolCallId:g,role:_||"tool",content:x},C=s.findIndex(H=>H.role==="assistant"&&H.toolCalls?.some(U=>U.id===g));if(C===-1)s.push(S);else{let H=C+1;for(;H<s.length&&s[H].role==="tool";)H++;s.splice(H,0,S)}await Promise.all(r.map(H=>{H.onNewMessage?.({message:S,messages:s,state:a,agent:n,input:t})})),u({messages:s})}return f()}case v.STATE_SNAPSHOT:{let h=await K(r,s,a,(p,g,x)=>p.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{snapshot:p}=m;a=p,u({state:a})}return f()}case v.STATE_DELTA:{let h=await K(r,s,a,(p,g,x)=>p.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{delta:p}=m;try{a=Zr.applyPatch(a,p,!0,!1).newDocument,u({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
7
|
Patch operations: ${JSON.stringify(p,null,2)}
|
|
8
|
-
Error: ${x}`)}}return f()}case v.MESSAGES_SNAPSHOT:{let h=await K(r,s,a,(p,g,x)=>p.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messages:p}=m,g=new Map(p.map(C=>[C.id,C])),x=p.some(C=>C.role==="reasoning"),_=C=>C.role==="activity"||C.role==="reasoning"&&!x;s=s.filter(C=>_(C)||g.has(C.id)).map(C=>_(C)?C:g.get(C.id));let w=new Set(s.map(C=>C.id));for(let C of p)w.has(C.id)||s.push(C);c({messages:s})}return f()}case v.ACTIVITY_SNAPSHOT:{let h=m,p=s.findIndex(C=>C.id===h.messageId),g=p>=0?s[p]:void 0,x=g?.role==="activity"?g:void 0,_=h.replace??!0,w=await K(r,s,a,(C,H,U)=>C.onActivitySnapshotEvent?.({event:h,messages:H,state:U,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(w),w.stopPropagation!==!0){let C={id:h.messageId,role:"activity",activityType:h.activityType,content:j(h.content)},H;p===-1?(s.push(C),H=C):x?_&&(s[p]={...x,activityType:h.activityType,content:j(h.content)}):_&&(s[p]=C,H=C),c({messages:s}),H&&await Promise.all(r.map(U=>U.onNewMessage?.({message:H,messages:s,state:a,agent:n,input:t})))}return f()}case v.ACTIVITY_DELTA:{let h=m,p=s.findIndex(w=>w.id===h.messageId);if(p===-1)return f();let g=s[p];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${h.messageId}' is not an activity message`),f();let x=g,_=await K(r,s,a,(w,C,H)=>w.onActivityDeltaEvent?.({event:h,messages:C,state:H,agent:n,input:t,activityMessage:x}));if(c(_),_.stopPropagation!==!0)try{let w=j(x.content??{}),C=Xr.applyPatch(w,h.patch??[],!0,!1).newDocument;s[p]={...x,content:j(C),activityType:h.activityType},c({messages:s})}catch(w){let C=w instanceof Error?w.message:String(w);console.warn(`Failed to apply activity patch for '${h.messageId}': ${C}`)}return f()}case v.RAW:return c(await K(r,s,a,(h,p,g)=>h.onRawEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.CUSTOM:return c(await K(r,s,a,(h,p,g)=>h.onCustomEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.RUN_STARTED:{let h=await K(r,s,a,(p,g,x)=>p.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let p=m;if(p.input?.messages){for(let g of p.input.messages)s.find(x=>x.id===g.id)||s.push(g);c({messages:s})}}return f()}case v.RUN_FINISHED:{let h=m,p=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)=>x.onRunFinishedEvent?.({...p,messages:_,state:w,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=p.outcome==="interrupt"?[...p.interrupts]:[]),f()}case v.RUN_ERROR:return c(await K(r,s,a,(h,p,g)=>h.onRunErrorEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.STEP_STARTED:return c(await K(r,s,a,(h,p,g)=>h.onStepStartedEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.STEP_FINISHED:return c(await K(r,s,a,(h,p,g)=>h.onStepFinishedEvent?.({event:m,messages:p,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,p,g)=>h.onReasoningStartEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.REASONING_MESSAGE_START:{let h=await K(r,s,a,(p,g,x)=>p.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(h),h.stopPropagation!==!0){let{messageId:p}=m;if(!s.find(g=>g.id===p)){let g={id:p,role:"reasoning",content:""};s.push(g),c({messages:s})}}return f()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:h,delta:p}=m,g=s.find(_=>_.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,C)=>_.onReasoningMessageContentEvent?.({event:m,messages:w,state:C,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:""}${p}`,c({messages:s})),f()}case v.REASONING_MESSAGE_END:{let{messageId:h}=m,p=s.find(g=>g.id===h);return p?(c(await K(r,s,a,(g,x,_)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:_,agent:n,input:t,reasoningMessageBuffer:typeof p.content=="string"?p.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:p,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,p,g)=>h.onReasoningEndEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:h,entityId:p,encryptedValue:g}=m,x=await K(r,s,a,(_,w,C)=>_.onReasoningEncryptedValueEvent?.({event:m,messages:w,state:C,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let _=!1;if(h==="tool-call"){for(let w of s)if(w.role==="assistant"&&w.toolCalls){let C=w.toolCalls.find(H=>H.id===p);if(C){C.encryptedValue=g,_=!0;break}}}else{let w=s.find(C=>C.id===p);w?.role!=="activity"&&w&&(w.encryptedValue=g,_=!0)}_&&(l.messages=s)}return f()}}return m.type,f()}),Ms(),r.length>0?Ls({}):m=>m)},Js=t=>e=>{let n=rr(t),r=new Map,o=new Map,i=!1,s=!1,a=!1,l=new Map,c=!1,f=!1,m=!1,y=()=>{r.clear(),o.clear(),l.clear(),c=!1,f=!1,i=!1,s=!1,m=!0};return e.pipe(Me(h=>{let p=h.type;if(n?.event("VERIFY","Event:",h,{type:h.type}),s)return ne(()=>new ee(`Cannot send event type '${p}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(i&&p!==v.RUN_ERROR&&p!==v.RUN_STARTED)return ne(()=>new ee(`Cannot send event type '${p}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(p===v.RUN_STARTED){if(m&&!i)return ne(()=>new ee("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));i&&y()}}else if(a=!0,p!==v.RUN_STARTED&&p!==v.RUN_ERROR)return ne(()=>new ee("First event must be 'RUN_STARTED'"));switch(p){case v.TEXT_MESSAGE_START:{let g=h.messageId;return r.has(g)?ne(()=>new ee(`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),ue(h))}case v.TEXT_MESSAGE_CONTENT:{let g=h.messageId;return r.has(g)?ue(h):ne(()=>new ee(`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),ue(h)):ne(()=>new ee(`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 o.has(g)?ne(()=>new ee(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),ue(h))}case v.TOOL_CALL_ARGS:{let g=h.toolCallId;return o.has(g)?ue(h):ne(()=>new ee(`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 o.has(g)?(o.delete(g),ue(h)):ne(()=>new ee(`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)?ne(()=>new ee(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),ue(h))}case v.STEP_FINISHED:{let g=h.stepName;return l.has(g)?(l.delete(g),ue(h)):ne(()=>new ee(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,ue(h);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return ne(()=>new ee(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return ne(()=>new ee(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return ne(()=>new ee(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return i=!0,ue(h);case v.RUN_ERROR:return s=!0,ue(h);case v.CUSTOM:return ue(h);case v.THINKING_TEXT_MESSAGE_START:return c?f?ne(()=>new ee("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(f=!0,ue(h)):ne(()=>new ee("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?ue(h):ne(()=>new ee("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,ue(h)):ne(()=>new ee("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?ne(()=>new ee("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(c=!0,ue(h));case v.THINKING_END:return c?(c=!1,ue(h)):ne(()=>new ee("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return ue(h)}}))},Qt=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),pm=t=>bo(()=>Kt(t())).pipe(Ps(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return Kt(e.text()).pipe(Me(i=>{let s=i;if(o.includes("application/json"))try{s=JSON.parse(i)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,ne(()=>a)}))}let n={type:Qt.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new te(o=>(o.next(n),(async()=>{try{for(;;){let{done:i,value:s}=await r.read();if(i)break;let a={type:Qt.DATA,data:s};o.next(a)}o.complete()}catch(i){o.error(i)}})(),()=>{r.cancel().catch(i=>{if(i?.name!=="AbortError")throw i})})):ne(()=>Error("Failed to getReader() from response"))})),fm=(t,e)=>{let n=rr(e),r=new st,o=new TextDecoder("utf-8",{fatal:!1}),i="";t.subscribe({next:a=>{if(a.type!==Qt.HEADERS&&a.type===Qt.DATA&&a.data){let l=o.decode(a.data,{stream:!0});i+=l;let c=i.split(/\n\n/);i=c.pop()||"";for(let f of c)s(f)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
|
|
9
|
-
`),
|
|
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()},
|
|
11
|
-
`)},Im=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,f=[],m={},y=h=>{typeof h=="object"&&h&&("messages"in h&&delete h.messages,o=h)};return r.pipe(Me(h=>{switch(h.type){case v.TEXT_MESSAGE_START:{let p=h;return[{type:Q.enum.TextMessageStart,messageId:p.messageId,role:p.role}]}case v.TEXT_MESSAGE_CONTENT:{let p=h;return[{type:Q.enum.TextMessageContent,messageId:p.messageId,content:p.delta}]}case v.TEXT_MESSAGE_END:{let p=h;return[{type:Q.enum.TextMessageEnd,messageId:p.messageId}]}case v.TOOL_CALL_START:{let p=h;return f.push({id:p.toolCallId,type:"function",function:{name:p.toolCallName,arguments:""}}),s=!0,m[p.toolCallId]=p.toolCallName,[{type:Q.enum.ActionExecutionStart,actionExecutionId:p.toolCallId,actionName:p.toolCallName,parentMessageId:p.parentMessageId}]}case v.TOOL_CALL_ARGS:{let p=h,g=f.find(_=>_.id===p.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${p.toolCallId}'`),[];g.function.arguments+=p.delta;let x=!1;if(c){let _=c.find(w=>w.tool==g.function.name);if(_)try{let w=JSON.parse(Eo(g.function.arguments));_.tool_argument&&_.tool_argument in w?(y({...o,[_.state_key]:w[_.tool_argument]}),x=!0):_.tool_argument||(y({...o,[_.state_key]:w}),x=!0)}catch{}}return[{type:Q.enum.ActionExecutionArgs,actionExecutionId:p.toolCallId,args:p.delta},...x?[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case v.TOOL_CALL_END:{let p=h;return[{type:Q.enum.ActionExecutionEnd,actionExecutionId:p.toolCallId}]}case v.TOOL_CALL_RESULT:{let p=h;return[{type:Q.enum.ActionExecutionResult,actionExecutionId:p.toolCallId,result:p.content,actionName:m[p.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let p=h;switch(p.name){case"Exit":i=!1;break;case"PredictState":c=p.value;break}return[{type:Q.enum.MetaEvent,name:p.name,value:p.value}]}case v.STATE_SNAPSHOT:return y(h.snapshot),[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case v.STATE_DELTA:{let p=h,g=Xr.applyPatch(o,p.delta,!0,!1);return g?(y(g.newDocument),[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=h.messages,[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:Cm(l)}:{}}),active:!1}];case v.RUN_ERROR:{let p=h;return[{type:Q.enum.RunError,message:p.message,code:p.code}]}case v.STEP_STARTED:return a=h.stepName,f=[],c=null,[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return f=[],c=null,[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Cm(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=km(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var ri=t=>e=>{let n=rr(t),r,o,i,s,a=()=>{if(!r||s!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return s=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},l=()=>{if(!o||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return s=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},c=()=>{if(!i||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:i.messageId};return s=void 0,i=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},f=()=>s==="text"?[a()]:s==="tool"?[l()]:s==="reasoning"?[c()]:[];return e.pipe(Me(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 y=m,h=[];if((s!=="text"||y.messageId!==void 0&&y.messageId!==r?.messageId)&&h.push(...f()),s!=="text"){if(y.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:y.messageId,name:y.name},s="text";let w={type:v.TEXT_MESSAGE_START,messageId:y.messageId,role:y.role||"assistant",...y.name!==void 0&&{name:y.name}};h.push(w),n?.event("TRANSFORM","TEXT_MESSAGE_START",w,{messageId:y.messageId})}if(y.delta!==void 0){let w={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:y.delta};h.push(w),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",w,{messageId:r.messageId})}return h;case v.TOOL_CALL_CHUNK:let p=m,g=[];if((s!=="tool"||p.toolCallId!==void 0&&p.toolCallId!==o?.toolCallId)&&g.push(...f()),s!=="tool"){if(p.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(p.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:p.toolCallId,toolCallName:p.toolCallName,parentMessageId:p.parentMessageId},s="tool";let w={type:v.TOOL_CALL_START,toolCallId:p.toolCallId,toolCallName:p.toolCallName,parentMessageId:p.parentMessageId};g.push(w),n?.event("TRANSFORM","TOOL_CALL_START",w,{toolCallId:p.toolCallId,toolCallName:p.toolCallName})}if(p.delta!==void 0){let w={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:p.delta};g.push(w),n?.event("TRANSFORM","TOOL_CALL_ARGS",w,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let x=m,_=[];if((s!=="reasoning"||x.messageId&&x.messageId!==i?.messageId)&&_.push(...f()),s!=="reasoning"){if(x.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");i={messageId:x.messageId},s="reasoning";let w={type:v.REASONING_MESSAGE_START,messageId:x.messageId};_.push(w),n?.event("TRANSFORM","REASONING_MESSAGE_START",w,{messageId:x.messageId})}if(x.delta!==void 0){let w={type:v.REASONING_MESSAGE_CONTENT,messageId:i.messageId,delta:x.delta};_.push(w),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",w,{messageId:i.messageId})}return _}return m.type,[]}),Jt(()=>{f()}))};function Nm(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function Qc(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.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 oi=class{runNext(t,e){return e.run(t).pipe(ri(!1))}runNextWithState(t,e){let n=j(t.messages||[]),r=j(t.state||{}),o=new no;return Jc(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(yo(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:j(n),state:j(r)})))}},Rm=class extends oi{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Om(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 Mm=class extends oi{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Om)};return this.runNext(o,e)}},Wc="THINKING_START",Xc="THINKING_END",Yc="THINKING_TEXT_MESSAGE_START",Kc="THINKING_TEXT_MESSAGE_CONTENT",Zc="THINKING_TEXT_MESSAGE_END",Lm=class extends oi{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(Zt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Wc:{this.currentReasoningId=De();let{title:e,...n}=t;return this.warnAboutTransformation(Wc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Yc:return this.currentMessageId=De(),this.warnAboutTransformation(Yc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Kc:{let{delta:e,...n}=t;return this.warnAboutTransformation(Kc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??De(),delta:e}}case Zc:{let e=this.currentMessageId??De();return this.warnAboutTransformation(Zc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Xc:{let e=this.currentReasoningId??De();return this.warnAboutTransformation(Xc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Pm(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function Dm(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function Um(t){let e=Pm(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 Hm(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>Dm(r)?Um(r):r);return{...t,content:n}}var Gm=class extends oi{run(t,e){let n={...t,messages:t.messages.map(Hm)};return this.runNext(n,e)}},Fm="0.0.57",$m=class{get maxVersion(){return Fm}get debug(){return this._debug}set debug(t){this._debug=ni(t),this._debugLogger=Zs(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Zs(ni(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??yt(),this.messages=j(r??[]),this.state=j(o??{}),this._debug=ni(i),this._debugLogger=Zs(this._debug),nr(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Mm),nr(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Lm),nr(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Gm)}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 Rm(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??yt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new st;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await vo(to(()=>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),ri(this.debugLogger),Js(this.debugLogger),l=>l.pipe(xo(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),Qn(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),Jt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(ue(null)));let a=j(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new xs}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??yt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new st;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await vo(to(()=>bo(()=>this.connect(n)),ri(this.debugLogger),Js(this.debugLogger),l=>l.pipe(xo(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),Qn(l=>(this.isRunning=!1,l instanceof xs?ro:this.onError(n,l,i))),Jt(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(ue(null)),{defaultValue:void 0});let a=j(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Jc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(Ds(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=j(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||yt(),tools:j(t?.tools??[]),context:j(t?.context??[]),forwardedProps:j(t?.forwardedProps??{}),state:j(this.state),messages:e,...t?.resume===void 0?{}:{resume:j(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new ee(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(Nm(i))throw new ee(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await K(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return Kt(K(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Zt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await K(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=j(this.messages),t.state=j(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=j(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=j(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=j(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??yt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(ri(this.debugLogger),Js(this.debugLogger),Im(this.threadId,e.runId,this.agentId),n=>n.pipe(Zt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},eu=class extends $m{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=j(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return mm(pm(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=j(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 ii=class{element;#n;#e;#t=[];constructor(e){this.#n=e,this.#e=e.strings??ae,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:De(),file:e,status:He.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#o(e);if(r!==null){n.status=He.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===He.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===He.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()}#o(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",Or(this.#n.maxBytes)):zm(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#o(e.file);if(n!==null){e.status=He.ERROR,e.error=n,this.#s(),this.#n.onChange?.();return}e.status=He.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#s(),this.#n.upload(e.file,o=>{e.progress=o,this.#s()},r.signal).then(o=>{e.status=He.READY,e.ref=o}).catch(o=>{e.status=He.ERROR,e.error=o instanceof Error?o.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.#i(e))}#i(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=fs(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.setAttribute("part","attachment-chip-name"),o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=e.status===He.ERROR?e.error:Or(e.file.size),n.append(r,o,i),e.status===He.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===He.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 zm(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}function si(t,e=Date.now(),n=ae){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let o=Math.round(r/60);if(o<60)return n.minutesAgo.replace("{n}",String(o));let i=Math.round(o/60);if(i<24)return n.hoursAgo.replace("{n}",String(i));let s=Math.round(i/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}var or=class{element;#n;#e;#t;#o;#r=[];constructor(e,n=ae){this.#n=e,this.#o=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",o=>{o.key==="Escape"&&(o.stopPropagation(),this.close())})}setRuns(e){this.#r=e,this.#a()}setStrings(e){this.#o=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.#o.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:si(Date.parse(e.started_at),Date.now(),this.#o),r.title=e.run_id,n.append(r),e.parent_run_id!==null){let o=document.createElement("span");o.className="checkpoint-branch",o.setAttribute("part","checkpoint-branch"),o.textContent=this.#o.forkedRun,o.title=e.parent_run_id,n.append(o)}return n.append(this.#i(e.run_id,"resume",this.#o.resumeRun),this.#i(e.run_id,"fork",this.#o.forkRun)),n}#i(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`checkpoint-action checkpoint-${n}`,o.setAttribute("part",`checkpoint-action checkpoint-${n}`),o.textContent=r,o.addEventListener("click",()=>{this.close(),this.#n(e,n)}),o}};function tu(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 ta(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2);let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=tu("cancel",r.cancel),f=tu("confirm",r.confirm),m=!1,y=h=>{m||(m=!0,c.disabled=!0,f.disabled=!0,i.setAttribute("data-resolved",h?"confirmed":"declined"),o(h))};if(c.addEventListener("click",()=>y(!1)),f.addEventListener("click",()=>y(!0)),n.signal?.addEventListener("abort",()=>y(!1),{once:!0}),l.append(c,f),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){y(!1);return}f.focus()})}function na(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function Bm(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function ra(t,e,n={}){let r=n.strings??ae,o=e.options??[],i=o.length>0,s=!i||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-${o.length}-${e.question.length}`,y=[];for(let U of o){let Y=document.createElement("label");Y.className="question-choice",Y.setAttribute("part","question-choice");let re=document.createElement("input");re.type="radio",re.name=m,re.value=U,re.setAttribute("part","question-radio");let Be=document.createElement("span");Be.setAttribute("part","question-choice-text"),Be.textContent=U,Y.append(re,Be),f.appendChild(Y),y.push(re)}let h=null,p=null;if(s){if(p=Bm(r.answerPlaceholder),i){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice"),h=document.createElement("input"),h.type="radio",h.name=m,h.value="",h.setAttribute("part","question-radio");let Y=document.createElement("span");Y.setAttribute("part","question-choice-text"),Y.textContent=r.otherOption,U.append(h,Y),f.appendChild(U),p.disabled=!0}f.appendChild(p)}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 _=!1,w=()=>{let U=y.find(Y=>Y.checked);if(U!==void 0)return U.value;if(p!==null&&(h===null||h.checked)){let Y=p.value.trim();return Y===""?null:Y}return null},C=()=>{p!==null&&h!==null&&(p.disabled=!h.checked),x.disabled=w()===null},H=U=>{if(!_){_=!0,x.disabled=!0;for(let Y of y)Y.disabled=!0;h!==null&&(h.disabled=!0),p!==null&&(p.disabled=!0),l.setAttribute("data-resolved",U===""?"cancelled":"answered"),a(U)}};for(let U of[...y,...h!==null?[h]:[]])U.addEventListener("change",C);if(p?.addEventListener("input",C),p?.addEventListener("keydown",U=>{if(U.key==="Enter"){U.preventDefault();let Y=w();Y!==null&&H(Y)}}),x.addEventListener("click",()=>{let U=w();U!==null&&H(U)}),n.signal?.addEventListener("abort",()=>H(""),{once:!0}),l.append(c,f,g),t.appendChild(l),n.signal?.aborted===!0){H("");return}C(),(i?y[0]:p)?.focus()})}function nu(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 Vm(t){if(Array.isArray(t))return t}function jm(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,s,a=[],l=!0,c=!1;try{if(i=(n=n.call(t)).next,e!==0)for(;!(l=(r=i.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(f){c=!0,o=f}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function qm(){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 Wm(t,e){return Vm(t)||jm(t,e)||Xm(t,e)||qm()}function Xm(t,e){if(t){if(typeof t=="string")return nu(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)?nu(t,e):void 0}}var vu=Object.entries,ru=Object.setPrototypeOf,Ym=Object.isFrozen,Km=Object.getPrototypeOf,Zm=Object.getOwnPropertyDescriptor,we=Object.freeze,Se=Object.seal,Nn=Object.create,bu=typeof Reflect<"u"&&Reflect,ca=bu.apply,ua=bu.construct;we||(we=function(e){return e});Se||(Se=function(e){return e});ca||(ca=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(n,o)});ua||(ua=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var In=me(Array.prototype.forEach),Jm=me(Array.prototype.lastIndexOf),ou=me(Array.prototype.pop),Cn=me(Array.prototype.push),Qm=me(Array.prototype.splice),At=Array.isArray,ar=me(String.prototype.toLowerCase),oa=me(String.prototype.toString),iu=me(String.prototype.match),ir=me(String.prototype.replace),su=me(String.prototype.indexOf),eg=me(String.prototype.trim),tg=me(Number.prototype.toString),ng=me(Boolean.prototype.toString),au=typeof BigInt>"u"?null:me(BigInt.prototype.toString),lu=typeof Symbol>"u"?null:me(Symbol.prototype.toString),ye=me(Object.prototype.hasOwnProperty),sr=me(Object.prototype.toString),be=me(RegExp.prototype.test),en=rg(TypeError);function me(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return ca(t,e,r)}}function rg(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return ua(t,n)}}function q(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ar;if(ru&&ru(t,null),!At(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=n(o);i!==o&&(Ym(e)||(e[r]=i),o=i)}t[o]=!0}return t}function og(t){for(let e=0;e<t.length;e++)ye(t,e)||(t[e]=null);return t}function Ae(t){let e=Nn(null);for(let r of vu(t)){var n=Wm(r,2);let o=n[0],i=n[1];ye(t,o)&&(At(i)?e[o]=og(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ae(i):e[o]=i)}return e}function ig(t){switch(typeof t){case"string":return t;case"number":return tg(t);case"boolean":return ng(t);case"bigint":return au?au(t):"0";case"symbol":return lu?lu(t):"Symbol()";case"undefined":return sr(t);case"function":case"object":{if(t===null)return sr(t);let e=t,n=Xe(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:sr(r)}return sr(t)}default:return sr(t)}}function Xe(t,e){for(;t!==null;){let r=Zm(t,e);if(r){if(r.get)return me(r.get);if(typeof r.value=="function")return me(r.value)}t=Km(t)}function n(){return null}return n}function sg(t){try{return be(t,""),!0}catch{return!1}}var cu=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"]),ia=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"]),sa=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"]),ag=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"]),aa=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"]),lg=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),uu=we(["#text"]),du=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"]),la=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","dominant-baseline","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-orientation","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"]),pu=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"]),ai=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),cg=Se(/{{[\w\W]*|^[\w\W]*}}/g),ug=Se(/<%[\w\W]*|^[\w\W]*%>/g),dg=Se(/\${[\w\W]*/g),pg=Se(/^data-[\-\w.\u00B7-\uFFFF]+$/),fg=Se(/^aria-[\-\w]+$/),fu=Se(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),hg=Se(/^(?:\w+script|data):/i),mg=Se(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),gg=Se(/^html$/i),vg=Se(/^[a-z][.\w]*(-[.\w]+)+$/i),hu=Se(/<[/\w!]/g),mu=Se(/<[/\w]/g),bg=Se(/<\/no(script|embed|frames)/i),yg=Se(/\/>/i),Ue={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},xg=function(){return typeof window>"u"?null:window},Eg=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},gu=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},_t=function(e,n,r,o){return ye(e,n)&&At(e[n])?q(o.base?Ae(o.base):{},e[n],o.transform):r};function yu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:xg(),e=S=>yu(S);if(e.version="3.4.13",e.removed=[],!t||!t.document||t.document.nodeType!==Ue.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let i=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,c=t.NamedNodeMap;c===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let f=t.DOMParser,m=t.trustedTypes,y=a.prototype,h=Xe(y,"cloneNode"),p=Xe(y,"remove"),g=Xe(y,"nextSibling"),x=Xe(y,"childNodes"),_=Xe(y,"parentNode"),w=Xe(y,"shadowRoot"),C=Xe(y,"attributes"),H=s&&s.prototype?Xe(s.prototype,"nodeType"):null,U=s&&s.prototype?Xe(s.prototype,"nodeName"):null,Y=s&&s.prototype?Xe(s.prototype,"ownerDocument"):null;if(typeof i=="function"){let S=n.createElement("template");S.content&&S.content.ownerDocument&&(n=S.content.ownerDocument)}let re,Be="",Ti,Na=!1,Ln=0,Ra=function(){if(Ln>0)throw en('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},on=function(d){Ra(),Ln++;try{return re.createHTML(d)}finally{Ln--}},Zu=function(d){Ra(),Ln++;try{return re.createScriptURL(d)}finally{Ln--}},Ju=function(){return Na||(Ti=Eg(m,o),Na=!0),Ti},gr=n,wi=gr.implementation,Oa=gr.createNodeIterator,Qu=gr.createDocumentFragment,ed=gr.getElementsByTagName,td=r.importNode,oe=gu();e.isSupported=typeof vu=="function"&&typeof _=="function"&&wi&&wi.createHTMLDocument!==void 0;let nd=cg,rd=ug,od=dg,id=pg,sd=fg,ad=hg,Ma=mg,ld=vg,La=fu,ie=null,Si=q({},[...cu,...ia,...sa,...aa,...uu]),se=null,_i=q({},[...du,...la,...pu,...ai]),de=Object.seal(Nn(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}})),Pn=null,Pa=null,mt=Object.seal(Nn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Da=!0,Ai=!0,Ua=!1,Ha=!0,gt=!1,vt=!0,It=!1,ki=!1,vr=null,br=null,Ii=!1,sn=!1,yr=!1,xr=!1,Ga=!0,Fa=!1,$a="user-content-",Ci=!0,Er=!1,an={},Ze=null,Ni=q({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),za=null,Ba=q({},["audio","video","img","source","image","track"]),Ri=null,Va=q({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Tr="http://www.w3.org/1998/Math/MathML",wr="http://www.w3.org/2000/svg",Je="http://www.w3.org/1999/xhtml",ln=Je,Oi=!1,Mi=null,cd=q({},[Tr,wr,Je],oa),ja=we(["mi","mo","mn","ms","mtext"]),Li=q({},ja),qa=we(["annotation-xml"]),Pi=q({},qa),ud=q({},["title","style","font","a","script"]),Dn=null,dd=["application/xhtml+xml","text/html"],pd="text/html",le=null,cn=null,fd=n.createElement("form"),Wa=function(d){return d instanceof RegExp||d instanceof Function},Di=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(cn&&cn===d)return;(!d||typeof d!="object")&&(d={}),d=Ae(d),Dn=dd.indexOf(d.PARSER_MEDIA_TYPE)===-1?pd:d.PARSER_MEDIA_TYPE,le=Dn==="application/xhtml+xml"?oa:ar,ie=_t(d,"ALLOWED_TAGS",Si,{transform:le}),se=_t(d,"ALLOWED_ATTR",_i,{transform:le}),Mi=_t(d,"ALLOWED_NAMESPACES",cd,{transform:oa}),Ri=_t(d,"ADD_URI_SAFE_ATTR",Va,{transform:le,base:Va}),za=_t(d,"ADD_DATA_URI_TAGS",Ba,{transform:le,base:Ba}),Ze=_t(d,"FORBID_CONTENTS",Ni,{transform:le}),Pn=_t(d,"FORBID_TAGS",Ae({}),{transform:le}),Pa=_t(d,"FORBID_ATTR",Ae({}),{transform:le}),an=ye(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?Ae(d.USE_PROFILES):d.USE_PROFILES:!1,Da=d.ALLOW_ARIA_ATTR!==!1,Ai=d.ALLOW_DATA_ATTR!==!1,Ua=d.ALLOW_UNKNOWN_PROTOCOLS||!1,Ha=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,gt=d.SAFE_FOR_TEMPLATES||!1,vt=d.SAFE_FOR_XML!==!1,It=d.WHOLE_DOCUMENT||!1,sn=d.RETURN_DOM||!1,yr=d.RETURN_DOM_FRAGMENT||!1,xr=d.RETURN_TRUSTED_TYPE||!1,Ii=d.FORCE_BODY||!1,Ga=d.SANITIZE_DOM!==!1,Fa=d.SANITIZE_NAMED_PROPS||!1,Ci=d.KEEP_CONTENT!==!1,Er=d.IN_PLACE||!1,La=sg(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:fu,ln=typeof d.NAMESPACE=="string"?d.NAMESPACE:Je,Li=ye(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ae(d.MATHML_TEXT_INTEGRATION_POINTS):q({},ja),Pi=ye(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ae(d.HTML_INTEGRATION_POINTS):q({},qa);let b=ye(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ae(d.CUSTOM_ELEMENT_HANDLING):Nn(null);if(de=Nn(null),ye(b,"tagNameCheck")&&Wa(b.tagNameCheck)&&(de.tagNameCheck=b.tagNameCheck),ye(b,"attributeNameCheck")&&Wa(b.attributeNameCheck)&&(de.attributeNameCheck=b.attributeNameCheck),ye(b,"allowCustomizedBuiltInElements")&&typeof b.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=b.allowCustomizedBuiltInElements),Se(de),gt&&(Ai=!1),yr&&(sn=!0),an&&(ie=q({},uu),se=Nn(null),an.html===!0&&(q(ie,cu),q(se,du)),an.svg===!0&&(q(ie,ia),q(se,la),q(se,ai)),an.svgFilters===!0&&(q(ie,sa),q(se,la),q(se,ai)),an.mathMl===!0&&(q(ie,aa),q(se,pu),q(se,ai))),mt.tagCheck=null,mt.attributeCheck=null,ye(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?mt.tagCheck=d.ADD_TAGS:At(d.ADD_TAGS)&&(ie===Si&&(ie=Ae(ie)),q(ie,d.ADD_TAGS,le))),ye(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?mt.attributeCheck=d.ADD_ATTR:At(d.ADD_ATTR)&&(se===_i&&(se=Ae(se)),q(se,d.ADD_ATTR,le))),ye(d,"ADD_URI_SAFE_ATTR")&&At(d.ADD_URI_SAFE_ATTR)&&q(Ri,d.ADD_URI_SAFE_ATTR,le),ye(d,"FORBID_CONTENTS")&&At(d.FORBID_CONTENTS)&&(Ze===Ni&&(Ze=Ae(Ze)),q(Ze,d.FORBID_CONTENTS,le)),ye(d,"ADD_FORBID_CONTENTS")&&At(d.ADD_FORBID_CONTENTS)&&(Ze===Ni&&(Ze=Ae(Ze)),q(Ze,d.ADD_FORBID_CONTENTS,le)),Ci&&(ie["#text"]=!0),It&&q(ie,["html","head","body"]),ie.table&&(q(ie,["tbody"]),delete Pn.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw en('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw en('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let E=re;re=d.TRUSTED_TYPES_POLICY;try{Be=on("")}catch(R){throw re=E,R}}else d.TRUSTED_TYPES_POLICY===null?(re=void 0,Be=""):(re===void 0&&(re=Ju()),re&&typeof Be=="string"&&(Be=on("")));we&&we(d),cn=d},Xa=q({},[...ia,...sa,...ag]),Ya=q({},[...aa,...lg]),hd=function(d,b,E){return b.namespaceURI===Je?d==="svg":b.namespaceURI===Tr?d==="svg"&&(E==="annotation-xml"||Li[E]):!!Xa[d]},md=function(d,b,E){return b.namespaceURI===Je?d==="math":b.namespaceURI===wr?d==="math"&&Pi[E]:!!Ya[d]},gd=function(d,b,E){return b.namespaceURI===wr&&!Pi[E]||b.namespaceURI===Tr&&!Li[E]?!1:!Ya[d]&&(ud[d]||!Xa[d])},vd=function(d){let b=_(d);(!b||!b.tagName)&&(b={namespaceURI:ln,tagName:"template"});let E=ar(d.tagName),R=ar(b.tagName);return Mi[d.namespaceURI]?d.namespaceURI===wr?hd(E,b,R):d.namespaceURI===Tr?md(E,b,R):d.namespaceURI===Je?gd(E,b,R):!!(Dn==="application/xhtml+xml"&&Mi[d.namespaceURI]):!1},bt=function(d){Cn(e.removed,{element:d});try{_(d).removeChild(d)}catch{if(p(d),!_(d))throw en("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Sr=function(d){Un(d);let b=x(d);if(b){let R=[];In(b,L=>{Cn(R,L)}),In(R,L=>{try{p(L)}catch{}})}let E=C(d);if(E)for(let R=E.length-1;R>=0;--R){let L=E[R],G=L&&L.name;if(typeof G=="string")try{d.removeAttribute(G)}catch{}}},Ct=function(d,b){try{Cn(e.removed,{attribute:b.getAttributeNode(d),from:b})}catch{Cn(e.removed,{attribute:null,from:b})}if(b.removeAttribute(d),d==="is")if(sn||yr)try{bt(b)}catch{}else try{b.setAttribute(d,"")}catch{}},bd=function(d){let b=C(d);if(b)for(let E=b.length-1;E>=0;--E){let R=b[E],L=R&&R.name;if(!(typeof L!="string"||se[le(L)]))try{d.removeAttribute(L)}catch{}}},Un=function(d){let b=[d];for(;b.length>0;){let E=b.pop();(H?H(E):E.nodeType)===Ue.element&&bd(E);let L=x(E);if(L)for(let G=L.length-1;G>=0;--G)b.push(L[G])}},yd=function(d){if(!vt)return;let b=[d];for(;b.length>0;){let E=b.pop(),R=H?H(E):E.nodeType;if(R===Ue.processingInstruction||R===Ue.comment&&be(mu,E.data)){try{p(E)}catch{}continue}if(R===Ue.element){let G=E,Z=le(U?U(E):E.nodeName);try{G.hasAttribute&&G.hasAttribute("patchsrc")&&G.removeAttribute("patchsrc"),G.hasAttribute&&G.hasAttribute("for")&&Z!=="label"&&Z!=="output"&&G.removeAttribute("for")}catch{}}let L=x(E);if(L)for(let G=L.length-1;G>=0;--G)b.push(L[G])}},Ka=function(d){let b=null,E=null;if(Ii)d="<remove></remove>"+d;else{let G=iu(d,/^[\r\n\t ]+/);E=G&&G[0]}Dn==="application/xhtml+xml"&&ln===Je&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let R=re?on(d):d;if(ln===Je)try{b=new f().parseFromString(R,Dn)}catch{}if(!b||!b.documentElement){b=wi.createDocument(ln,"template",null);try{b.documentElement.innerHTML=Oi?Be:R}catch{}}let L=b.body||b.documentElement;return d&&E&&L.insertBefore(n.createTextNode(E),L.childNodes[0]||null),ln===Je?ed.call(b,It?"html":"body")[0]:It?b.documentElement:L},Za=function(d){let b=Y?Y(d):d.ownerDocument;return Oa.call(b||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},_r=function(d){return d=ir(d,nd," "),d=ir(d,rd," "),d=ir(d,od," "),d},Ui=function(d){var b;d.normalize();let E=Y?Y(d):d.ownerDocument,R=Oa.call(E||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),L=R.nextNode();for(;L;)L.data=_r(L.data),L=R.nextNode();let G=(b=d.querySelectorAll)===null||b===void 0?void 0:b.call(d,"template");G&&In(G,Z=>{un(Z.content)&&Ui(Z.content)})},Ar=function(d){let b=U?U(d):null;return typeof b!="string"||le(b)!=="form"?!1:typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||d.attributes!==C(d)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function"||d.nodeType!==H(d)||d.childNodes!==x(d)},un=function(d){if(!H||typeof d!="object"||d===null)return!1;try{return H(d)===Ue.documentFragment}catch{return!1}},Hn=function(d){if(!H||typeof d!="object"||d===null)return!1;try{return typeof H(d)=="number"}catch{return!1}};function Qe(S,d,b){S.length!==0&&In(S,E=>{E.call(e,d,b,cn)})}let xd=function(d,b){return!!(vt&&d.hasChildNodes()&&!Hn(d.firstElementChild)&&be(hu,d.textContent)&&be(hu,d.innerHTML)||vt&&d.namespaceURI===Je&&b==="style"&&Hn(d.firstElementChild)||d.nodeType===Ue.processingInstruction||vt&&d.nodeType===Ue.comment&&be(mu,d.data))},Ed=function(d,b,E){if(!Pn[b]&&tl(b)&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,b)||de.tagNameCheck instanceof Function&&de.tagNameCheck(b)))return!1;if(Ci&&!Ze[b]){let R=_(d),L=x(d);if(L&&R){let G=L.length;for(let Z=G-1;Z>=0;--Z){let ce=d===E?h(L[Z],!0):L[Z];R.insertBefore(ce,g(d))}}}return bt(d),!0},Ja=function(d,b,E,R){return d.length===0?b:b===E||b===R?Ae(b):b},Qa=function(d,b){if(Qe(oe.beforeSanitizeElements,d,null),d!==b&&_(d)===null)return Er&&Un(d),!0;if(Ar(d))return bt(d),!0;let E=le(U?U(d):d.nodeName);if(ie=Ja(oe.uponSanitizeElement,ie,Si,vr),Qe(oe.uponSanitizeElement,d,{tagName:E,allowedTags:ie}),d!==b&&_(d)===null)return Er&&Un(d),!0;if(xd(d,E))return bt(d),!0;if(Pn[E]||!(mt.tagCheck instanceof Function&&mt.tagCheck(E))&&!ie[E]){let L=Ed(d,E,b);return L===!1&&Qe(oe.afterSanitizeElements,d,null),L}if((H?H(d):d.nodeType)===Ue.element&&!vd(d)||(E==="noscript"||E==="noembed"||E==="noframes")&&be(bg,d.innerHTML))return bt(d),!0;if(gt&&d.nodeType===Ue.text){let L=_r(d.textContent);d.textContent!==L&&(Cn(e.removed,{element:d.cloneNode()}),d.textContent=L)}return Qe(oe.afterSanitizeElements,d,null),!1},el=function(d,b,E){if(Pa[b]||vt&&b==="patchsrc"||vt&&b==="for"&&d!=="label"&&d!=="output"||Ga&&(b==="id"||b==="name")&&(E in n||E in fd))return!1;let R=se[b]||mt.attributeCheck instanceof Function&&mt.attributeCheck(b,d);if(!(Ai&&be(id,b))){if(!(Da&&be(sd,b))){if(R){if(!Ri[b]){if(!be(La,ir(E,Ma,""))){if(!((b==="src"||b==="xlink:href"||b==="href")&&d!=="script"&&su(E,"data:")===0&&za[d])){if(!(Ua&&!be(ad,ir(E,Ma,"")))){if(E)return!1}}}}}else if(!(tl(d)&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,d)||de.tagNameCheck instanceof Function&&de.tagNameCheck(d))&&(de.attributeNameCheck instanceof RegExp&&be(de.attributeNameCheck,b)||de.attributeNameCheck instanceof Function&&de.attributeNameCheck(b,d))||b==="is"&&de.allowCustomizedBuiltInElements&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,E)||de.tagNameCheck instanceof Function&&de.tagNameCheck(E))))return!1}}return!0},Td=q({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),tl=function(d){return!Td[ar(d)]&&be(ld,d)},wd=function(d,b,E,R){if(re&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!E)switch(m.getAttributeType(d,b)){case"TrustedHTML":return on(R);case"TrustedScriptURL":return Zu(R)}return R},Sd=function(d,b,E,R){try{E?d.setAttributeNS(E,b,R):d.setAttribute(b,R),Ar(d)?bt(d):ou(e.removed)}catch{Ct(b,d)}},nl=function(d){Qe(oe.beforeSanitizeAttributes,d,null);let b=d.attributes;if(!b||Ar(d))return;se=Ja(oe.uponSanitizeAttribute,se,_i,br);let E={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},R=b.length,L=le(d.nodeName);for(;R--;){let G=b[R],Z=G.name,ce=G.namespaceURI,Ce=G.value,Ne=le(Z),Gi=Ce,Ie=Z==="value"?Gi:eg(Gi);if(E.attrName=Ne,E.attrValue=Ie,E.keepAttr=!0,E.forceKeepAttr=void 0,Qe(oe.uponSanitizeAttribute,d,E),Ie=E.attrValue,Fa&&(Ne==="id"||Ne==="name")&&su(Ie,$a)!==0&&(Ct(Z,d),Ie=$a+Ie),vt&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ie)){Ct(Z,d);continue}if(Ne==="attributename"&&iu(Ie,"href")){Ct(Z,d);continue}if(!E.forceKeepAttr){if(!E.keepAttr){Ct(Z,d);continue}if(!Ha&&be(yg,Ie)){Ct(Z,d);continue}if(gt&&(Ie=_r(Ie)),!el(L,Ne,Ie)){Ct(Z,d);continue}Ie=wd(L,Ne,ce,Ie),Ie!==Gi&&Sd(d,Z,ce,Ie)}}Qe(oe.afterSanitizeAttributes,d,null)},kr=function(d){let b=null,E=Za(d);for(Qe(oe.beforeSanitizeShadowDOM,d,null);b=E.nextNode();)if(Qe(oe.uponSanitizeShadowNode,b,null),Qa(b,d),nl(b),un(b.content)&&kr(b.content),(H?H(b):b.nodeType)===Ue.element){let L=w(b);un(L)&&(Hi(L),kr(L))}Qe(oe.afterSanitizeShadowDOM,d,null)},Hi=function(d){let b=[{node:d,shadow:null}];for(;b.length>0;){let E=b.pop();if(E.shadow){kr(E.shadow);continue}let R=E.node,G=(H?H(R):R.nodeType)===Ue.element,Z=x(R);if(Z)for(let ce=Z.length-1;ce>=0;--ce)b.push({node:Z[ce],shadow:null});if(G){let ce=U?U(R):null;if(typeof ce=="string"&&le(ce)==="template"){let Ce=R.content;un(Ce)&&b.push({node:Ce,shadow:null})}}if(G){let ce=w(R);un(ce)&&b.push({node:null,shadow:ce},{node:ce,shadow:null})}}};return e.sanitize=function(S){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},b=null,E=null,R=null,L=null;if(Oi=!S,Oi&&(S="<!-->"),typeof S!="string"&&!Hn(S)&&(S=ig(S),typeof S!="string"))throw en("dirty is not a string, aborting");if(!e.isSupported)return S;ki?(ie=vr,se=br):Di(d),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=Ae(ie)),oe.uponSanitizeAttribute.length>0&&(se=Ae(se)),e.removed=[];let G=Er&&typeof S!="string"&&Hn(S);if(G){yd(S);let Ce=U?U(S):S.nodeName;if(typeof Ce=="string"){let Ne=le(Ce);if(!ie[Ne]||Pn[Ne])throw Sr(S),en("root node is forbidden and cannot be sanitized in-place")}if(Ar(S))throw Sr(S),en("root node is clobbered and cannot be sanitized in-place");try{Hi(S)}catch(Ne){throw Sr(S),Ne}}else if(Hn(S))b=Ka("<!---->"),E=b.ownerDocument.importNode(S,!0),E.nodeType===Ue.element&&E.nodeName==="BODY"||E.nodeName==="HTML"?b=E:b.appendChild(E),Hi(E);else{if(!sn&&!gt&&!It&&S.indexOf("<")===-1)return re&&xr?on(S):S;if(b=Ka(S),!b)return sn?null:xr?Be:""}b&&Ii&&bt(b.firstChild);let Z=G?S:b;try{let Ce=Za(Z);for(;R=Ce.nextNode();)Qa(R,Z),nl(R),un(R.content)&&kr(R.content)}catch(Ce){throw G&&(Sr(S),In(e.removed,Ne=>{Ne.element&&Un(Ne.element)})),Ce}if(G)return In(e.removed,Ce=>{Ce.element&&Un(Ce.element)}),gt&&Ui(S),S;if(sn){if(gt&&Ui(b),yr)for(L=Qu.call(b.ownerDocument);b.firstChild;)L.appendChild(b.firstChild);else L=b;return(se.shadowroot||se.shadowrootmode)&&(L=td.call(r,L,!0)),L}let ce=It?b.outerHTML:b.innerHTML;return It&&ie["!doctype"]&&b.ownerDocument&&b.ownerDocument.doctype&&b.ownerDocument.doctype.name&&be(gg,b.ownerDocument.doctype.name)&&(ce="<!DOCTYPE "+b.ownerDocument.doctype.name+`>
|
|
13
|
-
`+ce),
|
|
14
|
-
]`).replace("lheading",
|
|
8
|
+
Error: ${x}`)}}return f()}case v.MESSAGES_SNAPSHOT:{let h=await K(r,s,a,(p,g,x)=>p.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{messages:p}=m,g=new Map(p.map(C=>[C.id,C])),x=p.some(C=>C.role==="reasoning"),_=C=>C.role==="activity"||C.role==="reasoning"&&!x;s=s.filter(C=>_(C)||g.has(C.id)).map(C=>_(C)?C:g.get(C.id));let S=new Set(s.map(C=>C.id));for(let C of p)S.has(C.id)||s.push(C);u({messages:s})}return f()}case v.ACTIVITY_SNAPSHOT:{let h=m,p=s.findIndex(C=>C.id===h.messageId),g=p>=0?s[p]:void 0,x=g?.role==="activity"?g:void 0,_=h.replace??!0,S=await K(r,s,a,(C,H,U)=>C.onActivitySnapshotEvent?.({event:h,messages:H,state:U,agent:n,input:t,activityMessage:x,existingMessage:g}));if(u(S),S.stopPropagation!==!0){let C={id:h.messageId,role:"activity",activityType:h.activityType,content:q(h.content)},H;p===-1?(s.push(C),H=C):x?_&&(s[p]={...x,activityType:h.activityType,content:q(h.content)}):_&&(s[p]=C,H=C),u({messages:s}),H&&await Promise.all(r.map(U=>U.onNewMessage?.({message:H,messages:s,state:a,agent:n,input:t})))}return f()}case v.ACTIVITY_DELTA:{let h=m,p=s.findIndex(S=>S.id===h.messageId);if(p===-1)return f();let g=s[p];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${h.messageId}' is not an activity message`),f();let x=g,_=await K(r,s,a,(S,C,H)=>S.onActivityDeltaEvent?.({event:h,messages:C,state:H,agent:n,input:t,activityMessage:x}));if(u(_),_.stopPropagation!==!0)try{let S=q(x.content??{}),C=Zr.applyPatch(S,h.patch??[],!0,!1).newDocument;s[p]={...x,content:q(C),activityType:h.activityType},u({messages:s})}catch(S){let C=S instanceof Error?S.message:String(S);console.warn(`Failed to apply activity patch for '${h.messageId}': ${C}`)}return f()}case v.RAW:return u(await K(r,s,a,(h,p,g)=>h.onRawEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.CUSTOM:return u(await K(r,s,a,(h,p,g)=>h.onCustomEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.RUN_STARTED:{let h=await K(r,s,a,(p,g,x)=>p.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let p=m;if(p.input?.messages){for(let g of p.input.messages)s.find(x=>x.id===g.id)||s.push(g);u({messages:s})}}return f()}case v.RUN_FINISHED:{let h=m,p=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,_,S)=>x.onRunFinishedEvent?.({...p,messages:_,state:S,agent:n,input:t}));return u(g),g.stopPropagation!==!0&&(n.pendingInterrupts=p.outcome==="interrupt"?[...p.interrupts]:[]),f()}case v.RUN_ERROR:return u(await K(r,s,a,(h,p,g)=>h.onRunErrorEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.STEP_STARTED:return u(await K(r,s,a,(h,p,g)=>h.onStepStartedEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.STEP_FINISHED:return u(await K(r,s,a,(h,p,g)=>h.onStepFinishedEvent?.({event:m,messages:p,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 u(await K(r,s,a,(h,p,g)=>h.onReasoningStartEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.REASONING_MESSAGE_START:{let h=await K(r,s,a,(p,g,x)=>p.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(u(h),h.stopPropagation!==!0){let{messageId:p}=m;if(!s.find(g=>g.id===p)){let g={id:p,role:"reasoning",content:""};s.push(g),u({messages:s})}}return f()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:h,delta:p}=m,g=s.find(_=>_.id===h);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${h}'`),f();let x=await K(r,s,a,(_,S,C)=>_.onReasoningMessageContentEvent?.({event:m,messages:S,state:C,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return u(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${p}`,u({messages:s})),f()}case v.REASONING_MESSAGE_END:{let{messageId:h}=m,p=s.find(g=>g.id===h);return p?(u(await K(r,s,a,(g,x,_)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:_,agent:n,input:t,reasoningMessageBuffer:typeof p.content=="string"?p.content:""}))),await Promise.all(r.map(g=>{g.onNewMessage?.({message:p,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 u(await K(r,s,a,(h,p,g)=>h.onReasoningEndEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),f();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:h,entityId:p,encryptedValue:g}=m,x=await K(r,s,a,(_,S,C)=>_.onReasoningEncryptedValueEvent?.({event:m,messages:S,state:C,agent:n,input:t}));if(u(x),x.stopPropagation!==!0){let _=!1;if(h==="tool-call"){for(let S of s)if(S.role==="assistant"&&S.toolCalls){let C=S.toolCalls.find(H=>H.id===p);if(C){C.encryptedValue=g,_=!0;break}}}else{let S=s.find(C=>C.id===p);S?.role!=="activity"&&S&&(S.encryptedValue=g,_=!0)}_&&(l.messages=s)}return f()}}return m.type,f()}),Ps(),r.length>0?Ds({}):m=>m)},ea=t=>e=>{let n=or(t),r=new Map,o=new Map,i=!1,s=!1,a=!1,l=new Map,u=!1,f=!1,m=!1,y=()=>{r.clear(),o.clear(),l.clear(),u=!1,f=!1,i=!1,s=!1,m=!0};return e.pipe(Me(h=>{let p=h.type;if(n?.event("VERIFY","Event:",h,{type:h.type}),s)return ne(()=>new ee(`Cannot send event type '${p}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(i&&p!==v.RUN_ERROR&&p!==v.RUN_STARTED)return ne(()=>new ee(`Cannot send event type '${p}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(a){if(p===v.RUN_STARTED){if(m&&!i)return ne(()=>new ee("Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run."));i&&y()}}else if(a=!0,p!==v.RUN_STARTED&&p!==v.RUN_ERROR)return ne(()=>new ee("First event must be 'RUN_STARTED'"));switch(p){case v.TEXT_MESSAGE_START:{let g=h.messageId;return r.has(g)?ne(()=>new ee(`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),ue(h))}case v.TEXT_MESSAGE_CONTENT:{let g=h.messageId;return r.has(g)?ue(h):ne(()=>new ee(`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),ue(h)):ne(()=>new ee(`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 o.has(g)?ne(()=>new ee(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${g}' is already in progress. Complete it with 'TOOL_CALL_END' first.`)):(o.set(g,!0),ue(h))}case v.TOOL_CALL_ARGS:{let g=h.toolCallId;return o.has(g)?ue(h):ne(()=>new ee(`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 o.has(g)?(o.delete(g),ue(h)):ne(()=>new ee(`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)?ne(()=>new ee(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),ue(h))}case v.STEP_FINISHED:{let g=h.stepName;return l.has(g)?(l.delete(g),ue(h)):ne(()=>new ee(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,ue(h);case v.RUN_FINISHED:if(l.size>0){let g=Array.from(l.keys()).join(", ");return ne(()=>new ee(`Cannot send 'RUN_FINISHED' while steps are still active: ${g}`))}if(r.size>0){let g=Array.from(r.keys()).join(", ");return ne(()=>new ee(`Cannot send 'RUN_FINISHED' while text messages are still active: ${g}`))}if(o.size>0){let g=Array.from(o.keys()).join(", ");return ne(()=>new ee(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${g}`))}return i=!0,ue(h);case v.RUN_ERROR:return s=!0,ue(h);case v.CUSTOM:return ue(h);case v.THINKING_TEXT_MESSAGE_START:return u?f?ne(()=>new ee("Cannot send 'THINKING_TEXT_MESSAGE_START' event: A thinking message is already in progress. Complete it with 'THINKING_TEXT_MESSAGE_END' first.")):(f=!0,ue(h)):ne(()=>new ee("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?ue(h):ne(()=>new ee("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,ue(h)):ne(()=>new ee("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 u?ne(()=>new ee("Cannot send 'THINKING_START' event: A thinking step is already in progress. End it with 'THINKING_END' first.")):(u=!0,ue(h));case v.THINKING_END:return u?(u=!1,ue(h)):ne(()=>new ee("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return ue(h)}}))},en=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),fm=t=>Eo(()=>Zt(t())).pipe(Us(e=>{if(!e.ok){let o=e.headers.get("content-type")||"";return Zt(e.text()).pipe(Me(i=>{let s=i;if(o.includes("application/json"))try{s=JSON.parse(i)}catch{}let a=Error(`HTTP ${e.status}: ${typeof s=="string"?s:JSON.stringify(s)}`);return a.status=e.status,a.payload=s,ne(()=>a)}))}let n={type:en.HEADERS,status:e.status,headers:e.headers},r=e.body?.getReader();return r?new te(o=>(o.next(n),(async()=>{try{for(;;){let{done:i,value:s}=await r.read();if(i)break;let a={type:en.DATA,data:s};o.next(a)}o.complete()}catch(i){o.error(i)}})(),()=>{r.cancel().catch(i=>{if(i?.name!=="AbortError")throw i})})):ne(()=>Error("Failed to getReader() from response"))})),hm=(t,e)=>{let n=or(e),r=new st,o=new TextDecoder("utf-8",{fatal:!1}),i="";t.subscribe({next:a=>{if(a.type!==en.HEADERS&&a.type===en.DATA&&a.data){let l=o.decode(a.data,{stream:!0});i+=l;let u=i.split(/\n\n/);i=u.pop()||"";for(let f of u)s(f)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
|
|
9
|
+
`),u=[];for(let f of l)f.startsWith("data:")&&u.push(f.slice(5).replace(/^ /,""));if(u.length>0)try{let f=u.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()},mm=t=>{let e=new st,n=new Uint8Array;t.subscribe({next:o=>{if(o.type!==en.HEADERS&&o.type===en.DATA&&o.data){let i=new Uint8Array(n.length+o.data.length);i.set(n,0),i.set(o.data,n.length),n=i,r()}},error:o=>e.error(o),complete:()=>{if(n.length>0)try{r()}catch{console.warn("Incomplete or invalid protocol buffer data at stream end")}e.complete()}});function r(){for(;n.length>=4;){let o=4+new DataView(n.buffer,n.byteOffset,4).getUint32(0,!1);if(n.length<o)break;try{let i=n.slice(4,o),s=Bc(i);e.next(s),n=n.slice(o)}catch(i){let s=i instanceof Error?i.message:String(i);e.error(Error(`Failed to decode protocol buffer message: ${s}`));return}}}return e.asObservable()},gm=(t,e)=>{let n=or(e),r=new st,o=new io,i=!1;return t.subscribe({next:s=>{if(o.next(s),s.type===en.HEADERS&&!i){i=!0;let a=s.headers.get("content-type");n?.lifecycle("HTTP","Stream format detected:",{contentType:a,parser:a===Ks?"protobuf":"sse"}),a===Ks?mm(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):hm(o,n).subscribe({next:l=>{try{let u=Br.parse(l);n?.event("HTTP","Event validated:",u,{type:u.type,valid:!0}),r.next(u)}catch(u){n?.event("HTTP","Event invalid:",{json:l,error:String(u)}),r.error(u)}},error:l=>{if(l?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else i||r.error(Error("No headers event received before data events"))},error:s=>{o.error(s),r.error(s)},complete:()=>{o.complete()}}),r.asObservable()},Q=c.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),vm=c.enum(["LangGraphInterruptEvent","PredictState","Exit"]),bm=c.object({type:c.literal(Q.enum.TextMessageStart),messageId:c.string(),parentMessageId:c.string().optional(),role:c.string().optional()}),ym=c.object({type:c.literal(Q.enum.TextMessageContent),messageId:c.string(),content:c.string()}),xm=c.object({type:c.literal(Q.enum.TextMessageEnd),messageId:c.string()}),Em=c.object({type:c.literal(Q.enum.ActionExecutionStart),actionExecutionId:c.string(),actionName:c.string(),parentMessageId:c.string().optional()}),Tm=c.object({type:c.literal(Q.enum.ActionExecutionArgs),actionExecutionId:c.string(),args:c.string()}),Sm=c.object({type:c.literal(Q.enum.ActionExecutionEnd),actionExecutionId:c.string()}),wm=c.object({type:c.literal(Q.enum.ActionExecutionResult),actionName:c.string(),actionExecutionId:c.string(),result:c.string()}),_m=c.object({type:c.literal(Q.enum.AgentStateMessage),threadId:c.string(),agentName:c.string(),nodeName:c.string(),runId:c.string(),active:c.boolean(),role:c.string(),state:c.string(),running:c.boolean()}),Am=c.object({type:c.literal(Q.enum.MetaEvent),name:vm,value:c.any()}),km=c.object({type:c.literal(Q.enum.RunError),message:c.string(),code:c.string().optional()});c.discriminatedUnion("type",[bm,ym,xm,Em,Tm,Sm,wm,_m,Am,km]),c.object({id:c.string(),role:c.string(),content:c.string(),parentMessageId:c.string().optional()}),c.object({id:c.string(),name:c.string(),arguments:c.any(),parentMessageId:c.string().optional()}),c.object({id:c.string(),result:c.any(),actionExecutionId:c.string(),actionName:c.string()});var Im=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
|
+
`)},Cm=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,u=null,f=[],m={},y=h=>{typeof h=="object"&&h&&("messages"in h&&delete h.messages,o=h)};return r.pipe(Me(h=>{switch(h.type){case v.TEXT_MESSAGE_START:{let p=h;return[{type:Q.enum.TextMessageStart,messageId:p.messageId,role:p.role}]}case v.TEXT_MESSAGE_CONTENT:{let p=h;return[{type:Q.enum.TextMessageContent,messageId:p.messageId,content:p.delta}]}case v.TEXT_MESSAGE_END:{let p=h;return[{type:Q.enum.TextMessageEnd,messageId:p.messageId}]}case v.TOOL_CALL_START:{let p=h;return f.push({id:p.toolCallId,type:"function",function:{name:p.toolCallName,arguments:""}}),s=!0,m[p.toolCallId]=p.toolCallName,[{type:Q.enum.ActionExecutionStart,actionExecutionId:p.toolCallId,actionName:p.toolCallName,parentMessageId:p.parentMessageId}]}case v.TOOL_CALL_ARGS:{let p=h,g=f.find(_=>_.id===p.toolCallId);if(!g)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${p.toolCallId}'`),[];g.function.arguments+=p.delta;let x=!1;if(u){let _=u.find(S=>S.tool==g.function.name);if(_)try{let S=JSON.parse(wo(g.function.arguments));_.tool_argument&&_.tool_argument in S?(y({...o,[_.state_key]:S[_.tool_argument]}),x=!0):_.tool_argument||(y({...o,[_.state_key]:S}),x=!0)}catch{}}return[{type:Q.enum.ActionExecutionArgs,actionExecutionId:p.toolCallId,args:p.delta},...x?[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]:[]]}case v.TOOL_CALL_END:{let p=h;return[{type:Q.enum.ActionExecutionEnd,actionExecutionId:p.toolCallId}]}case v.TOOL_CALL_RESULT:{let p=h;return[{type:Q.enum.ActionExecutionResult,actionExecutionId:p.toolCallId,result:p.content,actionName:m[p.toolCallId]||"unknown"}]}case v.RAW:return[];case v.CUSTOM:{let p=h;switch(p.name){case"Exit":i=!1;break;case"PredictState":u=p.value;break}return[{type:Q.enum.MetaEvent,name:p.name,value:p.value}]}case v.STATE_SNAPSHOT:return y(h.snapshot),[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}];case v.STATE_DELTA:{let p=h,g=Zr.applyPatch(o,p.delta,!0,!1);return g?(y(g.newDocument),[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:s}]):[]}case v.MESSAGES_SNAPSHOT:return l=h.messages,[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:l}:{}}),active:!0}];case v.RUN_STARTED:return[];case v.RUN_FINISHED:return l&&(o.messages=l),Object.keys(o).length===0?[]:[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify({...o,...l?{messages:Nm(l)}:{}}),active:!1}];case v.RUN_ERROR:{let p=h;return[{type:Q.enum.RunError,message:p.message,code:p.code}]}case v.STEP_STARTED:return a=h.stepName,f=[],u=null,[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!0}];case v.STEP_FINISHED:return f=[],u=null,[{type:Q.enum.AgentStateMessage,threadId:t,agentName:n,nodeName:a,runId:e,running:i,role:"assistant",state:JSON.stringify(o),active:!1}];default:return[]}}))};function Nm(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=Im(n.content);if(r){let o={id:n.id,role:n.role,content:r};e.push(o)}if(n.role==="assistant"&&n.toolCalls&&n.toolCalls.length>0)for(let o of n.toolCalls){let i={id:o.id,name:o.function.name,arguments:JSON.parse(o.function.arguments),parentMessageId:n.id};e.push(i)}}else if(n.role==="tool"){let r="unknown";for(let i of t)if(i.role==="assistant"&&i.toolCalls?.length){for(let s of i.toolCalls)if(s.id===n.toolCallId){r=s.function.name;break}}let o={id:n.id,result:n.content,actionExecutionId:n.toolCallId,actionName:r};e.push(o)}return e}var si=t=>e=>{let n=or(t),r,o,i,s,a=()=>{if(!r||s!=="text")throw Error("No text message to close");let m={type:v.TEXT_MESSAGE_END,messageId:r.messageId};return s=void 0,r=void 0,n?.event("TRANSFORM","TEXT_MESSAGE_END",m,{messageId:m.messageId}),m},l=()=>{if(!o||s!=="tool")throw Error("No tool call to close");let m={type:v.TOOL_CALL_END,toolCallId:o.toolCallId};return s=void 0,o=void 0,n?.event("TRANSFORM","TOOL_CALL_END",m,{toolCallId:m.toolCallId}),m},u=()=>{if(!i||s!=="reasoning")throw Error("No reasoning message to close");let m={type:v.REASONING_MESSAGE_END,messageId:i.messageId};return s=void 0,i=void 0,n?.event("TRANSFORM","REASONING_MESSAGE_END",m,{messageId:m.messageId}),m},f=()=>s==="text"?[a()]:s==="tool"?[l()]:s==="reasoning"?[u()]:[];return e.pipe(Me(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 y=m,h=[];if((s!=="text"||y.messageId!==void 0&&y.messageId!==r?.messageId)&&h.push(...f()),s!=="text"){if(y.messageId===void 0)throw Error("First TEXT_MESSAGE_CHUNK must have a messageId");r={messageId:y.messageId,name:y.name},s="text";let S={type:v.TEXT_MESSAGE_START,messageId:y.messageId,role:y.role||"assistant",...y.name!==void 0&&{name:y.name}};h.push(S),n?.event("TRANSFORM","TEXT_MESSAGE_START",S,{messageId:y.messageId})}if(y.delta!==void 0){let S={type:v.TEXT_MESSAGE_CONTENT,messageId:r.messageId,delta:y.delta};h.push(S),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",S,{messageId:r.messageId})}return h;case v.TOOL_CALL_CHUNK:let p=m,g=[];if((s!=="tool"||p.toolCallId!==void 0&&p.toolCallId!==o?.toolCallId)&&g.push(...f()),s!=="tool"){if(p.toolCallId===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallId");if(p.toolCallName===void 0)throw Error("First TOOL_CALL_CHUNK must have a toolCallName");o={toolCallId:p.toolCallId,toolCallName:p.toolCallName,parentMessageId:p.parentMessageId},s="tool";let S={type:v.TOOL_CALL_START,toolCallId:p.toolCallId,toolCallName:p.toolCallName,parentMessageId:p.parentMessageId};g.push(S),n?.event("TRANSFORM","TOOL_CALL_START",S,{toolCallId:p.toolCallId,toolCallName:p.toolCallName})}if(p.delta!==void 0){let S={type:v.TOOL_CALL_ARGS,toolCallId:o.toolCallId,delta:p.delta};g.push(S),n?.event("TRANSFORM","TOOL_CALL_ARGS",S,{toolCallId:o.toolCallId})}return g;case v.REASONING_MESSAGE_CHUNK:let x=m,_=[];if((s!=="reasoning"||x.messageId&&x.messageId!==i?.messageId)&&_.push(...f()),s!=="reasoning"){if(x.messageId===void 0)throw Error("First REASONING_MESSAGE_CHUNK must have a messageId");i={messageId:x.messageId},s="reasoning";let S={type:v.REASONING_MESSAGE_START,messageId:x.messageId};_.push(S),n?.event("TRANSFORM","REASONING_MESSAGE_START",S,{messageId:x.messageId})}if(x.delta!==void 0){let S={type:v.REASONING_MESSAGE_CONTENT,messageId:i.messageId,delta:x.delta};_.push(S),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",S,{messageId:i.messageId})}return _}return m.type,[]}),Qt(()=>{f()}))};function Rm(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function eu(t,e){let n=new Set(t.map(s=>s.id)),r=new Set(Object.keys(e)),o=[...n].filter(s=>!r.has(s));if(o.length>0)throw Error(`buildResumeArray: missing responses for open interrupts: ${o.join(", ")}`);let i=[...r].filter(s=>!n.has(s));if(i.length>0)throw Error(`buildResumeArray: responses reference unknown interrupt ids: ${i.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 ai=class{runNext(t,e){return e.run(t).pipe(si(!1))}runNextWithState(t,e){let n=q(t.messages||[]),r=q(t.state||{}),o=new io;return Qc(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(To(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:q(n),state:q(r)})))}},Om=class extends ai{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function Mm(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 Lm=class extends ai{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(Mm)};return this.runNext(o,e)}},Xc="THINKING_START",Yc="THINKING_END",Kc="THINKING_TEXT_MESSAGE_START",Zc="THINKING_TEXT_MESSAGE_CONTENT",Jc="THINKING_TEXT_MESSAGE_END",Pm=class extends ai{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(Jt(n=>this.transformEvent(n)))}transformEvent(t){switch(t.type){case Xc:{this.currentReasoningId=De();let{title:e,...n}=t;return this.warnAboutTransformation(Xc,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case Kc:return this.currentMessageId=De(),this.warnAboutTransformation(Kc,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case Zc:{let{delta:e,...n}=t;return this.warnAboutTransformation(Zc,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??De(),delta:e}}case Jc:{let e=this.currentMessageId??De();return this.warnAboutTransformation(Jc,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case Yc:{let e=this.currentReasoningId??De();return this.warnAboutTransformation(Yc,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function Dm(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function Um(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function Hm(t){let e=Dm(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 Gm(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>Um(r)?Hm(r):r);return{...t,content:n}}var Fm=class extends ai{run(t,e){let n={...t,messages:t.messages.map(Gm)};return this.runNext(n,e)}},$m="0.0.57",zm=class{get maxVersion(){return $m}get debug(){return this._debug}set debug(t){this._debug=ii(t),this._debugLogger=Qs(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?Qs(ii(!0)):void 0:this._debugLogger=t}constructor({agentId:t,description:e,threadId:n,initialMessages:r,initialState:o,debug:i}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.agentId=t,this.description=e??"",this.threadId=n??xt(),this.messages=q(r??[]),this.state=q(o??{}),this._debug=ii(i),this._debugLogger=Qs(this._debug),rr(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new Lm),rr(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new Pm),rr(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new Fm)}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 Om(n):n);return this.middlewares.push(...e),this}async runAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??xt();let n=this.prepareRunAgentInput(t);this.debugLogger?.lifecycle("LIFECYCLE","Run started:",{agentId:this.agentId,threadId:this.threadId});let r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new st;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await xo(oo(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,u)=>({run:f=>u.run(f,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),si(this.debugLogger),ea(this.debugLogger),l=>l.pipe(So(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),er(l=>(this.debugLogger?.lifecycle("LIFECYCLE","Run errored:",{agentId:this.agentId,error:l instanceof Error?l.message:String(l)}),this.isRunning=!1,this.onError(n,l,i))),Qt(()=>{this.debugLogger?.lifecycle("LIFECYCLE","Run finished:",{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(ue(null)));let a=q(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}connect(t){throw new Ts}async connectAgent(t,e){try{this.isRunning=!0,this.agentId=this.agentId??xt();let n=this.prepareRunAgentInput(t),r,o=new Set(this.messages.map(l=>l.id)),i=[{onRunFinishedEvent:l=>{l.outcome==="success"&&(r=l.result)}},...this.subscribers,e??{}];await this.onInitialize(n,i),this.activeRunDetach$=new st;let s;this.activeRunCompletionPromise=new Promise(l=>{s=l}),await xo(oo(()=>Eo(()=>this.connect(n)),si(this.debugLogger),ea(this.debugLogger),l=>l.pipe(So(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),er(l=>(this.isRunning=!1,l instanceof Ts?so:this.onError(n,l,i))),Qt(()=>{this.isRunning=!1,this.onFinalize(n,i),s?.(),s=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(ue(null)),{defaultValue:void 0});let a=q(this.messages).filter(l=>!o.has(l.id));return{result:r,newMessages:a}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let t=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await t}apply(t,e,n){return Qc(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(Hs(r=>{r.messages&&(this.messages=r.messages,n.forEach(o=>{o.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),r.state&&(this.state=r.state,n.forEach(o=>{o.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))}))}prepareRunAgentInput(t){let e=q(this.messages).filter(n=>n.role!=="activity");return{threadId:this.threadId,runId:t?.runId||xt(),tools:q(t?.tools??[]),context:q(t?.context??[]),forwardedProps:q(t?.forwardedProps??{}),state:q(this.state),messages:e,...t?.resume===void 0?{}:{resume:q(t.resume)}}}async onInitialize(t,e){if(this.pendingInterrupts.length>0){let r=new Set((t.resume??[]).map(i=>i.interruptId)),o=this.pendingInterrupts.map(i=>i.id).filter(i=>!r.has(i));if(o.length>0)throw new ee(`Thread has ${o.length} pending interrupt(s) not addressed by resume: ${o.join(", ")}`);for(let i of this.pendingInterrupts)if(Rm(i))throw new ee(`Interrupt ${i.id} expired at ${i.expiresAt}`)}let n=await K(e,this.messages,this.state,(r,o,i)=>r.onRunInitialized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages&&(this.messages=n.messages,t.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state&&(this.state=n.state,t.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}onError(t,e,n){return Zt(K(n,this.messages,this.state,(r,o,i)=>r.onRunFailed?.({error:e,messages:o,state:i,agent:this,input:t}))).pipe(Jt(r=>{let o=r;if((o.messages!==void 0||o.state!==void 0)&&(o.messages!==void 0&&(this.messages=o.messages,n.forEach(i=>{i.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),o.state!==void 0&&(this.state=o.state,n.forEach(i=>{i.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})}))),o.stopPropagation!==!0){let i=String(e);if(!(e.name==="AbortError"||e.message==="Fetch is aborted"||e.message==="signal is aborted without reason"||e.message==="component unmounted"||i==="component unmounted"))throw console.error("Agent execution failed:",e),e}return{}}))}async onFinalize(t,e){let n=await K(e,this.messages,this.state,(r,o,i)=>r.onRunFinalized?.({messages:o,state:i,agent:this,input:t}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,e.forEach(r=>{r.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:t})})),n.state!==void 0&&(this.state=n.state,e.forEach(r=>{r.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:t})})))}clone(){let t=Object.create(Object.getPrototypeOf(this));return t.agentId=this.agentId,t.description=this.description,t.threadId=this.threadId,t.messages=q(this.messages),t.state=q(this.state),t._debug=this._debug,t._debugLogger=this._debugLogger,t.isRunning=this.isRunning,t.subscribers=[...this.subscribers],t.middlewares=[...this.middlewares],t.pendingInterrupts=q(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=q(t),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(t){this.state=q(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??xt();let e=this.prepareRunAgentInput(t);return(this.middlewares.length===0?this.run(e):this.middlewares.reduceRight((n,r)=>({run:o=>r.run(o,n),get messages(){return n.messages},get state(){return n.state}}),this).run(e)).pipe(si(this.debugLogger),ea(this.debugLogger),Cm(this.threadId,e.runId,this.agentId),n=>n.pipe(Jt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},tu=class extends zm{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=q(t.headers??{}),this.fetch=t.fetch??((e,n)=>fetch(e,n))}run(t){return gm(fm(()=>this.fetch(this.url,this.requestInit(t))),this.debugLogger)}clone(){let t=super.clone();t.url=this.url,t.headers=q(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 li=class{element;#n;#e;#t=[];constructor(e){this.#n=e,this.#e=e.strings??ae,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:De(),file:e,status:He.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#o(e);if(r!==null){n.status=He.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===He.UPLOADING)}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===He.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()}#o(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",Pr(this.#n.maxBytes)):Bm(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#o(e.file);if(n!==null){e.status=He.ERROR,e.error=n,this.#s(),this.#n.onChange?.();return}e.status=He.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#s(),this.#n.upload(e.file,o=>{e.progress=o,this.#s()},r.signal).then(o=>{e.status=He.READY,e.ref=o}).catch(o=>{e.status=He.ERROR,e.error=o instanceof Error?o.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.#i(e))}#i(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=ms(e.file.type),r.setAttribute("aria-hidden","true");let o=document.createElement("span");o.className="attachment-chip-name",o.setAttribute("part","attachment-chip-name"),o.textContent=e.file.name,o.title=e.file.name;let i=document.createElement("span");if(i.className="attachment-chip-size",i.setAttribute("part","attachment-chip-size"),i.textContent=e.status===He.ERROR?e.error:Pr(e.file.size),n.append(r,o,i),e.status===He.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===He.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 Bm(t,e){let n=t.split(",").map(i=>i.trim().toLowerCase()).filter(i=>i!=="");if(n.length===0)return!0;let r=e.type.toLowerCase(),o=e.name.toLowerCase();return n.some(i=>i.startsWith(".")?o.endsWith(i):i.endsWith("/*")?r.startsWith(i.slice(0,-1)):r===i)}function ci(t,e=Date.now(),n=ae){if(!Number.isFinite(t))return n.justNow;let r=Math.round((e-t)/1e3);if(r<60)return n.justNow;let o=Math.round(r/60);if(o<60)return n.minutesAgo.replace("{n}",String(o));let i=Math.round(o/60);if(i<24)return n.hoursAgo.replace("{n}",String(i));let s=Math.round(i/24);return s<7?n.daysAgo.replace("{n}",String(s)):n.weeksAgo.replace("{n}",String(Math.round(s/7)))}var ir=class{element;#n;#e;#t;#o;#r=[];constructor(e,n=ae){this.#n=e,this.#o=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",o=>{o.key==="Escape"&&(o.stopPropagation(),this.close())})}setRuns(e){this.#r=e,this.#a()}setStrings(e){this.#o=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.#o.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:ci(Date.parse(e.started_at),Date.now(),this.#o),r.title=e.run_id,n.append(r),e.parent_run_id!==null){let o=document.createElement("span");o.className="checkpoint-branch",o.setAttribute("part","checkpoint-branch"),o.textContent=this.#o.forkedRun,o.title=e.parent_run_id,n.append(o)}return n.append(this.#i(e.run_id,"resume",this.#o.resumeRun),this.#i(e.run_id,"fork",this.#o.forkRun)),n}#i(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`checkpoint-action checkpoint-${n}`,o.setAttribute("part",`checkpoint-action checkpoint-${n}`),o.textContent=r,o.addEventListener("click",()=>{this.close(),this.#n(e,n)}),o}};function nu(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 ra(t,e,n={}){let r=n.strings??ae;return new Promise(o=>{let i=document.createElement("div");i.className="confirm",i.setAttribute("part","confirm"),i.setAttribute("data-tool-name",e.toolName),i.setAttribute("role","group"),i.setAttribute("aria-label",r.confirmAction);let s=document.createElement("div");s.className="confirm-body",s.setAttribute("part","confirm-body"),s.textContent=e.message??r.confirmRun.replace("{tool}",e.toolName);let a=document.createElement("pre");a.className="confirm-args",a.setAttribute("part","confirm-args"),a.textContent=JSON.stringify(e.args,null,2);let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let u=nu("cancel",r.cancel),f=nu("confirm",r.confirm),m=!1,y=h=>{m||(m=!0,u.disabled=!0,f.disabled=!0,i.setAttribute("data-resolved",h?"confirmed":"declined"),o(h))};if(u.addEventListener("click",()=>y(!1)),f.addEventListener("click",()=>y(!0)),n.signal?.addEventListener("abort",()=>y(!1),{once:!0}),l.append(u,f),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){y(!1);return}f.focus()})}function oa(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function Vm(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function ia(t,e,n={}){let r=n.strings??ae,o=e.options??[],i=o.length>0,s=!i||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 u=document.createElement("div");u.className="question-body",u.setAttribute("part","question-body"),u.textContent=e.question;let f=document.createElement("div");f.className="question-options",f.setAttribute("part","question-options");let m=`q-${o.length}-${e.question.length}`,y=[];for(let U of o){let Y=document.createElement("label");Y.className="question-choice",Y.setAttribute("part","question-choice");let re=document.createElement("input");re.type="radio",re.name=m,re.value=U,re.setAttribute("part","question-radio");let Be=document.createElement("span");Be.setAttribute("part","question-choice-text"),Be.textContent=U,Y.append(re,Be),f.appendChild(Y),y.push(re)}let h=null,p=null;if(s){if(p=Vm(r.answerPlaceholder),i){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice"),h=document.createElement("input"),h.type="radio",h.name=m,h.value="",h.setAttribute("part","question-radio");let Y=document.createElement("span");Y.setAttribute("part","question-choice-text"),Y.textContent=r.otherOption,U.append(h,Y),f.appendChild(U),p.disabled=!0}f.appendChild(p)}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 _=!1,S=()=>{let U=y.find(Y=>Y.checked);if(U!==void 0)return U.value;if(p!==null&&(h===null||h.checked)){let Y=p.value.trim();return Y===""?null:Y}return null},C=()=>{p!==null&&h!==null&&(p.disabled=!h.checked),x.disabled=S()===null},H=U=>{if(!_){_=!0,x.disabled=!0;for(let Y of y)Y.disabled=!0;h!==null&&(h.disabled=!0),p!==null&&(p.disabled=!0),l.setAttribute("data-resolved",U===""?"cancelled":"answered"),a(U)}};for(let U of[...y,...h!==null?[h]:[]])U.addEventListener("change",C);if(p?.addEventListener("input",C),p?.addEventListener("keydown",U=>{if(U.key==="Enter"){U.preventDefault();let Y=S();Y!==null&&H(Y)}}),x.addEventListener("click",()=>{let U=S();U!==null&&H(U)}),n.signal?.addEventListener("abort",()=>H(""),{once:!0}),l.append(u,f,g),t.appendChild(l),n.signal?.aborted===!0){H("");return}C(),(i?y[0]:p)?.focus()})}function ru(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 jm(t){if(Array.isArray(t))return t}function qm(t,e){var n=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(n!=null){var r,o,i,s,a=[],l=!0,u=!1;try{if(i=(n=n.call(t)).next,e!==0)for(;!(l=(r=i.call(n)).done)&&(a.push(r.value),a.length!==e);l=!0);}catch(f){u=!0,o=f}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(u)throw o}}return a}}function Wm(){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 Xm(t,e){return jm(t)||qm(t,e)||Ym(t,e)||Wm()}function Ym(t,e){if(t){if(typeof t=="string")return ru(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)?ru(t,e):void 0}}var bu=Object.entries,ou=Object.setPrototypeOf,Km=Object.isFrozen,Zm=Object.getPrototypeOf,Jm=Object.getOwnPropertyDescriptor,Se=Object.freeze,we=Object.seal,Rn=Object.create,yu=typeof Reflect<"u"&&Reflect,da=yu.apply,pa=yu.construct;Se||(Se=function(e){return e});we||(we=function(e){return e});da||(da=function(e,n){for(var r=arguments.length,o=new Array(r>2?r-2:0),i=2;i<r;i++)o[i-2]=arguments[i];return e.apply(n,o)});pa||(pa=function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return new e(...r)});var Cn=me(Array.prototype.forEach),Qm=me(Array.prototype.lastIndexOf),iu=me(Array.prototype.pop),Nn=me(Array.prototype.push),eg=me(Array.prototype.splice),kt=Array.isArray,lr=me(String.prototype.toLowerCase),sa=me(String.prototype.toString),su=me(String.prototype.match),sr=me(String.prototype.replace),au=me(String.prototype.indexOf),tg=me(String.prototype.trim),ng=me(Number.prototype.toString),rg=me(Boolean.prototype.toString),lu=typeof BigInt>"u"?null:me(BigInt.prototype.toString),cu=typeof Symbol>"u"?null:me(Symbol.prototype.toString),ye=me(Object.prototype.hasOwnProperty),ar=me(Object.prototype.toString),be=me(RegExp.prototype.test),tn=og(TypeError);function me(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var n=arguments.length,r=new Array(n>1?n-1:0),o=1;o<n;o++)r[o-1]=arguments[o];return da(t,e,r)}}function og(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return pa(t,n)}}function W(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:lr;if(ou&&ou(t,null),!kt(e))return t;let r=e.length;for(;r--;){let o=e[r];if(typeof o=="string"){let i=n(o);i!==o&&(Km(e)||(e[r]=i),o=i)}t[o]=!0}return t}function ig(t){for(let e=0;e<t.length;e++)ye(t,e)||(t[e]=null);return t}function Ae(t){let e=Rn(null);for(let r of bu(t)){var n=Xm(r,2);let o=n[0],i=n[1];ye(t,o)&&(kt(i)?e[o]=ig(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ae(i):e[o]=i)}return e}function sg(t){switch(typeof t){case"string":return t;case"number":return ng(t);case"boolean":return rg(t);case"bigint":return lu?lu(t):"0";case"symbol":return cu?cu(t):"Symbol()";case"undefined":return ar(t);case"function":case"object":{if(t===null)return ar(t);let e=t,n=Ye(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:ar(r)}return ar(t)}default:return ar(t)}}function Ye(t,e){for(;t!==null;){let r=Jm(t,e);if(r){if(r.get)return me(r.get);if(typeof r.value=="function")return me(r.value)}t=Zm(t)}function n(){return null}return n}function ag(t){try{return be(t,""),!0}catch{return!1}}var uu=Se(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),aa=Se(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),la=Se(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),lg=Se(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),ca=Se(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),cg=Se(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),du=Se(["#text"]),pu=Se(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),ua=Se(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dominant-baseline","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-orientation","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"]),fu=Se(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ui=Se(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),ug=we(/{{[\w\W]*|^[\w\W]*}}/g),dg=we(/<%[\w\W]*|^[\w\W]*%>/g),pg=we(/\${[\w\W]*/g),fg=we(/^data-[\-\w.\u00B7-\uFFFF]+$/),hg=we(/^aria-[\-\w]+$/),hu=we(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),mg=we(/^(?:\w+script|data):/i),gg=we(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),vg=we(/^html$/i),bg=we(/^[a-z][.\w]*(-[.\w]+)+$/i),mu=we(/<[/\w!]/g),gu=we(/<[/\w]/g),yg=we(/<\/no(script|embed|frames)/i),xg=we(/\/>/i),Ue={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Eg=function(){return typeof window>"u"?null:window},Tg=function(e,n){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let r=null,o="data-tt-policy-suffix";n&&n.hasAttribute(o)&&(r=n.getAttribute(o));let i="dompurify"+(r?"#"+r:"");try{return e.createPolicy(i,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+i+" could not be created."),null}},vu=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},At=function(e,n,r,o){return ye(e,n)&&kt(e[n])?W(o.base?Ae(o.base):{},e[n],o.transform):r};function xu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Eg(),e=w=>xu(w);if(e.version="3.4.13",e.removed=[],!t||!t.document||t.document.nodeType!==Ue.document||!t.Element)return e.isSupported=!1,e;let n=t.document,r=n,o=r.currentScript;t.DocumentFragment;let i=t.HTMLTemplateElement,s=t.Node,a=t.Element,l=t.NodeFilter,u=t.NamedNodeMap;u===void 0&&(t.NamedNodeMap||t.MozNamedAttrMap),t.HTMLFormElement;let f=t.DOMParser,m=t.trustedTypes,y=a.prototype,h=Ye(y,"cloneNode"),p=Ye(y,"remove"),g=Ye(y,"nextSibling"),x=Ye(y,"childNodes"),_=Ye(y,"parentNode"),S=Ye(y,"shadowRoot"),C=Ye(y,"attributes"),H=s&&s.prototype?Ye(s.prototype,"nodeType"):null,U=s&&s.prototype?Ye(s.prototype,"nodeName"):null,Y=s&&s.prototype?Ye(s.prototype,"ownerDocument"):null;if(typeof i=="function"){let w=n.createElement("template");w.content&&w.content.ownerDocument&&(n=w.content.ownerDocument)}let re,Be="",wi,Ra=!1,Pn=0,Oa=function(){if(Pn>0)throw tn('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},sn=function(d){Oa(),Pn++;try{return re.createHTML(d)}finally{Pn--}},Ju=function(d){Oa(),Pn++;try{return re.createScriptURL(d)}finally{Pn--}},Qu=function(){return Ra||(wi=Tg(m,o),Ra=!0),wi},br=n,_i=br.implementation,Ma=br.createNodeIterator,ed=br.createDocumentFragment,td=br.getElementsByTagName,nd=r.importNode,oe=vu();e.isSupported=typeof bu=="function"&&typeof _=="function"&&_i&&_i.createHTMLDocument!==void 0;let rd=ug,od=dg,id=pg,sd=fg,ad=hg,ld=mg,La=gg,cd=bg,Pa=hu,ie=null,Ai=W({},[...uu,...aa,...la,...ca,...du]),se=null,ki=W({},[...pu,...ua,...fu,...ui]),de=Object.seal(Rn(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}})),Dn=null,Da=null,gt=Object.seal(Rn(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Ua=!0,Ii=!0,Ha=!1,Ga=!0,vt=!1,bt=!0,Ct=!1,Ci=!1,yr=null,xr=null,Ni=!1,an=!1,Er=!1,Tr=!1,Fa=!0,$a=!1,za="user-content-",Ri=!0,Sr=!1,ln={},Je=null,Oi=W({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]),Ba=null,Va=W({},["audio","video","img","source","image","track"]),Mi=null,ja=W({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),wr="http://www.w3.org/1998/Math/MathML",_r="http://www.w3.org/2000/svg",Qe="http://www.w3.org/1999/xhtml",cn=Qe,Li=!1,Pi=null,ud=W({},[wr,_r,Qe],sa),qa=Se(["mi","mo","mn","ms","mtext"]),Di=W({},qa),Wa=Se(["annotation-xml"]),Ui=W({},Wa),dd=W({},["title","style","font","a","script"]),Un=null,pd=["application/xhtml+xml","text/html"],fd="text/html",le=null,un=null,hd=n.createElement("form"),Xa=function(d){return d instanceof RegExp||d instanceof Function},Hi=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(un&&un===d)return;(!d||typeof d!="object")&&(d={}),d=Ae(d),Un=pd.indexOf(d.PARSER_MEDIA_TYPE)===-1?fd:d.PARSER_MEDIA_TYPE,le=Un==="application/xhtml+xml"?sa:lr,ie=At(d,"ALLOWED_TAGS",Ai,{transform:le}),se=At(d,"ALLOWED_ATTR",ki,{transform:le}),Pi=At(d,"ALLOWED_NAMESPACES",ud,{transform:sa}),Mi=At(d,"ADD_URI_SAFE_ATTR",ja,{transform:le,base:ja}),Ba=At(d,"ADD_DATA_URI_TAGS",Va,{transform:le,base:Va}),Je=At(d,"FORBID_CONTENTS",Oi,{transform:le}),Dn=At(d,"FORBID_TAGS",Ae({}),{transform:le}),Da=At(d,"FORBID_ATTR",Ae({}),{transform:le}),ln=ye(d,"USE_PROFILES")?d.USE_PROFILES&&typeof d.USE_PROFILES=="object"?Ae(d.USE_PROFILES):d.USE_PROFILES:!1,Ua=d.ALLOW_ARIA_ATTR!==!1,Ii=d.ALLOW_DATA_ATTR!==!1,Ha=d.ALLOW_UNKNOWN_PROTOCOLS||!1,Ga=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,vt=d.SAFE_FOR_TEMPLATES||!1,bt=d.SAFE_FOR_XML!==!1,Ct=d.WHOLE_DOCUMENT||!1,an=d.RETURN_DOM||!1,Er=d.RETURN_DOM_FRAGMENT||!1,Tr=d.RETURN_TRUSTED_TYPE||!1,Ni=d.FORCE_BODY||!1,Fa=d.SANITIZE_DOM!==!1,$a=d.SANITIZE_NAMED_PROPS||!1,Ri=d.KEEP_CONTENT!==!1,Sr=d.IN_PLACE||!1,Pa=ag(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:hu,cn=typeof d.NAMESPACE=="string"?d.NAMESPACE:Qe,Di=ye(d,"MATHML_TEXT_INTEGRATION_POINTS")&&d.MATHML_TEXT_INTEGRATION_POINTS&&typeof d.MATHML_TEXT_INTEGRATION_POINTS=="object"?Ae(d.MATHML_TEXT_INTEGRATION_POINTS):W({},qa),Ui=ye(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ae(d.HTML_INTEGRATION_POINTS):W({},Wa);let b=ye(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ae(d.CUSTOM_ELEMENT_HANDLING):Rn(null);if(de=Rn(null),ye(b,"tagNameCheck")&&Xa(b.tagNameCheck)&&(de.tagNameCheck=b.tagNameCheck),ye(b,"attributeNameCheck")&&Xa(b.attributeNameCheck)&&(de.attributeNameCheck=b.attributeNameCheck),ye(b,"allowCustomizedBuiltInElements")&&typeof b.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=b.allowCustomizedBuiltInElements),we(de),vt&&(Ii=!1),Er&&(an=!0),ln&&(ie=W({},du),se=Rn(null),ln.html===!0&&(W(ie,uu),W(se,pu)),ln.svg===!0&&(W(ie,aa),W(se,ua),W(se,ui)),ln.svgFilters===!0&&(W(ie,la),W(se,ua),W(se,ui)),ln.mathMl===!0&&(W(ie,ca),W(se,fu),W(se,ui))),gt.tagCheck=null,gt.attributeCheck=null,ye(d,"ADD_TAGS")&&(typeof d.ADD_TAGS=="function"?gt.tagCheck=d.ADD_TAGS:kt(d.ADD_TAGS)&&(ie===Ai&&(ie=Ae(ie)),W(ie,d.ADD_TAGS,le))),ye(d,"ADD_ATTR")&&(typeof d.ADD_ATTR=="function"?gt.attributeCheck=d.ADD_ATTR:kt(d.ADD_ATTR)&&(se===ki&&(se=Ae(se)),W(se,d.ADD_ATTR,le))),ye(d,"ADD_URI_SAFE_ATTR")&&kt(d.ADD_URI_SAFE_ATTR)&&W(Mi,d.ADD_URI_SAFE_ATTR,le),ye(d,"FORBID_CONTENTS")&&kt(d.FORBID_CONTENTS)&&(Je===Oi&&(Je=Ae(Je)),W(Je,d.FORBID_CONTENTS,le)),ye(d,"ADD_FORBID_CONTENTS")&&kt(d.ADD_FORBID_CONTENTS)&&(Je===Oi&&(Je=Ae(Je)),W(Je,d.ADD_FORBID_CONTENTS,le)),Ri&&(ie["#text"]=!0),Ct&&W(ie,["html","head","body"]),ie.table&&(W(ie,["tbody"]),delete Dn.tbody),d.TRUSTED_TYPES_POLICY){if(typeof d.TRUSTED_TYPES_POLICY.createHTML!="function")throw tn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof d.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw tn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');let E=re;re=d.TRUSTED_TYPES_POLICY;try{Be=sn("")}catch(R){throw re=E,R}}else d.TRUSTED_TYPES_POLICY===null?(re=void 0,Be=""):(re===void 0&&(re=Qu()),re&&typeof Be=="string"&&(Be=sn("")));Se&&Se(d),un=d},Ya=W({},[...aa,...la,...lg]),Ka=W({},[...ca,...cg]),md=function(d,b,E){return b.namespaceURI===Qe?d==="svg":b.namespaceURI===wr?d==="svg"&&(E==="annotation-xml"||Di[E]):!!Ya[d]},gd=function(d,b,E){return b.namespaceURI===Qe?d==="math":b.namespaceURI===_r?d==="math"&&Ui[E]:!!Ka[d]},vd=function(d,b,E){return b.namespaceURI===_r&&!Ui[E]||b.namespaceURI===wr&&!Di[E]?!1:!Ka[d]&&(dd[d]||!Ya[d])},bd=function(d){let b=_(d);(!b||!b.tagName)&&(b={namespaceURI:cn,tagName:"template"});let E=lr(d.tagName),R=lr(b.tagName);return Pi[d.namespaceURI]?d.namespaceURI===_r?md(E,b,R):d.namespaceURI===wr?gd(E,b,R):d.namespaceURI===Qe?vd(E,b,R):!!(Un==="application/xhtml+xml"&&Pi[d.namespaceURI]):!1},yt=function(d){Nn(e.removed,{element:d});try{_(d).removeChild(d)}catch{if(p(d),!_(d))throw tn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Ar=function(d){Hn(d);let b=x(d);if(b){let R=[];Cn(b,L=>{Nn(R,L)}),Cn(R,L=>{try{p(L)}catch{}})}let E=C(d);if(E)for(let R=E.length-1;R>=0;--R){let L=E[R],G=L&&L.name;if(typeof G=="string")try{d.removeAttribute(G)}catch{}}},Nt=function(d,b){try{Nn(e.removed,{attribute:b.getAttributeNode(d),from:b})}catch{Nn(e.removed,{attribute:null,from:b})}if(b.removeAttribute(d),d==="is")if(an||Er)try{yt(b)}catch{}else try{b.setAttribute(d,"")}catch{}},yd=function(d){let b=C(d);if(b)for(let E=b.length-1;E>=0;--E){let R=b[E],L=R&&R.name;if(!(typeof L!="string"||se[le(L)]))try{d.removeAttribute(L)}catch{}}},Hn=function(d){let b=[d];for(;b.length>0;){let E=b.pop();(H?H(E):E.nodeType)===Ue.element&&yd(E);let L=x(E);if(L)for(let G=L.length-1;G>=0;--G)b.push(L[G])}},xd=function(d){if(!bt)return;let b=[d];for(;b.length>0;){let E=b.pop(),R=H?H(E):E.nodeType;if(R===Ue.processingInstruction||R===Ue.comment&&be(gu,E.data)){try{p(E)}catch{}continue}if(R===Ue.element){let G=E,Z=le(U?U(E):E.nodeName);try{G.hasAttribute&&G.hasAttribute("patchsrc")&&G.removeAttribute("patchsrc"),G.hasAttribute&&G.hasAttribute("for")&&Z!=="label"&&Z!=="output"&&G.removeAttribute("for")}catch{}}let L=x(E);if(L)for(let G=L.length-1;G>=0;--G)b.push(L[G])}},Za=function(d){let b=null,E=null;if(Ni)d="<remove></remove>"+d;else{let G=su(d,/^[\r\n\t ]+/);E=G&&G[0]}Un==="application/xhtml+xml"&&cn===Qe&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let R=re?sn(d):d;if(cn===Qe)try{b=new f().parseFromString(R,Un)}catch{}if(!b||!b.documentElement){b=_i.createDocument(cn,"template",null);try{b.documentElement.innerHTML=Li?Be:R}catch{}}let L=b.body||b.documentElement;return d&&E&&L.insertBefore(n.createTextNode(E),L.childNodes[0]||null),cn===Qe?td.call(b,Ct?"html":"body")[0]:Ct?b.documentElement:L},Ja=function(d){let b=Y?Y(d):d.ownerDocument;return Ma.call(b||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},kr=function(d){return d=sr(d,rd," "),d=sr(d,od," "),d=sr(d,id," "),d},Gi=function(d){var b;d.normalize();let E=Y?Y(d):d.ownerDocument,R=Ma.call(E||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),L=R.nextNode();for(;L;)L.data=kr(L.data),L=R.nextNode();let G=(b=d.querySelectorAll)===null||b===void 0?void 0:b.call(d,"template");G&&Cn(G,Z=>{dn(Z.content)&&Gi(Z.content)})},Ir=function(d){let b=U?U(d):null;return typeof b!="string"||le(b)!=="form"?!1:typeof d.nodeName!="string"||typeof d.textContent!="string"||typeof d.removeChild!="function"||d.attributes!==C(d)||typeof d.removeAttribute!="function"||typeof d.setAttribute!="function"||typeof d.namespaceURI!="string"||typeof d.insertBefore!="function"||typeof d.hasChildNodes!="function"||d.nodeType!==H(d)||d.childNodes!==x(d)},dn=function(d){if(!H||typeof d!="object"||d===null)return!1;try{return H(d)===Ue.documentFragment}catch{return!1}},Gn=function(d){if(!H||typeof d!="object"||d===null)return!1;try{return typeof H(d)=="number"}catch{return!1}};function et(w,d,b){w.length!==0&&Cn(w,E=>{E.call(e,d,b,un)})}let Ed=function(d,b){return!!(bt&&d.hasChildNodes()&&!Gn(d.firstElementChild)&&be(mu,d.textContent)&&be(mu,d.innerHTML)||bt&&d.namespaceURI===Qe&&b==="style"&&Gn(d.firstElementChild)||d.nodeType===Ue.processingInstruction||bt&&d.nodeType===Ue.comment&&be(gu,d.data))},Td=function(d,b,E){if(!Dn[b]&&nl(b)&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,b)||de.tagNameCheck instanceof Function&&de.tagNameCheck(b)))return!1;if(Ri&&!Je[b]){let R=_(d),L=x(d);if(L&&R){let G=L.length;for(let Z=G-1;Z>=0;--Z){let ce=d===E?h(L[Z],!0):L[Z];R.insertBefore(ce,g(d))}}}return yt(d),!0},Qa=function(d,b,E,R){return d.length===0?b:b===E||b===R?Ae(b):b},el=function(d,b){if(et(oe.beforeSanitizeElements,d,null),d!==b&&_(d)===null)return Sr&&Hn(d),!0;if(Ir(d))return yt(d),!0;let E=le(U?U(d):d.nodeName);if(ie=Qa(oe.uponSanitizeElement,ie,Ai,yr),et(oe.uponSanitizeElement,d,{tagName:E,allowedTags:ie}),d!==b&&_(d)===null)return Sr&&Hn(d),!0;if(Ed(d,E))return yt(d),!0;if(Dn[E]||!(gt.tagCheck instanceof Function&>.tagCheck(E))&&!ie[E]){let L=Td(d,E,b);return L===!1&&et(oe.afterSanitizeElements,d,null),L}if((H?H(d):d.nodeType)===Ue.element&&!bd(d)||(E==="noscript"||E==="noembed"||E==="noframes")&&be(yg,d.innerHTML))return yt(d),!0;if(vt&&d.nodeType===Ue.text){let L=kr(d.textContent);d.textContent!==L&&(Nn(e.removed,{element:d.cloneNode()}),d.textContent=L)}return et(oe.afterSanitizeElements,d,null),!1},tl=function(d,b,E){if(Da[b]||bt&&b==="patchsrc"||bt&&b==="for"&&d!=="label"&&d!=="output"||Fa&&(b==="id"||b==="name")&&(E in n||E in hd))return!1;let R=se[b]||gt.attributeCheck instanceof Function&>.attributeCheck(b,d);if(!(Ii&&be(sd,b))){if(!(Ua&&be(ad,b))){if(R){if(!Mi[b]){if(!be(Pa,sr(E,La,""))){if(!((b==="src"||b==="xlink:href"||b==="href")&&d!=="script"&&au(E,"data:")===0&&Ba[d])){if(!(Ha&&!be(ld,sr(E,La,"")))){if(E)return!1}}}}}else if(!(nl(d)&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,d)||de.tagNameCheck instanceof Function&&de.tagNameCheck(d))&&(de.attributeNameCheck instanceof RegExp&&be(de.attributeNameCheck,b)||de.attributeNameCheck instanceof Function&&de.attributeNameCheck(b,d))||b==="is"&&de.allowCustomizedBuiltInElements&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,E)||de.tagNameCheck instanceof Function&&de.tagNameCheck(E))))return!1}}return!0},Sd=W({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),nl=function(d){return!Sd[lr(d)]&&be(cd,d)},wd=function(d,b,E,R){if(re&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!E)switch(m.getAttributeType(d,b)){case"TrustedHTML":return sn(R);case"TrustedScriptURL":return Ju(R)}return R},_d=function(d,b,E,R){try{E?d.setAttributeNS(E,b,R):d.setAttribute(b,R),Ir(d)?yt(d):iu(e.removed)}catch{Nt(b,d)}},rl=function(d){et(oe.beforeSanitizeAttributes,d,null);let b=d.attributes;if(!b||Ir(d))return;se=Qa(oe.uponSanitizeAttribute,se,ki,xr);let E={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},R=b.length,L=le(d.nodeName);for(;R--;){let G=b[R],Z=G.name,ce=G.namespaceURI,Ce=G.value,Ne=le(Z),$i=Ce,Ie=Z==="value"?$i:tg($i);if(E.attrName=Ne,E.attrValue=Ie,E.keepAttr=!0,E.forceKeepAttr=void 0,et(oe.uponSanitizeAttribute,d,E),Ie=E.attrValue,$a&&(Ne==="id"||Ne==="name")&&au(Ie,za)!==0&&(Nt(Z,d),Ie=za+Ie),bt&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ie)){Nt(Z,d);continue}if(Ne==="attributename"&&su(Ie,"href")){Nt(Z,d);continue}if(!E.forceKeepAttr){if(!E.keepAttr){Nt(Z,d);continue}if(!Ga&&be(xg,Ie)){Nt(Z,d);continue}if(vt&&(Ie=kr(Ie)),!tl(L,Ne,Ie)){Nt(Z,d);continue}Ie=wd(L,Ne,ce,Ie),Ie!==$i&&_d(d,Z,ce,Ie)}}et(oe.afterSanitizeAttributes,d,null)},Cr=function(d){let b=null,E=Ja(d);for(et(oe.beforeSanitizeShadowDOM,d,null);b=E.nextNode();)if(et(oe.uponSanitizeShadowNode,b,null),el(b,d),rl(b),dn(b.content)&&Cr(b.content),(H?H(b):b.nodeType)===Ue.element){let L=S(b);dn(L)&&(Fi(L),Cr(L))}et(oe.afterSanitizeShadowDOM,d,null)},Fi=function(d){let b=[{node:d,shadow:null}];for(;b.length>0;){let E=b.pop();if(E.shadow){Cr(E.shadow);continue}let R=E.node,G=(H?H(R):R.nodeType)===Ue.element,Z=x(R);if(Z)for(let ce=Z.length-1;ce>=0;--ce)b.push({node:Z[ce],shadow:null});if(G){let ce=U?U(R):null;if(typeof ce=="string"&&le(ce)==="template"){let Ce=R.content;dn(Ce)&&b.push({node:Ce,shadow:null})}}if(G){let ce=S(R);dn(ce)&&b.push({node:null,shadow:ce},{node:ce,shadow:null})}}};return e.sanitize=function(w){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},b=null,E=null,R=null,L=null;if(Li=!w,Li&&(w="<!-->"),typeof w!="string"&&!Gn(w)&&(w=sg(w),typeof w!="string"))throw tn("dirty is not a string, aborting");if(!e.isSupported)return w;Ci?(ie=yr,se=xr):Hi(d),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=Ae(ie)),oe.uponSanitizeAttribute.length>0&&(se=Ae(se)),e.removed=[];let G=Sr&&typeof w!="string"&&Gn(w);if(G){xd(w);let Ce=U?U(w):w.nodeName;if(typeof Ce=="string"){let Ne=le(Ce);if(!ie[Ne]||Dn[Ne])throw Ar(w),tn("root node is forbidden and cannot be sanitized in-place")}if(Ir(w))throw Ar(w),tn("root node is clobbered and cannot be sanitized in-place");try{Fi(w)}catch(Ne){throw Ar(w),Ne}}else if(Gn(w))b=Za("<!---->"),E=b.ownerDocument.importNode(w,!0),E.nodeType===Ue.element&&E.nodeName==="BODY"||E.nodeName==="HTML"?b=E:b.appendChild(E),Fi(E);else{if(!an&&!vt&&!Ct&&w.indexOf("<")===-1)return re&&Tr?sn(w):w;if(b=Za(w),!b)return an?null:Tr?Be:""}b&&Ni&&yt(b.firstChild);let Z=G?w:b;try{let Ce=Ja(Z);for(;R=Ce.nextNode();)el(R,Z),rl(R),dn(R.content)&&Cr(R.content)}catch(Ce){throw G&&(Ar(w),Cn(e.removed,Ne=>{Ne.element&&Hn(Ne.element)})),Ce}if(G)return Cn(e.removed,Ce=>{Ce.element&&Hn(Ce.element)}),vt&&Gi(w),w;if(an){if(vt&&Gi(b),Er)for(L=ed.call(b.ownerDocument);b.firstChild;)L.appendChild(b.firstChild);else L=b;return(se.shadowroot||se.shadowrootmode)&&(L=nd.call(r,L,!0)),L}let ce=Ct?b.outerHTML:b.innerHTML;return Ct&&ie["!doctype"]&&b.ownerDocument&&b.ownerDocument.doctype&&b.ownerDocument.doctype.name&&be(vg,b.ownerDocument.doctype.name)&&(ce="<!DOCTYPE "+b.ownerDocument.doctype.name+`>
|
|
13
|
+
`+ce),vt&&(ce=kr(ce)),re&&Tr?sn(ce):ce},e.setConfig=function(){let w=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Hi(w),Ci=!0,yr=ie,xr=se},e.clearConfig=function(){un=null,Ci=!1,yr=null,xr=null,re=wi,Be=""},e.isValidAttribute=function(w,d,b){un||Hi({});let E=le(w),R=le(d);return tl(E,R,b)},e.addHook=function(w,d){typeof d=="function"&&ye(oe,w)&&Nn(oe[w],d)},e.removeHook=function(w,d){if(ye(oe,w)){if(d!==void 0){let b=Qm(oe[w],d);return b===-1?void 0:eg(oe[w],b,1)[0]}return iu(oe[w])}},e.removeHooks=function(w){ye(oe,w)&&(oe[w]=[])},e.removeAllHooks=function(){oe=vu()},e}var Eu=xu();function ga(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var on=ga();function Cu(t){on=t}var nn={exec:()=>null};function On(t){let e=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),o=e[r];return o||(o=t(r),e[r]=o),o}}function j(t,e=""){let n=typeof t=="string"?t:t.source,r={replace:(o,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(ke.caret,"$1"),n=n.replace(o,s),r},getRegex:()=>new RegExp(n,e)};return r}var Sg=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),ke={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:On(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:On(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:On(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:On(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:On(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:On(t=>new RegExp(`^ {0,${t}}>`))},wg=/^(?:[ \t]*(?:\n|$))+/,_g=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ag=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,dr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,kg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,va=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Nu=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ru=j(Nu).replace(/bull/g,va).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}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Ig=j(Nu).replace(/bull/g,va).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}(?:\s|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ba=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Cg=/^[^\n]+/,ya=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ng=j(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ya).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Rg=j(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,va).getRegex(),mi="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",xa=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Og=j("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\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",xa).replace("tag",mi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Ou=t=>j(ba).replace("hr",dr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list",t).replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",mi).getRegex(),Mg=Ou(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Lg=Ou(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Pg=j(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Lg).getRegex(),Ea={blockquote:Pg,code:_g,def:Ng,fences:Ag,heading:kg,hr:dr,html:Og,lheading:Ru,list:Rg,newline:wg,paragraph:Mg,table:nn,text:Cg},Tu=j("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",dr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",mi).getRegex(),Dg={...Ea,lheading:Ig,table:Tu,paragraph:j(ba).replace("hr",dr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Tu).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~~~)[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",mi).getRegex()},Ug={...Ea,html:j(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",xa).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:nn,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:j(ba).replace("hr",dr).replace("heading",` *#{1,6} *[^
|
|
14
|
+
]`).replace("lheading",Ru).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Hg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Gg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Mu=/^( {2,}|\\)\n(?!\s*$)/,Fg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ht=/[\p{P}\p{S}]/u,Mn=/[\s\p{P}\p{S}]/u,pr=/[^\s\p{P}\p{S}]/u,$g=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Mn).getRegex(),zg=/[\p{Pi}\p{Ps}"']/u,Lu=/(?!~)[\p{P}\p{S}]/u,Bg=/(?!~)[\s\p{P}\p{S}]/u,Vg=/(?:[^\s\p{P}\p{S}]|~)/u,jg=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Sg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Pu=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,qg=j(Pu,"u").replace(/punct/g,ht).getRegex(),Wg=j(Pu,"u").replace(/punct/g,Lu).getRegex(),Xg=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,Yg=j(Xg,"u").replace(/openQuote/g,zg).replace(/punct/g,ht).getRegex(),Du="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Kg=j(Du,"gu").replace(/notPunctSpace/g,pr).replace(/punctSpace/g,Mn).replace(/punct/g,ht).getRegex(),Zg=j(Du,"gu").replace(/notPunctSpace/g,Vg).replace(/punctSpace/g,Bg).replace(/punct/g,Lu).getRegex(),Jg="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Qg=j(Jg,"gu").replace(/notPunctSpace/g,pr).replace(/punctSpace/g,Mn).replace(/punct/g,ht).getRegex(),ev=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,pr).replace(/punctSpace/g,Mn).replace(/punct/g,ht).getRegex(),tv="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",nv=j(tv,"gu").replace(/notPunctSpace/g,pr).replace(/punctSpace/g,Mn).replace(/punct/g,ht).getRegex(),rv=j(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,ht).getRegex(),ov="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",iv=j(ov,"gu").replace(/notPunctSpace/g,pr).replace(/punctSpace/g,Mn).replace(/punct/g,ht).getRegex(),sv=j(/\\(punct)/,"gu").replace(/punct/g,ht).getRegex(),av=j(/^<(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(),lv=j(xa).replace("(?:-->|$)","-->").getRegex(),cv=j("^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",lv).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),pi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,uv=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",pi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Uu=j(/^!?\[(label)\]\[(ref)\]/).replace("label",pi).replace("ref",ya).getRegex(),Hu=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",ya).getRegex(),dv=j("reflink|nolink(?!\\()","g").replace("reflink",Uu).replace("nolink",Hu).getRegex(),Su=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ta={_backpedal:nn,anyPunctuation:sv,autolink:av,blockSkip:jg,br:Mu,code:Gg,del:nn,delLDelim:nn,delRDelim:nn,emStrongLDelim:qg,emStrongRDelimAst:Kg,emStrongRDelimUnd:ev,escape:Hg,link:uv,nolink:Hu,punctuation:$g,reflink:Uu,reflinkSearch:dv,tag:cv,text:Fg,url:nn},pv={...Ta,emStrongLDelim:Yg,emStrongRDelimAst:Qg,emStrongRDelimUnd:nv,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",pi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",pi).getRegex()},fa={...Ta,emStrongRDelimAst:Zg,emStrongLDelim:Wg,delLDelim:rv,delRDelim:iv,url:j(/^((?: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:j(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {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()},fv={...fa,br:j(Mu).replace("{2,}","*").getRegex(),text:j(fa.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},di={normal:Ea,gfm:Dg,pedantic:Ug},cr={normal:Ta,gfm:fa,breaks:fv,pedantic:pv},hv={"&":"&","<":"<",">":">",'"':""","'":"'"},wu=t=>hv[t];function at(t,e){if(e){if(ke.escapeTest.test(t))return t.replace(ke.escapeReplace,wu)}else if(ke.escapeTestNoEncode.test(t))return t.replace(ke.escapeReplaceNoEncode,wu);return t}function _u(t){try{t=encodeURI(t).replace(ke.percentDecode,"%")}catch{return null}return t}function Au(t,e){let n=t.replace(ke.findPipe,(i,s,a)=>{let l=!1,u=s;for(;--u>=0&&a[u]==="\\";)l=!l;return l?"|":" |"}),r=n.split(ke.splitPipe),o=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),e)if(r.length>e)r.splice(e);else for(;r.length<e;)r.push("");for(;o<r.length;o++)r[o]=r[o].trim().replace(ke.slashPipe,"|");return r}function It(t,e,n){let r=t.length;if(r===0)return"";let o=0;for(;o<r;){let i=t.charAt(r-o-1);if(i===e&&!n)o++;else if(i!==e&&n)o++;else break}return t.slice(0,r-o)}function ku(t){let e=t.split(`
|
|
15
15
|
`),n=e.length-1;for(;n>=0&&ke.blankLine.test(e[n]);)n--;return e.length-n<=2?t:e.slice(0,n+1).join(`
|
|
16
|
-
`)}function
|
|
16
|
+
`)}function mv(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 gv(t,e=0){let n=e,r="";for(let o of t)if(o===" "){let i=4-n%4;r+=" ".repeat(i),n+=i}else r+=o,n++;return r}function Iu(t,e,n,r,o){let i=e.href,s=e.title||null,a=t[1].replace(o.other.outputLinkReplace,"$1");r.state.inLink=!0;let l={type:t[0].charAt(0)==="!"?"image":"link",raw:n,href:i,title:s,text:a,tokens:r.inlineTokens(a)};return r.state.inLink=!1,l}function vv(t,e,n){let r=t.match(n.other.indentCodeCompensation);if(r===null)return e;let o=r[1];return e.split(`
|
|
17
17
|
`).map(i=>{let s=i.match(n.other.beginningSpace);if(s===null)return i;let[a]=s;return a.length>=o.length?i.slice(o.length):i}).join(`
|
|
18
|
-
`)}var
|
|
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:
|
|
20
|
-
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=
|
|
18
|
+
`)}var fi=class{options;rules;lexer;constructor(t){this.options=t||on}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]:ku(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=vv(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=It(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:It(e[0],`
|
|
19
|
+
`),depth:e[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:It(e[0],`
|
|
20
|
+
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=It(e[0],`
|
|
21
21
|
`).split(`
|
|
22
|
-
`),r="",o="",i=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let
|
|
23
|
-
`),f=
|
|
22
|
+
`),r="",o="",i=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let u=a.join(`
|
|
23
|
+
`),f=u.replace(this.rules.other.blockquoteSetextReplace,`
|
|
24
24
|
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}
|
|
25
|
-
${
|
|
26
|
-
${f}`:f;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,i,!0),this.lexer.state.top=m,n.length===0)break;let y=i.at(-1);if(y?.type==="code")break;if(y?.type==="blockquote"){let h=y,p=
|
|
27
|
-
|
|
28
|
-
|
|
25
|
+
${u}`:u,o=o?`${o}
|
|
26
|
+
${f}`:f;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(f,i,!0),this.lexer.state.top=m,n.length===0)break;let y=i.at(-1);if(y?.type==="code")break;if(y?.type==="blockquote"){let h=y,p=n.join(`
|
|
27
|
+
`),g=h.raw+`
|
|
28
|
+
`+p.replace(this.rules.other.blockquoteSetextReplace2,""),x=this.blockquote(g);i[i.length-1]=x,r=`${r}
|
|
29
|
+
${p}`,o=o.substring(0,o.length-h.text.length)+x.text;break}else if(y?.type==="list"){let h=y,p=h.raw+`
|
|
29
30
|
`+n.join(`
|
|
30
31
|
`),g=this.list(p);i[i.length-1]=g,r=r.substring(0,r.length-y.raw.length)+g.raw,o=o.substring(0,o.length-h.raw.length)+g.raw,n=p.substring(i.at(-1).raw.length).split(`
|
|
31
|
-
`);continue}}return{type:"blockquote",raw:r,tokens:i,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,
|
|
32
|
+
`);continue}}return{type:"blockquote",raw:r,tokens:i,text:o}}}list(t){let e=this.rules.block.list.exec(t);if(e){let n=e[1].trim(),r=n.length>1,o={type:"list",raw:"",ordered:r,start:r?+n.slice(0,-1):"",loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:"[*+-]");let i=this.rules.other.listItemRegex(n),s=!1;for(;t;){let l=!1,u="",f="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;u=e[0],t=t.substring(u.length);let m=gv(e[2].split(`
|
|
32
33
|
`,1)[0],e[1].length),y=t.split(`
|
|
33
|
-
`,1)[0],h=!m.trim(),p=0;if(this.options.pedantic?(p=2,f=m.trimStart()):h?p=e[1].length+1:(p=m.search(this.rules.other.nonSpaceChar),p=p>4?1:p,f=m.slice(p),p+=e[1].length),h&&this.rules.other.blankLine.test(y)&&(
|
|
34
|
-
`,t=t.substring(y.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(p),x=this.rules.other.hrRegex(p),_=this.rules.other.fencesBeginRegex(p),
|
|
35
|
-
`,1)[0],Y;if(y=U,this.options.pedantic?(y=y.replace(this.rules.other.listReplaceNesting," "),Y=y):Y=y.replace(this.rules.other.tabCharGlobal," "),_.test(y)||
|
|
36
|
-
`+Y.slice(p);else{if(h||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(m)||
|
|
37
|
-
`+y}h=!y.trim(),
|
|
38
|
-
`,t=t.substring(U.length+1),m=Y.slice(p)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(
|
|
39
|
-
`),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=
|
|
40
|
-
`):[],i={type:"table",raw:
|
|
41
|
-
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?i.align.push("right"):this.rules.other.tableAlignCenter.test(s)?i.align.push("center"):this.rules.other.tableAlignLeft.test(s)?i.align.push("left"):i.align.push(null);for(let s=0;s<n.length;s++)i.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:i.align[s]});for(let s of o)i.rows.push(
|
|
34
|
+
`,1)[0],h=!m.trim(),p=0;if(this.options.pedantic?(p=2,f=m.trimStart()):h?p=e[1].length+1:(p=m.search(this.rules.other.nonSpaceChar),p=p>4?1:p,f=m.slice(p),p+=e[1].length),h&&this.rules.other.blankLine.test(y)&&(u+=y+`
|
|
35
|
+
`,t=t.substring(y.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(p),x=this.rules.other.hrRegex(p),_=this.rules.other.fencesBeginRegex(p),S=this.rules.other.headingBeginRegex(p),C=this.rules.other.htmlBeginRegex(p),H=this.rules.other.blockquoteBeginRegex(p);for(;t;){let U=t.split(`
|
|
36
|
+
`,1)[0],Y;if(y=U,this.options.pedantic?(y=y.replace(this.rules.other.listReplaceNesting," "),Y=y):Y=y.replace(this.rules.other.tabCharGlobal," "),_.test(y)||S.test(y)||C.test(y)||H.test(y)||g.test(y)||x.test(y))break;if(Y.search(this.rules.other.nonSpaceChar)>=p||!y.trim())f+=`
|
|
37
|
+
`+Y.slice(p);else{if(h||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||_.test(m)||S.test(m)||x.test(m))break;f+=`
|
|
38
|
+
`+y}h=!y.trim(),u+=U+`
|
|
39
|
+
`,t=t.substring(U.length+1),m=Y.slice(p)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(s=!0)),o.items.push({type:"list_item",raw:u,task:!!this.options.gfm&&this.rules.other.listIsTask.test(f),loose:!1,text:f,tokens:[]}),o.raw+=u}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let u=l.tokens[0];if(l.task&&(u?.type==="text"||u?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),u.raw=u.raw.replace(this.rules.other.listReplaceTask,""),u.text=u.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,o.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=m.raw+l.tokens[0].raw,l.tokens[0].text=m.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(m)):l.tokens.unshift({type:"paragraph",raw:m.raw,text:m.raw,tokens:[m]}):l.tokens.unshift(m)}}else l.task&&(l.task=!1);if(!o.loose){let f=l.tokens.filter(y=>y.type==="space"),m=f.length>0&&f.some(y=>this.rules.other.anyLine.test(y.raw));o.loose=m}}if(o.loose)for(let l of o.items){l.loose=!0;for(let u of l.tokens)u.type==="text"&&(u.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=ku(e[0]);return{type:"html",block:!0,raw:n,pre:e[1]==="pre"||e[1]==="script"||e[1]==="style",text:n}}}def(t){let e=this.rules.block.def.exec(t);if(e){let n=e[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=e[2]?e[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=e[3]?e[3].substring(1,e[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):e[3];return{type:"def",tag:n,raw:It(e[0],`
|
|
40
|
+
`),href:r,title:o}}}table(t){let e=this.rules.block.table.exec(t);if(!e||!this.rules.other.tableDelimiter.test(e[2]))return;let n=Au(e[1]),r=e[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=e[3]?.trim()?e[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
41
|
+
`):[],i={type:"table",raw:It(e[0],`
|
|
42
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let s of r)this.rules.other.tableAlignRight.test(s)?i.align.push("right"):this.rules.other.tableAlignCenter.test(s)?i.align.push("center"):this.rules.other.tableAlignLeft.test(s)?i.align.push("left"):i.align.push(null);for(let s=0;s<n.length;s++)i.header.push({text:n[s],tokens:this.lexer.inline(n[s]),header:!0,align:i.align[s]});for(let s of o)i.rows.push(Au(s,i.header.length).map((a,l)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:i.align[l]})));return i}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e){let n=e[1].trim();return{type:"heading",raw:It(e[0],`
|
|
42
43
|
`),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 i=
|
|
44
|
+
`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let n=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=It(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=mv(e[2],"()");if(i===-2)return;if(i>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+i;e[2]=e[2].substring(0,i),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let r=e[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=e[3]?e[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?r=r.slice(1):r=r.slice(1,-1)),Iu(e,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=e[r.toLowerCase()];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return Iu(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=0,u=r[0][0],f=n===u,m=u==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,e=e.slice(-1*t.length+o);(r=m.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(s=[...i].length,r[3]||r[4]){a+=s;continue}else if(r[5]||r[6]){if(o%3&&!((o+s)%3)){l+=s;continue}if(f)break}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let y=[...r[0]][0].length,h=t.slice(0,o+r.index+y+s);if(Math.min(o,s)%2){let g=h.slice(1,-1);return{type:"em",raw:h,text:g,tokens:this.lexer.inlineTokens(g)}}let p=h.slice(2,-2);return{type:"strong",raw:h,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let n=e[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return r&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:e[0],text:n}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t,e,n=""){let r=this.rules.inline.delLDelim.exec(t);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=this.rules.inline.delRDelim;for(l.lastIndex=0,e=e.slice(-1*t.length+o);(r=l.exec(e))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(s=[...i].length,s!==o))continue;if(r[3]||r[4]){a+=s;continue}if(a-=s,a>0)continue;s=Math.min(s,s+a);let u=[...r[0]][0].length,f=t.slice(0,o+r.index+u+s),m=f.slice(o,-o);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 o;do o=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(o!==e[0]);n=e[0],e[1]==="www."?r="http://"+e[0]:r=e[0]}return{type:"link",raw:e[0],text:n,href:r,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let n=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:n}}}},Ke=class ha{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||on,this.options.tokenizer=this.options.tokenizer||new fi,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:ke,block:di.normal,inline:cr.normal};this.options.pedantic?(n.block=di.pedantic,n.inline=cr.pedantic):this.options.gfm&&(n.block=di.gfm,this.options.breaks?n.inline=cr.breaks:n.inline=cr.gfm),this.tokenizer.rules=n}static get rules(){return{block:di,inline:cr}}static lex(e,n){return new ha(n).lex(e)}static lexInline(e,n){return new ha(n).inlineTokens(e)}lex(e){e=e.replace(ke.carriageReturn,`
|
|
44
45
|
`),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(ke.tabCharGlobal," ").replace(ke.spaceLine,""));let o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(a=>(i=a.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let a=n.at(-1);i.raw.length===1&&a!==void 0?a.raw+=`
|
|
45
46
|
`:n.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
46
47
|
`)?"":`
|
|
@@ -48,13 +49,13 @@ ${f}`:f;let m=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
48
49
|
`+i.text,this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
49
50
|
`)?"":`
|
|
50
51
|
`)+i.raw,a.text+=`
|
|
51
|
-
`+i.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),n.push(i);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),
|
|
52
|
+
`+i.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},n.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),n.push(i);continue}let s=e;if(this.options.extensions?.startBlock){let a=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(f=>{u=f.call({lexer:this},l),typeof u=="number"&&u>=0&&(a=Math.min(a,u))}),a<1/0&&a>=0&&(s=e.substring(0,a+1))}if(this.state.top&&(i=this.tokenizer.paragraph(s))){let a=n.at(-1);r&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
|
|
52
53
|
`)?"":`
|
|
53
54
|
`)+i.raw,a.text+=`
|
|
54
55
|
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i),r=s.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let a=n.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
55
56
|
`)?"":`
|
|
56
57
|
`)+i.raw,a.text+=`
|
|
57
|
-
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e
|
|
58
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,n}inline(e,n=[]){return this.inlineQueue.push({src:e,tokens:n}),n}inlineTokens(e,n=[]){this.tokenizer.lexer=this;let r=e;if(this.tokens.links){let a=Object.keys(this.tokens.links);a.length>0&&(r=r.replace(this.tokenizer.rules.inline.reflinkSearch,l=>a.includes(l.slice(l.lastIndexOf("[")+1,-1))?"["+"a".repeat(l.length-2)+"]":l))}r=r.replace(this.tokenizer.rules.inline.anyPunctuation,"++"),r=r.replace(this.tokenizer.rules.inline.blockSkip,(a,l,u)=>{let f=u?u.length:0;return a.slice(0,f)+"["+"a".repeat(a.length-f-2)+"]"}),r=this.options.hooks?.emStrongMask?.call({lexer:this},r)??r;let o=!1,i="",s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(i=""),o=!1;let a;if(this.options.extensions?.inline?.some(u=>(a=u.call({lexer:this},e,n))?(e=e.substring(a.raw.length),n.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let u=n.at(-1);a.type==="text"&&u?.type==="text"?(u.raw+=a.raw,u.text+=a.text):n.push(a);continue}if(a=this.tokenizer.emStrong(e,r,i)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.del(e,r,i)){e=e.substring(a.raw.length),n.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),n.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),n.push(a);continue}let l=e;if(this.options.extensions?.startInline){let u=1/0,f=e.slice(1),m;this.options.extensions.startInline.forEach(y=>{m=y.call({lexer:this},f),typeof m=="number"&&m>=0&&(u=Math.min(u,m))}),u<1/0&&u>=0&&(l=e.substring(0,u+1))}if(a=this.tokenizer.inlineText(l)){e=e.substring(a.raw.length),a.raw.slice(-1)!=="_"&&(i=a.raw.slice(-1)),o=!0;let u=n.at(-1);u?.type==="text"?(u.raw+=a.raw,u.text+=a.text):n.push(a);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)}},hi=class{options;parser;constructor(t){this.options=t||on}space(t){return""}code({text:t,lang:e,escaped:n}){let r=(e||"").match(ke.notSpaceStart)?.[0],o=t.replace(ke.endingNewline,"")+`
|
|
58
59
|
`;return r?'<pre><code class="language-'+at(r)+'">'+(n?o:at(o,!0))+`</code></pre>
|
|
59
60
|
`:"<pre><code>"+(n?o:at(o,!0))+`</code></pre>
|
|
60
61
|
`}blockquote({tokens:t}){return`<blockquote>
|
|
@@ -72,8 +73,8 @@ ${this.parser.parse(t)}</blockquote>
|
|
|
72
73
|
`}tablerow({text:t}){return`<tr>
|
|
73
74
|
${t}</tr>
|
|
74
75
|
`}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>${at(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=
|
|
76
|
-
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+at(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},
|
|
76
|
+
`}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>${at(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,tokens:n}){let r=this.parser.parseInline(n),o=_u(t);if(o===null)return r;t=o;let i='<a href="'+t+'"';return e&&(i+=' title="'+at(e)+'"'),i+=">"+r+"</a>",i}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=_u(t);if(o===null)return at(n);t=o;let i=`<img src="${t}" alt="${at(n)}"`;return e&&(i+=` title="${at(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:at(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}},Ze=class ma{options;renderer;textRenderer;constructor(e){this.options=e||on,this.options.renderer=this.options.renderer||new hi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Sa}static parse(e,n){return new ma(n).parse(e)}static parseInline(e,n){return new ma(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let s=o,a=this.options.extensions.renderers[s.type].call({parser:this},s);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(s.type)){n+=a||"";continue}}let i=o;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let s='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let i=e[o];if(this.options.extensions?.renderers?.[i.type]){let a=this.options.extensions.renderers[i.type].call({parser:this},i);if(a!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(i.type)){r+=a||"";continue}}let s=i;switch(s.type){case"escape":{r+=n.text(s);break}case"html":{r+=n.html(s);break}case"link":{r+=n.link(s);break}case"image":{r+=n.image(s);break}case"checkbox":{r+=n.checkbox(s);break}case"strong":{r+=n.strong(s);break}case"em":{r+=n.em(s);break}case"codespan":{r+=n.codespan(s);break}case"br":{r+=n.br(s);break}case"del":{r+=n.del(s);break}case"text":{r+=n.text(s);break}default:{let a='Token with "'+s.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return r}},ur=class{options;block;constructor(t){this.options=t||on}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?Ke.lex:Ke.lexInline}provideParser(t=this.block){return t?Ze.parse:Ze.parseInline}},wa=class{defaults=ga();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ze;Renderer=hi;TextRenderer=Sa;Lexer=Ke;Tokenizer=fi;Hooks=ur;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(n=n.concat(e.call(this,r)),r.type){case"table":{let o=r;for(let i of o.header)n=n.concat(this.walkTokens(i.tokens,e));for(let i of o.rows)for(let s of i)n=n.concat(this.walkTokens(s.tokens,e));break}case"list":{let o=r;n=n.concat(this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(i=>{let s=o[i].flat(1/0);n=n.concat(this.walkTokens(s,e))}):o.tokens&&(n=n.concat(this.walkTokens(o.tokens,e)))}}return n}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let i=e.renderers[o.name];i?e.renderers[o.name]=function(...s){let a=o.renderer.apply(this,s);return a===!1&&(a=i.apply(this,s)),a}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[o.level];i?i.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new hi(this.defaults);for(let i in n.renderer){if(!(i in o))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let s=i,a=n.renderer[s],l=o[s];o[s]=(...u)=>{let f=a.apply(o,u);return f===!1&&(f=l.apply(o,u)),f||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new fi(this.defaults);for(let i in n.tokenizer){if(!(i in o))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let s=i,a=n.tokenizer[s],l=o[s];o[s]=(...u)=>{let f=a.apply(o,u);return f===!1&&(f=l.apply(o,u)),f}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new ur;for(let i in n.hooks){if(!(i in o))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let s=i,a=n.hooks[s],l=o[s];ur.passThroughHooks.has(i)?o[s]=u=>{if(this.defaults.async&&ur.passThroughHooksRespectAsync.has(i))return(async()=>{let m=await a.call(o,u);return l.call(o,m)})();let f=a.call(o,u);return l.call(o,f)}:o[s]=(...u)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,u);return m===!1&&(m=await l.apply(o,u)),m})();let f=a.apply(o,u);return f===!1&&(f=l.apply(o,u)),f}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(s){let a=[];return a.push(i.call(this,s)),o&&(a=a.concat(o.call(this,s))),a}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return Ke.lex(t,e??this.defaults)}parser(t,e){return Ze.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let s=o.hooks?await o.hooks.preprocess(e):e,a=await(o.hooks?await o.hooks.provideLexer(t):t?Ke.lex:Ke.lexInline)(s,o),l=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let u=await(o.hooks?await o.hooks.provideParser(t):t?Ze.parse:Ze.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(u):u})().catch(i);try{o.hooks&&(e=o.hooks.preprocess(e));let s=(o.hooks?o.hooks.provideLexer(t):t?Ke.lex:Ke.lexInline)(e,o);o.hooks&&(s=o.hooks.processAllTokens(s)),o.walkTokens&&this.walkTokens(s,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(t):t?Ze.parse:Ze.parseInline)(s,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(s){return i(s)}}}onError(t,e){return n=>{if(n.message+=`
|
|
77
|
+
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+at(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},rn=new wa;function J(t,e){return rn.parse(t,e)}J.options=J.setOptions=function(t){return rn.setOptions(t),J.defaults=rn.defaults,Cu(J.defaults),J};J.getDefaults=ga;J.defaults=on;function bv(...t){return rn.use(...t),J.defaults=rn.defaults,Cu(J.defaults),J}J.use=bv;J.walkTokens=function(t,e){return rn.walkTokens(t,e)};J.parseInline=rn.parseInline;J.Parser=Ze;J.parser=Ze.parse;J.Renderer=hi;J.TextRenderer=Sa;J.Lexer=Ke;J.lexer=Ke.lex;J.Tokenizer=fi;J.Hooks=ur;J.parse=J;var fw=J.options,hw=J.setOptions,mw=J.walkTokens,gw=J.parseInline;var vw=Ze.parse,bw=Ke.lex;var yv=new wa({gfm:!0,breaks:!0}),Gu=["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"],Fu=["href","title","class"],xv=[...Gu,"img"],Ev=[...Fu,"src","alt","width","height"];function gi(t,e){let n=e?.allowImages===!0,r=yv.parse(t,{async:!1}),o=Eu.sanitize(r,{ALLOWED_TAGS:n?xv:Gu,ALLOWED_ATTR:n?Ev:Fu}),i=document.createElement("template");i.innerHTML=o;for(let s of i.content.querySelectorAll("a[href]"))s.setAttribute("target","_blank"),s.setAttribute("rel","noopener noreferrer");return i.innerHTML.trim()}function $u(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):$u(n,e)}function zu(t){let e=[];$u(t,e);let n=0;for(let{node:r,parent:o}of e){let i=document.createDocumentFragment();for(let s of r.data.split(/(\s+)/)){if(s==="")continue;if(/\s/.test(s)){i.appendChild(document.createTextNode(s));continue}let a=document.createElement("span");a.className="word",a.style.setProperty("--ag-ui-word-index",String(n)),a.textContent=s,i.appendChild(a),n+=1}o.replaceChild(i,r)}}function Bu(t,e,n){let r=document.createElement("div");r.className=`run-notice run-notice--${n}`,r.setAttribute("part",`run-notice run-notice-${n}`),r.setAttribute("role","status");let o=document.createElement("span");o.className="run-notice-icon",o.setAttribute("part","run-notice-icon"),o.textContent=t,o.setAttribute("aria-hidden","true");let i=document.createElement("span");return i.className="run-notice-text",i.setAttribute("part","run-notice-text"),i.textContent=e,r.append(o,i),r}var vi=class{chips;palette;#n;#e=[];#t=!1;#o=!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.#o=e}isOpen(){return!this.palette.hidden}onInput(e){this.#o&&e.startsWith("/")?this.#s(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#i(1),!0):e.key==="ArrowUp"?(this.#i(-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(o=>o.name.toLowerCase().includes(n)||o.title.toLowerCase().includes(n));if(r.length===0){this.close();return}this.#r=r,this.#a=0,this.#p(),this.palette.hidden=!1}#i(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 o=document.createElement("span");if(o.className="skill-item-title",o.setAttribute("part","skill-item-title"),o.textContent=e.title,r.appendChild(o),e.description!==void 0){let i=document.createElement("span");i.className="skill-item-desc",i.setAttribute("part","skill-item-desc"),i.textContent=e.description,r.appendChild(i)}r.addEventListener("click",()=>this.#l(e)),this.palette.appendChild(r)})}};var Vu=`
|
|
77
78
|
:host {
|
|
78
79
|
/* Colors */
|
|
79
80
|
--ag-ui-bg: #ffffff;
|
|
@@ -1573,11 +1574,11 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1573
1574
|
border-right: none;
|
|
1574
1575
|
box-shadow: none;
|
|
1575
1576
|
}
|
|
1576
|
-
`;var
|
|
1577
|
+
`;var bi=class{element;#n;#e;#t;#o;#r=!1;constructor(e=ae){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.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.#o.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var yi=class{element;#n;#e;#t;#o;#r;#a;#s=[];#i="";#l=null;constructor(e,n=ae){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",i=>this.#p(i));let o=document.createElement("div");o.className="drawer-header",o.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()}),o.append(this.#t,this.#o),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(o,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.#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}#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],o=n[n.length-1],i=this.#c();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#s=e,this.#i=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.#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 o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=ci(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(o,i,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 u=document.createElement("div");return u.className="drawer-row-actions",u.setAttribute("part","drawer-row-actions"),u.append(a,l),n.append(r,u),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 o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#u():this.#n.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#u())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),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 o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#a.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#a.delete,i.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(o,i,s),e.replaceChildren(r)}};function ju(t){return{[pe.PENDING]:t.toolRunning,[pe.DONE]:t.toolDone,[pe.ERROR]:t.toolError,[pe.DECLINED]:t.toolDeclined}}function Tv(t){return{[pe.DONE]:t.resultLabel,[pe.ERROR]:t.errorLabel,[pe.DECLINED]:t.declinedLabel}}var fr=class{element;#n;#e;#t;#o;#r=!1;constructor(e,n,r=je.FULL,o,i=ae){this.#e=r,this.#t=n,this.#o=i,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",pe.PENDING),this.element.setAttribute("data-display",r);let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");if(l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=o??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=ju(i)[pe.PENDING],s.append(a,l,this.#n),this.element.append(s),r===je.FULL){let u=document.createElement("pre");u.className="tool-call-args",u.setAttribute("part","tool-card-args"),u.textContent=JSON.stringify(n,null,2),this.element.append(u)}}get settled(){return this.#r}settle(e,n){if(this.#r||(this.#r=!0,this.element.setAttribute("data-status",e),this.#n.textContent=ju(this.#o)[e],this.#e===je.MINIMAL))return;let r=document.createElement("button");r.type="button",r.className="tool-call-toggle",r.setAttribute("part","tool-card-toggle"),r.setAttribute("aria-expanded","false");let o=document.createElement("pre");o.className="tool-call-result",o.setAttribute("part","tool-card-result"),o.hidden=!0,this.#e===je.COMPACT?(r.textContent=this.#o.details,o.textContent=`args: ${JSON.stringify(this.#t)}
|
|
1577
1578
|
|
|
1578
|
-
${n}`):(r.textContent=dv(this.#o)[e],o.textContent=n),r.addEventListener("click",()=>{let i=o.hidden;o.hidden=!i,r.setAttribute("aria-expanded",String(i))}),this.element.append(r,o)}};var bi=class{element;#n;#e;#t;#o="idle";#r=null;#a=null;#s=[];#i=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ae,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.#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.#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.#i=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#p(e){if(this.#i)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.#o=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 yi=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Mn=class{#n;#e;#t;#o;#r;#a;#s;#i;#l=!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.#a=e.resolveInterrupts??null,this.#s=e.onPersist??(()=>{}),this.#i=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:De(),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:De(),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||pv(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<ji;n+=1){if(this.#l)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#o()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#s(this.#n.messages),this.#l)return;if(!o.terminal)throw new yi(this.#i);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#l)return;e=Qc(o.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:De(),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:o}){r.onTextDelta(o)},onTextMessageEndEvent({textMessageBuffer:o}){r.onTextEnd(o)},onToolCallEndEvent({event:o,toolCallName:i,toolCallArgs:s}){let a={id:o.toolCallId,name:i,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:o}){r.onToolResult(o.toolCallId,o.content)},onActivitySnapshotEvent({event:o}){r.onActivity(o.activityType,o.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:o}){r.onReasoningDelta(o)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(o){n.terminal=!0,o.outcome==="interrupt"&&(n.interrupts=o.interrupts)},onRunErrorEvent({event:o}){n.terminal=!0,n.errored=!0,r.onError(o.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function pv(t){return t instanceof Error&&t.name==="AbortError"}function Sa(t){let e=t.attachments;return Array.isArray(e)?e.filter(fv):[]}function fv(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 _a="ag-ui-chat",pr="thread",Aa="threads",xi="messages:",Ei="checkpoint:",hv=60,mv=100,gv="New conversation",ht=class{#n;constructor(e=""){this.#n=e===""?_a:`${_a}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(pr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=De();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#s(this.#r(xi+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(xi+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#s(this.#r(Ei+e))}saveCheckpoint(e,n){let r=this.#r(Ei+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(xi+e)),sessionStorage.removeItem(this.#r(Ei+e)),this.#o(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(pr))===e&&sessionStorage.removeItem(this.#r(pr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(pr),e)}renameThread(e,n){let r=this.#t(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#o(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=bv(n),s=Date.now();o===void 0?r.push({threadId:e,title:ju(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=ju(n))),this.#o(r)}#t(){return this.#s(this.#r(Aa))??[]}#o(e){let n=this.#r(Aa);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${_a}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let o=sessionStorage.key(r);if(o===null||!o.startsWith(e))continue;let i=o.slice(e.length);vv(i)&&n.push([o,this.#r(i)])}for(let[r,o]of n){let i=sessionStorage.getItem(r);i!==null&&sessionStorage.getItem(o)===null&&sessionStorage.setItem(o,i),sessionStorage.removeItem(r)}}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function vv(t){return t===pr||t===Aa||t.startsWith(xi)||t.startsWith(Ei)}function ju(t){for(let e of t)if(e.role==="user"){let n=qu(e.content);if(n!=="")return Wu(n,hv)}return gv}function bv(t){for(let e of[...t].reverse()){let n=qu(e.content);if(n!=="")return Wu(n,mv)}return""}function qu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Wu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function ka(t){return new eu({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var fr=class{#n;#e;#t;#o=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.#o.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#a();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.#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}}#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 o=this.#e();try{await fetch(this.#n+encodeURIComponent(e)+"/",{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var hr=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 Ia(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 yv(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function yv(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Ca(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(xv(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Ev(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function xv(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Ev(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Xu="ag-ui-chat:collapsed",Yu="ag-ui-chat:theme",mr=class extends HTMLElement{agentFactory=ka;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#ne().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...as(this.getPageMap,this.autoInjectPageMap),...this.#Pe()];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=ae;#t=new $n;#o=new Map;#r=new Set;#a;#s;#i;#l;#c;#p;#u;#h;#f;#k=null;#E;#g;#v;#D;#T;#w;#I;#A=null;#U;#B=null;#L=[];#C=null;#R={};#H=!1;#b=null;#y=null;#V=0;#G=null;#S=null;#N=null;#d="";#O="";#j=0;#q=[];#Q=[];#ee=[];#te=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#i=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#p=document.createElement("span"),this.#E=document.createElement("div"),this.#g=document.createElement("button"),this.#v=document.createElement("input"),this.#D=document.createElement("div"),this.#U=document.createElement("span"),this.#T=document.createElement("button"),this.#w=document.createElement("button"),this.#I=document.createElement("div"),this.#u=new mi(e=>this.#$e(e)),this.#h=new vi({onSelect:e=>{this.#ze(e)},onNew:()=>{this.newChat(),this.#F()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#F()},onDelete:e=>{this.#Be(e)}}),this.#f=new or((e,n)=>{this.#ye(e,n)})}#W(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#k===null&&(this.#k=new hr(e,()=>this.headers)),this.#k)}async#ye(e,n){let r=this.#W();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="";let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:[]});await new Mn({agent:s,handlers:this.#he(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:l=>this.#pe(l),resolveInterrupts:l=>this.#fe(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#xe(){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)}get sharedState(){return this.#C?.state??this.#R}set sharedState(e){this.#R={...e},this.#C?.setState(this.#R)}registerPageState(e){for(let n of Rr(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#Ee(){return this.routeMap.length===0?[]:cs(()=>this.routeMap,()=>this.navigate)}#Te(){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:[],[Le]:"Read the page"},handler:()=>e()}]}#we(){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 ss(n,r=>this.resolvePageTarget(r))}#ne(){return[...this.#Ee(),...this.#Te(),...this.#we(),...this.#Se()]}#Se(){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.#_e(e)}]:[]}async#_e(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#b=new AbortController;let i=this.#b.signal;this.#x();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await ra(this.#_(),r,{signal:i,strings:this.#e});return this.#b=null,this.#m(),this.#i.scrollTop=this.#i.scrollHeight,s}#re(e){let n=this.#ne().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===Ve.INLINE||e===Ve.MINIMAL||e===Ve.COMPACT?e:Ve.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#O=this.id!==""?this.id:this.endpoint,this.#e=us({...this.#Ae(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#oe(Yu);e!==null&&this.setAttribute("theme",e)}this.#We(),this.#h.setStrings(this.#e),this.#f.setStrings(this.#e),this.#oe(Xu)==="1"&&this.setAttribute("collapsed",""),this.#ce(),this.#He(),this.#Ue(),this.#O!==""&&this.conversationStore instanceof ht&&(this.conversationStore=new ht(this.#O)),this.#De(),this.#ke(),this.#Ce(),this.#d=this.conversationStore.threadId(),this.#se()}disconnectedCallback(){this.#M(),this.#A?.dispose(),this.#B?.dispose()}#Ae(){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{}}#ke(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ie(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#A=new ii({upload:n,maxBytes:this.#Oe(),accept:r,strings:this.#e}),this.#D.appendChild(this.#A.element),this.#v.accept=r,this.#g.hidden=!1,this.#Le()}#Ie(e){return e===null?null:(n,r,o)=>Ca(n,{url:e,headers:this.headers,onProgress:r,signal:o})}#Ce(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Ne(e);n!==null&&(this.#B=new bi({transcribe:n,onText:r=>this.#Re(r),strings:this.#e}),this.#U.appendChild(this.#B.element))}#Ne(e){return e===null?null:n=>Ia(n,{url:e,headers:this.headers})}#Re(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#ue(),this.#l.focus()}#Oe(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return qi;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:qi}#Me(){let e=this.#v.files;if(e!==null)for(let n of Array.from(e))this.#A?.add(n);this.#v.value=""}#Le(){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.#A?.add(r)})}#Pe(){return this.#L.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#L.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
|
|
1579
|
+
${n}`):(r.textContent=Tv(this.#o)[e],o.textContent=n),r.addEventListener("click",()=>{let i=o.hidden;o.hidden=!i,r.setAttribute("aria-expanded",String(i))}),this.element.append(r,o)}};var xi=class{element;#n;#e;#t;#o="idle";#r=null;#a=null;#s=[];#i=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ae,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.#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.#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.#i=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#p(e){if(this.#i)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.#o=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 Ei=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Ln=class{#n;#e;#t;#o;#r;#a;#s;#i;#l=!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.#a=e.resolveInterrupts??null,this.#s=e.onPersist??(()=>{}),this.#i=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:De(),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:De(),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||Sv(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<Xi;n+=1){if(this.#l)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#o()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#s(this.#n.messages),this.#l)return;if(!o.terminal)throw new Ei(this.#i);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#l)return;e=eu(o.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:De(),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:o}){r.onTextDelta(o)},onTextMessageEndEvent({textMessageBuffer:o}){r.onTextEnd(o)},onToolCallEndEvent({event:o,toolCallName:i,toolCallArgs:s}){let a={id:o.toolCallId,name:i,args:s};e.push(a),r.onToolCall(a)},onToolCallResultEvent({event:o}){r.onToolResult(o.toolCallId,o.content)},onActivitySnapshotEvent({event:o}){r.onActivity(o.activityType,o.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:o}){r.onReasoningDelta(o)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(o){n.terminal=!0,o.outcome==="interrupt"&&(n.interrupts=o.interrupts)},onRunErrorEvent({event:o}){n.terminal=!0,n.errored=!0,r.onError(o.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Sv(t){return t instanceof Error&&t.name==="AbortError"}function _a(t){let e=t.attachments;return Array.isArray(e)?e.filter(wv):[]}function wv(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 Aa="ag-ui-chat",hr="thread",ka="threads",Ti="messages:",Si="checkpoint:",_v=60,Av=100,kv="New conversation",mt=class{#n;constructor(e=""){this.#n=e===""?Aa:`${Aa}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(hr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=De();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#s(this.#r(Ti+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(Ti+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#s(this.#r(Si+e))}saveCheckpoint(e,n){let r=this.#r(Si+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Ti+e)),sessionStorage.removeItem(this.#r(Si+e)),this.#o(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(hr))===e&&sessionStorage.removeItem(this.#r(hr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(hr),e)}renameThread(e,n){let r=this.#t(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#o(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=Cv(n),s=Date.now();o===void 0?r.push({threadId:e,title:qu(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=qu(n))),this.#o(r)}#t(){return this.#s(this.#r(ka))??[]}#o(e){let n=this.#r(ka);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Aa}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let o=sessionStorage.key(r);if(o===null||!o.startsWith(e))continue;let i=o.slice(e.length);Iv(i)&&n.push([o,this.#r(i)])}for(let[r,o]of n){let i=sessionStorage.getItem(r);i!==null&&sessionStorage.getItem(o)===null&&sessionStorage.setItem(o,i),sessionStorage.removeItem(r)}}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Iv(t){return t===hr||t===ka||t.startsWith(Ti)||t.startsWith(Si)}function qu(t){for(let e of t)if(e.role==="user"){let n=Wu(e.content);if(n!=="")return Xu(n,_v)}return kv}function Cv(t){for(let e of[...t].reverse()){let n=Wu(e.content);if(n!=="")return Xu(n,Av)}return""}function Wu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Xu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Ia(t){return new tu({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var mr=class{#n;#e;#t;#o=new Set;#r=new Map;constructor(e,n=()=>({}),r=new mt){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.#a();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.#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}}#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 o=this.#e();try{await fetch(`${this.#n}${encodeURIComponent(e)}/`,{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var gr=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 Ca(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 Nv(r));let o=await r.json();if(typeof o=="object"&&o!==null&&typeof o.text=="string")return o.text;throw new Error("transcription returned an unreadable response")}async function Nv(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Na(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url);for(let[l,u]of Object.entries(e.headers??{}))i.setRequestHeader(l,u);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Rv(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Ov(i)))}),i.addEventListener("error",()=>r(new Error("upload failed"))),i.addEventListener("abort",()=>r(new Error("upload cancelled")));let a=e.signal;a!==void 0&&a.addEventListener("abort",()=>i.abort()),i.send(o)})}function Rv(t){if(typeof t!="object"||t===null)throw new Error("not an object");let e=t,n=e.id,r=e.name,o=e.mime,i=e.size,s=e.url;if(typeof n!="string"||typeof r!="string"||typeof o!="string"||typeof i!="number")throw new Error("missing fields");return typeof s=="string"?{id:n,name:r,mime:o,size:i,url:s}:{id:n,name:r,mime:o,size:i}}function Ov(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Yu="ag-ui-chat:collapsed",Ku="ag-ui-chat:theme",vr=class extends HTMLElement{agentFactory=Ia;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#oe().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...cs(this.getPageMap,this.autoInjectPageMap),...this.#Ue()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new mt;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=ae;#t=new zn;#o=new Map;#r=new Set;#a;#s;#i;#l;#c;#p;#u;#h;#f;#k=null;#E;#g;#v;#U;#T;#S;#I;#A=null;#H;#B=null;#L=[];#C=null;#R={};#G=!1;#V=null;#b=null;#y=null;#j=0;#F=null;#w=null;#N=null;#d="";#O="";#q=0;#W=[];#te=[];#ne=[];#re=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#s=document.createElement("div"),this.#i=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#p=document.createElement("span"),this.#E=document.createElement("div"),this.#g=document.createElement("button"),this.#v=document.createElement("input"),this.#U=document.createElement("div"),this.#H=document.createElement("span"),this.#T=document.createElement("button"),this.#S=document.createElement("button"),this.#I=document.createElement("div"),this.#u=new vi(e=>this.#Be(e)),this.#h=new yi({onSelect:e=>{this.#Ve(e)},onNew:()=>{this.newChat(),this.#$()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#$()},onDelete:e=>{this.#je(e)}}),this.#f=new ir((e,n)=>{this.#Ee(e,n)})}#X(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#k===null&&(this.#k=new gr(e,()=>this.headers)),this.#k)}async#Ee(e,n){let r=this.#X();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="";let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:[]});await new Ln({agent:s,handlers:this.#ve(),getTools:()=>this.getTools(),getContext:()=>this.#ce(),executeTool:l=>this.#me(l),resolveInterrupts:l=>this.#ge(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Te(){let e=this.#X();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)}get sharedState(){return this.#C?.state??this.#R}set sharedState(e){this.#R={...e},this.#C?.setState(this.#R)}registerPageState(e){for(let n of Lr(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#Se(){return this.routeMap.length===0?[]:ds(()=>this.routeMap,()=>this.navigate)}#we(){let e=this.getPageMap;return e===null?[]:[{name:Wi,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:[],[Le]:"Read the page"},handler:()=>e()}]}#_e(){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 ls(n,r=>this.resolvePageTarget(r))}#oe(){return[...this.#Se(),...this.#we(),...this.#_e(),...this.#Ae()]}#Ae(){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.#ke(e)}]:[]}async#ke(e){let r={question:typeof e.question=="string"?e.question:""},o=e.options;Array.isArray(o)&&(r.options=o.filter(a=>typeof a=="string")),e.allow_custom===!0&&(r.allowCustom=!0),this.#b=new AbortController;let i=this.#b.signal;this.#x();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await ia(this.#_(),r,{signal:i,strings:this.#e});return this.#b=null,this.#m(),this.#i.scrollTop=this.#i.scrollHeight,s}#ie(e){let n=this.#oe().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===je.INLINE||e===je.MINIMAL||e===je.COMPACT?e:je.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#O=this.id!==""?this.id:this.endpoint,this.#e=ps({...this.#Ie(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#se(Ku);e!==null&&this.setAttribute("theme",e)}this.#Ze(),this.#h.setStrings(this.#e),this.#f.setStrings(this.#e),this.#se(Yu)==="1"&&this.setAttribute("collapsed",""),this.#pe(),this.#Fe(),this.#Ge(),this.#O!==""&&this.conversationStore instanceof mt&&(this.conversationStore=new mt(this.#O)),this.#He(),this.#Ce(),this.#Re(),this.#d=this.conversationStore.threadId(),this.#le()}disconnectedCallback(){this.#M(),this.#A?.dispose(),this.#B?.dispose()}#Ie(){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{}}#Ce(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ne(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"";this.#A=new li({upload:n,maxBytes:this.#Le(),accept:r,strings:this.#e}),this.#U.appendChild(this.#A.element),this.#v.accept=r,this.#g.hidden=!1,this.#De()}#Ne(e){return e===null?null:(n,r,o)=>Na(n,{url:e,headers:this.headers,onProgress:r,signal:o})}#Re(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Oe(e);n!==null&&(this.#B=new xi({transcribe:n,onText:r=>this.#Me(r),strings:this.#e}),this.#H.appendChild(this.#B.element))}#Oe(e){return e===null?null:n=>Ca(n,{url:e,headers:this.headers})}#Me(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#fe(),this.#l.focus()}#Le(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Yi;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Yi}#Pe(){let e=this.#v.files;if(e!==null)for(let n of Array.from(e))this.#A?.add(n);this.#v.value=""}#De(){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.#A?.add(r)})}#Ue(){return this.#L.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#L.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
|
|
1579
1580
|
`)}
|
|
1580
|
-
Use the read_attachment tool with an id to read a file's contents.`}]}#De(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new fr(e,()=>this.headers,this.conversationStore))}async#Ue(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=ls(await n.json())}catch{}}setSkills(e){this.#te=e,this.#X()}#He(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#ee=this.#Ge(),this.#X(),this.#Fe()}#Ge(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Yi(JSON.parse(e))}catch{return[]}}async#Fe(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#Q=Yi(await n.json()),this.#X()}catch{}}#X(){let e=new Map;for(let n of[...this.#Q,...this.#ee,...this.#te])e.set(n.name,n);this.#u.setSkills([...e.values()])}#$e(e){let{text:n,missing:r}=rl(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.#Y(Xu),e?"1":"0"),this.#ce(),this.dispatchEvent(new CustomEvent(zi,{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.#Y(Yu),e),this.#ie()}#Y(e){return this.#O===""?e:`${e}:${this.#O}`}#oe(e){let n=sessionStorage.getItem(this.#Y(e));return n!==null||this.#O===""?n:sessionStorage.getItem(e)}#ie(){let e=this.getAttribute("theme")==="dark";this.#T.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#M(),this.conversationStore.clear(this.#d),this.#K(),this.#d=this.conversationStore.threadId(),this.#P(!1)}#K(){this.#C=null,this.#y=null,this.#S=null,this.#N=null,this.#x(),this.#o.clear(),this.#r.clear(),this.#q=[],this.#L=[],this.#A?.clear(),this.#i.replaceChildren(this.#I),this.#m()}async#ze(e){e!==this.#d&&(this.#M(),this.#K(),this.conversationStore.setActiveThread(e),this.#d=e,this.#P(!1),await this.#se())}#Be(e){let n=e===this.#d;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#K(),this.#d=this.conversationStore.threadId(),this.#P(!1)),this.#F()}async#F(){this.#h.setThreads(await this.conversationStore.listThreads(),this.#d)}async#se(){this.#j+=1;let e=this.#j,n=await this.conversationStore.loadMessages(this.#d);if(e!==this.#j)return;if(n!==null){this.#q=n;for(let o of n)this.#Ve(o)}let r=this.conversationStore.loadCheckpoint(this.#d);r!==null&&await this.#qe(r)}#Ve(e){let n=typeof e.content=="string"?e.content:"";if(e.role===et.USER){let r=Sa(e);if(n!==""||r.length>0){let o=this.appendMessage(et.USER,n);r.length>0&&o.appendChild(ps(r))}return}if(e.role===et.ASSISTANT){n!==""&&this.appendMessage(et.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r){let i={id:o.id,name:o.function.name,args:this.#je(o.function.arguments)};this.#ve(i)||this.#J(i)}return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(fe.DONE,e.content)}}#je(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#ae(e){this.getAttribute("data-text-animation")==="word"&&$u(e)}async#qe(e){this.conversationStore.saveCheckpoint(this.#d,null);let n=this.#de();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===et.ASSISTANT?(r.innerHTML=hi(n,{allowImages:this.allowImages}),this.#_().appendChild(r)):(this.#S=null,r.textContent=n,this.#i.appendChild(r)),this.#m(),this.#i.scrollTop=this.#i.scrollHeight,r}#_(){if(this.#S===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#S=e,this.#i.appendChild(e),this.#m()}return this.#S}#We(){let e=document.createElement("style");e.textContent=Bu,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.#le("icon","icon",null));let o=document.createElement("slot");o.name="header-actions";let i=document.createElement("div");i.className="header-controls",i.setAttribute("part","header-controls");let s=this.#$("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#F(),this.#h.open()});let a=this.#$("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>{this.#xe(),this.#f.open()});let l=this.#$("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#$("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#W()!==null?i.append(s,a,l):i.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(),i.append(this.#T)),i.append(c),n.append(r,o,i),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.#I.className="empty",this.#I.setAttribute("part","empty");let f=document.createElement("slot");f.name="empty",this.#I.append(f),this.#i.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.#Xe(h)),this.#l.addEventListener("input",()=>this.#ue()),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.#H){this.#M();return}this.#Z()}),this.#E.className="skill-hint",this.#E.setAttribute("part","skill-hint"),this.#E.hidden=!0,this.#g.className="attach-btn",this.#g.type="button",this.#g.setAttribute("part","attach-button"),this.#g.textContent="\u{1F4CE}",this.#g.title=this.#e.attachFiles,this.#g.setAttribute("aria-label",this.#e.attachFiles),this.#g.hidden=!0,this.#g.addEventListener("click",()=>this.#v.click()),this.#v.className="attach-input",this.#v.type="file",this.#v.multiple=!0,this.#v.hidden=!0,this.#v.addEventListener("change",()=>this.#Me()),this.#D.className="attachment-slot",this.#U.className="voice-slot";let y=document.createElement("slot");y.name="footer",m.append(this.#g,this.#U,this.#l,this.#c,this.#v),this.#s.append(n,this.#i,this.#u.palette,this.#u.chips,this.#E,this.#D,m,y,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.#le("launcher","launcher-icon","\u{1F4AC}")),this.#w.addEventListener("click",()=>this.setCollapsed(!1)),this.#a.append(e,this.#s,this.#w)}#$(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n),o.textContent=r,o}#le(e,n,r){let o=document.createElement("span");o.className="icon-holder",o.setAttribute("part",n);let i=document.createElement("slot");i.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",i.append(a)}else r!==null&&i.append(document.createTextNode(r));return o.append(i),o}#ce(){this.#w.setAttribute("aria-expanded",String(!this.collapsed))}#m(){this.#I.hidden=this.#i.childElementCount>1}#ue(){this.#u.onInput(this.#l.value),this.#E.hidden=!0}#Xe(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#H){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#Z())}#M(){this.#b?.abort(),this.#C?.cancel()}#P(e){this.#H=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.#H)return;let e=this.#l.value.trim(),n=this.#A?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(et.USER,e);n.length>0&&r.appendChild(ps(n)),this.#l.value="",this.#A?.clearReady(),this.#L=n,this.dispatchEvent(new CustomEvent($i,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#Ye(e,n)}async#Ye(e,n){this.endpoint!==""&&await this.#de().send(e,n)}#de(){if(this.#C===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:this.#q,initialState:this.#R});this.#C=new Mn({agent:e,handlers:this.#he(),getTools:()=>this.getTools(),getContext:()=>this.getContext(),executeTool:n=>this.#pe(n),resolveInterrupts:n=>this.#fe(n),onPersist:n=>this.conversationStore.saveMessages(this.#d,n),onStateChanged:n=>this.#Ke(n),connectionLostMessage:this.#e.connectionLost})}return this.#C}#Ke(e){this.#R={...e},this.dispatchEvent(new CustomEvent(Bi,{detail:{state:this.#R},bubbles:!0,composed:!0}))}async#Ze(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Ki(n.parameters)}async#pe(e){if(Ku(e)!==null)return null;let n=this.#J(e);this.#o.delete(e.id);let r=this.#re(e.name);if(r===null)return this.#r.has(e.id)||n.settle(fe.DONE,this.#e.noResult),null;if(await this.#Ze(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Vi];typeof s=="string"&&(i.message=s),this.#b=new AbortController;let a=ta(this.#i,i,{signal:this.#b.signal,strings:this.#e});this.#m(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#b=null,!l){let c=this.#e.declinedAction;return n.settle(fe.DECLINED,c),this.#z(),{content:c}}}let o=Zi(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#d,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(fe.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(fe.DONE,s),this.#z(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#d,null);let s=i instanceof Error?i.message:String(i);return n.settle(fe.ERROR,s),this.#z(),{content:`Error: ${s}`,error:s}}}async#fe(e){let n={};this.#b=new AbortController,this.#x();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#o.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#b.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await ds(this.#_(),o,{signal:a,strings:this.#e});this.#m(),this.#i.scrollTop=this.#i.scrollHeight,l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(fe.DECLINED,this.#e.declinedAction))}return this.#b=null,n}#he(){return{onRunStart:()=>{this.#P(!0),this.#_(),this.#z()},onReasoningStart:()=>{this.#x(),this.#me()},onReasoningDelta:e=>{this.#me().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#x(),this.#N?.collapse(),this.#ge(e),this.#V+=1},onTextEnd:e=>{let n=this.#ge(e);this.#V<=1&&this.#ae(n),this.#y=null},onToolCall:e=>{this.#x(),!this.#ve(e)&&this.#J(e)},onActivity:(e,n)=>{if(e!==Wi)return;let r=Tv(n);r!==null&&this.#be("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(fe.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#x(),this.#y=null},onError:e=>{this.#x(),this.#ae(this.appendMessage(et.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#y=null},onCancelled:()=>{this.#x(),this.#Je(),this.#y=null},onSettled:()=>{this.#x(),this.#P(!1),this.#y=null,this.#L=[];for(let e of this.#o.values())e.settled||e.settle(fe.DONE,this.#e.noResult);this.#S!==null&&this.#S.childElementCount===0&&(this.#S.remove(),this.#m()),this.#S=null,this.#N=null}}}#Je(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#_().appendChild(e),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}#z(){if(this.#G!==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.#G=e,this.#_().appendChild(e),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}#x(){this.#G?.remove(),this.#G=null}#me(){if(this.#N===null){this.#N=new gi(this.#e);let e=this.#_();e.insertBefore(this.#N.element,e.firstChild),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}return this.#N}#ge(e){return this.#y===null&&(this.#y=this.appendMessage(et.ASSISTANT,""),this.#V=0),this.#y.innerHTML=hi(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#y}#ve(e){let n=Ku(e);return n===null?!1:(this.#be("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#be(e,n,r){this.#_().appendChild(zu(e,n,r)),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}#J(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#re(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??na(e.name),i=new dr(e.name,e.args,this.toolDisplay,o,this.#e);return this.#o.set(e.id,i),this.#_().appendChild(i.element),this.#m(),this.#i.scrollTop=this.#i.scrollHeight,i}};function Ku(t){if(t.name!==Xi)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function Tv(t){let e=t?.removed;return typeof e=="number"?e:null}function wv(){customElements.get(Ir)===void 0&&customElements.define(Ir,mr)}async function Sv(t,e,n={}){lt(t),await es(t,{flashMs:n.flashMs??0}),await Ji(t,e,n)}async function _v(t,e={}){lt(t),await Qi(t,e)}async function Av(t,e={}){lt(t),await ns(t,e)}async function kv(t,e,n={}){lt(t),await rs(t,e,n)}async function Iv(t,e,n={}){lt(t),await os(t,e,n)}function Cv(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?zn(t,!!e):Nt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Nv="0.15.0";export{mr as AgUiChat,Mn as AgUiClient,Wi as COMPACTION_ACTIVITY_TYPE,or as CheckpointMenu,$n as ClientToolRegistry,yi as ConnectionLostError,ae as DEFAULT_UI_STRINGS,Ir as ELEMENT_TAG,Xi as LOAD_CAPABILITY_TOOL,ji as MAX_TOOL_ROUNDS,et as MESSAGE_ROLE,is as PAGE_ACTIONS,fr as RemoteConversationStore,hr as RunIndex,Bi as STATE_EVENT,$i as SUBMIT_EVENT,ht as SessionStorageStore,zi as TOGGLE_EVENT,fe as TOOL_CALL_STATUS,Ve as TOOL_DISPLAY,dr as ToolCallCard,Nv as VERSION,Vi as X_CONFIRM_KEY,Gn as X_DESTRUCTIVE_KEY,Fn as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,_v as clickElement,ka as createHttpAgent,ss as createPageActionTools,as as createPageMapContext,Rr as createPageStateTools,cs as createRouteTools,Dd as createStateHookTools,wv as defineAgUiChat,Sv as fillField,es as focusWithFlash,Qi as highlightThenClick,Ki as isDestructive,Zi as isNavigates,us as mergeUiStrings,Sa as messageAttachments,ls as parseToolCatalog,sl as prefersReducedMotion,Av as pressButton,ns as pressThenClick,na as prettifyToolName,hi as renderMarkdown,ds as requestApproval,ta as requestConfirmation,ra as requestQuestion,lt as scrollIntoCenterView,kv as selectControl,rs as selectOption,Cv as setControlValue,zn as setNativeChecked,Nt as setNativeValue,Iv as toggleCheckbox,os as toggleControl,Ia as transcribeAudio,Ji as typeInto,Ca as uploadAttachment};
|
|
1581
|
+
Use the read_attachment tool with an id to read a file's contents.`}]}#He(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new mr(e,()=>this.headers,this.conversationStore))}async#Ge(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=us(await n.json())}catch{}}setSkills(e){this.#re=e,this.#Y()}#Fe(){this.#u.enableChips(this.getAttribute("data-prompt-chips")==="true"),this.#u.enableSlash(this.getAttribute("data-slash-commands")==="true"),this.#ne=this.#$e(),this.#Y(),this.#ze()}#$e(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Ji(JSON.parse(e))}catch{return[]}}async#ze(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#te=Ji(await n.json()),this.#Y()}catch{}}#Y(){let e=new Map;for(let n of[...this.#te,...this.#ne,...this.#re])e.set(n.name,n);this.#u.setSkills([...e.values()])}#Be(e){let{text:n,missing:r}=ol(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.#J():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.#K(Yu),e?"1":"0"),this.#pe(),this.dispatchEvent(new CustomEvent(Vi,{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.#K(Ku),e),this.#ae()}#K(e){return this.#O===""?e:`${e}:${this.#O}`}#se(e){let n=sessionStorage.getItem(this.#K(e));return n!==null||this.#O===""?n:sessionStorage.getItem(e)}#ae(){let e=this.getAttribute("theme")==="dark";this.#T.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#M(),this.conversationStore.clear(this.#d),this.#Z(),this.#d=this.conversationStore.threadId(),this.#P(!1)}#Z(){this.#C=null,this.#y=null,this.#w=null,this.#N=null,this.#x(),this.#o.clear(),this.#r.clear(),this.#W=[],this.#L=[],this.#A?.clear(),this.#i.replaceChildren(this.#I),this.#m()}async#Ve(e){e!==this.#d&&(this.#M(),this.#Z(),this.conversationStore.setActiveThread(e),this.#d=e,this.#P(!1),await this.#le())}#je(e){let n=e===this.#d;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#Z(),this.#d=this.conversationStore.threadId(),this.#P(!1)),this.#$()}async#$(){this.#h.setThreads(await this.conversationStore.listThreads(),this.#d)}async#le(){this.#q+=1;let e=this.#q,n=await this.conversationStore.loadMessages(this.#d);if(e!==this.#q)return;if(n!==null){this.#W=n;for(let o of n)this.#Xe(o)}let r=this.conversationStore.loadCheckpoint(this.#d);if(r!==null){await this.#Ke(r);return}this.#We(n)}#ce(){return this.#V=window.location.href,this.getContext()}#qe(){return this.#V!==null&&this.#V!==window.location.href}#We(e){let n=e?.at(-1);n===void 0||n.role!==Ve.USER||this.#Q("\u26A0",this.#e.runInterrupted,"interrupted")}#Xe(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ve.USER){let r=_a(e);if(n!==""||r.length>0){let o=this.appendMessage(Ve.USER,n);r.length>0&&o.appendChild(hs(r))}return}if(e.role===Ve.ASSISTANT){n!==""&&this.appendMessage(Ve.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r){let i={id:o.id,name:o.function.name,args:this.#Ye(o.function.arguments)};this.#xe(i)||this.#ee(i)}return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(pe.DONE,e.content)}}#Ye(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#ue(e){this.getAttribute("data-text-animation")==="word"&&zu(e)}async#Ke(e){this.conversationStore.saveCheckpoint(this.#d,null);let n=this.#he();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===Ve.ASSISTANT?(r.innerHTML=gi(n,{allowImages:this.allowImages}),this.#_().appendChild(r)):(this.#w=null,r.textContent=n,this.#i.appendChild(r)),this.#m(),this.#i.scrollTop=this.#i.scrollHeight,r}#_(){if(this.#w===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#w=e,this.#i.appendChild(e),this.#m()}return this.#w}#Ze(){let e=document.createElement("style");e.textContent=Vu,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.#de("icon","icon",null));let o=document.createElement("slot");o.name="header-actions";let i=document.createElement("div");i.className="header-controls",i.setAttribute("part","header-controls");let s=this.#z("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#$(),this.#h.open()});let a=this.#z("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>{this.#Te(),this.#f.open()});let l=this.#z("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let u=this.#z("collapse",this.#e.collapse,"\u2014");u.addEventListener("click",()=>this.toggleCollapsed()),this.#X()!==null?i.append(s,a,l):i.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.#ae(),i.append(this.#T)),i.append(u),n.append(r,o,i),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.#I.className="empty",this.#I.setAttribute("part","empty");let f=document.createElement("slot");f.name="empty",this.#I.append(f),this.#i.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.#Je(h)),this.#l.addEventListener("input",()=>this.#fe()),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.#G){this.#M();return}this.#J()}),this.#E.className="skill-hint",this.#E.setAttribute("part","skill-hint"),this.#E.hidden=!0,this.#g.className="attach-btn",this.#g.type="button",this.#g.setAttribute("part","attach-button"),this.#g.textContent="\u{1F4CE}",this.#g.title=this.#e.attachFiles,this.#g.setAttribute("aria-label",this.#e.attachFiles),this.#g.hidden=!0,this.#g.addEventListener("click",()=>this.#v.click()),this.#v.className="attach-input",this.#v.type="file",this.#v.multiple=!0,this.#v.hidden=!0,this.#v.addEventListener("change",()=>this.#Pe()),this.#U.className="attachment-slot",this.#H.className="voice-slot";let y=document.createElement("slot");y.name="footer",m.append(this.#g,this.#H,this.#l,this.#c,this.#v),this.#s.append(n,this.#i,this.#u.palette,this.#u.chips,this.#E,this.#U,m,y,this.#h.element,this.#f.element),this.#S.className="rail",this.#S.type="button",this.#S.setAttribute("part","launcher"),this.#S.setAttribute("aria-label",this.#e.expand),this.#S.append(this.#de("launcher","launcher-icon","\u{1F4AC}")),this.#S.addEventListener("click",()=>this.setCollapsed(!1)),this.#a.append(e,this.#s,this.#S)}#z(e,n,r){let o=document.createElement("button");return o.type="button",o.className=`header-btn header-btn--${e}`,o.setAttribute("part",`header-button ${e}-button`),o.title=n,o.setAttribute("aria-label",n),o.textContent=r,o}#de(e,n,r){let o=document.createElement("span");o.className="icon-holder",o.setAttribute("part",n);let i=document.createElement("slot");i.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",i.append(a)}else r!==null&&i.append(document.createTextNode(r));return o.append(i),o}#pe(){this.#S.setAttribute("aria-expanded",String(!this.collapsed))}#m(){this.#I.hidden=this.#i.childElementCount>1}#fe(){this.#u.onInput(this.#l.value),this.#E.hidden=!0}#Je(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#G){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#J())}#M(){this.#b?.abort(),this.#C?.cancel()}#P(e){this.#G=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#J(){if(this.#G)return;let e=this.#l.value.trim(),n=this.#A?.readyRefs()??[];if(e===""&&n.length===0)return;let r=this.appendMessage(Ve.USER,e);n.length>0&&r.appendChild(hs(n)),this.#l.value="",this.#A?.clearReady(),this.#L=n,this.dispatchEvent(new CustomEvent(Bi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#Qe(e,n)}async#Qe(e,n){this.endpoint!==""&&await this.#he().send(e,n)}#he(){if(this.#C===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#d,initialMessages:this.#W,initialState:this.#R});this.#C=new Ln({agent:e,handlers:this.#ve(),getTools:()=>this.getTools(),getContext:()=>this.#ce(),executeTool:n=>this.#me(n),resolveInterrupts:n=>this.#ge(n),onPersist:n=>this.conversationStore.saveMessages(this.#d,n),onStateChanged:n=>this.#et(n),connectionLostMessage:this.#e.connectionLost})}return this.#C}#et(e){this.#R={...e},this.dispatchEvent(new CustomEvent(ji,{detail:{state:this.#R},bubbles:!0,composed:!0}))}async#tt(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:Qi(n.parameters)}async#me(e){if(Zu(e)!==null)return null;let n=this.#ee(e);this.#o.delete(e.id);let r=this.#ie(e.name);if(r===null)return this.#r.has(e.id)||n.settle(pe.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Wi&&!Rr(r.parameters)&&this.#qe()){let i=this.#e.pageMoved;return n.settle(pe.ERROR,i),this.#D(),{content:`Error: ${i}`,error:i}}if(await this.#tt(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[qi];typeof s=="string"&&(i.message=s),this.#b=new AbortController;let a=ra(this.#i,i,{signal:this.#b.signal,strings:this.#e});this.#m(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#b=null,!l){let u=this.#e.declinedAction;return n.settle(pe.DECLINED,u),this.#D(),{content:u}}}let o=Rr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#d,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(pe.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(pe.DONE,s),this.#D(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#d,null);let s=i instanceof Error?i.message:String(i);return n.settle(pe.ERROR,s),this.#D(),{content:`Error: ${s}`,error:s}}}async#ge(e){let n={};this.#b=new AbortController,this.#x();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#o.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#b.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await fs(this.#_(),o,{signal:a,strings:this.#e});this.#m(),this.#i.scrollTop=this.#i.scrollHeight,l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(pe.DECLINED,this.#e.declinedAction))}return this.#b=null,n}#ve(){return{onRunStart:()=>{this.#P(!0),this.#_(),this.#D()},onReasoningStart:()=>{this.#x(),this.#be()},onReasoningDelta:e=>{this.#be().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#x(),this.#N?.collapse(),this.#ye(e),this.#j+=1},onTextEnd:e=>{let n=this.#ye(e);this.#j<=1&&this.#ue(n),this.#y=null},onToolCall:e=>{this.#x(),!this.#xe(e)&&this.#ee(e)},onActivity:(e,n)=>{if(e!==Ki)return;let r=Mv(n);r!==null&&this.#Q("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(pe.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#x(),this.#y=null},onError:e=>{this.#x(),this.#ue(this.appendMessage(Ve.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#y=null},onCancelled:()=>{this.#x(),this.#nt(),this.#y=null},onSettled:()=>{this.#x(),this.#P(!1),this.#y=null,this.#L=[];for(let e of this.#o.values())e.settled||e.settle(pe.DONE,this.#e.noResult);this.#w!==null&&this.#w.childElementCount===0&&(this.#w.remove(),this.#m()),this.#w=null,this.#N=null}}}#nt(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#_().appendChild(e),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}#D(){if(this.#F!==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.#F=e,this.#_().appendChild(e),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}#x(){this.#F?.remove(),this.#F=null}#be(){if(this.#N===null){this.#N=new bi(this.#e);let e=this.#_();e.insertBefore(this.#N.element,e.firstChild),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}return this.#N}#ye(e){return this.#y===null&&(this.#y=this.appendMessage(Ve.ASSISTANT,""),this.#j=0),this.#y.innerHTML=gi(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#y}#xe(e){let n=Zu(e);return n===null?!1:(this.#Q("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#Q(e,n,r){this.#_().appendChild(Bu(e,n,r)),this.#m(),this.#i.scrollTop=this.#i.scrollHeight}#ee(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#ie(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??oa(e.name),i=new fr(e.name,e.args,this.toolDisplay,o,this.#e);return this.#o.set(e.id,i),this.#_().appendChild(i.element),this.#m(),this.#i.scrollTop=this.#i.scrollHeight,i}};function Zu(t){if(t.name!==Zi)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function Mv(t){let e=t?.removed;return typeof e=="number"?e:null}function Lv(){customElements.get(Nr)===void 0&&customElements.define(Nr,vr)}async function Pv(t,e,n={}){lt(t),await ns(t,{flashMs:n.flashMs??0}),await es(t,e,n)}async function Dv(t,e={}){lt(t),await ts(t,e)}async function Uv(t,e={}){lt(t),await os(t,e)}async function Hv(t,e,n={}){lt(t),await is(t,e,n)}async function Gv(t,e,n={}){lt(t),await ss(t,e,n)}function Fv(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Bn(t,!!e):Rt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var $v="0.16.0";export{vr as AgUiChat,Ln as AgUiClient,Ki as COMPACTION_ACTIVITY_TYPE,ir as CheckpointMenu,zn as ClientToolRegistry,Ei as ConnectionLostError,ae as DEFAULT_UI_STRINGS,Nr as ELEMENT_TAG,Zi as LOAD_CAPABILITY_TOOL,Xi as MAX_TOOL_ROUNDS,Ve as MESSAGE_ROLE,as as PAGE_ACTIONS,mr as RemoteConversationStore,gr as RunIndex,ji as STATE_EVENT,Bi as SUBMIT_EVENT,mt as SessionStorageStore,Vi as TOGGLE_EVENT,pe as TOOL_CALL_STATUS,je as TOOL_DISPLAY,fr as ToolCallCard,$v as VERSION,qi as X_CONFIRM_KEY,Fn as X_DESTRUCTIVE_KEY,$n as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,Dv as clickElement,Ia as createHttpAgent,ls as createPageActionTools,cs as createPageMapContext,Lr as createPageStateTools,ds as createRouteTools,Ud as createStateHookTools,Lv as defineAgUiChat,Pv as fillField,ns as focusWithFlash,ts as highlightThenClick,Qi as isDestructive,Rr as isNavigates,ps as mergeUiStrings,_a as messageAttachments,us as parseToolCatalog,al as prefersReducedMotion,Uv as pressButton,os as pressThenClick,oa as prettifyToolName,gi as renderMarkdown,fs as requestApproval,ra as requestConfirmation,ia as requestQuestion,lt as scrollIntoCenterView,Hv as selectControl,is as selectOption,Fv as setControlValue,Bn as setNativeChecked,Rt as setNativeValue,Gv as toggleCheckbox,ss as toggleControl,Ca as transcribeAudio,es as typeInto,Na as uploadAttachment};
|
|
1581
1582
|
/*! Bundled license information:
|
|
1582
1583
|
|
|
1583
1584
|
fast-json-patch/module/helpers.mjs:
|