@artooi/ag-ui-web-component 0.35.1 → 0.35.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,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.35.2] — 2026-09-05
11
+
12
+ ### Fixed
13
+
14
+ - **The README's two callouts rendered as code blocks.** This file is the
15
+ documentation -- there is no docs site, so it is what GitHub shows and what npm
16
+ puts on the package page -- and `!!! note` is MkDocs syntax that neither
17
+ understands. The line rendered literally and its indented body became a *code
18
+ block*, so a warning was displayed as something to copy. Both are now GitHub
19
+ callouts.
20
+
21
+ One of the two was 0.35.1's own note about forgetting `defineAgUiChat()`,
22
+ written because that failure is silent. A reader hit the same failure after it
23
+ shipped, which is how the rendering was found: the note was there, was
24
+ correct, and reached nobody. `tests/readme_renders.test.ts` now fails on any
25
+ admonition, and on the registration callout going missing.
26
+
10
27
  ## [0.35.1] — 2026-09-05
11
28
 
12
29
  ### Documentation
@@ -3415,7 +3432,8 @@ hosts that both arrange the page the way it expects.
3415
3432
  ### Notes
3416
3433
  - First release — exercising the automated npm OIDC publish pipeline end-to-end.
3417
3434
 
3418
- [Unreleased]: https://github.com/Artui/ag-ui-web-component/compare/v0.35.1...HEAD
3435
+ [Unreleased]: https://github.com/Artui/ag-ui-web-component/compare/v0.35.2...HEAD
3436
+ [0.35.2]: https://github.com/Artui/ag-ui-web-component/compare/v0.35.1...v0.35.2
3419
3437
  [0.35.1]: https://github.com/Artui/ag-ui-web-component/compare/v0.35.0...v0.35.1
3420
3438
  [0.35.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.34.0...v0.35.0
3421
3439
  [0.34.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.33.1...v0.34.0
package/README.md CHANGED
@@ -149,16 +149,18 @@ Drop the element into your page and register the tools the agent may call:
149
149
  <ag-ui-chat endpoint="/agent/" title-text="Assistant"></ag-ui-chat>
150
150
  ```
151
151
 
152
- !!! note "If nothing appears, check `defineAgUiChat()` ran"
153
- Forgetting it looks like nothing. `<ag-ui-chat>` is then an *unknown
154
- element*, which every browser renders as an inline 0x0 box, in flow, with no
155
- console warning and no error so the page looks finished and the chat is
156
- simply absent. A bare `import "@artooi/ag-ui-web-component"` does not
157
- register anything, deliberately: registration is an explicit call so the
158
- package stays tree-shakeable.
159
-
160
- `customElements.get("ag-ui-chat")` in a console answers it in one line
161
- `undefined` means the call did not run.
152
+ > [!IMPORTANT]
153
+ > **If nothing appears, check that `defineAgUiChat()` ran.** Forgetting it looks
154
+ > like nothing at all. `<ag-ui-chat>` is then an *unknown element*, which every
155
+ > browser renders as an inline 0x0 box, in flow, with no console warning and no
156
+ > error so the page looks finished and the chat is simply absent. There is
157
+ > nothing to search for.
158
+ >
159
+ > A bare `import "@artooi/ag-ui-web-component"` registers nothing, deliberately:
160
+ > registration is an explicit call so the package stays tree-shakeable.
161
+ >
162
+ > `customElements.get("ag-ui-chat")` in a console answers it in one line.
163
+ > `undefined` means the call did not run.
162
164
 
163
165
  That's the whole integration: an `endpoint` attribute pointing at your AG-UI server, optional
164
166
  `headers`, and the tools you want the agent to be able to invoke in the browser. If your API is on
@@ -1668,11 +1670,11 @@ Retry sits on the **last** answer only. Re-running an older turn is branching,
1668
1670
  and for a page-driving agent editing a past turn is not neutral — those turns
1669
1671
  clicked buttons, and re-running turn 3 does not un-save what turn 5 saved.
1670
1672
 
1671
- !!! note
1672
- A retried turn **re-runs its tools.** The previous attempt already did what
1673
- it did, and this does not undo it. Confirmation still applies, so a
1674
- destructive tool asks again — unless the user waived it for this session
1675
- with *Always allow*.
1673
+ > [!NOTE]
1674
+ > A retried turn **re-runs its tools.** The previous attempt already did what it
1675
+ > did, and this does not undo it. Confirmation still applies, so a destructive
1676
+ > tool asks again — unless the user waived it for this session with
1677
+ > *Always allow*.
1676
1678
 
1677
1679
  A failed run gets the same row, with Retry and Copy and no rating: error text is
1678
1680
  what people paste into a bug report, but "the connection dropped" is not a
@@ -3665,7 +3665,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
3665
3665
  }
3666
3666
  `;var hs=class{element;get agent(){return this.#r}#t;#n;#e;#s=new Map;#r=null;constructor(e=se){this.element=document.createElement("div"),this.element.className="subagent",this.element.setAttribute("part","subagent"),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="subagent-row",this.#t.setAttribute("part","subagent-row"),this.#t.setAttribute("aria-expanded","false"),this.#t.disabled=!0;let n=document.createElement("span");n.className="subagent-icon",n.setAttribute("part","subagent-icon"),n.setAttribute("aria-hidden","true"),this.#n=document.createElement("span"),this.#n.className="subagent-status",this.#n.setAttribute("part","subagent-status"),this.#n.textContent=e.subAgentWorking,this.#t.append(n,this.#n),this.#e=document.createElement("div"),this.#e.className="subagent-steps",this.#e.setAttribute("part","subagent-steps"),this.#e.setAttribute("role","list"),this.#e.setAttribute("aria-label",e.subAgentSteps),this.#e.hidden=!0,this.#t.addEventListener("click",()=>{this.#d(this.#t.getAttribute("aria-expanded")!=="true")}),this.element.append(this.#t,this.#e)}report(e){this.element.setAttribute("data-phase",e.phase),e.agent!==null&&(this.#r=e.agent,this.element.setAttribute("data-agent",e.agent)),e.status!==null&&(this.#n.textContent=e.status),e.tool!==null&&this.#i(e.tool)}#i(e){let n=this.#s.get(e.toolCallId)??this.#o(e);if(e.ok===null){n.removeAttribute("data-ok");return}n.setAttribute("data-ok",String(e.ok))}#o(e){let n=document.createElement("div");n.className="subagent-step",n.setAttribute("part","subagent-step"),n.setAttribute("role","listitem"),n.setAttribute("data-tool-call-id",e.toolCallId);let r=document.createElement("span");r.className="subagent-step-icon",r.setAttribute("part","subagent-step-icon"),r.setAttribute("aria-hidden","true");let o=document.createElement("span");return o.className="subagent-step-name",o.setAttribute("part","subagent-step-name"),o.textContent=e.name,n.append(r,o),this.#e.appendChild(n),this.#s.set(e.toolCallId,n),this.#t.disabled=!1,n}#d(e){this.#e.hidden=!e,this.#t.setAttribute("aria-expanded",String(e))}};var Px=Object.values(Rn);function mp(t){return typeof t!="object"||t===null||Array.isArray(t)?null:t}function jr(t){return typeof t=="string"&&t!==""?t:null}function Dx(t){let e=mp(t);if(e===null)return null;let n=jr(e.toolCallId),r=jr(e.name),o=e.ok;return n===null||r===null||o!==null&&typeof o!="boolean"?null:{toolCallId:n,name:r,ok:o}}function gp(t){let e=mp(t);if(e===null)return null;let n=jr(e.delegationId),r=e.phase;return n===null||typeof r!="string"||!Px.includes(r)?null:{delegationId:n,phase:r,agent:jr(e.agent),status:jr(e.status),tool:Dx(e.tool)}}var Ux=4,Hx=120;function bp(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function ps(t,e,n){let r=bp(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let s=document.createElement("button");s.type="button",s.className="suggestion-chip",s.setAttribute("part","suggestion-chip"),s.textContent=i,s.addEventListener("click",()=>n(i)),o.appendChild(s)}return o}var fs=class{element;#t;#n;#e;#s;#r=!1;constructor(e=se){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="thoughts-toggle",this.#e.setAttribute("part","thoughts-toggle"),this.#e.setAttribute("aria-expanded","true"),this.#t=document.createElement("span"),this.#t.className="thoughts-label",this.#t.setAttribute("part","thoughts-label"),this.#t.textContent=e.thinking,this.#e.append(this.#t),this.#n=document.createElement("pre"),this.#n.className="thoughts-body",this.#n.setAttribute("part","thoughts-body"),this.#e.addEventListener("click",()=>{this.#i(!this.#r)}),this.element.append(this.#e,this.#n)}stream(e){this.#n.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#t.textContent=this.#s.thoughts,this.#i(!0))}#i(e){this.#r=e,this.#n.hidden=e,this.#e.setAttribute("aria-expanded",String(!e))}};var Gx=8,ms=class{element;#t;#n;#e;#s;#r;#i=null;#o;#d=[];#h="";#c;#a;#u="";#p=!0;#y=null;constructor(e,n=se){this.#t=e,this.#o=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.#n=document.createElement("div"),this.#n.className="drawer-panel",this.#n.setAttribute("part","drawer-panel"),this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true"),this.#n.setAttribute("aria-label",n.chatHistory),this.#n.addEventListener("keydown",i=>this.#R(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#e=document.createElement("span"),this.#e.className="drawer-title",this.#e.setAttribute("part","drawer-title"),this.#e.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#t.onNew()}),this.#c=document.createElement("button"),this.#c.type="button",this.#c.className="drawer-close",this.#c.setAttribute("part","drawer-close"),this.#c.title=n.closeHistory,this.#c.setAttribute("aria-label",n.closeHistory),this.#c.append(document.createTextNode("\xD7")),this.#c.addEventListener("click",()=>this.close()),o.append(this.#e,this.#s,this.#c),this.#a=document.createElement("input"),this.#a.type="search",this.#a.className="drawer-filter",this.#a.setAttribute("part","drawer-filter"),this.#a.placeholder=n.searchConversations,this.#a.setAttribute("aria-label",n.searchConversations),this.#a.addEventListener("input",()=>{this.#u=this.#a.value.trim().toLowerCase(),this.#w()}),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#n.append(o,this.#a,this.#r),this.element.append(r,this.#n)}setRelativeTimeFormatter(e){this.#i=e}#_(e){return this.#i!==null?this.#i(e):Or(e,void 0,this.#o)}setStrings(e){this.#o=e,this.#n.setAttribute("aria-label",e.chatHistory),this.#e.textContent=e.chats,this.#s.textContent=e.newChat,this.#c.title=e.closeHistory,this.#c.setAttribute("aria-label",e.closeHistory),this.#a.placeholder=e.searchConversations,this.#a.setAttribute("aria-label",e.searchConversations),this.#w()}setModal(e){this.#p=e,e?(this.#n.setAttribute("role","dialog"),this.#n.setAttribute("aria-modal","true")):(this.#n.setAttribute("role","region"),this.#n.removeAttribute("aria-modal"))}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#y=this.#H(),this.element.hidden=!1,this.#p&&this.#s.focus(),this.#t.onVisibility?.(!0))}close(){this.isOpen()&&(this.element.hidden=!0,this.#p&&this.#y?.focus(),this.#y=null,this.#t.onVisibility?.(!1))}toggle(){this.isOpen()?this.close():this.open()}#H(){return this.element.getRootNode().activeElement}#R(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab"||!this.#p)return;let n=Array.from(this.#n.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#H();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#d=e,this.#h=n,this.#w()}#w(){this.#r.replaceChildren();let e=this.#d.length<Gx;this.#a.hidden=e,e&&this.#u!==""&&(this.#a.value="",this.#u="");let n=this.#G();if(n.length===0){let r=document.createElement("div");r.className="drawer-empty",r.setAttribute("part","drawer-empty"),r.textContent=this.#d.length===0?this.#o.noConversations:this.#o.noMatches,this.#r.appendChild(r);return}for(let r of n)this.#r.appendChild(this.#se(r))}#G(){return this.#u===""?this.#d:this.#d.filter(e=>e.title.toLowerCase().includes(this.#u)||e.preview.toLowerCase().includes(this.#u))}#se(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#h&&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=this.#_(e.updatedAt);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.#t.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.#o.rename,a.setAttribute("aria-label",this.#o.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#z(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#o.delete,l.setAttribute("aria-label",this.#o.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#g(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}#z(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.#w():this.#t.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#w())};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()}#g(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.#o.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#o.delete,i.addEventListener("click",()=>this.#t.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.#o.cancel,s.addEventListener("click",()=>this.#w()),r.append(o,i,s),e.replaceChildren(r)}};function $l(t){return{[le.PENDING]:t.toolRunning,[le.DEFERRED]:t.toolDeferred,[le.DONE]:t.toolDone,[le.ERROR]:t.toolError,[le.DECLINED]:t.toolDeclined}}function zx(t){return{[le.DONE]:t.resultLabel,[le.ERROR]:t.errorLabel,[le.DECLINED]:t.declinedLabel}}function Fx(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var qr=class{element;approvalSlot;subagentSlot;#t;#n;#e;#s;#r;#i;#o;args;#d;#h;#c=!1;constructor(e,n,r,o=se,i={}){this.#o=o,this.args=n,this.#d=e,this.#h=i.formatPayload??null,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",le.PENDING),this.element.setAttribute("data-expanded","false");let s=document.createElement("div");s.className="tool-call-head",s.setAttribute("part","tool-card-head");let a=document.createElement("span");a.className="tool-call-icon",a.setAttribute("part","tool-card-icon"),a.setAttribute("aria-hidden","true");let l=document.createElement("span");l.className="tool-call-name",l.setAttribute("part","tool-card-name"),l.textContent=r??e,this.#t=document.createElement("span"),this.#t.className="tool-call-status",this.#t.setAttribute("part","tool-card-status"),this.#t.textContent=$l(o)[le.PENDING],this.#n=document.createElement("span"),this.#n.className="tool-call-decision",this.#n.setAttribute("part","tool-card-decision"),this.#n.hidden=!0,s.append(a,l,this.#t,this.#n);let c=this.#u("args",o.argumentsLabel);this.#a(c.body,{kind:"arguments",toolName:e,args:n},JSON.stringify(n,null,2)),c.root.hidden=Object.keys(n).length===0;let u=this.#u("result",o.resultLabel);this.#s=u.root,this.#r=u.label,this.#i=u.body,u.root.hidden=!0,this.#e=document.createElement("button"),this.#e.type="button",this.#e.className="tool-call-toggle",this.#e.setAttribute("part","tool-card-toggle"),this.#e.setAttribute("aria-expanded","false"),this.#e.textContent=o.details,this.#e.addEventListener("click",()=>this.#y(!this.#p()));let m=document.createElement("div");m.className="tool-call-body",m.setAttribute("part","tool-card-body"),m.append(c.root,u.root),this.approvalSlot=document.createElement("div"),this.approvalSlot.className="tool-call-approval",this.approvalSlot.setAttribute("part","tool-card-approval"),this.subagentSlot=document.createElement("div"),this.subagentSlot.className="tool-call-subagent",this.subagentSlot.setAttribute("part","tool-card-subagent"),this.element.append(s,this.subagentSlot,this.#e,m,this.approvalSlot)}mark(e){this.#c||(this.element.setAttribute("data-status",e),this.#t.textContent=$l(this.#o)[e])}recordDecision(e){this.element.setAttribute("data-decision",e),this.#n.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#n.hidden=!1}get settled(){return this.#c}settle(e,n){this.#c||(this.#c=!0,this.element.setAttribute("data-status",e),this.#t.textContent=$l(this.#o)[e],this.#r.textContent=zx(this.#o)[e],this.#a(this.#i,{kind:"result",toolName:this.#d,status:e,text:n},Fx(n)),this.#s.hidden=!1)}#a(e,n,r){let o=this.#h===null?null:this.#h(n);if(o===null){e.textContent=r;return}if(e.setAttribute("data-formatted","true"),typeof o=="string"){e.textContent=o;return}e.replaceChildren(o)}#u(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}}#p(){return this.element.getAttribute("data-expanded")==="true"}#y(e){this.element.setAttribute("data-expanded",String(e)),this.#e.setAttribute("aria-expanded",String(e))}};var vp=12e4,gs=class{element;#t;#n;#e;#s="idle";#r=null;#i=null;#o=[];#d=null;#h=!1;#c=!1;constructor(e){this.#t=e.transcribe,this.#n=e.onText,this.#e=e.strings??se,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=Lc,this.element.append(n),this.#R("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#u();return}this.#s!=="transcribing"&&await this.#a()}async#a(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#H(this.#e.transcriptionFailed);return}this.#i=e,this.#o=[],this.#h=!1;let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#y(n.mimeType)}),this.#r=n,n.start(),this.#d=setTimeout(()=>{this.#h=!0,this.#u()},vp),this.#R("recording")}#u(){this.#p(),this.#r?.stop()}#p(){this.#d!==null&&(clearTimeout(this.#d),this.#d=null)}dispose(){this.#c=!0,this.#p(),this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#_()}async#y(e){if(this.#c)return;this.#_(),this.#R("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#t(n);this.#R("idle"),this.#h&&(this.element.title=this.#e.recordingLimit.replace("{n}",String(vp/6e4))),r!==""&&this.#n(r)}catch(r){this.#H(r instanceof Error?r.message:this.#e.transcriptionFailed)}finally{this.#r=null}}#_(){for(let e of this.#i?.getTracks()??[])e.stop();this.#i=null}#H(e){this.#_(),this.#r=null,this.#R("idle"),this.element.title=e}#R(e){this.#s=e,this.element.dataset.state=e;let n=this.#w(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#w(e){return e==="recording"?this.#e.stopRecording:e==="transcribing"?this.#e.transcribing:this.#e.recordVoice}};var bs=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},ir=class{#t;#n;#e;#s;#r;#i;#o;#d=new Set;#h;#c;#a=!1;constructor(e){this.#t=e.agent,this.#n=e.handlers,this.#e=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#i=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#h=e.connectionLostMessage??"Connection lost";let n=e.maxToolRounds??Cn;this.#c=n>=1?Math.floor(n):Cn;let r=e.onStateChanged;r!==void 0&&this.#t.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#t.state}setState(e){this.#t.setState({...e})}get running(){return this.#t.isRunning}get messages(){return this.#t.messages}async send(e,n=[]){let r={id:Ie(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#t.addMessage(r),this.#o(this.#t.messages),await this.#u()}truncateToLastUser(){let e=[...this.#t.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#t.setMessages(r),this.#o(this.#t.messages),r}async resume(){await this.#u()}addToolResult(e,n){this.#t.addMessage({id:Ie(),role:"tool",content:n,toolCallId:e}),this.#o(this.#t.messages)}cancel(){this.#a=!0,this.#t.abortRun()}async#u(){this.#a=!1;try{await this.#y(),this.#a&&this.#p()}catch(e){this.#a||$x(e)?this.#p():this.#n.onError(e instanceof Error?e.message:String(e))}finally{this.#n.onSettled()}}#p(){this.#o(this.#t.messages),this.#n.onCancelled()}async#y(){let e;for(let n=0;n<this.#c;n+=1){if(this.#a)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#e(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#t.runAgent(i,this.#_(r,o)),e=void 0,this.#o(this.#t.messages),this.#a)return;if(!o.terminal)throw new bs(this.#h);if(o.errored)return;if(o.interrupts.length>0){if(this.#i===null)return;let a=await this.#i(o.interrupts);if(this.#a)return;e=Qu(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.#t.addMessage({id:Ie(),role:"tool",content:l.content,toolCallId:a.id}),this.#o(this.#t.messages),s=!0}}if(!s)return}}#_(e,n){let r=this.#n,o=this.#d,i=()=>this.#a,s=new Set;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:a}){o.has(a.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${a.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:a}){r.onTextDelta(a)},onTextMessageEndEvent({event:a,textMessageBuffer:l}){o.add(a.messageId),r.onTextEnd(l)},onToolCallEndEvent({event:a,toolCallName:l,toolCallArgs:c}){let u={id:a.toolCallId,name:l,args:c};e.push(u),r.onToolCall(u)},onToolCallResultEvent({event:a}){r.onToolResult(a.toolCallId,a.content)},onActivitySnapshotEvent({event:a,messages:l}){if(l.some(u=>u.id===a.messageId&&u.role==="activity")){r.onActivityChanged(a.messageId,a.activityType,a.content);return}r.onActivity(a.activityType,a.content,a.messageId)},onActivityDeltaEvent({event:a}){s.add(a.messageId)},onCustomEvent({event:a}){r.onCustomEvent(a.name,a.value)},onSubagentStartedEvent({event:a}){r.onSubAgentStarted(a.subagentRunId,a.name,a.parentToolCallId??null)},onSubagentFinishedEvent({event:a}){r.onSubAgentFinished(a.subagentRunId)},onSubagentErrorEvent({event:a}){r.onSubAgentError(a.subagentRunId,a.message)},onMessagesSnapshotEvent({event:a}){r.onMessagesSnapshot(a.messages)},onMessagesChanged({messages:a}){if(s.size!==0){for(let l of s){let c=a.find(u=>u.id===l);c!==void 0&&c.role==="activity"&&r.onActivityChanged(l,c.activityType,c.content)}s.clear()}},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:a}){r.onReasoningDelta(a)},onReasoningMessageEndEvent({reasoningMessageBuffer:a}){r.onReasoningDelta(a)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(a){n.terminal=!0,a.outcome==="interrupt"&&(n.interrupts=a.interrupts)},onRunErrorEvent({event:a}){n.terminal=!0,n.errored=!0,!i()&&r.onError(a.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function $x(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function Bl(t){let e=t.attachments;return Array.isArray(e)?e.filter(Bx):[]}function Bx(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 yp="ag-ui-chat",sr="thread",Vl="threads",Wr="messages:",ys="checkpoint:",Xr="minted:",Vx=60,jx=100,qx="New conversation",wp=!1;function bt(t,e){try{sessionStorage.setItem(t,e)}catch{if(wp)return;wp=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function vs(t){return t===""?yp:`${yp}@${t}`}var Ze=class t{#t;constructor(e=""){this.#t=vs(e),e!==""&&t.adopt("",e)}static adopt(e,n){let r=`${vs(e)}:`,o=`${vs(n)}:`;for(let[i,s]of xp(r)){let a=sessionStorage.getItem(i),l=o+s;a!==null&&sessionStorage.getItem(l)===null&&bt(l,a),sessionStorage.removeItem(i)}}static purge(e){for(let[n]of xp(`${vs(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#r(sr))??this.newThread()}newThread(){let e=Ie();return bt(this.#r(sr),e),bt(this.#r(Xr+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#r(Xr+e))!==null&&sessionStorage.getItem(this.#r(Wr+e))===null}loadMessages(e){return Promise.resolve(this.#i(this.#r(Wr+e)))}saveMessages(e,n){bt(this.#r(Wr+e),JSON.stringify(n)),sessionStorage.removeItem(this.#r(Xr+e)),this.#n(e,n)}loadCheckpoint(e){return this.#i(this.#r(ys+e))}saveCheckpoint(e,n){let r=this.#r(ys+e);if(n===null){sessionStorage.removeItem(r);return}bt(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Wr+e)),sessionStorage.removeItem(this.#r(ys+e)),sessionStorage.removeItem(this.#r(Xr+e)),this.#s(this.#e().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(sr))===e&&sessionStorage.removeItem(this.#r(sr))}listThreads(){let e=this.#e().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){bt(this.#r(sr),e)}renameThread(e,n){let r=this.#e(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#n(e,n){let r=this.#e(),o=r.find(a=>a.threadId===e),i=Xx(n),s=Date.now();o===void 0?r.push({threadId:e,title:Ep(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Ep(n))),this.#s(r)}#e(){return this.#i(this.#r(Vl))??[]}#s(e){let n=this.#r(Vl);if(e.length===0){sessionStorage.removeItem(n);return}bt(n,JSON.stringify(e))}#r(e){return`${this.#t}:${e}`}#i(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function xp(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);Wx(o)&&e.push([r,o])}return e}function Wx(t){return t===sr||t===Vl||t.startsWith(Wr)||t.startsWith(ys)||t.startsWith(Xr)}function Ep(t){for(let e of t)if(e.role==="user"){let n=_p(e.content);if(n!=="")return Tp(n,Vx)}return qx}function Xx(t){for(let e of[...t].reverse()){let n=_p(e.content);if(n!=="")return Tp(n,jx)}return""}function _p(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Tp(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Qe(t,e){return e===void 0?t:{...t,credentials:e}}function ws(t){if(t.newThread!==void 0)return t.newThread();let e=Ie();return t.setActiveThread(e),e}function xs(t,e,n,r){if(e.length===0)return;let o=new URL(String(t),location.href).origin;o===location.origin||n.includes(o)||r.has(o)||(r.add(o),console.warn(`<ag-ui-chat>: sending host credentials (${e.join(", ")}) to ${o}, which is not this page's origin (${location.origin}). Those headers are the page's own authentication, and whichever server answers the browser's preflight receives them \u2014 so a URL attribute built from a query parameter or from tenant-authored configuration is a channel for the token to leave on. If this destination is deliberate, name it in \`trustedOrigins\` to confirm it and silence this notice. Reported once per origin.`))}function jl(t){let e=t.headers??{},n=new Set;return new Ju({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),s=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(xs(r,s,t.trustedOrigins??[],n),i===void 0)return fetch(r,Qe(o,t.credentials));let a=new Headers(o?.headers);for(let[l,c]of Object.entries(i))a.set(l,c);return fetch(r,Qe({...o,headers:a},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var Yr=class{#t;#n;#e;#s;#r;#i=new Set;#o=new Map;constructor(e,n=()=>({}),r=new Ze,o=()=>{},i=!0){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r,this.#s=o,this.#r=i}threadId(){return this.#e.threadId()}setActiveThread(e){this.#e.setActiveThread(e)}newThread(){return ws(this.#e)}isUnsent(e){return this.#e.isUnsent?.(e)===!0}saveMessages(e,n){this.#e.saveMessages(e,this.#r?n:[])}loadCheckpoint(e){return this.#e.loadCheckpoint(e)}saveCheckpoint(e,n){this.#e.saveCheckpoint(e,n)}renameThread(e,n){this.#e.renameThread(e,n),this.#o.set(e,n),this.#u(e,"PATCH",{title:n})}clear(e){this.#e.clear(e),this.#i.add(e),this.#u(e,"DELETE")}async listThreads(){let e=await this.#d();return e===null?this.#e.listThreads():e.filter(n=>!this.#i.has(n.thread_id)).map(n=>this.#c(n))}async loadMessages(e){if(this.#e.isUnsent?.(e)===!0)return null;let n=await this.#a(`${this.#t}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#e.loadMessages(e);let r=await this.#h(n);return r===null?this.#e.loadMessages(e):r.messages??null}async#d(){let e=await this.#a(this.#t);if(e===null||!e.ok)return null;let n=await this.#h(e);return n===null?null:n.threads??[]}async#h(e){try{return await e.json()}catch{return null}}#c(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#a(e){try{return await fetch(e,Qe({headers:this.#n()},this.#s()))}catch{return null}}async#u(e,n,r){let o=this.#n();try{await fetch(`${this.#t}${encodeURIComponent(e)}/`,Qe({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#s()))}catch{}}};var Kr=class{#t;#n;#e;constructor(e,n=()=>({}),r=()=>{}){this.#t=e.endsWith("/")?e:`${e}/`,this.#n=n,this.#e=r}async list(){try{let e=await fetch(this.#t,Qe({method:"GET",headers:{Accept:"application/json",...this.#n()}},this.#e()));return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#s("resume",e)}forkUrl(e){return this.#s("fork",e)}#s(e,n){return`${this.#t.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function ql(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,Qe({method:"POST",headers:{...e.headers??{}},body:n},e.credentials));if(!r.ok)throw new Error(await Yx(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 Yx(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Wl(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(Kx(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(Zx(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 Kx(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 Zx(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Qx=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],Ql=["omit","same-origin","include"];function Xl(t){return Ql.includes(t)}var Sp="ag-ui-chat:collapsed",Ap="ag-ui-chat:size",kp="ag-ui-chat:theme",Yl="ag-ui-chat:launcher";function Jx(t){if(typeof t!="object"||t===null)return null;let{left:e,top:n}=t;return typeof e=="number"&&typeof n=="number"?{left:e,top:n}:null}var Ip=new Set([null,"","floating","bottom-left"]),eE=[{y:"top"},{y:"bottom"},{x:"left"},{x:"right"},{x:"left",y:"top"},{x:"right",y:"top"},{x:"left",y:"bottom"},{x:"right",y:"bottom"}],Kl=6,Zl=new Set,Zr=class extends HTMLElement{agentFactory=jl;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>[...this.#At().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#r.tools()];getContext=()=>[...tl(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new Ze;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#t={};#n=new Set;#e=se;#s=new Set;#r=new kr;#i=new Map;#o=new Map;#d=new Map;#h=new Map;#c=new Set;#a=new Map;#u=new Map;#p=new Set;#y=[];#_=new Set;#H=null;#R=new Set;#w;#G=document.createElement("div");#se=document.createElement("div");#z=document.createElement("button");#g=document.createElement("button");#je="";#ae=null;#Ie=document.createElement("div");#v;#K=null;#Re=!1;#x;#b;#l;#T;#Ce;#F;#I;#S;#qe=null;#L;#C;#N;#Ne;#$;#f;#B;#le=document.createElement("span");#Oe=0;#Z;#A=null;#E=null;#ce=[];#Q=[];#V=document.createElement("div");#J=null;#P=null;#ee=null;#te={x:"right",y:"bottom"};#xt=new Map;#de=()=>{this.#Dt(),!this.#cn()&&(this.#st(),this.#I.isOpen()&&(this.#I.setModal(!this.#dt()),this.#ut()))};#ln(e){let n=this.#O(),r=n.left+Je,o=n.top+Je,i=n.left+n.width-Je,s=n.top+n.height-Je;return{left:Math.min(Math.max(e.left,r),e.right),top:Math.min(Math.max(e.top,o),e.bottom),right:Math.max(Math.min(e.right,i),e.left),bottom:Math.max(Math.min(e.bottom,s),e.top)}}#cn(){return this.#f.hasAttribute("data-dragging")||this.#w.querySelector(".header[data-dragging]")!==null}#Me;#We=null;#ue=!1;#ne=null;#he={};#W=!1;#Xe=null;#D=null;#Le=null;#Ye=0;#Pe="";#re=null;#De=null;#j=null;#oe=null;#m="";#pe="";#Ue=null;#Ke="";#Et="";#ye=null;#Ze=0;#Qe=[];#_t=[];#Tt=[];#St=[];constructor(){super(),this.#w=this.attachShadow({mode:"open"}),this.#x=document.createElement("div"),this.#b=document.createElement("div"),this.#l=document.createElement("textarea"),this.#T=document.createElement("button"),this.#Ce=document.createElement("span"),this.#L=document.createElement("div"),this.#C=document.createElement("button"),this.#N=document.createElement("input"),this.#Ne=document.createElement("div"),this.#Me=document.createElement("span"),this.#$=document.createElement("button"),this.#f=document.createElement("button"),this.#B=document.createElement("span"),this.#Z=document.createElement("div"),this.registerActivityRenderer({type:Qs,render:e=>{let n=iE(e);return n===null?null:Fl("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(n)),"compaction")}}),this.registerActivityRenderer({type:Xs,render:e=>ps(e,this.#e,n=>{this.sendMessage(n)})}),this.#F=new us(e=>this.#Dn(e)),this.#I=new ms({onSelect:e=>{this.#Qn(e)},onNew:()=>{this.newChat(),this.#Ae()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#Ae()},onDelete:e=>{this.#Jn(e)},onVisibility:()=>{this.#ut()}}),this.#S=new Mr((e,n)=>{this.#dn(e,n)})}#Je(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#qe===null&&(this.#qe=new Kr(e,()=>this.#xe(e),()=>this.#He())),this.#qe)}async#dn(e,n){let r=this.#Je();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="",this.#Y();let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#m,initialMessages:[]});await new ir({agent:s,handlers:this.#en(),getTools:()=>this.#kt(),getContext:()=>this.#Wt(),executeTool:l=>this.#Qt(l),resolveInterrupts:l=>this.#Jt(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#un(){let e=this.#Je();this.#S.setRelativeTimeFormatter(this.formatRelativeTime),this.#S.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement","credentials","user-key",...Qx]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Xl(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${Ql.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.#Fn(),this.#qn(),!this.#ze()&&this.collapsed&&this.setCollapsed(!1),requestAnimationFrame(()=>this.#fe());return}if(e==="title-text"){this.#Ce.textContent=r??this.#e.title,this.#le.textContent=this.#Ce.textContent;return}if(e==="user-key"){this.#ue&&(n??"")!==(r??"")&&this.#Kn(n??"",r??"");return}n===r||!this.#ue||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.#r.register(e)}get sharedState(){return this.#ne?.state??this.#he}set sharedState(e){this.#he={...e},this.#ne?.setState(this.#he)}registerPageState(e){for(let n of Yi(e))this.#r.register(n)}registerStateHook(e){this.registerPageState(e)}#hn(){return this.routeMap.length===0?[]:rl(()=>this.routeMap,()=>this.navigate)}#pn(){let e=this.getPageMap;return e===null?[]:[{name:Ks,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:[],[xe]:"Read the page"},handler:()=>e()}]}#fn(){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[...el(n,r=>this.resolvePageTarget(r)),...n.has(Cr.CHAT)?Ba(this):[]]}#At(){return[...this.#hn(),...this.#pn(),...this.#fn(),...this.#mn()]}#mn(){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.#gn(e)}]:[]}async#gn(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.#D=new AbortController;let i=this.#D.signal;this.#U();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await yl(this.#M(),r,{signal:i,strings:this.#e});return this.#D=null,this.#k(),this.#v.follow(),s}#kt(){let e=this.getTools();return this.#s=new Set(e.map(n=>n.name)),e}#et(e){let n=this.#At().find(r=>r.name===e);return n!==void 0?n:this.#r.has(e)?this.#r.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Xl(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Xl(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${Ql.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#we(){return{...this.headers,...this.getHeaders?.()}}#xe(e){let n=this.#we();return xs(e,Object.keys(n),this.trustedOrigins,this.#n),n}#He(){return this.credentials??void 0}#Ge(){let e=this.#He();return e===void 0?{}:{credentials:e}}#It(e){return Qe({headers:this.#xe(e)},this.#He())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===Nn.INLINE||e===Nn.MINIMAL||e===Nn.COMPACT?e:Nn.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#pe=this.#Yn(),this.#ot(this.#$t()),requestAnimationFrame(()=>{this.#st(),this.#fe()}),this.#e=ol({...this.#vn(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#lt(kp);e!==null&&this.setAttribute("theme",e)}if(this.#or(),this.#I.setStrings(this.#e),this.#S.setStrings(this.#e),this.#ze()&&this.#Hn()&&this.setAttribute("collapsed",""),this.#Kt(),this.#Ln(),this.conversationStore instanceof Ze){let e=this.#at();this.#ye=e===""?this.conversationStore:new Ze(e),this.conversationStore=this.#ye}window.addEventListener("resize",this.#de),window.visualViewport?.addEventListener("resize",this.#de),window.visualViewport?.addEventListener("scroll",this.#de),this.#Dt(),this.#Nt(),this.#yn(),this.#xn(),this.#m=this.conversationStore.threadId(),queueMicrotask(()=>this.#bn()),this.#Fe(),this.#ue=!0}#bn(){this.#ue&&(this.#Ot(),this.#Mt())}async reload(){this.#X(),this.#Se(),this.#ie(!1),await Promise.all([this.#Ot(),this.#Mt(),this.#Fe()])}disconnectedCallback(){this.#ue=!1,window.removeEventListener("resize",this.#de),window.visualViewport?.removeEventListener("resize",this.#de),window.visualViewport?.removeEventListener("scroll",this.#de),this.#Ue!==null&&(Zl.delete(this.#Ue),this.#Ue=null),this.#X(),this.#ae?.detach(),this.#ae=null,this.#A?.dispose(),this.#We?.dispose(),this.#v.dispose(),this.#K!==null&&(clearTimeout(this.#K),this.#K=null)}#Rt(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#vn(){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{}}#yn(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#wn(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new Zi({upload:n,maxBytes:this.#In(),accept:r,strings:this.#e,onChange:()=>this.#pr(o)});this.#A=o,this.#Ne.appendChild(this.#A.element),this.#N.accept=r,this.#C.hidden=!1,this.#Cn(),this.#Mn(o)}#wn(e){return e===null?null:(n,r,o)=>Wl(n,{url:e,headers:this.#xe(e),...this.#Ge(),onProgress:r,signal:o})}#xn(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#En(e);n!==null&&(this.#We=new gs({transcribe:n,onText:r=>this.#_n(r),strings:this.#e}),this.#Me.appendChild(this.#We.element))}#En(e){return e===null?null:n=>ql(n,{url:e,headers:this.#xe(e),...this.#Ge()})}#_n(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#Zt(),this.#l.focus()}quote(e){let n=ml(e);if(n==="")return;let r=this.#l.value.replace(/\s+$/,"");this.#l.value=r===""?n:`${r}
3667
3667
 
3668
- ${n}`,this.#Y(),this.#l.focus();let o=this.#l.value.length;this.#l.setSelectionRange(o,o)}offerQuoteInPage(e=document.body){this.#ae?.detach();let n=bl({within:e,label:this.#e.quoteSelection,exclude:this,onQuote:r=>this.quote(r)});return this.#ae=n,()=>{n.detach(),this.#ae===n&&(this.#ae=null)}}#Tn(){return this.getAttribute("data-quote-selection")!=="false"}#Ct(e){if(!this.#Tn())return;let n=e===void 0?void 0:{x:e.clientX,y:e.clientY},r=Dr(this.#b,[this.#w],n);if(r===null){this.#tt();return}this.#je=r.text,this.#Sn(r.rect)}#Sn(e){this.#g.hidden=!1;let n=this.#Ie.getBoundingClientRect(),r=e.top-n.top,o=r<Kl+this.#g.offsetHeight;this.#g.dataset.below=String(o),this.#g.style.top=`${o?e.bottom-n.top+Kl:r-Kl}px`;let i=this.#g.offsetWidth/2,s=e.left+e.width/2-n.left;this.#g.style.left=`${Math.min(Math.max(s,i),n.width-i)}px`}#tt(){this.#g.hidden=!0,this.#je=""}#An(){let e=this.getAttribute("data-max-tool-rounds");return e===null?Cn:Number.parseInt(e,10)}#kn(){let e=this.getAttribute("data-message-actions");return e===null?new Set([Ft.COPY,Ft.RETRY]):new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}#In(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Zs;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Zs}#Rn(){let e=this.#N.files;if(e!==null)for(let n of Array.from(e))this.#A?.add(n);this.#N.value=""}#Cn(){this.#x.addEventListener("dragover",e=>{e.preventDefault(),this.#x.classList.add("chat--dragover")}),this.#x.addEventListener("dragleave",()=>{this.#x.classList.remove("chat--dragover")}),this.#x.addEventListener("drop",e=>{e.preventDefault(),this.#x.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#A?.add(r)})}#Nn(e,n,r){let o=this.#On(),i=n.getData("text/plain");if(o===null||i.length<o)return;e.preventDefault();let s=new Date().toISOString().replace(/[:.]/g,"-");r.add(new File([i],`pasted-${s}.txt`,{type:"text/plain"}))}#On(){let e=this.getAttribute("data-paste-attach");if(e===null)return mo;if(e==="off")return null;let n=Number.parseInt(e,10);return Number.isNaN(n)||n<=0?(console.warn(`<ag-ui-chat>: data-paste-attach="${e}" is neither "off" nor a positive number of characters, so the default of ${mo} is used.`),mo):n}#Mn(e){this.#x.addEventListener("paste",n=>{let r=n.clipboardData??null;if(r===null)return;let o=Array.from(r.files);if(o.length===0){this.#Nn(n,r,e);return}r.getData("text/plain")===""&&n.preventDefault();for(let i of o)this.#A?.add(rE(i))})}#Nt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new Yr(e,()=>this.#xe(e),this.conversationStore,()=>this.#He(),this.getAttribute("data-threads-cache")!=="false"))}async#Ot(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#t=nl(await n.json())}catch{}}setSkills(e){this.#St=e,this.#nt()}#Ln(){this.#F.enableChips(this.#Rt("data-prompt-chips")),this.#F.enableSlash(this.#Rt("data-slash-commands")),this.#Tt=this.#Pn(),this.#nt()}#Pn(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return $a(JSON.parse(e))}catch{return[]}}async#Mt(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#_t=$a(await n.json()),this.#nt()}catch{}}#nt(){let e=new Map;for(let n of[...this.#_t,...this.#Tt,...this.#St])e.set(n.name,n);this.#F.setSkills([...e.values()])}#Dn(e){if(e.prompt===void 0){this.#L.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=eh(e.prompt,this.skillContext());if(r.length>0){this.#L.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#L.hidden=!1,this.#l.value=n,this.#Y(),this.#l.focus(),this.#Un(n);return}if(this.#L.hidden=!0,this.#l.value=n,this.#Y(),e.sendImmediately===!1){this.#l.focus();return}this.#ft()}#Un(e){let n=e.indexOf("{");this.#l.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e,n={}){e&&!this.#ze()||(n.announce===!0&&e&&!this.collapsed&&this.#in(this.#e.chatMinimised,null),e||this.#st(),e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),bt(this.#Te(Sp),e?"1":"0"),this.#Be(0),this.dispatchEvent(new CustomEvent(zs,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){return this.#Oe}#Hn(){let e=this.#Vt(Sp);return e!==null?e==="1":Ip.has(this.getAttribute("placement"))&&!this.hasAttribute("data-start-open")}#ze(){return this.getAttribute("placement")!=="page"}describeSurface(){let e=this.getBoundingClientRect(),n=this.#O(),r=e.width>=n.width-1&&e.height>=n.height-1;return{placement:this.getAttribute("placement"),collapsed:this.collapsed,collapsible:this.#ze(),movable:this.#q()&&!r,draggable:this.#q(),fullBleed:r,box:{left:Math.round(e.left),top:Math.round(e.top),width:Math.round(e.width),height:Math.round(e.height)},viewport:{left:Math.round(n.left),top:Math.round(n.top),width:Math.round(n.width),height:Math.round(n.height)}}}moveTo(e,n={}){if(!this.#q())return!1;let r=n.announce===!0?this.#Gn():null,o=this.#O(),i=this.getBoundingClientRect();if(i.width>=o.width-1&&i.height>=o.height-1)return!1;let[s,a]=e.split("-"),l=o.left+$t,c=o.top+$t,u=a==="left"?l:Math.max(l,o.left+o.width-$t-i.width),m=s==="top"?c:Math.max(c,o.top+o.height-$t-i.height),w={left:u,top:m,right:u+i.width,bottom:m+i.height},p=this.#f.offsetWidth,h=this.#f.offsetHeight;return this.#it(w,{left:a==="left"?w.left:w.right-p,top:s==="top"?w.top:w.bottom-h,width:p,height:h}),this.#_e(),r!==null&&this.#in(this.#e.chatMoved,r),!0}#Gn(){let e=this.style.getPropertyValue("--ag-ui-inset"),n=this.style.getPropertyValue("--ag-ui-launcher-inset"),r=this.getAttribute("data-expand-corner"),o=this.#E,i=this.#P,s=this.#ee;return()=>{let a=(l,c)=>{c===""?this.style.removeProperty(l):this.style.setProperty(l,c)};a("--ag-ui-inset",e),a("--ag-ui-launcher-inset",n),r===null?this.removeAttribute("data-expand-corner"):this.setAttribute("data-expand-corner",r),this.#E=o,this.#P=i,this.#ee=s,o===null?this.#Zn(Yl):this.#_e(),this.#fe()}}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),this.#ct(kp,e),this.#jt()}#rt(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#zn(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height"),o=this.#Lt(e,-1),i=o.x===null||o.y===null?this.#Lt(e,1):o;return this.#Pt("--ag-ui-width",n),this.#Pt("--ag-ui-height",r),{x:o.x??i.x??"right",y:o.y??i.y??"bottom"}}#Lt(e,n){this.#ot({width:e.width+n,height:e.height+n});let r=this.getBoundingClientRect(),o=(i,s)=>Math.abs(i-s)>=.5;return{x:o(r.width,e.width)?o(r.left,e.left)?"right":"left":null,y:o(r.height,e.height)?o(r.top,e.top)?"bottom":"top":null}}#fe(){if(!this.#ue)return;let e=this.#ee??this.#zn();this.#te=e,this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`),this.#Ft()}#Pt(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ot(e){let n=this.#rt();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`))}#Fn(){let e=this.#rt();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#q(){return this.getAttribute("data-launcher-drag")!=="false"&&Ip.has(this.getAttribute("placement"))}#O(){let e=window.visualViewport,n=e?.width??window.innerWidth,r=e?.height??window.innerHeight,o=getComputedStyle(this.#se),i=l=>{let c=Number.parseFloat(o.getPropertyValue(l));return Number.isFinite(c)?c:0},s=i("padding-left"),a=i("padding-top");return{left:s,top:a,width:Math.max(0,n-s-i("padding-right")),height:Math.max(0,r-a-i("padding-bottom"))}}#Ee(){let e=document.documentElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}#Dt(){let e=window.visualViewport;if(e==null)return;if(Math.abs(e.height-window.innerHeight)<1){this.style.removeProperty("--ag-ui-visual-viewport-height"),this.style.removeProperty("--ag-ui-visual-viewport-inset-bottom");return}this.style.setProperty("--ag-ui-visual-viewport-height",`${Math.round(e.height)}px`);let n=window.innerHeight-e.height-e.offsetTop;this.style.setProperty("--ag-ui-visual-viewport-inset-bottom",`${Math.max(0,Math.round(n))}px`)}#me(){let e=this.#f.offsetWidth,n=this.#f.offsetHeight,r=this.#E;if(r!==null)return{left:r.left,top:r.top,width:e,height:n};let o=this.#f.getBoundingClientRect();return{left:o.left+o.width/2-e/2,top:o.top+o.height/2-n/2,width:e,height:n}}#Ut(e){if(!this.#q())return;this.#E=e,this.#P=null;let n=this.getBoundingClientRect(),r=hl(this.#me(),{width:n.width,height:n.height},this.#O(),this.#Ee());this.style.setProperty("--ag-ui-inset",r.hostInset),this.style.setProperty("--ag-ui-launcher-inset",r.launcherInset),this.#ee=r.corner,this.setAttribute("data-expand-corner",`${r.corner.y}-${r.corner.x}`),this.#fe()}#Ht(e,n){this.#Ut({left:e,top:n})}#$n(e,n){this.#Ht(e,n),this.#_e()}#Gt(e,n){if(!this.#q())return{held:e,launcher:null};if(this.#E===null){let c=this.#me();this.#E={left:c.left,top:c.top}}let r=this.#E,o=Lr(e,this.#O(),Je),i=this.#ee??this.#te,s=this.#Ee();this.style.setProperty("--ag-ui-inset",[i.y==="top"?`${Math.round(o.top)}px`:"auto",i.x==="right"?`${Math.round(s.width-o.right)}px`:"auto",i.y==="bottom"?`${Math.round(s.height-o.bottom)}px`:"auto",i.x==="left"?`${Math.round(o.left)}px`:"auto"].join(" ")),this.#P={left:o.left,top:o.top};let a={...this.#me(),left:r.left+(o.left-n.left),top:r.top+(o.top-n.top)},l={...a,...Pt(a,this.#O())};return this.style.setProperty("--ag-ui-launcher-inset",Pr(o,l,i,this.#Ee()).launcherInset),{held:o,launcher:l}}#Bn(e,n){let{held:r,launcher:o}=this.#Gt(e,n);o!==null&&(this.#it(r,o),this.#_e())}#it(e,n){let r=this.#O(),o=this.#Ee(),i={width:e.right-e.left,height:e.bottom-e.top},{corner:s}=hl(n,i,r,o),a=Pr(e,n,s,o);this.style.setProperty("--ag-ui-inset",a.hostInset),this.style.setProperty("--ag-ui-launcher-inset",a.launcherInset),this.#E={left:n.left,top:n.top},this.#P={left:e.left,top:e.top},this.#ee=s,this.setAttribute("data-expand-corner",`${s.y}-${s.x}`),this.#fe()}#Vn(e){if(!this.#q())return;let n=this.getBoundingClientRect(),r=Lr({left:e.left,top:e.top,right:e.left+n.width,bottom:e.top+n.height},this.#O(),Je),o=this.#me(),i={...o,left:o.left+(r.left-e.left),top:o.top+(r.top-e.top)};this.#it(r,{...i,...Pt(i,this.#O())})}#_e(){let e=this.#E;if(e===null)return;let n=this.#P;this.#ct(Yl,JSON.stringify(n===null?e:{...e,panel:n}))}#st(){let e=this.#jn(),n=this.#E??e;if(n===null)return;let r=this.#P??e?.panel??null;if(r!==null){this.#E={left:n.left,top:n.top},this.#Vn(r);return}let o=this.#me();this.#Ut(Pt({...o,left:n.left,top:n.top},this.#O()))}#jn(){let e=this.#lt(Yl);if(e===null)return null;try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;let{left:r,top:o,panel:i}=n;if(typeof r!="number"||typeof o!="number")return null;let s=Jx(i);return s===null?{left:r,top:o}:{left:r,top:o,panel:s}}catch{return null}}#qn(){this.#q()||(this.#E=null,this.#P=null,this.#ee=null,this.style.removeProperty("--ag-ui-inset"),this.style.removeProperty("--ag-ui-launcher-inset"),this.removeAttribute("data-expand-corner"))}#zt(e,n){if(n=this.#ln(n),this.#ot({width:n.right-n.left,height:n.bottom-n.top}),e.x!==this.#te.x&&e.y!==this.#te.y)return n;let r=this.#Ee(),o=this.#te,i=s=>`${Math.round(s)}px`;if(this.style.setProperty("--ag-ui-inset",[o.y==="top"?i(n.top):"auto",o.x==="right"?i(r.width-n.right):"auto",o.y==="bottom"?i(r.height-n.bottom):"auto",o.x==="left"?i(n.left):"auto"].join(" ")),this.#E!==null){let s=this.#f.offsetWidth;this.#E={left:o.x==="left"?n.left:n.right-s,top:o.y==="top"?n.top:n.bottom-s}}return this.#P!==null&&(this.#P={left:n.left,top:n.top}),n}#Wn(e,n){let r=this.#zt(e,n);this.#Xn({width:r.right-r.left,height:r.bottom-r.top}),this.#_e(),this.#fe()}#Ft(){let e=`${this.#te.y==="top"?"bottom":"top"}-${this.#te.x==="left"?"right":"left"}`;for(let[n,r]of this.#xt){let o=n===e;r.tabIndex=o?0:-1,o?r.removeAttribute("aria-hidden"):r.setAttribute("aria-hidden","true")}}#Xn(e){let n={...this.#$t(),...e};this.#ct(Ap,JSON.stringify(n))}#$t(){let e=this.#lt(Ap);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#Yn(){let e=this.id!==""?this.id:this.endpoint;return e===""?"":this.#Et===e?this.#Ke:Zl.has(e)?(this.#Et=e,this.#Ke=`${e}~${Ie()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${e}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#Ke):(Zl.add(e),this.#Ue=e,e)}#at(e=this.userKey){return e===""?this.#pe:`${this.#pe}#${e}`}#Kn(e,n){let r=this.#at(e),o=this.#at(n);if(e===""){Ze.adopt(r,o),this.#Bt(o);return}Ze.purge(r),this.#Bt(o),this.#X(),this.#Se(),this.#ie(!1),this.#Be(0),this.#m=this.conversationStore.threadId(),this.#Fe(),this.#Ae()}#Bt(e){this.#ye!==null&&(this.#ye=new Ze(e),this.conversationStore=this.#ye,this.#Nt())}#Te(e){return this.#pe===""?e:`${e}:${this.#pe}`}#Vt(e){let n=sessionStorage.getItem(this.#Te(e));return n!==null||this.#pe===""?n:sessionStorage.getItem(e)}#lt(e){try{let n=localStorage.getItem(this.#Te(e));if(n!==null)return n}catch{}return this.#Vt(e)}#ct(e,n){let r=this.#Te(e);try{localStorage.setItem(r,n)}catch{}bt(r,n)}#Zn(e){let n=this.#Te(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#jt(){let e=this.getAttribute("theme")==="dark";this.#$.replaceChildren(this.#pt("theme","theme-icon",e?Dc:Pc,null))}openThreads(){this.#S.close(),this.#Ae(),this.#I.setModal(!this.#dt()),this.#I.open(),this.#ut()}#dt(){return this.getAttribute("placement")==="page"&&this.getBoundingClientRect().width>=Xc}#ut(){this.#I.isOpen()&&this.#dt()?this.setAttribute("data-threads-docked",""):this.removeAttribute("data-threads-docked")}openCheckpoints(){this.#I.close(),this.#un(),this.#S.open()}closeThreads(){this.#I.close()}closeCheckpoints(){this.#S.close()}toggleCheckpoints(){if(this.#S.open_){this.#S.close();return}this.openCheckpoints()}newChat(){this.#X(),this.conversationStore.isUnsent?.(this.#m)===!0&&this.conversationStore.clear(this.#m),this.#Se(),this.#m=ws(this.conversationStore),this.#ie(!1),this.#Be(0)}#Se(){this.#ne=null,this.#qt(),this.#Qe=[],this.#ce.length=0,this.#J=null}#qt(){this.#be(),this.#j=null,this.#oe=null,this.#U(),this.#i.clear(),this.#o.clear(),this.#d.clear(),this.#p.clear(),this.#a.clear(),this.#u.clear(),this.#H=null,this.#A?.clear(),this.#b.replaceChildren(this.#Z),this.#k()}async retryLastTurn(){if(this.#W)return!1;let e=this.#mt(),n=e.truncateToLastUser();if(n===null)return!1;this.#qt();for(let r of n)this.#Xt(r);return await e.resume(),!0}async#Qn(e){e!==this.#m&&(this.#X(),this.#Se(),this.conversationStore.setActiveThread(e),this.#m=e,this.#ie(!1),await this.#Fe())}#Jn(e){let n=e===this.#m;n&&this.#X(),this.conversationStore.clear(e),n&&(this.#Se(),this.#m=this.conversationStore.threadId(),this.#ie(!1)),this.#Ae()}async#Ae(){this.#I.setRelativeTimeFormatter(this.formatRelativeTime),this.#I.setThreads(await this.conversationStore.listThreads(),this.#m)}async#Fe(){this.#Ze+=1;let e=this.#Ze,n=await this.conversationStore.loadMessages(this.#m);if(e!==this.#Ze)return;if(n!==null){this.#Qe=n;for(let o of n)this.#Xt(o)}let r=this.conversationStore.loadCheckpoint(this.#m);if(r!==null){await this.#rr(r);return}this.#tr(n)}#Wt(){return this.#Xe=window.location.href,this.getContext()}#er(){return this.#Xe!==null&&this.#Xe!==window.location.href}#tr(e){let n=e?.at(-1);n===void 0||n.role!==qe.USER||this.#ve("\u26A0",this.#e.runInterrupted,"interrupted")}#Xt(e){let n=typeof e.content=="string"?e.content:"";if(e.role===qe.USER){let r=Bl(e);if(n!==""||r.length>0){let o=this.appendMessage(qe.USER,n);r.length>0&&o.appendChild(al(r))}return}if(e.role===qe.ASSISTANT){if(n!==""){let r=this.appendMessage(qe.ASSISTANT,n);r.classList.add("message--restored"),this.#gt(r)}for(let r of nE(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#nr(r.function.arguments)};if(this.#on(o))continue;this.#a.set(o.id,this.#wt(o).element);let i=this.#et(o.name)?.render;i!==void 0&&this.#sn(i,o)}return}if(e.role==="activity"){let r=e;typeof r.activityType=="string"&&this.#yt(e.id,r.activityType,r.content);return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(le.DONE,e.content)}}#nr(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Yt(e){this.getAttribute("data-text-animation")==="word"&&hp(e)}async#rr(e){this.conversationStore.saveCheckpoint(this.#m,null);let n=this.#mt();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===qe.ASSISTANT?(r.innerHTML=cs(n,{allowImages:this.allowImages}),sl(r,this.#e),this.#M().appendChild(r)):(this.#j=null,r.textContent=n,this.#b.appendChild(r)),this.#k(),e===qe.USER?this.#v.jump():this.#v.follow(),r}#M(){if(this.#j===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#j=e,this.#b.appendChild(e),this.#k()}return this.#j}#or(){this.#x.className="chat",this.#x.setAttribute("part","panel");let e=document.createElement("div");e.className="header",e.setAttribute("part","header");let n=this.#Ce;n.className="header-title",n.setAttribute("part","title"),n.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&e.append(this.#pt("icon","icon",null));let r=document.createElement("slot");r.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let i=this.#$e("history",this.#e.chatHistory,"\u2630");i.addEventListener("click",()=>this.openThreads());let s=this.#$e("checkpoints",this.#e.checkpoints,"\u21BA");s.addEventListener("click",()=>this.toggleCheckpoints());let a=this.#$e("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#$e("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),this.#Je()!==null?o.append(i,s,a):o.append(i,a),this.getAttribute("data-theme-toggle")!==null&&(this.#$.type="button",this.#$.className="header-btn header-btn--theme",this.#$.setAttribute("part","header-button theme-toggle"),this.#$.title=this.#e.toggleTheme,this.#$.setAttribute("aria-label",this.#e.toggleTheme),this.#$.addEventListener("click",()=>this.toggleTheme()),this.#jt(),o.append(this.#$)),o.append(l),e.append(n,r,o),Eh(e,{enabled:()=>!this.collapsed&&this.#q(),rect:()=>this.getBoundingClientRect(),apply:(g,x)=>this.#Gt(g,x),commit:(g,x)=>this.#Bn(g,x)}),this.#b.className="messages",this.#b.setAttribute("part","messages"),this.#b.setAttribute("role","log"),this.#b.setAttribute("aria-live","off"),this.#b.setAttribute("aria-label",this.#e.conversation),this.#z.className="jump-latest",this.#z.type="button",this.#z.setAttribute("part","jump-latest"),this.#z.textContent=this.#e.jumpToLatest,this.#z.addEventListener("click",()=>{this.#v.jump()}),this.#g.className="quote-selection",this.#g.type="button",this.#g.setAttribute("part","quote-selection"),this.#g.textContent=this.#e.quoteSelection,this.#g.hidden=!0,this.#g.addEventListener("mousedown",g=>{g.preventDefault()}),this.#g.addEventListener("click",()=>{this.quote(this.#je),window.getSelection()?.removeAllRanges(),this.#tt()}),this.#b.addEventListener("mouseup",g=>this.#Ct(g)),this.#b.addEventListener("keyup",()=>this.#Ct()),this.#b.addEventListener("mousedown",()=>this.#tt()),this.#v=pp({viewport:this.#b,onMissedContent:g=>{this.#z.dataset.missed=String(g)}}),this.#G.className="sr-only",this.#G.setAttribute("role","status"),this.#G.setAttribute("aria-live","polite"),this.#G.setAttribute("aria-atomic","true"),this.#Z.className="empty",this.#Z.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty";let u=this.#cr();u!==null&&c.append(u),this.#Z.append(c),this.#V.className="queued",this.#V.setAttribute("part","queued"),this.#V.setAttribute("role","group"),this.#V.setAttribute("aria-label",this.#e.queued),this.#V.hidden=!0,this.#b.append(this.#Z);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let w=document.createElement("div");w.className="composer",w.setAttribute("part","composer-surface");let p=document.createElement("div");p.className="composer-tools",p.setAttribute("part","composer-tools"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=1,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",g=>this.#dr(g)),this.#l.addEventListener("input",()=>this.#Zt()),this.#T.className="send",this.#T.type="button",this.#T.setAttribute("part","send"),this.#T.append(this.#ht("icon-send","send-send",Nc),this.#ht("icon-stop","send-stop",Oc)),this.#T.title=this.#e.send,this.#T.setAttribute("aria-label",this.#e.send),this.#T.dataset.state="idle",this.#T.addEventListener("click",()=>{if(this.#W){this.#X();return}this.#ft()}),this.#L.className="skill-hint",this.#L.setAttribute("part","skill-hint"),this.#L.hidden=!0,this.#C.className="attach-btn",this.#C.type="button",this.#C.setAttribute("part","attach-button"),this.#C.append(this.#ht("icon-attach","attach-glyph",Mc)),this.#C.title=this.#e.attachFiles,this.#C.setAttribute("aria-label",this.#e.attachFiles),this.#C.hidden=!0,this.#C.addEventListener("click",()=>this.#N.click()),this.#N.className="attach-input",this.#N.type="file",this.#N.multiple=!0,this.#N.hidden=!0,this.#N.addEventListener("change",()=>this.#Rn()),this.#Ne.className="attachment-slot",this.#Me.className="voice-slot";let h=document.createElement("slot");h.name="footer",p.append(this.#C,this.#Me,this.#T),w.append(this.#l,p),m.append(w,this.#N),this.#Ie.className="messages-wrap",this.#Ie.append(this.#b,this.#z,this.#g),this.#x.append(e,this.#Ie,this.#F.palette,this.#F.chips,this.#L,this.#V,this.#Ne,m,h,this.#I.element,this.#S.element),this.#x.addEventListener("pointerdown",g=>{if(!this.#S.open_)return;let x=g.composedPath();x.includes(this.#S.element)||x.includes(s)||this.#S.close()}),this.#f.className="launcher",this.#f.type="button",this.#f.setAttribute("part","launcher"),this.#f.setAttribute("aria-label",this.#e.expand),this.#B.className="launcher-badge",this.#B.setAttribute("part","launcher-badge"),this.#B.setAttribute("aria-hidden","true"),this.#B.hidden=!0,this.#le.className="rail-label",this.#le.setAttribute("part","rail-label"),this.#le.setAttribute("aria-hidden","true"),this.#le.textContent=this.getAttribute("title-text")??this.#e.title,this.#f.append(this.#pt("launcher","launcher-icon",Uc,this.#sr()),this.#le,this.#B),this.#f.addEventListener("click",()=>this.setCollapsed(!1)),bh(this.#f,{enabled:()=>this.collapsed&&this.#q(),rect:()=>this.#me(),viewport:()=>this.#O(),apply:(g,x)=>this.#Ht(g,x),commit:(g,x)=>this.#$n(g,x)});for(let g of eE){let x=dp(g,{axis:()=>this.#rt(),rect:()=>this.getBoundingClientRect(),apply:T=>this.#zt(g,T),commit:T=>this.#Wn(g,T),label:this.#e.resizePanel});x.tabIndex=-1,x.setAttribute("aria-hidden","true"),this.#xt.set(ds(g),x),this.#x.appendChild(x)}this.#Ft(),this.#ir(),this.#se.className="viewport-probe",this.#se.setAttribute("aria-hidden","true"),this.#w.append(this.#se,this.#G,this.#x,this.#f)}#ke(e){this.#K!==null&&clearTimeout(this.#K),this.#G.textContent=e,this.#K=setTimeout(()=>{this.#K=null,this.#G.textContent=""},qc)}#ir(){let e=new CSSStyleSheet;e.replaceSync(fp),this.#w.adoptedStyleSheets=[e]}#$e(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}#ht(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#sr(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#pt(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}#Kt(){this.#f.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#Oe;this.#B.textContent=e>9?"9+":String(e),this.#B.hidden=e===0||!this.#ar();let n=this.#B.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#f.setAttribute("aria-label",n),this.#f.title=n}#ar(){return this.getAttribute("data-unread-badge")!=="false"}#Be(e){this.#Oe=e,this.#Kt(),this.dispatchEvent(new CustomEvent(Fs,{detail:{unread:e},bubbles:!0,composed:!0}))}#lr(){this.collapsed&&this.#Be(this.#Oe+1)}#cr(){let e=this.getAttribute("data-starters");if(e===null)return null;let n;try{n=JSON.parse(e)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return ps({prompts:n},this.#e,r=>{this.sendMessage(r)})}#k(){this.#Z.hidden=this.#b.childElementCount>1}#Zt(){this.#F.onInput(this.#l.value),this.#L.hidden=!0,this.#Y(),this.#J=null}#dr(e){if(this.#F.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#W){e.preventDefault(),this.#X();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#ft();return}this.#ur(e)}#ur(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#F.isOpen())return;let r=this.#ce;if(r.length===0||this.#J===null&&(!n||this.#l.value!==""))return;let o=this.#J===null?0:this.#J+(n?1:-1);o>=r.length||(e.preventDefault(),this.#J=o<0?null:o,this.#l.value=o<0?"":r[o],this.#l.setSelectionRange(this.#l.value.length,this.#l.value.length),this.#Y())}#X(){for(let e of this.#Q)this.#ce[0]!==e&&this.#ce.unshift(e);this.#Q.length=0,this.#Ve(),this.#D?.abort(),this.#ne?.cancel()}#ie(e){let n=this.#W&&!e;this.#W=e;let r=e?this.#e.stop:this.#e.send;this.#T.title=r,this.#T.setAttribute("aria-label",r),this.#T.dataset.state=e?"running":"idle",n&&this.#hr()}#hr(){let e=this.#Q.shift();this.#Ve(),e!==void 0&&this.sendMessage(e)}#Ve(){this.#V.replaceChildren(),this.#V.hidden=this.#Q.length===0;for(let[e,n]of this.#Q.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=this.#e.removeQueued.replace("{text}",n),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#Q.splice(e,1),this.#Ve()}),this.#V.appendChild(r)}}#Y(){this.#l.style.height="auto",this.#l.style.height=`${this.#l.scrollHeight}px`}async#ft(){let e=this.#l.value.trim(),n=this.#A?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#W){e!==""&&(this.#Q.push(e),this.#Ve(),this.#l.value="",this.#Y());return}e!==""&&this.#ce[0]!==e&&this.#ce.unshift(e),this.#J=null,this.#l.value="",this.#Y(),this.#A?.hasPending()===!0&&this.#ve("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#A.pendingCount())),"attachment-pending"),this.#A?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(this.#W||e===""&&n.length===0)return;let r=this.appendMessage(qe.USER,e);n.length>0&&r.appendChild(al(n)),this.dispatchEvent(new CustomEvent(Gs,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#fr(e,n)}attachFile(e){return this.#A===null?!1:(this.#A.add(e),!0)}#pr(e){this.dispatchEvent(new CustomEvent(Bs,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#fr(e,n){this.endpoint!==""&&await this.#mt().send(e,n)}#mt(){if(this.#ne===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#m,initialMessages:this.#Qe,initialState:this.#he});this.#ne=new ir({agent:e,handlers:this.#en(),getTools:()=>this.#kt(),getContext:()=>this.#Wt(),executeTool:n=>this.#Qt(n),resolveInterrupts:n=>this.#Jt(n),onPersist:n=>this.conversationStore.saveMessages(this.#m,n),onStateChanged:n=>this.#mr(n),connectionLostMessage:this.#e.connectionLost,maxToolRounds:this.#An()})}return this.#ne}#mr(e){this.#he={...e},this.dispatchEvent(new CustomEvent($s,{detail:{state:this.#he},bubbles:!0,composed:!0}))}#gt(e,n={}){let r=this.#kn(),o=r.has(Ft.COPY),i=n.rateable!==!1&&r.has(Ft.FEEDBACK);(o||i)&&fl(e,{strings:this.#e,...o?{text:()=>Ji(e).text,html:()=>Ji(e).html}:{},...i?{onFeedback:s=>{this.dispatchEvent(new CustomEvent(Ws,{detail:{content:Ji(e).text,rating:s},bubbles:!0,composed:!0}))}}:{}}),r.has(Ft.RETRY)&&this.#gr(es(e,this.#e))}#gr(e){this.#H?.querySelector(".message-action--retry")?.remove();let n=ts("retry",this.#e.retryMessage,Gc);n.addEventListener("click",()=>{this.retryLastTurn()}),e.prepend(n),this.#H=e}async#br(e,n){return this.autoConfirm?null:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0?"predicate":null:this.#_.has(e.name)?null:Va(n.parameters)?"destructive":null}async#Qt(e){if(Rp(e)!==null)return null;let n=this.#wt(e);this.#i.delete(e.id),this.#a.set(e.id,n.element);let r=this.#s.has(e.name)?this.#et(e.name):null;if(r===null)return this.#p.has(e.id)||n.settle(le.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Ks&&!ji(r.parameters)&&this.#er()){let s=this.#e.pageMoved;return n.settle(le.ERROR,s),this.#ge(),{content:`Error: ${s}`,error:s}}let o=await this.#br(e,r);if(o!==null){let s={toolName:e.name,args:e.args},a=r.parameters[po];typeof a=="string"&&(s.message=a),this.#D=new AbortController;let l=ul(this.#M(),s,{signal:this.#D.signal,strings:this.#e,...o==="destructive"?{onAlwaysAllow:()=>this.#_.add(e.name)}:{}});this.#k(),this.#v.follow();let c=await l;if(this.#D=null,n.recordDecision(c?"approved":"declined"),!c){let u=this.#e.declinedAction;return n.settle(le.DECLINED,u),this.#ge(),{content:u}}}let i=ji(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#m,{toolCallId:e.id});try{let s=await r.handler(e.args,e.id);if(r.render!==void 0&&this.#sn(r.render,e),i)return n.settle(le.DONE,this.#e.navigating),{content:"",halt:!0};let a=JSON.stringify(s??null);return n.settle(le.DONE,a),this.#ge(),{content:a}}catch(s){i&&this.conversationStore.saveCheckpoint(this.#m,null);let a=s instanceof Error?s.message:String(s);return n.settle(le.ERROR,a),this.#ge(),{content:`Error: ${a}`,error:a}}}async#Jt(e){this.#D=new AbortController,this.#ke(this.#e.announceAwaitingDecision.replace("{count}",String(e.length))),this.#U();let n=this.#D.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#i.get(i.toolCallId):void 0,a={},l=tE(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c);let u,m=this.approveWithEdits&&s!==void 0;m&&(a.args=s.args),s?.mark(le.DEFERRED);let w=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await il(s?.approvalSlot??this.#M(),a,{signal:n,strings:this.#e,...m?{onEdit:p=>{u=p}}:{}});return s?.recordDecision(w?"approved":"declined"),w?s?.mark(le.PENDING):s?.settle(le.DECLINED,this.#e.declinedAction),{id:i.id,approved:w,editedArgs:u}}));this.#k(),this.#v.follow(),this.#D=null;let o={};for(let{id:i,approved:s,editedArgs:a}of r)o[i]=s?{status:"resolved",payload:a===void 0?{approved:!0}:{approved:!0,editedArgs:a}}:{status:"cancelled"};return o}#en(){return{onRunStart:()=>{this.#W||(this.#Re=!1,this.#ke(this.#e.announceResponding)),this.#ie(!0),this.#M(),this.#ge()},onReasoningStart:()=>{this.#U(),this.#nn()},onReasoningDelta:e=>{this.#nn().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#U(),this.#oe?.collapse(),this.#_r(e),this.#Ye+=1},onTextEnd:e=>{let n=this.#vt(e);this.#Ye<=1&&this.#Yt(n),sl(n,this.#e),this.#gt(n),this.#be(),this.#lr()},onToolCall:e=>{this.#U(),!this.#on(e)&&(this.#y.push({id:e.id,name:e.name}),this.#wt(e))},onActivity:(e,n,r)=>{this.#yt(r,e,n)},onCustomEvent:(e,n)=>{if(e===Ys){this.#yr(n);return}if(e===Cc){this.#wr(n);return}this.dispatchEvent(new CustomEvent(js,{detail:{name:e,value:n},bubbles:!0,composed:!0}))},onSubAgentStarted:(e,n,r)=>{r!==null&&(this.#d.set(e,r),this.#bt({delegationId:r,agent:n===""?null:n,phase:Rn.STARTED,status:this.#e.subAgentDelegatedTo.replace("{agent}",n),tool:null}))},onSubAgentFinished:e=>{this.#tn(e,Rn.FINISHED,null)},onSubAgentError:(e,n)=>{this.#tn(e,Rn.FAILED,n===""?this.#e.subAgentFailed:n)},onMessagesSnapshot:()=>{this.#ve("\u{1F504}",this.#e.historyReplaced,"history-replaced")},onToolResult:(e,n)=>{let r=this.#i.get(e);r!==void 0&&(r.settle(le.DONE,n),this.#p.add(e),this.#ge())},onActivityChanged:(e,n,r)=>{this.#yt(e,n,r)},onRunEnd:()=>{this.#U(),this.#be()},onError:e=>{this.#Re=!0,this.#ke(this.#e.announceFailed),this.#U();let n=this.appendMessage(qe.ASSISTANT,`\u26A0\uFE0F ${e}`);n.classList.add("message--failed"),this.#gt(n,{rateable:!1}),this.#Yt(n),this.#be()},onCancelled:()=>{this.#Re=!0,this.#ke(this.#e.announceStopped),this.#U(),this.#Er(),this.#be()},onSettled:()=>{this.#Re||this.#ke(this.#e.announceAnswerReady),this.#U(),this.#ie(!1),this.#be();for(let e of this.#i.values())e.settled||e.settle(le.DONE,this.#e.noResult);this.#j!==null&&this.#j.childElementCount===0&&(this.#j.remove(),this.#k()),this.#j=null,this.#oe=null,this.#vr()}}}#vr(){let e=this.#y.map(({id:r,name:o})=>({name:o,side:this.#p.has(r)?"server":"client"}));this.#y=[];let n=[...this.#R];this.#R=new Set,this.dispatchEvent(new CustomEvent(Vs,{detail:{tools:e,invalidated:n},bubbles:!0,composed:!0}))}#yr(e){let n=e??{},r=Array.isArray(n.keys)?n.keys.filter(o=>typeof o=="string"):[];if(r.length!==0){for(let o of r)this.#R.add(o);this.dispatchEvent(new CustomEvent(qs,{detail:{keys:r,reason:typeof n.reason=="string"?n.reason:null},bubbles:!0,composed:!0}))}}#wr(e){let n=gp(e);n!==null&&this.#bt(n)}#tn(e,n,r){let o=this.#d.get(e);if(o===void 0)return;let i=this.#o.get(o)?.agent??null;this.#bt({delegationId:o,agent:i,phase:n,status:r===null?this.#xr(i):r,tool:null})}#xr(e){return e===null?this.#e.subAgentWorking:this.#e.subAgentFinished.replace("{agent}",e)}#bt(e){let n=this.#i.get(e.delegationId);if(n===void 0)return;let r=this.#o.get(e.delegationId);r===void 0&&(r=new hs(this.#e),this.#o.set(e.delegationId,r),n.subagentSlot.appendChild(r.element)),r.report(e),this.#v.follow()}#Er(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#M().appendChild(e),this.#k(),this.#v.follow()}#ge(){if(this.#De!==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.#De=e,this.#M().appendChild(e),this.#k(),this.#v.follow()}#U(){this.#De?.remove(),this.#De=null}#nn(){if(this.#oe===null){this.#oe=new fs(this.#e);let e=this.#M();e.insertBefore(this.#oe.element,e.firstChild),this.#k(),this.#v.follow()}return this.#oe}#rn(){return this.#Le===null&&(this.#Le=this.appendMessage(qe.ASSISTANT,""),this.#Ye=0),this.#Le}#_r(e){this.#Pe=e,this.#rn(),this.#re===null&&(this.#re=requestAnimationFrame(()=>{this.#re=null,this.#vt(this.#Pe)}))}#vt(e){this.#re!==null&&(cancelAnimationFrame(this.#re),this.#re=null),this.#Pe=e;let n=this.#rn();return n.innerHTML=cs(e,{allowImages:this.allowImages}),this.#v.follow(),n}#be(){this.#re!==null&&this.#vt(this.#Pe),this.#Le=null}#on(e){let n=Rp(e);return n===null?!1:(this.#ve("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#ve(e,n,r,o){this.#M().appendChild(Fl(e,n,r,o)),this.#k(),this.#v.follow()}#in(e,n){this.#ve("\u2922",e,"surface",n===null?void 0:{label:this.#e.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#h.has(fo)&&!this.#r.has(Qi);e.includes("activity")&&this.registerActivityRenderer({type:fo,render:r=>{let o=er(r);return o===null?null:Nr(o)},removedNotice:this.#e.chartUndrawable}),e.includes("tool")&&this.registerTool(uh()),n&&this.isConnected&&this.reload()}#sn(e,n){let r;try{r=e(n.args)}catch(o){console.warn(`ag-ui-chat: render failed for tool ${n.name}`,o);return}r!==null&&(this.#a.get(n.id)?.after(r),this.#an())}registerActivityRenderer(e){this.#h.set(e.type,e),this.#c.delete(e.type)}get unhandledActivityTypes(){return[...this.#c]}#yt(e,n,r){let o=this.#h.get(n);if(o===void 0){this.#c.add(n);return}let i;try{i=o.render(r)}catch(a){console.warn(`ag-ui-chat: render failed for activity ${n}`,a),i=null}if(i===null){this.#Tr(e,n,o.removedNotice,r);return}let s=this.#u.get(e);s===void 0?this.#M().appendChild(i):s.replaceWith(i),this.#u.set(e,i),this.#an()}#Tr(e,n,r,o){let i=this.#u.has(e);this.#u.get(e)?.remove(),this.#u.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#ve("\u{1F4C9}",r,"chart-undrawable")}#an(){this.#k(),this.#v.follow()}#wt(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#et(e.name)?.parameters[xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]?.summary??vl(e.name),i=new qr(e.name,e.args,o,this.#e,{formatPayload:s=>this.formatToolPayload?.(s)??null});return this.#i.set(e.id,i),this.#M().appendChild(i.element),this.#k(),this.#v.follow(),i}};function tE(t){let e=t.metadata?.[po];return typeof e=="string"&&e.trim()!==""?e:void 0}function nE(t){return Array.isArray(t)?t.filter(oE):[]}function rE(t){if(t.name!=="")return t;let e=t.type.split("/")[1]??t.type,n=new Date().toISOString().replace(/[:.]/g,"-");return new File([t],e===""?`pasted-${n}`:`pasted-${n}.${e}`,{type:t.type})}function oE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function Rp(t){if(t.name!==Js)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function iE(t){let e=t?.removed;return typeof e=="number"?e:null}function sE(){customElements.get(ho)===void 0&&customElements.define(ho,Zr)}async function aE(t,e,n={}){await _t(t),await Ka(t,{...n,flashMs:n.flashMs??0}),await Xa(t,e,n)}async function lE(t,e={}){await _t(t),await Ya(t,e)}async function cE(t,e={}){await _t(t),await Za(t,e)}async function dE(t,e,n={}){await _t(t),await Qa(t,e,n)}async function uE(t,e,n={}){await _t(t),await Ja(t,e,n)}function hE(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Ir(t,!!e):fn(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var pE="0.35.1";export{Bs as ATTACHMENT_EVENT,Zr as AgUiChat,ir as AgUiClient,fo as CHART_ACTIVITY_TYPE,Qi as CHART_TOOL_NAME,Vi as CHAT_CORNERS,Qs as COMPACTION_ACTIVITY_TYPE,js as CUSTOM_AGENT_EVENT,Mr as CheckpointMenu,kr as ClientToolRegistry,bs as ConnectionLostError,se as DEFAULT_UI_STRINGS,ho as ELEMENT_TAG,Ws as FEEDBACK_EVENT,Ys as INVALIDATE_CUSTOM_NAME,qs as INVALIDATE_EVENT,Js as LOAD_CAPABILITY_TOOL,My as MAX_QUOTE_CHARS,Ux as MAX_SUGGESTIONS,Hx as MAX_SUGGESTION_CHARS,Cn as MAX_TOOL_ROUNDS,Ft as MESSAGE_ACTIONS,qe as MESSAGE_ROLE,Cr as PAGE_ACTIONS,Vs as RUN_FINISHED_EVENT,Yr as RemoteConversationStore,Kr as RunIndex,$s as STATE_EVENT,Gs as SUBMIT_EVENT,Xs as SUGGESTIONS_ACTIVITY_TYPE,Ze as SessionStorageStore,zs as TOGGLE_EVENT,le as TOOL_CALL_STATUS,Nn as TOOL_DISPLAY,qr as ToolCallCard,Fs as UNREAD_EVENT,pE as VERSION,po as X_CONFIRM_KEY,ur as X_DESTRUCTIVE_KEY,hr as X_NAVIGATES_KEY,xe as X_SUMMARY_KEY,ml as asQuote,fl as attachMessageActions,bl as attachQuoteOffer,er as chartSpecFrom,lE as clickElement,Ba as createChatSurfaceTools,jl as createHttpAgent,el as createPageActionTools,tl as createPageMapContext,Yi as createPageStateTools,rl as createRouteTools,Fv as createStateHookTools,sE as defineAgUiChat,aE as fillField,Dv as flash,Ka as focusWithFlash,Ya as highlightThenClick,th as isChatCorner,Va as isDestructive,ji as isNavigates,ol as mergeUiStrings,es as messageActionBar,Bl as messageAttachments,nl as parseToolCatalog,Wi as prefersReducedMotion,cE as pressButton,Za as pressThenClick,vl as prettifyToolName,Dr as quotableSelection,Or as relativeTime,Nr as renderChart,cs as renderMarkdown,ps as renderSuggestionChips,il as requestApproval,ul as requestConfirmation,yl as requestQuestion,_t as scrollIntoCenterView,dE as selectControl,Qa as selectOption,hE as setControlValue,Ir as setNativeChecked,fn as setNativeValue,ja as showHighlightOverlay,bp as suggestionPrompts,uE as toggleCheckbox,Ja as toggleControl,ql as transcribeAudio,Xa as typeInto,Wl as uploadAttachment};
3668
+ ${n}`,this.#Y(),this.#l.focus();let o=this.#l.value.length;this.#l.setSelectionRange(o,o)}offerQuoteInPage(e=document.body){this.#ae?.detach();let n=bl({within:e,label:this.#e.quoteSelection,exclude:this,onQuote:r=>this.quote(r)});return this.#ae=n,()=>{n.detach(),this.#ae===n&&(this.#ae=null)}}#Tn(){return this.getAttribute("data-quote-selection")!=="false"}#Ct(e){if(!this.#Tn())return;let n=e===void 0?void 0:{x:e.clientX,y:e.clientY},r=Dr(this.#b,[this.#w],n);if(r===null){this.#tt();return}this.#je=r.text,this.#Sn(r.rect)}#Sn(e){this.#g.hidden=!1;let n=this.#Ie.getBoundingClientRect(),r=e.top-n.top,o=r<Kl+this.#g.offsetHeight;this.#g.dataset.below=String(o),this.#g.style.top=`${o?e.bottom-n.top+Kl:r-Kl}px`;let i=this.#g.offsetWidth/2,s=e.left+e.width/2-n.left;this.#g.style.left=`${Math.min(Math.max(s,i),n.width-i)}px`}#tt(){this.#g.hidden=!0,this.#je=""}#An(){let e=this.getAttribute("data-max-tool-rounds");return e===null?Cn:Number.parseInt(e,10)}#kn(){let e=this.getAttribute("data-message-actions");return e===null?new Set([Ft.COPY,Ft.RETRY]):new Set(e.split(",").map(n=>n.trim()).filter(n=>n!==""))}#In(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Zs;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Zs}#Rn(){let e=this.#N.files;if(e!==null)for(let n of Array.from(e))this.#A?.add(n);this.#N.value=""}#Cn(){this.#x.addEventListener("dragover",e=>{e.preventDefault(),this.#x.classList.add("chat--dragover")}),this.#x.addEventListener("dragleave",()=>{this.#x.classList.remove("chat--dragover")}),this.#x.addEventListener("drop",e=>{e.preventDefault(),this.#x.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#A?.add(r)})}#Nn(e,n,r){let o=this.#On(),i=n.getData("text/plain");if(o===null||i.length<o)return;e.preventDefault();let s=new Date().toISOString().replace(/[:.]/g,"-");r.add(new File([i],`pasted-${s}.txt`,{type:"text/plain"}))}#On(){let e=this.getAttribute("data-paste-attach");if(e===null)return mo;if(e==="off")return null;let n=Number.parseInt(e,10);return Number.isNaN(n)||n<=0?(console.warn(`<ag-ui-chat>: data-paste-attach="${e}" is neither "off" nor a positive number of characters, so the default of ${mo} is used.`),mo):n}#Mn(e){this.#x.addEventListener("paste",n=>{let r=n.clipboardData??null;if(r===null)return;let o=Array.from(r.files);if(o.length===0){this.#Nn(n,r,e);return}r.getData("text/plain")===""&&n.preventDefault();for(let i of o)this.#A?.add(rE(i))})}#Nt(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new Yr(e,()=>this.#xe(e),this.conversationStore,()=>this.#He(),this.getAttribute("data-threads-cache")!=="false"))}async#Ot(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#t=nl(await n.json())}catch{}}setSkills(e){this.#St=e,this.#nt()}#Ln(){this.#F.enableChips(this.#Rt("data-prompt-chips")),this.#F.enableSlash(this.#Rt("data-slash-commands")),this.#Tt=this.#Pn(),this.#nt()}#Pn(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return $a(JSON.parse(e))}catch{return[]}}async#Mt(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,this.#It(e));this.#_t=$a(await n.json()),this.#nt()}catch{}}#nt(){let e=new Map;for(let n of[...this.#_t,...this.#Tt,...this.#St])e.set(n.name,n);this.#F.setSkills([...e.values()])}#Dn(e){if(e.prompt===void 0){this.#L.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=eh(e.prompt,this.skillContext());if(r.length>0){this.#L.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#L.hidden=!1,this.#l.value=n,this.#Y(),this.#l.focus(),this.#Un(n);return}if(this.#L.hidden=!0,this.#l.value=n,this.#Y(),e.sendImmediately===!1){this.#l.focus();return}this.#ft()}#Un(e){let n=e.indexOf("{");this.#l.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e,n={}){e&&!this.#ze()||(n.announce===!0&&e&&!this.collapsed&&this.#in(this.#e.chatMinimised,null),e||this.#st(),e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),bt(this.#Te(Sp),e?"1":"0"),this.#Be(0),this.dispatchEvent(new CustomEvent(zs,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){return this.#Oe}#Hn(){let e=this.#Vt(Sp);return e!==null?e==="1":Ip.has(this.getAttribute("placement"))&&!this.hasAttribute("data-start-open")}#ze(){return this.getAttribute("placement")!=="page"}describeSurface(){let e=this.getBoundingClientRect(),n=this.#O(),r=e.width>=n.width-1&&e.height>=n.height-1;return{placement:this.getAttribute("placement"),collapsed:this.collapsed,collapsible:this.#ze(),movable:this.#q()&&!r,draggable:this.#q(),fullBleed:r,box:{left:Math.round(e.left),top:Math.round(e.top),width:Math.round(e.width),height:Math.round(e.height)},viewport:{left:Math.round(n.left),top:Math.round(n.top),width:Math.round(n.width),height:Math.round(n.height)}}}moveTo(e,n={}){if(!this.#q())return!1;let r=n.announce===!0?this.#Gn():null,o=this.#O(),i=this.getBoundingClientRect();if(i.width>=o.width-1&&i.height>=o.height-1)return!1;let[s,a]=e.split("-"),l=o.left+$t,c=o.top+$t,u=a==="left"?l:Math.max(l,o.left+o.width-$t-i.width),m=s==="top"?c:Math.max(c,o.top+o.height-$t-i.height),w={left:u,top:m,right:u+i.width,bottom:m+i.height},p=this.#f.offsetWidth,h=this.#f.offsetHeight;return this.#it(w,{left:a==="left"?w.left:w.right-p,top:s==="top"?w.top:w.bottom-h,width:p,height:h}),this.#_e(),r!==null&&this.#in(this.#e.chatMoved,r),!0}#Gn(){let e=this.style.getPropertyValue("--ag-ui-inset"),n=this.style.getPropertyValue("--ag-ui-launcher-inset"),r=this.getAttribute("data-expand-corner"),o=this.#E,i=this.#P,s=this.#ee;return()=>{let a=(l,c)=>{c===""?this.style.removeProperty(l):this.style.setProperty(l,c)};a("--ag-ui-inset",e),a("--ag-ui-launcher-inset",n),r===null?this.removeAttribute("data-expand-corner"):this.setAttribute("data-expand-corner",r),this.#E=o,this.#P=i,this.#ee=s,o===null?this.#Zn(Yl):this.#_e(),this.#fe()}}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),this.#ct(kp,e),this.#jt()}#rt(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#zn(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height"),o=this.#Lt(e,-1),i=o.x===null||o.y===null?this.#Lt(e,1):o;return this.#Pt("--ag-ui-width",n),this.#Pt("--ag-ui-height",r),{x:o.x??i.x??"right",y:o.y??i.y??"bottom"}}#Lt(e,n){this.#ot({width:e.width+n,height:e.height+n});let r=this.getBoundingClientRect(),o=(i,s)=>Math.abs(i-s)>=.5;return{x:o(r.width,e.width)?o(r.left,e.left)?"right":"left":null,y:o(r.height,e.height)?o(r.top,e.top)?"bottom":"top":null}}#fe(){if(!this.#ue)return;let e=this.#ee??this.#zn();this.#te=e,this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`),this.#Ft()}#Pt(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ot(e){let n=this.#rt();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`))}#Fn(){let e=this.#rt();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#q(){return this.getAttribute("data-launcher-drag")!=="false"&&Ip.has(this.getAttribute("placement"))}#O(){let e=window.visualViewport,n=e?.width??window.innerWidth,r=e?.height??window.innerHeight,o=getComputedStyle(this.#se),i=l=>{let c=Number.parseFloat(o.getPropertyValue(l));return Number.isFinite(c)?c:0},s=i("padding-left"),a=i("padding-top");return{left:s,top:a,width:Math.max(0,n-s-i("padding-right")),height:Math.max(0,r-a-i("padding-bottom"))}}#Ee(){let e=document.documentElement;return{width:e.clientWidth||window.innerWidth,height:e.clientHeight||window.innerHeight}}#Dt(){let e=window.visualViewport;if(e==null)return;if(Math.abs(e.height-window.innerHeight)<1){this.style.removeProperty("--ag-ui-visual-viewport-height"),this.style.removeProperty("--ag-ui-visual-viewport-inset-bottom");return}this.style.setProperty("--ag-ui-visual-viewport-height",`${Math.round(e.height)}px`);let n=window.innerHeight-e.height-e.offsetTop;this.style.setProperty("--ag-ui-visual-viewport-inset-bottom",`${Math.max(0,Math.round(n))}px`)}#me(){let e=this.#f.offsetWidth,n=this.#f.offsetHeight,r=this.#E;if(r!==null)return{left:r.left,top:r.top,width:e,height:n};let o=this.#f.getBoundingClientRect();return{left:o.left+o.width/2-e/2,top:o.top+o.height/2-n/2,width:e,height:n}}#Ut(e){if(!this.#q())return;this.#E=e,this.#P=null;let n=this.getBoundingClientRect(),r=hl(this.#me(),{width:n.width,height:n.height},this.#O(),this.#Ee());this.style.setProperty("--ag-ui-inset",r.hostInset),this.style.setProperty("--ag-ui-launcher-inset",r.launcherInset),this.#ee=r.corner,this.setAttribute("data-expand-corner",`${r.corner.y}-${r.corner.x}`),this.#fe()}#Ht(e,n){this.#Ut({left:e,top:n})}#$n(e,n){this.#Ht(e,n),this.#_e()}#Gt(e,n){if(!this.#q())return{held:e,launcher:null};if(this.#E===null){let c=this.#me();this.#E={left:c.left,top:c.top}}let r=this.#E,o=Lr(e,this.#O(),Je),i=this.#ee??this.#te,s=this.#Ee();this.style.setProperty("--ag-ui-inset",[i.y==="top"?`${Math.round(o.top)}px`:"auto",i.x==="right"?`${Math.round(s.width-o.right)}px`:"auto",i.y==="bottom"?`${Math.round(s.height-o.bottom)}px`:"auto",i.x==="left"?`${Math.round(o.left)}px`:"auto"].join(" ")),this.#P={left:o.left,top:o.top};let a={...this.#me(),left:r.left+(o.left-n.left),top:r.top+(o.top-n.top)},l={...a,...Pt(a,this.#O())};return this.style.setProperty("--ag-ui-launcher-inset",Pr(o,l,i,this.#Ee()).launcherInset),{held:o,launcher:l}}#Bn(e,n){let{held:r,launcher:o}=this.#Gt(e,n);o!==null&&(this.#it(r,o),this.#_e())}#it(e,n){let r=this.#O(),o=this.#Ee(),i={width:e.right-e.left,height:e.bottom-e.top},{corner:s}=hl(n,i,r,o),a=Pr(e,n,s,o);this.style.setProperty("--ag-ui-inset",a.hostInset),this.style.setProperty("--ag-ui-launcher-inset",a.launcherInset),this.#E={left:n.left,top:n.top},this.#P={left:e.left,top:e.top},this.#ee=s,this.setAttribute("data-expand-corner",`${s.y}-${s.x}`),this.#fe()}#Vn(e){if(!this.#q())return;let n=this.getBoundingClientRect(),r=Lr({left:e.left,top:e.top,right:e.left+n.width,bottom:e.top+n.height},this.#O(),Je),o=this.#me(),i={...o,left:o.left+(r.left-e.left),top:o.top+(r.top-e.top)};this.#it(r,{...i,...Pt(i,this.#O())})}#_e(){let e=this.#E;if(e===null)return;let n=this.#P;this.#ct(Yl,JSON.stringify(n===null?e:{...e,panel:n}))}#st(){let e=this.#jn(),n=this.#E??e;if(n===null)return;let r=this.#P??e?.panel??null;if(r!==null){this.#E={left:n.left,top:n.top},this.#Vn(r);return}let o=this.#me();this.#Ut(Pt({...o,left:n.left,top:n.top},this.#O()))}#jn(){let e=this.#lt(Yl);if(e===null)return null;try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;let{left:r,top:o,panel:i}=n;if(typeof r!="number"||typeof o!="number")return null;let s=Jx(i);return s===null?{left:r,top:o}:{left:r,top:o,panel:s}}catch{return null}}#qn(){this.#q()||(this.#E=null,this.#P=null,this.#ee=null,this.style.removeProperty("--ag-ui-inset"),this.style.removeProperty("--ag-ui-launcher-inset"),this.removeAttribute("data-expand-corner"))}#zt(e,n){if(n=this.#ln(n),this.#ot({width:n.right-n.left,height:n.bottom-n.top}),e.x!==this.#te.x&&e.y!==this.#te.y)return n;let r=this.#Ee(),o=this.#te,i=s=>`${Math.round(s)}px`;if(this.style.setProperty("--ag-ui-inset",[o.y==="top"?i(n.top):"auto",o.x==="right"?i(r.width-n.right):"auto",o.y==="bottom"?i(r.height-n.bottom):"auto",o.x==="left"?i(n.left):"auto"].join(" ")),this.#E!==null){let s=this.#f.offsetWidth;this.#E={left:o.x==="left"?n.left:n.right-s,top:o.y==="top"?n.top:n.bottom-s}}return this.#P!==null&&(this.#P={left:n.left,top:n.top}),n}#Wn(e,n){let r=this.#zt(e,n);this.#Xn({width:r.right-r.left,height:r.bottom-r.top}),this.#_e(),this.#fe()}#Ft(){let e=`${this.#te.y==="top"?"bottom":"top"}-${this.#te.x==="left"?"right":"left"}`;for(let[n,r]of this.#xt){let o=n===e;r.tabIndex=o?0:-1,o?r.removeAttribute("aria-hidden"):r.setAttribute("aria-hidden","true")}}#Xn(e){let n={...this.#$t(),...e};this.#ct(Ap,JSON.stringify(n))}#$t(){let e=this.#lt(Ap);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#Yn(){let e=this.id!==""?this.id:this.endpoint;return e===""?"":this.#Et===e?this.#Ke:Zl.has(e)?(this.#Et=e,this.#Ke=`${e}~${Ie()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${e}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#Ke):(Zl.add(e),this.#Ue=e,e)}#at(e=this.userKey){return e===""?this.#pe:`${this.#pe}#${e}`}#Kn(e,n){let r=this.#at(e),o=this.#at(n);if(e===""){Ze.adopt(r,o),this.#Bt(o);return}Ze.purge(r),this.#Bt(o),this.#X(),this.#Se(),this.#ie(!1),this.#Be(0),this.#m=this.conversationStore.threadId(),this.#Fe(),this.#Ae()}#Bt(e){this.#ye!==null&&(this.#ye=new Ze(e),this.conversationStore=this.#ye,this.#Nt())}#Te(e){return this.#pe===""?e:`${e}:${this.#pe}`}#Vt(e){let n=sessionStorage.getItem(this.#Te(e));return n!==null||this.#pe===""?n:sessionStorage.getItem(e)}#lt(e){try{let n=localStorage.getItem(this.#Te(e));if(n!==null)return n}catch{}return this.#Vt(e)}#ct(e,n){let r=this.#Te(e);try{localStorage.setItem(r,n)}catch{}bt(r,n)}#Zn(e){let n=this.#Te(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#jt(){let e=this.getAttribute("theme")==="dark";this.#$.replaceChildren(this.#pt("theme","theme-icon",e?Dc:Pc,null))}openThreads(){this.#S.close(),this.#Ae(),this.#I.setModal(!this.#dt()),this.#I.open(),this.#ut()}#dt(){return this.getAttribute("placement")==="page"&&this.getBoundingClientRect().width>=Xc}#ut(){this.#I.isOpen()&&this.#dt()?this.setAttribute("data-threads-docked",""):this.removeAttribute("data-threads-docked")}openCheckpoints(){this.#I.close(),this.#un(),this.#S.open()}closeThreads(){this.#I.close()}closeCheckpoints(){this.#S.close()}toggleCheckpoints(){if(this.#S.open_){this.#S.close();return}this.openCheckpoints()}newChat(){this.#X(),this.conversationStore.isUnsent?.(this.#m)===!0&&this.conversationStore.clear(this.#m),this.#Se(),this.#m=ws(this.conversationStore),this.#ie(!1),this.#Be(0)}#Se(){this.#ne=null,this.#qt(),this.#Qe=[],this.#ce.length=0,this.#J=null}#qt(){this.#be(),this.#j=null,this.#oe=null,this.#U(),this.#i.clear(),this.#o.clear(),this.#d.clear(),this.#p.clear(),this.#a.clear(),this.#u.clear(),this.#H=null,this.#A?.clear(),this.#b.replaceChildren(this.#Z),this.#k()}async retryLastTurn(){if(this.#W)return!1;let e=this.#mt(),n=e.truncateToLastUser();if(n===null)return!1;this.#qt();for(let r of n)this.#Xt(r);return await e.resume(),!0}async#Qn(e){e!==this.#m&&(this.#X(),this.#Se(),this.conversationStore.setActiveThread(e),this.#m=e,this.#ie(!1),await this.#Fe())}#Jn(e){let n=e===this.#m;n&&this.#X(),this.conversationStore.clear(e),n&&(this.#Se(),this.#m=this.conversationStore.threadId(),this.#ie(!1)),this.#Ae()}async#Ae(){this.#I.setRelativeTimeFormatter(this.formatRelativeTime),this.#I.setThreads(await this.conversationStore.listThreads(),this.#m)}async#Fe(){this.#Ze+=1;let e=this.#Ze,n=await this.conversationStore.loadMessages(this.#m);if(e!==this.#Ze)return;if(n!==null){this.#Qe=n;for(let o of n)this.#Xt(o)}let r=this.conversationStore.loadCheckpoint(this.#m);if(r!==null){await this.#rr(r);return}this.#tr(n)}#Wt(){return this.#Xe=window.location.href,this.getContext()}#er(){return this.#Xe!==null&&this.#Xe!==window.location.href}#tr(e){let n=e?.at(-1);n===void 0||n.role!==qe.USER||this.#ve("\u26A0",this.#e.runInterrupted,"interrupted")}#Xt(e){let n=typeof e.content=="string"?e.content:"";if(e.role===qe.USER){let r=Bl(e);if(n!==""||r.length>0){let o=this.appendMessage(qe.USER,n);r.length>0&&o.appendChild(al(r))}return}if(e.role===qe.ASSISTANT){if(n!==""){let r=this.appendMessage(qe.ASSISTANT,n);r.classList.add("message--restored"),this.#gt(r)}for(let r of nE(e.toolCalls)){let o={id:r.id,name:r.function.name,args:this.#nr(r.function.arguments)};if(this.#on(o))continue;this.#a.set(o.id,this.#wt(o).element);let i=this.#et(o.name)?.render;i!==void 0&&this.#sn(i,o)}return}if(e.role==="activity"){let r=e;typeof r.activityType=="string"&&this.#yt(e.id,r.activityType,r.content);return}if(e.role==="tool"){let r=this.#i.get(e.toolCallId);r!==void 0&&r.settle(le.DONE,e.content)}}#nr(e){if(typeof e!="string")return{};try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#Yt(e){this.getAttribute("data-text-animation")==="word"&&hp(e)}async#rr(e){this.conversationStore.saveCheckpoint(this.#m,null);let n=this.#mt();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===qe.ASSISTANT?(r.innerHTML=cs(n,{allowImages:this.allowImages}),sl(r,this.#e),this.#M().appendChild(r)):(this.#j=null,r.textContent=n,this.#b.appendChild(r)),this.#k(),e===qe.USER?this.#v.jump():this.#v.follow(),r}#M(){if(this.#j===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#j=e,this.#b.appendChild(e),this.#k()}return this.#j}#or(){this.#x.className="chat",this.#x.setAttribute("part","panel");let e=document.createElement("div");e.className="header",e.setAttribute("part","header");let n=this.#Ce;n.className="header-title",n.setAttribute("part","title"),n.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&e.append(this.#pt("icon","icon",null));let r=document.createElement("slot");r.name="header-actions";let o=document.createElement("div");o.className="header-controls",o.setAttribute("part","header-controls");let i=this.#$e("history",this.#e.chatHistory,"\u2630");i.addEventListener("click",()=>this.openThreads());let s=this.#$e("checkpoints",this.#e.checkpoints,"\u21BA");s.addEventListener("click",()=>this.toggleCheckpoints());let a=this.#$e("new",this.#e.newChat,"\u271A");a.addEventListener("click",()=>this.newChat());let l=this.#$e("collapse",this.#e.collapse,"\u2014");l.addEventListener("click",()=>this.toggleCollapsed()),this.#Je()!==null?o.append(i,s,a):o.append(i,a),this.getAttribute("data-theme-toggle")!==null&&(this.#$.type="button",this.#$.className="header-btn header-btn--theme",this.#$.setAttribute("part","header-button theme-toggle"),this.#$.title=this.#e.toggleTheme,this.#$.setAttribute("aria-label",this.#e.toggleTheme),this.#$.addEventListener("click",()=>this.toggleTheme()),this.#jt(),o.append(this.#$)),o.append(l),e.append(n,r,o),Eh(e,{enabled:()=>!this.collapsed&&this.#q(),rect:()=>this.getBoundingClientRect(),apply:(g,x)=>this.#Gt(g,x),commit:(g,x)=>this.#Bn(g,x)}),this.#b.className="messages",this.#b.setAttribute("part","messages"),this.#b.setAttribute("role","log"),this.#b.setAttribute("aria-live","off"),this.#b.setAttribute("aria-label",this.#e.conversation),this.#z.className="jump-latest",this.#z.type="button",this.#z.setAttribute("part","jump-latest"),this.#z.textContent=this.#e.jumpToLatest,this.#z.addEventListener("click",()=>{this.#v.jump()}),this.#g.className="quote-selection",this.#g.type="button",this.#g.setAttribute("part","quote-selection"),this.#g.textContent=this.#e.quoteSelection,this.#g.hidden=!0,this.#g.addEventListener("mousedown",g=>{g.preventDefault()}),this.#g.addEventListener("click",()=>{this.quote(this.#je),window.getSelection()?.removeAllRanges(),this.#tt()}),this.#b.addEventListener("mouseup",g=>this.#Ct(g)),this.#b.addEventListener("keyup",()=>this.#Ct()),this.#b.addEventListener("mousedown",()=>this.#tt()),this.#v=pp({viewport:this.#b,onMissedContent:g=>{this.#z.dataset.missed=String(g)}}),this.#G.className="sr-only",this.#G.setAttribute("role","status"),this.#G.setAttribute("aria-live","polite"),this.#G.setAttribute("aria-atomic","true"),this.#Z.className="empty",this.#Z.setAttribute("part","empty");let c=document.createElement("slot");c.name="empty";let u=this.#cr();u!==null&&c.append(u),this.#Z.append(c),this.#V.className="queued",this.#V.setAttribute("part","queued"),this.#V.setAttribute("role","group"),this.#V.setAttribute("aria-label",this.#e.queued),this.#V.hidden=!0,this.#b.append(this.#Z);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer");let w=document.createElement("div");w.className="composer",w.setAttribute("part","composer-surface");let p=document.createElement("div");p.className="composer-tools",p.setAttribute("part","composer-tools"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=1,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",g=>this.#dr(g)),this.#l.addEventListener("input",()=>this.#Zt()),this.#T.className="send",this.#T.type="button",this.#T.setAttribute("part","send"),this.#T.append(this.#ht("icon-send","send-send",Nc),this.#ht("icon-stop","send-stop",Oc)),this.#T.title=this.#e.send,this.#T.setAttribute("aria-label",this.#e.send),this.#T.dataset.state="idle",this.#T.addEventListener("click",()=>{if(this.#W){this.#X();return}this.#ft()}),this.#L.className="skill-hint",this.#L.setAttribute("part","skill-hint"),this.#L.hidden=!0,this.#C.className="attach-btn",this.#C.type="button",this.#C.setAttribute("part","attach-button"),this.#C.append(this.#ht("icon-attach","attach-glyph",Mc)),this.#C.title=this.#e.attachFiles,this.#C.setAttribute("aria-label",this.#e.attachFiles),this.#C.hidden=!0,this.#C.addEventListener("click",()=>this.#N.click()),this.#N.className="attach-input",this.#N.type="file",this.#N.multiple=!0,this.#N.hidden=!0,this.#N.addEventListener("change",()=>this.#Rn()),this.#Ne.className="attachment-slot",this.#Me.className="voice-slot";let h=document.createElement("slot");h.name="footer",p.append(this.#C,this.#Me,this.#T),w.append(this.#l,p),m.append(w,this.#N),this.#Ie.className="messages-wrap",this.#Ie.append(this.#b,this.#z,this.#g),this.#x.append(e,this.#Ie,this.#F.palette,this.#F.chips,this.#L,this.#V,this.#Ne,m,h,this.#I.element,this.#S.element),this.#x.addEventListener("pointerdown",g=>{if(!this.#S.open_)return;let x=g.composedPath();x.includes(this.#S.element)||x.includes(s)||this.#S.close()}),this.#f.className="launcher",this.#f.type="button",this.#f.setAttribute("part","launcher"),this.#f.setAttribute("aria-label",this.#e.expand),this.#B.className="launcher-badge",this.#B.setAttribute("part","launcher-badge"),this.#B.setAttribute("aria-hidden","true"),this.#B.hidden=!0,this.#le.className="rail-label",this.#le.setAttribute("part","rail-label"),this.#le.setAttribute("aria-hidden","true"),this.#le.textContent=this.getAttribute("title-text")??this.#e.title,this.#f.append(this.#pt("launcher","launcher-icon",Uc,this.#sr()),this.#le,this.#B),this.#f.addEventListener("click",()=>this.setCollapsed(!1)),bh(this.#f,{enabled:()=>this.collapsed&&this.#q(),rect:()=>this.#me(),viewport:()=>this.#O(),apply:(g,x)=>this.#Ht(g,x),commit:(g,x)=>this.#$n(g,x)});for(let g of eE){let x=dp(g,{axis:()=>this.#rt(),rect:()=>this.getBoundingClientRect(),apply:T=>this.#zt(g,T),commit:T=>this.#Wn(g,T),label:this.#e.resizePanel});x.tabIndex=-1,x.setAttribute("aria-hidden","true"),this.#xt.set(ds(g),x),this.#x.appendChild(x)}this.#Ft(),this.#ir(),this.#se.className="viewport-probe",this.#se.setAttribute("aria-hidden","true"),this.#w.append(this.#se,this.#G,this.#x,this.#f)}#ke(e){this.#K!==null&&clearTimeout(this.#K),this.#G.textContent=e,this.#K=setTimeout(()=>{this.#K=null,this.#G.textContent=""},qc)}#ir(){let e=new CSSStyleSheet;e.replaceSync(fp),this.#w.adoptedStyleSheets=[e]}#$e(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}#ht(e,n,r){let o=document.createElement("slot");return o.name=e,o.className=n,o.innerHTML=r,o}#sr(){return this.getAttribute("data-launcher-icon-url")??this.getAttribute("data-icon-url")}#pt(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}#Kt(){this.#f.setAttribute("aria-expanded",String(!this.collapsed));let e=this.#Oe;this.#B.textContent=e>9?"9+":String(e),this.#B.hidden=e===0||!this.#ar();let n=this.#B.hidden?this.#e.expand:this.#e.expandUnread.replace("{count}",String(e));this.#f.setAttribute("aria-label",n),this.#f.title=n}#ar(){return this.getAttribute("data-unread-badge")!=="false"}#Be(e){this.#Oe=e,this.#Kt(),this.dispatchEvent(new CustomEvent(Fs,{detail:{unread:e},bubbles:!0,composed:!0}))}#lr(){this.collapsed&&this.#Be(this.#Oe+1)}#cr(){let e=this.getAttribute("data-starters");if(e===null)return null;let n;try{n=JSON.parse(e)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return ps({prompts:n},this.#e,r=>{this.sendMessage(r)})}#k(){this.#Z.hidden=this.#b.childElementCount>1}#Zt(){this.#F.onInput(this.#l.value),this.#L.hidden=!0,this.#Y(),this.#J=null}#dr(e){if(this.#F.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#W){e.preventDefault(),this.#X();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#ft();return}this.#ur(e)}#ur(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#F.isOpen())return;let r=this.#ce;if(r.length===0||this.#J===null&&(!n||this.#l.value!==""))return;let o=this.#J===null?0:this.#J+(n?1:-1);o>=r.length||(e.preventDefault(),this.#J=o<0?null:o,this.#l.value=o<0?"":r[o],this.#l.setSelectionRange(this.#l.value.length,this.#l.value.length),this.#Y())}#X(){for(let e of this.#Q)this.#ce[0]!==e&&this.#ce.unshift(e);this.#Q.length=0,this.#Ve(),this.#D?.abort(),this.#ne?.cancel()}#ie(e){let n=this.#W&&!e;this.#W=e;let r=e?this.#e.stop:this.#e.send;this.#T.title=r,this.#T.setAttribute("aria-label",r),this.#T.dataset.state=e?"running":"idle",n&&this.#hr()}#hr(){let e=this.#Q.shift();this.#Ve(),e!==void 0&&this.sendMessage(e)}#Ve(){this.#V.replaceChildren(),this.#V.hidden=this.#Q.length===0;for(let[e,n]of this.#Q.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=this.#e.removeQueued.replace("{text}",n),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#Q.splice(e,1),this.#Ve()}),this.#V.appendChild(r)}}#Y(){this.#l.style.height="auto",this.#l.style.height=`${this.#l.scrollHeight}px`}async#ft(){let e=this.#l.value.trim(),n=this.#A?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#W){e!==""&&(this.#Q.push(e),this.#Ve(),this.#l.value="",this.#Y());return}e!==""&&this.#ce[0]!==e&&this.#ce.unshift(e),this.#J=null,this.#l.value="",this.#Y(),this.#A?.hasPending()===!0&&this.#ve("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#A.pendingCount())),"attachment-pending"),this.#A?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(this.#W||e===""&&n.length===0)return;let r=this.appendMessage(qe.USER,e);n.length>0&&r.appendChild(al(n)),this.dispatchEvent(new CustomEvent(Gs,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#fr(e,n)}attachFile(e){return this.#A===null?!1:(this.#A.add(e),!0)}#pr(e){this.dispatchEvent(new CustomEvent(Bs,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#fr(e,n){this.endpoint!==""&&await this.#mt().send(e,n)}#mt(){if(this.#ne===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.#we(),getHeaders:()=>this.#we(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:this.#m,initialMessages:this.#Qe,initialState:this.#he});this.#ne=new ir({agent:e,handlers:this.#en(),getTools:()=>this.#kt(),getContext:()=>this.#Wt(),executeTool:n=>this.#Qt(n),resolveInterrupts:n=>this.#Jt(n),onPersist:n=>this.conversationStore.saveMessages(this.#m,n),onStateChanged:n=>this.#mr(n),connectionLostMessage:this.#e.connectionLost,maxToolRounds:this.#An()})}return this.#ne}#mr(e){this.#he={...e},this.dispatchEvent(new CustomEvent($s,{detail:{state:this.#he},bubbles:!0,composed:!0}))}#gt(e,n={}){let r=this.#kn(),o=r.has(Ft.COPY),i=n.rateable!==!1&&r.has(Ft.FEEDBACK);(o||i)&&fl(e,{strings:this.#e,...o?{text:()=>Ji(e).text,html:()=>Ji(e).html}:{},...i?{onFeedback:s=>{this.dispatchEvent(new CustomEvent(Ws,{detail:{content:Ji(e).text,rating:s},bubbles:!0,composed:!0}))}}:{}}),r.has(Ft.RETRY)&&this.#gr(es(e,this.#e))}#gr(e){this.#H?.querySelector(".message-action--retry")?.remove();let n=ts("retry",this.#e.retryMessage,Gc);n.addEventListener("click",()=>{this.retryLastTurn()}),e.prepend(n),this.#H=e}async#br(e,n){return this.autoConfirm?null:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0?"predicate":null:this.#_.has(e.name)?null:Va(n.parameters)?"destructive":null}async#Qt(e){if(Rp(e)!==null)return null;let n=this.#wt(e);this.#i.delete(e.id),this.#a.set(e.id,n.element);let r=this.#s.has(e.name)?this.#et(e.name):null;if(r===null)return this.#p.has(e.id)||n.settle(le.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Ks&&!ji(r.parameters)&&this.#er()){let s=this.#e.pageMoved;return n.settle(le.ERROR,s),this.#ge(),{content:`Error: ${s}`,error:s}}let o=await this.#br(e,r);if(o!==null){let s={toolName:e.name,args:e.args},a=r.parameters[po];typeof a=="string"&&(s.message=a),this.#D=new AbortController;let l=ul(this.#M(),s,{signal:this.#D.signal,strings:this.#e,...o==="destructive"?{onAlwaysAllow:()=>this.#_.add(e.name)}:{}});this.#k(),this.#v.follow();let c=await l;if(this.#D=null,n.recordDecision(c?"approved":"declined"),!c){let u=this.#e.declinedAction;return n.settle(le.DECLINED,u),this.#ge(),{content:u}}}let i=ji(r.parameters)&&this.navigate===null;i&&this.conversationStore.saveCheckpoint(this.#m,{toolCallId:e.id});try{let s=await r.handler(e.args,e.id);if(r.render!==void 0&&this.#sn(r.render,e),i)return n.settle(le.DONE,this.#e.navigating),{content:"",halt:!0};let a=JSON.stringify(s??null);return n.settle(le.DONE,a),this.#ge(),{content:a}}catch(s){i&&this.conversationStore.saveCheckpoint(this.#m,null);let a=s instanceof Error?s.message:String(s);return n.settle(le.ERROR,a),this.#ge(),{content:`Error: ${a}`,error:a}}}async#Jt(e){this.#D=new AbortController,this.#ke(this.#e.announceAwaitingDecision.replace("{count}",String(e.length))),this.#U();let n=this.#D.signal,r=await Promise.all(e.map(async i=>{let s=i.toolCallId!==void 0?this.#i.get(i.toolCallId):void 0,a={},l=tE(i)??i.message;l!==void 0&&(a.message=l);let c=s?.element.getAttribute("data-tool-name");c!=null&&(a.toolName=c);let u,m=this.approveWithEdits&&s!==void 0;m&&(a.args=s.args),s?.mark(le.DEFERRED);let w=this.approvalRenderer!==null?await this.approvalRenderer(a,{signal:n}):await il(s?.approvalSlot??this.#M(),a,{signal:n,strings:this.#e,...m?{onEdit:p=>{u=p}}:{}});return s?.recordDecision(w?"approved":"declined"),w?s?.mark(le.PENDING):s?.settle(le.DECLINED,this.#e.declinedAction),{id:i.id,approved:w,editedArgs:u}}));this.#k(),this.#v.follow(),this.#D=null;let o={};for(let{id:i,approved:s,editedArgs:a}of r)o[i]=s?{status:"resolved",payload:a===void 0?{approved:!0}:{approved:!0,editedArgs:a}}:{status:"cancelled"};return o}#en(){return{onRunStart:()=>{this.#W||(this.#Re=!1,this.#ke(this.#e.announceResponding)),this.#ie(!0),this.#M(),this.#ge()},onReasoningStart:()=>{this.#U(),this.#nn()},onReasoningDelta:e=>{this.#nn().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#U(),this.#oe?.collapse(),this.#_r(e),this.#Ye+=1},onTextEnd:e=>{let n=this.#vt(e);this.#Ye<=1&&this.#Yt(n),sl(n,this.#e),this.#gt(n),this.#be(),this.#lr()},onToolCall:e=>{this.#U(),!this.#on(e)&&(this.#y.push({id:e.id,name:e.name}),this.#wt(e))},onActivity:(e,n,r)=>{this.#yt(r,e,n)},onCustomEvent:(e,n)=>{if(e===Ys){this.#yr(n);return}if(e===Cc){this.#wr(n);return}this.dispatchEvent(new CustomEvent(js,{detail:{name:e,value:n},bubbles:!0,composed:!0}))},onSubAgentStarted:(e,n,r)=>{r!==null&&(this.#d.set(e,r),this.#bt({delegationId:r,agent:n===""?null:n,phase:Rn.STARTED,status:this.#e.subAgentDelegatedTo.replace("{agent}",n),tool:null}))},onSubAgentFinished:e=>{this.#tn(e,Rn.FINISHED,null)},onSubAgentError:(e,n)=>{this.#tn(e,Rn.FAILED,n===""?this.#e.subAgentFailed:n)},onMessagesSnapshot:()=>{this.#ve("\u{1F504}",this.#e.historyReplaced,"history-replaced")},onToolResult:(e,n)=>{let r=this.#i.get(e);r!==void 0&&(r.settle(le.DONE,n),this.#p.add(e),this.#ge())},onActivityChanged:(e,n,r)=>{this.#yt(e,n,r)},onRunEnd:()=>{this.#U(),this.#be()},onError:e=>{this.#Re=!0,this.#ke(this.#e.announceFailed),this.#U();let n=this.appendMessage(qe.ASSISTANT,`\u26A0\uFE0F ${e}`);n.classList.add("message--failed"),this.#gt(n,{rateable:!1}),this.#Yt(n),this.#be()},onCancelled:()=>{this.#Re=!0,this.#ke(this.#e.announceStopped),this.#U(),this.#Er(),this.#be()},onSettled:()=>{this.#Re||this.#ke(this.#e.announceAnswerReady),this.#U(),this.#ie(!1),this.#be();for(let e of this.#i.values())e.settled||e.settle(le.DONE,this.#e.noResult);this.#j!==null&&this.#j.childElementCount===0&&(this.#j.remove(),this.#k()),this.#j=null,this.#oe=null,this.#vr()}}}#vr(){let e=this.#y.map(({id:r,name:o})=>({name:o,side:this.#p.has(r)?"server":"client"}));this.#y=[];let n=[...this.#R];this.#R=new Set,this.dispatchEvent(new CustomEvent(Vs,{detail:{tools:e,invalidated:n},bubbles:!0,composed:!0}))}#yr(e){let n=e??{},r=Array.isArray(n.keys)?n.keys.filter(o=>typeof o=="string"):[];if(r.length!==0){for(let o of r)this.#R.add(o);this.dispatchEvent(new CustomEvent(qs,{detail:{keys:r,reason:typeof n.reason=="string"?n.reason:null},bubbles:!0,composed:!0}))}}#wr(e){let n=gp(e);n!==null&&this.#bt(n)}#tn(e,n,r){let o=this.#d.get(e);if(o===void 0)return;let i=this.#o.get(o)?.agent??null;this.#bt({delegationId:o,agent:i,phase:n,status:r===null?this.#xr(i):r,tool:null})}#xr(e){return e===null?this.#e.subAgentWorking:this.#e.subAgentFinished.replace("{agent}",e)}#bt(e){let n=this.#i.get(e.delegationId);if(n===void 0)return;let r=this.#o.get(e.delegationId);r===void 0&&(r=new hs(this.#e),this.#o.set(e.delegationId,r),n.subagentSlot.appendChild(r.element)),r.report(e),this.#v.follow()}#Er(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#M().appendChild(e),this.#k(),this.#v.follow()}#ge(){if(this.#De!==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.#De=e,this.#M().appendChild(e),this.#k(),this.#v.follow()}#U(){this.#De?.remove(),this.#De=null}#nn(){if(this.#oe===null){this.#oe=new fs(this.#e);let e=this.#M();e.insertBefore(this.#oe.element,e.firstChild),this.#k(),this.#v.follow()}return this.#oe}#rn(){return this.#Le===null&&(this.#Le=this.appendMessage(qe.ASSISTANT,""),this.#Ye=0),this.#Le}#_r(e){this.#Pe=e,this.#rn(),this.#re===null&&(this.#re=requestAnimationFrame(()=>{this.#re=null,this.#vt(this.#Pe)}))}#vt(e){this.#re!==null&&(cancelAnimationFrame(this.#re),this.#re=null),this.#Pe=e;let n=this.#rn();return n.innerHTML=cs(e,{allowImages:this.allowImages}),this.#v.follow(),n}#be(){this.#re!==null&&this.#vt(this.#Pe),this.#Le=null}#on(e){let n=Rp(e);return n===null?!1:(this.#ve("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#ve(e,n,r,o){this.#M().appendChild(Fl(e,n,r,o)),this.#k(),this.#v.follow()}#in(e,n){this.#ve("\u2922",e,"surface",n===null?void 0:{label:this.#e.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#h.has(fo)&&!this.#r.has(Qi);e.includes("activity")&&this.registerActivityRenderer({type:fo,render:r=>{let o=er(r);return o===null?null:Nr(o)},removedNotice:this.#e.chartUndrawable}),e.includes("tool")&&this.registerTool(uh()),n&&this.isConnected&&this.reload()}#sn(e,n){let r;try{r=e(n.args)}catch(o){console.warn(`ag-ui-chat: render failed for tool ${n.name}`,o);return}r!==null&&(this.#a.get(n.id)?.after(r),this.#an())}registerActivityRenderer(e){this.#h.set(e.type,e),this.#c.delete(e.type)}get unhandledActivityTypes(){return[...this.#c]}#yt(e,n,r){let o=this.#h.get(n);if(o===void 0){this.#c.add(n);return}let i;try{i=o.render(r)}catch(a){console.warn(`ag-ui-chat: render failed for activity ${n}`,a),i=null}if(i===null){this.#Tr(e,n,o.removedNotice,r);return}let s=this.#u.get(e);s===void 0?this.#M().appendChild(i):s.replaceWith(i),this.#u.set(e,i),this.#an()}#Tr(e,n,r,o){let i=this.#u.has(e);this.#u.get(e)?.remove(),this.#u.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#ve("\u{1F4C9}",r,"chart-undrawable")}#an(){this.#k(),this.#v.follow()}#wt(e){let n=this.#i.get(e.id);if(n!==void 0)return n;let r=this.#et(e.name)?.parameters[xe],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#t[e.name]?.summary??vl(e.name),i=new qr(e.name,e.args,o,this.#e,{formatPayload:s=>this.formatToolPayload?.(s)??null});return this.#i.set(e.id,i),this.#M().appendChild(i.element),this.#k(),this.#v.follow(),i}};function tE(t){let e=t.metadata?.[po];return typeof e=="string"&&e.trim()!==""?e:void 0}function nE(t){return Array.isArray(t)?t.filter(oE):[]}function rE(t){if(t.name!=="")return t;let e=t.type.split("/")[1]??t.type,n=new Date().toISOString().replace(/[:.]/g,"-");return new File([t],e===""?`pasted-${n}`:`pasted-${n}.${e}`,{type:t.type})}function oE(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.function?.name=="string"}function Rp(t){if(t.name!==Js)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function iE(t){let e=t?.removed;return typeof e=="number"?e:null}function sE(){customElements.get(ho)===void 0&&customElements.define(ho,Zr)}async function aE(t,e,n={}){await _t(t),await Ka(t,{...n,flashMs:n.flashMs??0}),await Xa(t,e,n)}async function lE(t,e={}){await _t(t),await Ya(t,e)}async function cE(t,e={}){await _t(t),await Za(t,e)}async function dE(t,e,n={}){await _t(t),await Qa(t,e,n)}async function uE(t,e,n={}){await _t(t),await Ja(t,e,n)}function hE(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Ir(t,!!e):fn(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var pE="0.35.2";export{Bs as ATTACHMENT_EVENT,Zr as AgUiChat,ir as AgUiClient,fo as CHART_ACTIVITY_TYPE,Qi as CHART_TOOL_NAME,Vi as CHAT_CORNERS,Qs as COMPACTION_ACTIVITY_TYPE,js as CUSTOM_AGENT_EVENT,Mr as CheckpointMenu,kr as ClientToolRegistry,bs as ConnectionLostError,se as DEFAULT_UI_STRINGS,ho as ELEMENT_TAG,Ws as FEEDBACK_EVENT,Ys as INVALIDATE_CUSTOM_NAME,qs as INVALIDATE_EVENT,Js as LOAD_CAPABILITY_TOOL,My as MAX_QUOTE_CHARS,Ux as MAX_SUGGESTIONS,Hx as MAX_SUGGESTION_CHARS,Cn as MAX_TOOL_ROUNDS,Ft as MESSAGE_ACTIONS,qe as MESSAGE_ROLE,Cr as PAGE_ACTIONS,Vs as RUN_FINISHED_EVENT,Yr as RemoteConversationStore,Kr as RunIndex,$s as STATE_EVENT,Gs as SUBMIT_EVENT,Xs as SUGGESTIONS_ACTIVITY_TYPE,Ze as SessionStorageStore,zs as TOGGLE_EVENT,le as TOOL_CALL_STATUS,Nn as TOOL_DISPLAY,qr as ToolCallCard,Fs as UNREAD_EVENT,pE as VERSION,po as X_CONFIRM_KEY,ur as X_DESTRUCTIVE_KEY,hr as X_NAVIGATES_KEY,xe as X_SUMMARY_KEY,ml as asQuote,fl as attachMessageActions,bl as attachQuoteOffer,er as chartSpecFrom,lE as clickElement,Ba as createChatSurfaceTools,jl as createHttpAgent,el as createPageActionTools,tl as createPageMapContext,Yi as createPageStateTools,rl as createRouteTools,Fv as createStateHookTools,sE as defineAgUiChat,aE as fillField,Dv as flash,Ka as focusWithFlash,Ya as highlightThenClick,th as isChatCorner,Va as isDestructive,ji as isNavigates,ol as mergeUiStrings,es as messageActionBar,Bl as messageAttachments,nl as parseToolCatalog,Wi as prefersReducedMotion,cE as pressButton,Za as pressThenClick,vl as prettifyToolName,Dr as quotableSelection,Or as relativeTime,Nr as renderChart,cs as renderMarkdown,ps as renderSuggestionChips,il as requestApproval,ul as requestConfirmation,yl as requestQuestion,_t as scrollIntoCenterView,dE as selectControl,Qa as selectOption,hE as setControlValue,Ir as setNativeChecked,fn as setNativeValue,ja as showHighlightOverlay,bp as suggestionPrompts,uE as toggleCheckbox,Ja as toggleControl,ql as transcribeAudio,Xa as typeInto,Wl as uploadAttachment};
3669
3669
  /*! Bundled license information:
3670
3670
 
3671
3671
  fast-json-patch/module/helpers.mjs: