@artooi/ag-ui-web-component 0.25.1 → 0.25.2

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 CHANGED
@@ -7,6 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.25.2] — 2026-08-25
11
+
12
+ ### Fixed
13
+
14
+ - **A server-side tool round went silent between the tool card and the answer.**
15
+ The pending indicator is hidden when a tool call arrives, so the card can be
16
+ the live thing on screen. Client-side tools put it back before returning their
17
+ result; the server-side path never did — so once a streamed result settled the
18
+ card, the wait while the server called the model again had nothing to own it.
19
+ With a large attachment inlined into the tool result, and re-sent with every
20
+ subsequent request, that is the longest pause in a run.
21
+
22
+ The indicator now returns when a streamed result settles a card, and is
23
+ cleared by whatever comes next: reasoning, the first text delta, the round
24
+ ending, or the terminal settle guarantee. This is not the case 0.2.1 removed
25
+ it for — that one runs after the run has ended, where nothing would clear it.
26
+ The terminal guarantee that shipped in the same release is what makes showing
27
+ it here safe.
28
+
10
29
  ## [0.25.1] — 2026-08-24
11
30
 
12
31
  ### Fixed
@@ -1554,7 +1573,8 @@ hosts that both arrange the page the way it expects.
1554
1573
  ### Notes
1555
1574
  - First release — exercising the automated npm OIDC publish pipeline end-to-end.
1556
1575
 
1557
- [Unreleased]: https://github.com/Artui/ag-ui-web-component/compare/v0.25.1...HEAD
1576
+ [Unreleased]: https://github.com/Artui/ag-ui-web-component/compare/v0.25.2...HEAD
1577
+ [0.25.2]: https://github.com/Artui/ag-ui-web-component/compare/v0.25.1...v0.25.2
1558
1578
  [0.25.1]: https://github.com/Artui/ag-ui-web-component/compare/v0.25.0...v0.25.1
1559
1579
  [0.25.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.24.0...v0.25.0
1560
1580
  [0.24.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.23.1...v0.24.0
@@ -2357,7 +2357,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
2357
2357
  border-right: none;
2358
2358
  box-shadow: none;
2359
2359
  }
2360
- `;var wi=class{element;#n;#e;#t;#o;#r=!1;constructor(e=le){this.#o=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.setAttribute("part","thoughts-label"),this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#a(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#o.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var Ti=class{element;#n;#e;#t;#o;#r;#a;#l=[];#c="";#i=null;constructor(e,n=le){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.#o=document.createElement("button"),this.#o.type="button",this.#o.className="drawer-new",this.#o.setAttribute("part","drawer-new"),this.#o.textContent=n.newChat,this.#o.addEventListener("click",()=>{this.close(),this.#n.onNew()}),o.append(this.#t,this.#o),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(o,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#a=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#o.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#i=this.#s(),this.element.hidden=!1,this.#o.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#i?.focus(),this.#i=null)}toggle(){this.isOpen()?this.close():this.open()}#s(){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.#s();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#l=e,this.#c=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#l.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.#l)this.#r.appendChild(this.#p(e))}#p(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#c&&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=fi(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.#f(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()}#f(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 La(t){return{[ee.PENDING]:t.toolRunning,[ee.DEFERRED]:t.toolDeferred,[ee.DONE]:t.toolDone,[ee.ERROR]:t.toolError,[ee.DECLINED]:t.toolDeclined}}function tb(t){return{[ee.DONE]:t.resultLabel,[ee.ERROR]:t.errorLabel,[ee.DECLINED]:t.declinedLabel}}function nb(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var mr=class{element;approvalSlot;#n;#e;#t;#o;#r;#a;#l;#c=!1;constructor(e,n,r,o=le){this.#l=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",ee.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=La(o)[ee.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.#i("args",o.argumentsLabel);l.body.textContent=JSON.stringify(n,null,2),l.root.hidden=Object.keys(n).length===0;let c=this.#i("result",o.resultLabel);this.#o=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.#s()));let p=document.createElement("div");p.className="tool-call-body",p.setAttribute("part","tool-card-body"),p.append(l.root,c.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.element.append(i,this.#t,p,this.approvalSlot)}mark(e){this.#c||(this.element.setAttribute("data-status",e),this.#n.textContent=La(this.#l)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#e.textContent=e==="approved"?this.#l.decisionApproved:this.#l.decisionDeclined,this.#e.hidden=!1}get settled(){return this.#c}settle(e,n){this.#c||(this.#c=!0,this.element.setAttribute("data-status",e),this.#n.textContent=La(this.#l)[e],this.#r.textContent=tb(this.#l)[e],this.#a.textContent=nb(n),this.#o.hidden=!1)}#i(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}}#s(){return this.element.getAttribute("data-expanded")==="true"}#d(e){this.element.setAttribute("data-expanded",String(e)),this.#t.setAttribute("aria-expanded",String(e))}};var Si=class{element;#n;#e;#t;#o="idle";#r=null;#a=null;#l=[];#c=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??le,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=yl,this.element.append(n),this.#h("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#o==="recording"){this.#s();return}this.#o!=="transcribing"&&await this.#i()}async#i(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#p(this.#t.transcriptionFailed);return}this.#a=e,this.#l=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#l.push(r.data)}),n.addEventListener("stop",()=>{this.#d(n.mimeType)}),this.#r=n,n.start(),this.#h("recording")}#s(){this.#r?.stop()}dispose(){this.#c=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#d(e){if(this.#c)return;this.#u(),this.#h("transcribing");let n=new Blob(this.#l,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#h("idle"),r!==""&&this.#e(r)}catch(r){this.#p(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}#p(e){this.#u(),this.#r=null,this.#h("idle"),this.element.title=e}#h(e){this.#o=e,this.element.dataset.state=e;let n=this.#f(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#f(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var Ai=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Pn=class{#n;#e;#t;#o;#r;#a;#l;#c=new Set;#i;#s=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#o=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#l=e.onPersist??(()=>{}),this.#i=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Ue(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#l(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.#l(this.#n.messages)}cancel(){this.#s=!0,this.#n.abortRun()}async#d(){this.#s=!1;try{await this.#p(),this.#s&&this.#u()}catch(e){this.#s||rb(e)?this.#u():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#u(){this.#l(this.#n.messages),this.#e.onCancelled()}async#p(){let e;for(let n=0;n<ts;n+=1){if(this.#s)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#o()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#l(this.#n.messages),this.#s)return;if(!o.terminal)throw new Ai(this.#i);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#s)return;e=xd(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.#l(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e,o=this.#c;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 rb(t){return t instanceof Error&&t.name==="AbortError"}function Pa(t){let e=t.attachments;return Array.isArray(e)?e.filter(ob):[]}function ob(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 Da="ag-ui-chat",gr="thread",Ua="threads",vr="messages:",Ii="checkpoint:",ki="minted:",ib=60,sb=100,ab="New conversation",mt=class{#n;constructor(e=""){this.#n=e===""?Da:`${Da}@${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),sessionStorage.setItem(this.#r(ki+r),"1"),r}isUnsent(e){return sessionStorage.getItem(this.#r(ki+e))!==null&&sessionStorage.getItem(this.#r(vr+e))===null}loadMessages(e){return Promise.resolve(this.#l(this.#r(vr+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(vr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(ki+e)),this.#e(e,n)}loadCheckpoint(e){return this.#l(this.#r(Ii+e))}saveCheckpoint(e,n){let r=this.#r(Ii+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(vr+e)),sessionStorage.removeItem(this.#r(Ii+e)),sessionStorage.removeItem(this.#r(ki+e)),this.#o(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.#o(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=cb(n),s=Date.now();o===void 0?r.push({threadId:e,title:fu(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=fu(n))),this.#o(r)}#t(){return this.#l(this.#r(Ua))??[]}#o(e){let n=this.#r(Ua);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Da}:`,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);lb(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)}}#l(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function lb(t){return t===gr||t===Ua||t.startsWith(vr)||t.startsWith(Ii)}function fu(t){for(let e of t)if(e.role==="user"){let n=mu(e.content);if(n!=="")return gu(n,ib)}return ab}function cb(t){for(let e of[...t].reverse()){let n=mu(e.content);if(n!=="")return gu(n,sb)}return""}function mu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function gu(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 Ha(t){return new _d({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 br=class{#n;#e;#t;#o;#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.#o=o}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}isUnsent(e){return this.#t.isUnsent?.(e)===!0}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.#l();return e===null?this.#t.listThreads():e.filter(n=>!this.#r.has(n.thread_id)).map(n=>this.#i(n))}async loadMessages(e){if(this.#t.isUnsent?.(e)===!0)return null;let n=await this.#s(`${this.#n}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#c(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#l(){let e=await this.#s(this.#n);if(e===null||!e.ok)return null;let n=await this.#c(e);return n===null?null:n.threads??[]}async#c(e){try{return await e.json()}catch{return null}}#i(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#s(e){try{return await fetch(e,Be({headers:this.#e()},this.#o()))}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.#o()))}catch{}}};var yr=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.#o("resume",e)}forkUrl(e){return this.#o("fork",e)}#o(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function za(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 db(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 db(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Fa(t,e){return new Promise((n,r)=>{let 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(ub(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(pb(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 ub(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 pb(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var hb=["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"],$a=["omit","same-origin","include"];function Ga(t){return $a.includes(t)}var vu="ag-ui-chat:collapsed",bu="ag-ui-chat:size",yu="ag-ui-chat:theme",xr=class extends HTMLElement{agentFactory=Ha;headers={};getHeaders=null;allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#be().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...vs(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=le;#t=new Bn;#o=new Map;#r=new Set;#a=[];#l;#c;#i;#s;#d;#u;#p;#h;#f;#J=null;#_;#b;#y;#G;#A;#x;#k;#$=0;#R;#g=null;#B;#Q=null;#U=!1;#N=null;#L={};#H=!1;#ee=null;#E=null;#w=null;#te=0;#V=null;#I=null;#O=null;#m="";#P="";#ne=0;#re=[];#me=[];#ge=[];#ve=[];constructor(){super(),this.#l=this.attachShadow({mode:"open"}),this.#c=document.createElement("div"),this.#i=document.createElement("div"),this.#s=document.createElement("textarea"),this.#d=document.createElement("button"),this.#u=document.createElement("span"),this.#_=document.createElement("div"),this.#b=document.createElement("button"),this.#y=document.createElement("input"),this.#G=document.createElement("div"),this.#B=document.createElement("span"),this.#A=document.createElement("button"),this.#x=document.createElement("button"),this.#k=document.createElement("span"),this.#R=document.createElement("div"),this.#p=new Ei(e=>this.#st(e)),this.#h=new Ti({onSelect:e=>{this.#dt(e)},onNew:()=>{this.newChat(),this.#Y()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Y()},onDelete:e=>{this.#ut(e)}}),this.#f=new ar((e,n)=>{this.#Fe(e,n)})}#oe(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#J===null&&(this.#J=new yr(e,()=>this.#C(),()=>this.#j())),this.#J)}async#Fe(e,n){let r=this.#oe();if(r===null)return;let o=this.#s.value.trim();if(o==="")return;this.#s.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.#m,initialMessages:[]});await new Pn({agent:s,handlers:this.#De(),getTools:()=>this.getTools(),getContext:()=>this.#Ie(),executeTool:l=>this.#Le(l),resolveInterrupts:l=>this.#Pe(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Ge(){let e=this.#oe();this.#f.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials",...hb]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Ga(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${$a.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.#lt(),requestAnimationFrame(()=>this.#ae());return}if(e==="title-text"){this.#u.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 zr(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#$e(){return this.routeMap.length===0?[]:ys(()=>this.routeMap,()=>this.navigate)}#Be(){let e=this.getPageMap;return e===null?[]:[{name:es,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()}]}#Ve(){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 gs(n,r=>this.resolvePageTarget(r))}#be(){return[...this.#$e(),...this.#Be(),...this.#Ve(),...this.#je()]}#je(){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.#qe(e)}]:[]}async#qe(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.#E=new AbortController;let i=this.#E.signal;this.#S();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await fa(this.#T(),r,{signal:i,strings:this.#e});return this.#E=null,this.#v(),this.#i.scrollTop=this.#i.scrollHeight,s}#ye(e){let n=this.#be().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&&Ga(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Ga(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${$a.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}}#xe(){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.#le(this.#Ae()),requestAnimationFrame(()=>this.#ae()),this.#e=xs({...this.#Xe(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#ce(yu);e!==null&&this.setAttribute("theme",e)}this.#vt(),this.#h.setStrings(this.#e),this.#f.setStrings(this.#e),this.#ce(vu)==="1"&&this.setAttribute("collapsed",""),this.#Ne(),this.#ot(),this.#P!==""&&this.conversationStore instanceof mt&&(this.conversationStore=new mt(this.#P)),this.#rt(),this.#Ye(),this.#Ze(),this.#m=this.conversationStore.threadId(),queueMicrotask(()=>this.#We()),this.#de(),this.#U=!0}#We(){this.#U&&(this.#Ee(),this.#we())}async reload(){this.#M(),this.#X(),this.#D(!1),await Promise.all([this.#Ee(),this.#we(),this.#de()])}disconnectedCallback(){this.#U=!1,this.#M(),this.#g?.dispose(),this.#Q?.dispose()}#_e(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#Xe(){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{}}#Ye(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ke(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new hi({upload:n,maxBytes:this.#et(),accept:r,strings:this.#e,onChange:()=>this.#Et(o)});this.#g=o,this.#G.appendChild(this.#g.element),this.#y.accept=r,this.#b.hidden=!1,this.#nt()}#Ke(e){return e===null?null:(n,r,o)=>Fa(n,{url:e,headers:this.#C(),...this.#q(),onProgress:r,signal:o})}#Ze(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Je(e);n!==null&&(this.#Q=new Si({transcribe:n,onText:r=>this.#Qe(r),strings:this.#e}),this.#B.appendChild(this.#Q.element))}#Je(e){return e===null?null:n=>za(n,{url:e,headers:this.#C(),...this.#q()})}#Qe(e){let n=this.#s.value.trim();this.#s.value=n===""?e:`${n} ${e}`,this.#Oe(),this.#s.focus()}#et(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return ns;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:ns}#tt(){let e=this.#y.files;if(e!==null)for(let n of Array.from(e))this.#g?.add(n);this.#y.value=""}#nt(){this.#c.addEventListener("dragover",e=>{e.preventDefault(),this.#c.classList.add("chat--dragover")}),this.#c.addEventListener("dragleave",()=>{this.#c.classList.remove("chat--dragover")}),this.#c.addEventListener("drop",e=>{e.preventDefault(),this.#c.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#g?.add(r)})}#rt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new br(e,()=>this.#C(),this.conversationStore,()=>this.#j()))}async#Ee(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#xe());this.#n=bs(await n.json())}catch{}}setSkills(e){this.#ve=e,this.#ie()}#ot(){this.#p.enableChips(this.#_e("data-prompt-chips")),this.#p.enableSlash(this.#_e("data-slash-commands")),this.#ge=this.#it(),this.#ie()}#it(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return is(JSON.parse(e))}catch{return[]}}async#we(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#xe());this.#me=is(await n.json()),this.#ie()}catch{}}#ie(){let e=new Map;for(let n of[...this.#me,...this.#ge,...this.#ve])e.set(n.name,n);this.#p.setSkills([...e.values()])}#st(e){if(e.prompt===void 0){this.#_.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=Sl(e.prompt,this.skillContext());if(r.length>0){this.#_.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#_.hidden=!1,this.#s.value=n,this.#z(),this.#s.focus(),this.#at(n);return}if(this.#_.hidden=!0,this.#s.value=n,this.#z(),e.sendImmediately===!1){this.#s.focus();return}this.#he()}#at(e){let n=e.indexOf("{");this.#s.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(vu),e?"1":"0"),this.#pe(0),this.dispatchEvent(new CustomEvent(Yi,{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(yu),e),this.#ke()}#se(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#Te(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height");this.#le({width:e.width+1,height:e.height+1});let o=this.getBoundingClientRect();return this.#Se("--ag-ui-width",n),this.#Se("--ag-ui-height",r),{x:Math.abs(o.left-e.left)<.5?"left":"right",y:Math.abs(o.top-e.top)<.5?"top":"bottom"}}#ae(){if(!this.#U)return;let e=this.#Te();this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`)}#Se(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#le(e){let n=this.#se();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`))}#lt(){let e=this.#se();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#ct(e){let n={...this.#Ae(),...e};sessionStorage.setItem(this.#W(bu),JSON.stringify(n))}#Ae(){let e=this.#ce(bu);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}`}#ce(e){let n=sessionStorage.getItem(this.#W(e));return n!==null||this.#P===""?n:sessionStorage.getItem(e)}#ke(){let e=this.getAttribute("theme")==="dark";this.#A.textContent=e?"\u2600\uFE0F":"\u{1F319}"}openThreads(){this.#f.close(),this.#Y(),this.#h.open()}openCheckpoints(){this.#h.close(),this.#Ge(),this.#f.open()}closeCheckpoints(){this.#f.close()}toggleCheckpoints(){if(this.#f.open_){this.#f.close();return}this.openCheckpoints()}newChat(){this.#M(),this.conversationStore.clear(this.#m),this.#X(),this.#m=this.conversationStore.threadId(),this.#D(!1),this.#pe(0)}#X(){this.#N=null,this.#w=null,this.#I=null,this.#O=null,this.#S(),this.#o.clear(),this.#r.clear(),this.#re=[],this.#g?.clear(),this.#i.replaceChildren(this.#R),this.#v()}async#dt(e){e!==this.#m&&(this.#M(),this.#X(),this.conversationStore.setActiveThread(e),this.#m=e,this.#D(!1),await this.#de())}#ut(e){let n=e===this.#m;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#X(),this.#m=this.conversationStore.threadId(),this.#D(!1)),this.#Y()}async#Y(){this.#h.setThreads(await this.conversationStore.listThreads(),this.#m)}async#de(){this.#ne+=1;let e=this.#ne,n=await this.conversationStore.loadMessages(this.#m);if(e!==this.#ne)return;if(n!==null){this.#re=n;for(let o of n)this.#ft(o)}let r=this.conversationStore.loadCheckpoint(this.#m);if(r!==null){await this.#gt(r);return}this.#ht(n)}#Ie(){return this.#ee=window.location.href,this.getContext()}#pt(){return this.#ee!==null&&this.#ee!==window.location.href}#ht(e){let n=e?.at(-1);n===void 0||n.role!==je.USER||this.#Z("\u26A0",this.#e.runInterrupted,"interrupted")}#ft(e){let n=typeof e.content=="string"?e.content:"";if(e.role===je.USER){let r=Pa(e);if(n!==""||r.length>0){let o=this.appendMessage(je.USER,n);r.length>0&&o.appendChild(ws(r))}return}if(e.role===je.ASSISTANT){n!==""&&this.appendMessage(je.ASSISTANT,n).classList.add("message--restored");for(let r of mb(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#mt(r.function.arguments)};this.#ze(o)||this.#fe(o)}return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(ee.DONE,e.content)}}#mt(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"&&uu(e)}async#gt(e){this.conversationStore.saveCheckpoint(this.#m,null);let n=this.#Me();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=_i(n,{allowImages:this.allowImages}),Es(r,this.#e),this.#T().appendChild(r)):(this.#I=null,r.textContent=n,this.#i.appendChild(r)),this.#v(),this.#i.scrollTop=this.#i.scrollHeight,r}#T(){if(this.#I===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#I=e,this.#i.appendChild(e),this.#v()}return this.#I}#vt(){let e=document.createElement("style");e.textContent=hu,this.#c.className="chat",this.#c.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#u;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.#Re("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,"\u21BA");a.addEventListener("click",()=>this.toggleCheckpoints());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.#oe()!==null?i.append(s,a,l):i.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#A.type="button",this.#A.className="header-btn header-btn--theme",this.#A.setAttribute("part","header-button theme-toggle"),this.#A.title=this.#e.toggleTheme,this.#A.setAttribute("aria-label",this.#e.toggleTheme),this.#A.addEventListener("click",()=>this.toggleTheme()),this.#ke(),i.append(this.#A)),i.append(c),n.append(r,o,i),this.#i.className="messages",this.#i.setAttribute("part","messages"),this.#i.setAttribute("role","log"),this.#i.setAttribute("aria-live","polite"),this.#i.setAttribute("aria-label",this.#e.conversation),this.#R.className="empty",this.#R.setAttribute("part","empty");let p=document.createElement("slot");p.name="empty",this.#R.append(p),this.#i.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.#s.className="input",this.#s.setAttribute("part","input"),this.#s.setAttribute("aria-label",this.#e.message),this.#s.rows=1,this.#s.placeholder=this.#e.inputPlaceholder,this.#s.addEventListener("keydown",g=>this.#_t(g)),this.#s.addEventListener("input",()=>this.#Oe()),this.#d.className="send",this.#d.type="button",this.#d.setAttribute("part","send"),this.#d.append(this.#ue("icon-send","send-send",gl),this.#ue("icon-stop","send-stop",vl)),this.#d.title=this.#e.send,this.#d.setAttribute("aria-label",this.#e.send),this.#d.dataset.state="idle",this.#d.addEventListener("click",()=>{if(this.#H){this.#M();return}this.#he()}),this.#_.className="skill-hint",this.#_.setAttribute("part","skill-hint"),this.#_.hidden=!0,this.#b.className="attach-btn",this.#b.type="button",this.#b.setAttribute("part","attach-button"),this.#b.append(this.#ue("icon-attach","attach-glyph",bl)),this.#b.title=this.#e.attachFiles,this.#b.setAttribute("aria-label",this.#e.attachFiles),this.#b.hidden=!0,this.#b.addEventListener("click",()=>this.#y.click()),this.#y.className="attach-input",this.#y.type="file",this.#y.multiple=!0,this.#y.hidden=!0,this.#y.addEventListener("change",()=>this.#tt()),this.#G.className="attachment-slot",this.#B.className="voice-slot";let h=document.createElement("slot");h.name="footer",f.append(this.#b,this.#B,this.#d),y.append(this.#s,f),m.append(y,this.#y),this.#c.append(n,this.#i,this.#p.palette,this.#p.chips,this.#_,this.#G,m,h,this.#h.element,this.#f.element),this.#c.addEventListener("pointerdown",g=>{if(!this.#f.open_)return;let x=g.composedPath();x.includes(this.#f.element)||x.includes(a)||this.#f.close()}),this.#x.className="launcher",this.#x.type="button",this.#x.setAttribute("part","launcher"),this.#x.setAttribute("aria-label",this.#e.expand),this.#k.className="launcher-badge",this.#k.setAttribute("part","launcher-badge"),this.#k.setAttribute("aria-hidden","true"),this.#k.hidden=!0,this.#x.append(this.#Re("launcher","launcher-icon",xl,this.#bt()),this.#k),this.#x.addEventListener("click",()=>this.setCollapsed(!1)),this.#c.append(cu({axis:()=>this.#se(),anchor:()=>this.#Te(),rect:()=>this.getBoundingClientRect(),apply:g=>this.#le(g),commit:g=>{this.#ct(g),this.#ae()},label:this.#e.resizePanel})),this.#l.append(e,this.#c,this.#x)}#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}#bt(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#Re(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}#Ne(){this.#x.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#$;this.#k.textContent=e>9?"9+":String(e),this.#k.hidden=e===0||!this.#yt();let n=this.#k.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#x.setAttribute("aria-label",n),this.#x.title=n}#yt(){return this.getAttribute("data-unread-badge")!=="false"}#pe(e){this.#$=e,this.#Ne(),this.dispatchEvent(new CustomEvent(Ki,{detail:{unread:e},bubbles:!0,composed:!0}))}#xt(){this.collapsed&&this.#pe(this.#$+1)}#v(){this.#R.hidden=this.#i.childElementCount>1}#Oe(){this.#p.onInput(this.#s.value),this.#_.hidden=!0,this.#z()}#_t(e){if(this.#p.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#H){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#he())}#M(){this.#E?.abort(),this.#N?.cancel()}#D(e){this.#H=e;let n=e?this.#e.stop:this.#e.send;this.#d.title=n,this.#d.setAttribute("aria-label",n),this.#d.dataset.state=e?"running":"idle"}#z(){this.#s.style.height="auto",this.#s.style.height=`${this.#s.scrollHeight}px`}async#he(){if(this.#H)return;let e=this.#s.value.trim(),n=this.#g?.readyRefs()??[];e===""&&n.length===0||(this.#s.value="",this.#z(),this.#g?.hasPending()===!0&&this.#Z("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#g.pendingCount())),"attachment-pending"),this.#g?.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(ws(n)),this.dispatchEvent(new CustomEvent(Xi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#wt(e,n)}attachFile(e){return this.#g===null?!1:(this.#g.add(e),!0)}#Et(e){this.dispatchEvent(new CustomEvent(Ji,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#wt(e,n){this.endpoint!==""&&await this.#Me().send(e,n)}#Me(){if(this.#N===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#C(),getHeaders:()=>this.#C(),...this.#q(),threadId:this.#m,initialMessages:this.#re,initialState:this.#L});this.#N=new Pn({agent:e,handlers:this.#De(),getTools:()=>this.getTools(),getContext:()=>this.#Ie(),executeTool:n=>this.#Le(n),resolveInterrupts:n=>this.#Pe(n),onPersist:n=>this.conversationStore.saveMessages(this.#m,n),onStateChanged:n=>this.#Tt(n),connectionLostMessage:this.#e.connectionLost})}return this.#N}#Tt(e){this.#L={...e},this.dispatchEvent(new CustomEvent(Zi,{detail:{state:this.#L},bubbles:!0,composed:!0}))}async#St(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:ss(n.parameters)}async#Le(e){if(xu(e)!==null)return null;let n=this.#fe(e);this.#o.delete(e.id);let r=this.#ye(e.name);if(r===null)return this.#r.has(e.id)||n.settle(ee.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==es&&!Pr(r.parameters)&&this.#pt()){let i=this.#e.pageMoved;return n.settle(ee.ERROR,i),this.#F(),{content:`Error: ${i}`,error:i}}if(await this.#St(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Lr];typeof s=="string"&&(i.message=s),this.#E=new AbortController;let a=pa(this.#T(),i,{signal:this.#E.signal,strings:this.#e});this.#v(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#E=null,n.recordDecision(l?"approved":"declined"),!l){let c=this.#e.declinedAction;return n.settle(ee.DECLINED,c),this.#F(),{content:c}}}let o=Pr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#m,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(ee.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(ee.DONE,s),this.#F(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#m,null);let s=i instanceof Error?i.message:String(i);return n.settle(ee.ERROR,s),this.#F(),{content:`Error: ${s}`,error:s}}}async#Pe(e){this.#E=new AbortController,this.#S();let n=this.#E.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#o.get(i.toolCallId):void 0,a={},l=fb(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c),s?.mark(ee.DEFERRED);let p=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await _s(s?.approvalSlot??this.#T(),a,{signal:n,strings:this.#e});return s?.recordDecision(p?"approved":"declined"),p?s?.mark(ee.PENDING):s?.settle(ee.DECLINED,this.#e.declinedAction),{id:i.id,approved:p}}));this.#v(),this.#i.scrollTop=this.#i.scrollHeight,this.#E=null;let o={};for(let{id:i,approved:s}of r)o[i]=s?{status:"resolved",payload:{approved:!0}}:{status:"cancelled"};return o}#De(){return{onRunStart:()=>{this.#D(!0),this.#T(),this.#F()},onReasoningStart:()=>{this.#S(),this.#Ue()},onReasoningDelta:e=>{this.#Ue().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#S(),this.#O?.collapse(),this.#He(e),this.#te+=1},onTextEnd:e=>{let n=this.#He(e);this.#te<=1&&this.#Ce(n),Es(n,this.#e),this.#w=null,this.#xt()},onToolCall:e=>{this.#S(),!this.#ze(e)&&(this.#a.push({id:e.id,name:e.name}),this.#fe(e))},onActivity:(e,n)=>{if(e!==rs)return;let r=vb(n);r!==null&&this.#Z("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(ee.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#S(),this.#w=null},onError:e=>{this.#S(),this.#Ce(this.appendMessage(je.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#w=null},onCancelled:()=>{this.#S(),this.#kt(),this.#w=null},onSettled:()=>{this.#S(),this.#D(!1),this.#w=null;for(let e of this.#o.values())e.settled||e.settle(ee.DONE,this.#e.noResult);this.#I!==null&&this.#I.childElementCount===0&&(this.#I.remove(),this.#v()),this.#I=null,this.#O=null,this.#At()}}}#At(){let e=this.#a.map(({id:n,name:r})=>({name:r,side:this.#r.has(n)?"server":"client"}));this.#a=[],this.dispatchEvent(new CustomEvent(Qi,{detail:{tools:e},bubbles:!0,composed:!0}))}#kt(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#T().appendChild(e),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}#F(){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.#T().appendChild(e),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}#S(){this.#V?.remove(),this.#V=null}#Ue(){if(this.#O===null){this.#O=new wi(this.#e);let e=this.#T();e.insertBefore(this.#O.element,e.firstChild),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}return this.#O}#He(e){return this.#w===null&&(this.#w=this.appendMessage(je.ASSISTANT,""),this.#te=0),this.#w.innerHTML=_i(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#w}#ze(e){let n=xu(e);return n===null?!1:(this.#Z("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#Z(e,n,r){this.#T().appendChild(pu(e,n,r)),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}#fe(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#ye(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??ha(e.name),i=new mr(e.name,e.args,o,this.#e);return this.#o.set(e.id,i),this.#T().appendChild(i.element),this.#v(),this.#i.scrollTop=this.#i.scrollHeight,i}};function fb(t){let e=t.metadata?.[Lr];return typeof e=="string"&&e.trim()!==""?e:void 0}function mb(t){return Array.isArray(t)?t.filter(gb):[]}function gb(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function xu(t){if(t.name!==os)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function vb(t){let e=t?.removed;return typeof e=="number"?e:null}function bb(){customElements.get(Mr)===void 0&&customElements.define(Mr,xr)}async function yb(t,e,n={}){await lt(t),await us(t,{...n,flashMs:n.flashMs??0}),await cs(t,e,n)}async function xb(t,e={}){await lt(t),await ds(t,e)}async function _b(t,e={}){await lt(t),await ps(t,e)}async function Eb(t,e,n={}){await lt(t),await hs(t,e,n)}async function wb(t,e,n={}){await lt(t),await fs(t,e,n)}function Tb(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 Sb="0.25.1";export{Ji as ATTACHMENT_EVENT,xr as AgUiChat,Pn as AgUiClient,rs as COMPACTION_ACTIVITY_TYPE,ar as CheckpointMenu,Bn as ClientToolRegistry,Ai as ConnectionLostError,le as DEFAULT_UI_STRINGS,Mr as ELEMENT_TAG,os as LOAD_CAPABILITY_TOOL,ts as MAX_TOOL_ROUNDS,je as MESSAGE_ROLE,ms as PAGE_ACTIONS,Qi as RUN_FINISHED_EVENT,br as RemoteConversationStore,yr as RunIndex,Zi as STATE_EVENT,Xi as SUBMIT_EVENT,mt as SessionStorageStore,Yi as TOGGLE_EVENT,ee as TOOL_CALL_STATUS,pn as TOOL_DISPLAY,mr as ToolCallCard,Ki as UNREAD_EVENT,Sb as VERSION,Lr as X_CONFIRM_KEY,Gn as X_DESTRUCTIVE_KEY,$n as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,xb as clickElement,Ha as createHttpAgent,gs as createPageActionTools,vs as createPageMapContext,zr as createPageStateTools,ys as createRouteTools,hp as createStateHookTools,bb as defineAgUiChat,yb as fillField,lp as flash,us as focusWithFlash,ds as highlightThenClick,ss as isDestructive,Pr as isNavigates,xs as mergeUiStrings,Pa as messageAttachments,bs as parseToolCatalog,Ur as prefersReducedMotion,_b as pressButton,ps as pressThenClick,ha as prettifyToolName,_i as renderMarkdown,_s as requestApproval,pa as requestConfirmation,fa as requestQuestion,lt as scrollIntoCenterView,Eb as selectControl,hs as selectOption,Tb as setControlValue,Vn as setNativeChecked,Nt as setNativeValue,wb as toggleCheckbox,fs as toggleControl,za as transcribeAudio,cs as typeInto,Fa as uploadAttachment};
2360
+ `;var wi=class{element;#n;#e;#t;#o;#r=!1;constructor(e=le){this.#o=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.setAttribute("part","thoughts-label"),this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#a(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#o.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var Ti=class{element;#n;#e;#t;#o;#r;#a;#l=[];#c="";#i=null;constructor(e,n=le){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.#o=document.createElement("button"),this.#o.type="button",this.#o.className="drawer-new",this.#o.setAttribute("part","drawer-new"),this.#o.textContent=n.newChat,this.#o.addEventListener("click",()=>{this.close(),this.#n.onNew()}),o.append(this.#t,this.#o),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(o,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#a=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#o.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#i=this.#s(),this.element.hidden=!1,this.#o.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#i?.focus(),this.#i=null)}toggle(){this.isOpen()?this.close():this.open()}#s(){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.#s();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#l=e,this.#c=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#l.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.#l)this.#r.appendChild(this.#p(e))}#p(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#c&&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=fi(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.#f(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()}#f(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 La(t){return{[ee.PENDING]:t.toolRunning,[ee.DEFERRED]:t.toolDeferred,[ee.DONE]:t.toolDone,[ee.ERROR]:t.toolError,[ee.DECLINED]:t.toolDeclined}}function tb(t){return{[ee.DONE]:t.resultLabel,[ee.ERROR]:t.errorLabel,[ee.DECLINED]:t.declinedLabel}}function nb(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var mr=class{element;approvalSlot;#n;#e;#t;#o;#r;#a;#l;#c=!1;constructor(e,n,r,o=le){this.#l=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",ee.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=La(o)[ee.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.#i("args",o.argumentsLabel);l.body.textContent=JSON.stringify(n,null,2),l.root.hidden=Object.keys(n).length===0;let c=this.#i("result",o.resultLabel);this.#o=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.#s()));let p=document.createElement("div");p.className="tool-call-body",p.setAttribute("part","tool-card-body"),p.append(l.root,c.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.element.append(i,this.#t,p,this.approvalSlot)}mark(e){this.#c||(this.element.setAttribute("data-status",e),this.#n.textContent=La(this.#l)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#e.textContent=e==="approved"?this.#l.decisionApproved:this.#l.decisionDeclined,this.#e.hidden=!1}get settled(){return this.#c}settle(e,n){this.#c||(this.#c=!0,this.element.setAttribute("data-status",e),this.#n.textContent=La(this.#l)[e],this.#r.textContent=tb(this.#l)[e],this.#a.textContent=nb(n),this.#o.hidden=!1)}#i(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}}#s(){return this.element.getAttribute("data-expanded")==="true"}#d(e){this.element.setAttribute("data-expanded",String(e)),this.#t.setAttribute("aria-expanded",String(e))}};var Si=class{element;#n;#e;#t;#o="idle";#r=null;#a=null;#l=[];#c=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??le,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=yl,this.element.append(n),this.#h("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#o==="recording"){this.#s();return}this.#o!=="transcribing"&&await this.#i()}async#i(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#p(this.#t.transcriptionFailed);return}this.#a=e,this.#l=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#l.push(r.data)}),n.addEventListener("stop",()=>{this.#d(n.mimeType)}),this.#r=n,n.start(),this.#h("recording")}#s(){this.#r?.stop()}dispose(){this.#c=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#d(e){if(this.#c)return;this.#u(),this.#h("transcribing");let n=new Blob(this.#l,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#h("idle"),r!==""&&this.#e(r)}catch(r){this.#p(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}#p(e){this.#u(),this.#r=null,this.#h("idle"),this.element.title=e}#h(e){this.#o=e,this.element.dataset.state=e;let n=this.#f(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#f(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var Ai=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Pn=class{#n;#e;#t;#o;#r;#a;#l;#c=new Set;#i;#s=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#o=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#l=e.onPersist??(()=>{}),this.#i=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Ue(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#l(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.#l(this.#n.messages)}cancel(){this.#s=!0,this.#n.abortRun()}async#d(){this.#s=!1;try{await this.#p(),this.#s&&this.#u()}catch(e){this.#s||rb(e)?this.#u():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#u(){this.#l(this.#n.messages),this.#e.onCancelled()}async#p(){let e;for(let n=0;n<ts;n+=1){if(this.#s)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#o()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#l(this.#n.messages),this.#s)return;if(!o.terminal)throw new Ai(this.#i);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#s)return;e=xd(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.#l(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e,o=this.#c;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 rb(t){return t instanceof Error&&t.name==="AbortError"}function Pa(t){let e=t.attachments;return Array.isArray(e)?e.filter(ob):[]}function ob(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 Da="ag-ui-chat",gr="thread",Ua="threads",vr="messages:",Ii="checkpoint:",ki="minted:",ib=60,sb=100,ab="New conversation",mt=class{#n;constructor(e=""){this.#n=e===""?Da:`${Da}@${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),sessionStorage.setItem(this.#r(ki+r),"1"),r}isUnsent(e){return sessionStorage.getItem(this.#r(ki+e))!==null&&sessionStorage.getItem(this.#r(vr+e))===null}loadMessages(e){return Promise.resolve(this.#l(this.#r(vr+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(vr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(ki+e)),this.#e(e,n)}loadCheckpoint(e){return this.#l(this.#r(Ii+e))}saveCheckpoint(e,n){let r=this.#r(Ii+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(vr+e)),sessionStorage.removeItem(this.#r(Ii+e)),sessionStorage.removeItem(this.#r(ki+e)),this.#o(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.#o(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=cb(n),s=Date.now();o===void 0?r.push({threadId:e,title:fu(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=fu(n))),this.#o(r)}#t(){return this.#l(this.#r(Ua))??[]}#o(e){let n=this.#r(Ua);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Da}:`,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);lb(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)}}#l(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function lb(t){return t===gr||t===Ua||t.startsWith(vr)||t.startsWith(Ii)}function fu(t){for(let e of t)if(e.role==="user"){let n=mu(e.content);if(n!=="")return gu(n,ib)}return ab}function cb(t){for(let e of[...t].reverse()){let n=mu(e.content);if(n!=="")return gu(n,sb)}return""}function mu(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function gu(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 Ha(t){return new _d({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 br=class{#n;#e;#t;#o;#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.#o=o}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}isUnsent(e){return this.#t.isUnsent?.(e)===!0}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.#l();return e===null?this.#t.listThreads():e.filter(n=>!this.#r.has(n.thread_id)).map(n=>this.#i(n))}async loadMessages(e){if(this.#t.isUnsent?.(e)===!0)return null;let n=await this.#s(`${this.#n}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#c(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#l(){let e=await this.#s(this.#n);if(e===null||!e.ok)return null;let n=await this.#c(e);return n===null?null:n.threads??[]}async#c(e){try{return await e.json()}catch{return null}}#i(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#s(e){try{return await fetch(e,Be({headers:this.#e()},this.#o()))}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.#o()))}catch{}}};var yr=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.#o("resume",e)}forkUrl(e){return this.#o("fork",e)}#o(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function za(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 db(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 db(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Fa(t,e){return new Promise((n,r)=>{let 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(ub(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(pb(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 ub(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 pb(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var hb=["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"],$a=["omit","same-origin","include"];function Ga(t){return $a.includes(t)}var vu="ag-ui-chat:collapsed",bu="ag-ui-chat:size",yu="ag-ui-chat:theme",xr=class extends HTMLElement{agentFactory=Ha;headers={};getHeaders=null;allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#be().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...vs(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=le;#t=new Bn;#o=new Map;#r=new Set;#a=[];#l;#c;#i;#s;#d;#u;#p;#h;#f;#J=null;#_;#b;#y;#G;#A;#x;#k;#$=0;#R;#g=null;#B;#Q=null;#H=!1;#N=null;#L={};#z=!1;#ee=null;#E=null;#w=null;#te=0;#V=null;#I=null;#O=null;#m="";#P="";#ne=0;#re=[];#me=[];#ge=[];#ve=[];constructor(){super(),this.#l=this.attachShadow({mode:"open"}),this.#c=document.createElement("div"),this.#i=document.createElement("div"),this.#s=document.createElement("textarea"),this.#d=document.createElement("button"),this.#u=document.createElement("span"),this.#_=document.createElement("div"),this.#b=document.createElement("button"),this.#y=document.createElement("input"),this.#G=document.createElement("div"),this.#B=document.createElement("span"),this.#A=document.createElement("button"),this.#x=document.createElement("button"),this.#k=document.createElement("span"),this.#R=document.createElement("div"),this.#p=new Ei(e=>this.#st(e)),this.#h=new Ti({onSelect:e=>{this.#dt(e)},onNew:()=>{this.newChat(),this.#Y()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Y()},onDelete:e=>{this.#ut(e)}}),this.#f=new ar((e,n)=>{this.#Fe(e,n)})}#oe(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#J===null&&(this.#J=new yr(e,()=>this.#C(),()=>this.#j())),this.#J)}async#Fe(e,n){let r=this.#oe();if(r===null)return;let o=this.#s.value.trim();if(o==="")return;this.#s.value="",this.#F();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.#m,initialMessages:[]});await new Pn({agent:s,handlers:this.#De(),getTools:()=>this.getTools(),getContext:()=>this.#Ie(),executeTool:l=>this.#Le(l),resolveInterrupts:l=>this.#Pe(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Ge(){let e=this.#oe();this.#f.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials",...hb]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Ga(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${$a.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.#lt(),requestAnimationFrame(()=>this.#ae());return}if(e==="title-text"){this.#u.textContent=r??this.#e.title;return}n===r||!this.#H||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 zr(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#$e(){return this.routeMap.length===0?[]:ys(()=>this.routeMap,()=>this.navigate)}#Be(){let e=this.getPageMap;return e===null?[]:[{name:es,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()}]}#Ve(){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 gs(n,r=>this.resolvePageTarget(r))}#be(){return[...this.#$e(),...this.#Be(),...this.#Ve(),...this.#je()]}#je(){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.#qe(e)}]:[]}async#qe(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.#E=new AbortController;let i=this.#E.signal;this.#S();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await fa(this.#T(),r,{signal:i,strings:this.#e});return this.#E=null,this.#v(),this.#i.scrollTop=this.#i.scrollHeight,s}#ye(e){let n=this.#be().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&&Ga(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Ga(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${$a.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}}#xe(){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.#le(this.#Ae()),requestAnimationFrame(()=>this.#ae()),this.#e=xs({...this.#Xe(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#ce(yu);e!==null&&this.setAttribute("theme",e)}this.#vt(),this.#h.setStrings(this.#e),this.#f.setStrings(this.#e),this.#ce(vu)==="1"&&this.setAttribute("collapsed",""),this.#Ne(),this.#ot(),this.#P!==""&&this.conversationStore instanceof mt&&(this.conversationStore=new mt(this.#P)),this.#rt(),this.#Ye(),this.#Ze(),this.#m=this.conversationStore.threadId(),queueMicrotask(()=>this.#We()),this.#de(),this.#H=!0}#We(){this.#H&&(this.#Ee(),this.#we())}async reload(){this.#M(),this.#X(),this.#D(!1),await Promise.all([this.#Ee(),this.#we(),this.#de()])}disconnectedCallback(){this.#H=!1,this.#M(),this.#g?.dispose(),this.#Q?.dispose()}#_e(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#Xe(){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{}}#Ye(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ke(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new hi({upload:n,maxBytes:this.#et(),accept:r,strings:this.#e,onChange:()=>this.#Et(o)});this.#g=o,this.#G.appendChild(this.#g.element),this.#y.accept=r,this.#b.hidden=!1,this.#nt()}#Ke(e){return e===null?null:(n,r,o)=>Fa(n,{url:e,headers:this.#C(),...this.#q(),onProgress:r,signal:o})}#Ze(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Je(e);n!==null&&(this.#Q=new Si({transcribe:n,onText:r=>this.#Qe(r),strings:this.#e}),this.#B.appendChild(this.#Q.element))}#Je(e){return e===null?null:n=>za(n,{url:e,headers:this.#C(),...this.#q()})}#Qe(e){let n=this.#s.value.trim();this.#s.value=n===""?e:`${n} ${e}`,this.#Oe(),this.#s.focus()}#et(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return ns;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:ns}#tt(){let e=this.#y.files;if(e!==null)for(let n of Array.from(e))this.#g?.add(n);this.#y.value=""}#nt(){this.#c.addEventListener("dragover",e=>{e.preventDefault(),this.#c.classList.add("chat--dragover")}),this.#c.addEventListener("dragleave",()=>{this.#c.classList.remove("chat--dragover")}),this.#c.addEventListener("drop",e=>{e.preventDefault(),this.#c.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#g?.add(r)})}#rt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new br(e,()=>this.#C(),this.conversationStore,()=>this.#j()))}async#Ee(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#xe());this.#n=bs(await n.json())}catch{}}setSkills(e){this.#ve=e,this.#ie()}#ot(){this.#p.enableChips(this.#_e("data-prompt-chips")),this.#p.enableSlash(this.#_e("data-slash-commands")),this.#ge=this.#it(),this.#ie()}#it(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return is(JSON.parse(e))}catch{return[]}}async#we(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#xe());this.#me=is(await n.json()),this.#ie()}catch{}}#ie(){let e=new Map;for(let n of[...this.#me,...this.#ge,...this.#ve])e.set(n.name,n);this.#p.setSkills([...e.values()])}#st(e){if(e.prompt===void 0){this.#_.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=Sl(e.prompt,this.skillContext());if(r.length>0){this.#_.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#_.hidden=!1,this.#s.value=n,this.#F(),this.#s.focus(),this.#at(n);return}if(this.#_.hidden=!0,this.#s.value=n,this.#F(),e.sendImmediately===!1){this.#s.focus();return}this.#he()}#at(e){let n=e.indexOf("{");this.#s.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(vu),e?"1":"0"),this.#pe(0),this.dispatchEvent(new CustomEvent(Yi,{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(yu),e),this.#ke()}#se(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#Te(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height");this.#le({width:e.width+1,height:e.height+1});let o=this.getBoundingClientRect();return this.#Se("--ag-ui-width",n),this.#Se("--ag-ui-height",r),{x:Math.abs(o.left-e.left)<.5?"left":"right",y:Math.abs(o.top-e.top)<.5?"top":"bottom"}}#ae(){if(!this.#H)return;let e=this.#Te();this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`)}#Se(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#le(e){let n=this.#se();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`))}#lt(){let e=this.#se();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#ct(e){let n={...this.#Ae(),...e};sessionStorage.setItem(this.#W(bu),JSON.stringify(n))}#Ae(){let e=this.#ce(bu);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}`}#ce(e){let n=sessionStorage.getItem(this.#W(e));return n!==null||this.#P===""?n:sessionStorage.getItem(e)}#ke(){let e=this.getAttribute("theme")==="dark";this.#A.textContent=e?"\u2600\uFE0F":"\u{1F319}"}openThreads(){this.#f.close(),this.#Y(),this.#h.open()}openCheckpoints(){this.#h.close(),this.#Ge(),this.#f.open()}closeCheckpoints(){this.#f.close()}toggleCheckpoints(){if(this.#f.open_){this.#f.close();return}this.openCheckpoints()}newChat(){this.#M(),this.conversationStore.clear(this.#m),this.#X(),this.#m=this.conversationStore.threadId(),this.#D(!1),this.#pe(0)}#X(){this.#N=null,this.#w=null,this.#I=null,this.#O=null,this.#S(),this.#o.clear(),this.#r.clear(),this.#re=[],this.#g?.clear(),this.#i.replaceChildren(this.#R),this.#v()}async#dt(e){e!==this.#m&&(this.#M(),this.#X(),this.conversationStore.setActiveThread(e),this.#m=e,this.#D(!1),await this.#de())}#ut(e){let n=e===this.#m;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#X(),this.#m=this.conversationStore.threadId(),this.#D(!1)),this.#Y()}async#Y(){this.#h.setThreads(await this.conversationStore.listThreads(),this.#m)}async#de(){this.#ne+=1;let e=this.#ne,n=await this.conversationStore.loadMessages(this.#m);if(e!==this.#ne)return;if(n!==null){this.#re=n;for(let o of n)this.#ft(o)}let r=this.conversationStore.loadCheckpoint(this.#m);if(r!==null){await this.#gt(r);return}this.#ht(n)}#Ie(){return this.#ee=window.location.href,this.getContext()}#pt(){return this.#ee!==null&&this.#ee!==window.location.href}#ht(e){let n=e?.at(-1);n===void 0||n.role!==je.USER||this.#Z("\u26A0",this.#e.runInterrupted,"interrupted")}#ft(e){let n=typeof e.content=="string"?e.content:"";if(e.role===je.USER){let r=Pa(e);if(n!==""||r.length>0){let o=this.appendMessage(je.USER,n);r.length>0&&o.appendChild(ws(r))}return}if(e.role===je.ASSISTANT){n!==""&&this.appendMessage(je.ASSISTANT,n).classList.add("message--restored");for(let r of mb(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#mt(r.function.arguments)};this.#ze(o)||this.#fe(o)}return}if(e.role==="tool"){let r=this.#o.get(e.toolCallId);r!==void 0&&r.settle(ee.DONE,e.content)}}#mt(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"&&uu(e)}async#gt(e){this.conversationStore.saveCheckpoint(this.#m,null);let n=this.#Me();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=_i(n,{allowImages:this.allowImages}),Es(r,this.#e),this.#T().appendChild(r)):(this.#I=null,r.textContent=n,this.#i.appendChild(r)),this.#v(),this.#i.scrollTop=this.#i.scrollHeight,r}#T(){if(this.#I===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#I=e,this.#i.appendChild(e),this.#v()}return this.#I}#vt(){let e=document.createElement("style");e.textContent=hu,this.#c.className="chat",this.#c.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#u;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.#Re("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,"\u21BA");a.addEventListener("click",()=>this.toggleCheckpoints());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.#oe()!==null?i.append(s,a,l):i.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#A.type="button",this.#A.className="header-btn header-btn--theme",this.#A.setAttribute("part","header-button theme-toggle"),this.#A.title=this.#e.toggleTheme,this.#A.setAttribute("aria-label",this.#e.toggleTheme),this.#A.addEventListener("click",()=>this.toggleTheme()),this.#ke(),i.append(this.#A)),i.append(c),n.append(r,o,i),this.#i.className="messages",this.#i.setAttribute("part","messages"),this.#i.setAttribute("role","log"),this.#i.setAttribute("aria-live","polite"),this.#i.setAttribute("aria-label",this.#e.conversation),this.#R.className="empty",this.#R.setAttribute("part","empty");let p=document.createElement("slot");p.name="empty",this.#R.append(p),this.#i.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.#s.className="input",this.#s.setAttribute("part","input"),this.#s.setAttribute("aria-label",this.#e.message),this.#s.rows=1,this.#s.placeholder=this.#e.inputPlaceholder,this.#s.addEventListener("keydown",g=>this.#_t(g)),this.#s.addEventListener("input",()=>this.#Oe()),this.#d.className="send",this.#d.type="button",this.#d.setAttribute("part","send"),this.#d.append(this.#ue("icon-send","send-send",gl),this.#ue("icon-stop","send-stop",vl)),this.#d.title=this.#e.send,this.#d.setAttribute("aria-label",this.#e.send),this.#d.dataset.state="idle",this.#d.addEventListener("click",()=>{if(this.#z){this.#M();return}this.#he()}),this.#_.className="skill-hint",this.#_.setAttribute("part","skill-hint"),this.#_.hidden=!0,this.#b.className="attach-btn",this.#b.type="button",this.#b.setAttribute("part","attach-button"),this.#b.append(this.#ue("icon-attach","attach-glyph",bl)),this.#b.title=this.#e.attachFiles,this.#b.setAttribute("aria-label",this.#e.attachFiles),this.#b.hidden=!0,this.#b.addEventListener("click",()=>this.#y.click()),this.#y.className="attach-input",this.#y.type="file",this.#y.multiple=!0,this.#y.hidden=!0,this.#y.addEventListener("change",()=>this.#tt()),this.#G.className="attachment-slot",this.#B.className="voice-slot";let h=document.createElement("slot");h.name="footer",f.append(this.#b,this.#B,this.#d),y.append(this.#s,f),m.append(y,this.#y),this.#c.append(n,this.#i,this.#p.palette,this.#p.chips,this.#_,this.#G,m,h,this.#h.element,this.#f.element),this.#c.addEventListener("pointerdown",g=>{if(!this.#f.open_)return;let x=g.composedPath();x.includes(this.#f.element)||x.includes(a)||this.#f.close()}),this.#x.className="launcher",this.#x.type="button",this.#x.setAttribute("part","launcher"),this.#x.setAttribute("aria-label",this.#e.expand),this.#k.className="launcher-badge",this.#k.setAttribute("part","launcher-badge"),this.#k.setAttribute("aria-hidden","true"),this.#k.hidden=!0,this.#x.append(this.#Re("launcher","launcher-icon",xl,this.#bt()),this.#k),this.#x.addEventListener("click",()=>this.setCollapsed(!1)),this.#c.append(cu({axis:()=>this.#se(),anchor:()=>this.#Te(),rect:()=>this.getBoundingClientRect(),apply:g=>this.#le(g),commit:g=>{this.#ct(g),this.#ae()},label:this.#e.resizePanel})),this.#l.append(e,this.#c,this.#x)}#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}#bt(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#Re(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}#Ne(){this.#x.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#$;this.#k.textContent=e>9?"9+":String(e),this.#k.hidden=e===0||!this.#yt();let n=this.#k.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#x.setAttribute("aria-label",n),this.#x.title=n}#yt(){return this.getAttribute("data-unread-badge")!=="false"}#pe(e){this.#$=e,this.#Ne(),this.dispatchEvent(new CustomEvent(Ki,{detail:{unread:e},bubbles:!0,composed:!0}))}#xt(){this.collapsed&&this.#pe(this.#$+1)}#v(){this.#R.hidden=this.#i.childElementCount>1}#Oe(){this.#p.onInput(this.#s.value),this.#_.hidden=!0,this.#F()}#_t(e){if(this.#p.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#z){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#he())}#M(){this.#E?.abort(),this.#N?.cancel()}#D(e){this.#z=e;let n=e?this.#e.stop:this.#e.send;this.#d.title=n,this.#d.setAttribute("aria-label",n),this.#d.dataset.state=e?"running":"idle"}#F(){this.#s.style.height="auto",this.#s.style.height=`${this.#s.scrollHeight}px`}async#he(){if(this.#z)return;let e=this.#s.value.trim(),n=this.#g?.readyRefs()??[];e===""&&n.length===0||(this.#s.value="",this.#F(),this.#g?.hasPending()===!0&&this.#Z("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#g.pendingCount())),"attachment-pending"),this.#g?.clearReady(),await this.sendMessage(e,n))}async sendMessage(e,n=[]){if(this.#z||e===""&&n.length===0)return;let r=this.appendMessage(je.USER,e);n.length>0&&r.appendChild(ws(n)),this.dispatchEvent(new CustomEvent(Xi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#wt(e,n)}attachFile(e){return this.#g===null?!1:(this.#g.add(e),!0)}#Et(e){this.dispatchEvent(new CustomEvent(Ji,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#wt(e,n){this.endpoint!==""&&await this.#Me().send(e,n)}#Me(){if(this.#N===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#C(),getHeaders:()=>this.#C(),...this.#q(),threadId:this.#m,initialMessages:this.#re,initialState:this.#L});this.#N=new Pn({agent:e,handlers:this.#De(),getTools:()=>this.getTools(),getContext:()=>this.#Ie(),executeTool:n=>this.#Le(n),resolveInterrupts:n=>this.#Pe(n),onPersist:n=>this.conversationStore.saveMessages(this.#m,n),onStateChanged:n=>this.#Tt(n),connectionLostMessage:this.#e.connectionLost})}return this.#N}#Tt(e){this.#L={...e},this.dispatchEvent(new CustomEvent(Zi,{detail:{state:this.#L},bubbles:!0,composed:!0}))}async#St(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:ss(n.parameters)}async#Le(e){if(xu(e)!==null)return null;let n=this.#fe(e);this.#o.delete(e.id);let r=this.#ye(e.name);if(r===null)return this.#r.has(e.id)||n.settle(ee.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==es&&!Pr(r.parameters)&&this.#pt()){let i=this.#e.pageMoved;return n.settle(ee.ERROR,i),this.#U(),{content:`Error: ${i}`,error:i}}if(await this.#St(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Lr];typeof s=="string"&&(i.message=s),this.#E=new AbortController;let a=pa(this.#T(),i,{signal:this.#E.signal,strings:this.#e});this.#v(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#E=null,n.recordDecision(l?"approved":"declined"),!l){let c=this.#e.declinedAction;return n.settle(ee.DECLINED,c),this.#U(),{content:c}}}let o=Pr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#m,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(ee.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(ee.DONE,s),this.#U(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#m,null);let s=i instanceof Error?i.message:String(i);return n.settle(ee.ERROR,s),this.#U(),{content:`Error: ${s}`,error:s}}}async#Pe(e){this.#E=new AbortController,this.#S();let n=this.#E.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#o.get(i.toolCallId):void 0,a={},l=fb(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c),s?.mark(ee.DEFERRED);let p=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await _s(s?.approvalSlot??this.#T(),a,{signal:n,strings:this.#e});return s?.recordDecision(p?"approved":"declined"),p?s?.mark(ee.PENDING):s?.settle(ee.DECLINED,this.#e.declinedAction),{id:i.id,approved:p}}));this.#v(),this.#i.scrollTop=this.#i.scrollHeight,this.#E=null;let o={};for(let{id:i,approved:s}of r)o[i]=s?{status:"resolved",payload:{approved:!0}}:{status:"cancelled"};return o}#De(){return{onRunStart:()=>{this.#D(!0),this.#T(),this.#U()},onReasoningStart:()=>{this.#S(),this.#Ue()},onReasoningDelta:e=>{this.#Ue().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#S(),this.#O?.collapse(),this.#He(e),this.#te+=1},onTextEnd:e=>{let n=this.#He(e);this.#te<=1&&this.#Ce(n),Es(n,this.#e),this.#w=null,this.#xt()},onToolCall:e=>{this.#S(),!this.#ze(e)&&(this.#a.push({id:e.id,name:e.name}),this.#fe(e))},onActivity:(e,n)=>{if(e!==rs)return;let r=vb(n);r!==null&&this.#Z("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#o.get(e);r!==void 0&&(r.settle(ee.DONE,n),this.#r.add(e),this.#U())},onRunEnd:()=>{this.#S(),this.#w=null},onError:e=>{this.#S(),this.#Ce(this.appendMessage(je.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#w=null},onCancelled:()=>{this.#S(),this.#kt(),this.#w=null},onSettled:()=>{this.#S(),this.#D(!1),this.#w=null;for(let e of this.#o.values())e.settled||e.settle(ee.DONE,this.#e.noResult);this.#I!==null&&this.#I.childElementCount===0&&(this.#I.remove(),this.#v()),this.#I=null,this.#O=null,this.#At()}}}#At(){let e=this.#a.map(({id:n,name:r})=>({name:r,side:this.#r.has(n)?"server":"client"}));this.#a=[],this.dispatchEvent(new CustomEvent(Qi,{detail:{tools:e},bubbles:!0,composed:!0}))}#kt(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#T().appendChild(e),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}#U(){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.#T().appendChild(e),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}#S(){this.#V?.remove(),this.#V=null}#Ue(){if(this.#O===null){this.#O=new wi(this.#e);let e=this.#T();e.insertBefore(this.#O.element,e.firstChild),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}return this.#O}#He(e){return this.#w===null&&(this.#w=this.appendMessage(je.ASSISTANT,""),this.#te=0),this.#w.innerHTML=_i(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#w}#ze(e){let n=xu(e);return n===null?!1:(this.#Z("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#Z(e,n,r){this.#T().appendChild(pu(e,n,r)),this.#v(),this.#i.scrollTop=this.#i.scrollHeight}#fe(e){let n=this.#o.get(e.id);if(n!==void 0)return n;let r=this.#ye(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??ha(e.name),i=new mr(e.name,e.args,o,this.#e);return this.#o.set(e.id,i),this.#T().appendChild(i.element),this.#v(),this.#i.scrollTop=this.#i.scrollHeight,i}};function fb(t){let e=t.metadata?.[Lr];return typeof e=="string"&&e.trim()!==""?e:void 0}function mb(t){return Array.isArray(t)?t.filter(gb):[]}function gb(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function xu(t){if(t.name!==os)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function vb(t){let e=t?.removed;return typeof e=="number"?e:null}function bb(){customElements.get(Mr)===void 0&&customElements.define(Mr,xr)}async function yb(t,e,n={}){await lt(t),await us(t,{...n,flashMs:n.flashMs??0}),await cs(t,e,n)}async function xb(t,e={}){await lt(t),await ds(t,e)}async function _b(t,e={}){await lt(t),await ps(t,e)}async function Eb(t,e,n={}){await lt(t),await hs(t,e,n)}async function wb(t,e,n={}){await lt(t),await fs(t,e,n)}function Tb(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 Sb="0.25.2";export{Ji as ATTACHMENT_EVENT,xr as AgUiChat,Pn as AgUiClient,rs as COMPACTION_ACTIVITY_TYPE,ar as CheckpointMenu,Bn as ClientToolRegistry,Ai as ConnectionLostError,le as DEFAULT_UI_STRINGS,Mr as ELEMENT_TAG,os as LOAD_CAPABILITY_TOOL,ts as MAX_TOOL_ROUNDS,je as MESSAGE_ROLE,ms as PAGE_ACTIONS,Qi as RUN_FINISHED_EVENT,br as RemoteConversationStore,yr as RunIndex,Zi as STATE_EVENT,Xi as SUBMIT_EVENT,mt as SessionStorageStore,Yi as TOGGLE_EVENT,ee as TOOL_CALL_STATUS,pn as TOOL_DISPLAY,mr as ToolCallCard,Ki as UNREAD_EVENT,Sb as VERSION,Lr as X_CONFIRM_KEY,Gn as X_DESTRUCTIVE_KEY,$n as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,xb as clickElement,Ha as createHttpAgent,gs as createPageActionTools,vs as createPageMapContext,zr as createPageStateTools,ys as createRouteTools,hp as createStateHookTools,bb as defineAgUiChat,yb as fillField,lp as flash,us as focusWithFlash,ds as highlightThenClick,ss as isDestructive,Pr as isNavigates,xs as mergeUiStrings,Pa as messageAttachments,bs as parseToolCatalog,Ur as prefersReducedMotion,_b as pressButton,ps as pressThenClick,ha as prettifyToolName,_i as renderMarkdown,_s as requestApproval,pa as requestConfirmation,fa as requestQuestion,lt as scrollIntoCenterView,Eb as selectControl,hs as selectOption,Tb as setControlValue,Vn as setNativeChecked,Nt as setNativeValue,wb as toggleCheckbox,fs as toggleControl,za as transcribeAudio,cs as typeInto,Fa as uploadAttachment};
2361
2361
  /*! Bundled license information:
2362
2362
 
2363
2363
  fast-json-patch/module/helpers.mjs: