@artooi/ag-ui-web-component 0.23.0 → 0.23.1
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 +73 -36
- package/README.md +7 -7
- package/dist/ag-ui-web-component.bundle.js +98 -117
- package/dist/ag-ui-web-component.bundle.js.map +3 -3
- package/dist/constants.d.ts +56 -85
- package/dist/constants.d.ts.map +1 -1
- package/dist/core/ag_ui_chat.d.ts +90 -127
- package/dist/core/ag_ui_chat.d.ts.map +1 -1
- package/dist/core/agui_client.d.ts +24 -30
- package/dist/core/agui_client.d.ts.map +1 -1
- package/dist/core/attachment.d.ts +9 -14
- package/dist/core/attachment.d.ts.map +1 -1
- package/dist/core/conversation_store.d.ts +20 -27
- package/dist/core/conversation_store.d.ts.map +1 -1
- package/dist/core/create_http_agent.d.ts +13 -15
- package/dist/core/create_http_agent.d.ts.map +1 -1
- package/dist/core/remote_conversation_store.d.ts +8 -9
- package/dist/core/remote_conversation_store.d.ts.map +1 -1
- package/dist/core/run_index.d.ts +11 -20
- package/dist/core/run_index.d.ts.map +1 -1
- package/dist/core/transcribe_audio.d.ts +8 -8
- package/dist/core/transcribe_audio.d.ts.map +1 -1
- package/dist/core/upload_attachment.d.ts +15 -18
- package/dist/core/upload_attachment.d.ts.map +1 -1
- package/dist/core/utils.d.ts +4 -6
- package/dist/core/utils.d.ts.map +1 -1
- package/dist/dom/animations.d.ts +22 -30
- package/dist/dom/animations.d.ts.map +1 -1
- package/dist/dom/dom_driver.d.ts +7 -7
- package/dist/dom/native_setter.d.ts +2 -2
- package/dist/dom/native_setter.d.ts.map +1 -1
- package/dist/index.js +290 -378
- package/dist/index.js.map +2 -2
- package/dist/skills/fill_template.d.ts +4 -5
- package/dist/skills/fill_template.d.ts.map +1 -1
- package/dist/skills/parse_skills.d.ts.map +1 -1
- package/dist/skills/skill.d.ts +7 -8
- package/dist/skills/skill.d.ts.map +1 -1
- package/dist/tools/client_tool_registry.d.ts +2 -2
- package/dist/tools/page_action_tools.d.ts +7 -10
- package/dist/tools/page_action_tools.d.ts.map +1 -1
- package/dist/tools/page_state.d.ts +5 -8
- package/dist/tools/page_state.d.ts.map +1 -1
- package/dist/tools/route_map.d.ts +7 -10
- package/dist/tools/route_map.d.ts.map +1 -1
- package/dist/ui/approval_card.d.ts +15 -20
- package/dist/ui/approval_card.d.ts.map +1 -1
- package/dist/ui/attach_copy_buttons.d.ts +4 -10
- package/dist/ui/attach_copy_buttons.d.ts.map +1 -1
- package/dist/ui/attachment_chips.d.ts +7 -10
- package/dist/ui/attachment_chips.d.ts.map +1 -1
- package/dist/ui/attachment_tray.d.ts +6 -6
- package/dist/ui/checkpoint_menu.d.ts +7 -8
- package/dist/ui/checkpoint_menu.d.ts.map +1 -1
- package/dist/ui/confirmation_card.d.ts +10 -15
- package/dist/ui/confirmation_card.d.ts.map +1 -1
- package/dist/ui/question_card.d.ts +12 -15
- package/dist/ui/question_card.d.ts.map +1 -1
- package/dist/ui/relative_time.d.ts +5 -7
- package/dist/ui/relative_time.d.ts.map +1 -1
- package/dist/ui/render_markdown.d.ts +8 -8
- package/dist/ui/render_markdown.d.ts.map +1 -1
- package/dist/ui/resize_handle.d.ts +21 -34
- package/dist/ui/resize_handle.d.ts.map +1 -1
- package/dist/ui/run_notice.d.ts +5 -7
- package/dist/ui/run_notice.d.ts.map +1 -1
- package/dist/ui/skills_menu.d.ts +4 -5
- package/dist/ui/skills_menu.d.ts.map +1 -1
- package/dist/ui/styles.d.ts +1 -1
- package/dist/ui/styles.d.ts.map +1 -1
- package/dist/ui/thoughts_block.d.ts +9 -11
- package/dist/ui/thoughts_block.d.ts.map +1 -1
- package/dist/ui/thread_drawer.d.ts +6 -5
- package/dist/ui/thread_drawer.d.ts.map +1 -1
- package/dist/ui/tool_call_card.d.ts +17 -25
- package/dist/ui/tool_call_card.d.ts.map +1 -1
- package/dist/ui/ui_strings.d.ts +6 -12
- package/dist/ui/ui_strings.d.ts.map +1 -1
- package/dist/ui/voice_input.d.ts +10 -11
- package/dist/ui/voice_input.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/constants.ts +58 -87
- package/src/core/ag_ui_chat.ts +239 -267
- package/src/core/agui_client.ts +60 -71
- package/src/core/attachment.ts +9 -14
- package/src/core/conversation_store.ts +25 -33
- package/src/core/create_http_agent.ts +18 -22
- package/src/core/remote_conversation_store.ts +14 -15
- package/src/core/run_index.ts +14 -23
- package/src/core/transcribe_audio.ts +9 -10
- package/src/core/upload_attachment.ts +18 -21
- package/src/core/utils.ts +4 -6
- package/src/dom/animations.ts +33 -43
- package/src/dom/dom_driver.ts +7 -7
- package/src/dom/native_setter.ts +11 -12
- package/src/skills/fill_template.ts +4 -5
- package/src/skills/parse_skills.ts +3 -4
- package/src/skills/skill.ts +7 -8
- package/src/tools/client_tool_registry.ts +2 -2
- package/src/tools/page_action_tools.ts +12 -15
- package/src/tools/page_state.ts +5 -8
- package/src/tools/route_map.ts +15 -19
- package/src/ui/approval_card.ts +15 -20
- package/src/ui/attach_copy_buttons.ts +9 -18
- package/src/ui/attachment_chips.ts +7 -10
- package/src/ui/attachment_tray.ts +6 -6
- package/src/ui/checkpoint_menu.ts +7 -8
- package/src/ui/confirmation_card.ts +10 -15
- package/src/ui/question_card.ts +12 -15
- package/src/ui/relative_time.ts +5 -7
- package/src/ui/render_markdown.ts +25 -51
- package/src/ui/resize_handle.ts +25 -38
- package/src/ui/run_notice.ts +9 -12
- package/src/ui/skills_menu.ts +4 -5
- package/src/ui/styles.ts +79 -98
- package/src/ui/thoughts_block.ts +11 -13
- package/src/ui/thread_drawer.ts +6 -5
- package/src/ui/tool_call_card.ts +22 -32
- package/src/ui/ui_strings.ts +6 -12
- package/src/ui/voice_input.ts +10 -11
- package/src/version.ts +1 -1
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
var jd=Object.defineProperty;var ji=(t,e)=>{for(var n in e)jd(t,n,{get:e[n],enumerable:!0})};var Or="ag-ui-chat",qi="ag-ui-submit",Wi="ag-ui-toggle",Xi="ag-ui-unread",Yi="ag-ui-state",Ki="ag-ui-attachments",je={USER:"user",ASSISTANT:"assistant"},Fn="x-destructive",Zi="x-confirm",Le="x-summary",$n="x-navigates",Ji="read_page",Qi=10,pe={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Pe={UPLOADING:"uploading",READY:"ready",ERROR:"error"},es=10*1024*1024,pn={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"},ts="compaction",ns="load_capability",hl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19.5V5m-6.5 6.5L12 5l6.5 6.5"/></svg>',fl='<svg class="glyph glyph--solid" viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2.5"/></svg>',ml='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M17 8.5V15a5 5 0 0 1-10 0V7a3 3 0 0 1 6 0v7.5a1 1 0 0 1-2 0V8.5"/></svg>',gl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4a3 3 0 0 1 3 3v5a3 3 0 0 1-6 0V7a3 3 0 0 1 3-3z"/><path d="M5 11v1a7 7 0 0 0 14 0v-1"/><path d="M12 19v3"/></svg>',vl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H9l-5 4z"/></svg>',bl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg>',yl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><circle cx="9" cy="10" r="1.5"/><path d="M4.5 17.5 9 13.5l3.5 3 3-2.5 4.5 4"/></svg>',xl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/><rect class="glyph--solid" x="7.5" y="13.5" width="9" height="4.5" rx="1"/></svg>',_l='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/><path d="M8.5 13.5h7M8.5 17h4.5"/></svg>';var qd=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function El(t,e){let n=[];return{text:t.replace(qd,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Wd(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&(e.prompt===void 0||typeof e.prompt=="string")}function rs(t){return Array.isArray(t)?t.filter(Wd):[]}var Bn=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 os(t){return t[Fn]===!0}function Mr(t){return t[$n]===!0}function Lr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Xd=Lr(HTMLInputElement.prototype,"value"),Yd=Lr(HTMLTextAreaElement.prototype,"value"),Kd=Lr(HTMLSelectElement.prototype,"value"),Zd=Lr(HTMLInputElement.prototype,"checked");function Nt(t,e){t instanceof HTMLTextAreaElement?Yd.call(t,e):t instanceof HTMLSelectElement?Kd.call(t,e):Xd.call(t,e)}function Vn(t,e){Zd.call(t,e)}var is="#4f46e5",Jd="rgba(79, 70, 229, 0.4)",Qd="--ag-ui-accent";function jn(t){return new Promise(e=>{setTimeout(e,t)})}function Pr(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ss(t){return t<=0||Pr()?Promise.resolve():jn(t)}function Dr(t,e){let n=window.getComputedStyle(t).getPropertyValue(Qd).trim();return n===""?e:n}function wl(t){return`0 0 0 3px ${Dr(t,Jd)}`}async function as(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 jn(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function ls(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Dr(t,is)}`,t.style.outlineOffset="2px",await jn(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}var ep=600,tp=100;function lt(t,e={}){let n=Pr();return t.scrollIntoView({block:"center",inline:"nearest",behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(r=>{let o,i=()=>{clearTimeout(o),document.removeEventListener("scroll",s,!0),document.removeEventListener("scrollend",i,!0),r()},s=()=>{document.removeEventListener("scroll",s,!0),clearTimeout(o),o=setTimeout(i,e.settleMs??ep)};o=setTimeout(i,tp),document.addEventListener("scroll",s,!0),document.addEventListener("scrollend",i,!0)})}var np=1200,rp=1/3;async function Tl(t,e,n){(e.focus??n)&&t.focus({preventScroll:!0});let r=e.flashMs??np;if(r<=0)return;let o=t.style.outline,i=t.style.outlineOffset,s=t.style.transition,a=e.color??Dr(t,is);t.style.outline=`3px solid ${a}`,t.style.outlineOffset="2px";let l=Pr()?0:Math.round(r*rp);await jn(r-l),l>0&&(t.style.transition=`outline-color ${l}ms ease-out`,t.style.outline="3px solid transparent",await jn(l)),t.style.outline=o,t.style.outlineOffset=i,t.style.transition=s}function op(t,e={}){return Tl(t,e,!1)}function cs(t,e={}){return Tl(t,e,!0)}async function us(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=wl(t),await ss(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function ip(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function ds(t,e,n={}){let r=ip(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 ${Dr(t,is)}`,t.style.outlineOffset="2px",await ss(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 ps(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=wl(t),await ss(r),Vn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var hs={SCROLL:"scroll",DRAG:"drag"};function fs(t,e){let n=[];return t.has(hs.SCROLL)&&n.push(sp(e)),t.has(hs.DRAG)&&n.push(ap(e)),n}function sp(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 ap(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 lp(o,i),{dragged:!0,from:n,to:r}}}}function lp(t,e){let n=new DataTransfer;qn(t,"dragstart",n),qn(e,"dragenter",n),qn(e,"dragover",n),qn(e,"drop",n),qn(t,"dragend",n)}function qn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function ms(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ur(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 cp=Ur;function gs(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 Sl=/:([A-Za-z_][A-Za-z0-9_]*)/g;function up(t){return[...t.matchAll(Sl)].map(e=>e[0].slice(1))}function dp(t,e,n){let r={...n};return{path:e.replace(Sl,(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 pp(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 vs(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:up(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(h=>h.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=dp(o.id,o.path,i),l=pp(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",expandUnread:"Expand \u2014 {count} unread",toggleTheme:"Toggle theme",copyCode:"Copy",copied:"Copied",copyFailed:"Copy failed",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.",attachmentsStillUploading:"{n} file still uploading \u2014 it was not sent with this message and is still attached.",skillNeeds:"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.",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",resizePanel:"Resize the chat panel",decisionApproved:"approved by you",decisionDeclined:"declined by you",argumentsLabel:"Arguments",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 bs(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function Al(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 ys(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=Al("deny",r.deny),c=Al("approve",r.approve),h=!1,m=y=>{h||(h=!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 xs(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(hp(r,e)))}}function hp(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{fp(n).then(o=>{mp(r,o?e.copied:e.copyFailed,e)})}),r}async function fp(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function mp(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}function _s(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(gp(n));return e}function gp(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.innerHTML=Es(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=Hr(t.size),e.append(n,r,o),e}function Es(t){return t.startsWith("image/")?yl:t==="application/pdf"?xl:t.startsWith("text/")?_l:bl}function Hr(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 kl(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 ws,vp=new Uint8Array(16);function Ts(){if(!ws){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ws=crypto.getRandomValues.bind(crypto)}return ws(vp)}var bp=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ss={randomUUID:bp};function yp(t,e,n){if(Ss.randomUUID&&!e&&!t)return Ss.randomUUID();t=t||{};let r=t.random??t.rng?.()??Ts();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 kl(r)}var xt=yp;var u={};ji(u,{BRAND:()=>jp,DIRTY:()=>Ot,EMPTY_PATH:()=>wp,INVALID:()=>P,NEVER:()=>Ch,OK:()=>Se,ParseStatus:()=>_e,Schema:()=>$,ZodAny:()=>wt,ZodArray:()=>pt,ZodBigInt:()=>Lt,ZodBoolean:()=>Pt,ZodBranded:()=>Xn,ZodCatch:()=>qt,ZodDate:()=>Dt,ZodDefault:()=>jt,ZodDiscriminatedUnion:()=>Fr,ZodEffects:()=>Fe,ZodEnum:()=>Bt,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Br,ZodIntersection:()=>Gt,ZodIssueCode:()=>E,ZodLazy:()=>Ft,ZodLiteral:()=>$t,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Vt,ZodNever:()=>qe,ZodNull:()=>Ht,ZodNullable:()=>rt,ZodNumber:()=>Mt,ZodObject:()=>Oe,ZodOptional:()=>ze,ZodParsedType:()=>I,ZodPipeline:()=>Yn,ZodPromise:()=>Tt,ZodReadonly:()=>Wt,ZodRecord:()=>$r,ZodSchema:()=>$,ZodSet:()=>yn,ZodString:()=>Et,ZodSymbol:()=>gn,ZodTransformer:()=>Fe,ZodTuple:()=>nt,ZodType:()=>$,ZodUndefined:()=>Ut,ZodUnion:()=>zt,ZodUnknown:()=>dt,ZodVoid:()=>vn,addIssueToContext:()=>k,any:()=>eh,array:()=>oh,bigint:()=>Yp,boolean:()=>Hl,coerce:()=>Ih,custom:()=>Pl,date:()=>Kp,datetimeRegex:()=>Ml,defaultErrorMap:()=>ct,discriminatedUnion:()=>lh,effect:()=>xh,enum:()=>vh,function:()=>fh,getErrorMap:()=>hn,getParsedType:()=>tt,instanceof:()=>Wp,intersection:()=>ch,isAborted:()=>zr,isAsync:()=>fn,isDirty:()=>Gr,isValid:()=>_t,late:()=>qp,lazy:()=>mh,literal:()=>gh,makeIssue:()=>Wn,map:()=>ph,nan:()=>Xp,nativeEnum:()=>bh,never:()=>nh,null:()=>Qp,nullable:()=>Eh,number:()=>Ul,object:()=>ih,objectUtil:()=>As,oboolean:()=>kh,onumber:()=>Ah,optional:()=>_h,ostring:()=>Sh,pipeline:()=>Th,preprocess:()=>wh,promise:()=>yh,quotelessJson:()=>xp,record:()=>dh,set:()=>hh,setErrorMap:()=>Ep,strictObject:()=>sh,string:()=>Dl,symbol:()=>Zp,transformer:()=>xh,tuple:()=>uh,undefined:()=>Jp,union:()=>ah,unknown:()=>th,util:()=>V,void:()=>rh});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 As;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(As||(As={}));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 E=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"]),xp=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ne=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()}};Ne.create=t=>new Ne(t);var _p=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===I.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,V.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:V.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,V.assertNever(t)}return{message:n}},ct=_p;var Il=ct;function Ep(t){Il=t}function hn(){return Il}var Wn=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}},wp=[];function k(t,e){let n=hn(),r=Wn({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 _e=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}),Se=t=>({status:"valid",value:t}),zr=t=>t.status==="aborted",Gr=t=>t.status==="dirty",_t=t=>t.status==="valid",fn=t=>typeof Promise<"u"&&t instanceof Promise;var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var Ge=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}},Cl=(t,e)=>{if(_t(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 Ne(t.common.issues);return this._error=n,this._error}}};function G(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 $=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 _e,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 Cl(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 _t(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=>_t(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 Cl(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Fe({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 ze.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Tt.create(this,this._def)}or(e){return zt.create([this,e],this._def)}and(e){return Gt.create(this,e,this._def)}transform(e){return new Fe({...G(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new jt({...G(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new Xn({typeName:D.ZodBranded,type:this,...G(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new qt({...G(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 Yn.create(this,e)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tp=/^c[^\s-]{8,}$/i,Sp=/^[0-9a-z]+$/,Ap=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kp=/^[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,Ip=/^[a-z0-9_-]{21}$/i,Cp=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rp=/^[-+]?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,Op="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ks,Mp=/^(?:(?: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])$/,Lp=/^(?:(?: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])$/,Pp=/^(([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]))$/,Dp=/^(([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])$/,Up=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nl="((\\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])))",zp=new RegExp(`^${Nl}$`);function Ol(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 Gp(t){return new RegExp(`^${Ol(t)}$`)}function Ml(t){let e=`${Nl}T${Ol(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 Fp(t,e){return!!((e==="v4"||!e)&&Mp.test(t)||(e==="v6"||!e)&&Pp.test(t))}function $p(t,e){if(!Cp.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 Bp(t,e){return!!((e==="v4"||!e)&&Lp.test(t)||(e==="v6"||!e)&&Dp.test(t))}var Et=class t extends ${_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:E.invalid_type,expected:I.string,received:i.parsedType}),P}let r=new _e,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:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?k(o,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&k(o,{code:E.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:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")ks||(ks=new RegExp(Op,"u")),ks.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")kp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Ip.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Sp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ap.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:E.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:E.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.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:E.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?zp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Gp(i).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Rp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Fp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?$p(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Up.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Hp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:E.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:E.invalid_string,...R.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...R.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...R.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...R.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...R.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...R.errToObj(n)})}nonempty(e){return this.min(1,R.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,...G(t)});function Vp(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 ${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:E.invalid_type,expected:I.number,received:i.parsedType}),P}let r,o=new _e;for(let i of this._def.checks)i.kind==="int"?V.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:E.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Vp(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:E.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,R.toString(n))}gt(e,n){return this.setLimit("min",e,!1,R.toString(n))}lte(e,n){return this.setLimit("max",e,!0,R.toString(n))}lt(e,n){return this.setLimit("max",e,!1,R.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:R.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.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,...G(t)});var Lt=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==I.bigint)return this._getInvalidInput(e);let r,o=new _e;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:E.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.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:E.invalid_type,expected:I.bigint,received:n.parsedType}),P}gte(e,n){return this.setLimit("min",e,!0,R.toString(n))}gt(e,n){return this.setLimit("min",e,!1,R.toString(n))}lte(e,n){return this.setLimit("max",e,!0,R.toString(n))}lt(e,n){return this.setLimit("max",e,!1,R.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:R.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:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:R.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,...G(t)});var Pt=class extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:I.boolean,received:r.parsedType}),P}return Se(e.data)}};Pt.create=t=>new Pt({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...G(t)});var Dt=class t extends ${_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:E.invalid_type,expected:I.date,received:i.parsedType}),P}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return k(i,{code:E.invalid_date}),P}let r=new _e,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:E.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:E.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:R.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:R.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,...G(t)});var gn=class extends ${_parse(e){if(this._getType(e)!==I.symbol){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:I.symbol,received:r.parsedType}),P}return Se(e.data)}};gn.create=t=>new gn({typeName:D.ZodSymbol,...G(t)});var Ut=class extends ${_parse(e){if(this._getType(e)!==I.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:I.undefined,received:r.parsedType}),P}return Se(e.data)}};Ut.create=t=>new Ut({typeName:D.ZodUndefined,...G(t)});var Ht=class extends ${_parse(e){if(this._getType(e)!==I.null){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:I.null,received:r.parsedType}),P}return Se(e.data)}};Ht.create=t=>new Ht({typeName:D.ZodNull,...G(t)});var wt=class extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Se(e.data)}};wt.create=t=>new wt({typeName:D.ZodAny,...G(t)});var dt=class extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Se(e.data)}};dt.create=t=>new dt({typeName:D.ZodUnknown,...G(t)});var qe=class extends ${_parse(e){let n=this._getOrReturnCtx(e);return k(n,{code:E.invalid_type,expected:I.never,received:n.parsedType}),P}};qe.create=t=>new qe({typeName:D.ZodNever,...G(t)});var vn=class extends ${_parse(e){if(this._getType(e)!==I.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:I.void,received:r.parsedType}),P}return Se(e.data)}};vn.create=t=>new vn({typeName:D.ZodVoid,...G(t)});var pt=class t extends ${_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==I.array)return k(n,{code:E.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?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(k(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(k(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Ge(n,s,n.path,a)))).then(s=>_e.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Ge(n,s,n.path,a)));return _e.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:R.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:R.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:R.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,...G(e)});function mn(t){if(t instanceof Oe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ze.create(mn(r))}return new Oe({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:mn(t.element)}):t instanceof ze?ze.create(mn(t.unwrap())):t instanceof rt?rt.create(mn(t.unwrap())):t instanceof nt?nt.create(t.items.map(e=>mn(e))):t}var Oe=class t extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=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:E.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 qe&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let h=i[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new Ge(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof qe){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of a)l.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(c==="strict")a.length>0&&(k(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of a){let m=o.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new Ge(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let h of l){let m=await h.key,y=await h.value;c.push({key:m,value:y,alwaysSet:h.alwaysSet})}return c}).then(c=>_e.mergeObjectSync(r,c)):_e.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return R.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:R.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 mn(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 ze;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Ll(V.objectKeys(this.shape))}};Oe.create=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strip",catchall:qe.create(),typeName:D.ZodObject,...G(e)});Oe.strictCreate=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strict",catchall:qe.create(),typeName:D.ZodObject,...G(e)});Oe.lazycreate=(t,e)=>new Oe({shape:t,unknownKeys:"strip",catchall:qe.create(),typeName:D.ZodObject,...G(e)});var zt=class extends ${_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 Ne(a.ctx.common.issues));return k(n,{code:E.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},h=l._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,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 Ne(l));return k(n,{code:E.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};zt.create=(t,e)=>new zt({options:t,typeName:D.ZodUnion,...G(e)});var ut=t=>t instanceof Ft?ut(t.schema):t instanceof Fe?ut(t.innerType()):t instanceof $t?[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 ze?[void 0,...ut(t.unwrap())]:t instanceof rt?[null,...ut(t.unwrap())]:t instanceof Xn||t instanceof Wt?ut(t.unwrap()):t instanceof qt?ut(t._def.innerType):[],Fr=class t extends ${_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.object)return k(n,{code:E.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:E.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,...G(r)})}};function Is(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=Is(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=Is(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 ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(zr(i)||zr(s))return P;let a=Is(i.value,s.value);return a.valid?((Gr(i)||Gr(s))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:E.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,...G(n)});var nt=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.array)return k(r,{code:E.invalid_type,expected:I.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return k(r,{code:E.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:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ge(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>_e.mergeArray(n,s)):_e.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,...G(e)})};var $r=class t extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.object)return k(r,{code:E.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 Ge(r,a,r.path,a)),value:s._parse(new Ge(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?_e.mergeObjectAsync(n,o):_e.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof $?new t({keyType:e,valueType:n,typeName:D.ZodRecord,...G(r)}):new t({keyType:Et.create(),valueType:e,typeName:D.ZodRecord,...G(n)})}},bn=class extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.map)return k(r,{code:E.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 Ge(r,a,r.path,[c,"key"])),value:i._parse(new Ge(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,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return P;(c.status==="dirty"||h.status==="dirty")&&n.dirty(),a.set(c.value,h.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return P;(c.status==="dirty"||h.status==="dirty")&&n.dirty(),a.set(c.value,h.value)}return{status:n.value,value:a}}}};bn.create=(t,e,n)=>new bn({valueType:e,keyType:t,typeName:D.ZodMap,...G(n)});var yn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==I.set)return k(r,{code:E.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:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(k(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let h of l){if(h.status==="aborted")return P;h.status==="dirty"&&n.dirty(),c.add(h.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new Ge(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:R.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:R.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};yn.create=(t,e)=>new yn({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...G(e)});var Br=class t extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==I.function)return k(n,{code:E.invalid_type,expected:I.function,received:n.parsedType}),P;function r(a,l){return Wn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,hn(),ct].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function o(a,l){return Wn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,hn(),ct].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Tt){let a=this;return Se(async function(...l){let c=new Ne([]),h=await a._def.args.parseAsync(l,i).catch(f=>{throw c.addIssue(r(l,f)),c}),m=await Reflect.apply(s,this,h);return await a._def.returns._def.type.parseAsync(m,i).catch(f=>{throw c.addIssue(o(m,f)),c})})}else{let a=this;return Se(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new Ne([r(l,c.error)]);let h=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(h,i);if(!m.success)throw new Ne([o(h,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,...G(r)})}},Ft=class extends ${get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ft.create=(t,e)=>new Ft({getter:t,typeName:D.ZodLazy,...G(e)});var $t=class extends ${_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return k(n,{received:n.data,code:E.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,...G(e)});function Ll(t,e){return new Bt({values:t,typeName:D.ZodEnum,...G(e)})}var Bt=class t extends ${_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:E.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:E.invalid_enum_value,options:r}),P}return Se(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=Ll;var Vt=class extends ${_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:E.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:E.invalid_enum_value,options:o}),P}return Se(e.data)}get enum(){return this._def.values}};Vt.create=(t,e)=>new Vt({values:t,typeName:D.ZodNativeEnum,...G(e)});var Tt=class extends ${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:E.invalid_type,expected:I.promise,received:n.parsedType}),P;let r=n.parsedType===I.promise?n.data:Promise.resolve(n.data);return Se(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tt.create=(t,e)=>new Tt({type:t,typeName:D.ZodPromise,...G(e)});var Fe=class extends ${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(!_t(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=>_t(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):P);V.assertNever(o)}};Fe.create=(t,e,n)=>new Fe({schema:t,typeName:D.ZodEffects,effect:e,...G(n)});Fe.createWithPreprocess=(t,e,n)=>new Fe({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...G(n)});var ze=class extends ${_parse(e){return this._getType(e)===I.undefined?Se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ze.create=(t,e)=>new ze({innerType:t,typeName:D.ZodOptional,...G(e)});var rt=class extends ${_parse(e){return this._getType(e)===I.null?Se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(t,e)=>new rt({innerType:t,typeName:D.ZodNullable,...G(e)});var jt=class extends ${_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,...G(e)});var qt=class extends ${_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 Ne(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ne(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,...G(e)});var xn=class extends ${_parse(e){if(this._getType(e)!==I.nan){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:I.nan,received:r.parsedType}),P}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:D.ZodNaN,...G(t)});var jp=Symbol("zod_brand"),Xn=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Yn=class t extends ${_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 ${_parse(e){let n=this._def.innerType._parse(e),r=o=>(_t(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,...G(e)});function Rl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Pl(t,e={},n){return t?wt.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=Rl(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=Rl(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):wt.create()}var qp={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 Wp=(t,e={message:`Input not instance of ${t.name}`})=>Pl(n=>n instanceof t,e),Dl=Et.create,Ul=Mt.create,Xp=xn.create,Yp=Lt.create,Hl=Pt.create,Kp=Dt.create,Zp=gn.create,Jp=Ut.create,Qp=Ht.create,eh=wt.create,th=dt.create,nh=qe.create,rh=vn.create,oh=pt.create,ih=Oe.create,sh=Oe.strictCreate,ah=zt.create,lh=Fr.create,ch=Gt.create,uh=nt.create,dh=$r.create,ph=bn.create,hh=yn.create,fh=Br.create,mh=Ft.create,gh=$t.create,vh=Bt.create,bh=Vt.create,yh=Tt.create,xh=Fe.create,_h=ze.create,Eh=rt.create,wh=Fe.createWithPreprocess,Th=Yn.create,Sh=()=>Dl().optional(),Ah=()=>Ul().optional(),kh=()=>Hl().optional(),Ih={string:(t=>Et.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 Ch=P;var Rh=u.object({name:u.string(),arguments:u.string()}),Nh=u.object({id:u.string(),type:u.literal("function"),function:Rh,encryptedValue:u.string().optional()}),Vr=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),Oh=u.object({type:u.literal("text"),text:u.string()}),Mh=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),Lh=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),jr=u.discriminatedUnion("type",[Mh,Lh]),Ph=u.object({type:u.literal("image"),source:jr,metadata:u.unknown().optional()}),Dh=u.object({type:u.literal("audio"),source:jr,metadata:u.unknown().optional()}),Uh=u.object({type:u.literal("video"),source:jr,metadata:u.unknown().optional()}),Hh=u.object({type:u.literal("document"),source:jr,metadata:u.unknown().optional()});var zl=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()}),Gl=(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"]})},Iy=zl.superRefine((t,e)=>{Gl(t,e)}),zh=u.discriminatedUnion("type",[Oh,Ph,Dh,Uh,Hh,zl]),Gh=zh.superRefine((t,e)=>{t.type==="binary"&&Gl(t,e)}),Fh=Vr.extend({role:u.literal("developer"),content:u.string()}),$h=Vr.extend({role:u.literal("system"),content:u.string()}),Bh=Vr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(Nh).optional()}),Vh=Vr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(Gh)])}),jh=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),qh=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),Wh=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),Fl=u.discriminatedUnion("role",[Fh,$h,Bh,Vh,jh,qh,Wh]),Cy=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),Xh=u.object({description:u.string(),value:u.string()}),$l=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),Yh=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()}),Kh=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Zh=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(Fl),tools:u.array($l),context:u.array(Xh),forwardedProps:u.any(),resume:u.array(Kh).optional()}),Jh=u.any(),ee=class extends Error{constructor(t){super(t)}},Cs=class extends ee{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Qh=u.object({name:u.string(),description:u.string().optional()}),ef=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()}),tf=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),nf=u.object({supported:u.boolean().optional(),items:u.array($l).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),rf=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),of=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),sf=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(Qh).optional()}),af=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),lf=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),cf=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),uf=u.object({input:lf.optional(),output:cf.optional()}),df=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),pf=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()}),Ry=u.object({identity:ef.optional(),transport:tf.optional(),tools:nf.optional(),output:rf.optional(),state:of.optional(),multiAgent:sf.optional(),reasoning:af.optional(),multimodal:uf.optional(),execution:df.optional(),humanInTheLoop:pf.optional(),custom:u.record(u.unknown()).optional()}),Bl=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(),hf=X.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:Bl.default("assistant"),name:u.string().optional()}),Vl=X.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),ff=X.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),mf=X.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:Bl.optional(),delta:u.string().optional(),name:u.string().optional()}),gf=X.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),vf=Vl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),bf=X.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),yf=X.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),xf=X.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),_f=X.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),Ef=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()}),Tf=X.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),Sf=X.extend({type:u.literal(v.THINKING_END)}),Af=X.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:Jh}),kf=X.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),If=X.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(Fl)}),Cf=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)}),Rf=X.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),Nf=X.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),Of=X.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Mf=X.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Zh.optional()}),Lf=u.object({type:u.literal("success")}).strict(),Pf=u.object({type:u.literal("interrupt"),interrupts:u.array(Yh).min(1)}).strict(),Df=u.discriminatedUnion("type",[Lf,Pf]),Uf=X.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:Df.nullable().optional().transform(t=>t??void 0)}),Hf=X.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),zf=X.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),Gf=X.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),Ff=u.union([u.literal("tool-call"),u.literal("message")]),$f=X.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),Bf=X.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),Vf=X.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),jf=X.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),qf=X.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),Wf=X.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),Xf=X.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:Ff,entityId:u.string(),encryptedValue:u.string()}),qr=u.discriminatedUnion("type",[hf,Vl,ff,mf,Tf,Sf,gf,vf,bf,yf,xf,_f,wf,Ef,Af,kf,If,Cf,Rf,Nf,Of,Mf,Uf,Hf,zf,Gf,$f,Bf,Vf,jf,qf,Wf,Xf]);var Rs={};ji(Rs,{JsonPatchError:()=>he,_areEquals:()=>Jn,applyOperation:()=>Xt,applyPatch:()=>Qr,applyReducer:()=>Qf,deepClone:()=>Zf,getValueByPointer:()=>Zr,validate:()=>ql,validator:()=>Jr});var Yf=(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)}})(),Kf=Object.prototype.hasOwnProperty;function Xr(t,e){return Kf.call(t,e)}function Yr(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)Xr(t,o)&&r.push(o);return r}function Ee(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Kr(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 Kn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Wr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Wr(t[e]))return!0}else if(typeof t=="object"){for(var r=Yr(t),o=r.length,i=0;i<o;i++)if(Wr(t[r[i]]))return!0}}return!1}function jl(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(`
|
|
1
|
+
var jd=Object.defineProperty;var ji=(t,e)=>{for(var n in e)jd(t,n,{get:e[n],enumerable:!0})};var Or="ag-ui-chat",qi="ag-ui-submit",Wi="ag-ui-toggle",Xi="ag-ui-unread",Yi="ag-ui-state",Ki="ag-ui-attachments",je={USER:"user",ASSISTANT:"assistant"},Fn="x-destructive",Zi="x-confirm",Le="x-summary",$n="x-navigates",Ji="read_page",Qi=10,pe={PENDING:"pending",DONE:"done",ERROR:"error",DECLINED:"declined"},Pe={UPLOADING:"uploading",READY:"ready",ERROR:"error"},es=10*1024*1024,pn={INLINE:"inline",MINIMAL:"minimal",COMPACT:"compact",FULL:"full"},ts="compaction",ns="load_capability",hl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 19.5V5m-6.5 6.5L12 5l6.5 6.5"/></svg>',fl='<svg class="glyph glyph--solid" viewBox="0 0 24 24" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="2.5"/></svg>',ml='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M17 8.5V15a5 5 0 0 1-10 0V7a3 3 0 0 1 6 0v7.5a1 1 0 0 1-2 0V8.5"/></svg>',gl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4a3 3 0 0 1 3 3v5a3 3 0 0 1-6 0V7a3 3 0 0 1 3-3z"/><path d="M5 11v1a7 7 0 0 0 14 0v-1"/><path d="M12 19v3"/></svg>',vl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v8a2.5 2.5 0 0 1-2.5 2.5H9l-5 4z"/></svg>',bl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg>',yl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><rect x="3.5" y="4.5" width="17" height="15" rx="2.5"/><circle cx="9" cy="10" r="1.5"/><path d="M4.5 17.5 9 13.5l3.5 3 3-2.5 4.5 4"/></svg>',xl='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/><rect class="glyph--solid" x="7.5" y="13.5" width="9" height="4.5" rx="1"/></svg>',_l='<svg class="glyph" viewBox="0 0 24 24" aria-hidden="true"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/><path d="M8.5 13.5h7M8.5 17h4.5"/></svg>';var qd=/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;function El(t,e){let n=[];return{text:t.replace(qd,(o,i)=>{let s=e[i];return s==null||s===""?(n.includes(i)||n.push(i),o):String(s)}),missing:n}}function Wd(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.name=="string"&&typeof e.title=="string"&&(e.prompt===void 0||typeof e.prompt=="string")}function rs(t){return Array.isArray(t)?t.filter(Wd):[]}var Bn=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 os(t){return t[Fn]===!0}function Mr(t){return t[$n]===!0}function Lr(t,e){return Object.getOwnPropertyDescriptor(t,e).set}var Xd=Lr(HTMLInputElement.prototype,"value"),Yd=Lr(HTMLTextAreaElement.prototype,"value"),Kd=Lr(HTMLSelectElement.prototype,"value"),Zd=Lr(HTMLInputElement.prototype,"checked");function Nt(t,e){t instanceof HTMLTextAreaElement?Yd.call(t,e):t instanceof HTMLSelectElement?Kd.call(t,e):Xd.call(t,e)}function Vn(t,e){Zd.call(t,e)}var is="#4f46e5",Jd="rgba(79, 70, 229, 0.4)",Qd="--ag-ui-accent";function jn(t){return new Promise(e=>{setTimeout(e,t)})}function Pr(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ss(t){return t<=0||Pr()?Promise.resolve():jn(t)}function Dr(t,e){let n=window.getComputedStyle(t).getPropertyValue(Qd).trim();return n===""?e:n}function wl(t){return`0 0 0 3px ${Dr(t,Jd)}`}async function as(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 jn(r);t.dispatchEvent(new Event("change",{bubbles:!0}))}async function ls(t,e={}){let n=e.highlightMs??280,r=t.style.outline,o=t.style.outlineOffset;t.style.outline=`2px solid ${Dr(t,is)}`,t.style.outlineOffset="2px",await jn(n),t.style.outline=r,t.style.outlineOffset=o,t.click()}var ep=600,tp=100;function lt(t,e={}){let n=Pr();return t.scrollIntoView({block:"center",inline:"nearest",behavior:n?"auto":"smooth"}),n?Promise.resolve():new Promise(r=>{let o,i=()=>{clearTimeout(o),document.removeEventListener("scroll",s,!0),document.removeEventListener("scrollend",i,!0),r()},s=()=>{document.removeEventListener("scroll",s,!0),clearTimeout(o),o=setTimeout(i,e.settleMs??ep)};o=setTimeout(i,tp),document.addEventListener("scroll",s,!0),document.addEventListener("scrollend",i,!0)})}var np=1200,rp=1/3;async function Tl(t,e,n){(e.focus??n)&&t.focus({preventScroll:!0});let r=e.flashMs??np;if(r<=0)return;let o=t.style.outline,i=t.style.outlineOffset,s=t.style.transition,a=e.color??Dr(t,is);t.style.outline=`3px solid ${a}`,t.style.outlineOffset="2px";let l=Pr()?0:Math.round(r*rp);await jn(r-l),l>0&&(t.style.transition=`outline-color ${l}ms ease-out`,t.style.outline="3px solid transparent",await jn(l)),t.style.outline=o,t.style.outlineOffset=i,t.style.transition=s}function op(t,e={}){return Tl(t,e,!1)}function cs(t,e={}){return Tl(t,e,!0)}async function us(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=wl(t),await ss(n),t.style.transform=r,t.style.transition=o,t.style.boxShadow=i,t.click()}function ip(t,e){for(let n of Array.from(t.options))if(n.value===e||n.text===e)return n;return null}async function ds(t,e,n={}){let r=ip(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 ${Dr(t,is)}`,t.style.outlineOffset="2px",await ss(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 ps(t,e,n={}){let r=n.flashMs??200,o=t.style.boxShadow;t.style.boxShadow=wl(t),await ss(r),Vn(t,e),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0})),t.style.boxShadow=o}var hs={SCROLL:"scroll",DRAG:"drag"};function fs(t,e){let n=[];return t.has(hs.SCROLL)&&n.push(sp(e)),t.has(hs.DRAG)&&n.push(ap(e)),n}function sp(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 ap(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 lp(o,i),{dragged:!0,from:n,to:r}}}}function lp(t,e){let n=new DataTransfer;qn(t,"dragstart",n),qn(e,"dragenter",n),qn(e,"dragover",n),qn(e,"drop",n),qn(t,"dragend",n)}function qn(t,e,n){let r=new Event(e,{bubbles:!0,cancelable:!0});r.dataTransfer=n,t.dispatchEvent(r)}function ms(t,e){return!e||t===null?[]:[{description:"page_map",value:JSON.stringify(t())}]}function Ur(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 cp=Ur;function gs(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 Sl=/:([A-Za-z_][A-Za-z0-9_]*)/g;function up(t){return[...t.matchAll(Sl)].map(e=>e[0].slice(1))}function dp(t,e,n){let r={...n};return{path:e.replace(Sl,(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 pp(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 vs(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:up(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(h=>h.id===r);if(o===void 0)throw new Error(`unknown route "${String(r)}"`);let i=n.params??{},{path:s,leftover:a}=dp(o.id,o.path,i),l=pp(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",expandUnread:"Expand \u2014 {count} unread",toggleTheme:"Toggle theme",copyCode:"Copy",copied:"Copied",copyFailed:"Copy failed",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.",attachmentsStillUploading:"{n} file still uploading \u2014 it was not sent with this message and is still attached.",skillNeeds:"\u201C{title}\u201D needs {fields} \u2014 fill it in below, then send.",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",resizePanel:"Resize the chat panel",decisionApproved:"approved by you",decisionDeclined:"declined by you",argumentsLabel:"Arguments",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 bs(t){let e={...ae};for(let n of Object.keys(t)){let r=t[n];r!==void 0&&(e[n]=r)}return e}function Al(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 ys(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=Al("deny",r.deny),c=Al("approve",r.approve),h=!1,m=y=>{h||(h=!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 xs(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(hp(r,e)))}}function hp(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{fp(n).then(o=>{mp(r,o?e.copied:e.copyFailed,e)})}),r}async function fp(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function mp(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}function _s(t){let e=document.createElement("div");e.className="attachment-chips",e.setAttribute("part","attachment-chips");for(let n of t)e.appendChild(gp(n));return e}function gp(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.innerHTML=Es(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=Hr(t.size),e.append(n,r,o),e}function Es(t){return t.startsWith("image/")?yl:t==="application/pdf"?xl:t.startsWith("text/")?_l:bl}function Hr(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 kl(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 ws,vp=new Uint8Array(16);function Ts(){if(!ws){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ws=crypto.getRandomValues.bind(crypto)}return ws(vp)}var bp=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),Ss={randomUUID:bp};function yp(t,e,n){if(Ss.randomUUID&&!e&&!t)return Ss.randomUUID();t=t||{};let r=t.random??t.rng?.()??Ts();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 kl(r)}var xt=yp;var u={};ji(u,{BRAND:()=>jp,DIRTY:()=>Ot,EMPTY_PATH:()=>wp,INVALID:()=>P,NEVER:()=>Ih,OK:()=>Se,ParseStatus:()=>_e,Schema:()=>$,ZodAny:()=>wt,ZodArray:()=>pt,ZodBigInt:()=>Lt,ZodBoolean:()=>Pt,ZodBranded:()=>Xn,ZodCatch:()=>qt,ZodDate:()=>Dt,ZodDefault:()=>jt,ZodDiscriminatedUnion:()=>Fr,ZodEffects:()=>Fe,ZodEnum:()=>Bt,ZodError:()=>Ne,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Br,ZodIntersection:()=>Gt,ZodIssueCode:()=>E,ZodLazy:()=>Ft,ZodLiteral:()=>$t,ZodMap:()=>bn,ZodNaN:()=>xn,ZodNativeEnum:()=>Vt,ZodNever:()=>qe,ZodNull:()=>Ht,ZodNullable:()=>rt,ZodNumber:()=>Mt,ZodObject:()=>Oe,ZodOptional:()=>ze,ZodParsedType:()=>C,ZodPipeline:()=>Yn,ZodPromise:()=>Tt,ZodReadonly:()=>Wt,ZodRecord:()=>$r,ZodSchema:()=>$,ZodSet:()=>yn,ZodString:()=>Et,ZodSymbol:()=>gn,ZodTransformer:()=>Fe,ZodTuple:()=>nt,ZodType:()=>$,ZodUndefined:()=>Ut,ZodUnion:()=>zt,ZodUnknown:()=>dt,ZodVoid:()=>vn,addIssueToContext:()=>k,any:()=>eh,array:()=>oh,bigint:()=>Yp,boolean:()=>Hl,coerce:()=>Ch,custom:()=>Pl,date:()=>Kp,datetimeRegex:()=>Ml,defaultErrorMap:()=>ct,discriminatedUnion:()=>lh,effect:()=>xh,enum:()=>vh,function:()=>fh,getErrorMap:()=>hn,getParsedType:()=>tt,instanceof:()=>Wp,intersection:()=>ch,isAborted:()=>zr,isAsync:()=>fn,isDirty:()=>Gr,isValid:()=>_t,late:()=>qp,lazy:()=>mh,literal:()=>gh,makeIssue:()=>Wn,map:()=>ph,nan:()=>Xp,nativeEnum:()=>bh,never:()=>nh,null:()=>Qp,nullable:()=>Eh,number:()=>Ul,object:()=>ih,objectUtil:()=>As,oboolean:()=>kh,onumber:()=>Ah,optional:()=>_h,ostring:()=>Sh,pipeline:()=>Th,preprocess:()=>wh,promise:()=>yh,quotelessJson:()=>xp,record:()=>dh,set:()=>hh,setErrorMap:()=>Ep,strictObject:()=>sh,string:()=>Dl,symbol:()=>Zp,transformer:()=>xh,tuple:()=>uh,undefined:()=>Jp,union:()=>ah,unknown:()=>th,util:()=>V,void:()=>rh});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 As;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(As||(As={}));var C=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 C.undefined;case"string":return C.string;case"number":return Number.isNaN(t)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(t)?C.array:t===null?C.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?C.promise:typeof Map<"u"&&t instanceof Map?C.map:typeof Set<"u"&&t instanceof Set?C.set:typeof Date<"u"&&t instanceof Date?C.date:C.object;default:return C.unknown}};var E=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"]),xp=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ne=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()}};Ne.create=t=>new Ne(t);var _p=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===C.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,V.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${V.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${V.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${V.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:V.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,V.assertNever(t)}return{message:n}},ct=_p;var Cl=ct;function Ep(t){Cl=t}function hn(){return Cl}var Wn=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}},wp=[];function k(t,e){let n=hn(),r=Wn({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 _e=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}),Se=t=>({status:"valid",value:t}),zr=t=>t.status==="aborted",Gr=t=>t.status==="dirty",_t=t=>t.status==="valid",fn=t=>typeof Promise<"u"&&t instanceof Promise;var R;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(R||(R={}));var Ge=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}},Il=(t,e)=>{if(_t(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 Ne(t.common.issues);return this._error=n,this._error}}};function G(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 $=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 _e,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 Il(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 _t(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=>_t(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 Il(r,i)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{let s=e(o),a=()=>i.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Fe({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 ze.create(this,this._def)}nullable(){return rt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return pt.create(this)}promise(){return Tt.create(this,this._def)}or(e){return zt.create([this,e],this._def)}and(e){return Gt.create(this,e,this._def)}transform(e){return new Fe({...G(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new jt({...G(this._def),innerType:this,defaultValue:n,typeName:D.ZodDefault})}brand(){return new Xn({typeName:D.ZodBranded,type:this,...G(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new qt({...G(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 Yn.create(this,e)}readonly(){return Wt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Tp=/^c[^\s-]{8,}$/i,Sp=/^[0-9a-z]+$/,Ap=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kp=/^[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,Cp=/^[a-z0-9_-]{21}$/i,Ip=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rp=/^[-+]?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,Op="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ks,Mp=/^(?:(?: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])$/,Lp=/^(?:(?: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])$/,Pp=/^(([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]))$/,Dp=/^(([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])$/,Up=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Hp=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Nl="((\\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])))",zp=new RegExp(`^${Nl}$`);function Ol(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 Gp(t){return new RegExp(`^${Ol(t)}$`)}function Ml(t){let e=`${Nl}T${Ol(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 Fp(t,e){return!!((e==="v4"||!e)&&Mp.test(t)||(e==="v6"||!e)&&Pp.test(t))}function $p(t,e){if(!Ip.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 Bp(t,e){return!!((e==="v4"||!e)&&Lp.test(t)||(e==="v6"||!e)&&Dp.test(t))}var Et=class t extends ${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.string){let i=this._getOrReturnCtx(e);return k(i,{code:E.invalid_type,expected:C.string,received:i.parsedType}),P}let r=new _e,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:E.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let s=e.data.length>i.value,a=e.data.length<i.value;(s||a)&&(o=this._getOrReturnCtx(e,o),s?k(o,{code:E.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):a&&k(o,{code:E.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:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")ks||(ks=new RegExp(Op,"u")),ks.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"emoji",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")kp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"uuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Cp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"nanoid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Tp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Sp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cuid2",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Ap.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ulid",code:E.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),k(o,{validation:"url",code:E.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"regex",code:E.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.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:E.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?zp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?Gp(i).test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{code:E.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?Rp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"duration",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Fp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"ip",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?$p(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"jwt",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Bp(e.data,i.version)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"cidr",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?Up.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64",code:E.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?Hp.test(e.data)||(o=this._getOrReturnCtx(e,o),k(o,{validation:"base64url",code:E.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:E.invalid_string,...R.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...R.errToObj(e)})}url(e){return this._addCheck({kind:"url",...R.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...R.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...R.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...R.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...R.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...R.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...R.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...R.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...R.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...R.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...R.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...R.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,...R.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,...R.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...R.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...R.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...R.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...R.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...R.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...R.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...R.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...R.errToObj(n)})}nonempty(e){return this.min(1,R.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,...G(t)});function Vp(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 ${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)!==C.number){let i=this._getOrReturnCtx(e);return k(i,{code:E.invalid_type,expected:C.number,received:i.parsedType}),P}let r,o=new _e;for(let i of this._def.checks)i.kind==="int"?V.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:E.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Vp(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:E.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,R.toString(n))}gt(e,n){return this.setLimit("min",e,!1,R.toString(n))}lte(e,n){return this.setLimit("max",e,!0,R.toString(n))}lt(e,n){return this.setLimit("max",e,!1,R.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:R.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:R.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:R.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:R.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:R.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:R.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:R.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,...G(t)});var Lt=class t extends ${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==C.bigint)return this._getInvalidInput(e);let r,o=new _e;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:E.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),k(r,{code:E.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:E.invalid_type,expected:C.bigint,received:n.parsedType}),P}gte(e,n){return this.setLimit("min",e,!0,R.toString(n))}gt(e,n){return this.setLimit("min",e,!1,R.toString(n))}lte(e,n){return this.setLimit("max",e,!0,R.toString(n))}lt(e,n){return this.setLimit("max",e,!1,R.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:R.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:R.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:R.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:R.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:R.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:R.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,...G(t)});var Pt=class extends ${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.boolean){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:C.boolean,received:r.parsedType}),P}return Se(e.data)}};Pt.create=t=>new Pt({typeName:D.ZodBoolean,coerce:t?.coerce||!1,...G(t)});var Dt=class t extends ${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.date){let i=this._getOrReturnCtx(e);return k(i,{code:E.invalid_type,expected:C.date,received:i.parsedType}),P}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return k(i,{code:E.invalid_date}),P}let r=new _e,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:E.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),k(o,{code:E.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:R.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:R.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,...G(t)});var gn=class extends ${_parse(e){if(this._getType(e)!==C.symbol){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:C.symbol,received:r.parsedType}),P}return Se(e.data)}};gn.create=t=>new gn({typeName:D.ZodSymbol,...G(t)});var Ut=class extends ${_parse(e){if(this._getType(e)!==C.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:C.undefined,received:r.parsedType}),P}return Se(e.data)}};Ut.create=t=>new Ut({typeName:D.ZodUndefined,...G(t)});var Ht=class extends ${_parse(e){if(this._getType(e)!==C.null){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:C.null,received:r.parsedType}),P}return Se(e.data)}};Ht.create=t=>new Ht({typeName:D.ZodNull,...G(t)});var wt=class extends ${constructor(){super(...arguments),this._any=!0}_parse(e){return Se(e.data)}};wt.create=t=>new wt({typeName:D.ZodAny,...G(t)});var dt=class extends ${constructor(){super(...arguments),this._unknown=!0}_parse(e){return Se(e.data)}};dt.create=t=>new dt({typeName:D.ZodUnknown,...G(t)});var qe=class extends ${_parse(e){let n=this._getOrReturnCtx(e);return k(n,{code:E.invalid_type,expected:C.never,received:n.parsedType}),P}};qe.create=t=>new qe({typeName:D.ZodNever,...G(t)});var vn=class extends ${_parse(e){if(this._getType(e)!==C.undefined){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:C.void,received:r.parsedType}),P}return Se(e.data)}};vn.create=t=>new vn({typeName:D.ZodVoid,...G(t)});var pt=class t extends ${_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==C.array)return k(n,{code:E.invalid_type,expected:C.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?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:s?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(k(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(k(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>o.type._parseAsync(new Ge(n,s,n.path,a)))).then(s=>_e.mergeArray(r,s));let i=[...n.data].map((s,a)=>o.type._parseSync(new Ge(n,s,n.path,a)));return _e.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:R.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:R.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:R.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,...G(e)});function mn(t){if(t instanceof Oe){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=ze.create(mn(r))}return new Oe({...t._def,shape:()=>e})}else return t instanceof pt?new pt({...t._def,type:mn(t.element)}):t instanceof ze?ze.create(mn(t.unwrap())):t instanceof rt?rt.create(mn(t.unwrap())):t instanceof nt?nt.create(t.items.map(e=>mn(e))):t}var Oe=class t extends ${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=V.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==C.object){let c=this._getOrReturnCtx(e);return k(c,{code:E.invalid_type,expected:C.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 qe&&this._def.unknownKeys==="strip"))for(let c in o.data)s.includes(c)||a.push(c);let l=[];for(let c of s){let h=i[c],m=o.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new Ge(o,m,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof qe){let c=this._def.unknownKeys;if(c==="passthrough")for(let h of a)l.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(c==="strict")a.length>0&&(k(o,{code:E.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let h of a){let m=o.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new Ge(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let h of l){let m=await h.key,y=await h.value;c.push({key:m,value:y,alwaysSet:h.alwaysSet})}return c}).then(c=>_e.mergeObjectSync(r,c)):_e.mergeObjectSync(r,l)}get shape(){return this._def.shape()}strict(e){return R.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:R.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 mn(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 ze;)i=i._def.innerType;n[r]=i}return new t({...this._def,shape:()=>n})}keyof(){return Ll(V.objectKeys(this.shape))}};Oe.create=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strip",catchall:qe.create(),typeName:D.ZodObject,...G(e)});Oe.strictCreate=(t,e)=>new Oe({shape:()=>t,unknownKeys:"strict",catchall:qe.create(),typeName:D.ZodObject,...G(e)});Oe.lazycreate=(t,e)=>new Oe({shape:t,unknownKeys:"strip",catchall:qe.create(),typeName:D.ZodObject,...G(e)});var zt=class extends ${_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 Ne(a.ctx.common.issues));return k(n,{code:E.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},h=l._parseSync({data:n.data,path:n.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,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 Ne(l));return k(n,{code:E.invalid_union,unionErrors:a}),P}}get options(){return this._def.options}};zt.create=(t,e)=>new zt({options:t,typeName:D.ZodUnion,...G(e)});var ut=t=>t instanceof Ft?ut(t.schema):t instanceof Fe?ut(t.innerType()):t instanceof $t?[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 ze?[void 0,...ut(t.unwrap())]:t instanceof rt?[null,...ut(t.unwrap())]:t instanceof Xn||t instanceof Wt?ut(t.unwrap()):t instanceof qt?ut(t._def.innerType):[],Fr=class t extends ${_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.object)return k(n,{code:E.invalid_type,expected:C.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:E.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,...G(r)})}};function Cs(t,e){let n=tt(t),r=tt(e);if(t===e)return{valid:!0,data:t};if(n===C.object&&r===C.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=Cs(t[a],e[a]);if(!l.valid)return{valid:!1};s[a]=l.data}return{valid:!0,data:s}}else if(n===C.array&&r===C.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=Cs(s,a);if(!l.valid)return{valid:!1};o.push(l.data)}return{valid:!0,data:o}}else return n===C.date&&r===C.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Gt=class extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(i,s)=>{if(zr(i)||zr(s))return P;let a=Cs(i.value,s.value);return a.valid?((Gr(i)||Gr(s))&&n.dirty(),{status:n.value,value:a.data}):(k(r,{code:E.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,...G(n)});var nt=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.array)return k(r,{code:E.invalid_type,expected:C.array,received:r.parsedType}),P;if(r.data.length<this._def.items.length)return k(r,{code:E.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:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let i=[...r.data].map((s,a)=>{let l=this._def.items[a]||this._def.rest;return l?l._parse(new Ge(r,s,r.path,a)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>_e.mergeArray(n,s)):_e.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,...G(e)})};var $r=class t extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.object)return k(r,{code:E.invalid_type,expected:C.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 Ge(r,a,r.path,a)),value:s._parse(new Ge(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?_e.mergeObjectAsync(n,o):_e.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof $?new t({keyType:e,valueType:n,typeName:D.ZodRecord,...G(r)}):new t({keyType:Et.create(),valueType:e,typeName:D.ZodRecord,...G(n)})}},bn=class extends ${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.map)return k(r,{code:E.invalid_type,expected:C.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 Ge(r,a,r.path,[c,"key"])),value:i._parse(new Ge(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,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return P;(c.status==="dirty"||h.status==="dirty")&&n.dirty(),a.set(c.value,h.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let l of s){let c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return P;(c.status==="dirty"||h.status==="dirty")&&n.dirty(),a.set(c.value,h.value)}return{status:n.value,value:a}}}};bn.create=(t,e,n)=>new bn({valueType:e,keyType:t,typeName:D.ZodMap,...G(n)});var yn=class t extends ${_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.set)return k(r,{code:E.invalid_type,expected:C.set,received:r.parsedType}),P;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(k(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(k(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let i=this._def.valueType;function s(l){let c=new Set;for(let h of l){if(h.status==="aborted")return P;h.status==="dirty"&&n.dirty(),c.add(h.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((l,c)=>i._parse(new Ge(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:R.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:R.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};yn.create=(t,e)=>new yn({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...G(e)});var Br=class t extends ${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.function)return k(n,{code:E.invalid_type,expected:C.function,received:n.parsedType}),P;function r(a,l){return Wn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,hn(),ct].filter(c=>!!c),issueData:{code:E.invalid_arguments,argumentsError:l}})}function o(a,l){return Wn({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,hn(),ct].filter(c=>!!c),issueData:{code:E.invalid_return_type,returnTypeError:l}})}let i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof Tt){let a=this;return Se(async function(...l){let c=new Ne([]),h=await a._def.args.parseAsync(l,i).catch(f=>{throw c.addIssue(r(l,f)),c}),m=await Reflect.apply(s,this,h);return await a._def.returns._def.type.parseAsync(m,i).catch(f=>{throw c.addIssue(o(m,f)),c})})}else{let a=this;return Se(function(...l){let c=a._def.args.safeParse(l,i);if(!c.success)throw new Ne([r(l,c.error)]);let h=Reflect.apply(s,this,c.data),m=a._def.returns.safeParse(h,i);if(!m.success)throw new Ne([o(h,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,...G(r)})}},Ft=class extends ${get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ft.create=(t,e)=>new Ft({getter:t,typeName:D.ZodLazy,...G(e)});var $t=class extends ${_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return k(n,{received:n.data,code:E.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,...G(e)});function Ll(t,e){return new Bt({values:t,typeName:D.ZodEnum,...G(e)})}var Bt=class t extends ${_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:E.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:E.invalid_enum_value,options:r}),P}return Se(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=Ll;var Vt=class extends ${_parse(e){let n=V.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==C.string&&r.parsedType!==C.number){let o=V.objectValues(n);return k(r,{expected:V.joinValues(o),received:r.parsedType,code:E.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:E.invalid_enum_value,options:o}),P}return Se(e.data)}get enum(){return this._def.values}};Vt.create=(t,e)=>new Vt({values:t,typeName:D.ZodNativeEnum,...G(e)});var Tt=class extends ${unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==C.promise&&n.common.async===!1)return k(n,{code:E.invalid_type,expected:C.promise,received:n.parsedType}),P;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return Se(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Tt.create=(t,e)=>new Tt({type:t,typeName:D.ZodPromise,...G(e)});var Fe=class extends ${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(!_t(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=>_t(s)?Promise.resolve(o.transform(s.value,i)).then(a=>({status:n.value,value:a})):P);V.assertNever(o)}};Fe.create=(t,e,n)=>new Fe({schema:t,typeName:D.ZodEffects,effect:e,...G(n)});Fe.createWithPreprocess=(t,e,n)=>new Fe({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...G(n)});var ze=class extends ${_parse(e){return this._getType(e)===C.undefined?Se(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ze.create=(t,e)=>new ze({innerType:t,typeName:D.ZodOptional,...G(e)});var rt=class extends ${_parse(e){return this._getType(e)===C.null?Se(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};rt.create=(t,e)=>new rt({innerType:t,typeName:D.ZodNullable,...G(e)});var jt=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===C.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,...G(e)});var qt=class extends ${_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 Ne(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ne(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,...G(e)});var xn=class extends ${_parse(e){if(this._getType(e)!==C.nan){let r=this._getOrReturnCtx(e);return k(r,{code:E.invalid_type,expected:C.nan,received:r.parsedType}),P}return{status:"valid",value:e.data}}};xn.create=t=>new xn({typeName:D.ZodNaN,...G(t)});var jp=Symbol("zod_brand"),Xn=class extends ${_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Yn=class t extends ${_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 ${_parse(e){let n=this._def.innerType._parse(e),r=o=>(_t(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,...G(e)});function Rl(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Pl(t,e={},n){return t?wt.create().superRefine((r,o)=>{let i=t(r);if(i instanceof Promise)return i.then(s=>{if(!s){let a=Rl(e,r),l=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:l})}});if(!i){let s=Rl(e,r),a=s.fatal??n??!0;o.addIssue({code:"custom",...s,fatal:a})}}):wt.create()}var qp={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 Wp=(t,e={message:`Input not instance of ${t.name}`})=>Pl(n=>n instanceof t,e),Dl=Et.create,Ul=Mt.create,Xp=xn.create,Yp=Lt.create,Hl=Pt.create,Kp=Dt.create,Zp=gn.create,Jp=Ut.create,Qp=Ht.create,eh=wt.create,th=dt.create,nh=qe.create,rh=vn.create,oh=pt.create,ih=Oe.create,sh=Oe.strictCreate,ah=zt.create,lh=Fr.create,ch=Gt.create,uh=nt.create,dh=$r.create,ph=bn.create,hh=yn.create,fh=Br.create,mh=Ft.create,gh=$t.create,vh=Bt.create,bh=Vt.create,yh=Tt.create,xh=Fe.create,_h=ze.create,Eh=rt.create,wh=Fe.createWithPreprocess,Th=Yn.create,Sh=()=>Dl().optional(),Ah=()=>Ul().optional(),kh=()=>Hl().optional(),Ch={string:(t=>Et.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 Ih=P;var Rh=u.object({name:u.string(),arguments:u.string()}),Nh=u.object({id:u.string(),type:u.literal("function"),function:Rh,encryptedValue:u.string().optional()}),Vr=u.object({id:u.string(),role:u.string(),content:u.string().optional(),name:u.string().optional(),encryptedValue:u.string().optional()}),Oh=u.object({type:u.literal("text"),text:u.string()}),Mh=u.object({type:u.literal("data"),value:u.string(),mimeType:u.string()}),Lh=u.object({type:u.literal("url"),value:u.string(),mimeType:u.string().optional()}),jr=u.discriminatedUnion("type",[Mh,Lh]),Ph=u.object({type:u.literal("image"),source:jr,metadata:u.unknown().optional()}),Dh=u.object({type:u.literal("audio"),source:jr,metadata:u.unknown().optional()}),Uh=u.object({type:u.literal("video"),source:jr,metadata:u.unknown().optional()}),Hh=u.object({type:u.literal("document"),source:jr,metadata:u.unknown().optional()});var zl=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()}),Gl=(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"]})},Ry=zl.superRefine((t,e)=>{Gl(t,e)}),zh=u.discriminatedUnion("type",[Oh,Ph,Dh,Uh,Hh,zl]),Gh=zh.superRefine((t,e)=>{t.type==="binary"&&Gl(t,e)}),Fh=Vr.extend({role:u.literal("developer"),content:u.string()}),$h=Vr.extend({role:u.literal("system"),content:u.string()}),Bh=Vr.extend({role:u.literal("assistant"),content:u.string().optional(),toolCalls:u.array(Nh).optional()}),Vh=Vr.extend({role:u.literal("user"),content:u.union([u.string(),u.array(Gh)])}),jh=u.object({id:u.string(),content:u.string(),role:u.literal("tool"),toolCallId:u.string(),error:u.string().optional(),encryptedValue:u.string().optional()}),qh=u.object({id:u.string(),role:u.literal("activity"),activityType:u.string(),content:u.record(u.any())}),Wh=u.object({id:u.string(),role:u.literal("reasoning"),content:u.string(),encryptedValue:u.string().optional()}),Fl=u.discriminatedUnion("role",[Fh,$h,Bh,Vh,jh,qh,Wh]),Ny=u.union([u.literal("developer"),u.literal("system"),u.literal("assistant"),u.literal("user"),u.literal("tool"),u.literal("activity"),u.literal("reasoning")]),Xh=u.object({description:u.string(),value:u.string()}),$l=u.object({name:u.string(),description:u.string(),parameters:u.any(),metadata:u.record(u.any()).optional()}),Yh=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()}),Kh=u.object({interruptId:u.string(),status:u.enum(["resolved","cancelled"]),payload:u.any().optional()}),Zh=u.object({threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),state:u.any(),messages:u.array(Fl),tools:u.array($l),context:u.array(Xh),forwardedProps:u.any(),resume:u.array(Kh).optional()}),Jh=u.any(),ee=class extends Error{constructor(t){super(t)}},Is=class extends ee{constructor(){super("Connect not implemented. This method is not supported by the current agent.")}},Qh=u.object({name:u.string(),description:u.string().optional()}),ef=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()}),tf=u.object({streaming:u.boolean().optional(),websocket:u.boolean().optional(),httpBinary:u.boolean().optional(),pushNotifications:u.boolean().optional(),resumable:u.boolean().optional()}),nf=u.object({supported:u.boolean().optional(),items:u.array($l).optional(),parallelCalls:u.boolean().optional(),clientProvided:u.boolean().optional()}),rf=u.object({structuredOutput:u.boolean().optional(),supportedMimeTypes:u.array(u.string()).optional()}),of=u.object({snapshots:u.boolean().optional(),deltas:u.boolean().optional(),memory:u.boolean().optional(),persistentState:u.boolean().optional()}),sf=u.object({supported:u.boolean().optional(),delegation:u.boolean().optional(),handoffs:u.boolean().optional(),subAgents:u.array(Qh).optional()}),af=u.object({supported:u.boolean().optional(),streaming:u.boolean().optional(),encrypted:u.boolean().optional()}),lf=u.object({image:u.boolean().optional(),audio:u.boolean().optional(),video:u.boolean().optional(),pdf:u.boolean().optional(),file:u.boolean().optional()}),cf=u.object({image:u.boolean().optional(),audio:u.boolean().optional()}),uf=u.object({input:lf.optional(),output:cf.optional()}),df=u.object({codeExecution:u.boolean().optional(),sandboxed:u.boolean().optional(),maxIterations:u.number().optional(),maxExecutionTime:u.number().optional()}),pf=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()}),Oy=u.object({identity:ef.optional(),transport:tf.optional(),tools:nf.optional(),output:rf.optional(),state:of.optional(),multiAgent:sf.optional(),reasoning:af.optional(),multimodal:uf.optional(),execution:df.optional(),humanInTheLoop:pf.optional(),custom:u.record(u.unknown()).optional()}),Bl=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(),hf=X.extend({type:u.literal(v.TEXT_MESSAGE_START),messageId:u.string(),role:Bl.default("assistant"),name:u.string().optional()}),Vl=X.extend({type:u.literal(v.TEXT_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),ff=X.extend({type:u.literal(v.TEXT_MESSAGE_END),messageId:u.string()}),mf=X.extend({type:u.literal(v.TEXT_MESSAGE_CHUNK),messageId:u.string().optional(),role:Bl.optional(),delta:u.string().optional(),name:u.string().optional()}),gf=X.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_START)}),vf=Vl.omit({messageId:!0,type:!0}).extend({type:u.literal(v.THINKING_TEXT_MESSAGE_CONTENT)}),bf=X.extend({type:u.literal(v.THINKING_TEXT_MESSAGE_END)}),yf=X.extend({type:u.literal(v.TOOL_CALL_START),toolCallId:u.string(),toolCallName:u.string(),parentMessageId:u.string().optional()}),xf=X.extend({type:u.literal(v.TOOL_CALL_ARGS),toolCallId:u.string(),delta:u.string()}),_f=X.extend({type:u.literal(v.TOOL_CALL_END),toolCallId:u.string()}),Ef=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()}),Tf=X.extend({type:u.literal(v.THINKING_START),title:u.string().optional()}),Sf=X.extend({type:u.literal(v.THINKING_END)}),Af=X.extend({type:u.literal(v.STATE_SNAPSHOT),snapshot:Jh}),kf=X.extend({type:u.literal(v.STATE_DELTA),delta:u.array(u.any())}),Cf=X.extend({type:u.literal(v.MESSAGES_SNAPSHOT),messages:u.array(Fl)}),If=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)}),Rf=X.extend({type:u.literal(v.ACTIVITY_DELTA),messageId:u.string(),activityType:u.string(),patch:u.array(u.any())}),Nf=X.extend({type:u.literal(v.RAW),event:u.any(),source:u.string().optional()}),Of=X.extend({type:u.literal(v.CUSTOM),name:u.string(),value:u.any()}),Mf=X.extend({type:u.literal(v.RUN_STARTED),threadId:u.string(),runId:u.string(),parentRunId:u.string().optional(),input:Zh.optional()}),Lf=u.object({type:u.literal("success")}).strict(),Pf=u.object({type:u.literal("interrupt"),interrupts:u.array(Yh).min(1)}).strict(),Df=u.discriminatedUnion("type",[Lf,Pf]),Uf=X.extend({type:u.literal(v.RUN_FINISHED),threadId:u.string(),runId:u.string(),result:u.any().optional(),outcome:Df.nullable().optional().transform(t=>t??void 0)}),Hf=X.extend({type:u.literal(v.RUN_ERROR),message:u.string(),code:u.string().optional()}),zf=X.extend({type:u.literal(v.STEP_STARTED),stepName:u.string()}),Gf=X.extend({type:u.literal(v.STEP_FINISHED),stepName:u.string()}),Ff=u.union([u.literal("tool-call"),u.literal("message")]),$f=X.extend({type:u.literal(v.REASONING_START),messageId:u.string()}),Bf=X.extend({type:u.literal(v.REASONING_MESSAGE_START),messageId:u.string(),role:u.literal("reasoning")}),Vf=X.extend({type:u.literal(v.REASONING_MESSAGE_CONTENT),messageId:u.string(),delta:u.string()}),jf=X.extend({type:u.literal(v.REASONING_MESSAGE_END),messageId:u.string()}),qf=X.extend({type:u.literal(v.REASONING_MESSAGE_CHUNK),messageId:u.string().optional(),delta:u.string().optional()}),Wf=X.extend({type:u.literal(v.REASONING_END),messageId:u.string()}),Xf=X.extend({type:u.literal(v.REASONING_ENCRYPTED_VALUE),subtype:Ff,entityId:u.string(),encryptedValue:u.string()}),qr=u.discriminatedUnion("type",[hf,Vl,ff,mf,Tf,Sf,gf,vf,bf,yf,xf,_f,wf,Ef,Af,kf,Cf,If,Rf,Nf,Of,Mf,Uf,Hf,zf,Gf,$f,Bf,Vf,jf,qf,Wf,Xf]);var Rs={};ji(Rs,{JsonPatchError:()=>he,_areEquals:()=>Jn,applyOperation:()=>Xt,applyPatch:()=>Qr,applyReducer:()=>Qf,deepClone:()=>Zf,getValueByPointer:()=>Zr,validate:()=>ql,validator:()=>Jr});var Yf=(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)}})(),Kf=Object.prototype.hasOwnProperty;function Xr(t,e){return Kf.call(t,e)}function Yr(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)Xr(t,o)&&r.push(o);return r}function Ee(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function Kr(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 Kn(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Wr(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(var e=0,n=t.length;e<n;e++)if(Wr(t[e]))return!0}else if(typeof t=="object"){for(var r=Yr(t),o=r.length,i=0;i<o;i++)if(Wr(t[r[i]]))return!0}}return!1}function jl(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
2
|
`)}var Zn=(function(t){Yf(e,t);function e(n,r,o,i,s){var a=this.constructor,l=t.call(this,jl(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=jl(n,{name:r,index:o,operation:i,tree:s}),l}return e})(Error);var he=Zn,Zf=Ee,_n={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=Zr(n,this.path);r&&(r=Ee(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=Zr(n,this.from);return Xt(n,{op:"add",path:this.path,value:Ee(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:Jn(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}},Jf={add:function(t,e,n){return Kr(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:_n.move,copy:_n.copy,test:_n.test,_get:_n._get};function Zr(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):Jr(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=Zr(t,e.from),e.op==="move"&&(s.removed=t),s;if(e.op==="test"){if(s.test=Jn(t,e.value),s.test===!1)throw new he("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 he("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return s}}else{r||(t=Ee(t));var a=e.path||"",l=a.split("/"),c=t,h=1,m=l.length,y=void 0,f=void 0,p=void 0;for(typeof n=="function"?p=n:p=Jr;;){if(f=l[h],f&&f.indexOf("~")!=-1&&(f=Kn(f)),o&&(f=="__proto__"||f=="prototype"&&h>0&&l[h-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[f]===void 0?y=l.slice(0,h).join("/"):h==m-1&&(y=e.path),y!==void 0&&p(e,0,t,y)),h++,Array.isArray(c)){if(f==="-")f=c.length;else{if(n&&!Kr(f))throw new he("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);Kr(f)&&(f=~~f)}if(h>=m){if(n&&e.op==="add"&&f>c.length)throw new he("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=Jf[e.op].call(e,c,f,t);if(s.test===!1)throw new he("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}}else if(h>=m){var s=_n[e.op].call(e,c,f,t);if(s.test===!1)throw new he("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return s}if(c=c[f],n&&h<m&&(!c||typeof c!="object"))throw new he("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}function Qr(t,e,n,r,o){if(r===void 0&&(r=!0),o===void 0&&(o=!0),n&&!Array.isArray(e))throw new he("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=Ee(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 Qf(t,e,n){var r=Xt(t,e);if(r.test===!1)throw new he("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Jr(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new he("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(_n[t.op]){if(typeof t.path!="string")throw new he("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new he('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 he("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 he("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")&&Wr(t.value))throw new he("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 he("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 he("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=ql([s],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new he("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new he("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function ql(t,e,n){try{if(!Array.isArray(t))throw new he("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Qr(Ee(e),Ee(t),n||!0);else{n=n||Jr;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(o){if(o instanceof he)return o;throw o}}function Jn(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(!Jn(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],!Jn(t[s],e[s]))return!1;return!0}return t!==t&&e!==e}var Ls={};ji(Ls,{compare:()=>am,generate:()=>Ns,observe:()=>sm,unobserve:()=>im});var Os=new WeakMap,em=(function(){function t(e){this.observers=new Map,this.obj=e}return t})(),tm=(function(){function t(e,n){this.callback=e,this.observer=n}return t})();function nm(t){return Os.get(t)}function rm(t,e){return t.observers.get(e)}function om(t,e){t.observers.delete(e.callback)}function im(t,e){e.unobserve()}function sm(t,e){var n=[],r,o=nm(t);if(!o)o=new em(t),Os.set(t,o);else{var i=rm(o,e);r=i&&i.observer}if(r)return r;if(r={},o.value=Ee(t),e){r.callback=e,r.next=null;var s=function(){Ns(r)},a=function(){clearTimeout(r.next),r.next=setTimeout(s)};typeof window<"u"&&(window.addEventListener("mouseup",a),window.addEventListener("keyup",a),window.addEventListener("mousedown",a),window.addEventListener("keydown",a),window.addEventListener("change",a))}return r.patches=n,r.object=t,r.unobserve=function(){Ns(r),clearTimeout(r.next),om(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 tm(e,r)),r}function Ns(t,e){e===void 0&&(e=!1);var n=Os.get(t.object);Ms(n.value,t.object,t.patches,"",e),t.patches.length&&Qr(n.value,t.patches);var r=t.patches;return r.length>0&&(t.patches=[],t.callback&&t.callback(r)),r}function Ms(t,e,n,r,o){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var i=Yr(e),s=Yr(t),a=!1,l=!1,c=s.length-1;c>=0;c--){var h=s[c],m=t[h];if(Xr(e,h)&&!(e[h]===void 0&&m!==void 0&&Array.isArray(e)===!1)){var y=e[h];typeof m=="object"&&m!=null&&typeof y=="object"&&y!=null&&Array.isArray(m)===Array.isArray(y)?Ms(m,y,n,r+"/"+ot(h),o):m!==y&&(a=!0,o&&n.push({op:"test",path:r+"/"+ot(h),value:Ee(m)}),n.push({op:"replace",path:r+"/"+ot(h),value:Ee(y)}))}else Array.isArray(t)===Array.isArray(e)?(o&&n.push({op:"test",path:r+"/"+ot(h),value:Ee(m)}),n.push({op:"remove",path:r+"/"+ot(h)}),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 h=i[c];!Xr(t,h)&&e[h]!==void 0&&n.push({op:"add",path:r+"/"+ot(h),value:Ee(e[h])})}}}function am(t,e,n){n===void 0&&(n=!1);var r=[];return Ms(t,e,r,"",n),r}var eo=Object.assign({},Rs,Ls,{JsonPatchError:Zn,deepClone:Ee,escapePathComponent:ot,unescapePathComponent:Kn});var Ps=function(t,e){return Ps=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])},Ps(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");Ps(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function Wl(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(h){try{c(r.next(h))}catch(m){s(m)}}function l(h){try{c(r.throw(h))}catch(m){s(m)}}function c(h){h.done?i(h.value):o(h.value).then(a,l)}c((r=r.apply(t,e||[])).next())})}function to(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(h){return l([c,h])}}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(h){c=[6,h],o=0}finally{r=i=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}}function ht(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 wn(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 Xl(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),o,i=[];return o=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",s),o[Symbol.asyncIterator]=function(){return this},o;function s(f){return function(p){return Promise.resolve(p).then(f,m)}}function a(f,p){r[f]&&(o[f]=function(g){return new Promise(function(x,S){i.push([f,g,x,S])>1||l(f,g)})},p&&(o[f]=p(o[f])))}function l(f,p){try{c(r[f](p))}catch(g){y(i[0][3],g)}}function c(f){f.value instanceof Yt?Promise.resolve(f.value.v).then(h,m):y(i[0][2],f)}function h(f){l("next",f)}function m(f){l("throw",f)}function y(f,p){f(p),i.shift(),i.length&&l(i[0][0],i[0][1])}}function Yl(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 ht=="function"?ht(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 no=Tn(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 Qn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Sn=(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=ht(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 h=this.initialTeardown;if(B(h))try{h()}catch(g){i=g instanceof no?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=ht(m),f=y.next();!f.done;f=y.next()){var p=f.value;try{Kl(p)}catch(g){i=i??[],g instanceof no?i=wn(wn([],En(i)),En(g.errors)):i.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(i)throw new no(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Kl(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)&&Qn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Qn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Ds=Sn.EMPTY;function ro(t){return t instanceof Sn||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function Kl(t){B(t)?t():t.unsubscribe()}var We={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var An={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=An.delegate;return o?.setTimeout?o.setTimeout.apply(o,wn([t,e],En(n))):setTimeout.apply(void 0,wn([t,e],En(n)))},clearTimeout:function(t){var e=An.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function oo(t){An.setTimeout(function(){var e=We.onUnhandledError;if(e)e(t);else throw t})}function er(){}var Zl=(function(){return Us("C",void 0,void 0)})();function Jl(t){return Us("E",void 0,t)}function Ql(t){return Us("N",t,void 0)}function Us(t,e,n){return{kind:t,value:e,error:n}}var Kt=null;function kn(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 ec(t){We.useDeprecatedSynchronousErrorHandling&&Kt&&(Kt.errorThrown=!0,Kt.error=t)}var tr=(function(t){it(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,ro(n)&&n.add(r)):r.destination=dm,r}return e.create=function(n,r,o){return new so(n,r,o)},e.prototype.next=function(n){this.isStopped?zs(Ql(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?zs(Jl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?zs(Zl,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})(Sn);var lm=Function.prototype.bind;function Hs(t,e){return lm.call(t,e)}var cm=(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){io(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){io(r)}else io(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){io(n)}},t})(),so=(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&&Hs(n.next,a),error:n.error&&Hs(n.error,a),complete:n.complete&&Hs(n.complete,a)}):s=n}return i.destination=new cm(s),i}return e})(tr);function io(t){We.useDeprecatedSynchronousErrorHandling?ec(t):oo(t)}function um(t){throw t}function zs(t,e){var n=We.onStoppedNotification;n&&An.setTimeout(function(){return n(t,e)})}var dm={closed:!0,next:er,error:um,complete:er};var In=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function Cn(t){return t}function ao(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Gs(t)}function Gs(t){return t.length===0?Cn: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=hm(e)?e:new so(e,n,r);return kn(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=tc(n),new n(function(o,i){var s=new so({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[In]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Gs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=tc(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 tc(t){var e;return(e=t??We.Promise)!==null&&e!==void 0?e:Promise}function pm(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function hm(t){return t&&t instanceof tr||pm(t)&&ro(t)}function fm(t){return B(t?.lift)}function fe(t){return function(e){if(fm(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 mm(t,e,n,r,o)}var mm=(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(h){n.error(h)}}:t.prototype._next,l._error=i?function(c){try{i(c)}catch(h){n.error(h)}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})(tr);var nc=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 rc(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new nc},e.prototype.next=function(n){var r=this;kn(function(){var o,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=ht(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;kn(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;kn(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?Ds:(this.currentObservers=null,a.push(n),new Sn(function(){r.currentObservers=null,Qn(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 rc(n,r)},e})(te);var rc=(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:Ds},e})(st);var Fs={now:function(){return(Fs.delegate||Date).now()},delegate:void 0};var lo=(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=Fs);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,h=1;h<i.length&&i[h]<=l;h+=2)c=h;c&&i.splice(0,c+1)}},e})(st);var co=new te(function(t){return t.complete()});function oc(t){return t&&B(t.schedule)}function gm(t){return t[t.length-1]}function ic(t){return oc(gm(t))?t.pop():void 0}var uo=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function po(t){return B(t?.then)}function ho(t){return B(t[In])}function fo(t){return Symbol.asyncIterator&&B(t?.[Symbol.asyncIterator])}function mo(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 vm(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var go=vm();function vo(t){return B(t?.[go])}function bo(t){return Xl(this,arguments,function(){var n,r,o,i;return to(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 yo(t){return B(t?.getReader)}function ve(t){if(t instanceof te)return t;if(t!=null){if(ho(t))return bm(t);if(uo(t))return ym(t);if(po(t))return xm(t);if(fo(t))return sc(t);if(vo(t))return _m(t);if(yo(t))return Em(t)}throw mo(t)}function bm(t){return new te(function(e){var n=t[In]();if(B(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ym(t){return new te(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function xm(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,oo)})}function _m(t){return new te(function(e){var n,r;try{for(var o=ht(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 sc(t){return new te(function(e){wm(t,e).catch(function(n){return e.error(n)})})}function Em(t){return sc(bo(t))}function wm(t,e){var n,r,o,i;return Wl(this,void 0,void 0,function(){var s,a;return to(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Yl(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 $e(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 xo(t,e){return e===void 0&&(e=0),fe(function(n,r){n.subscribe(ge(r,function(o){return $e(r,t,function(){return r.next(o)},e)},function(){return $e(r,t,function(){return r.complete()},e)},function(o){return $e(r,t,function(){return r.error(o)},e)}))})}function _o(t,e){return e===void 0&&(e=0),fe(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function ac(t,e){return ve(t).pipe(_o(e),xo(e))}function lc(t,e){return ve(t).pipe(_o(e),xo(e))}function cc(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 uc(t,e){return new te(function(n){var r;return $e(n,e,function(){r=t[go](),$e(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 Eo(t,e){if(!t)throw new Error("Iterable cannot be null");return new te(function(n){$e(n,e,function(){var r=t[Symbol.asyncIterator]();$e(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function dc(t,e){return Eo(bo(t),e)}function pc(t,e){if(t!=null){if(ho(t))return ac(t,e);if(uo(t))return cc(t,e);if(po(t))return lc(t,e);if(fo(t))return Eo(t,e);if(vo(t))return uc(t,e);if(yo(t))return dc(t,e)}throw mo(t)}function Zt(t,e){return e?pc(t,e):ve(t)}function ue(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=ic(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 hc=Tn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function wo(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 hc)}})})}function Jt(t,e){return fe(function(n,r){var o=0;n.subscribe(ge(r,function(i){r.next(t.call(e,i,o++))}))})}function fc(t,e,n,r,o,i,s,a){var l=[],c=0,h=0,m=!1,y=function(){m&&!l.length&&!c&&e.complete()},f=function(g){return c<r?p(g):l.push(g)},p=function(g){i&&e.next(g),c++;var x=!1;ve(n(g,h++)).subscribe(ge(e,function(S){o?.(S),i?f(S):e.next(S)},function(){x=!0},void 0,function(){if(x)try{c--;for(var S=function(){var w=l.shift();s?$e(e,s,function(){return p(w)}):p(w)};l.length&&c<r;)S();y()}catch(w){e.error(w)}}))};return t.subscribe(ge(e,f,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),fe(function(r,o){return fc(r,o,t,n)}))}function $s(t){return t===void 0&&(t=1/0),Me(Cn,t)}function To(t){return new te(function(e){ve(t()).subscribe(e)})}function nr(t){return fe(function(e,n){var r=null,o=!1,i;r=e.subscribe(ge(n,void 0,void 0,function(s){i=ve(t(s,nr(t)(e))),r?(r.unsubscribe(),r=null,i.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,i.subscribe(n))})}function So(t,e){return B(e)?Me(t,e,1):Me(t,1)}function Bs(t){return fe(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 fe(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function Vs(t,e){return fe(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,h=i++;ve(t(l,h)).subscribe(o=ge(r,function(m){return r.next(e?e(l,m,h,c++):m)},function(){o=null,a()}))},function(){s=!0,a()}))})}function Ao(t){return fe(function(e,n){ve(t).subscribe(ge(n,function(){return n.complete()},er)),!n.closed&&e.subscribe(n)})}function js(t,e,n){var r=B(t)||e||n?{next:t,error:e,complete:n}:t;return r?fe(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)}))}):Cn}function mc(t){return` \r
|
|
5
|
-
`.indexOf(t)>=0}function ko(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)},h=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}},f=t.length;n<f;n++){var p=t[n];switch(e[e.length-1]){case"topLevel":y(p);break;case"string":switch(p){case'"':h();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":p==="u"?s("stringUnicode"):(c("stringEscape"),h());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),h());break;case"number":p==="."?a("numberNeedsDigit"):p==="e"||p==="E"?a("numberNeedsExponent"):(p<"0"||p>"9")&&(m(),h());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(),h());break;case"arrayNeedsValue":p==="]"?h():mc(p)||(c("collectionItem"),a("arrayNeedsComma"),y(p));break;case"arrayNeedsComma":p==="]"?h():p===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":p==="}"?h():p==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":p===":"&&a("objectNeedsValue");break;case"objectNeedsValue":mc(p)||(c("collectionItem"),a("objectNeedsComma"),y(p));break;case"objectNeedsComma":p==="}"?h():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])))},S=e.length-1;S>=0;S--)switch(e[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":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 vc(){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 Co(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 Io=4294967296;function qs(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>=Io&&(o=o+(r/Io|0),r=r%Io)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),e?yc(r,o):Xs(r,o)}function bc(t,e){let n=Xs(t,e),r=n.hi&2147483648;r&&(n=yc(n.lo,n.hi));let o=Ws(n.lo,n.hi);return r?"-"+o:o}function Ws(t,e){if({lo:t,hi:e}=Tm(t,e),e<=2097151)return String(Io*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()+gc(s)+gc(i)}function Tm(t,e){return{lo:t>>>0,hi:e>>>0}}function Xs(t,e){return{lo:t|0,hi:e|0}}function yc(t,e){return e=~e,t?t=~t+1:e+=1,Xs(t,e)}var gc=t=>{let e=String(t);return"0000000".slice(e.length)+e};function Ys(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 xc(){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=Sm();function Sm(){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()),_c(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),Ec(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),_c(n),qs(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),Ec(n),qs(n)},dec(n,r){return bc(n,r)},uDec(n,r){return Ws(n,r)}}}function _c(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function Ec(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var Ks=Symbol.for("@bufbuild/protobuf/text-encoding");function Zs(){if(globalThis[Ks]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[Ks]={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[Ks]}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 Am=34028234663852886e22,km=-34028234663852886e22,Im=4294967295,Cm=2147483647,Rm=-2147483648,F=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(wc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Js(e),Ys(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){wc(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,Ys(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 Co(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 Co(o,i,this.buf),this}uint64(e){let n=Xe.uEnc(e);return Co(n.lo,n.hi,this.buf),this}},A=class{constructor(e,n=Zs().decodeUtf8){this.decodeUtf8=n,this.varint64=vc,this.uint32=xc,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 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>Cm||t<Rm)throw new Error("invalid int32: "+t)}function wc(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>Im||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>Am||t<km))throw new Error("invalid float32: "+t)}var Om=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Qs(){return{fields:{}}}var rr={encode(t,e=new F){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&na.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=na.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 rr.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 Tc(){return{key:"",value:void 0}}var na={encode(t,e=new F){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=Tc();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 na.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.key=t.key??"",e.value=t.value??void 0,e}};function ea(){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 F){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&&rr.encode(rr.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&or.encode(or.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=ea();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=rr.unwrap(rr.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.listValue=or.unwrap(or.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=ea();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=ea();if(t===null)e.nullValue=Om.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 ta(){return{values:[]}}var or={encode(t,e=new F){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=ta();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 or.fromPartial(t??{})},fromPartial(t){let e=ta();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=ta();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},Mm=(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 Sc(){return{op:0,path:"",from:void 0,value:void 0}}var No={encode(t,e=new F){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=Sc();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 No.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Ac(){return{id:"",type:"",function:void 0}}var Oo={encode(t,e=new F){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&Mo.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof 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.id=n.string();continue;case 2:if(i!==18)break;o.type=n.string();continue;case 3:if(i!==26)break;o.function=Mo.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=Ac();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?Mo.fromPartial(t.function):void 0,e}};function kc(){return{name:"",arguments:""}}var Mo={encode(t,e=new F){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=kc();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 Mo.fromPartial(t??{})},fromPartial(t){let e=kc();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Ic(){return{value:"",mimeType:""}}var Lo={encode(t,e=new F){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=Ic();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 Lo.fromPartial(t??{})},fromPartial(t){let e=Ic();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Cc(){return{value:"",mimeType:void 0}}var Po={encode(t,e=new F){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=Cc();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 Po.fromPartial(t??{})},fromPartial(t){let e=Cc();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Rc(){return{data:void 0,url:void 0}}var De={encode(t,e=new F){return t.data!==void 0&&Lo.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Po.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=Rc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.data=Lo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.url=Po.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return De.fromPartial(t??{})},fromPartial(t){let e=Rc();return e.data=t.data!==void 0&&t.data!==null?Lo.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Po.fromPartial(t.url):void 0,e}};function Nc(){return{text:""}}var Do={encode(t,e=new F){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=Nc();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 Do.fromPartial(t??{})},fromPartial(t){let e=Nc();return e.text=t.text??"",e}};function Oc(){return{source:void 0,metadata:void 0}}var Uo={encode(t,e=new F){return t.source!==void 0&&De.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=Oc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=De.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=Oc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Mc(){return{source:void 0,metadata:void 0}}var Ho={encode(t,e=new F){return t.source!==void 0&&De.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=De.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 Ho.fromPartial(t??{})},fromPartial(t){let e=Mc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Lc(){return{source:void 0,metadata:void 0}}var zo={encode(t,e=new F){return t.source!==void 0&&De.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=Lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=De.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 zo.fromPartial(t??{})},fromPartial(t){let e=Lc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Pc(){return{source:void 0,metadata:void 0}}var Go={encode(t,e=new F){return t.source!==void 0&&De.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=Pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=De.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 Go.fromPartial(t??{})},fromPartial(t){let e=Pc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Dc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Fo={encode(t,e=new F){return t.text!==void 0&&Do.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Uo.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Ho.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&zo.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Go.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=Dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=Do.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.image=Uo.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.audio=Ho.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.video=zo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.document=Go.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=Dc();return e.text=t.text!==void 0&&t.text!==null?Do.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Uo.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Ho.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?zo.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Go.fromPartial(t.document):void 0,e}};function Uc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var $o={encode(t,e=new F){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)Oo.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)Fo.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=Uc();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(Oo.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(Fo.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=Uc();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=>Oo.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Fo.fromPartial(n))||[],e}};function Hc(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Bo={encode(t,e=new F){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=Hc();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 Bo.fromPartial(t??{})},fromPartial(t){let e=Hc();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}},Lm=(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 zc(){return{type:0,timestamp:void 0,rawEvent:void 0}}var M={encode(t,e=new F){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=zc();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=Pm(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=zc();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function Gc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Vo={encode(t,e=new F){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=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.name=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=Gc();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 Fc(){return{baseEvent:void 0,messageId:"",delta:""}}var jo={encode(t,e=new F){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=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.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 jo.fromPartial(t??{})},fromPartial(t){let e=Fc();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 qo={encode(t,e=new F){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 qo.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 Bc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Wo={encode(t,e=new F){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=Bc();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 Wo.fromPartial(t??{})},fromPartial(t){let e=Bc();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 Vc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Xo={encode(t,e=new F){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=Vc();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 Xo.fromPartial(t??{})},fromPartial(t){let e=Vc();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 jc(){return{baseEvent:void 0,toolCallId:""}}var Yo={encode(t,e=new F){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=jc();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 Yo.fromPartial(t??{})},fromPartial(t){let e=jc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function qc(){return{baseEvent:void 0,snapshot:void 0}}var Ko={encode(t,e=new F){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=qc();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 Ko.fromPartial(t??{})},fromPartial(t){let e=qc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Wc(){return{baseEvent:void 0,delta:[]}}var Zo={encode(t,e=new F){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)No.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=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.delta.push(No.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=Wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>No.fromPartial(n))||[],e}};function Xc(){return{baseEvent:void 0,messages:[]}}var Jo={encode(t,e=new F){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)$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=Xc();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($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=Xc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>$o.fromPartial(n))||[],e}};function Yc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Qo={encode(t,e=new F){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=Yc();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 Qo.fromPartial(t??{})},fromPartial(t){let e=Yc();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 Kc(){return{baseEvent:void 0,name:"",value:void 0}}var ei={encode(t,e=new F){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=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.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 ei.fromPartial(t??{})},fromPartial(t){let e=Kc();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 Zc(){return{baseEvent:void 0,threadId:"",runId:""}}var ti={encode(t,e=new F){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=Zc();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 ti.fromPartial(t??{})},fromPartial(t){let e=Zc();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 Jc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var ni={encode(t,e=new F){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)Bo.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=Jc();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(Bo.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ni.fromPartial(t??{})},fromPartial(t){let e=Jc();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=>Bo.fromPartial(n))||[],e}};function Qc(){return{baseEvent:void 0,code:void 0,message:""}}var ri={encode(t,e=new F){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=Qc();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 ri.fromPartial(t??{})},fromPartial(t){let e=Qc();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 eu(){return{baseEvent:void 0,stepName:""}}var oi={encode(t,e=new F){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=eu();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 oi.fromPartial(t??{})},fromPartial(t){let e=eu();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function tu(){return{baseEvent:void 0,stepName:""}}var ii={encode(t,e=new F){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=tu();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 ii.fromPartial(t??{})},fromPartial(t){let e=tu();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function nu(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var si={encode(t,e=new F){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=nu();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 si.fromPartial(t??{})},fromPartial(t){let e=nu();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 ru(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var ai={encode(t,e=new F){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=ru();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 ai.fromPartial(t??{})},fromPartial(t){let e=ru();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 ou(){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 iu={encode(t,e=new F){return t.textMessageStart!==void 0&&Vo.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&jo.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&qo.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Wo.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Xo.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Yo.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Ko.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Zo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Jo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Qo.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&ei.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&ti.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&ni.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&ri.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&oi.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&ii.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&si.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&ai.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=ou();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.textMessageStart=Vo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.textMessageContent=jo.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.textMessageEnd=qo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.toolCallStart=Wo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.toolCallArgs=Xo.decode(n,n.uint32());continue;case 6:if(i!==50)break;o.toolCallEnd=Yo.decode(n,n.uint32());continue;case 7:if(i!==58)break;o.stateSnapshot=Ko.decode(n,n.uint32());continue;case 8:if(i!==66)break;o.stateDelta=Zo.decode(n,n.uint32());continue;case 9:if(i!==74)break;o.messagesSnapshot=Jo.decode(n,n.uint32());continue;case 10:if(i!==82)break;o.raw=Qo.decode(n,n.uint32());continue;case 11:if(i!==90)break;o.custom=ei.decode(n,n.uint32());continue;case 12:if(i!==98)break;o.runStarted=ti.decode(n,n.uint32());continue;case 13:if(i!==106)break;o.runFinished=ni.decode(n,n.uint32());continue;case 14:if(i!==114)break;o.runError=ri.decode(n,n.uint32());continue;case 15:if(i!==122)break;o.stepStarted=oi.decode(n,n.uint32());continue;case 16:if(i!==130)break;o.stepFinished=ii.decode(n,n.uint32());continue;case 17:if(i!==138)break;o.textMessageChunk=si.decode(n,n.uint32());continue;case 18:if(i!==146)break;o.toolCallChunk=ai.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return iu.fromPartial(t??{})},fromPartial(t){let e=ou();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Vo.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?jo.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?qo.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Wo.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Xo.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Yo.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Ko.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Zo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Jo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Qo.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?ei.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?ti.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?ni.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?ri.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?oi.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?ii.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?si.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?ai.fromPartial(t.toolCallChunk):void 0,e}};function Pm(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 Ro=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}}},Dm=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:Ro(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:Ro(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:Ro(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:Ro(t.document.source),metadata:t.document.metadata}}};function su(t){let e=iu.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=Lm[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=>Dm(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=Mm[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]}),qr.parse(n)}var ra="application/vnd.ag-ui.event+proto";var Hm=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,oa=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(Hm);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},au=t=>t==="*"||t==="x"||t==="X",lu=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},zm=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Gm=(t,e)=>{if(au(t)||au(e))return 0;let[n,r]=zm(lu(t),lu(e));return n>r?1:n<r?-1:0},ia=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=Gm(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var ir=(t,e)=>{let n=oa(t),r=oa(e),o=n.pop(),i=r.pop(),s=ia(n,r);return s!==0?s:o&&i?ia(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 Ue(){return xt()}function la(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&la(e);return t}var cu=512*1024;function uu(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&&!uu(e,n,cu),l=a?q(e):e,c=a?q(n):n,h=!1,m=!1,y;for(let f of t)try{a&&(la(l),la(c));let p=await r(f,l,c);if(p===void 0)continue;let g=!1;if(p.messages!==void 0&&p.messages!==l&&(l=q(p.messages),h=!0,g=!0),p.state!==void 0&&p.state!==c&&(c=q(p.state),m=!0,g=!0),a&&g&&uu(l,c,cu)&&(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{...h?{messages:Object.isFrozen(l)?q(l):l}:{},...m?{state:Object.isFrozen(c)?q(c):c}:{},...y===void 0?{}:{stopPropagation:y}}}function li(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 sr(t){if(t instanceof ca)return t;if(t===!0)return new ca(li(!0))}var ca=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 sa(t){return t.enabled?new ca(t):void 0}function Fm(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 gu=(t,e,n,r,o)=>{let i=sr(o),s=q(n.messages),a=q(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)},h=()=>{let m=q(l);return l={},m.messages!==void 0||m.state!==void 0?ue(m):co};return e.pipe(So(async m=>{let y=await K(r,s,a,(f,p,g)=>f.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 h();switch(m.type){case v.TEXT_MESSAGE_START:{let f=await K(r,s,a,(p,g,x)=>p.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:p,role:g="assistant",name:x}=m;if(!s.find(S=>S.id===p)){let S={id:p,role:g,content:"",...x!==void 0&&{name:x}};s.push(S),c({messages:s})}}return h()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:f,delta:p}=m,g=s.find(S=>S.id===f);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${f}'`),h();let x=await K(r,s,a,(S,w,C)=>S.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})),h()}case v.TEXT_MESSAGE_END:{let{messageId:f}=m,p=s.find(g=>g.id===f);return p?(c(await K(r,s,a,(g,x,S)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:S,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})})),h()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${f}'`),h())}case v.TOOL_CALL_START:{let f=await K(r,s,a,(p,g,x)=>p.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{toolCallId:p,toolCallName:g,parentMessageId:x}=m,S=Fm(s,x,p);S.toolCalls??=[],S.toolCalls.push({id:p,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return h()}case v.TOOL_CALL_ARGS:{let{toolCallId:f,delta:p}=m,g=s.find(w=>w.toolCalls?.some(C=>C.id===f));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${f}'`),h();let x=g.toolCalls?.find(w=>w.id===f);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${f}'`),h();let S=await K(r,s,a,(w,C,H)=>{let U=x.function.arguments,Y=x.function.name,re={};try{re=ko(U)}catch{}return w.onToolCallArgsEvent?.({event:m,messages:C,state:H,agent:n,input:t,toolCallBuffer:U,toolCallName:Y,partialToolCallArgs:re})});return c(S),S.stopPropagation!==!0&&(x.function.arguments+=p,c({messages:s})),h()}case v.TOOL_CALL_END:{let{toolCallId:f}=m,p=s.find(x=>x.toolCalls?.some(S=>S.id===f));if(!p)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${f}'`),h();let g=p.toolCalls?.find(x=>x.id===f);return g?(c(await K(r,s,a,(x,S,w)=>{let C=g.function.arguments,H=g.function.name,U={};try{U=JSON.parse(C)}catch{}return x.onToolCallEndEvent?.({event:m,messages:S,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})})),h()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${f}'`),h())}case v.TOOL_CALL_RESULT:{let f=await K(r,s,a,(p,g,x)=>p.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:p,toolCallId:g,content:x,role:S}=m,w={id:p,toolCallId:g,role:S||"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 h()}case v.STATE_SNAPSHOT:{let f=await K(r,s,a,(p,g,x)=>p.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{snapshot:p}=m;a=p,c({state:a})}return h()}case v.STATE_DELTA:{let f=await K(r,s,a,(p,g,x)=>p.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{delta:p}=m;try{a=eo.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 Qn(t,e){if(t){var n=t.indexOf(e);0<=n&&t.splice(n,1)}}var Sn=(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=ht(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 h=this.initialTeardown;if(B(h))try{h()}catch(g){i=g instanceof no?g.errors:[g]}var m=this._finalizers;if(m){this._finalizers=null;try{for(var y=ht(m),f=y.next();!f.done;f=y.next()){var p=f.value;try{Kl(p)}catch(g){i=i??[],g instanceof no?i=wn(wn([],En(i)),En(g.errors)):i.push(g)}}}catch(g){r={error:g}}finally{try{f&&!f.done&&(o=y.return)&&o.call(y)}finally{if(r)throw r.error}}}if(i)throw new no(i)}},t.prototype.add=function(e){var n;if(e&&e!==this)if(this.closed)Kl(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)&&Qn(n,e)},t.prototype.remove=function(e){var n=this._finalizers;n&&Qn(n,e),e instanceof t&&e._removeParent(this)},t.EMPTY=(function(){var e=new t;return e.closed=!0,e})(),t})();var Ds=Sn.EMPTY;function ro(t){return t instanceof Sn||t&&"closed"in t&&B(t.remove)&&B(t.add)&&B(t.unsubscribe)}function Kl(t){B(t)?t():t.unsubscribe()}var We={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var An={setTimeout:function(t,e){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=An.delegate;return o?.setTimeout?o.setTimeout.apply(o,wn([t,e],En(n))):setTimeout.apply(void 0,wn([t,e],En(n)))},clearTimeout:function(t){var e=An.delegate;return(e?.clearTimeout||clearTimeout)(t)},delegate:void 0};function oo(t){An.setTimeout(function(){var e=We.onUnhandledError;if(e)e(t);else throw t})}function er(){}var Zl=(function(){return Us("C",void 0,void 0)})();function Jl(t){return Us("E",void 0,t)}function Ql(t){return Us("N",t,void 0)}function Us(t,e,n){return{kind:t,value:e,error:n}}var Kt=null;function kn(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 ec(t){We.useDeprecatedSynchronousErrorHandling&&Kt&&(Kt.errorThrown=!0,Kt.error=t)}var tr=(function(t){it(e,t);function e(n){var r=t.call(this)||this;return r.isStopped=!1,n?(r.destination=n,ro(n)&&n.add(r)):r.destination=dm,r}return e.create=function(n,r,o){return new so(n,r,o)},e.prototype.next=function(n){this.isStopped?zs(Ql(n),this):this._next(n)},e.prototype.error=function(n){this.isStopped?zs(Jl(n),this):(this.isStopped=!0,this._error(n))},e.prototype.complete=function(){this.isStopped?zs(Zl,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})(Sn);var lm=Function.prototype.bind;function Hs(t,e){return lm.call(t,e)}var cm=(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){io(r)}},t.prototype.error=function(e){var n=this.partialObserver;if(n.error)try{n.error(e)}catch(r){io(r)}else io(e)},t.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(n){io(n)}},t})(),so=(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&&Hs(n.next,a),error:n.error&&Hs(n.error,a),complete:n.complete&&Hs(n.complete,a)}):s=n}return i.destination=new cm(s),i}return e})(tr);function io(t){We.useDeprecatedSynchronousErrorHandling?ec(t):oo(t)}function um(t){throw t}function zs(t,e){var n=We.onStoppedNotification;n&&An.setTimeout(function(){return n(t,e)})}var dm={closed:!0,next:er,error:um,complete:er};var Cn=(function(){return typeof Symbol=="function"&&Symbol.observable||"@@observable"})();function In(t){return t}function ao(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return Gs(t)}function Gs(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=hm(e)?e:new so(e,n,r);return kn(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=tc(n),new n(function(o,i){var s=new so({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[Cn]=function(){return this},t.prototype.pipe=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return Gs(e)(this)},t.prototype.toPromise=function(e){var n=this;return e=tc(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 tc(t){var e;return(e=t??We.Promise)!==null&&e!==void 0?e:Promise}function pm(t){return t&&B(t.next)&&B(t.error)&&B(t.complete)}function hm(t){return t&&t instanceof tr||pm(t)&&ro(t)}function fm(t){return B(t?.lift)}function fe(t){return function(e){if(fm(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 mm(t,e,n,r,o)}var mm=(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(h){n.error(h)}}:t.prototype._next,l._error=i?function(c){try{i(c)}catch(h){n.error(h)}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})(tr);var nc=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 rc(this,this);return r.operator=n,r},e.prototype._throwIfClosed=function(){if(this.closed)throw new nc},e.prototype.next=function(n){var r=this;kn(function(){var o,i;if(r._throwIfClosed(),!r.isStopped){r.currentObservers||(r.currentObservers=Array.from(r.observers));try{for(var s=ht(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;kn(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;kn(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?Ds:(this.currentObservers=null,a.push(n),new Sn(function(){r.currentObservers=null,Qn(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 rc(n,r)},e})(te);var rc=(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:Ds},e})(st);var Fs={now:function(){return(Fs.delegate||Date).now()},delegate:void 0};var lo=(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=Fs);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,h=1;h<i.length&&i[h]<=l;h+=2)c=h;c&&i.splice(0,c+1)}},e})(st);var co=new te(function(t){return t.complete()});function oc(t){return t&&B(t.schedule)}function gm(t){return t[t.length-1]}function ic(t){return oc(gm(t))?t.pop():void 0}var uo=(function(t){return t&&typeof t.length=="number"&&typeof t!="function"});function po(t){return B(t?.then)}function ho(t){return B(t[Cn])}function fo(t){return Symbol.asyncIterator&&B(t?.[Symbol.asyncIterator])}function mo(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 vm(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var go=vm();function vo(t){return B(t?.[go])}function bo(t){return Xl(this,arguments,function(){var n,r,o,i;return to(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 yo(t){return B(t?.getReader)}function ve(t){if(t instanceof te)return t;if(t!=null){if(ho(t))return bm(t);if(uo(t))return ym(t);if(po(t))return xm(t);if(fo(t))return sc(t);if(vo(t))return _m(t);if(yo(t))return Em(t)}throw mo(t)}function bm(t){return new te(function(e){var n=t[Cn]();if(B(n.subscribe))return n.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function ym(t){return new te(function(e){for(var n=0;n<t.length&&!e.closed;n++)e.next(t[n]);e.complete()})}function xm(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,oo)})}function _m(t){return new te(function(e){var n,r;try{for(var o=ht(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 sc(t){return new te(function(e){wm(t,e).catch(function(n){return e.error(n)})})}function Em(t){return sc(bo(t))}function wm(t,e){var n,r,o,i;return Wl(this,void 0,void 0,function(){var s,a;return to(this,function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=Yl(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 $e(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 xo(t,e){return e===void 0&&(e=0),fe(function(n,r){n.subscribe(ge(r,function(o){return $e(r,t,function(){return r.next(o)},e)},function(){return $e(r,t,function(){return r.complete()},e)},function(o){return $e(r,t,function(){return r.error(o)},e)}))})}function _o(t,e){return e===void 0&&(e=0),fe(function(n,r){r.add(t.schedule(function(){return n.subscribe(r)},e))})}function ac(t,e){return ve(t).pipe(_o(e),xo(e))}function lc(t,e){return ve(t).pipe(_o(e),xo(e))}function cc(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 uc(t,e){return new te(function(n){var r;return $e(n,e,function(){r=t[go](),$e(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 Eo(t,e){if(!t)throw new Error("Iterable cannot be null");return new te(function(n){$e(n,e,function(){var r=t[Symbol.asyncIterator]();$e(n,e,function(){r.next().then(function(o){o.done?n.complete():n.next(o.value)})},0,!0)})})}function dc(t,e){return Eo(bo(t),e)}function pc(t,e){if(t!=null){if(ho(t))return ac(t,e);if(uo(t))return cc(t,e);if(po(t))return lc(t,e);if(fo(t))return Eo(t,e);if(vo(t))return uc(t,e);if(yo(t))return dc(t,e)}throw mo(t)}function Zt(t,e){return e?pc(t,e):ve(t)}function ue(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=ic(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 hc=Tn(function(t){return function(){t(this),this.name="EmptyError",this.message="no elements in sequence"}});function wo(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 hc)}})})}function Jt(t,e){return fe(function(n,r){var o=0;n.subscribe(ge(r,function(i){r.next(t.call(e,i,o++))}))})}function fc(t,e,n,r,o,i,s,a){var l=[],c=0,h=0,m=!1,y=function(){m&&!l.length&&!c&&e.complete()},f=function(g){return c<r?p(g):l.push(g)},p=function(g){i&&e.next(g),c++;var x=!1;ve(n(g,h++)).subscribe(ge(e,function(S){o?.(S),i?f(S):e.next(S)},function(){x=!0},void 0,function(){if(x)try{c--;for(var S=function(){var w=l.shift();s?$e(e,s,function(){return p(w)}):p(w)};l.length&&c<r;)S();y()}catch(w){e.error(w)}}))};return t.subscribe(ge(e,f,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),fe(function(r,o){return fc(r,o,t,n)}))}function $s(t){return t===void 0&&(t=1/0),Me(In,t)}function To(t){return new te(function(e){ve(t()).subscribe(e)})}function nr(t){return fe(function(e,n){var r=null,o=!1,i;r=e.subscribe(ge(n,void 0,void 0,function(s){i=ve(t(s,nr(t)(e))),r?(r.unsubscribe(),r=null,i.subscribe(n)):o=!0})),o&&(r.unsubscribe(),r=null,i.subscribe(n))})}function So(t,e){return B(e)?Me(t,e,1):Me(t,1)}function Bs(t){return fe(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 fe(function(e,n){try{e.subscribe(n)}finally{n.add(t)}})}function Vs(t,e){return fe(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,h=i++;ve(t(l,h)).subscribe(o=ge(r,function(m){return r.next(e?e(l,m,h,c++):m)},function(){o=null,a()}))},function(){s=!0,a()}))})}function Ao(t){return fe(function(e,n){ve(t).subscribe(ge(n,function(){return n.complete()},er)),!n.closed&&e.subscribe(n)})}function js(t,e,n){var r=B(t)||e||n?{next:t,error:e,complete:n}:t;return r?fe(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)}))}):In}function mc(t){return` \r
|
|
5
|
+
`.indexOf(t)>=0}function ko(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)},h=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}},f=t.length;n<f;n++){var p=t[n];switch(e[e.length-1]){case"topLevel":y(p);break;case"string":switch(p){case'"':h();break;case"\\":l("stringEscape"),s("stringEscaped");break}break;case"stringEscaped":p==="u"?s("stringUnicode"):(c("stringEscape"),h());break;case"stringUnicode":n-t.lastIndexOf("u",n)===4&&(c("stringEscape"),h());break;case"number":p==="."?a("numberNeedsDigit"):p==="e"||p==="E"?a("numberNeedsExponent"):(p<"0"||p>"9")&&(m(),h());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(),h());break;case"arrayNeedsValue":p==="]"?h():mc(p)||(c("collectionItem"),a("arrayNeedsComma"),y(p));break;case"arrayNeedsComma":p==="]"?h():p===","&&(l("collectionItem"),a("arrayNeedsValue"));break;case"objectNeedsKey":p==="}"?h():p==='"'&&(l("collectionItem"),a("objectNeedsColon"),s("string"));break;case"objectNeedsColon":p===":"&&a("objectNeedsValue");break;case"objectNeedsValue":mc(p)||(c("collectionItem"),a("objectNeedsComma"),y(p));break;case"objectNeedsComma":p==="}"?h():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])))},S=e.length-1;S>=0;S--)switch(e[S]){case"string":g.push('"');break;case"numberNeedsDigit":case"numberNeedsExponent":g.push("0");break;case"true":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 vc(){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 Io(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 Co=4294967296;function qs(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>=Co&&(o=o+(r/Co|0),r=r%Co)}return i(-24,-18),i(-18,-12),i(-12,-6),i(-6),e?yc(r,o):Xs(r,o)}function bc(t,e){let n=Xs(t,e),r=n.hi&2147483648;r&&(n=yc(n.lo,n.hi));let o=Ws(n.lo,n.hi);return r?"-"+o:o}function Ws(t,e){if({lo:t,hi:e}=Tm(t,e),e<=2097151)return String(Co*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()+gc(s)+gc(i)}function Tm(t,e){return{lo:t>>>0,hi:e>>>0}}function Xs(t,e){return{lo:t|0,hi:e|0}}function yc(t,e){return e=~e,t?t=~t+1:e+=1,Xs(t,e)}var gc=t=>{let e=String(t);return"0000000".slice(e.length)+e};function Ys(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 xc(){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=Sm();function Sm(){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()),_c(n),n},uParse(n){return typeof n!="string"&&(n=n.toString()),Ec(n),n},enc(n){return typeof n!="string"&&(n=n.toString()),_c(n),qs(n)},uEnc(n){return typeof n!="string"&&(n=n.toString()),Ec(n),qs(n)},dec(n,r){return bc(n,r)},uDec(n,r){return Ws(n,r)}}}function _c(t){if(!/^-?[0-9]+$/.test(t))throw new Error("invalid int64: "+t)}function Ec(t){if(!/^[0-9]+$/.test(t))throw new Error("invalid uint64: "+t)}var Ks=Symbol.for("@bufbuild/protobuf/text-encoding");function Zs(){if(globalThis[Ks]==null){let t=new globalThis.TextEncoder,e=new globalThis.TextDecoder,n;globalThis[Ks]={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[Ks]}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 Am=34028234663852886e22,km=-34028234663852886e22,Cm=4294967295,Im=2147483647,Rm=-2147483648,F=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(wc(e);e>127;)this.buf.push(e&127|128),e=e>>>7;return this.buf.push(e),this}int32(e){return Js(e),Ys(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){wc(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,Ys(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 Io(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 Io(o,i,this.buf),this}uint64(e){let n=Xe.uEnc(e);return Io(n.lo,n.hi,this.buf),this}},A=class{constructor(e,n=Zs().decodeUtf8){this.decodeUtf8=n,this.varint64=vc,this.uint32=xc,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 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>Im||t<Rm)throw new Error("invalid int32: "+t)}function wc(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>Cm||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>Am||t<km))throw new Error("invalid float32: "+t)}var Om=(function(t){return t[t.NULL_VALUE=0]="NULL_VALUE",t[t.UNRECOGNIZED=-1]="UNRECOGNIZED",t})({});function Qs(){return{fields:{}}}var rr={encode(t,e=new F){return Object.entries(t.fields).forEach(([n,r])=>{r!==void 0&&na.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=na.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 rr.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 Tc(){return{key:"",value:void 0}}var na={encode(t,e=new F){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=Tc();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 na.fromPartial(t??{})},fromPartial(t){let e=Tc();return e.key=t.key??"",e.value=t.value??void 0,e}};function ea(){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 F){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&&rr.encode(rr.wrap(t.structValue),e.uint32(42).fork()).join(),t.listValue!==void 0&&or.encode(or.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=ea();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=rr.unwrap(rr.decode(n,n.uint32()));continue;case 6:if(i!==50)break;o.listValue=or.unwrap(or.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=ea();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=ea();if(t===null)e.nullValue=Om.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 ta(){return{values:[]}}var or={encode(t,e=new F){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=ta();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 or.fromPartial(t??{})},fromPartial(t){let e=ta();return e.values=t.values?.map(n=>n)||[],e},wrap(t){let e=ta();return e.values=t??[],e},unwrap(t){return t?.hasOwnProperty("values")&&globalThis.Array.isArray(t.values)?t.values:t}},Mm=(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 Sc(){return{op:0,path:"",from:void 0,value:void 0}}var No={encode(t,e=new F){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=Sc();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 No.fromPartial(t??{})},fromPartial(t){let e=Sc();return e.op=t.op??0,e.path=t.path??"",e.from=t.from??void 0,e.value=t.value??void 0,e}};function Ac(){return{id:"",type:"",function:void 0}}var Oo={encode(t,e=new F){return t.id!==""&&e.uint32(10).string(t.id),t.type!==""&&e.uint32(18).string(t.type),t.function!==void 0&&Mo.encode(t.function,e.uint32(26).fork()).join(),e},decode(t,e){let n=t instanceof 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.id=n.string();continue;case 2:if(i!==18)break;o.type=n.string();continue;case 3:if(i!==26)break;o.function=Mo.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=Ac();return e.id=t.id??"",e.type=t.type??"",e.function=t.function!==void 0&&t.function!==null?Mo.fromPartial(t.function):void 0,e}};function kc(){return{name:"",arguments:""}}var Mo={encode(t,e=new F){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=kc();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 Mo.fromPartial(t??{})},fromPartial(t){let e=kc();return e.name=t.name??"",e.arguments=t.arguments??"",e}};function Cc(){return{value:"",mimeType:""}}var Lo={encode(t,e=new F){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=Cc();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 Lo.fromPartial(t??{})},fromPartial(t){let e=Cc();return e.value=t.value??"",e.mimeType=t.mimeType??"",e}};function Ic(){return{value:"",mimeType:void 0}}var Po={encode(t,e=new F){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=Ic();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 Po.fromPartial(t??{})},fromPartial(t){let e=Ic();return e.value=t.value??"",e.mimeType=t.mimeType??void 0,e}};function Rc(){return{data:void 0,url:void 0}}var De={encode(t,e=new F){return t.data!==void 0&&Lo.encode(t.data,e.uint32(10).fork()).join(),t.url!==void 0&&Po.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=Rc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.data=Lo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.url=Po.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return De.fromPartial(t??{})},fromPartial(t){let e=Rc();return e.data=t.data!==void 0&&t.data!==null?Lo.fromPartial(t.data):void 0,e.url=t.url!==void 0&&t.url!==null?Po.fromPartial(t.url):void 0,e}};function Nc(){return{text:""}}var Do={encode(t,e=new F){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=Nc();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 Do.fromPartial(t??{})},fromPartial(t){let e=Nc();return e.text=t.text??"",e}};function Oc(){return{source:void 0,metadata:void 0}}var Uo={encode(t,e=new F){return t.source!==void 0&&De.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=Oc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=De.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=Oc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Mc(){return{source:void 0,metadata:void 0}}var Ho={encode(t,e=new F){return t.source!==void 0&&De.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=De.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 Ho.fromPartial(t??{})},fromPartial(t){let e=Mc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Lc(){return{source:void 0,metadata:void 0}}var zo={encode(t,e=new F){return t.source!==void 0&&De.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=Lc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=De.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 zo.fromPartial(t??{})},fromPartial(t){let e=Lc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Pc(){return{source:void 0,metadata:void 0}}var Go={encode(t,e=new F){return t.source!==void 0&&De.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=Pc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.source=De.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 Go.fromPartial(t??{})},fromPartial(t){let e=Pc();return e.source=t.source!==void 0&&t.source!==null?De.fromPartial(t.source):void 0,e.metadata=t.metadata??void 0,e}};function Dc(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var Fo={encode(t,e=new F){return t.text!==void 0&&Do.encode(t.text,e.uint32(10).fork()).join(),t.image!==void 0&&Uo.encode(t.image,e.uint32(18).fork()).join(),t.audio!==void 0&&Ho.encode(t.audio,e.uint32(26).fork()).join(),t.video!==void 0&&zo.encode(t.video,e.uint32(34).fork()).join(),t.document!==void 0&&Go.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=Dc();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.text=Do.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.image=Uo.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.audio=Ho.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.video=zo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.document=Go.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=Dc();return e.text=t.text!==void 0&&t.text!==null?Do.fromPartial(t.text):void 0,e.image=t.image!==void 0&&t.image!==null?Uo.fromPartial(t.image):void 0,e.audio=t.audio!==void 0&&t.audio!==null?Ho.fromPartial(t.audio):void 0,e.video=t.video!==void 0&&t.video!==null?zo.fromPartial(t.video):void 0,e.document=t.document!==void 0&&t.document!==null?Go.fromPartial(t.document):void 0,e}};function Uc(){return{id:"",role:"",content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[]}}var $o={encode(t,e=new F){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)Oo.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)Fo.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=Uc();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(Oo.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(Fo.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=Uc();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=>Oo.fromPartial(n))||[],e.toolCallId=t.toolCallId??void 0,e.error=t.error??void 0,e.contentParts=t.contentParts?.map(n=>Fo.fromPartial(n))||[],e}};function Hc(){return{id:"",reason:"",message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0}}var Bo={encode(t,e=new F){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=Hc();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 Bo.fromPartial(t??{})},fromPartial(t){let e=Hc();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}},Lm=(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 zc(){return{type:0,timestamp:void 0,rawEvent:void 0}}var M={encode(t,e=new F){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=zc();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=Pm(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=zc();return e.type=t.type??0,e.timestamp=t.timestamp??void 0,e.rawEvent=t.rawEvent??void 0,e}};function Gc(){return{baseEvent:void 0,messageId:"",role:void 0,name:void 0}}var Vo={encode(t,e=new F){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=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.name=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=Gc();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 Fc(){return{baseEvent:void 0,messageId:"",delta:""}}var jo={encode(t,e=new F){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=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.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 jo.fromPartial(t??{})},fromPartial(t){let e=Fc();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 qo={encode(t,e=new F){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 qo.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 Bc(){return{baseEvent:void 0,toolCallId:"",toolCallName:"",parentMessageId:void 0}}var Wo={encode(t,e=new F){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=Bc();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 Wo.fromPartial(t??{})},fromPartial(t){let e=Bc();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 Vc(){return{baseEvent:void 0,toolCallId:"",delta:""}}var Xo={encode(t,e=new F){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=Vc();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 Xo.fromPartial(t??{})},fromPartial(t){let e=Vc();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 jc(){return{baseEvent:void 0,toolCallId:""}}var Yo={encode(t,e=new F){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=jc();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 Yo.fromPartial(t??{})},fromPartial(t){let e=jc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.toolCallId=t.toolCallId??"",e}};function qc(){return{baseEvent:void 0,snapshot:void 0}}var Ko={encode(t,e=new F){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=qc();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 Ko.fromPartial(t??{})},fromPartial(t){let e=qc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.snapshot=t.snapshot??void 0,e}};function Wc(){return{baseEvent:void 0,delta:[]}}var Zo={encode(t,e=new F){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.delta)No.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=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.delta.push(No.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=Wc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.delta=t.delta?.map(n=>No.fromPartial(n))||[],e}};function Xc(){return{baseEvent:void 0,messages:[]}}var Jo={encode(t,e=new F){t.baseEvent!==void 0&&M.encode(t.baseEvent,e.uint32(10).fork()).join();for(let n of t.messages)$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=Xc();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($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=Xc();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.messages=t.messages?.map(n=>$o.fromPartial(n))||[],e}};function Yc(){return{baseEvent:void 0,event:void 0,source:void 0}}var Qo={encode(t,e=new F){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=Yc();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 Qo.fromPartial(t??{})},fromPartial(t){let e=Yc();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 Kc(){return{baseEvent:void 0,name:"",value:void 0}}var ei={encode(t,e=new F){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=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.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 ei.fromPartial(t??{})},fromPartial(t){let e=Kc();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 Zc(){return{baseEvent:void 0,threadId:"",runId:""}}var ti={encode(t,e=new F){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=Zc();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 ti.fromPartial(t??{})},fromPartial(t){let e=Zc();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 Jc(){return{baseEvent:void 0,threadId:"",runId:"",result:void 0,outcome:"",interrupts:[]}}var ni={encode(t,e=new F){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)Bo.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=Jc();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(Bo.decode(n,n.uint32()));continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return ni.fromPartial(t??{})},fromPartial(t){let e=Jc();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=>Bo.fromPartial(n))||[],e}};function Qc(){return{baseEvent:void 0,code:void 0,message:""}}var ri={encode(t,e=new F){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=Qc();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 ri.fromPartial(t??{})},fromPartial(t){let e=Qc();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 eu(){return{baseEvent:void 0,stepName:""}}var oi={encode(t,e=new F){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=eu();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 oi.fromPartial(t??{})},fromPartial(t){let e=eu();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function tu(){return{baseEvent:void 0,stepName:""}}var ii={encode(t,e=new F){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=tu();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 ii.fromPartial(t??{})},fromPartial(t){let e=tu();return e.baseEvent=t.baseEvent!==void 0&&t.baseEvent!==null?M.fromPartial(t.baseEvent):void 0,e.stepName=t.stepName??"",e}};function nu(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0}}var si={encode(t,e=new F){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=nu();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 si.fromPartial(t??{})},fromPartial(t){let e=nu();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 ru(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0}}var ai={encode(t,e=new F){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=ru();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 ai.fromPartial(t??{})},fromPartial(t){let e=ru();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 ou(){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 iu={encode(t,e=new F){return t.textMessageStart!==void 0&&Vo.encode(t.textMessageStart,e.uint32(10).fork()).join(),t.textMessageContent!==void 0&&jo.encode(t.textMessageContent,e.uint32(18).fork()).join(),t.textMessageEnd!==void 0&&qo.encode(t.textMessageEnd,e.uint32(26).fork()).join(),t.toolCallStart!==void 0&&Wo.encode(t.toolCallStart,e.uint32(34).fork()).join(),t.toolCallArgs!==void 0&&Xo.encode(t.toolCallArgs,e.uint32(42).fork()).join(),t.toolCallEnd!==void 0&&Yo.encode(t.toolCallEnd,e.uint32(50).fork()).join(),t.stateSnapshot!==void 0&&Ko.encode(t.stateSnapshot,e.uint32(58).fork()).join(),t.stateDelta!==void 0&&Zo.encode(t.stateDelta,e.uint32(66).fork()).join(),t.messagesSnapshot!==void 0&&Jo.encode(t.messagesSnapshot,e.uint32(74).fork()).join(),t.raw!==void 0&&Qo.encode(t.raw,e.uint32(82).fork()).join(),t.custom!==void 0&&ei.encode(t.custom,e.uint32(90).fork()).join(),t.runStarted!==void 0&&ti.encode(t.runStarted,e.uint32(98).fork()).join(),t.runFinished!==void 0&&ni.encode(t.runFinished,e.uint32(106).fork()).join(),t.runError!==void 0&&ri.encode(t.runError,e.uint32(114).fork()).join(),t.stepStarted!==void 0&&oi.encode(t.stepStarted,e.uint32(122).fork()).join(),t.stepFinished!==void 0&&ii.encode(t.stepFinished,e.uint32(130).fork()).join(),t.textMessageChunk!==void 0&&si.encode(t.textMessageChunk,e.uint32(138).fork()).join(),t.toolCallChunk!==void 0&&ai.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=ou();for(;n.pos<r;){let i=n.uint32();switch(i>>>3){case 1:if(i!==10)break;o.textMessageStart=Vo.decode(n,n.uint32());continue;case 2:if(i!==18)break;o.textMessageContent=jo.decode(n,n.uint32());continue;case 3:if(i!==26)break;o.textMessageEnd=qo.decode(n,n.uint32());continue;case 4:if(i!==34)break;o.toolCallStart=Wo.decode(n,n.uint32());continue;case 5:if(i!==42)break;o.toolCallArgs=Xo.decode(n,n.uint32());continue;case 6:if(i!==50)break;o.toolCallEnd=Yo.decode(n,n.uint32());continue;case 7:if(i!==58)break;o.stateSnapshot=Ko.decode(n,n.uint32());continue;case 8:if(i!==66)break;o.stateDelta=Zo.decode(n,n.uint32());continue;case 9:if(i!==74)break;o.messagesSnapshot=Jo.decode(n,n.uint32());continue;case 10:if(i!==82)break;o.raw=Qo.decode(n,n.uint32());continue;case 11:if(i!==90)break;o.custom=ei.decode(n,n.uint32());continue;case 12:if(i!==98)break;o.runStarted=ti.decode(n,n.uint32());continue;case 13:if(i!==106)break;o.runFinished=ni.decode(n,n.uint32());continue;case 14:if(i!==114)break;o.runError=ri.decode(n,n.uint32());continue;case 15:if(i!==122)break;o.stepStarted=oi.decode(n,n.uint32());continue;case 16:if(i!==130)break;o.stepFinished=ii.decode(n,n.uint32());continue;case 17:if(i!==138)break;o.textMessageChunk=si.decode(n,n.uint32());continue;case 18:if(i!==146)break;o.toolCallChunk=ai.decode(n,n.uint32());continue}if((i&7)===4||i===0)break;n.skip(i&7)}return o},create(t){return iu.fromPartial(t??{})},fromPartial(t){let e=ou();return e.textMessageStart=t.textMessageStart!==void 0&&t.textMessageStart!==null?Vo.fromPartial(t.textMessageStart):void 0,e.textMessageContent=t.textMessageContent!==void 0&&t.textMessageContent!==null?jo.fromPartial(t.textMessageContent):void 0,e.textMessageEnd=t.textMessageEnd!==void 0&&t.textMessageEnd!==null?qo.fromPartial(t.textMessageEnd):void 0,e.toolCallStart=t.toolCallStart!==void 0&&t.toolCallStart!==null?Wo.fromPartial(t.toolCallStart):void 0,e.toolCallArgs=t.toolCallArgs!==void 0&&t.toolCallArgs!==null?Xo.fromPartial(t.toolCallArgs):void 0,e.toolCallEnd=t.toolCallEnd!==void 0&&t.toolCallEnd!==null?Yo.fromPartial(t.toolCallEnd):void 0,e.stateSnapshot=t.stateSnapshot!==void 0&&t.stateSnapshot!==null?Ko.fromPartial(t.stateSnapshot):void 0,e.stateDelta=t.stateDelta!==void 0&&t.stateDelta!==null?Zo.fromPartial(t.stateDelta):void 0,e.messagesSnapshot=t.messagesSnapshot!==void 0&&t.messagesSnapshot!==null?Jo.fromPartial(t.messagesSnapshot):void 0,e.raw=t.raw!==void 0&&t.raw!==null?Qo.fromPartial(t.raw):void 0,e.custom=t.custom!==void 0&&t.custom!==null?ei.fromPartial(t.custom):void 0,e.runStarted=t.runStarted!==void 0&&t.runStarted!==null?ti.fromPartial(t.runStarted):void 0,e.runFinished=t.runFinished!==void 0&&t.runFinished!==null?ni.fromPartial(t.runFinished):void 0,e.runError=t.runError!==void 0&&t.runError!==null?ri.fromPartial(t.runError):void 0,e.stepStarted=t.stepStarted!==void 0&&t.stepStarted!==null?oi.fromPartial(t.stepStarted):void 0,e.stepFinished=t.stepFinished!==void 0&&t.stepFinished!==null?ii.fromPartial(t.stepFinished):void 0,e.textMessageChunk=t.textMessageChunk!==void 0&&t.textMessageChunk!==null?si.fromPartial(t.textMessageChunk):void 0,e.toolCallChunk=t.toolCallChunk!==void 0&&t.toolCallChunk!==null?ai.fromPartial(t.toolCallChunk):void 0,e}};function Pm(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 Ro=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}}},Dm=t=>{if(!(!t||typeof t!="object")){if(t.text)return{type:"text",text:t.text.text};if(t.image)return{type:"image",source:Ro(t.image.source),metadata:t.image.metadata};if(t.audio)return{type:"audio",source:Ro(t.audio.source),metadata:t.audio.metadata};if(t.video)return{type:"video",source:Ro(t.video.source),metadata:t.video.metadata};if(t.document)return{type:"document",source:Ro(t.document.source),metadata:t.document.metadata}}};function su(t){let e=iu.decode(t),n=Object.values(e).find(r=>r!==void 0);if(!n)throw new Error("Invalid event");if(n.type=Lm[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=>Dm(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=Mm[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]}),qr.parse(n)}var ra="application/vnd.ag-ui.event+proto";var Hm=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,oa=t=>{if(typeof t!="string")throw new TypeError("Invalid argument expected string");let e=t.match(Hm);if(!e)throw new Error(`Invalid argument not valid semver ('${t}' received)`);return e.shift(),e},au=t=>t==="*"||t==="x"||t==="X",lu=t=>{let e=parseInt(t,10);return isNaN(e)?t:e},zm=(t,e)=>typeof t!=typeof e?[String(t),String(e)]:[t,e],Gm=(t,e)=>{if(au(t)||au(e))return 0;let[n,r]=zm(lu(t),lu(e));return n>r?1:n<r?-1:0},ia=(t,e)=>{for(let n=0;n<Math.max(t.length,e.length);n++){let r=Gm(t[n]||"0",e[n]||"0");if(r!==0)return r}return 0};var ir=(t,e)=>{let n=oa(t),r=oa(e),o=n.pop(),i=r.pop(),s=ia(n,r);return s!==0?s:o&&i?ia(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 Ue(){return xt()}function la(t){if(Object.freeze(t),typeof t=="object"&&t)for(let e of Object.values(t))typeof e=="object"&&e&&!Object.isFrozen(e)&&la(e);return t}var cu=512*1024;function uu(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&&!uu(e,n,cu),l=a?q(e):e,c=a?q(n):n,h=!1,m=!1,y;for(let f of t)try{a&&(la(l),la(c));let p=await r(f,l,c);if(p===void 0)continue;let g=!1;if(p.messages!==void 0&&p.messages!==l&&(l=q(p.messages),h=!0,g=!0),p.state!==void 0&&p.state!==c&&(c=q(p.state),m=!0,g=!0),a&&g&&uu(l,c,cu)&&(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{...h?{messages:Object.isFrozen(l)?q(l):l}:{},...m?{state:Object.isFrozen(c)?q(c):c}:{},...y===void 0?{}:{stopPropagation:y}}}function li(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 sr(t){if(t instanceof ca)return t;if(t===!0)return new ca(li(!0))}var ca=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 sa(t){return t.enabled?new ca(t):void 0}function Fm(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 gu=(t,e,n,r,o)=>{let i=sr(o),s=q(n.messages),a=q(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)},h=()=>{let m=q(l);return l={},m.messages!==void 0||m.state!==void 0?ue(m):co};return e.pipe(So(async m=>{let y=await K(r,s,a,(f,p,g)=>f.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 h();switch(m.type){case v.TEXT_MESSAGE_START:{let f=await K(r,s,a,(p,g,x)=>p.onTextMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:p,role:g="assistant",name:x}=m;if(!s.find(S=>S.id===p)){let S={id:p,role:g,content:"",...x!==void 0&&{name:x}};s.push(S),c({messages:s})}}return h()}case v.TEXT_MESSAGE_CONTENT:{let{messageId:f,delta:p}=m,g=s.find(S=>S.id===f);if(!g)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${f}'`),h();let x=await K(r,s,a,(S,w,I)=>S.onTextMessageContentEvent?.({event:m,messages:w,state:I,agent:n,input:t,textMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${p}`,c({messages:s})),h()}case v.TEXT_MESSAGE_END:{let{messageId:f}=m,p=s.find(g=>g.id===f);return p?(c(await K(r,s,a,(g,x,S)=>g.onTextMessageEndEvent?.({event:m,messages:x,state:S,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})})),h()):(console.warn(`TEXT_MESSAGE_END: No message found with ID '${f}'`),h())}case v.TOOL_CALL_START:{let f=await K(r,s,a,(p,g,x)=>p.onToolCallStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{toolCallId:p,toolCallName:g,parentMessageId:x}=m,S=Fm(s,x,p);S.toolCalls??=[],S.toolCalls.push({id:p,type:"function",function:{name:g,arguments:""}}),c({messages:s})}return h()}case v.TOOL_CALL_ARGS:{let{toolCallId:f,delta:p}=m,g=s.find(w=>w.toolCalls?.some(I=>I.id===f));if(!g)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${f}'`),h();let x=g.toolCalls?.find(w=>w.id===f);if(!x)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${f}'`),h();let S=await K(r,s,a,(w,I,H)=>{let U=x.function.arguments,Y=x.function.name,re={};try{re=ko(U)}catch{}return w.onToolCallArgsEvent?.({event:m,messages:I,state:H,agent:n,input:t,toolCallBuffer:U,toolCallName:Y,partialToolCallArgs:re})});return c(S),S.stopPropagation!==!0&&(x.function.arguments+=p,c({messages:s})),h()}case v.TOOL_CALL_END:{let{toolCallId:f}=m,p=s.find(x=>x.toolCalls?.some(S=>S.id===f));if(!p)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${f}'`),h();let g=p.toolCalls?.find(x=>x.id===f);return g?(c(await K(r,s,a,(x,S,w)=>{let I=g.function.arguments,H=g.function.name,U={};try{U=JSON.parse(I)}catch{}return x.onToolCallEndEvent?.({event:m,messages:S,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})})),h()):(console.warn(`TOOL_CALL_END: No tool call found with ID '${f}'`),h())}case v.TOOL_CALL_RESULT:{let f=await K(r,s,a,(p,g,x)=>p.onToolCallResultEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messageId:p,toolCallId:g,content:x,role:S}=m,w={id:p,toolCallId:g,role:S||"tool",content:x},I=s.findIndex(H=>H.role==="assistant"&&H.toolCalls?.some(U=>U.id===g));if(I===-1)s.push(w);else{let H=I+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 h()}case v.STATE_SNAPSHOT:{let f=await K(r,s,a,(p,g,x)=>p.onStateSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{snapshot:p}=m;a=p,c({state:a})}return h()}case v.STATE_DELTA:{let f=await K(r,s,a,(p,g,x)=>p.onStateDeltaEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{delta:p}=m;try{a=eo.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:
|
|
6
6
|
Current state: ${JSON.stringify(a,null,2)}
|
|
7
7
|
Patch operations: ${JSON.stringify(p,null,2)}
|
|
8
|
-
Error: ${x}`)}}return h()}case v.MESSAGES_SNAPSHOT:{let f=await K(r,s,a,(p,g,x)=>p.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messages:p}=m,g=new Map(p.map(C=>[C.id,C])),x=p.some(C=>C.role==="reasoning"),S=C=>C.role==="activity"||C.role==="reasoning"&&!x;s=s.filter(C=>S(C)||g.has(C.id)).map(C=>S(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 h()}case v.ACTIVITY_SNAPSHOT:{let f=m,p=s.findIndex(C=>C.id===f.messageId),g=p>=0?s[p]:void 0,x=g?.role==="activity"?g:void 0,S=f.replace??!0,w=await K(r,s,a,(C,H,U)=>C.onActivitySnapshotEvent?.({event:f,messages:H,state:U,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(w),w.stopPropagation!==!0){let C={id:f.messageId,role:"activity",activityType:f.activityType,content:q(f.content)},H;p===-1?(s.push(C),H=C):x?S&&(s[p]={...x,activityType:f.activityType,content:q(f.content)}):S&&(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 h()}case v.ACTIVITY_DELTA:{let f=m,p=s.findIndex(w=>w.id===f.messageId);if(p===-1)return h();let g=s[p];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${f.messageId}' is not an activity message`),h();let x=g,S=await K(r,s,a,(w,C,H)=>w.onActivityDeltaEvent?.({event:f,messages:C,state:H,agent:n,input:t,activityMessage:x}));if(c(S),S.stopPropagation!==!0)try{let w=q(x.content??{}),C=eo.applyPatch(w,f.patch??[],!0,!1).newDocument;s[p]={...x,content:q(C),activityType:f.activityType},c({messages:s})}catch(w){let C=w instanceof Error?w.message:String(w);console.warn(`Failed to apply activity patch for '${f.messageId}': ${C}`)}return h()}case v.RAW:return c(await K(r,s,a,(f,p,g)=>f.onRawEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.CUSTOM:return c(await K(r,s,a,(f,p,g)=>f.onCustomEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.RUN_STARTED:{let f=await K(r,s,a,(p,g,x)=>p.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.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 h()}case v.RUN_FINISHED:{let f=m,p=f.outcome?.type==="interrupt"?{event:f,outcome:"interrupt",interrupts:f.outcome.interrupts}:{event:f,outcome:"success",result:f.result},g=await K(r,s,a,(x,S,w)=>x.onRunFinishedEvent?.({...p,messages:S,state:w,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=p.outcome==="interrupt"?[...p.interrupts]:[]),h()}case v.RUN_ERROR:return c(await K(r,s,a,(f,p,g)=>f.onRunErrorEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.STEP_STARTED:return c(await K(r,s,a,(f,p,g)=>f.onStepStartedEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.STEP_FINISHED:return c(await K(r,s,a,(f,p,g)=>f.onStepFinishedEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();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 h();case v.THINKING_END:return h();case v.THINKING_TEXT_MESSAGE_START:return h();case v.THINKING_TEXT_MESSAGE_CONTENT:return h();case v.THINKING_TEXT_MESSAGE_END:return h();case v.REASONING_START:return c(await K(r,s,a,(f,p,g)=>f.onReasoningStartEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.REASONING_MESSAGE_START:{let f=await K(r,s,a,(p,g,x)=>p.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.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 h()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:f,delta:p}=m,g=s.find(S=>S.id===f);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${f}'`),h();let x=await K(r,s,a,(S,w,C)=>S.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})),h()}case v.REASONING_MESSAGE_END:{let{messageId:f}=m,p=s.find(g=>g.id===f);return p?(c(await K(r,s,a,(g,x,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:S,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})})),h()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${f}'`),h())}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,(f,p,g)=>f.onReasoningEndEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:f,entityId:p,encryptedValue:g}=m,x=await K(r,s,a,(S,w,C)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:w,state:C,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let S=!1;if(f==="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,S=!0;break}}}else{let w=s.find(C=>C.id===p);w?.role!=="activity"&&w&&(w.encryptedValue=g,S=!0)}S&&(l.messages=s)}return h()}}return m.type,h()}),$s(),r.length>0?Bs({}):m=>m)},aa=t=>e=>{let n=sr(t),r=new Map,o=new Map,i=!1,s=!1,a=!1,l=new Map,c=!1,h=!1,m=!1,y=()=>{r.clear(),o.clear(),l.clear(),c=!1,h=!1,i=!1,s=!1,m=!0};return e.pipe(Me(f=>{let p=f.type;if(n?.event("VERIFY","Event:",f,{type:f.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=f.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(f))}case v.TEXT_MESSAGE_CONTENT:{let g=f.messageId;return r.has(g)?ue(f):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=f.messageId;return r.has(g)?(r.delete(g),ue(f)):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=f.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(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return o.has(g)?ue(f):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=f.toolCallId;return o.has(g)?(o.delete(g),ue(f)):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=f.stepName;return l.has(g)?ne(()=>new ee(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),ue(f))}case v.STEP_FINISHED:{let g=f.stepName;return l.has(g)?(l.delete(g),ue(f)):ne(()=>new ee(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,ue(f);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(f);case v.RUN_ERROR:return s=!0,ue(f);case v.CUSTOM:return ue(f);case v.THINKING_TEXT_MESSAGE_START:return c?h?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.")):(h=!0,ue(f)):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 h?ue(f):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 h?(h=!1,ue(f)):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(f));case v.THINKING_END:return c?(c=!1,ue(f)):ne(()=>new ee("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return ue(f)}}))},en=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),$m=t=>To(()=>Zt(t())).pipe(Vs(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"))})),Bm=(t,e)=>{let n=sr(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 c=i.split(/\n\n/);i=c.pop()||"";for(let h of c)s(h)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
|
|
8
|
+
Error: ${x}`)}}return h()}case v.MESSAGES_SNAPSHOT:{let f=await K(r,s,a,(p,g,x)=>p.onMessagesSnapshotEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.stopPropagation!==!0){let{messages:p}=m,g=new Map(p.map(I=>[I.id,I])),x=p.some(I=>I.role==="reasoning"),S=I=>I.role==="activity"||I.role==="reasoning"&&!x;s=s.filter(I=>S(I)||g.has(I.id)).map(I=>S(I)?I:g.get(I.id));let w=new Set(s.map(I=>I.id));for(let I of p)w.has(I.id)||s.push(I);c({messages:s})}return h()}case v.ACTIVITY_SNAPSHOT:{let f=m,p=s.findIndex(I=>I.id===f.messageId),g=p>=0?s[p]:void 0,x=g?.role==="activity"?g:void 0,S=f.replace??!0,w=await K(r,s,a,(I,H,U)=>I.onActivitySnapshotEvent?.({event:f,messages:H,state:U,agent:n,input:t,activityMessage:x,existingMessage:g}));if(c(w),w.stopPropagation!==!0){let I={id:f.messageId,role:"activity",activityType:f.activityType,content:q(f.content)},H;p===-1?(s.push(I),H=I):x?S&&(s[p]={...x,activityType:f.activityType,content:q(f.content)}):S&&(s[p]=I,H=I),c({messages:s}),H&&await Promise.all(r.map(U=>U.onNewMessage?.({message:H,messages:s,state:a,agent:n,input:t})))}return h()}case v.ACTIVITY_DELTA:{let f=m,p=s.findIndex(w=>w.id===f.messageId);if(p===-1)return h();let g=s[p];if(g.role!=="activity")return console.warn(`ACTIVITY_DELTA: Message '${f.messageId}' is not an activity message`),h();let x=g,S=await K(r,s,a,(w,I,H)=>w.onActivityDeltaEvent?.({event:f,messages:I,state:H,agent:n,input:t,activityMessage:x}));if(c(S),S.stopPropagation!==!0)try{let w=q(x.content??{}),I=eo.applyPatch(w,f.patch??[],!0,!1).newDocument;s[p]={...x,content:q(I),activityType:f.activityType},c({messages:s})}catch(w){let I=w instanceof Error?w.message:String(w);console.warn(`Failed to apply activity patch for '${f.messageId}': ${I}`)}return h()}case v.RAW:return c(await K(r,s,a,(f,p,g)=>f.onRawEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.CUSTOM:return c(await K(r,s,a,(f,p,g)=>f.onCustomEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.RUN_STARTED:{let f=await K(r,s,a,(p,g,x)=>p.onRunStartedEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.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 h()}case v.RUN_FINISHED:{let f=m,p=f.outcome?.type==="interrupt"?{event:f,outcome:"interrupt",interrupts:f.outcome.interrupts}:{event:f,outcome:"success",result:f.result},g=await K(r,s,a,(x,S,w)=>x.onRunFinishedEvent?.({...p,messages:S,state:w,agent:n,input:t}));return c(g),g.stopPropagation!==!0&&(n.pendingInterrupts=p.outcome==="interrupt"?[...p.interrupts]:[]),h()}case v.RUN_ERROR:return c(await K(r,s,a,(f,p,g)=>f.onRunErrorEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.STEP_STARTED:return c(await K(r,s,a,(f,p,g)=>f.onStepStartedEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.STEP_FINISHED:return c(await K(r,s,a,(f,p,g)=>f.onStepFinishedEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();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 h();case v.THINKING_END:return h();case v.THINKING_TEXT_MESSAGE_START:return h();case v.THINKING_TEXT_MESSAGE_CONTENT:return h();case v.THINKING_TEXT_MESSAGE_END:return h();case v.REASONING_START:return c(await K(r,s,a,(f,p,g)=>f.onReasoningStartEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.REASONING_MESSAGE_START:{let f=await K(r,s,a,(p,g,x)=>p.onReasoningMessageStartEvent?.({event:m,messages:g,state:x,agent:n,input:t}));if(c(f),f.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 h()}case v.REASONING_MESSAGE_CONTENT:{let{messageId:f,delta:p}=m,g=s.find(S=>S.id===f);if(!g)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${f}'`),h();let x=await K(r,s,a,(S,w,I)=>S.onReasoningMessageContentEvent?.({event:m,messages:w,state:I,agent:n,input:t,reasoningMessageBuffer:typeof g.content=="string"?g.content:""}));return c(x),x.stopPropagation!==!0&&(g.content=`${typeof g.content=="string"?g.content:""}${p}`,c({messages:s})),h()}case v.REASONING_MESSAGE_END:{let{messageId:f}=m,p=s.find(g=>g.id===f);return p?(c(await K(r,s,a,(g,x,S)=>g.onReasoningMessageEndEvent?.({event:m,messages:x,state:S,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})})),h()):(console.warn(`REASONING_MESSAGE_END: No message found with ID '${f}'`),h())}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,(f,p,g)=>f.onReasoningEndEvent?.({event:m,messages:p,state:g,agent:n,input:t}))),h();case v.REASONING_ENCRYPTED_VALUE:{let{subtype:f,entityId:p,encryptedValue:g}=m,x=await K(r,s,a,(S,w,I)=>S.onReasoningEncryptedValueEvent?.({event:m,messages:w,state:I,agent:n,input:t}));if(c(x),x.stopPropagation!==!0){let S=!1;if(f==="tool-call"){for(let w of s)if(w.role==="assistant"&&w.toolCalls){let I=w.toolCalls.find(H=>H.id===p);if(I){I.encryptedValue=g,S=!0;break}}}else{let w=s.find(I=>I.id===p);w?.role!=="activity"&&w&&(w.encryptedValue=g,S=!0)}S&&(l.messages=s)}return h()}}return m.type,h()}),$s(),r.length>0?Bs({}):m=>m)},aa=t=>e=>{let n=sr(t),r=new Map,o=new Map,i=!1,s=!1,a=!1,l=new Map,c=!1,h=!1,m=!1,y=()=>{r.clear(),o.clear(),l.clear(),c=!1,h=!1,i=!1,s=!1,m=!0};return e.pipe(Me(f=>{let p=f.type;if(n?.event("VERIFY","Event:",f,{type:f.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=f.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(f))}case v.TEXT_MESSAGE_CONTENT:{let g=f.messageId;return r.has(g)?ue(f):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=f.messageId;return r.has(g)?(r.delete(g),ue(f)):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=f.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(f))}case v.TOOL_CALL_ARGS:{let g=f.toolCallId;return o.has(g)?ue(f):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=f.toolCallId;return o.has(g)?(o.delete(g),ue(f)):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=f.stepName;return l.has(g)?ne(()=>new ee(`Step "${g}" is already active for 'STEP_STARTED'`)):(l.set(g,!0),ue(f))}case v.STEP_FINISHED:{let g=f.stepName;return l.has(g)?(l.delete(g),ue(f)):ne(()=>new ee(`Cannot send 'STEP_FINISHED' for step "${g}" that was not started`))}case v.RUN_STARTED:return m=!0,ue(f);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(f);case v.RUN_ERROR:return s=!0,ue(f);case v.CUSTOM:return ue(f);case v.THINKING_TEXT_MESSAGE_START:return c?h?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.")):(h=!0,ue(f)):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 h?ue(f):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 h?(h=!1,ue(f)):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(f));case v.THINKING_END:return c?(c=!1,ue(f)):ne(()=>new ee("Cannot send 'THINKING_END' event: No active thinking step found. A 'THINKING_START' event must be sent first."));default:return ue(f)}}))},en=(function(t){return t.HEADERS="headers",t.DATA="data",t})({}),$m=t=>To(()=>Zt(t())).pipe(Vs(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"))})),Bm=(t,e)=>{let n=sr(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 c=i.split(/\n\n/);i=c.pop()||"";for(let h of c)s(h)}},error:a=>r.error(a),complete:()=>{i&&(i+=o.decode(),s(i)),r.complete()}});function s(a){let l=a.split(`
|
|
9
9
|
`),c=[];for(let h of l)h.startsWith("data:")&&c.push(h.slice(5).replace(/^ /,""));if(c.length>0)try{let h=c.join(`
|
|
10
10
|
`),m=JSON.parse(h);n?.event("SSE","Event received:",m,{type:m.type}),r.next(m)}catch(h){r.error(h)}}return r.asObservable()},Vm=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=su(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()},jm=(t,e)=>{let n=sr(e),r=new st,o=new lo,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===ra?"protobuf":"sse"}),a===ra?Vm(o).subscribe({next:l=>r.next(l),error:l=>r.error(l),complete:()=>r.complete()}):Bm(o,n).subscribe({next:l=>{try{let c=qr.parse(l);n?.event("HTTP","Event validated:",c,{type:c.type,valid:!0}),r.next(c)}catch(c){n?.event("HTTP","Event invalid:",{json:l,error:String(c)}),r.error(c)}},error:l=>{if(l?.name==="AbortError"){r.next({type:v.RUN_ERROR,message:l.message||"Request aborted",code:"abort",rawEvent:l}),r.complete();return}return r.error(l)},complete:()=>r.complete()})}else i||r.error(Error("No headers event received before data events"))},error:s=>{o.error(s),r.error(s)},complete:()=>{o.complete()}}),r.asObservable()},Q=u.enum(["TextMessageStart","TextMessageContent","TextMessageEnd","ActionExecutionStart","ActionExecutionArgs","ActionExecutionEnd","ActionExecutionResult","AgentStateMessage","MetaEvent","RunStarted","RunFinished","RunError","NodeStarted","NodeFinished"]),qm=u.enum(["LangGraphInterruptEvent","PredictState","Exit"]),Wm=u.object({type:u.literal(Q.enum.TextMessageStart),messageId:u.string(),parentMessageId:u.string().optional(),role:u.string().optional()}),Xm=u.object({type:u.literal(Q.enum.TextMessageContent),messageId:u.string(),content:u.string()}),Ym=u.object({type:u.literal(Q.enum.TextMessageEnd),messageId:u.string()}),Km=u.object({type:u.literal(Q.enum.ActionExecutionStart),actionExecutionId:u.string(),actionName:u.string(),parentMessageId:u.string().optional()}),Zm=u.object({type:u.literal(Q.enum.ActionExecutionArgs),actionExecutionId:u.string(),args:u.string()}),Jm=u.object({type:u.literal(Q.enum.ActionExecutionEnd),actionExecutionId:u.string()}),Qm=u.object({type:u.literal(Q.enum.ActionExecutionResult),actionName:u.string(),actionExecutionId:u.string(),result:u.string()}),eg=u.object({type:u.literal(Q.enum.AgentStateMessage),threadId:u.string(),agentName:u.string(),nodeName:u.string(),runId:u.string(),active:u.boolean(),role:u.string(),state:u.string(),running:u.boolean()}),tg=u.object({type:u.literal(Q.enum.MetaEvent),name:qm,value:u.any()}),ng=u.object({type:u.literal(Q.enum.RunError),message:u.string(),code:u.string().optional()});u.discriminatedUnion("type",[Wm,Xm,Ym,Km,Zm,Jm,Qm,eg,tg,ng]),u.object({id:u.string(),role:u.string(),content:u.string(),parentMessageId:u.string().optional()}),u.object({id:u.string(),name:u.string(),arguments:u.any(),parentMessageId:u.string().optional()}),u.object({id:u.string(),result:u.any(),actionExecutionId:u.string(),actionName:u.string()});var rg=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
|
-
`)},og=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,h=[],m={},y=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(Me(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let p=f;return[{type:Q.enum.TextMessageStart,messageId:p.messageId,role:p.role}]}case v.TEXT_MESSAGE_CONTENT:{let p=f;return[{type:Q.enum.TextMessageContent,messageId:p.messageId,content:p.delta}]}case v.TEXT_MESSAGE_END:{let p=f;return[{type:Q.enum.TextMessageEnd,messageId:p.messageId}]}case v.TOOL_CALL_START:{let p=f;return h.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=f,g=h.find(S=>S.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 S=c.find(w=>w.tool==g.function.name);if(S)try{let w=JSON.parse(ko(g.function.arguments));S.tool_argument&&S.tool_argument in w?(y({...o,[S.state_key]:w[S.tool_argument]}),x=!0):S.tool_argument||(y({...o,[S.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=f;return[{type:Q.enum.ActionExecutionEnd,actionExecutionId:p.toolCallId}]}case v.TOOL_CALL_RESULT:{let p=f;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=f;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(f.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=f,g=eo.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=f.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:ig(l)}:{}}),active:!1}];case v.RUN_ERROR:{let p=f;return[{type:Q.enum.RunError,message:p.message,code:p.code}]}case v.STEP_STARTED:return a=f.stepName,h=[],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 h=[],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 ig(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=rg(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 ci=t=>e=>{let n=sr(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},h=()=>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[...h(),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,f=[];if((s!=="text"||y.messageId!==void 0&&y.messageId!==r?.messageId)&&f.push(...h()),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}};f.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};f.push(w),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",w,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let p=m,g=[];if((s!=="tool"||p.toolCallId!==void 0&&p.toolCallId!==o?.toolCallId)&&g.push(...h()),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,S=[];if((s!=="reasoning"||x.messageId&&x.messageId!==i?.messageId)&&S.push(...h()),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};S.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};S.push(w),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",w,{messageId:i.messageId})}return S}return m.type,[]}),Qt(()=>{h()}))};function sg(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function vu(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 ui=class{runNext(t,e){return e.run(t).pipe(ci(!1))}runNextWithState(t,e){let n=q(t.messages||[]),r=q(t.state||{}),o=new lo;return gu(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(So(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:q(n),state:q(r)})))}},ag=class extends ui{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function lg(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 cg=class extends ui{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(lg)};return this.runNext(o,e)}},du="THINKING_START",pu="THINKING_END",hu="THINKING_TEXT_MESSAGE_START",fu="THINKING_TEXT_MESSAGE_CONTENT",mu="THINKING_TEXT_MESSAGE_END",ug=class extends ui{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 du:{this.currentReasoningId=Ue();let{title:e,...n}=t;return this.warnAboutTransformation(du,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case hu:return this.currentMessageId=Ue(),this.warnAboutTransformation(hu,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case fu:{let{delta:e,...n}=t;return this.warnAboutTransformation(fu,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ue(),delta:e}}case mu:{let e=this.currentMessageId??Ue();return this.warnAboutTransformation(mu,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case pu:{let e=this.currentReasoningId??Ue();return this.warnAboutTransformation(pu,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function dg(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function pg(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function hg(t){let e=dg(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 fg(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>pg(r)?hg(r):r);return{...t,content:n}}var mg=class extends ui{run(t,e){let n={...t,messages:t.messages.map(fg)};return this.runNext(n,e)}},gg="0.0.57",vg=class{get maxVersion(){return gg}get debug(){return this._debug}set debug(t){this._debug=li(t),this._debugLogger=sa(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?sa(li(!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=li(i),this._debugLogger=sa(this._debug),ir(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new cg),ir(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new ug),ir(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new mg)}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 ag(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 wo(ao(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:h=>c.run(h,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),ci(this.debugLogger),aa(this.debugLogger),l=>l.pipe(Ao(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),nr(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 Cs}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 wo(ao(()=>To(()=>this.connect(n)),ci(this.debugLogger),aa(this.debugLogger),l=>l.pipe(Ao(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),nr(l=>(this.isRunning=!1,l instanceof Cs?co: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 gu(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(js(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(sg(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(ci(this.debugLogger),aa(this.debugLogger),og(this.threadId,e.runId,this.agentId),n=>n.pipe(Jt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},bu=class extends vg{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 jm($m(()=>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 di=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:Ue(),file:e,status:Pe.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#s(e);if(r!==null){n.status=Pe.ERROR,n.error=r,this.#i(),this.#n.onChange?.();return}this.#i(),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===Pe.UPLOADING)}pendingCount(){return this.#t.filter(e=>e.status===Pe.UPLOADING).length}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Pe.UPLOADING),this.#i()}clear(){for(let e of this.#t)e.controller?.abort();this.#t=[],this.#i()}dispose(){for(let e of this.#t)e.controller?.abort()}#s(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",Hr(this.#n.maxBytes)):bg(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#s(e.file);if(n!==null){e.status=Pe.ERROR,e.error=n,this.#i(),this.#n.onChange?.();return}e.status=Pe.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#i(),this.#n.upload(e.file,o=>{e.progress=o,this.#i()},r.signal).then(o=>{e.status=Pe.READY,e.ref=o}).catch(o=>{e.status=Pe.ERROR,e.error=o instanceof Error?o.message:this.#e.uploadFailed}).finally(()=>{e.controller=null,this.#i(),this.#n.onChange?.()})}#a(e){e.controller?.abort(),this.#t=this.#t.filter(n=>n!==e),this.#i(),this.#n.onChange?.()}#i(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#o(e))}#o(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.innerHTML=Es(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===Pe.ERROR?e.error:Hr(e.file.size),n.append(r,o,i),e.status===Pe.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===Pe.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 bg(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 pi(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 ar=class{element;#n;#e;#t;#s=null;#r;#a=[];constructor(e,n=ae){this.#n=e,this.#r=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.tabIndex=-1,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.setAttribute("part","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=>this.#l(o))}setRuns(e){this.#a=e,this.#c()}setStrings(e){this.#r=e,this.element.setAttribute("aria-label",e.checkpoints),this.#t.textContent=e.checkpoints,this.#c()}open(){this.open_||(this.#s=this.#i(),this.element.hidden=!1,(this.#o()[0]??this.element).focus())}close(){this.open_&&(this.element.hidden=!0,this.#s?.focus(),this.#s=null)}#i(){return this.element.getRootNode().activeElement}#o(){return Array.from(this.element.querySelectorAll("button, [tabindex]")).filter(e=>!e.hidden)}#l(e){if(e.key==="Escape"){e.stopPropagation(),this.close();return}if(e.key!=="Tab")return;let n=this.#o(),r=n[0],o=n[n.length-1],i=this.#i();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}get open_(){return!this.element.hidden}#c(){if(this.#e.replaceChildren(),this.#a.length===0){let e=document.createElement("div");e.className="checkpoints-empty",e.setAttribute("part","checkpoints-empty"),e.textContent=this.#r.noCheckpoints,this.#e.append(e);return}for(let e of this.#a)this.#e.append(this.#d(e))}#d(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.setAttribute("part","checkpoint-label"),r.textContent=e.started_at===null?e.run_id:pi(Date.parse(e.started_at),Date.now(),this.#r),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.#r.forkedRun,o.title=e.parent_run_id,n.append(o)}return n.append(this.#u(e.run_id,"resume",this.#r.resumeRun),this.#u(e.run_id,"fork",this.#r.forkRun)),n}#u(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 yu(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 ua(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),a.hidden=Object.keys(e.args).length===0;let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=yu("cancel",r.cancel),h=yu("confirm",r.confirm),m=!1,y=f=>{m||(m=!0,i.remove(),o(f))};if(c.addEventListener("click",()=>y(!1)),h.addEventListener("click",()=>y(!0)),n.signal?.addEventListener("abort",()=>y(!1),{once:!0}),l.append(c,h),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){y(!1);return}h.focus()})}function da(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function yg(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function pa(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 h=document.createElement("div");h.className="question-options",h.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 Ve=document.createElement("span");Ve.setAttribute("part","question-choice-text"),Ve.textContent=U,Y.append(re,Ve),h.appendChild(Y),y.push(re)}let f=null,p=null;if(s){if(p=yg(r.answerPlaceholder),i){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice"),f=document.createElement("input"),f.type="radio",f.name=m,f.value="",f.setAttribute("part","question-radio");let Y=document.createElement("span");Y.setAttribute("part","question-choice-text"),Y.textContent=r.otherOption,U.append(f,Y),h.appendChild(U),p.disabled=!0}h.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 S=!1,w=()=>{let U=y.find(Y=>Y.checked);if(U!==void 0)return U.value;if(p!==null&&(f===null||f.checked)){let Y=p.value.trim();return Y===""?null:Y}return null},C=()=>{p!==null&&f!==null&&(p.disabled=!f.checked),x.disabled=w()===null},H=U=>{if(!S){S=!0,x.disabled=!0;for(let Y of y)Y.disabled=!0;f!==null&&(f.disabled=!0),p!==null&&(p.disabled=!0),l.setAttribute("data-resolved",U===""?"cancelled":"answered"),a(U)}};for(let U of[...y,...f!==null?[f]:[]])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,h,g),t.appendChild(l),n.signal?.aborted===!0){H("");return}C(),(i?y[0]:p)?.focus()})}function xu(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 xg(t){if(Array.isArray(t))return t}function _g(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(h){c=!0,o=h}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function Eg(){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 wg(t,e){return xg(t)||_g(t,e)||Tg(t,e)||Eg()}function Tg(t,e){if(t){if(typeof t=="string")return xu(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)?xu(t,e):void 0}}var Pu=Object.entries,_u=Object.setPrototypeOf,Sg=Object.isFrozen,Ag=Object.getPrototypeOf,kg=Object.getOwnPropertyDescriptor,we=Object.freeze,Te=Object.seal,On=Object.create,Du=typeof Reflect<"u"&&Reflect,ba=Du.apply,ya=Du.construct;we||(we=function(e){return e});Te||(Te=function(e){return e});ba||(ba=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)});ya||(ya=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 Rn=me(Array.prototype.forEach),Ig=me(Array.prototype.lastIndexOf),Eu=me(Array.prototype.pop),Nn=me(Array.prototype.push),Cg=me(Array.prototype.splice),kt=Array.isArray,ur=me(String.prototype.toLowerCase),ha=me(String.prototype.toString),wu=me(String.prototype.match),lr=me(String.prototype.replace),Tu=me(String.prototype.indexOf),Rg=me(String.prototype.trim),Ng=me(Number.prototype.toString),Og=me(Boolean.prototype.toString),Su=typeof BigInt>"u"?null:me(BigInt.prototype.toString),Au=typeof Symbol>"u"?null:me(Symbol.prototype.toString),ye=me(Object.prototype.hasOwnProperty),cr=me(Object.prototype.toString),be=me(RegExp.prototype.test),tn=Mg(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 ba(t,e,r)}}function Mg(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return ya(t,n)}}function W(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ur;if(_u&&_u(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&&(Sg(e)||(e[r]=i),o=i)}t[o]=!0}return t}function Lg(t){for(let e=0;e<t.length;e++)ye(t,e)||(t[e]=null);return t}function Ae(t){let e=On(null);for(let r of Pu(t)){var n=wg(r,2);let o=n[0],i=n[1];ye(t,o)&&(kt(i)?e[o]=Lg(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ae(i):e[o]=i)}return e}function Pg(t){switch(typeof t){case"string":return t;case"number":return Ng(t);case"boolean":return Og(t);case"bigint":return Su?Su(t):"0";case"symbol":return Au?Au(t):"Symbol()";case"undefined":return cr(t);case"function":case"object":{if(t===null)return cr(t);let e=t,n=Ye(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:cr(r)}return cr(t)}default:return cr(t)}}function Ye(t,e){for(;t!==null;){let r=kg(t,e);if(r){if(r.get)return me(r.get);if(typeof r.value=="function")return me(r.value)}t=Ag(t)}function n(){return null}return n}function Dg(t){try{return be(t,""),!0}catch{return!1}}var ku=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"]),fa=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"]),ma=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"]),Ug=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"]),ga=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"]),Hg=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Iu=we(["#text"]),Cu=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"]),va=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"]),Ru=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"]),hi=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),zg=Te(/{{[\w\W]*|^[\w\W]*}}/g),Gg=Te(/<%[\w\W]*|^[\w\W]*%>/g),Fg=Te(/\${[\w\W]*/g),$g=Te(/^data-[\-\w.\u00B7-\uFFFF]+$/),Bg=Te(/^aria-[\-\w]+$/),Nu=Te(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vg=Te(/^(?:\w+script|data):/i),jg=Te(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),qg=Te(/^html$/i),Wg=Te(/^[a-z][.\w]*(-[.\w]+)+$/i),Ou=Te(/<[/\w!]/g),Mu=Te(/<[/\w]/g),Xg=Te(/<\/no(script|embed|frames)/i),Yg=Te(/\/>/i),He={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Kg=function(){return typeof window>"u"?null:window},Zg=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}},Lu=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 Uu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Kg(),e=T=>Uu(T);if(e.version="3.4.13",e.removed=[],!t||!t.document||t.document.nodeType!==He.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 h=t.DOMParser,m=t.trustedTypes,y=a.prototype,f=Ye(y,"cloneNode"),p=Ye(y,"remove"),g=Ye(y,"nextSibling"),x=Ye(y,"childNodes"),S=Ye(y,"parentNode"),w=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 T=n.createElement("template");T.content&&T.content.ownerDocument&&(n=T.content.ownerDocument)}let re,Ve="",ki,Ga=!1,Dn=0,Fa=function(){if(Dn>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){Fa(),Dn++;try{return re.createHTML(d)}finally{Dn--}},vd=function(d){Fa(),Dn++;try{return re.createScriptURL(d)}finally{Dn--}},bd=function(){return Ga||(ki=Zg(m,o),Ga=!0),ki},xr=n,Ii=xr.implementation,$a=xr.createNodeIterator,yd=xr.createDocumentFragment,xd=xr.getElementsByTagName,_d=r.importNode,oe=Lu();e.isSupported=typeof Pu=="function"&&typeof S=="function"&&Ii&&Ii.createHTMLDocument!==void 0;let Ed=zg,wd=Gg,Td=Fg,Sd=$g,Ad=Bg,kd=Vg,Ba=jg,Id=Wg,Va=Nu,ie=null,Ci=W({},[...ku,...fa,...ma,...ga,...Iu]),se=null,Ri=W({},[...Cu,...va,...Ru,...hi]),de=Object.seal(On(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}})),Un=null,ja=null,gt=Object.seal(On(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),qa=!0,Ni=!0,Wa=!1,Xa=!0,vt=!1,bt=!0,Ct=!1,Oi=!1,_r=null,Er=null,Mi=!1,an=!1,wr=!1,Tr=!1,Ya=!0,Ka=!1,Za="user-content-",Li=!0,Sr=!1,ln={},Je=null,Pi=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"]),Ja=null,Qa=W({},["audio","video","img","source","image","track"]),Di=null,el=W({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ar="http://www.w3.org/1998/Math/MathML",kr="http://www.w3.org/2000/svg",Qe="http://www.w3.org/1999/xhtml",cn=Qe,Ui=!1,Hi=null,Cd=W({},[Ar,kr,Qe],ha),tl=we(["mi","mo","mn","ms","mtext"]),zi=W({},tl),nl=we(["annotation-xml"]),Gi=W({},nl),Rd=W({},["title","style","font","a","script"]),Hn=null,Nd=["application/xhtml+xml","text/html"],Od="text/html",le=null,un=null,Md=n.createElement("form"),rl=function(d){return d instanceof RegExp||d instanceof Function},Fi=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),Hn=Nd.indexOf(d.PARSER_MEDIA_TYPE)===-1?Od:d.PARSER_MEDIA_TYPE,le=Hn==="application/xhtml+xml"?ha:ur,ie=At(d,"ALLOWED_TAGS",Ci,{transform:le}),se=At(d,"ALLOWED_ATTR",Ri,{transform:le}),Hi=At(d,"ALLOWED_NAMESPACES",Cd,{transform:ha}),Di=At(d,"ADD_URI_SAFE_ATTR",el,{transform:le,base:el}),Ja=At(d,"ADD_DATA_URI_TAGS",Qa,{transform:le,base:Qa}),Je=At(d,"FORBID_CONTENTS",Pi,{transform:le}),Un=At(d,"FORBID_TAGS",Ae({}),{transform:le}),ja=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,qa=d.ALLOW_ARIA_ATTR!==!1,Ni=d.ALLOW_DATA_ATTR!==!1,Wa=d.ALLOW_UNKNOWN_PROTOCOLS||!1,Xa=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,wr=d.RETURN_DOM_FRAGMENT||!1,Tr=d.RETURN_TRUSTED_TYPE||!1,Mi=d.FORCE_BODY||!1,Ya=d.SANITIZE_DOM!==!1,Ka=d.SANITIZE_NAMED_PROPS||!1,Li=d.KEEP_CONTENT!==!1,Sr=d.IN_PLACE||!1,Va=Dg(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Nu,cn=typeof d.NAMESPACE=="string"?d.NAMESPACE:Qe,zi=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({},tl),Gi=ye(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ae(d.HTML_INTEGRATION_POINTS):W({},nl);let b=ye(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ae(d.CUSTOM_ELEMENT_HANDLING):On(null);if(de=On(null),ye(b,"tagNameCheck")&&rl(b.tagNameCheck)&&(de.tagNameCheck=b.tagNameCheck),ye(b,"attributeNameCheck")&&rl(b.attributeNameCheck)&&(de.attributeNameCheck=b.attributeNameCheck),ye(b,"allowCustomizedBuiltInElements")&&typeof b.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=b.allowCustomizedBuiltInElements),Te(de),vt&&(Ni=!1),wr&&(an=!0),ln&&(ie=W({},Iu),se=On(null),ln.html===!0&&(W(ie,ku),W(se,Cu)),ln.svg===!0&&(W(ie,fa),W(se,va),W(se,hi)),ln.svgFilters===!0&&(W(ie,ma),W(se,va),W(se,hi)),ln.mathMl===!0&&(W(ie,ga),W(se,Ru),W(se,hi))),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===Ci&&(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===Ri&&(se=Ae(se)),W(se,d.ADD_ATTR,le))),ye(d,"ADD_URI_SAFE_ATTR")&&kt(d.ADD_URI_SAFE_ATTR)&&W(Di,d.ADD_URI_SAFE_ATTR,le),ye(d,"FORBID_CONTENTS")&&kt(d.FORBID_CONTENTS)&&(Je===Pi&&(Je=Ae(Je)),W(Je,d.FORBID_CONTENTS,le)),ye(d,"ADD_FORBID_CONTENTS")&&kt(d.ADD_FORBID_CONTENTS)&&(Je===Pi&&(Je=Ae(Je)),W(Je,d.ADD_FORBID_CONTENTS,le)),Li&&(ie["#text"]=!0),Ct&&W(ie,["html","head","body"]),ie.table&&(W(ie,["tbody"]),delete Un.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 _=re;re=d.TRUSTED_TYPES_POLICY;try{Ve=sn("")}catch(N){throw re=_,N}}else d.TRUSTED_TYPES_POLICY===null?(re=void 0,Ve=""):(re===void 0&&(re=bd()),re&&typeof Ve=="string"&&(Ve=sn("")));we&&we(d),un=d},ol=W({},[...fa,...ma,...Ug]),il=W({},[...ga,...Hg]),Ld=function(d,b,_){return b.namespaceURI===Qe?d==="svg":b.namespaceURI===Ar?d==="svg"&&(_==="annotation-xml"||zi[_]):!!ol[d]},Pd=function(d,b,_){return b.namespaceURI===Qe?d==="math":b.namespaceURI===kr?d==="math"&&Gi[_]:!!il[d]},Dd=function(d,b,_){return b.namespaceURI===kr&&!Gi[_]||b.namespaceURI===Ar&&!zi[_]?!1:!il[d]&&(Rd[d]||!ol[d])},Ud=function(d){let b=S(d);(!b||!b.tagName)&&(b={namespaceURI:cn,tagName:"template"});let _=ur(d.tagName),N=ur(b.tagName);return Hi[d.namespaceURI]?d.namespaceURI===kr?Ld(_,b,N):d.namespaceURI===Ar?Pd(_,b,N):d.namespaceURI===Qe?Dd(_,b,N):!!(Hn==="application/xhtml+xml"&&Hi[d.namespaceURI]):!1},yt=function(d){Nn(e.removed,{element:d});try{S(d).removeChild(d)}catch{if(p(d),!S(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")}},Ir=function(d){zn(d);let b=x(d);if(b){let N=[];Rn(b,L=>{Nn(N,L)}),Rn(N,L=>{try{p(L)}catch{}})}let _=C(d);if(_)for(let N=_.length-1;N>=0;--N){let L=_[N],z=L&&L.name;if(typeof z=="string")try{d.removeAttribute(z)}catch{}}},Rt=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||wr)try{yt(b)}catch{}else try{b.setAttribute(d,"")}catch{}},Hd=function(d){let b=C(d);if(b)for(let _=b.length-1;_>=0;--_){let N=b[_],L=N&&N.name;if(!(typeof L!="string"||se[le(L)]))try{d.removeAttribute(L)}catch{}}},zn=function(d){let b=[d];for(;b.length>0;){let _=b.pop();(H?H(_):_.nodeType)===He.element&&Hd(_);let L=x(_);if(L)for(let z=L.length-1;z>=0;--z)b.push(L[z])}},zd=function(d){if(!bt)return;let b=[d];for(;b.length>0;){let _=b.pop(),N=H?H(_):_.nodeType;if(N===He.processingInstruction||N===He.comment&&be(Mu,_.data)){try{p(_)}catch{}continue}if(N===He.element){let z=_,Z=le(U?U(_):_.nodeName);try{z.hasAttribute&&z.hasAttribute("patchsrc")&&z.removeAttribute("patchsrc"),z.hasAttribute&&z.hasAttribute("for")&&Z!=="label"&&Z!=="output"&&z.removeAttribute("for")}catch{}}let L=x(_);if(L)for(let z=L.length-1;z>=0;--z)b.push(L[z])}},sl=function(d){let b=null,_=null;if(Mi)d="<remove></remove>"+d;else{let z=wu(d,/^[\r\n\t ]+/);_=z&&z[0]}Hn==="application/xhtml+xml"&&cn===Qe&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let N=re?sn(d):d;if(cn===Qe)try{b=new h().parseFromString(N,Hn)}catch{}if(!b||!b.documentElement){b=Ii.createDocument(cn,"template",null);try{b.documentElement.innerHTML=Ui?Ve:N}catch{}}let L=b.body||b.documentElement;return d&&_&&L.insertBefore(n.createTextNode(_),L.childNodes[0]||null),cn===Qe?xd.call(b,Ct?"html":"body")[0]:Ct?b.documentElement:L},al=function(d){let b=Y?Y(d):d.ownerDocument;return $a.call(b||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Cr=function(d){return d=lr(d,Ed," "),d=lr(d,wd," "),d=lr(d,Td," "),d},$i=function(d){var b;d.normalize();let _=Y?Y(d):d.ownerDocument,N=$a.call(_||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),L=N.nextNode();for(;L;)L.data=Cr(L.data),L=N.nextNode();let z=(b=d.querySelectorAll)===null||b===void 0?void 0:b.call(d,"template");z&&Rn(z,Z=>{dn(Z.content)&&$i(Z.content)})},Rr=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)===He.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(T,d,b){T.length!==0&&Rn(T,_=>{_.call(e,d,b,un)})}let Gd=function(d,b){return!!(bt&&d.hasChildNodes()&&!Gn(d.firstElementChild)&&be(Ou,d.textContent)&&be(Ou,d.innerHTML)||bt&&d.namespaceURI===Qe&&b==="style"&&Gn(d.firstElementChild)||d.nodeType===He.processingInstruction||bt&&d.nodeType===He.comment&&be(Mu,d.data))},Fd=function(d,b,_){if(!Un[b]&&dl(b)&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,b)||de.tagNameCheck instanceof Function&&de.tagNameCheck(b)))return!1;if(Li&&!Je[b]){let N=S(d),L=x(d);if(L&&N){let z=L.length;for(let Z=z-1;Z>=0;--Z){let ce=d===_?f(L[Z],!0):L[Z];N.insertBefore(ce,g(d))}}}return yt(d),!0},ll=function(d,b,_,N){return d.length===0?b:b===_||b===N?Ae(b):b},cl=function(d,b){if(et(oe.beforeSanitizeElements,d,null),d!==b&&S(d)===null)return Sr&&zn(d),!0;if(Rr(d))return yt(d),!0;let _=le(U?U(d):d.nodeName);if(ie=ll(oe.uponSanitizeElement,ie,Ci,_r),et(oe.uponSanitizeElement,d,{tagName:_,allowedTags:ie}),d!==b&&S(d)===null)return Sr&&zn(d),!0;if(Gd(d,_))return yt(d),!0;if(Un[_]||!(gt.tagCheck instanceof Function&>.tagCheck(_))&&!ie[_]){let L=Fd(d,_,b);return L===!1&&et(oe.afterSanitizeElements,d,null),L}if((H?H(d):d.nodeType)===He.element&&!Ud(d)||(_==="noscript"||_==="noembed"||_==="noframes")&&be(Xg,d.innerHTML))return yt(d),!0;if(vt&&d.nodeType===He.text){let L=Cr(d.textContent);d.textContent!==L&&(Nn(e.removed,{element:d.cloneNode()}),d.textContent=L)}return et(oe.afterSanitizeElements,d,null),!1},ul=function(d,b,_){if(ja[b]||bt&&b==="patchsrc"||bt&&b==="for"&&d!=="label"&&d!=="output"||Ya&&(b==="id"||b==="name")&&(_ in n||_ in Md))return!1;let N=se[b]||gt.attributeCheck instanceof Function&>.attributeCheck(b,d);if(!(Ni&&be(Sd,b))){if(!(qa&&be(Ad,b))){if(N){if(!Di[b]){if(!be(Va,lr(_,Ba,""))){if(!((b==="src"||b==="xlink:href"||b==="href")&&d!=="script"&&Tu(_,"data:")===0&&Ja[d])){if(!(Wa&&!be(kd,lr(_,Ba,"")))){if(_)return!1}}}}}else if(!(dl(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,_)||de.tagNameCheck instanceof Function&&de.tagNameCheck(_))))return!1}}return!0},$d=W({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),dl=function(d){return!$d[ur(d)]&&be(Id,d)},Bd=function(d,b,_,N){if(re&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!_)switch(m.getAttributeType(d,b)){case"TrustedHTML":return sn(N);case"TrustedScriptURL":return vd(N)}return N},Vd=function(d,b,_,N){try{_?d.setAttributeNS(_,b,N):d.setAttribute(b,N),Rr(d)?yt(d):Eu(e.removed)}catch{Rt(b,d)}},pl=function(d){et(oe.beforeSanitizeAttributes,d,null);let b=d.attributes;if(!b||Rr(d))return;se=ll(oe.uponSanitizeAttribute,se,Ri,Er);let _={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},N=b.length,L=le(d.nodeName);for(;N--;){let z=b[N],Z=z.name,ce=z.namespaceURI,Ce=z.value,Re=le(Z),Vi=Ce,Ie=Z==="value"?Vi:Rg(Vi);if(_.attrName=Re,_.attrValue=Ie,_.keepAttr=!0,_.forceKeepAttr=void 0,et(oe.uponSanitizeAttribute,d,_),Ie=_.attrValue,Ka&&(Re==="id"||Re==="name")&&Tu(Ie,Za)!==0&&(Rt(Z,d),Ie=Za+Ie),bt&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ie)){Rt(Z,d);continue}if(Re==="attributename"&&wu(Ie,"href")){Rt(Z,d);continue}if(!_.forceKeepAttr){if(!_.keepAttr){Rt(Z,d);continue}if(!Xa&&be(Yg,Ie)){Rt(Z,d);continue}if(vt&&(Ie=Cr(Ie)),!ul(L,Re,Ie)){Rt(Z,d);continue}Ie=Bd(L,Re,ce,Ie),Ie!==Vi&&Vd(d,Z,ce,Ie)}}et(oe.afterSanitizeAttributes,d,null)},Nr=function(d){let b=null,_=al(d);for(et(oe.beforeSanitizeShadowDOM,d,null);b=_.nextNode();)if(et(oe.uponSanitizeShadowNode,b,null),cl(b,d),pl(b),dn(b.content)&&Nr(b.content),(H?H(b):b.nodeType)===He.element){let L=w(b);dn(L)&&(Bi(L),Nr(L))}et(oe.afterSanitizeShadowDOM,d,null)},Bi=function(d){let b=[{node:d,shadow:null}];for(;b.length>0;){let _=b.pop();if(_.shadow){Nr(_.shadow);continue}let N=_.node,z=(H?H(N):N.nodeType)===He.element,Z=x(N);if(Z)for(let ce=Z.length-1;ce>=0;--ce)b.push({node:Z[ce],shadow:null});if(z){let ce=U?U(N):null;if(typeof ce=="string"&&le(ce)==="template"){let Ce=N.content;dn(Ce)&&b.push({node:Ce,shadow:null})}}if(z){let ce=w(N);dn(ce)&&b.push({node:null,shadow:ce},{node:ce,shadow:null})}}};return e.sanitize=function(T){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},b=null,_=null,N=null,L=null;if(Ui=!T,Ui&&(T="<!-->"),typeof T!="string"&&!Gn(T)&&(T=Pg(T),typeof T!="string"))throw tn("dirty is not a string, aborting");if(!e.isSupported)return T;Oi?(ie=_r,se=Er):Fi(d),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=Ae(ie)),oe.uponSanitizeAttribute.length>0&&(se=Ae(se)),e.removed=[];let z=Sr&&typeof T!="string"&&Gn(T);if(z){zd(T);let Ce=U?U(T):T.nodeName;if(typeof Ce=="string"){let Re=le(Ce);if(!ie[Re]||Un[Re])throw Ir(T),tn("root node is forbidden and cannot be sanitized in-place")}if(Rr(T))throw Ir(T),tn("root node is clobbered and cannot be sanitized in-place");try{Bi(T)}catch(Re){throw Ir(T),Re}}else if(Gn(T))b=sl("<!---->"),_=b.ownerDocument.importNode(T,!0),_.nodeType===He.element&&_.nodeName==="BODY"||_.nodeName==="HTML"?b=_:b.appendChild(_),Bi(_);else{if(!an&&!vt&&!Ct&&T.indexOf("<")===-1)return re&&Tr?sn(T):T;if(b=sl(T),!b)return an?null:Tr?Ve:""}b&&Mi&&yt(b.firstChild);let Z=z?T:b;try{let Ce=al(Z);for(;N=Ce.nextNode();)cl(N,Z),pl(N),dn(N.content)&&Nr(N.content)}catch(Ce){throw z&&(Ir(T),Rn(e.removed,Re=>{Re.element&&zn(Re.element)})),Ce}if(z)return Rn(e.removed,Ce=>{Ce.element&&zn(Ce.element)}),vt&&$i(T),T;if(an){if(vt&&$i(b),wr)for(L=yd.call(b.ownerDocument);b.firstChild;)L.appendChild(b.firstChild);else L=b;return(se.shadowroot||se.shadowrootmode)&&(L=_d.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(qg,b.ownerDocument.doctype.name)&&(ce="<!DOCTYPE "+b.ownerDocument.doctype.name+`>
|
|
13
|
-
`+ce),vt&&(ce=
|
|
14
|
-
]`).replace("lheading",Xu).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},hv=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,fv=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ku=/^( {2,}|\\)\n(?!\s*$)/,mv=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ft=/[\p{P}\p{S}]/u,Ln=/[\s\p{P}\p{S}]/u,fr=/[^\s\p{P}\p{S}]/u,gv=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ln).getRegex(),vv=/[\p{Pi}\p{Ps}"']/u,Zu=/(?!~)[\p{P}\p{S}]/u,bv=/(?!~)[\s\p{P}\p{S}]/u,yv=/(?:[^\s\p{P}\p{S}]|~)/u,xv=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Jg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ju=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,_v=j(Ju,"u").replace(/punct/g,ft).getRegex(),Ev=j(Ju,"u").replace(/punct/g,Zu).getRegex(),wv=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,Tv=j(wv,"u").replace(/openQuote/g,vv).replace(/punct/g,ft).getRegex(),Qu="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Sv=j(Qu,"gu").replace(/notPunctSpace/g,fr).replace(/punctSpace/g,Ln).replace(/punct/g,ft).getRegex(),Av=j(Qu,"gu").replace(/notPunctSpace/g,yv).replace(/punctSpace/g,bv).replace(/punct/g,Zu).getRegex(),kv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",
|
|
11
|
+
`)},og=(t,e,n)=>r=>{let o={},i=!0,s=!0,a="",l=null,c=null,h=[],m={},y=f=>{typeof f=="object"&&f&&("messages"in f&&delete f.messages,o=f)};return r.pipe(Me(f=>{switch(f.type){case v.TEXT_MESSAGE_START:{let p=f;return[{type:Q.enum.TextMessageStart,messageId:p.messageId,role:p.role}]}case v.TEXT_MESSAGE_CONTENT:{let p=f;return[{type:Q.enum.TextMessageContent,messageId:p.messageId,content:p.delta}]}case v.TEXT_MESSAGE_END:{let p=f;return[{type:Q.enum.TextMessageEnd,messageId:p.messageId}]}case v.TOOL_CALL_START:{let p=f;return h.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=f,g=h.find(S=>S.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 S=c.find(w=>w.tool==g.function.name);if(S)try{let w=JSON.parse(ko(g.function.arguments));S.tool_argument&&S.tool_argument in w?(y({...o,[S.state_key]:w[S.tool_argument]}),x=!0):S.tool_argument||(y({...o,[S.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=f;return[{type:Q.enum.ActionExecutionEnd,actionExecutionId:p.toolCallId}]}case v.TOOL_CALL_RESULT:{let p=f;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=f;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(f.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=f,g=eo.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=f.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:ig(l)}:{}}),active:!1}];case v.RUN_ERROR:{let p=f;return[{type:Q.enum.RunError,message:p.message,code:p.code}]}case v.STEP_STARTED:return a=f.stepName,h=[],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 h=[],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 ig(t){let e=[];for(let n of t)if(n.role==="assistant"||n.role==="user"||n.role==="system"){let r=rg(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 ci=t=>e=>{let n=sr(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},h=()=>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[...h(),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,f=[];if((s!=="text"||y.messageId!==void 0&&y.messageId!==r?.messageId)&&f.push(...h()),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}};f.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};f.push(w),n?.event("TRANSFORM","TEXT_MESSAGE_CONTENT",w,{messageId:r.messageId})}return f;case v.TOOL_CALL_CHUNK:let p=m,g=[];if((s!=="tool"||p.toolCallId!==void 0&&p.toolCallId!==o?.toolCallId)&&g.push(...h()),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,S=[];if((s!=="reasoning"||x.messageId&&x.messageId!==i?.messageId)&&S.push(...h()),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};S.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};S.push(w),n?.event("TRANSFORM","REASONING_MESSAGE_CONTENT",w,{messageId:i.messageId})}return S}return m.type,[]}),Qt(()=>{h()}))};function sg(t,e=new Date){return t.expiresAt===void 0?!1:new Date(t.expiresAt)<=e}function vu(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 ui=class{runNext(t,e){return e.run(t).pipe(ci(!1))}runNextWithState(t,e){let n=q(t.messages||[]),r=q(t.state||{}),o=new lo;return gu(t,o,e,[]).subscribe(i=>{i.messages!==void 0&&(n=i.messages),i.state!==void 0&&(r=i.state)}),this.runNext(t,e).pipe(So(async i=>(o.next(i),await new Promise(s=>setTimeout(s,0)),{event:i,messages:q(n),state:q(r)})))}},ag=class extends ui{constructor(t){super(),this.fn=t}run(t,e){return this.fn(t,e)}};function lg(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 cg=class extends ui{run(t,e){let{parentRunId:n,...r}=t,o={...r,messages:r.messages.map(lg)};return this.runNext(o,e)}},du="THINKING_START",pu="THINKING_END",hu="THINKING_TEXT_MESSAGE_START",fu="THINKING_TEXT_MESSAGE_CONTENT",mu="THINKING_TEXT_MESSAGE_END",ug=class extends ui{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 du:{this.currentReasoningId=Ue();let{title:e,...n}=t;return this.warnAboutTransformation(du,v.REASONING_START),{...n,type:v.REASONING_START,messageId:this.currentReasoningId}}case hu:return this.currentMessageId=Ue(),this.warnAboutTransformation(hu,v.REASONING_MESSAGE_START),{...t,type:v.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:"assistant"};case fu:{let{delta:e,...n}=t;return this.warnAboutTransformation(fu,v.REASONING_MESSAGE_CONTENT),{...n,type:v.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??Ue(),delta:e}}case mu:{let e=this.currentMessageId??Ue();return this.warnAboutTransformation(mu,v.REASONING_MESSAGE_END),{...t,type:v.REASONING_MESSAGE_END,messageId:e}}case pu:{let e=this.currentReasoningId??Ue();return this.warnAboutTransformation(pu,v.REASONING_END),{...t,type:v.REASONING_END,messageId:e}}default:return t}}};function dg(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"document"}function pg(t){return typeof t=="object"&&!!t&&"type"in t&&t.type==="binary"&&"mimeType"in t&&typeof t.mimeType=="string"}function hg(t){let e=dg(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 fg(t){let e=t.content;if(!Array.isArray(e))return t;let n=e.map(r=>pg(r)?hg(r):r);return{...t,content:n}}var mg=class extends ui{run(t,e){let n={...t,messages:t.messages.map(fg)};return this.runNext(n,e)}},gg="0.0.57",vg=class{get maxVersion(){return gg}get debug(){return this._debug}set debug(t){this._debug=li(t),this._debugLogger=sa(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(t){typeof t=="boolean"?this._debugLogger=t?sa(li(!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=li(i),this._debugLogger=sa(this._debug),ir(this.maxVersion,"0.0.39")<=0&&this.middlewares.unshift(new cg),ir(this.maxVersion,"0.0.45")<=0&&this.middlewares.unshift(new ug),ir(this.maxVersion,"0.0.47")<=0&&this.middlewares.unshift(new mg)}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 ag(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 wo(ao(()=>this.middlewares.length===0?this.run(n):this.middlewares.reduceRight((l,c)=>({run:h=>c.run(h,l),get messages(){return l.messages},get state(){return l.state}}),this).run(n),ci(this.debugLogger),aa(this.debugLogger),l=>l.pipe(Ao(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),nr(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 Is}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 wo(ao(()=>To(()=>this.connect(n)),ci(this.debugLogger),aa(this.debugLogger),l=>l.pipe(Ao(this.activeRunDetach$)),l=>this.apply(n,l,i),l=>this.processApplyEvents(n,l,i),nr(l=>(this.isRunning=!1,l instanceof Is?co: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 gu(t,e,this,n,this.debugLogger)}processApplyEvents(t,e,n){return e.pipe(js(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(sg(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(ci(this.debugLogger),aa(this.debugLogger),og(this.threadId,e.runId,this.agentId),n=>n.pipe(Jt(r=>(this.debugLogger?.event("LEGACY","Event:",r,{type:r.type}),r))))}},bu=class extends vg{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 jm($m(()=>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 di=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:Ue(),file:e,status:Pe.UPLOADING,progress:0,ref:null,error:"",controller:null};this.#t.push(n);let r=this.#s(e);if(r!==null){n.status=Pe.ERROR,n.error=r,this.#i(),this.#n.onChange?.();return}this.#i(),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===Pe.UPLOADING)}pendingCount(){return this.#t.filter(e=>e.status===Pe.UPLOADING).length}isEmpty(){return this.#t.length===0}clearReady(){this.#t=this.#t.filter(e=>e.status===Pe.UPLOADING),this.#i()}clear(){for(let e of this.#t)e.controller?.abort();this.#t=[],this.#i()}dispose(){for(let e of this.#t)e.controller?.abort()}#s(e){return this.#n.maxBytes>0&&e.size>this.#n.maxBytes?this.#e.tooLarge.replace("{size}",Hr(this.#n.maxBytes)):bg(this.#n.accept,e)?null:this.#e.fileTypeNotAllowed}#r(e){let n=this.#s(e.file);if(n!==null){e.status=Pe.ERROR,e.error=n,this.#i(),this.#n.onChange?.();return}e.status=Pe.UPLOADING,e.progress=0,e.error="";let r=new AbortController;e.controller=r,this.#i(),this.#n.upload(e.file,o=>{e.progress=o,this.#i()},r.signal).then(o=>{e.status=Pe.READY,e.ref=o}).catch(o=>{e.status=Pe.ERROR,e.error=o instanceof Error?o.message:this.#e.uploadFailed}).finally(()=>{e.controller=null,this.#i(),this.#n.onChange?.()})}#a(e){e.controller?.abort(),this.#t=this.#t.filter(n=>n!==e),this.#i(),this.#n.onChange?.()}#i(){this.element.replaceChildren(),this.element.hidden=this.#t.length===0;for(let e of this.#t)this.element.appendChild(this.#o(e))}#o(e){let n=document.createElement("div");n.className=`attachment-chip attachment-chip--${e.status}`,n.setAttribute("part","attachment-chip");let r=document.createElement("span");r.className="attachment-chip-icon",r.setAttribute("part","attachment-chip-icon"),r.innerHTML=Es(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===Pe.ERROR?e.error:Hr(e.file.size),n.append(r,o,i),e.status===Pe.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===Pe.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 bg(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 pi(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 ar=class{element;#n;#e;#t;#s=null;#r;#a=[];constructor(e,n=ae){this.#n=e,this.#r=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.tabIndex=-1,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.setAttribute("part","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=>this.#l(o))}setRuns(e){this.#a=e,this.#c()}setStrings(e){this.#r=e,this.element.setAttribute("aria-label",e.checkpoints),this.#t.textContent=e.checkpoints,this.#c()}open(){this.open_||(this.#s=this.#i(),this.element.hidden=!1,(this.#o()[0]??this.element).focus())}close(){this.open_&&(this.element.hidden=!0,this.#s?.focus(),this.#s=null)}#i(){return this.element.getRootNode().activeElement}#o(){return Array.from(this.element.querySelectorAll("button, [tabindex]")).filter(e=>!e.hidden)}#l(e){if(e.key==="Escape"){e.stopPropagation(),this.close();return}if(e.key!=="Tab")return;let n=this.#o(),r=n[0],o=n[n.length-1],i=this.#i();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}get open_(){return!this.element.hidden}#c(){if(this.#e.replaceChildren(),this.#a.length===0){let e=document.createElement("div");e.className="checkpoints-empty",e.setAttribute("part","checkpoints-empty"),e.textContent=this.#r.noCheckpoints,this.#e.append(e);return}for(let e of this.#a)this.#e.append(this.#d(e))}#d(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.setAttribute("part","checkpoint-label"),r.textContent=e.started_at===null?e.run_id:pi(Date.parse(e.started_at),Date.now(),this.#r),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.#r.forkedRun,o.title=e.parent_run_id,n.append(o)}return n.append(this.#u(e.run_id,"resume",this.#r.resumeRun),this.#u(e.run_id,"fork",this.#r.forkRun)),n}#u(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 yu(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 ua(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),a.hidden=Object.keys(e.args).length===0;let l=document.createElement("div");l.className="confirm-actions",l.setAttribute("part","confirm-actions");let c=yu("cancel",r.cancel),h=yu("confirm",r.confirm),m=!1,y=f=>{m||(m=!0,i.remove(),o(f))};if(c.addEventListener("click",()=>y(!1)),h.addEventListener("click",()=>y(!0)),n.signal?.addEventListener("abort",()=>y(!1),{once:!0}),l.append(c,h),i.append(s,a,l),t.appendChild(i),n.signal?.aborted===!0){y(!1);return}h.focus()})}function da(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}function yg(t){let e=document.createElement("input");return e.type="text",e.className="question-input",e.setAttribute("part","question-input"),e.placeholder=t,e}function pa(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 h=document.createElement("div");h.className="question-options",h.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 Ve=document.createElement("span");Ve.setAttribute("part","question-choice-text"),Ve.textContent=U,Y.append(re,Ve),h.appendChild(Y),y.push(re)}let f=null,p=null;if(s){if(p=yg(r.answerPlaceholder),i){let U=document.createElement("label");U.className="question-choice",U.setAttribute("part","question-choice"),f=document.createElement("input"),f.type="radio",f.name=m,f.value="",f.setAttribute("part","question-radio");let Y=document.createElement("span");Y.setAttribute("part","question-choice-text"),Y.textContent=r.otherOption,U.append(f,Y),h.appendChild(U),p.disabled=!0}h.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 S=!1,w=()=>{let U=y.find(Y=>Y.checked);if(U!==void 0)return U.value;if(p!==null&&(f===null||f.checked)){let Y=p.value.trim();return Y===""?null:Y}return null},I=()=>{p!==null&&f!==null&&(p.disabled=!f.checked),x.disabled=w()===null},H=U=>{if(!S){S=!0,x.disabled=!0;for(let Y of y)Y.disabled=!0;f!==null&&(f.disabled=!0),p!==null&&(p.disabled=!0),l.setAttribute("data-resolved",U===""?"cancelled":"answered"),a(U)}};for(let U of[...y,...f!==null?[f]:[]])U.addEventListener("change",I);if(p?.addEventListener("input",I),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,h,g),t.appendChild(l),n.signal?.aborted===!0){H("");return}I(),(i?y[0]:p)?.focus()})}function xu(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 xg(t){if(Array.isArray(t))return t}function _g(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(h){c=!0,o=h}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(c)throw o}}return a}}function Eg(){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 wg(t,e){return xg(t)||_g(t,e)||Tg(t,e)||Eg()}function Tg(t,e){if(t){if(typeof t=="string")return xu(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)?xu(t,e):void 0}}var Pu=Object.entries,_u=Object.setPrototypeOf,Sg=Object.isFrozen,Ag=Object.getPrototypeOf,kg=Object.getOwnPropertyDescriptor,we=Object.freeze,Te=Object.seal,On=Object.create,Du=typeof Reflect<"u"&&Reflect,ba=Du.apply,ya=Du.construct;we||(we=function(e){return e});Te||(Te=function(e){return e});ba||(ba=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)});ya||(ya=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 Rn=me(Array.prototype.forEach),Cg=me(Array.prototype.lastIndexOf),Eu=me(Array.prototype.pop),Nn=me(Array.prototype.push),Ig=me(Array.prototype.splice),kt=Array.isArray,ur=me(String.prototype.toLowerCase),ha=me(String.prototype.toString),wu=me(String.prototype.match),lr=me(String.prototype.replace),Tu=me(String.prototype.indexOf),Rg=me(String.prototype.trim),Ng=me(Number.prototype.toString),Og=me(Boolean.prototype.toString),Su=typeof BigInt>"u"?null:me(BigInt.prototype.toString),Au=typeof Symbol>"u"?null:me(Symbol.prototype.toString),ye=me(Object.prototype.hasOwnProperty),cr=me(Object.prototype.toString),be=me(RegExp.prototype.test),tn=Mg(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 ba(t,e,r)}}function Mg(t){return function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return ya(t,n)}}function W(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ur;if(_u&&_u(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&&(Sg(e)||(e[r]=i),o=i)}t[o]=!0}return t}function Lg(t){for(let e=0;e<t.length;e++)ye(t,e)||(t[e]=null);return t}function Ae(t){let e=On(null);for(let r of Pu(t)){var n=wg(r,2);let o=n[0],i=n[1];ye(t,o)&&(kt(i)?e[o]=Lg(i):i&&typeof i=="object"&&i.constructor===Object?e[o]=Ae(i):e[o]=i)}return e}function Pg(t){switch(typeof t){case"string":return t;case"number":return Ng(t);case"boolean":return Og(t);case"bigint":return Su?Su(t):"0";case"symbol":return Au?Au(t):"Symbol()";case"undefined":return cr(t);case"function":case"object":{if(t===null)return cr(t);let e=t,n=Ye(e,"toString");if(typeof n=="function"){let r=n(e);return typeof r=="string"?r:cr(r)}return cr(t)}default:return cr(t)}}function Ye(t,e){for(;t!==null;){let r=kg(t,e);if(r){if(r.get)return me(r.get);if(typeof r.value=="function")return me(r.value)}t=Ag(t)}function n(){return null}return n}function Dg(t){try{return be(t,""),!0}catch{return!1}}var ku=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"]),fa=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"]),ma=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"]),Ug=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"]),ga=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"]),Hg=we(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Cu=we(["#text"]),Iu=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"]),va=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"]),Ru=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"]),hi=we(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),zg=Te(/{{[\w\W]*|^[\w\W]*}}/g),Gg=Te(/<%[\w\W]*|^[\w\W]*%>/g),Fg=Te(/\${[\w\W]*/g),$g=Te(/^data-[\-\w.\u00B7-\uFFFF]+$/),Bg=Te(/^aria-[\-\w]+$/),Nu=Te(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Vg=Te(/^(?:\w+script|data):/i),jg=Te(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),qg=Te(/^html$/i),Wg=Te(/^[a-z][.\w]*(-[.\w]+)+$/i),Ou=Te(/<[/\w!]/g),Mu=Te(/<[/\w]/g),Xg=Te(/<\/no(script|embed|frames)/i),Yg=Te(/\/>/i),He={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Kg=function(){return typeof window>"u"?null:window},Zg=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}},Lu=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 Uu(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Kg(),e=T=>Uu(T);if(e.version="3.4.13",e.removed=[],!t||!t.document||t.document.nodeType!==He.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 h=t.DOMParser,m=t.trustedTypes,y=a.prototype,f=Ye(y,"cloneNode"),p=Ye(y,"remove"),g=Ye(y,"nextSibling"),x=Ye(y,"childNodes"),S=Ye(y,"parentNode"),w=Ye(y,"shadowRoot"),I=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 T=n.createElement("template");T.content&&T.content.ownerDocument&&(n=T.content.ownerDocument)}let re,Ve="",ki,Ga=!1,Dn=0,Fa=function(){if(Dn>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){Fa(),Dn++;try{return re.createHTML(d)}finally{Dn--}},vd=function(d){Fa(),Dn++;try{return re.createScriptURL(d)}finally{Dn--}},bd=function(){return Ga||(ki=Zg(m,o),Ga=!0),ki},xr=n,Ci=xr.implementation,$a=xr.createNodeIterator,yd=xr.createDocumentFragment,xd=xr.getElementsByTagName,_d=r.importNode,oe=Lu();e.isSupported=typeof Pu=="function"&&typeof S=="function"&&Ci&&Ci.createHTMLDocument!==void 0;let Ed=zg,wd=Gg,Td=Fg,Sd=$g,Ad=Bg,kd=Vg,Ba=jg,Cd=Wg,Va=Nu,ie=null,Ii=W({},[...ku,...fa,...ma,...ga,...Cu]),se=null,Ri=W({},[...Iu,...va,...Ru,...hi]),de=Object.seal(On(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}})),Un=null,ja=null,gt=Object.seal(On(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),qa=!0,Ni=!0,Wa=!1,Xa=!0,vt=!1,bt=!0,It=!1,Oi=!1,_r=null,Er=null,Mi=!1,an=!1,wr=!1,Tr=!1,Ya=!0,Ka=!1,Za="user-content-",Li=!0,Sr=!1,ln={},Je=null,Pi=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"]),Ja=null,Qa=W({},["audio","video","img","source","image","track"]),Di=null,el=W({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Ar="http://www.w3.org/1998/Math/MathML",kr="http://www.w3.org/2000/svg",Qe="http://www.w3.org/1999/xhtml",cn=Qe,Ui=!1,Hi=null,Id=W({},[Ar,kr,Qe],ha),tl=we(["mi","mo","mn","ms","mtext"]),zi=W({},tl),nl=we(["annotation-xml"]),Gi=W({},nl),Rd=W({},["title","style","font","a","script"]),Hn=null,Nd=["application/xhtml+xml","text/html"],Od="text/html",le=null,un=null,Md=n.createElement("form"),rl=function(d){return d instanceof RegExp||d instanceof Function},Fi=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),Hn=Nd.indexOf(d.PARSER_MEDIA_TYPE)===-1?Od:d.PARSER_MEDIA_TYPE,le=Hn==="application/xhtml+xml"?ha:ur,ie=At(d,"ALLOWED_TAGS",Ii,{transform:le}),se=At(d,"ALLOWED_ATTR",Ri,{transform:le}),Hi=At(d,"ALLOWED_NAMESPACES",Id,{transform:ha}),Di=At(d,"ADD_URI_SAFE_ATTR",el,{transform:le,base:el}),Ja=At(d,"ADD_DATA_URI_TAGS",Qa,{transform:le,base:Qa}),Je=At(d,"FORBID_CONTENTS",Pi,{transform:le}),Un=At(d,"FORBID_TAGS",Ae({}),{transform:le}),ja=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,qa=d.ALLOW_ARIA_ATTR!==!1,Ni=d.ALLOW_DATA_ATTR!==!1,Wa=d.ALLOW_UNKNOWN_PROTOCOLS||!1,Xa=d.ALLOW_SELF_CLOSE_IN_ATTR!==!1,vt=d.SAFE_FOR_TEMPLATES||!1,bt=d.SAFE_FOR_XML!==!1,It=d.WHOLE_DOCUMENT||!1,an=d.RETURN_DOM||!1,wr=d.RETURN_DOM_FRAGMENT||!1,Tr=d.RETURN_TRUSTED_TYPE||!1,Mi=d.FORCE_BODY||!1,Ya=d.SANITIZE_DOM!==!1,Ka=d.SANITIZE_NAMED_PROPS||!1,Li=d.KEEP_CONTENT!==!1,Sr=d.IN_PLACE||!1,Va=Dg(d.ALLOWED_URI_REGEXP)?d.ALLOWED_URI_REGEXP:Nu,cn=typeof d.NAMESPACE=="string"?d.NAMESPACE:Qe,zi=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({},tl),Gi=ye(d,"HTML_INTEGRATION_POINTS")&&d.HTML_INTEGRATION_POINTS&&typeof d.HTML_INTEGRATION_POINTS=="object"?Ae(d.HTML_INTEGRATION_POINTS):W({},nl);let b=ye(d,"CUSTOM_ELEMENT_HANDLING")&&d.CUSTOM_ELEMENT_HANDLING&&typeof d.CUSTOM_ELEMENT_HANDLING=="object"?Ae(d.CUSTOM_ELEMENT_HANDLING):On(null);if(de=On(null),ye(b,"tagNameCheck")&&rl(b.tagNameCheck)&&(de.tagNameCheck=b.tagNameCheck),ye(b,"attributeNameCheck")&&rl(b.attributeNameCheck)&&(de.attributeNameCheck=b.attributeNameCheck),ye(b,"allowCustomizedBuiltInElements")&&typeof b.allowCustomizedBuiltInElements=="boolean"&&(de.allowCustomizedBuiltInElements=b.allowCustomizedBuiltInElements),Te(de),vt&&(Ni=!1),wr&&(an=!0),ln&&(ie=W({},Cu),se=On(null),ln.html===!0&&(W(ie,ku),W(se,Iu)),ln.svg===!0&&(W(ie,fa),W(se,va),W(se,hi)),ln.svgFilters===!0&&(W(ie,ma),W(se,va),W(se,hi)),ln.mathMl===!0&&(W(ie,ga),W(se,Ru),W(se,hi))),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===Ii&&(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===Ri&&(se=Ae(se)),W(se,d.ADD_ATTR,le))),ye(d,"ADD_URI_SAFE_ATTR")&&kt(d.ADD_URI_SAFE_ATTR)&&W(Di,d.ADD_URI_SAFE_ATTR,le),ye(d,"FORBID_CONTENTS")&&kt(d.FORBID_CONTENTS)&&(Je===Pi&&(Je=Ae(Je)),W(Je,d.FORBID_CONTENTS,le)),ye(d,"ADD_FORBID_CONTENTS")&&kt(d.ADD_FORBID_CONTENTS)&&(Je===Pi&&(Je=Ae(Je)),W(Je,d.ADD_FORBID_CONTENTS,le)),Li&&(ie["#text"]=!0),It&&W(ie,["html","head","body"]),ie.table&&(W(ie,["tbody"]),delete Un.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 _=re;re=d.TRUSTED_TYPES_POLICY;try{Ve=sn("")}catch(N){throw re=_,N}}else d.TRUSTED_TYPES_POLICY===null?(re=void 0,Ve=""):(re===void 0&&(re=bd()),re&&typeof Ve=="string"&&(Ve=sn("")));we&&we(d),un=d},ol=W({},[...fa,...ma,...Ug]),il=W({},[...ga,...Hg]),Ld=function(d,b,_){return b.namespaceURI===Qe?d==="svg":b.namespaceURI===Ar?d==="svg"&&(_==="annotation-xml"||zi[_]):!!ol[d]},Pd=function(d,b,_){return b.namespaceURI===Qe?d==="math":b.namespaceURI===kr?d==="math"&&Gi[_]:!!il[d]},Dd=function(d,b,_){return b.namespaceURI===kr&&!Gi[_]||b.namespaceURI===Ar&&!zi[_]?!1:!il[d]&&(Rd[d]||!ol[d])},Ud=function(d){let b=S(d);(!b||!b.tagName)&&(b={namespaceURI:cn,tagName:"template"});let _=ur(d.tagName),N=ur(b.tagName);return Hi[d.namespaceURI]?d.namespaceURI===kr?Ld(_,b,N):d.namespaceURI===Ar?Pd(_,b,N):d.namespaceURI===Qe?Dd(_,b,N):!!(Hn==="application/xhtml+xml"&&Hi[d.namespaceURI]):!1},yt=function(d){Nn(e.removed,{element:d});try{S(d).removeChild(d)}catch{if(p(d),!S(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")}},Cr=function(d){zn(d);let b=x(d);if(b){let N=[];Rn(b,L=>{Nn(N,L)}),Rn(N,L=>{try{p(L)}catch{}})}let _=I(d);if(_)for(let N=_.length-1;N>=0;--N){let L=_[N],z=L&&L.name;if(typeof z=="string")try{d.removeAttribute(z)}catch{}}},Rt=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||wr)try{yt(b)}catch{}else try{b.setAttribute(d,"")}catch{}},Hd=function(d){let b=I(d);if(b)for(let _=b.length-1;_>=0;--_){let N=b[_],L=N&&N.name;if(!(typeof L!="string"||se[le(L)]))try{d.removeAttribute(L)}catch{}}},zn=function(d){let b=[d];for(;b.length>0;){let _=b.pop();(H?H(_):_.nodeType)===He.element&&Hd(_);let L=x(_);if(L)for(let z=L.length-1;z>=0;--z)b.push(L[z])}},zd=function(d){if(!bt)return;let b=[d];for(;b.length>0;){let _=b.pop(),N=H?H(_):_.nodeType;if(N===He.processingInstruction||N===He.comment&&be(Mu,_.data)){try{p(_)}catch{}continue}if(N===He.element){let z=_,Z=le(U?U(_):_.nodeName);try{z.hasAttribute&&z.hasAttribute("patchsrc")&&z.removeAttribute("patchsrc"),z.hasAttribute&&z.hasAttribute("for")&&Z!=="label"&&Z!=="output"&&z.removeAttribute("for")}catch{}}let L=x(_);if(L)for(let z=L.length-1;z>=0;--z)b.push(L[z])}},sl=function(d){let b=null,_=null;if(Mi)d="<remove></remove>"+d;else{let z=wu(d,/^[\r\n\t ]+/);_=z&&z[0]}Hn==="application/xhtml+xml"&&cn===Qe&&(d='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+d+"</body></html>");let N=re?sn(d):d;if(cn===Qe)try{b=new h().parseFromString(N,Hn)}catch{}if(!b||!b.documentElement){b=Ci.createDocument(cn,"template",null);try{b.documentElement.innerHTML=Ui?Ve:N}catch{}}let L=b.body||b.documentElement;return d&&_&&L.insertBefore(n.createTextNode(_),L.childNodes[0]||null),cn===Qe?xd.call(b,It?"html":"body")[0]:It?b.documentElement:L},al=function(d){let b=Y?Y(d):d.ownerDocument;return $a.call(b||d,d,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Ir=function(d){return d=lr(d,Ed," "),d=lr(d,wd," "),d=lr(d,Td," "),d},$i=function(d){var b;d.normalize();let _=Y?Y(d):d.ownerDocument,N=$a.call(_||d,d,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),L=N.nextNode();for(;L;)L.data=Ir(L.data),L=N.nextNode();let z=(b=d.querySelectorAll)===null||b===void 0?void 0:b.call(d,"template");z&&Rn(z,Z=>{dn(Z.content)&&$i(Z.content)})},Rr=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!==I(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)===He.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(T,d,b){T.length!==0&&Rn(T,_=>{_.call(e,d,b,un)})}let Gd=function(d,b){return!!(bt&&d.hasChildNodes()&&!Gn(d.firstElementChild)&&be(Ou,d.textContent)&&be(Ou,d.innerHTML)||bt&&d.namespaceURI===Qe&&b==="style"&&Gn(d.firstElementChild)||d.nodeType===He.processingInstruction||bt&&d.nodeType===He.comment&&be(Mu,d.data))},Fd=function(d,b,_){if(!Un[b]&&dl(b)&&(de.tagNameCheck instanceof RegExp&&be(de.tagNameCheck,b)||de.tagNameCheck instanceof Function&&de.tagNameCheck(b)))return!1;if(Li&&!Je[b]){let N=S(d),L=x(d);if(L&&N){let z=L.length;for(let Z=z-1;Z>=0;--Z){let ce=d===_?f(L[Z],!0):L[Z];N.insertBefore(ce,g(d))}}}return yt(d),!0},ll=function(d,b,_,N){return d.length===0?b:b===_||b===N?Ae(b):b},cl=function(d,b){if(et(oe.beforeSanitizeElements,d,null),d!==b&&S(d)===null)return Sr&&zn(d),!0;if(Rr(d))return yt(d),!0;let _=le(U?U(d):d.nodeName);if(ie=ll(oe.uponSanitizeElement,ie,Ii,_r),et(oe.uponSanitizeElement,d,{tagName:_,allowedTags:ie}),d!==b&&S(d)===null)return Sr&&zn(d),!0;if(Gd(d,_))return yt(d),!0;if(Un[_]||!(gt.tagCheck instanceof Function&>.tagCheck(_))&&!ie[_]){let L=Fd(d,_,b);return L===!1&&et(oe.afterSanitizeElements,d,null),L}if((H?H(d):d.nodeType)===He.element&&!Ud(d)||(_==="noscript"||_==="noembed"||_==="noframes")&&be(Xg,d.innerHTML))return yt(d),!0;if(vt&&d.nodeType===He.text){let L=Ir(d.textContent);d.textContent!==L&&(Nn(e.removed,{element:d.cloneNode()}),d.textContent=L)}return et(oe.afterSanitizeElements,d,null),!1},ul=function(d,b,_){if(ja[b]||bt&&b==="patchsrc"||bt&&b==="for"&&d!=="label"&&d!=="output"||Ya&&(b==="id"||b==="name")&&(_ in n||_ in Md))return!1;let N=se[b]||gt.attributeCheck instanceof Function&>.attributeCheck(b,d);if(!(Ni&&be(Sd,b))){if(!(qa&&be(Ad,b))){if(N){if(!Di[b]){if(!be(Va,lr(_,Ba,""))){if(!((b==="src"||b==="xlink:href"||b==="href")&&d!=="script"&&Tu(_,"data:")===0&&Ja[d])){if(!(Wa&&!be(kd,lr(_,Ba,"")))){if(_)return!1}}}}}else if(!(dl(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,_)||de.tagNameCheck instanceof Function&&de.tagNameCheck(_))))return!1}}return!0},$d=W({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),dl=function(d){return!$d[ur(d)]&&be(Cd,d)},Bd=function(d,b,_,N){if(re&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!_)switch(m.getAttributeType(d,b)){case"TrustedHTML":return sn(N);case"TrustedScriptURL":return vd(N)}return N},Vd=function(d,b,_,N){try{_?d.setAttributeNS(_,b,N):d.setAttribute(b,N),Rr(d)?yt(d):Eu(e.removed)}catch{Rt(b,d)}},pl=function(d){et(oe.beforeSanitizeAttributes,d,null);let b=d.attributes;if(!b||Rr(d))return;se=ll(oe.uponSanitizeAttribute,se,Ri,Er);let _={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:se,forceKeepAttr:void 0},N=b.length,L=le(d.nodeName);for(;N--;){let z=b[N],Z=z.name,ce=z.namespaceURI,Ie=z.value,Re=le(Z),Vi=Ie,Ce=Z==="value"?Vi:Rg(Vi);if(_.attrName=Re,_.attrValue=Ce,_.keepAttr=!0,_.forceKeepAttr=void 0,et(oe.uponSanitizeAttribute,d,_),Ce=_.attrValue,Ka&&(Re==="id"||Re==="name")&&Tu(Ce,Za)!==0&&(Rt(Z,d),Ce=Za+Ce),bt&&be(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Ce)){Rt(Z,d);continue}if(Re==="attributename"&&wu(Ce,"href")){Rt(Z,d);continue}if(!_.forceKeepAttr){if(!_.keepAttr){Rt(Z,d);continue}if(!Xa&&be(Yg,Ce)){Rt(Z,d);continue}if(vt&&(Ce=Ir(Ce)),!ul(L,Re,Ce)){Rt(Z,d);continue}Ce=Bd(L,Re,ce,Ce),Ce!==Vi&&Vd(d,Z,ce,Ce)}}et(oe.afterSanitizeAttributes,d,null)},Nr=function(d){let b=null,_=al(d);for(et(oe.beforeSanitizeShadowDOM,d,null);b=_.nextNode();)if(et(oe.uponSanitizeShadowNode,b,null),cl(b,d),pl(b),dn(b.content)&&Nr(b.content),(H?H(b):b.nodeType)===He.element){let L=w(b);dn(L)&&(Bi(L),Nr(L))}et(oe.afterSanitizeShadowDOM,d,null)},Bi=function(d){let b=[{node:d,shadow:null}];for(;b.length>0;){let _=b.pop();if(_.shadow){Nr(_.shadow);continue}let N=_.node,z=(H?H(N):N.nodeType)===He.element,Z=x(N);if(Z)for(let ce=Z.length-1;ce>=0;--ce)b.push({node:Z[ce],shadow:null});if(z){let ce=U?U(N):null;if(typeof ce=="string"&&le(ce)==="template"){let Ie=N.content;dn(Ie)&&b.push({node:Ie,shadow:null})}}if(z){let ce=w(N);dn(ce)&&b.push({node:null,shadow:ce},{node:ce,shadow:null})}}};return e.sanitize=function(T){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},b=null,_=null,N=null,L=null;if(Ui=!T,Ui&&(T="<!-->"),typeof T!="string"&&!Gn(T)&&(T=Pg(T),typeof T!="string"))throw tn("dirty is not a string, aborting");if(!e.isSupported)return T;Oi?(ie=_r,se=Er):Fi(d),(oe.uponSanitizeElement.length>0||oe.uponSanitizeAttribute.length>0)&&(ie=Ae(ie)),oe.uponSanitizeAttribute.length>0&&(se=Ae(se)),e.removed=[];let z=Sr&&typeof T!="string"&&Gn(T);if(z){zd(T);let Ie=U?U(T):T.nodeName;if(typeof Ie=="string"){let Re=le(Ie);if(!ie[Re]||Un[Re])throw Cr(T),tn("root node is forbidden and cannot be sanitized in-place")}if(Rr(T))throw Cr(T),tn("root node is clobbered and cannot be sanitized in-place");try{Bi(T)}catch(Re){throw Cr(T),Re}}else if(Gn(T))b=sl("<!---->"),_=b.ownerDocument.importNode(T,!0),_.nodeType===He.element&&_.nodeName==="BODY"||_.nodeName==="HTML"?b=_:b.appendChild(_),Bi(_);else{if(!an&&!vt&&!It&&T.indexOf("<")===-1)return re&&Tr?sn(T):T;if(b=sl(T),!b)return an?null:Tr?Ve:""}b&&Mi&&yt(b.firstChild);let Z=z?T:b;try{let Ie=al(Z);for(;N=Ie.nextNode();)cl(N,Z),pl(N),dn(N.content)&&Nr(N.content)}catch(Ie){throw z&&(Cr(T),Rn(e.removed,Re=>{Re.element&&zn(Re.element)})),Ie}if(z)return Rn(e.removed,Ie=>{Ie.element&&zn(Ie.element)}),vt&&$i(T),T;if(an){if(vt&&$i(b),wr)for(L=yd.call(b.ownerDocument);b.firstChild;)L.appendChild(b.firstChild);else L=b;return(se.shadowroot||se.shadowrootmode)&&(L=_d.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(qg,b.ownerDocument.doctype.name)&&(ce="<!DOCTYPE "+b.ownerDocument.doctype.name+`>
|
|
13
|
+
`+ce),vt&&(ce=Ir(ce)),re&&Tr?sn(ce):ce},e.setConfig=function(){let T=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Fi(T),Oi=!0,_r=ie,Er=se},e.clearConfig=function(){un=null,Oi=!1,_r=null,Er=null,re=ki,Ve=""},e.isValidAttribute=function(T,d,b){un||Fi({});let _=le(T),N=le(d);return ul(_,N,b)},e.addHook=function(T,d){typeof d=="function"&&ye(oe,T)&&Nn(oe[T],d)},e.removeHook=function(T,d){if(ye(oe,T)){if(d!==void 0){let b=Cg(oe[T],d);return b===-1?void 0:Ig(oe[T],b,1)[0]}return Eu(oe[T])}},e.removeHooks=function(T){ye(oe,T)&&(oe[T]=[])},e.removeAllHooks=function(){oe=Lu()},e}var Hu=Uu();function wa(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var on=wa();function qu(t){on=t}var nn={exec:()=>null};function Mn(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 Jg=((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:Mn(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Mn(t=>new RegExp(`^ {0,${t}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Mn(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:Mn(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:Mn(t=>new RegExp(`^ {0,${t}}<(?:[a-z].*>|!--)`,"i")),blockquoteBeginRegex:Mn(t=>new RegExp(`^ {0,${t}}>`))},Qg=/^(?:[ \t]*(?:\n|$))+/,ev=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,tv=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hr=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,nv=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ta=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Wu=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Xu=j(Wu).replace(/bull/g,Ta).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(),rv=j(Wu).replace(/bull/g,Ta).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(),Sa=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,ov=/^[^\n]+/,Aa=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,iv=j(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",Aa).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),sv=j(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ta).getRegex(),bi="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",ka=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,av=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",ka).replace("tag",bi).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Yu=t=>j(Sa).replace("hr",hr).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",bi).getRegex(),lv=Yu(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),cv=Yu(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),uv=j(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",cv).getRegex(),Ca={blockquote:uv,code:ev,def:iv,fences:tv,heading:nv,hr,html:av,lheading:Xu,list:sv,newline:Qg,paragraph:lv,table:nn,text:ov},zu=j("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",hr).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",bi).getRegex(),dv={...Ca,lheading:rv,table:zu,paragraph:j(Sa).replace("hr",hr).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",zu).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",bi).getRegex()},pv={...Ca,html:j(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ka).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(Sa).replace("hr",hr).replace("heading",` *#{1,6} *[^
|
|
14
|
+
]`).replace("lheading",Xu).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},hv=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,fv=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Ku=/^( {2,}|\\)\n(?!\s*$)/,mv=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ft=/[\p{P}\p{S}]/u,Ln=/[\s\p{P}\p{S}]/u,fr=/[^\s\p{P}\p{S}]/u,gv=j(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Ln).getRegex(),vv=/[\p{Pi}\p{Ps}"']/u,Zu=/(?!~)[\p{P}\p{S}]/u,bv=/(?!~)[\s\p{P}\p{S}]/u,yv=/(?:[^\s\p{P}\p{S}]|~)/u,xv=j(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Jg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ju=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,_v=j(Ju,"u").replace(/punct/g,ft).getRegex(),Ev=j(Ju,"u").replace(/punct/g,Zu).getRegex(),wv=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,Tv=j(wv,"u").replace(/openQuote/g,vv).replace(/punct/g,ft).getRegex(),Qu="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Sv=j(Qu,"gu").replace(/notPunctSpace/g,fr).replace(/punctSpace/g,Ln).replace(/punct/g,ft).getRegex(),Av=j(Qu,"gu").replace(/notPunctSpace/g,yv).replace(/punctSpace/g,bv).replace(/punct/g,Zu).getRegex(),kv="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Cv=j(kv,"gu").replace(/notPunctSpace/g,fr).replace(/punctSpace/g,Ln).replace(/punct/g,ft).getRegex(),Iv=j("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,fr).replace(/punctSpace/g,Ln).replace(/punct/g,ft).getRegex(),Rv="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",Nv=j(Rv,"gu").replace(/notPunctSpace/g,fr).replace(/punctSpace/g,Ln).replace(/punct/g,ft).getRegex(),Ov=j(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,ft).getRegex(),Mv="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Lv=j(Mv,"gu").replace(/notPunctSpace/g,fr).replace(/punctSpace/g,Ln).replace(/punct/g,ft).getRegex(),Pv=j(/\\(punct)/,"gu").replace(/punct/g,ft).getRegex(),Dv=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(),Uv=j(ka).replace("(?:-->|$)","-->").getRegex(),Hv=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",Uv).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),mi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,zv=j(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",mi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ed=j(/^!?\[(label)\]\[(ref)\]/).replace("label",mi).replace("ref",Aa).getRegex(),td=j(/^!?\[(ref)\](?:\[\])?/).replace("ref",Aa).getRegex(),Gv=j("reflink|nolink(?!\\()","g").replace("reflink",ed).replace("nolink",td).getRegex(),Gu=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ia={_backpedal:nn,anyPunctuation:Pv,autolink:Dv,blockSkip:xv,br:Ku,code:fv,del:nn,delLDelim:nn,delRDelim:nn,emStrongLDelim:_v,emStrongRDelimAst:Sv,emStrongRDelimUnd:Iv,escape:hv,link:zv,nolink:td,punctuation:gv,reflink:ed,reflinkSearch:Gv,tag:Hv,text:mv,url:nn},Fv={...Ia,emStrongLDelim:Tv,emStrongRDelimAst:Cv,emStrongRDelimUnd:Nv,link:j(/^!?\[(label)\]\((.*?)\)/).replace("label",mi).getRegex(),reflink:j(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",mi).getRegex()},xa={...Ia,emStrongRDelimAst:Av,emStrongLDelim:Ev,delLDelim:Ov,delRDelim:Lv,url:j(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Gu).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",Gu).getRegex()},$v={...xa,br:j(Ku).replace("{2,}","*").getRegex(),text:j(xa.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},fi={normal:Ca,gfm:dv,pedantic:pv},dr={normal:Ia,gfm:xa,breaks:$v,pedantic:Fv},Bv={"&":"&","<":"<",">":">",'"':""","'":"'"},Fu=t=>Bv[t];function at(t,e){if(e){if(ke.escapeTest.test(t))return t.replace(ke.escapeReplace,Fu)}else if(ke.escapeTestNoEncode.test(t))return t.replace(ke.escapeReplaceNoEncode,Fu);return t}function $u(t){try{t=encodeURI(t).replace(ke.percentDecode,"%")}catch{return null}return t}function Bu(t,e){let n=t.replace(ke.findPipe,(i,s,a)=>{let l=!1,c=s;for(;--c>=0&&a[c]==="\\";)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 Ct(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 Vu(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
16
|
`)}function Vv(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 jv(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 ju(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 qv(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 gi=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]:Vu(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=qv(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=
|
|
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 gi=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]:Vu(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=qv(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=Ct(n,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(n=r.trim())}return{type:"heading",raw:Ct(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:Ct(e[0],`
|
|
20
|
+
`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let n=Ct(e[0],`
|
|
21
21
|
`).split(`
|
|
22
22
|
`),r="",o="",i=[];for(;n.length>0;){let s=!1,a=[],l;for(l=0;l<n.length;l++)if(this.rules.other.blockquoteStart.test(n[l]))a.push(n[l]),s=!0;else if(!s)a.push(n[l]);else break;n=n.slice(l);let c=a.join(`
|
|
23
23
|
`),h=c.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -32,16 +32,16 @@ ${p}`,o=o.substring(0,o.length-f.text.length)+x.text;break}else if(y?.type==="li
|
|
|
32
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,c="",h="";if(!(e=i.exec(t))||this.rules.block.hr.test(t))break;c=e[0],t=t.substring(c.length);let m=jv(e[2].split(`
|
|
33
33
|
`,1)[0],e[1].length),y=t.split(`
|
|
34
34
|
`,1)[0],f=!m.trim(),p=0;if(this.options.pedantic?(p=2,h=m.trimStart()):f?p=e[1].length+1:(p=m.search(this.rules.other.nonSpaceChar),p=p>4?1:p,h=m.slice(p),p+=e[1].length),f&&this.rules.other.blankLine.test(y)&&(c+=y+`
|
|
35
|
-
`,t=t.substring(y.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(p),x=this.rules.other.hrRegex(p),S=this.rules.other.fencesBeginRegex(p),w=this.rules.other.headingBeginRegex(p),
|
|
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," "),S.test(y)||w.test(y)||
|
|
35
|
+
`,t=t.substring(y.length+1),l=!0),!l){let g=this.rules.other.nextBulletRegex(p),x=this.rules.other.hrRegex(p),S=this.rules.other.fencesBeginRegex(p),w=this.rules.other.headingBeginRegex(p),I=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," "),S.test(y)||w.test(y)||I.test(y)||H.test(y)||g.test(y)||x.test(y))break;if(Y.search(this.rules.other.nonSpaceChar)>=p||!y.trim())h+=`
|
|
37
37
|
`+Y.slice(p);else{if(f||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||S.test(m)||w.test(m)||x.test(m))break;h+=`
|
|
38
38
|
`+y}f=!y.trim(),c+=U+`
|
|
39
|
-
`,t=t.substring(U.length+1),m=Y.slice(p)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let h=this.rules.other.listTaskCheckbox.exec(l.raw);if(h){let m={type:"checkbox",raw:h[0]+" ",checked:h[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 h=l.tokens.filter(y=>y.type==="space"),m=h.length>0&&h.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 c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=Vu(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:
|
|
39
|
+
`,t=t.substring(U.length+1),m=Y.slice(p)}}o.loose||(s?o.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(s=!0)),o.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(h),loose:!1,text:h,tokens:[]}),o.raw+=c}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let l of o.items){this.lexer.state.top=!1,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&(c?.type==="text"||c?.type==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let m=this.lexer.inlineQueue.length-1;m>=0;m--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[m].src)){this.lexer.inlineQueue[m].src=this.lexer.inlineQueue[m].src.replace(this.rules.other.listReplaceTask,"");break}let h=this.rules.other.listTaskCheckbox.exec(l.raw);if(h){let m={type:"checkbox",raw:h[0]+" ",checked:h[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 h=l.tokens.filter(y=>y.type==="space"),m=h.length>0&&h.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 c of l.tokens)c.type==="text"&&(c.type="paragraph")}return o}}html(t){let e=this.rules.block.html.exec(t);if(e){let n=Vu(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:Ct(e[0],`
|
|
40
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=Bu(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:
|
|
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(Bu(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:
|
|
41
|
+
`):[],i={type:"table",raw:Ct(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(Bu(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:Ct(e[0],`
|
|
43
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)===`
|
|
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=
|
|
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=Ct(n.slice(0,-1),"\\");if((n.length-i.length)%2===0)return}else{let i=Vv(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)),ju(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 ju(n,o,n[0],this.lexer,this.rules)}}emStrong(t,e,n=""){let r=this.rules.inline.emStrongLDelim.exec(t);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let o=[...r[0]].length-1,i,s,a=o,l=0,c=r[0][0],h=n===c,m=c==="*"?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(h)break}if(a-=s,a>0)continue;s=Math.min(s,s+a+l);let y=[...r[0]][0].length,f=t.slice(0,o+r.index+y+s);if(Math.min(o,s)%2){let g=f.slice(1,-1);return{type:"em",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}let p=f.slice(2,-2);return{type:"strong",raw:f,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 c=[...r[0]][0].length,h=t.slice(0,o+r.index+c+s),m=h.slice(o,-o);return{type:"del",raw:h,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 _a{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 gi,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:fi.normal,inline:dr.normal};this.options.pedantic?(n.block=fi.pedantic,n.inline=dr.pedantic):this.options.gfm&&(n.block=fi.gfm,this.options.breaks?n.inline=dr.breaks:n.inline=dr.gfm),this.tokenizer.rules=n}static get rules(){return{block:fi,inline:dr}}static lex(e,n){return new _a(n).lex(e)}static lexInline(e,n){return new _a(n).inlineTokens(e)}lex(e){e=e.replace(ke.carriageReturn,`
|
|
45
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+=`
|
|
46
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(`
|
|
47
47
|
`)?"":`
|
|
@@ -74,18 +74,17 @@ ${this.parser.parse(t)}</blockquote>
|
|
|
74
74
|
${t}</tr>
|
|
75
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}>
|
|
76
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)}},Ra=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 Ea{options;renderer;textRenderer;constructor(e){this.options=e||on,this.options.renderer=this.options.renderer||new vi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ra}static parse(e,n){return new Ea(n).parse(e)}static parseInline(e,n){return new Ea(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}},pr=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}},Na=class{defaults=wa();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Ze;Renderer=vi;TextRenderer=Ra;Lexer=Ke;Tokenizer=gi;Hooks=pr;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 vi(this.defaults);for(let i in n.renderer){if(!(i in o))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let s=i,a=n.renderer[s],l=o[s];o[s]=(...c)=>{let h=a.apply(o,c);return h===!1&&(h=l.apply(o,c)),h||""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new gi(this.defaults);for(let i in n.tokenizer){if(!(i in o))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let s=i,a=n.tokenizer[s],l=o[s];o[s]=(...c)=>{let h=a.apply(o,c);return h===!1&&(h=l.apply(o,c)),h}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new pr;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];pr.passThroughHooks.has(i)?o[s]=c=>{if(this.defaults.async&&pr.passThroughHooksRespectAsync.has(i))return(async()=>{let m=await a.call(o,c);return l.call(o,m)})();let h=a.call(o,c);return l.call(o,h)}:o[s]=(...c)=>{if(this.defaults.async)return(async()=>{let m=await a.apply(o,c);return m===!1&&(m=await l.apply(o,c)),m})();let h=a.apply(o,c);return h===!1&&(h=l.apply(o,c)),h}}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 c=await(o.hooks?await o.hooks.provideParser(t):t?Ze.parse:Ze.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(i);try{o.hooks&&(e=o.hooks.preprocess(e));let s=(o.hooks?o.hooks.provideLexer(t):t?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 Na;function J(t,e){return rn.parse(t,e)}J.options=J.setOptions=function(t){return rn.setOptions(t),J.defaults=rn.defaults,qu(J.defaults),J};J.getDefaults=wa;J.defaults=on;function Wv(...t){return rn.use(...t),J.defaults=rn.defaults,qu(J.defaults),J}J.use=Wv;J.walkTokens=function(t,e){return rn.walkTokens(t,e)};J.parseInline=rn.parseInline;J.Parser=Ze;J.parser=Ze.parse;J.Renderer=vi;J.TextRenderer=Ra;J.Lexer=Ke;J.lexer=Ke.lex;J.Tokenizer=gi;J.Hooks=pr;J.parse=J;var
|
|
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 Na;function J(t,e){return rn.parse(t,e)}J.options=J.setOptions=function(t){return rn.setOptions(t),J.defaults=rn.defaults,qu(J.defaults),J};J.getDefaults=wa;J.defaults=on;function Wv(...t){return rn.use(...t),J.defaults=rn.defaults,qu(J.defaults),J}J.use=Wv;J.walkTokens=function(t,e){return rn.walkTokens(t,e)};J.parseInline=rn.parseInline;J.Parser=Ze;J.parser=Ze.parse;J.Renderer=vi;J.TextRenderer=Ra;J.Lexer=Ke;J.lexer=Ke.lex;J.Tokenizer=gi;J.Hooks=pr;J.parse=J;var XT=J.options,YT=J.setOptions,KT=J.walkTokens,ZT=J.parseInline;var JT=Ze.parse,QT=Ke.lex;var Xv=new Na({gfm:!0,breaks:!0}),nd=["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"],rd=["href","title","class"],Yv=[...nd,"img"],Kv=[...rd,"src","alt","width","height"];function yi(t,e){let n=e?.allowImages===!0,r=Xv.parse(t,{async:!1}),o=Hu.sanitize(r,{ALLOWED_TAGS:n?Yv:nd,ALLOWED_ATTR:n?Kv:rd}),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 od(t){let e=document.createElement("div");e.className="resize-handle",e.setAttribute("part","resize-handle"),e.setAttribute("role","separator"),e.setAttribute("aria-label",t.label),e.tabIndex=0;let n=(r,o,i,s,a)=>{let l=o.x==="right"?i.right-s:s-i.left,c={width:Math.max(280,l)};if(r!=="both")return c;let h=o.y==="bottom"?i.bottom-a:a-i.top;return{...c,height:Math.max(240,h)}};return e.addEventListener("pointerdown",r=>{let o=t.axis();if(o==="none")return;let i=t.anchor(),s=t.rect(),a=c=>{t.apply(n(o,i,s,c.clientX,c.clientY))},l=c=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",l),e.removeAttribute("data-dragging"),t.commit(n(o,i,s,c.clientX,c.clientY))};e.setAttribute("data-dragging","true"),window.addEventListener("pointermove",a),window.addEventListener("pointerup",l),r.preventDefault()}),e.addEventListener("keydown",r=>{let o=t.axis();if(o==="none")return;let i=t.anchor(),s=t.rect(),a=r.shiftKey?64:16,l=i.x==="right"?-1:1,c=s.right-s.left,h=s.bottom-s.top,m=null;if(r.key==="ArrowLeft")m={width:Math.max(280,c-a*l)};else if(r.key==="ArrowRight")m={width:Math.max(280,c+a*l)};else if(o==="both"&&(r.key==="ArrowUp"||r.key==="ArrowDown")){let y=r.key===(i.y==="bottom"?"ArrowUp":"ArrowDown");m={height:Math.max(240,h+(y?a:-a))}}m!==null&&(r.preventDefault(),t.apply(m),t.commit(m))}),e}function id(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):id(n,e)}function sd(t){let e=[];id(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 ad(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 xi=class{chips;palette;#n;#e=[];#t=!1;#s=!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.#s=e}isOpen(){return!this.palette.hidden}onInput(e){this.#s&&e.startsWith("/")?this.#i(e.slice(1)):this.close()}onKeydown(e){return this.isOpen()?e.key==="ArrowDown"?(this.#o(1),!0):e.key==="ArrowUp"?(this.#o(-1),!0):e.key==="Escape"?(this.close(),!0):e.key==="Enter"?(this.#r.slice(this.#a,this.#a+1).forEach(n=>{this.#l(n)}),!0):!1:!1}close(){this.palette.hidden=!0,this.palette.replaceChildren()}#i(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.#d(),this.palette.hidden=!1}#o(e){let n=this.#r.length;this.#a=(this.#a+e+n)%n,this.#d()}#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.title=`/${n.name}`,r.addEventListener("click",()=>this.#l(n)),this.chips.appendChild(r)}}#d(){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");o.className="skill-item-title",o.setAttribute("part","skill-item-title");let i=document.createElement("code");if(i.className="skill-item-token",i.setAttribute("part","skill-item-token"),i.textContent=`/${e.name}`,o.append(i,document.createTextNode(` ${e.title}`)),r.appendChild(o),e.description!==void 0){let s=document.createElement("span");s.className="skill-item-desc",s.setAttribute("part","skill-item-desc"),s.textContent=e.description,r.appendChild(s)}r.addEventListener("click",()=>this.#l(e)),this.palette.appendChild(r)})}};var ld=`
|
|
78
78
|
/* \u2500\u2500 Token defaults \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
79
79
|
Every public --ag-ui-* token is read here into a private --_* alias, and
|
|
80
80
|
only the alias is used by the rules below.
|
|
81
81
|
|
|
82
82
|
The indirection is what makes ancestor theming work. Declaring the public
|
|
83
|
-
name on :host would set it
|
|
84
|
-
always beats one inherited from an ancestor
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
inherited normally while a value aimed at the element still wins over it.
|
|
83
|
+
name on :host would set it on the host element, and a value on an element
|
|
84
|
+
always beats one inherited from an ancestor, so tokens put on a wrapper
|
|
85
|
+
would have no effect. Reading the public name with the default as a var()
|
|
86
|
+
fallback leaves it undeclared on the element, so an ancestor's value
|
|
87
|
+
inherits normally while one aimed at the element still wins.
|
|
89
88
|
|
|
90
89
|
Two invariants hold this together:
|
|
91
90
|
1. No rule outside this file's :host blocks may reference a public name
|
|
@@ -112,11 +111,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
112
111
|
--_border: var(--ag-ui-border, #e2e2ec);
|
|
113
112
|
--_radius: var(--ag-ui-radius, 12px);
|
|
114
113
|
|
|
115
|
-
/* Body text and raised chrome
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
transparent box. The defaults below restate exactly that, so this is a
|
|
119
|
-
rename with no repaint \u2014 see the note on .code-copy. */
|
|
114
|
+
/* Body text and raised chrome, read only by the code-block copy button.
|
|
115
|
+
The defaults restate what it inherits, so a host that sets neither sees
|
|
116
|
+
no repaint \u2014 see the note on .code-copy. */
|
|
120
117
|
--_text: var(--ag-ui-text, var(--_fg));
|
|
121
118
|
--_surface: var(--ag-ui-surface, transparent);
|
|
122
119
|
|
|
@@ -169,9 +166,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
169
166
|
--_launcher-inset: var(--ag-ui-launcher-inset, auto 0 0 auto);
|
|
170
167
|
|
|
171
168
|
/* Motion. One duration and two curves drive every collapse, expand and
|
|
172
|
-
slide-over, so the
|
|
173
|
-
|
|
174
|
-
|
|
169
|
+
slide-over, so the widget accelerates and settles as one thing. The
|
|
170
|
+
default curve decelerates into place; the pop curve overshoots slightly,
|
|
171
|
+
for something arriving. */
|
|
175
172
|
--_motion: var(--ag-ui-motion, 0.28s);
|
|
176
173
|
--_ease: var(--ag-ui-ease, cubic-bezier(0.32, 0.72, 0, 1));
|
|
177
174
|
--_ease-pop: var(--ag-ui-ease-pop, cubic-bezier(0.34, 1.36, 0.64, 1));
|
|
@@ -195,7 +192,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
195
192
|
/* Reading-column width for placement="page" (full-bleed, centred content). */
|
|
196
193
|
--_content-max-width: var(--ag-ui-content-max-width, 820px);
|
|
197
194
|
/* Slim rail the sidebar placement collapses to. Only that placement reads
|
|
198
|
-
it, but it is declared here so
|
|
195
|
+
it, but it is declared here so every alias has a default in one place. */
|
|
199
196
|
--_rail-width: var(--ag-ui-rail-width, 52px);
|
|
200
197
|
|
|
201
198
|
position: var(--_position);
|
|
@@ -287,11 +284,11 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
287
284
|
--_radius: var(--ag-ui-radius, 0);
|
|
288
285
|
}
|
|
289
286
|
|
|
290
|
-
/* Page: full-bleed background with a centred reading column
|
|
291
|
-
"full"
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
287
|
+
/* Page: full-bleed background with a centred reading column capped at
|
|
288
|
+
--ag-ui-content-max-width, where "full" is edge-to-edge and left-aligned.
|
|
289
|
+
The column comes from symmetric auto padding on the scroll area and
|
|
290
|
+
composer rather than a per-row wrapper, so user pills still right-align and
|
|
291
|
+
the assistant well spans the column. */
|
|
295
292
|
:host([placement="page"]) {
|
|
296
293
|
--_inset: var(--ag-ui-inset, 0);
|
|
297
294
|
--_width: var(--ag-ui-width, 100vw);
|
|
@@ -309,9 +306,8 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
309
306
|
padding-inline: max(12px, calc((100% - var(--_content-max-width)) / 2));
|
|
310
307
|
}
|
|
311
308
|
|
|
312
|
-
/* The rows between the message list and the composer
|
|
313
|
-
|
|
314
|
-
with the column too \u2014 chips are padding-based, the palette/hint/tray are
|
|
309
|
+
/* The rows between the message list and the composer line up with the column
|
|
310
|
+
too. Chips and tray are padding-based while palette and hint are
|
|
315
311
|
margin-based, so each gets its own inline axis nudged by the same gutter. */
|
|
316
312
|
:host([placement="page"]) .skill-chips,
|
|
317
313
|
:host([placement="page"]) .attachment-tray {
|
|
@@ -420,13 +416,12 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
420
416
|
visibility var(--_motion) var(--_ease);
|
|
421
417
|
}
|
|
422
418
|
|
|
423
|
-
/* The launcher grows out of the corner the panel shrank into.
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
must stay reachable. */
|
|
419
|
+
/* The launcher grows out of the corner the panel shrank into. It stays laid
|
|
420
|
+
out at rest rather than display:none, which is what lets it animate both in
|
|
421
|
+
and out: an unrendered element has no before-change style to transition
|
|
422
|
+
from, and one flipping display to none cannot transition at all. visibility
|
|
423
|
+
keeps it unpaintable, untabbable and unclickable in between, so the expanded
|
|
424
|
+
panel's own controls underneath stay reachable. */
|
|
430
425
|
:host([collapsed]) .launcher {
|
|
431
426
|
opacity: 1;
|
|
432
427
|
transform: none;
|
|
@@ -587,20 +582,18 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
587
582
|
|
|
588
583
|
/* \u2500\u2500 Collapse \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
589
584
|
Collapsing shrinks the widget to the round floating launcher: the panel
|
|
590
|
-
scales
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
The host box keeps its expanded size
|
|
595
|
-
a dragged --ag-ui-width would
|
|
596
|
-
paints there once the panel is gone, so the box only has to stop
|
|
597
|
-
clicks: pointer events go to none
|
|
598
|
-
|
|
599
|
-
Two placements collapse
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
floating circle would escape the layout, and page is a full-screen route
|
|
603
|
-
with no corner to float in. */
|
|
585
|
+
scales toward the launcher's corner and fades, the launcher pops in from the
|
|
586
|
+
same point. Both halves are transform and opacity only, so the morph runs on
|
|
587
|
+
the compositor and never reflows the host page.
|
|
588
|
+
|
|
589
|
+
The host box keeps its expanded size, since animating it would animate
|
|
590
|
+
layout and a dragged --ag-ui-width would fight the launcher's own size.
|
|
591
|
+
Nothing paints there once the panel is gone, so the box only has to stop
|
|
592
|
+
swallowing clicks: pointer events go to none and the launcher takes them.
|
|
593
|
+
|
|
594
|
+
Two placements collapse differently: "sidebar" slides to its rail (below),
|
|
595
|
+
while "embedded" and "page" keep the header bar, having no corner for a
|
|
596
|
+
floating circle that would escape the host's layout. */
|
|
604
597
|
:host([collapsed]) {
|
|
605
598
|
pointer-events: none;
|
|
606
599
|
}
|
|
@@ -611,11 +604,11 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
611
604
|
visibility: hidden;
|
|
612
605
|
}
|
|
613
606
|
|
|
614
|
-
/* visibility
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
607
|
+
/* visibility keeps the panel out of the tab order and the a11y tree at rest
|
|
608
|
+
without display:none killing the transition. It interpolates so any progress
|
|
609
|
+
below 1 still counts as visible: the panel stays on screen for the whole
|
|
610
|
+
collapse, flips hidden exactly at the end, and on expand is visible from the
|
|
611
|
+
first frame. */
|
|
619
612
|
.chat {
|
|
620
613
|
transform-origin: bottom right;
|
|
621
614
|
transition:
|
|
@@ -642,10 +635,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
642
635
|
visibility: visible;
|
|
643
636
|
}
|
|
644
637
|
|
|
645
|
-
/* These two keep the header bar, so the launcher must stay out of the way
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
whatever the page happens to position. */
|
|
638
|
+
/* These two keep the header bar, so the launcher must stay out of the way: an
|
|
639
|
+
embedded host is position: static, which would let an absolutely-positioned
|
|
640
|
+
circle escape the layout and land against whatever the page positions. */
|
|
649
641
|
:host([collapsed]:is([placement="embedded"], [placement="page"])) .launcher {
|
|
650
642
|
visibility: hidden;
|
|
651
643
|
opacity: 0;
|
|
@@ -685,7 +677,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
685
677
|
and the pending indicator so a whole answer reads (and can be boxed) as one
|
|
686
678
|
unit. A flex column on the message-list gap, stretched to the list width so
|
|
687
679
|
its children keep their own left/right alignment. data-answer-well opts into
|
|
688
|
-
the bordered "well"; without it the
|
|
680
|
+
the bordered "well"; without it the turn renders as a flat stack. */
|
|
689
681
|
.answer {
|
|
690
682
|
display: flex;
|
|
691
683
|
flex-direction: column;
|
|
@@ -811,13 +803,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
811
803
|
position: relative;
|
|
812
804
|
}
|
|
813
805
|
|
|
814
|
-
/*
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
back to the initial transparent, and the hover/copied colour to the
|
|
818
|
-
inherited body colour. The defaults chosen upstream (transparent, and the
|
|
819
|
-
body foreground) reproduce that, so the rename repaints nothing. A raised
|
|
820
|
-
surface behind the button is a separate design question. */
|
|
806
|
+
/* The only reader of --ag-ui-surface and --ag-ui-text. Their defaults are
|
|
807
|
+
transparent and the body foreground, which is what this button rendered as
|
|
808
|
+
before either token existed; changing them repaints only this control. */
|
|
821
809
|
.code-copy {
|
|
822
810
|
position: absolute;
|
|
823
811
|
top: 4px;
|
|
@@ -863,12 +851,10 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
863
851
|
color: var(--_muted);
|
|
864
852
|
}
|
|
865
853
|
|
|
866
|
-
/* Markdown tables. table/thead/tbody/tr/th/td are all in
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
width-constrained, so without this the columns either crush or push the
|
|
871
|
-
layout sideways. */
|
|
854
|
+
/* Markdown tables. table/thead/tbody/tr/th/td are all in the sanitizer's
|
|
855
|
+
ALLOWED_TAGS, so an agent can emit one. A wide table must scroll inside its
|
|
856
|
+
own box rather than stretch the message: the bubble is width-constrained, so
|
|
857
|
+
without this the columns either crush or push the layout sideways. */
|
|
872
858
|
.message--assistant table {
|
|
873
859
|
display: block;
|
|
874
860
|
width: fit-content;
|
|
@@ -1125,8 +1111,6 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1125
1111
|
color: var(--_muted);
|
|
1126
1112
|
}
|
|
1127
1113
|
|
|
1128
|
-
/* The record of a human decision on a gated call. An approved call used to
|
|
1129
|
-
look exactly like one that was never gated. */
|
|
1130
1114
|
.skill-item-token {
|
|
1131
1115
|
font-family: ui-monospace, "SF Mono", Menlo, monospace;
|
|
1132
1116
|
font-size: 0.92em;
|
|
@@ -1134,6 +1118,8 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1134
1118
|
margin-right: 6px;
|
|
1135
1119
|
}
|
|
1136
1120
|
|
|
1121
|
+
/* The lasting record of a human decision on a gated call \u2014 without it an
|
|
1122
|
+
approved call looks exactly like one that was never gated. */
|
|
1137
1123
|
.tool-call-decision {
|
|
1138
1124
|
flex: none;
|
|
1139
1125
|
font-size: 11px;
|
|
@@ -1156,10 +1142,8 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1156
1142
|
}
|
|
1157
1143
|
|
|
1158
1144
|
/* Display modes are pure visibility over one DOM shape, selected from the host
|
|
1159
|
-
attribute rather than a value stamped on the card
|
|
1160
|
-
|
|
1161
|
-
re-read it, the way data-answer-well behaves. Baking the structure per mode
|
|
1162
|
-
meant the setting only reached cards created afterwards.
|
|
1145
|
+
attribute rather than a value stamped on the card at build time, so flipping
|
|
1146
|
+
data-tool-display re-styles cards already on screen. See ToolCallCard.
|
|
1163
1147
|
|
|
1164
1148
|
Default (no attribute) is the full mode: arguments always visible, result
|
|
1165
1149
|
behind the toggle. */
|
|
@@ -1256,20 +1240,19 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1256
1240
|
}
|
|
1257
1241
|
|
|
1258
1242
|
/* Then the measurement corrects it. Which edges are held still belongs to the
|
|
1259
|
-
host's layout
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
embedded panel its host right-aligns. */
|
|
1243
|
+
host's layout, not to placement -- a floating panel a host right-aligns is
|
|
1244
|
+
anchored bottom-left -- so the element measures them and stamps a single
|
|
1245
|
+
hyphenated "<y>-<x>" token here. Equal specificity to the rules above, so
|
|
1246
|
+
source order is what lets the measured value win.
|
|
1247
|
+
|
|
1248
|
+
Two traps, both of which silently draw the grip on the corner that moves:
|
|
1249
|
+
|
|
1250
|
+
Never write these as [data-resize-anchor~="left"]. The stamped value is one
|
|
1251
|
+
hyphenated token and ~= matches whitespace-separated words, so it can never
|
|
1252
|
+
match.
|
|
1253
|
+
|
|
1254
|
+
Each rule must set both sides of its axis, not only the side it moves, or it
|
|
1255
|
+
cannot undo a placement guess that flipped the other way. */
|
|
1273
1256
|
:host([data-resize-anchor$="-left"]) .resize-handle {
|
|
1274
1257
|
left: auto;
|
|
1275
1258
|
right: 0;
|
|
@@ -1330,10 +1313,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1330
1313
|
}
|
|
1331
1314
|
|
|
1332
1315
|
/* \u2500\u2500 Composer \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
1333
|
-
One surface owns the border, the background and the focus ring; the field
|
|
1334
|
-
its tool row sit inside it
|
|
1335
|
-
textarea's height
|
|
1336
|
-
and turned Send into a full-height slab. */
|
|
1316
|
+
One surface owns the border, the background and the focus ring; the field
|
|
1317
|
+
and its tool row sit inside it, rather than being siblings stretched to the
|
|
1318
|
+
textarea's height. */
|
|
1337
1319
|
.input-row {
|
|
1338
1320
|
display: flex;
|
|
1339
1321
|
padding: 12px;
|
|
@@ -1581,13 +1563,12 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
1581
1563
|
}
|
|
1582
1564
|
|
|
1583
1565
|
/* A chip carries its own text colour because it carries its own background.
|
|
1584
|
-
The same chip renders in two places with opposite inherited colours:
|
|
1585
|
-
composer tray it
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
Overridden below for an errored chip, which must keep its red. */
|
|
1566
|
+
The same chip renders in two places with opposite inherited colours: the
|
|
1567
|
+
composer tray gives it the panel's, a sent user bubble gives it the user
|
|
1568
|
+
foreground, which is white on the stock light theme and near-invisible
|
|
1569
|
+
against the chip. Pairing the colour with the background it belongs to makes
|
|
1570
|
+
both placements read alike. Overridden below for an errored chip, which
|
|
1571
|
+
keeps its red. */
|
|
1591
1572
|
.attachment-chip {
|
|
1592
1573
|
display: inline-flex;
|
|
1593
1574
|
align-items: center;
|
|
@@ -2241,7 +2222,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
|
|
|
2241
2222
|
border-right: none;
|
|
2242
2223
|
box-shadow: none;
|
|
2243
2224
|
}
|
|
2244
|
-
`;var _i=class{element;#n;#e;#t;#s;#r=!1;constructor(e=ae){this.#s=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.#s.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var Ei=class{element;#n;#e;#t;#s;#r;#a;#i=[];#o="";#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.#d(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.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#n.onNew()}),o.append(this.#t,this.#s),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.#s.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#s.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}#d(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.#i=e,this.#o=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#i.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.#i)this.#r.appendChild(this.#f(e))}#f(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#o&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let 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=pi(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.#h(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.#C(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#h(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()}#C(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 cd(t){return{[pe.PENDING]:t.toolRunning,[pe.DONE]:t.toolDone,[pe.ERROR]:t.toolError,[pe.DECLINED]:t.toolDeclined}}function Zv(t){return{[pe.DONE]:t.resultLabel,[pe.ERROR]:t.errorLabel,[pe.DECLINED]:t.declinedLabel}}function Jv(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var mr=class{element;#n;#e;#t;#s;#r;#a;#i;#o=!1;constructor(e,n,r,o=ae){this.#i=o,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",pe.PENDING),this.element.setAttribute("data-expanded","false");let i=document.createElement("div");i.className="tool-call-head",i.setAttribute("part","tool-card-head");let s=document.createElement("span");s.className="tool-call-icon",s.setAttribute("part","tool-card-icon"),s.setAttribute("aria-hidden","true");let a=document.createElement("span");a.className="tool-call-name",a.setAttribute("part","tool-card-name"),a.textContent=r??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=cd(o)[pe.PENDING],this.#e=document.createElement("span"),this.#e.className="tool-call-decision",this.#e.setAttribute("part","tool-card-decision"),this.#e.hidden=!0,i.append(s,a,this.#n,this.#e);let l=this.#l("args",o.argumentsLabel);l.body.textContent=JSON.stringify(n,null,2),l.root.hidden=Object.keys(n).length===0;let c=this.#l("result",o.resultLabel);this.#s=c.root,this.#r=c.label,this.#a=c.body,c.root.hidden=!0,this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="tool-call-toggle",this.#t.setAttribute("part","tool-card-toggle"),this.#t.setAttribute("aria-expanded","false"),this.#t.textContent=o.details,this.#t.addEventListener("click",()=>this.#d(!this.#c()));let h=document.createElement("div");h.className="tool-call-body",h.setAttribute("part","tool-card-body"),h.append(l.root,c.root),this.element.append(i,this.#t,h)}recordDecision(e){this.element.setAttribute("data-decision",e),this.#e.textContent=e==="approved"?this.#i.decisionApproved:this.#i.decisionDeclined,this.#e.hidden=!1}get settled(){return this.#o}settle(e,n){this.#o||(this.#o=!0,this.element.setAttribute("data-status",e),this.#n.textContent=cd(this.#i)[e],this.#r.textContent=Zv(this.#i)[e],this.#a.textContent=Jv(n),this.#s.hidden=!1)}#l(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#c(){return this.element.getAttribute("data-expanded")==="true"}#d(e){this.element.setAttribute("data-expanded",String(e)),this.#t.setAttribute("aria-expanded",String(e))}};var wi=class{element;#n;#e;#t;#s="idle";#r=null;#a=null;#i=[];#o=!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");let n=document.createElement("slot");n.name="icon-voice",n.innerHTML=gl,this.element.append(n),this.#h("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#c();return}this.#s!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#f(this.#t.transcriptionFailed);return}this.#a=e,this.#i=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#i.push(r.data)}),n.addEventListener("stop",()=>{this.#d(n.mimeType)}),this.#r=n,n.start(),this.#h("recording")}#c(){this.#r?.stop()}dispose(){this.#o=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#d(e){if(this.#o)return;this.#u(),this.#h("transcribing");let n=new Blob(this.#i,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#h("idle"),r!==""&&this.#e(r)}catch(r){this.#f(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}#f(e){this.#u(),this.#r=null,this.#h("idle"),this.element.title=e}#h(e){this.#s=e,this.element.dataset.state=e;let n=this.#C(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#C(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var Ti=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Pn=class{#n;#e;#t;#s;#r;#a;#i;#o=new Set;#l;#c=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#i=e.onPersist??(()=>{}),this.#l=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:Ue(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#i(this.#n.messages),await this.#d()}async resume(){await this.#d()}addToolResult(e,n){this.#n.addMessage({id:Ue(),role:"tool",content:n,toolCallId:e}),this.#i(this.#n.messages)}cancel(){this.#c=!0,this.#n.abortRun()}async#d(){this.#c=!1;try{await this.#f(),this.#c&&this.#u()}catch(e){this.#c||Qv(e)?this.#u():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#u(){this.#i(this.#n.messages),this.#e.onCancelled()}async#f(){let e;for(let n=0;n<Qi;n+=1){if(this.#c)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#i(this.#n.messages),this.#c)return;if(!o.terminal)throw new Ti(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#c)return;e=vu(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:Ue(),role:"tool",content:l.content,toolCallId:a.id}),this.#i(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e,o=this.#o;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:i}){o.has(i.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${i.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({event:i,textMessageBuffer:s}){o.add(i.messageId),r.onTextEnd(s)},onToolCallEndEvent({event:i,toolCallName:s,toolCallArgs:a}){let l={id:i.toolCallId,name:s,args:a};e.push(l),r.onToolCall(l)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onActivitySnapshotEvent({event:i}){r.onActivity(i.activityType,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(i){n.terminal=!0,i.outcome==="interrupt"&&(n.interrupts=i.interrupts)},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Qv(t){return t instanceof Error&&t.name==="AbortError"}function Oa(t){let e=t.attachments;return Array.isArray(e)?e.filter(eb):[]}function eb(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 Ma="ag-ui-chat",gr="thread",La="threads",Si="messages:",Ai="checkpoint:",tb=60,nb=100,rb="New conversation",mt=class{#n;constructor(e=""){this.#n=e===""?Ma:`${Ma}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(gr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Ue();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#i(this.#r(Si+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(Si+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#i(this.#r(Ai+e))}saveCheckpoint(e,n){let r=this.#r(Ai+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Si+e)),sessionStorage.removeItem(this.#r(Ai+e)),this.#s(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(gr))===e&&sessionStorage.removeItem(this.#r(gr))}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(gr),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.#s(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=ib(n),s=Date.now();o===void 0?r.push({threadId:e,title:ud(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=ud(n))),this.#s(r)}#t(){return this.#i(this.#r(La))??[]}#s(e){let n=this.#r(La);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Ma}:`,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);ob(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)}}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function ob(t){return t===gr||t===La||t.startsWith(Si)||t.startsWith(Ai)}function ud(t){for(let e of t)if(e.role==="user"){let n=dd(e.content);if(n!=="")return pd(n,tb)}return rb}function ib(t){for(let e of[...t].reverse()){let n=dd(e.content);if(n!=="")return pd(n,nb)}return""}function dd(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function pd(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Be(t,e){return e===void 0?t:{...t,credentials:e}}function Pa(t){return new bu({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,Be(n,t.credentials));let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,Be({...n,headers:o},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var vr=class{#n;#e;#t;#s;#r=new Set;#a=new Map;constructor(e,n=()=>({}),r=new mt,o=()=>{}){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r,this.#s=o}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.#a.set(e,n),this.#d(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#r.add(e),this.#d(e,"DELETE")}async listThreads(){let e=await this.#i();return e===null?this.#t.listThreads():e.filter(n=>!this.#r.has(n.thread_id)).map(n=>this.#l(n))}async loadMessages(e){let n=await this.#c(`${this.#n}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#o(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#i(){let e=await this.#c(this.#n);if(e===null||!e.ok)return null;let n=await this.#o(e);return n===null?null:n.threads??[]}async#o(e){try{return await e.json()}catch{return null}}#l(e){return{threadId:e.thread_id,title:this.#a.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#c(e){try{return await fetch(e,Be({headers:this.#e()},this.#s()))}catch{return null}}async#d(e,n,r){let o=this.#e();try{await fetch(`${this.#n}${encodeURIComponent(e)}/`,Be({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var br=class{#n;#e;#t;constructor(e,n=()=>({}),r=()=>{}){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}async list(){try{let e=await fetch(this.#n,Be({method:"GET",headers:{Accept:"application/json",...this.#e()}},this.#t()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function Da(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Be({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await sb(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 sb(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Ua(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url),i.withCredentials=e.credentials==="include";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(ab(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(lb(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 ab(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 lb(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var cb=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],za=["omit","same-origin","include"];function Ha(t){return za.includes(t)}var hd="ag-ui-chat:collapsed",fd="ag-ui-chat:size",md="ag-ui-chat:theme",yr=class extends HTMLElement{agentFactory=Pa;headers={};getHeaders=null;allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#ve().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...ms(this.getPageMap,this.autoInjectPageMap)];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 Bn;#s=new Map;#r=new Set;#a;#i;#o;#l;#c;#d;#u;#f;#h;#C=null;#x;#v;#b;#F;#S;#y;#A;#$=0;#R;#m=null;#B;#J=null;#U=!1;#N=null;#L={};#H=!1;#Q=null;#_=null;#E=null;#ee=0;#V=null;#k=null;#O=null;#p="";#P="";#te=0;#ne=[];#fe=[];#me=[];#ge=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#i=document.createElement("div"),this.#o=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#d=document.createElement("span"),this.#x=document.createElement("div"),this.#v=document.createElement("button"),this.#b=document.createElement("input"),this.#F=document.createElement("div"),this.#B=document.createElement("span"),this.#S=document.createElement("button"),this.#y=document.createElement("button"),this.#A=document.createElement("span"),this.#R=document.createElement("div"),this.#u=new xi(e=>this.#it(e)),this.#f=new Ei({onSelect:e=>{this.#ct(e)},onNew:()=>{this.newChat(),this.#Y()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Y()},onDelete:e=>{this.#ut(e)}}),this.#h=new ar((e,n)=>{this.#ze(e,n)})}#re(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#C===null&&(this.#C=new br(e,()=>this.#I(),()=>this.#j())),this.#C)}async#ze(e,n){let r=this.#re();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="",this.#z();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#I(),getHeaders:()=>this.#I(),...this.#q(),threadId:this.#p,initialMessages:[]});await new Pn({agent:s,handlers:this.#Pe(),getTools:()=>this.getTools(),getContext:()=>this.#ke(),executeTool:l=>this.#Me(l),resolveInterrupts:l=>this.#Le(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Ge(){let e=this.#re();this.#h.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials",...cb]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Ha(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${za.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="placement"){this.#at(),requestAnimationFrame(()=>this.#se());return}if(e==="title-text"){this.#d.textContent=r??this.#e.title;return}n===r||!this.#U||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#t.register(e)}get sharedState(){return this.#N?.state??this.#L}set sharedState(e){this.#L={...e},this.#N?.setState(this.#L)}registerPageState(e){for(let n of Ur(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#Fe(){return this.routeMap.length===0?[]:vs(()=>this.routeMap,()=>this.navigate)}#$e(){let e=this.getPageMap;return e===null?[]:[{name:Ji,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()}]}#Be(){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 fs(n,r=>this.resolvePageTarget(r))}#ve(){return[...this.#Fe(),...this.#$e(),...this.#Be(),...this.#Ve()]}#Ve(){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.#je(e)}]:[]}async#je(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.#_=new AbortController;let i=this.#_.signal;this.#T();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await pa(this.#w(),r,{signal:i,strings:this.#e});return this.#_=null,this.#g(),this.#o.scrollTop=this.#o.scrollHeight,s}#be(e){let n=this.#ve().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 credentials(){let e=this.getAttribute("credentials");return e!==null&&Ha(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Ha(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${za.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#I(){return{...this.headers,...this.getHeaders?.()}}#j(){return this.credentials??void 0}#q(){let e=this.#j();return e===void 0?{}:{credentials:e}}#ye(){return Be({headers:this.#I()},this.#j())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===pn.INLINE||e===pn.MINIMAL||e===pn.COMPACT?e:pn.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#P=this.id!==""?this.id:this.endpoint,this.#ae(this.#Se()),requestAnimationFrame(()=>this.#se()),this.#e=bs({...this.#We(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#le(md);e!==null&&this.setAttribute("theme",e)}this.#gt(),this.#f.setStrings(this.#e),this.#h.setStrings(this.#e),this.#le(hd)==="1"&&this.setAttribute("collapsed",""),this.#Re(),this.#rt(),this.#P!==""&&this.conversationStore instanceof mt&&(this.conversationStore=new mt(this.#P)),this.#nt(),this.#Xe(),this.#Ke(),this.#p=this.conversationStore.threadId(),queueMicrotask(()=>this.#qe()),this.#ce(),this.#U=!0}#qe(){this.#U&&(this.#_e(),this.#Ee())}async reload(){this.#M(),this.#X(),this.#D(!1),await Promise.all([this.#_e(),this.#Ee(),this.#ce()])}disconnectedCallback(){this.#U=!1,this.#M(),this.#m?.dispose(),this.#J?.dispose()}#xe(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#We(){let e=this.getAttribute("data-strings");if(e===null)return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Xe(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ye(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new di({upload:n,maxBytes:this.#Qe(),accept:r,strings:this.#e,onChange:()=>this.#_t(o)});this.#m=o,this.#F.appendChild(this.#m.element),this.#b.accept=r,this.#v.hidden=!1,this.#tt()}#Ye(e){return e===null?null:(n,r,o)=>Ua(n,{url:e,headers:this.#I(),...this.#q(),onProgress:r,signal:o})}#Ke(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Ze(e);n!==null&&(this.#J=new wi({transcribe:n,onText:r=>this.#Je(r),strings:this.#e}),this.#B.appendChild(this.#J.element))}#Ze(e){return e===null?null:n=>Da(n,{url:e,headers:this.#I(),...this.#q()})}#Je(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#Ne(),this.#l.focus()}#Qe(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return es;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:es}#et(){let e=this.#b.files;if(e!==null)for(let n of Array.from(e))this.#m?.add(n);this.#b.value=""}#tt(){this.#i.addEventListener("dragover",e=>{e.preventDefault(),this.#i.classList.add("chat--dragover")}),this.#i.addEventListener("dragleave",()=>{this.#i.classList.remove("chat--dragover")}),this.#i.addEventListener("drop",e=>{e.preventDefault(),this.#i.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#m?.add(r)})}#nt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new vr(e,()=>this.#I(),this.conversationStore,()=>this.#j()))}async#_e(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#ye());this.#n=gs(await n.json())}catch{}}setSkills(e){this.#ge=e,this.#oe()}#rt(){this.#u.enableChips(this.#xe("data-prompt-chips")),this.#u.enableSlash(this.#xe("data-slash-commands")),this.#me=this.#ot(),this.#oe()}#ot(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return rs(JSON.parse(e))}catch{return[]}}async#Ee(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#ye());this.#fe=rs(await n.json()),this.#oe()}catch{}}#oe(){let e=new Map;for(let n of[...this.#fe,...this.#me,...this.#ge])e.set(n.name,n);this.#u.setSkills([...e.values()])}#it(e){if(e.prompt===void 0){this.#x.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=El(e.prompt,this.skillContext());if(r.length>0){this.#x.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#x.hidden=!1,this.#l.value=n,this.#z(),this.#l.focus(),this.#st(n);return}if(this.#x.hidden=!0,this.#l.value=n,this.#z(),e.sendImmediately===!1){this.#l.focus();return}this.#pe()}#st(e){let n=e.indexOf("{");this.#l.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#W(hd),e?"1":"0"),this.#de(0),this.dispatchEvent(new CustomEvent(Wi,{detail:{collapsed:e},bubbles:!0,composed:!0}))}get unread(){return this.#$}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#W(md),e),this.#Ae()}#ie(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#we(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height");this.#ae({width:e.width+1,height:e.height+1});let o=this.getBoundingClientRect();return this.#Te("--ag-ui-width",n),this.#Te("--ag-ui-height",r),{x:Math.abs(o.left-e.left)<.5?"left":"right",y:Math.abs(o.top-e.top)<.5?"top":"bottom"}}#se(){if(!this.#U)return;let e=this.#we();this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`)}#Te(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ae(e){let n=this.#ie();n!=="none"&&(e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&n==="both"&&this.style.setProperty("--ag-ui-height",`${e.height}px`))}#at(){let e=this.#ie();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#lt(e){let n={...this.#Se(),...e};sessionStorage.setItem(this.#W(fd),JSON.stringify(n))}#Se(){let e=this.#le(fd);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#W(e){return this.#P===""?e:`${e}:${this.#P}`}#le(e){let n=sessionStorage.getItem(this.#W(e));return n!==null||this.#P===""?n:sessionStorage.getItem(e)}#Ae(){let e=this.getAttribute("theme")==="dark";this.#S.textContent=e?"\u2600\uFE0F":"\u{1F319}"}openThreads(){this.#Y(),this.#f.open()}openCheckpoints(){this.#Ge(),this.#h.open()}newChat(){this.#M(),this.conversationStore.clear(this.#p),this.#X(),this.#p=this.conversationStore.threadId(),this.#D(!1),this.#de(0)}#X(){this.#N=null,this.#E=null,this.#k=null,this.#O=null,this.#T(),this.#s.clear(),this.#r.clear(),this.#ne=[],this.#m?.clear(),this.#o.replaceChildren(this.#R),this.#g()}async#ct(e){e!==this.#p&&(this.#M(),this.#X(),this.conversationStore.setActiveThread(e),this.#p=e,this.#D(!1),await this.#ce())}#ut(e){let n=e===this.#p;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#X(),this.#p=this.conversationStore.threadId(),this.#D(!1)),this.#Y()}async#Y(){this.#f.setThreads(await this.conversationStore.listThreads(),this.#p)}async#ce(){this.#te+=1;let e=this.#te,n=await this.conversationStore.loadMessages(this.#p);if(e!==this.#te)return;if(n!==null){this.#ne=n;for(let o of n)this.#ht(o)}let r=this.conversationStore.loadCheckpoint(this.#p);if(r!==null){await this.#mt(r);return}this.#pt(n)}#ke(){return this.#Q=window.location.href,this.getContext()}#dt(){return this.#Q!==null&&this.#Q!==window.location.href}#pt(e){let n=e?.at(-1);n===void 0||n.role!==je.USER||this.#Z("\u26A0",this.#e.runInterrupted,"interrupted")}#ht(e){let n=typeof e.content=="string"?e.content:"";if(e.role===je.USER){let r=Oa(e);if(n!==""||r.length>0){let o=this.appendMessage(je.USER,n);r.length>0&&o.appendChild(_s(r))}return}if(e.role===je.ASSISTANT){n!==""&&this.appendMessage(je.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.#ft(o.function.arguments)};this.#He(i)||this.#he(i)}return}if(e.role==="tool"){let r=this.#s.get(e.toolCallId);r!==void 0&&r.settle(pe.DONE,e.content)}}#ft(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Ie(e){this.getAttribute("data-text-animation")==="word"&&sd(e)}async#mt(e){this.conversationStore.saveCheckpoint(this.#p,null);let n=this.#Oe();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===je.ASSISTANT?(r.innerHTML=yi(n,{allowImages:this.allowImages}),xs(r,this.#e),this.#w().appendChild(r)):(this.#k=null,r.textContent=n,this.#o.appendChild(r)),this.#g(),this.#o.scrollTop=this.#o.scrollHeight,r}#w(){if(this.#k===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#k=e,this.#o.appendChild(e),this.#g()}return this.#k}#gt(){let e=document.createElement("style");e.textContent=ld,this.#i.className="chat",this.#i.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#d;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.#Ce("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.#K("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>this.openThreads());let a=this.#K("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>this.openCheckpoints());let l=this.#K("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#K("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#re()!==null?i.append(s,a,l):i.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#S.type="button",this.#S.className="header-btn header-btn--theme",this.#S.setAttribute("part","header-button theme-toggle"),this.#S.title=this.#e.toggleTheme,this.#S.setAttribute("aria-label",this.#e.toggleTheme),this.#S.addEventListener("click",()=>this.toggleTheme()),this.#Ae(),i.append(this.#S)),i.append(c),n.append(r,o,i),this.#o.className="messages",this.#o.setAttribute("part","messages"),this.#o.setAttribute("role","log"),this.#o.setAttribute("aria-live","polite"),this.#o.setAttribute("aria-label",this.#e.conversation),this.#R.className="empty",this.#R.setAttribute("part","empty");let h=document.createElement("slot");h.name="empty",this.#R.append(h),this.#o.append(this.#R);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let y=document.createElement("div");y.className="composer",y.setAttribute("part","composer-surface");let f=document.createElement("div");f.className="composer-tools",f.setAttribute("part","composer-tools"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=1,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",g=>this.#xt(g)),this.#l.addEventListener("input",()=>this.#Ne()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.append(this.#ue("icon-send","send-send",hl),this.#ue("icon-stop","send-stop",fl)),this.#c.title=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.#pe()}),this.#x.className="skill-hint",this.#x.setAttribute("part","skill-hint"),this.#x.hidden=!0,this.#v.className="attach-btn",this.#v.type="button",this.#v.setAttribute("part","attach-button"),this.#v.append(this.#ue("icon-attach","attach-glyph",ml)),this.#v.title=this.#e.attachFiles,this.#v.setAttribute("aria-label",this.#e.attachFiles),this.#v.hidden=!0,this.#v.addEventListener("click",()=>this.#b.click()),this.#b.className="attach-input",this.#b.type="file",this.#b.multiple=!0,this.#b.hidden=!0,this.#b.addEventListener("change",()=>this.#et()),this.#F.className="attachment-slot",this.#B.className="voice-slot";let p=document.createElement("slot");p.name="footer",f.append(this.#v,this.#B,this.#c),y.append(this.#l,f),m.append(y,this.#b),this.#i.append(n,this.#o,this.#u.palette,this.#u.chips,this.#x,this.#F,m,p,this.#f.element,this.#h.element),this.#y.className="launcher",this.#y.type="button",this.#y.setAttribute("part","launcher"),this.#y.setAttribute("aria-label",this.#e.expand),this.#A.className="launcher-badge",this.#A.setAttribute("part","launcher-badge"),this.#A.setAttribute("aria-hidden","true"),this.#A.hidden=!0,this.#y.append(this.#Ce("launcher","launcher-icon",vl,this.#vt()),this.#A),this.#y.addEventListener("click",()=>this.setCollapsed(!1)),this.#i.append(od({axis:()=>this.#ie(),anchor:()=>this.#we(),rect:()=>this.getBoundingClientRect(),apply:g=>this.#ae(g),commit:g=>{this.#lt(g),this.#se()},label:this.#e.resizePanel})),this.#a.append(e,this.#i,this.#y)}#K(e,n,r){let o=document.createElement("button");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);let i=document.createElement("slot");return i.name=`icon-${e}`,i.append(document.createTextNode(r)),o.append(i),o}#ue(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#vt(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#Ce(e,n,r,o=this.getAttribute("data-icon-url")){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let s=document.createElement("slot");if(s.name=e,o!==null){let a=document.createElement("img");a.className="icon-img",a.src=o,a.alt="",s.append(a)}else r!==null&&(s.innerHTML=r);return i.append(s),i}#Re(){this.#y.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#$;this.#A.textContent=e>9?"9+":String(e),this.#A.hidden=e===0||!this.#bt();let n=this.#A.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#y.setAttribute("aria-label",n),this.#y.title=n}#bt(){return this.getAttribute("data-unread-badge")!=="false"}#de(e){this.#$=e,this.#Re(),this.dispatchEvent(new CustomEvent(Xi,{detail:{unread:e},bubbles:!0,composed:!0}))}#yt(){this.collapsed&&this.#de(this.#$+1)}#g(){this.#R.hidden=this.#o.childElementCount>1}#Ne(){this.#u.onInput(this.#l.value),this.#x.hidden=!0,this.#z()}#xt(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.#pe())}#M(){this.#_?.abort(),this.#N?.cancel()}#D(e){this.#H=e;let n=e?this.#e.stop:this.#e.send;this.#c.title=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}#z(){this.#l.style.height="auto",this.#l.style.height=`${this.#l.scrollHeight}px`}async#pe(){if(this.#H)return;let e=this.#l.value.trim(),n=this.#m?.readyRefs()??[];e===""&&n.length===0||(this.#l.value="",this.#z(),this.#m?.hasPending()===!0&&this.#Z("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#m.pendingCount())),"attachment-pending"),this.#m?.clearReady(),await this.sendMessage(e,n))}async sendMessage(e,n=[]){if(this.#H||e===""&&n.length===0)return;let r=this.appendMessage(je.USER,e);n.length>0&&r.appendChild(_s(n)),this.dispatchEvent(new CustomEvent(qi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#Et(e,n)}attachFile(e){return this.#m===null?!1:(this.#m.add(e),!0)}#_t(e){this.dispatchEvent(new CustomEvent(Ki,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#Et(e,n){this.endpoint!==""&&await this.#Oe().send(e,n)}#Oe(){if(this.#N===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#I(),getHeaders:()=>this.#I(),...this.#q(),threadId:this.#p,initialMessages:this.#ne,initialState:this.#L});this.#N=new Pn({agent:e,handlers:this.#Pe(),getTools:()=>this.getTools(),getContext:()=>this.#ke(),executeTool:n=>this.#Me(n),resolveInterrupts:n=>this.#Le(n),onPersist:n=>this.conversationStore.saveMessages(this.#p,n),onStateChanged:n=>this.#wt(n),connectionLostMessage:this.#e.connectionLost})}return this.#N}#wt(e){this.#L={...e},this.dispatchEvent(new CustomEvent(Yi,{detail:{state:this.#L},bubbles:!0,composed:!0}))}async#Tt(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:os(n.parameters)}async#Me(e){if(gd(e)!==null)return null;let n=this.#he(e);this.#s.delete(e.id);let r=this.#be(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!==Ji&&!Mr(r.parameters)&&this.#dt()){let i=this.#e.pageMoved;return n.settle(pe.ERROR,i),this.#G(),{content:`Error: ${i}`,error:i}}if(await this.#Tt(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Zi];typeof s=="string"&&(i.message=s),this.#_=new AbortController;let a=ua(this.#w(),i,{signal:this.#_.signal,strings:this.#e});this.#g(),this.#o.scrollTop=this.#o.scrollHeight;let l=await a;if(this.#_=null,n.recordDecision(l?"approved":"declined"),!l){let c=this.#e.declinedAction;return n.settle(pe.DECLINED,c),this.#G(),{content:c}}}let o=Mr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#p,{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.#G(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#p,null);let s=i instanceof Error?i.message:String(i);return n.settle(pe.ERROR,s),this.#G(),{content:`Error: ${s}`,error:s}}}async#Le(e){let n={};this.#_=new AbortController,this.#T();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#s.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#_.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await ys(this.#w(),o,{signal:a,strings:this.#e});this.#g(),this.#o.scrollTop=this.#o.scrollHeight,i?.recordDecision(l?"approved":"declined"),l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(pe.DECLINED,this.#e.declinedAction))}return this.#_=null,n}#Pe(){return{onRunStart:()=>{this.#D(!0),this.#w(),this.#G()},onReasoningStart:()=>{this.#T(),this.#De()},onReasoningDelta:e=>{this.#De().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#T(),this.#O?.collapse(),this.#Ue(e),this.#ee+=1},onTextEnd:e=>{let n=this.#Ue(e);this.#ee<=1&&this.#Ie(n),xs(n,this.#e),this.#E=null,this.#yt()},onToolCall:e=>{this.#T(),!this.#He(e)&&this.#he(e)},onActivity:(e,n)=>{if(e!==ts)return;let r=ub(n);r!==null&&this.#Z("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#s.get(e);r!==void 0&&(r.settle(pe.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#T(),this.#E=null},onError:e=>{this.#T(),this.#Ie(this.appendMessage(je.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#E=null},onCancelled:()=>{this.#T(),this.#St(),this.#E=null},onSettled:()=>{this.#T(),this.#D(!1),this.#E=null;for(let e of this.#s.values())e.settled||e.settle(pe.DONE,this.#e.noResult);this.#k!==null&&this.#k.childElementCount===0&&(this.#k.remove(),this.#g()),this.#k=null,this.#O=null}}}#St(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#w().appendChild(e),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}#G(){if(this.#V!==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.#V=e,this.#w().appendChild(e),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}#T(){this.#V?.remove(),this.#V=null}#De(){if(this.#O===null){this.#O=new _i(this.#e);let e=this.#w();e.insertBefore(this.#O.element,e.firstChild),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}return this.#O}#Ue(e){return this.#E===null&&(this.#E=this.appendMessage(je.ASSISTANT,""),this.#ee=0),this.#E.innerHTML=yi(e,{allowImages:this.allowImages}),this.#o.scrollTop=this.#o.scrollHeight,this.#E}#He(e){let n=gd(e);return n===null?!1:(this.#Z("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#Z(e,n,r){this.#w().appendChild(ad(e,n,r)),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}#he(e){let n=this.#s.get(e.id);if(n!==void 0)return n;let r=this.#be(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??da(e.name),i=new mr(e.name,e.args,o,this.#e);return this.#s.set(e.id,i),this.#w().appendChild(i.element),this.#g(),this.#o.scrollTop=this.#o.scrollHeight,i}};function gd(t){if(t.name!==ns)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function ub(t){let e=t?.removed;return typeof e=="number"?e:null}function db(){customElements.get(Or)===void 0&&customElements.define(Or,yr)}async function pb(t,e,n={}){await lt(t),await cs(t,{...n,flashMs:n.flashMs??0}),await as(t,e,n)}async function hb(t,e={}){await lt(t),await ls(t,e)}async function fb(t,e={}){await lt(t),await us(t,e)}async function mb(t,e,n={}){await lt(t),await ds(t,e,n)}async function gb(t,e,n={}){await lt(t),await ps(t,e,n)}function vb(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Vn(t,!!e):Nt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var bb="0.23.0";export{Ki as ATTACHMENT_EVENT,yr as AgUiChat,Pn as AgUiClient,ts as COMPACTION_ACTIVITY_TYPE,ar as CheckpointMenu,Bn as ClientToolRegistry,Ti as ConnectionLostError,ae as DEFAULT_UI_STRINGS,Or as ELEMENT_TAG,ns as LOAD_CAPABILITY_TOOL,Qi as MAX_TOOL_ROUNDS,je as MESSAGE_ROLE,hs as PAGE_ACTIONS,vr as RemoteConversationStore,br as RunIndex,Yi as STATE_EVENT,qi as SUBMIT_EVENT,mt as SessionStorageStore,Wi as TOGGLE_EVENT,pe as TOOL_CALL_STATUS,pn as TOOL_DISPLAY,mr as ToolCallCard,Xi as UNREAD_EVENT,bb as VERSION,Zi as X_CONFIRM_KEY,Fn as X_DESTRUCTIVE_KEY,$n as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,hb as clickElement,Pa as createHttpAgent,fs as createPageActionTools,ms as createPageMapContext,Ur as createPageStateTools,vs as createRouteTools,cp as createStateHookTools,db as defineAgUiChat,pb as fillField,op as flash,cs as focusWithFlash,ls as highlightThenClick,os as isDestructive,Mr as isNavigates,bs as mergeUiStrings,Oa as messageAttachments,gs as parseToolCatalog,Pr as prefersReducedMotion,fb as pressButton,us as pressThenClick,da as prettifyToolName,yi as renderMarkdown,ys as requestApproval,ua as requestConfirmation,pa as requestQuestion,lt as scrollIntoCenterView,mb as selectControl,ds as selectOption,vb as setControlValue,Vn as setNativeChecked,Nt as setNativeValue,gb as toggleCheckbox,ps as toggleControl,Da as transcribeAudio,as as typeInto,Ua as uploadAttachment};
|
|
2225
|
+
`;var _i=class{element;#n;#e;#t;#s;#r=!1;constructor(e=ae){this.#s=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.#s.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var Ei=class{element;#n;#e;#t;#s;#r;#a;#i=[];#o="";#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.#d(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.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#n.onNew()}),o.append(this.#t,this.#s),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.#s.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#s.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}#d(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.#i=e,this.#o=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#i.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.#i)this.#r.appendChild(this.#f(e))}#f(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#o&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let 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=pi(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.#h(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.#I(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#h(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()}#I(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 cd(t){return{[pe.PENDING]:t.toolRunning,[pe.DONE]:t.toolDone,[pe.ERROR]:t.toolError,[pe.DECLINED]:t.toolDeclined}}function Zv(t){return{[pe.DONE]:t.resultLabel,[pe.ERROR]:t.errorLabel,[pe.DECLINED]:t.declinedLabel}}function Jv(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var mr=class{element;#n;#e;#t;#s;#r;#a;#i;#o=!1;constructor(e,n,r,o=ae){this.#i=o,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",pe.PENDING),this.element.setAttribute("data-expanded","false");let i=document.createElement("div");i.className="tool-call-head",i.setAttribute("part","tool-card-head");let s=document.createElement("span");s.className="tool-call-icon",s.setAttribute("part","tool-card-icon"),s.setAttribute("aria-hidden","true");let a=document.createElement("span");a.className="tool-call-name",a.setAttribute("part","tool-card-name"),a.textContent=r??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=cd(o)[pe.PENDING],this.#e=document.createElement("span"),this.#e.className="tool-call-decision",this.#e.setAttribute("part","tool-card-decision"),this.#e.hidden=!0,i.append(s,a,this.#n,this.#e);let l=this.#l("args",o.argumentsLabel);l.body.textContent=JSON.stringify(n,null,2),l.root.hidden=Object.keys(n).length===0;let c=this.#l("result",o.resultLabel);this.#s=c.root,this.#r=c.label,this.#a=c.body,c.root.hidden=!0,this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="tool-call-toggle",this.#t.setAttribute("part","tool-card-toggle"),this.#t.setAttribute("aria-expanded","false"),this.#t.textContent=o.details,this.#t.addEventListener("click",()=>this.#d(!this.#c()));let h=document.createElement("div");h.className="tool-call-body",h.setAttribute("part","tool-card-body"),h.append(l.root,c.root),this.element.append(i,this.#t,h)}recordDecision(e){this.element.setAttribute("data-decision",e),this.#e.textContent=e==="approved"?this.#i.decisionApproved:this.#i.decisionDeclined,this.#e.hidden=!1}get settled(){return this.#o}settle(e,n){this.#o||(this.#o=!0,this.element.setAttribute("data-status",e),this.#n.textContent=cd(this.#i)[e],this.#r.textContent=Zv(this.#i)[e],this.#a.textContent=Jv(n),this.#s.hidden=!1)}#l(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#c(){return this.element.getAttribute("data-expanded")==="true"}#d(e){this.element.setAttribute("data-expanded",String(e)),this.#t.setAttribute("aria-expanded",String(e))}};var wi=class{element;#n;#e;#t;#s="idle";#r=null;#a=null;#i=[];#o=!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");let n=document.createElement("slot");n.name="icon-voice",n.innerHTML=gl,this.element.append(n),this.#h("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#c();return}this.#s!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#f(this.#t.transcriptionFailed);return}this.#a=e,this.#i=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#i.push(r.data)}),n.addEventListener("stop",()=>{this.#d(n.mimeType)}),this.#r=n,n.start(),this.#h("recording")}#c(){this.#r?.stop()}dispose(){this.#o=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#d(e){if(this.#o)return;this.#u(),this.#h("transcribing");let n=new Blob(this.#i,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#h("idle"),r!==""&&this.#e(r)}catch(r){this.#f(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}#f(e){this.#u(),this.#r=null,this.#h("idle"),this.element.title=e}#h(e){this.#s=e,this.element.dataset.state=e;let n=this.#I(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#I(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var Ti=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Pn=class{#n;#e;#t;#s;#r;#a;#i;#o=new Set;#l;#c=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#i=e.onPersist??(()=>{}),this.#l=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:Ue(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#i(this.#n.messages),await this.#d()}async resume(){await this.#d()}addToolResult(e,n){this.#n.addMessage({id:Ue(),role:"tool",content:n,toolCallId:e}),this.#i(this.#n.messages)}cancel(){this.#c=!0,this.#n.abortRun()}async#d(){this.#c=!1;try{await this.#f(),this.#c&&this.#u()}catch(e){this.#c||Qv(e)?this.#u():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#u(){this.#i(this.#n.messages),this.#e.onCancelled()}async#f(){let e;for(let n=0;n<Qi;n+=1){if(this.#c)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#i(this.#n.messages),this.#c)return;if(!o.terminal)throw new Ti(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#c)return;e=vu(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:Ue(),role:"tool",content:l.content,toolCallId:a.id}),this.#i(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e,o=this.#o;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:i}){o.has(i.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${i.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({event:i,textMessageBuffer:s}){o.add(i.messageId),r.onTextEnd(s)},onToolCallEndEvent({event:i,toolCallName:s,toolCallArgs:a}){let l={id:i.toolCallId,name:s,args:a};e.push(l),r.onToolCall(l)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onActivitySnapshotEvent({event:i}){r.onActivity(i.activityType,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(i){n.terminal=!0,i.outcome==="interrupt"&&(n.interrupts=i.interrupts)},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Qv(t){return t instanceof Error&&t.name==="AbortError"}function Oa(t){let e=t.attachments;return Array.isArray(e)?e.filter(eb):[]}function eb(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 Ma="ag-ui-chat",gr="thread",La="threads",Si="messages:",Ai="checkpoint:",tb=60,nb=100,rb="New conversation",mt=class{#n;constructor(e=""){this.#n=e===""?Ma:`${Ma}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(gr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Ue();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#i(this.#r(Si+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(Si+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#i(this.#r(Ai+e))}saveCheckpoint(e,n){let r=this.#r(Ai+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Si+e)),sessionStorage.removeItem(this.#r(Ai+e)),this.#s(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(gr))===e&&sessionStorage.removeItem(this.#r(gr))}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(gr),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.#s(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=ib(n),s=Date.now();o===void 0?r.push({threadId:e,title:ud(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=ud(n))),this.#s(r)}#t(){return this.#i(this.#r(La))??[]}#s(e){let n=this.#r(La);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Ma}:`,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);ob(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)}}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function ob(t){return t===gr||t===La||t.startsWith(Si)||t.startsWith(Ai)}function ud(t){for(let e of t)if(e.role==="user"){let n=dd(e.content);if(n!=="")return pd(n,tb)}return rb}function ib(t){for(let e of[...t].reverse()){let n=dd(e.content);if(n!=="")return pd(n,nb)}return""}function dd(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function pd(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Be(t,e){return e===void 0?t:{...t,credentials:e}}function Pa(t){return new bu({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,Be(n,t.credentials));let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,Be({...n,headers:o},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var vr=class{#n;#e;#t;#s;#r=new Set;#a=new Map;constructor(e,n=()=>({}),r=new mt,o=()=>{}){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r,this.#s=o}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.#a.set(e,n),this.#d(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#r.add(e),this.#d(e,"DELETE")}async listThreads(){let e=await this.#i();return e===null?this.#t.listThreads():e.filter(n=>!this.#r.has(n.thread_id)).map(n=>this.#l(n))}async loadMessages(e){let n=await this.#c(`${this.#n}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#o(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#i(){let e=await this.#c(this.#n);if(e===null||!e.ok)return null;let n=await this.#o(e);return n===null?null:n.threads??[]}async#o(e){try{return await e.json()}catch{return null}}#l(e){return{threadId:e.thread_id,title:this.#a.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#c(e){try{return await fetch(e,Be({headers:this.#e()},this.#s()))}catch{return null}}async#d(e,n,r){let o=this.#e();try{await fetch(`${this.#n}${encodeURIComponent(e)}/`,Be({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var br=class{#n;#e;#t;constructor(e,n=()=>({}),r=()=>{}){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}async list(){try{let e=await fetch(this.#n,Be({method:"GET",headers:{Accept:"application/json",...this.#e()}},this.#t()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function Da(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Be({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await sb(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 sb(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Ua(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url),i.withCredentials=e.credentials==="include";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(ab(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(lb(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 ab(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 lb(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var cb=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],za=["omit","same-origin","include"];function Ha(t){return za.includes(t)}var hd="ag-ui-chat:collapsed",fd="ag-ui-chat:size",md="ag-ui-chat:theme",yr=class extends HTMLElement{agentFactory=Pa;headers={};getHeaders=null;allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#ve().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...ms(this.getPageMap,this.autoInjectPageMap)];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 Bn;#s=new Map;#r=new Set;#a;#i;#o;#l;#c;#d;#u;#f;#h;#I=null;#x;#v;#b;#F;#S;#y;#A;#$=0;#R;#m=null;#B;#J=null;#U=!1;#N=null;#L={};#H=!1;#Q=null;#_=null;#E=null;#ee=0;#V=null;#k=null;#O=null;#p="";#P="";#te=0;#ne=[];#fe=[];#me=[];#ge=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#i=document.createElement("div"),this.#o=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#d=document.createElement("span"),this.#x=document.createElement("div"),this.#v=document.createElement("button"),this.#b=document.createElement("input"),this.#F=document.createElement("div"),this.#B=document.createElement("span"),this.#S=document.createElement("button"),this.#y=document.createElement("button"),this.#A=document.createElement("span"),this.#R=document.createElement("div"),this.#u=new xi(e=>this.#it(e)),this.#f=new Ei({onSelect:e=>{this.#ct(e)},onNew:()=>{this.newChat(),this.#Y()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Y()},onDelete:e=>{this.#ut(e)}}),this.#h=new ar((e,n)=>{this.#ze(e,n)})}#re(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#I===null&&(this.#I=new br(e,()=>this.#C(),()=>this.#j())),this.#I)}async#ze(e,n){let r=this.#re();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="",this.#z();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#C(),getHeaders:()=>this.#C(),...this.#q(),threadId:this.#p,initialMessages:[]});await new Pn({agent:s,handlers:this.#Pe(),getTools:()=>this.getTools(),getContext:()=>this.#ke(),executeTool:l=>this.#Me(l),resolveInterrupts:l=>this.#Le(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Ge(){let e=this.#re();this.#h.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials",...cb]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Ha(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${za.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="placement"){this.#at(),requestAnimationFrame(()=>this.#se());return}if(e==="title-text"){this.#d.textContent=r??this.#e.title;return}n===r||!this.#U||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#t.register(e)}get sharedState(){return this.#N?.state??this.#L}set sharedState(e){this.#L={...e},this.#N?.setState(this.#L)}registerPageState(e){for(let n of Ur(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#Fe(){return this.routeMap.length===0?[]:vs(()=>this.routeMap,()=>this.navigate)}#$e(){let e=this.getPageMap;return e===null?[]:[{name:Ji,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()}]}#Be(){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 fs(n,r=>this.resolvePageTarget(r))}#ve(){return[...this.#Fe(),...this.#$e(),...this.#Be(),...this.#Ve()]}#Ve(){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.#je(e)}]:[]}async#je(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.#_=new AbortController;let i=this.#_.signal;this.#T();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await pa(this.#w(),r,{signal:i,strings:this.#e});return this.#_=null,this.#g(),this.#o.scrollTop=this.#o.scrollHeight,s}#be(e){let n=this.#ve().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 credentials(){let e=this.getAttribute("credentials");return e!==null&&Ha(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Ha(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${za.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#C(){return{...this.headers,...this.getHeaders?.()}}#j(){return this.credentials??void 0}#q(){let e=this.#j();return e===void 0?{}:{credentials:e}}#ye(){return Be({headers:this.#C()},this.#j())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===pn.INLINE||e===pn.MINIMAL||e===pn.COMPACT?e:pn.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#P=this.id!==""?this.id:this.endpoint,this.#ae(this.#Se()),requestAnimationFrame(()=>this.#se()),this.#e=bs({...this.#We(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#le(md);e!==null&&this.setAttribute("theme",e)}this.#gt(),this.#f.setStrings(this.#e),this.#h.setStrings(this.#e),this.#le(hd)==="1"&&this.setAttribute("collapsed",""),this.#Re(),this.#rt(),this.#P!==""&&this.conversationStore instanceof mt&&(this.conversationStore=new mt(this.#P)),this.#nt(),this.#Xe(),this.#Ke(),this.#p=this.conversationStore.threadId(),queueMicrotask(()=>this.#qe()),this.#ce(),this.#U=!0}#qe(){this.#U&&(this.#_e(),this.#Ee())}async reload(){this.#M(),this.#X(),this.#D(!1),await Promise.all([this.#_e(),this.#Ee(),this.#ce()])}disconnectedCallback(){this.#U=!1,this.#M(),this.#m?.dispose(),this.#J?.dispose()}#xe(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#We(){let e=this.getAttribute("data-strings");if(e===null)return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Xe(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ye(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new di({upload:n,maxBytes:this.#Qe(),accept:r,strings:this.#e,onChange:()=>this.#_t(o)});this.#m=o,this.#F.appendChild(this.#m.element),this.#b.accept=r,this.#v.hidden=!1,this.#tt()}#Ye(e){return e===null?null:(n,r,o)=>Ua(n,{url:e,headers:this.#C(),...this.#q(),onProgress:r,signal:o})}#Ke(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Ze(e);n!==null&&(this.#J=new wi({transcribe:n,onText:r=>this.#Je(r),strings:this.#e}),this.#B.appendChild(this.#J.element))}#Ze(e){return e===null?null:n=>Da(n,{url:e,headers:this.#C(),...this.#q()})}#Je(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#Ne(),this.#l.focus()}#Qe(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return es;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:es}#et(){let e=this.#b.files;if(e!==null)for(let n of Array.from(e))this.#m?.add(n);this.#b.value=""}#tt(){this.#i.addEventListener("dragover",e=>{e.preventDefault(),this.#i.classList.add("chat--dragover")}),this.#i.addEventListener("dragleave",()=>{this.#i.classList.remove("chat--dragover")}),this.#i.addEventListener("drop",e=>{e.preventDefault(),this.#i.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#m?.add(r)})}#nt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new vr(e,()=>this.#C(),this.conversationStore,()=>this.#j()))}async#_e(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#ye());this.#n=gs(await n.json())}catch{}}setSkills(e){this.#ge=e,this.#oe()}#rt(){this.#u.enableChips(this.#xe("data-prompt-chips")),this.#u.enableSlash(this.#xe("data-slash-commands")),this.#me=this.#ot(),this.#oe()}#ot(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return rs(JSON.parse(e))}catch{return[]}}async#Ee(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#ye());this.#fe=rs(await n.json()),this.#oe()}catch{}}#oe(){let e=new Map;for(let n of[...this.#fe,...this.#me,...this.#ge])e.set(n.name,n);this.#u.setSkills([...e.values()])}#it(e){if(e.prompt===void 0){this.#x.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=El(e.prompt,this.skillContext());if(r.length>0){this.#x.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#x.hidden=!1,this.#l.value=n,this.#z(),this.#l.focus(),this.#st(n);return}if(this.#x.hidden=!0,this.#l.value=n,this.#z(),e.sendImmediately===!1){this.#l.focus();return}this.#pe()}#st(e){let n=e.indexOf("{");this.#l.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#W(hd),e?"1":"0"),this.#de(0),this.dispatchEvent(new CustomEvent(Wi,{detail:{collapsed:e},bubbles:!0,composed:!0}))}get unread(){return this.#$}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#W(md),e),this.#Ae()}#ie(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#we(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height");this.#ae({width:e.width+1,height:e.height+1});let o=this.getBoundingClientRect();return this.#Te("--ag-ui-width",n),this.#Te("--ag-ui-height",r),{x:Math.abs(o.left-e.left)<.5?"left":"right",y:Math.abs(o.top-e.top)<.5?"top":"bottom"}}#se(){if(!this.#U)return;let e=this.#we();this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`)}#Te(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ae(e){let n=this.#ie();n!=="none"&&(e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&n==="both"&&this.style.setProperty("--ag-ui-height",`${e.height}px`))}#at(){let e=this.#ie();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#lt(e){let n={...this.#Se(),...e};sessionStorage.setItem(this.#W(fd),JSON.stringify(n))}#Se(){let e=this.#le(fd);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#W(e){return this.#P===""?e:`${e}:${this.#P}`}#le(e){let n=sessionStorage.getItem(this.#W(e));return n!==null||this.#P===""?n:sessionStorage.getItem(e)}#Ae(){let e=this.getAttribute("theme")==="dark";this.#S.textContent=e?"\u2600\uFE0F":"\u{1F319}"}openThreads(){this.#Y(),this.#f.open()}openCheckpoints(){this.#Ge(),this.#h.open()}newChat(){this.#M(),this.conversationStore.clear(this.#p),this.#X(),this.#p=this.conversationStore.threadId(),this.#D(!1),this.#de(0)}#X(){this.#N=null,this.#E=null,this.#k=null,this.#O=null,this.#T(),this.#s.clear(),this.#r.clear(),this.#ne=[],this.#m?.clear(),this.#o.replaceChildren(this.#R),this.#g()}async#ct(e){e!==this.#p&&(this.#M(),this.#X(),this.conversationStore.setActiveThread(e),this.#p=e,this.#D(!1),await this.#ce())}#ut(e){let n=e===this.#p;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#X(),this.#p=this.conversationStore.threadId(),this.#D(!1)),this.#Y()}async#Y(){this.#f.setThreads(await this.conversationStore.listThreads(),this.#p)}async#ce(){this.#te+=1;let e=this.#te,n=await this.conversationStore.loadMessages(this.#p);if(e!==this.#te)return;if(n!==null){this.#ne=n;for(let o of n)this.#ht(o)}let r=this.conversationStore.loadCheckpoint(this.#p);if(r!==null){await this.#mt(r);return}this.#pt(n)}#ke(){return this.#Q=window.location.href,this.getContext()}#dt(){return this.#Q!==null&&this.#Q!==window.location.href}#pt(e){let n=e?.at(-1);n===void 0||n.role!==je.USER||this.#Z("\u26A0",this.#e.runInterrupted,"interrupted")}#ht(e){let n=typeof e.content=="string"?e.content:"";if(e.role===je.USER){let r=Oa(e);if(n!==""||r.length>0){let o=this.appendMessage(je.USER,n);r.length>0&&o.appendChild(_s(r))}return}if(e.role===je.ASSISTANT){n!==""&&this.appendMessage(je.ASSISTANT,n).classList.add("message--restored");for(let r of ub(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#ft(r.function.arguments)};this.#He(o)||this.#he(o)}return}if(e.role==="tool"){let r=this.#s.get(e.toolCallId);r!==void 0&&r.settle(pe.DONE,e.content)}}#ft(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Ce(e){this.getAttribute("data-text-animation")==="word"&&sd(e)}async#mt(e){this.conversationStore.saveCheckpoint(this.#p,null);let n=this.#Oe();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===je.ASSISTANT?(r.innerHTML=yi(n,{allowImages:this.allowImages}),xs(r,this.#e),this.#w().appendChild(r)):(this.#k=null,r.textContent=n,this.#o.appendChild(r)),this.#g(),this.#o.scrollTop=this.#o.scrollHeight,r}#w(){if(this.#k===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#k=e,this.#o.appendChild(e),this.#g()}return this.#k}#gt(){let e=document.createElement("style");e.textContent=ld,this.#i.className="chat",this.#i.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#d;r.className="header-title",r.setAttribute("part","title"),r.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&n.append(this.#Ie("icon","icon",null));let 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.#K("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>this.openThreads());let a=this.#K("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>this.openCheckpoints());let l=this.#K("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#K("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#re()!==null?i.append(s,a,l):i.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#S.type="button",this.#S.className="header-btn header-btn--theme",this.#S.setAttribute("part","header-button theme-toggle"),this.#S.title=this.#e.toggleTheme,this.#S.setAttribute("aria-label",this.#e.toggleTheme),this.#S.addEventListener("click",()=>this.toggleTheme()),this.#Ae(),i.append(this.#S)),i.append(c),n.append(r,o,i),this.#o.className="messages",this.#o.setAttribute("part","messages"),this.#o.setAttribute("role","log"),this.#o.setAttribute("aria-live","polite"),this.#o.setAttribute("aria-label",this.#e.conversation),this.#R.className="empty",this.#R.setAttribute("part","empty");let h=document.createElement("slot");h.name="empty",this.#R.append(h),this.#o.append(this.#R);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let y=document.createElement("div");y.className="composer",y.setAttribute("part","composer-surface");let f=document.createElement("div");f.className="composer-tools",f.setAttribute("part","composer-tools"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=1,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",g=>this.#xt(g)),this.#l.addEventListener("input",()=>this.#Ne()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.append(this.#ue("icon-send","send-send",hl),this.#ue("icon-stop","send-stop",fl)),this.#c.title=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.#pe()}),this.#x.className="skill-hint",this.#x.setAttribute("part","skill-hint"),this.#x.hidden=!0,this.#v.className="attach-btn",this.#v.type="button",this.#v.setAttribute("part","attach-button"),this.#v.append(this.#ue("icon-attach","attach-glyph",ml)),this.#v.title=this.#e.attachFiles,this.#v.setAttribute("aria-label",this.#e.attachFiles),this.#v.hidden=!0,this.#v.addEventListener("click",()=>this.#b.click()),this.#b.className="attach-input",this.#b.type="file",this.#b.multiple=!0,this.#b.hidden=!0,this.#b.addEventListener("change",()=>this.#et()),this.#F.className="attachment-slot",this.#B.className="voice-slot";let p=document.createElement("slot");p.name="footer",f.append(this.#v,this.#B,this.#c),y.append(this.#l,f),m.append(y,this.#b),this.#i.append(n,this.#o,this.#u.palette,this.#u.chips,this.#x,this.#F,m,p,this.#f.element,this.#h.element),this.#y.className="launcher",this.#y.type="button",this.#y.setAttribute("part","launcher"),this.#y.setAttribute("aria-label",this.#e.expand),this.#A.className="launcher-badge",this.#A.setAttribute("part","launcher-badge"),this.#A.setAttribute("aria-hidden","true"),this.#A.hidden=!0,this.#y.append(this.#Ie("launcher","launcher-icon",vl,this.#vt()),this.#A),this.#y.addEventListener("click",()=>this.setCollapsed(!1)),this.#i.append(od({axis:()=>this.#ie(),anchor:()=>this.#we(),rect:()=>this.getBoundingClientRect(),apply:g=>this.#ae(g),commit:g=>{this.#lt(g),this.#se()},label:this.#e.resizePanel})),this.#a.append(e,this.#i,this.#y)}#K(e,n,r){let o=document.createElement("button");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);let i=document.createElement("slot");return i.name=`icon-${e}`,i.append(document.createTextNode(r)),o.append(i),o}#ue(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#vt(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#Ie(e,n,r,o=this.getAttribute("data-icon-url")){let i=document.createElement("span");i.className="icon-holder",i.setAttribute("part",n);let s=document.createElement("slot");if(s.name=e,o!==null){let a=document.createElement("img");a.className="icon-img",a.src=o,a.alt="",s.append(a)}else r!==null&&(s.innerHTML=r);return i.append(s),i}#Re(){this.#y.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#$;this.#A.textContent=e>9?"9+":String(e),this.#A.hidden=e===0||!this.#bt();let n=this.#A.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#y.setAttribute("aria-label",n),this.#y.title=n}#bt(){return this.getAttribute("data-unread-badge")!=="false"}#de(e){this.#$=e,this.#Re(),this.dispatchEvent(new CustomEvent(Xi,{detail:{unread:e},bubbles:!0,composed:!0}))}#yt(){this.collapsed&&this.#de(this.#$+1)}#g(){this.#R.hidden=this.#o.childElementCount>1}#Ne(){this.#u.onInput(this.#l.value),this.#x.hidden=!0,this.#z()}#xt(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.#pe())}#M(){this.#_?.abort(),this.#N?.cancel()}#D(e){this.#H=e;let n=e?this.#e.stop:this.#e.send;this.#c.title=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}#z(){this.#l.style.height="auto",this.#l.style.height=`${this.#l.scrollHeight}px`}async#pe(){if(this.#H)return;let e=this.#l.value.trim(),n=this.#m?.readyRefs()??[];e===""&&n.length===0||(this.#l.value="",this.#z(),this.#m?.hasPending()===!0&&this.#Z("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#m.pendingCount())),"attachment-pending"),this.#m?.clearReady(),await this.sendMessage(e,n))}async sendMessage(e,n=[]){if(this.#H||e===""&&n.length===0)return;let r=this.appendMessage(je.USER,e);n.length>0&&r.appendChild(_s(n)),this.dispatchEvent(new CustomEvent(qi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#Et(e,n)}attachFile(e){return this.#m===null?!1:(this.#m.add(e),!0)}#_t(e){this.dispatchEvent(new CustomEvent(Ki,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#Et(e,n){this.endpoint!==""&&await this.#Oe().send(e,n)}#Oe(){if(this.#N===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#C(),getHeaders:()=>this.#C(),...this.#q(),threadId:this.#p,initialMessages:this.#ne,initialState:this.#L});this.#N=new Pn({agent:e,handlers:this.#Pe(),getTools:()=>this.getTools(),getContext:()=>this.#ke(),executeTool:n=>this.#Me(n),resolveInterrupts:n=>this.#Le(n),onPersist:n=>this.conversationStore.saveMessages(this.#p,n),onStateChanged:n=>this.#wt(n),connectionLostMessage:this.#e.connectionLost})}return this.#N}#wt(e){this.#L={...e},this.dispatchEvent(new CustomEvent(Yi,{detail:{state:this.#L},bubbles:!0,composed:!0}))}async#Tt(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:os(n.parameters)}async#Me(e){if(gd(e)!==null)return null;let n=this.#he(e);this.#s.delete(e.id);let r=this.#be(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!==Ji&&!Mr(r.parameters)&&this.#dt()){let i=this.#e.pageMoved;return n.settle(pe.ERROR,i),this.#G(),{content:`Error: ${i}`,error:i}}if(await this.#Tt(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Zi];typeof s=="string"&&(i.message=s),this.#_=new AbortController;let a=ua(this.#w(),i,{signal:this.#_.signal,strings:this.#e});this.#g(),this.#o.scrollTop=this.#o.scrollHeight;let l=await a;if(this.#_=null,n.recordDecision(l?"approved":"declined"),!l){let c=this.#e.declinedAction;return n.settle(pe.DECLINED,c),this.#G(),{content:c}}}let o=Mr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#p,{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.#G(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#p,null);let s=i instanceof Error?i.message:String(i);return n.settle(pe.ERROR,s),this.#G(),{content:`Error: ${s}`,error:s}}}async#Le(e){let n={};this.#_=new AbortController,this.#T();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#s.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#_.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await ys(this.#w(),o,{signal:a,strings:this.#e});this.#g(),this.#o.scrollTop=this.#o.scrollHeight,i?.recordDecision(l?"approved":"declined"),l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(pe.DECLINED,this.#e.declinedAction))}return this.#_=null,n}#Pe(){return{onRunStart:()=>{this.#D(!0),this.#w(),this.#G()},onReasoningStart:()=>{this.#T(),this.#De()},onReasoningDelta:e=>{this.#De().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#T(),this.#O?.collapse(),this.#Ue(e),this.#ee+=1},onTextEnd:e=>{let n=this.#Ue(e);this.#ee<=1&&this.#Ce(n),xs(n,this.#e),this.#E=null,this.#yt()},onToolCall:e=>{this.#T(),!this.#He(e)&&this.#he(e)},onActivity:(e,n)=>{if(e!==ts)return;let r=pb(n);r!==null&&this.#Z("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#s.get(e);r!==void 0&&(r.settle(pe.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#T(),this.#E=null},onError:e=>{this.#T(),this.#Ce(this.appendMessage(je.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#E=null},onCancelled:()=>{this.#T(),this.#St(),this.#E=null},onSettled:()=>{this.#T(),this.#D(!1),this.#E=null;for(let e of this.#s.values())e.settled||e.settle(pe.DONE,this.#e.noResult);this.#k!==null&&this.#k.childElementCount===0&&(this.#k.remove(),this.#g()),this.#k=null,this.#O=null}}}#St(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#w().appendChild(e),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}#G(){if(this.#V!==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.#V=e,this.#w().appendChild(e),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}#T(){this.#V?.remove(),this.#V=null}#De(){if(this.#O===null){this.#O=new _i(this.#e);let e=this.#w();e.insertBefore(this.#O.element,e.firstChild),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}return this.#O}#Ue(e){return this.#E===null&&(this.#E=this.appendMessage(je.ASSISTANT,""),this.#ee=0),this.#E.innerHTML=yi(e,{allowImages:this.allowImages}),this.#o.scrollTop=this.#o.scrollHeight,this.#E}#He(e){let n=gd(e);return n===null?!1:(this.#Z("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#Z(e,n,r){this.#w().appendChild(ad(e,n,r)),this.#g(),this.#o.scrollTop=this.#o.scrollHeight}#he(e){let n=this.#s.get(e.id);if(n!==void 0)return n;let r=this.#be(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??da(e.name),i=new mr(e.name,e.args,o,this.#e);return this.#s.set(e.id,i),this.#w().appendChild(i.element),this.#g(),this.#o.scrollTop=this.#o.scrollHeight,i}};function ub(t){return Array.isArray(t)?t.filter(db):[]}function db(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function gd(t){if(t.name!==ns)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function pb(t){let e=t?.removed;return typeof e=="number"?e:null}function hb(){customElements.get(Or)===void 0&&customElements.define(Or,yr)}async function fb(t,e,n={}){await lt(t),await cs(t,{...n,flashMs:n.flashMs??0}),await as(t,e,n)}async function mb(t,e={}){await lt(t),await ls(t,e)}async function gb(t,e={}){await lt(t),await us(t,e)}async function vb(t,e,n={}){await lt(t),await ds(t,e,n)}async function bb(t,e,n={}){await lt(t),await ps(t,e,n)}function yb(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Vn(t,!!e):Nt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var xb="0.23.1";export{Ki as ATTACHMENT_EVENT,yr as AgUiChat,Pn as AgUiClient,ts as COMPACTION_ACTIVITY_TYPE,ar as CheckpointMenu,Bn as ClientToolRegistry,Ti as ConnectionLostError,ae as DEFAULT_UI_STRINGS,Or as ELEMENT_TAG,ns as LOAD_CAPABILITY_TOOL,Qi as MAX_TOOL_ROUNDS,je as MESSAGE_ROLE,hs as PAGE_ACTIONS,vr as RemoteConversationStore,br as RunIndex,Yi as STATE_EVENT,qi as SUBMIT_EVENT,mt as SessionStorageStore,Wi as TOGGLE_EVENT,pe as TOOL_CALL_STATUS,pn as TOOL_DISPLAY,mr as ToolCallCard,Xi as UNREAD_EVENT,xb as VERSION,Zi as X_CONFIRM_KEY,Fn as X_DESTRUCTIVE_KEY,$n as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,mb as clickElement,Pa as createHttpAgent,fs as createPageActionTools,ms as createPageMapContext,Ur as createPageStateTools,vs as createRouteTools,cp as createStateHookTools,hb as defineAgUiChat,fb as fillField,op as flash,cs as focusWithFlash,ls as highlightThenClick,os as isDestructive,Mr as isNavigates,bs as mergeUiStrings,Oa as messageAttachments,gs as parseToolCatalog,Pr as prefersReducedMotion,gb as pressButton,us as pressThenClick,da as prettifyToolName,yi as renderMarkdown,ys as requestApproval,ua as requestConfirmation,pa as requestQuestion,lt as scrollIntoCenterView,vb as selectControl,ds as selectOption,yb as setControlValue,Vn as setNativeChecked,Nt as setNativeValue,bb as toggleCheckbox,ps as toggleControl,Da as transcribeAudio,as as typeInto,Ua as uploadAttachment};
|
|
2245
2226
|
/*! Bundled license information:
|
|
2246
2227
|
|
|
2247
2228
|
fast-json-patch/module/helpers.mjs:
|