@artooi/ag-ui-web-component 0.20.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.20.1] — 2026-08-11
11
+
12
+ ### Fixed
13
+
14
+ - ⛔ **`placement="side"` (and `sidebar`) stopped being full height once the
15
+ panel had been resized.** A dragged size is written as a custom property on
16
+ the host, and an inline custom property **outranks a `:host([placement=…])`
17
+ rule setting the same property** — so a height dragged while floating capped a
18
+ docked sidebar that had asked for `100vh`. Since the size persists per tab,
19
+ one drag broke every later visit.
20
+
21
+ ⚠ **The previous release claimed this was already handled, and the reasoning
22
+ was wrong.** Writing `--ag-ui-height` rather than inline `height` was supposed
23
+ to leave placement with the final say; it does not, because the indirection
24
+ changes nothing about the cascade. The fix is explicit rather than
25
+ cascade-dependent: **a placement owns the axes it fixes**, a persisted size is
26
+ applied only to the axes it leaves free, and switching placement hands the
27
+ owned axes back.
28
+
29
+ ⇒ *"I used the more specific-looking mechanism" is not a substitute for
30
+ checking which declaration actually wins.*
31
+
10
32
  ## [0.20.0] — 2026-08-11
11
33
 
12
34
  ### Added
@@ -1039,7 +1061,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1039
1061
  ### Notes
1040
1062
  - First release — exercising the automated npm OIDC publish pipeline end-to-end.
1041
1063
 
1042
- [Unreleased]: https://github.com/Artui/ag-ui-web-component/compare/v0.20.0...HEAD
1064
+ [Unreleased]: https://github.com/Artui/ag-ui-web-component/compare/v0.20.1...HEAD
1065
+ [0.20.1]: https://github.com/Artui/ag-ui-web-component/compare/v0.20.0...v0.20.1
1043
1066
  [0.20.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.19.0...v0.20.0
1044
1067
  [0.19.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.18.0...v0.19.0
1045
1068
  [0.18.0]: https://github.com/Artui/ag-ui-web-component/compare/v0.17.0...v0.18.0
package/README.md CHANGED
@@ -574,10 +574,15 @@ puts it. The element probes its own geometry and reflects the result as
574
574
  `data-resize-anchor` (e.g. `bottom-right` means those two edges are fixed), which
575
575
  is what positions the grip.
576
576
 
577
- A drag writes `--ag-ui-width` / `--ag-ui-height` on the host **as custom
578
- properties, not inline `width`/`height`** — the placement rules set those same
579
- properties, so an inline dimension would outrank them and a panel dragged while
580
- floating would keep that width after switching to fullscreen.
577
+ A drag writes `--ag-ui-width` / `--ag-ui-height` on the host as custom
578
+ properties.
579
+
580
+ **That alone does not leave placement in charge** — an inline custom property
581
+ still outranks a `:host([placement=…])` rule setting the same property. So the
582
+ component enforces the split directly: **a placement owns the axes it fixes**,
583
+ and a dragged or persisted size is only ever applied to the ones it leaves free.
584
+ Switching placement hands the owned axes back. Without that, a height dragged
585
+ while floating capped a docked sidebar that had asked for `100vh`.
581
586
 
582
587
  ⚠ **A host rule that sizes the element wins over both.** `ag-ui-chat { flex: 1 }`
583
588
  stretches the panel to its container and the dragged width has no visible
@@ -1863,9 +1863,9 @@ Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error
1863
1863
  border-right: none;
1864
1864
  box-shadow: none;
1865
1865
  }
1866
- `;var bi=class{element;#n;#e;#t;#s;#r=!1;constructor(e=ae){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.setAttribute("part","thoughts-label"),this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#a(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#s.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var yi=class{element;#n;#e;#t;#s;#r;#a;#o=[];#i="";#l=null;constructor(e,n=ae){this.#n=e,this.#a=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#e=document.createElement("div"),this.#e.className="drawer-panel",this.#e.setAttribute("part","drawer-panel"),this.#e.setAttribute("role","dialog"),this.#e.setAttribute("aria-modal","true"),this.#e.setAttribute("aria-label",n.chatHistory),this.#e.addEventListener("keydown",i=>this.#d(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#t=document.createElement("span"),this.#t.className="drawer-title",this.#t.setAttribute("part","drawer-title"),this.#t.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#n.onNew()}),o.append(this.#t,this.#s),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(o,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#a=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#s.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#s.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#l?.focus(),this.#l=null)}toggle(){this.isOpen()?this.close():this.open()}#c(){return this.element.getRootNode().activeElement}#d(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let n=Array.from(this.#e.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#c();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#o=e,this.#i=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#o.length===0){let e=document.createElement("div");e.className="drawer-empty",e.setAttribute("part","drawer-empty"),e.textContent=this.#a.noConversations,this.#r.appendChild(e);return}for(let e of this.#o)this.#r.appendChild(this.#f(e))}#f(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#i&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=ci(e.updatedAt,void 0,this.#a);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#n.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#a.rename,a.setAttribute("aria-label",this.#a.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#h(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#a.delete,l.setAttribute("aria-label",this.#a.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#k(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#h(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#u():this.#n.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#u())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),e.replaceChildren(r),r.focus(),r.select()}#k(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#a.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#a.delete,i.addEventListener("click",()=>this.#n.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#a.cancel,s.addEventListener("click",()=>this.#u()),r.append(o,i,s),e.replaceChildren(r)}};function Xu(t){return{[pe.PENDING]:t.toolRunning,[pe.DONE]:t.toolDone,[pe.ERROR]:t.toolError,[pe.DECLINED]:t.toolDeclined}}function Cv(t){return{[pe.DONE]:t.resultLabel,[pe.ERROR]:t.errorLabel,[pe.DECLINED]:t.declinedLabel}}function Rv(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var hr=class{element;#n;#e;#t;#s;#r;#a;#o;#i=!1;constructor(e,n,r,o=ae){this.#o=o,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",pe.PENDING),this.element.setAttribute("data-expanded","false");let i=document.createElement("div");i.className="tool-call-head",i.setAttribute("part","tool-card-head");let s=document.createElement("span");s.className="tool-call-icon",s.setAttribute("part","tool-card-icon"),s.setAttribute("aria-hidden","true");let a=document.createElement("span");a.className="tool-call-name",a.setAttribute("part","tool-card-name"),a.textContent=r??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=Xu(o)[pe.PENDING],this.#e=document.createElement("span"),this.#e.className="tool-call-decision",this.#e.setAttribute("part","tool-card-decision"),this.#e.hidden=!0,i.append(s,a,this.#n,this.#e);let l=this.#l("args",o.argumentsLabel);l.body.textContent=JSON.stringify(n,null,2),l.root.hidden=Object.keys(n).length===0;let c=this.#l("result",o.resultLabel);this.#s=c.root,this.#r=c.label,this.#a=c.body,c.root.hidden=!0,this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="tool-call-toggle",this.#t.setAttribute("part","tool-card-toggle"),this.#t.setAttribute("aria-expanded","false"),this.#t.textContent=o.details,this.#t.addEventListener("click",()=>this.#d(!this.#c()));let h=document.createElement("div");h.className="tool-call-body",h.setAttribute("part","tool-card-body"),h.append(l.root,c.root),this.element.append(i,this.#t,h)}recordDecision(e){this.element.setAttribute("data-decision",e),this.#e.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#e.hidden=!1}get settled(){return this.#i}settle(e,n){this.#i||(this.#i=!0,this.element.setAttribute("data-status",e),this.#n.textContent=Xu(this.#o)[e],this.#r.textContent=Cv(this.#o)[e],this.#a.textContent=Rv(n),this.#s.hidden=!1)}#l(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#c(){return this.element.getAttribute("data-expanded")==="true"}#d(e){this.element.setAttribute("data-expanded",String(e)),this.#t.setAttribute("aria-expanded",String(e))}};var xi=class{element;#n;#e;#t;#s="idle";#r=null;#a=null;#o=[];#i=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ae,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button"),this.element.textContent="\u{1F3A4}",this.#h("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#c();return}this.#s!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#f(this.#t.transcriptionFailed);return}this.#a=e,this.#o=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#d(n.mimeType)}),this.#r=n,n.start(),this.#h("recording")}#c(){this.#r?.stop()}dispose(){this.#i=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#d(e){if(this.#i)return;this.#u(),this.#h("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#h("idle"),r!==""&&this.#e(r)}catch(r){this.#f(r instanceof Error?r.message:this.#t.transcriptionFailed)}finally{this.#r=null}}#u(){for(let e of this.#a?.getTracks()??[])e.stop();this.#a=null}#f(e){this.#u(),this.#r=null,this.#h("idle"),this.element.title=e}#h(e){this.#s=e,this.element.dataset.state=e;let n=this.#k(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#k(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var Ei=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Ln=class{#n;#e;#t;#s;#r;#a;#o;#i=new Set;#l;#c=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Ue(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#o(this.#n.messages),await this.#d()}async resume(){await this.#d()}addToolResult(e,n){this.#n.addMessage({id:Ue(),role:"tool",content:n,toolCallId:e}),this.#o(this.#n.messages)}cancel(){this.#c=!0,this.#n.abortRun()}async#d(){this.#c=!1;try{await this.#f(),this.#c&&this.#u()}catch(e){this.#c||Nv(e)?this.#u():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#u(){this.#o(this.#n.messages),this.#e.onCancelled()}async#f(){let e;for(let n=0;n<Yi;n+=1){if(this.#c)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#o(this.#n.messages),this.#c)return;if(!o.terminal)throw new Ei(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#c)return;e=nu(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;this.#n.addMessage({id:Ue(),role:"tool",content:l.content,toolCallId:a.id}),this.#o(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e,o=this.#i;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:i}){o.has(i.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${i.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({event:i,textMessageBuffer:s}){o.add(i.messageId),r.onTextEnd(s)},onToolCallEndEvent({event:i,toolCallName:s,toolCallArgs:a}){let l={id:i.toolCallId,name:s,args:a};e.push(l),r.onToolCall(l)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onActivitySnapshotEvent({event:i}){r.onActivity(i.activityType,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(i){n.terminal=!0,i.outcome==="interrupt"&&(n.interrupts=i.interrupts)},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Nv(t){return t instanceof Error&&t.name==="AbortError"}function ka(t){let e=t.attachments;return Array.isArray(e)?e.filter(Ov):[]}function Ov(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 Ia="ag-ui-chat",fr="thread",Ca="threads",Ti="messages:",wi="checkpoint:",Mv=60,Lv=100,Pv="New conversation",ft=class{#n;constructor(e=""){this.#n=e===""?Ia:`${Ia}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(fr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Ue();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#o(this.#r(Ti+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(Ti+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#o(this.#r(wi+e))}saveCheckpoint(e,n){let r=this.#r(wi+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Ti+e)),sessionStorage.removeItem(this.#r(wi+e)),this.#s(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(fr))===e&&sessionStorage.removeItem(this.#r(fr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(fr),e)}renameThread(e,n){let r=this.#t(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=Uv(n),s=Date.now();o===void 0?r.push({threadId:e,title:Yu(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Yu(n))),this.#s(r)}#t(){return this.#o(this.#r(Ca))??[]}#s(e){let n=this.#r(Ca);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Ia}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let o=sessionStorage.key(r);if(o===null||!o.startsWith(e))continue;let i=o.slice(e.length);Dv(i)&&n.push([o,this.#r(i)])}for(let[r,o]of n){let i=sessionStorage.getItem(r);i!==null&&sessionStorage.getItem(o)===null&&sessionStorage.setItem(o,i),sessionStorage.removeItem(r)}}#o(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Dv(t){return t===fr||t===Ca||t.startsWith(Ti)||t.startsWith(wi)}function Yu(t){for(let e of t)if(e.role==="user"){let n=Ku(e.content);if(n!=="")return Zu(n,Mv)}return Pv}function Uv(t){for(let e of[...t].reverse()){let n=Ku(e.content);if(n!=="")return Zu(n,Lv)}return""}function Ku(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Zu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Ra(t){return new ru({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var mr=class{#n;#e;#t;#s=new Set;#r=new Map;constructor(e,n=()=>({}),r=new ft){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}saveMessages(e,n){this.#t.saveMessages(e,n)}loadCheckpoint(e){return this.#t.loadCheckpoint(e)}saveCheckpoint(e,n){this.#t.saveCheckpoint(e,n)}renameThread(e,n){this.#t.renameThread(e,n),this.#r.set(e,n),this.#c(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#s.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#a();return e===null?this.#t.listThreads():e.filter(n=>!this.#s.has(n.thread_id)).map(n=>this.#i(n))}async loadMessages(e){let n=await this.#l(`${this.#n}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#o(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#a(){let e=await this.#l(this.#n);if(e===null||!e.ok)return null;let n=await this.#o(e);return n===null?null:n.threads??[]}async#o(e){try{return await e.json()}catch{return null}}#i(e){return{threadId:e.thread_id,title:this.#r.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#l(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#c(e,n,r){let o=this.#e();try{await fetch(`${this.#n}${encodeURIComponent(e)}/`,{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var gr=class{#n;#e;constructor(e,n=()=>({})){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n}async list(){try{let e=await fetch(this.#n,{method:"GET",headers:{Accept:"application/json",...this.#e()}});return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#t("resume",e)}forkUrl(e){return this.#t("fork",e)}#t(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function Na(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,{method:"POST",headers:{...e.headers??{}},body:n});if(!r.ok)throw new Error(await Hv(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 Hv(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Oa(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Gv(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(zv(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 Gv(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 zv(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Fv=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],Ju="ag-ui-chat:collapsed",Qu="ag-ui-chat:size",ed="ag-ui-chat:theme",vr=class extends HTMLElement{agentFactory=Ra;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#le().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...us(this.getPageMap,this.autoInjectPageMap),...this.#Ve()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new ft;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=ae;#t=new $n;#s=new Map;#r=new Set;#a;#o;#i;#l;#c;#d;#u;#f;#h;#k=null;#y;#v;#b;#H;#S;#_;#I;#m=null;#G;#q=null;#z=!1;#L=[];#C=null;#N={};#P=!1;#W=null;#x=null;#E=null;#X=0;#F=null;#A=null;#R=null;#p="";#O="";#Y=0;#K=[];#ie=[];#se=[];#ae=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#o=document.createElement("div"),this.#i=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#d=document.createElement("span"),this.#y=document.createElement("div"),this.#v=document.createElement("button"),this.#b=document.createElement("input"),this.#H=document.createElement("div"),this.#G=document.createElement("span"),this.#S=document.createElement("button"),this.#_=document.createElement("button"),this.#I=document.createElement("div"),this.#u=new vi(e=>this.#Ke(e)),this.#f=new yi({onSelect:e=>{this.#et(e)},onNew:()=>{this.newChat(),this.#B()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#B()},onDelete:e=>{this.#tt(e)}}),this.#h=new ir((e,n)=>{this.#Ie(e,n)})}#Z(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#k===null&&(this.#k=new gr(e,()=>this.headers)),this.#k)}async#Ie(e,n){let r=this.#Z();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="";let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#p,initialMessages:[]});await new Ln({agent:s,handlers:this.#Se(),getTools:()=>this.getTools(),getContext:()=>this.#ge(),executeTool:l=>this.#Te(l),resolveInterrupts:l=>this.#we(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Ce(){let e=this.#Z();this.#h.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement",...Fv]}attributeChangedCallback(e,n,r){if(e==="placement"){requestAnimationFrame(()=>this.#Q());return}if(e==="title-text"){this.#d.textContent=r??this.#e.title;return}n===r||!this.#z||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#t.register(e)}get sharedState(){return this.#C?.state??this.#N}set sharedState(e){this.#N={...e},this.#C?.setState(this.#N)}registerPageState(e){for(let n of Lr(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#Re(){return this.routeMap.length===0?[]:ps(()=>this.routeMap,()=>this.navigate)}#Ne(){let e=this.getPageMap;return e===null?[]:[{name:Xi,description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Le]:"Read the page"},handler:()=>e()}]}#Oe(){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 cs(n,r=>this.resolvePageTarget(r))}#le(){return[...this.#Re(),...this.#Ne(),...this.#Oe(),...this.#Me()]}#Me(){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.#Le(e)}]:[]}async#Le(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.#x=new AbortController;let i=this.#x.signal;this.#w();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await aa(this.#T(),r,{signal:i,strings:this.#e});return this.#x=null,this.#g(),this.#i.scrollTop=this.#i.scrollHeight,s}#ce(e){let n=this.#le().find(r=>r.name===e);return n!==void 0?n:this.#t.has(e)?this.#t.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===dn.INLINE||e===dn.MINIMAL||e===dn.COMPACT?e:dn.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#O=this.id!==""?this.id:this.endpoint,this.#ee(this.#he()),requestAnimationFrame(()=>this.#Q()),this.#e=hs({...this.#Pe(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#te(ed);e!==null&&this.setAttribute("theme",e)}this.#at(),this.#f.setStrings(this.#e),this.#h.setStrings(this.#e),this.#te(Ju)==="1"&&this.setAttribute("collapsed",""),this.#ye(),this.#We(),this.#qe(),this.#O!==""&&this.conversationStore instanceof ft&&(this.conversationStore=new ft(this.#O)),this.#je(),this.#De(),this.#He(),this.#p=this.conversationStore.threadId(),this.#me(),this.#z=!0}disconnectedCallback(){this.#z=!1,this.#M(),this.#m?.dispose(),this.#q?.dispose()}#ue(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#Pe(){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{}}#De(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#Ue(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new li({upload:n,maxBytes:this.#Fe(),accept:r,strings:this.#e,onChange:()=>this.#ct(o)});this.#m=o,this.#H.appendChild(this.#m.element),this.#b.accept=r,this.#v.hidden=!1,this.#Be()}#Ue(e){return e===null?null:(n,r,o)=>Oa(n,{url:e,headers:this.headers,onProgress:r,signal:o})}#He(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#Ge(e);n!==null&&(this.#q=new xi({transcribe:n,onText:r=>this.#ze(r),strings:this.#e}),this.#G.appendChild(this.#q.element))}#Ge(e){return e===null?null:n=>Na(n,{url:e,headers:this.headers})}#ze(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#xe(),this.#l.focus()}#Fe(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Ki;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Ki}#$e(){let e=this.#b.files;if(e!==null)for(let n of Array.from(e))this.#m?.add(n);this.#b.value=""}#Be(){this.#o.addEventListener("dragover",e=>{e.preventDefault(),this.#o.classList.add("chat--dragover")}),this.#o.addEventListener("dragleave",()=>{this.#o.classList.remove("chat--dragover")}),this.#o.addEventListener("drop",e=>{e.preventDefault(),this.#o.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#m?.add(r)})}#Ve(){return this.#L.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#L.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1866
+ `;var bi=class{element;#n;#e;#t;#s;#r=!1;constructor(e=ae){this.#s=e,this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="thoughts-toggle",this.#t.setAttribute("part","thoughts-toggle"),this.#t.setAttribute("aria-expanded","true"),this.#n=document.createElement("span"),this.#n.className="thoughts-label",this.#n.setAttribute("part","thoughts-label"),this.#n.textContent=e.thinking,this.#t.append(this.#n),this.#e=document.createElement("pre"),this.#e.className="thoughts-body",this.#e.setAttribute("part","thoughts-body"),this.#t.addEventListener("click",()=>{this.#a(!this.#r)}),this.element.append(this.#t,this.#e)}stream(e){this.#e.textContent=e}collapse(){this.#r||(this.element.removeAttribute("data-streaming"),this.#n.textContent=this.#s.thoughts,this.#a(!0))}#a(e){this.#r=e,this.#e.hidden=e,this.#t.setAttribute("aria-expanded",String(!e))}};var yi=class{element;#n;#e;#t;#s;#r;#a;#o=[];#i="";#l=null;constructor(e,n=ae){this.#n=e,this.#a=n,this.element=document.createElement("div"),this.element.className="drawer",this.element.setAttribute("part","drawer"),this.element.hidden=!0;let r=document.createElement("div");r.className="drawer-backdrop",r.setAttribute("part","drawer-backdrop"),r.addEventListener("click",()=>this.close()),this.#e=document.createElement("div"),this.#e.className="drawer-panel",this.#e.setAttribute("part","drawer-panel"),this.#e.setAttribute("role","dialog"),this.#e.setAttribute("aria-modal","true"),this.#e.setAttribute("aria-label",n.chatHistory),this.#e.addEventListener("keydown",i=>this.#d(i));let o=document.createElement("div");o.className="drawer-header",o.setAttribute("part","drawer-header"),this.#t=document.createElement("span"),this.#t.className="drawer-title",this.#t.setAttribute("part","drawer-title"),this.#t.textContent=n.chats,this.#s=document.createElement("button"),this.#s.type="button",this.#s.className="drawer-new",this.#s.setAttribute("part","drawer-new"),this.#s.textContent=n.newChat,this.#s.addEventListener("click",()=>{this.close(),this.#n.onNew()}),o.append(this.#t,this.#s),this.#r=document.createElement("div"),this.#r.className="drawer-list",this.#r.setAttribute("part","drawer-list"),this.#e.append(o,this.#r),this.element.append(r,this.#e)}setStrings(e){this.#a=e,this.#e.setAttribute("aria-label",e.chatHistory),this.#t.textContent=e.chats,this.#s.textContent=e.newChat,this.#u()}isOpen(){return!this.element.hidden}open(){this.isOpen()||(this.#l=this.#c(),this.element.hidden=!1,this.#s.focus())}close(){this.isOpen()&&(this.element.hidden=!0,this.#l?.focus(),this.#l=null)}toggle(){this.isOpen()?this.close():this.open()}#c(){return this.element.getRootNode().activeElement}#d(e){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let n=Array.from(this.#e.querySelectorAll("button, input, [tabindex]")).filter(s=>!s.hidden),r=n[0],o=n[n.length-1],i=this.#c();e.shiftKey&&i===r?(e.preventDefault(),o?.focus()):!e.shiftKey&&i===o&&(e.preventDefault(),r?.focus())}setThreads(e,n){this.#o=e,this.#i=n,this.#u()}#u(){if(this.#r.replaceChildren(),this.#o.length===0){let e=document.createElement("div");e.className="drawer-empty",e.setAttribute("part","drawer-empty"),e.textContent=this.#a.noConversations,this.#r.appendChild(e);return}for(let e of this.#o)this.#r.appendChild(this.#f(e))}#f(e){let n=document.createElement("div");n.className="drawer-row",n.setAttribute("part","drawer-row"),e.threadId===this.#i&&n.classList.add("drawer-row--active");let r=document.createElement("button");r.type="button",r.className="drawer-row-select",r.setAttribute("part","drawer-row-select");let o=document.createElement("span");o.className="drawer-row-title",o.setAttribute("part","drawer-row-title"),o.textContent=e.title;let i=document.createElement("span");i.className="drawer-row-time",i.setAttribute("part","drawer-row-time"),i.textContent=ci(e.updatedAt,void 0,this.#a);let s=document.createElement("span");s.className="drawer-row-preview",s.setAttribute("part","drawer-row-preview"),s.textContent=e.preview,r.append(o,i,s),r.addEventListener("click",()=>{this.close(),this.#n.onSelect(e.threadId)});let a=document.createElement("button");a.type="button",a.className="drawer-row-rename",a.setAttribute("part","drawer-row-rename"),a.title=this.#a.rename,a.setAttribute("aria-label",this.#a.renameConversation),a.textContent="\u270E",a.addEventListener("click",()=>this.#h(n,e));let l=document.createElement("button");l.type="button",l.className="drawer-row-delete",l.setAttribute("part","drawer-row-delete"),l.title=this.#a.delete,l.setAttribute("aria-label",this.#a.deleteConversation),l.textContent="\u{1F5D1}",l.addEventListener("click",()=>this.#k(n,e));let c=document.createElement("div");return c.className="drawer-row-actions",c.setAttribute("part","drawer-row-actions"),c.append(a,l),n.append(r,c),n}#h(e,n){let r=document.createElement("input");r.type="text",r.className="drawer-rename-input",r.setAttribute("part","drawer-rename-input"),r.value=n.title;let o=!1,i=()=>{if(o)return;o=!0;let a=r.value.trim();a===""||a===n.title?this.#u():this.#n.onRename(n.threadId,a)},s=()=>{o||(o=!0,this.#u())};r.addEventListener("keydown",a=>{a.key==="Enter"?(a.preventDefault(),i()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),s())}),r.addEventListener("blur",()=>i()),e.replaceChildren(r),r.focus(),r.select()}#k(e,n){let r=document.createElement("div");r.className="drawer-confirm",r.setAttribute("part","drawer-confirm");let o=document.createElement("span");o.className="drawer-confirm-label",o.setAttribute("part","drawer-confirm-label"),o.textContent=this.#a.deletePrompt;let i=document.createElement("button");i.type="button",i.className="drawer-confirm-yes",i.setAttribute("part","drawer-confirm-yes"),i.textContent=this.#a.delete,i.addEventListener("click",()=>this.#n.onDelete(n.threadId));let s=document.createElement("button");s.type="button",s.className="drawer-confirm-no",s.setAttribute("part","drawer-confirm-no"),s.textContent=this.#a.cancel,s.addEventListener("click",()=>this.#u()),r.append(o,i,s),e.replaceChildren(r)}};function Xu(t){return{[pe.PENDING]:t.toolRunning,[pe.DONE]:t.toolDone,[pe.ERROR]:t.toolError,[pe.DECLINED]:t.toolDeclined}}function Cv(t){return{[pe.DONE]:t.resultLabel,[pe.ERROR]:t.errorLabel,[pe.DECLINED]:t.declinedLabel}}function Rv(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}var hr=class{element;#n;#e;#t;#s;#r;#a;#o;#i=!1;constructor(e,n,r,o=ae){this.#o=o,this.element=document.createElement("div"),this.element.className="tool-call",this.element.setAttribute("part","tool-card"),this.element.setAttribute("data-tool-name",e),this.element.setAttribute("data-status",pe.PENDING),this.element.setAttribute("data-expanded","false");let i=document.createElement("div");i.className="tool-call-head",i.setAttribute("part","tool-card-head");let s=document.createElement("span");s.className="tool-call-icon",s.setAttribute("part","tool-card-icon"),s.setAttribute("aria-hidden","true");let a=document.createElement("span");a.className="tool-call-name",a.setAttribute("part","tool-card-name"),a.textContent=r??e,this.#n=document.createElement("span"),this.#n.className="tool-call-status",this.#n.setAttribute("part","tool-card-status"),this.#n.textContent=Xu(o)[pe.PENDING],this.#e=document.createElement("span"),this.#e.className="tool-call-decision",this.#e.setAttribute("part","tool-card-decision"),this.#e.hidden=!0,i.append(s,a,this.#n,this.#e);let l=this.#l("args",o.argumentsLabel);l.body.textContent=JSON.stringify(n,null,2),l.root.hidden=Object.keys(n).length===0;let c=this.#l("result",o.resultLabel);this.#s=c.root,this.#r=c.label,this.#a=c.body,c.root.hidden=!0,this.#t=document.createElement("button"),this.#t.type="button",this.#t.className="tool-call-toggle",this.#t.setAttribute("part","tool-card-toggle"),this.#t.setAttribute("aria-expanded","false"),this.#t.textContent=o.details,this.#t.addEventListener("click",()=>this.#d(!this.#c()));let h=document.createElement("div");h.className="tool-call-body",h.setAttribute("part","tool-card-body"),h.append(l.root,c.root),this.element.append(i,this.#t,h)}recordDecision(e){this.element.setAttribute("data-decision",e),this.#e.textContent=e==="approved"?this.#o.decisionApproved:this.#o.decisionDeclined,this.#e.hidden=!1}get settled(){return this.#i}settle(e,n){this.#i||(this.#i=!0,this.element.setAttribute("data-status",e),this.#n.textContent=Xu(this.#o)[e],this.#r.textContent=Cv(this.#o)[e],this.#a.textContent=Rv(n),this.#s.hidden=!1)}#l(e,n){let r=document.createElement("div");r.className=`tool-call-section tool-call-section--${e}`,r.setAttribute("part",`tool-card-section tool-card-${e}-section`);let o=document.createElement("span");o.className="tool-call-section-label",o.setAttribute("part",`tool-card-section-label tool-card-${e}-label`),o.textContent=n;let i=document.createElement("pre");return i.className=`tool-call-${e}`,i.setAttribute("part",`tool-card-${e}`),r.append(o,i),{root:r,label:o,body:i}}#c(){return this.element.getAttribute("data-expanded")==="true"}#d(e){this.element.setAttribute("data-expanded",String(e)),this.#t.setAttribute("aria-expanded",String(e))}};var xi=class{element;#n;#e;#t;#s="idle";#r=null;#a=null;#o=[];#i=!1;constructor(e){this.#n=e.transcribe,this.#e=e.onText,this.#t=e.strings??ae,this.element=document.createElement("button"),this.element.type="button",this.element.className="voice-btn",this.element.setAttribute("part","voice-button"),this.element.textContent="\u{1F3A4}",this.#h("idle"),this.element.addEventListener("click",()=>{this.toggle()})}async toggle(){if(this.#s==="recording"){this.#c();return}this.#s!=="transcribing"&&await this.#l()}async#l(){let e;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{this.#f(this.#t.transcriptionFailed);return}this.#a=e,this.#o=[];let n=new MediaRecorder(e);n.addEventListener("dataavailable",r=>{this.#o.push(r.data)}),n.addEventListener("stop",()=>{this.#d(n.mimeType)}),this.#r=n,n.start(),this.#h("recording")}#c(){this.#r?.stop()}dispose(){this.#i=!0,this.#r!==null&&this.#r.state!=="inactive"&&this.#r.stop(),this.#r=null,this.#u()}async#d(e){if(this.#i)return;this.#u(),this.#h("transcribing");let n=new Blob(this.#o,{type:e||"audio/webm"});try{let r=await this.#n(n);this.#h("idle"),r!==""&&this.#e(r)}catch(r){this.#f(r instanceof Error?r.message:this.#t.transcriptionFailed)}finally{this.#r=null}}#u(){for(let e of this.#a?.getTracks()??[])e.stop();this.#a=null}#f(e){this.#u(),this.#r=null,this.#h("idle"),this.element.title=e}#h(e){this.#s=e,this.element.dataset.state=e;let n=this.#k(e);this.element.title=n,this.element.setAttribute("aria-label",n),this.element.setAttribute("aria-pressed",String(e==="recording")),this.element.disabled=e==="transcribing"}#k(e){return e==="recording"?this.#t.stopRecording:e==="transcribing"?this.#t.transcribing:this.#t.recordVoice}};var Ei=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},Ln=class{#n;#e;#t;#s;#r;#a;#o;#i=new Set;#l;#c=!1;constructor(e){this.#n=e.agent,this.#e=e.handlers,this.#t=e.getTools??(()=>[]),this.#s=e.getContext??(()=>[]),this.#r=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost";let n=e.onStateChanged;n!==void 0&&this.#n.subscribe({onStateChanged:({state:r})=>{n(r)}})}get state(){return this.#n.state}setState(e){this.#n.setState({...e})}get running(){return this.#n.isRunning}get messages(){return this.#n.messages}async send(e,n=[]){let r={id:Ue(),role:"user",content:e};n.length>0&&(r.attachments=n),this.#n.addMessage(r),this.#o(this.#n.messages),await this.#d()}async resume(){await this.#d()}addToolResult(e,n){this.#n.addMessage({id:Ue(),role:"tool",content:n,toolCallId:e}),this.#o(this.#n.messages)}cancel(){this.#c=!0,this.#n.abortRun()}async#d(){this.#c=!1;try{await this.#f(),this.#c&&this.#u()}catch(e){this.#c||Nv(e)?this.#u():this.#e.onError(e instanceof Error?e.message:String(e))}finally{this.#e.onSettled()}}#u(){this.#o(this.#n.messages),this.#e.onCancelled()}async#f(){let e;for(let n=0;n<Yi;n+=1){if(this.#c)return;let r=[],o={terminal:!1,errored:!1,interrupts:[]},i={tools:this.#t(),context:this.#s()};if(e!==void 0&&(i.resume=e),await this.#n.runAgent(i,this.#h(r,o)),e=void 0,this.#o(this.#n.messages),this.#c)return;if(!o.terminal)throw new Ei(this.#l);if(o.errored)return;if(o.interrupts.length>0){if(this.#a===null)return;let a=await this.#a(o.interrupts);if(this.#c)return;e=nu(o.interrupts,a);continue}if(this.#r===null||r.length===0)return;let s=!1;for(let a of r){let l=await this.#r(a);if(l!==null){if(l.halt===!0)return;this.#n.addMessage({id:Ue(),role:"tool",content:l.content,toolCallId:a.id}),this.#o(this.#n.messages),s=!0}}if(!s)return}}#h(e,n){let r=this.#e,o=this.#i;return{onRunInitialized(){r.onRunStart()},onTextMessageStartEvent({event:i}){o.has(i.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${i.messageId}", which was already closed. Its content will be appended to that earlier message rather than starting a new one, and the merged result is what gets persisted. Issue a fresh id per message.`)},onTextMessageContentEvent({textMessageBuffer:i}){r.onTextDelta(i)},onTextMessageEndEvent({event:i,textMessageBuffer:s}){o.add(i.messageId),r.onTextEnd(s)},onToolCallEndEvent({event:i,toolCallName:s,toolCallArgs:a}){let l={id:i.toolCallId,name:s,args:a};e.push(l),r.onToolCall(l)},onToolCallResultEvent({event:i}){r.onToolResult(i.toolCallId,i.content)},onActivitySnapshotEvent({event:i}){r.onActivity(i.activityType,i.content)},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:i}){r.onReasoningDelta(i)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(i){n.terminal=!0,i.outcome==="interrupt"&&(n.interrupts=i.interrupts)},onRunErrorEvent({event:i}){n.terminal=!0,n.errored=!0,r.onError(i.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function Nv(t){return t instanceof Error&&t.name==="AbortError"}function ka(t){let e=t.attachments;return Array.isArray(e)?e.filter(Ov):[]}function Ov(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 Ia="ag-ui-chat",fr="thread",Ca="threads",Ti="messages:",wi="checkpoint:",Mv=60,Lv=100,Pv="New conversation",ft=class{#n;constructor(e=""){this.#n=e===""?Ia:`${Ia}@${e}`,e!==""&&this.#a()}threadId(){let e=this.#r(fr),n=sessionStorage.getItem(e);if(n!==null)return n;let r=Ue();return sessionStorage.setItem(e,r),r}loadMessages(e){return Promise.resolve(this.#o(this.#r(Ti+e)))}saveMessages(e,n){sessionStorage.setItem(this.#r(Ti+e),JSON.stringify(n)),this.#e(e,n)}loadCheckpoint(e){return this.#o(this.#r(wi+e))}saveCheckpoint(e,n){let r=this.#r(wi+e);if(n===null){sessionStorage.removeItem(r);return}sessionStorage.setItem(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#r(Ti+e)),sessionStorage.removeItem(this.#r(wi+e)),this.#s(this.#t().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#r(fr))===e&&sessionStorage.removeItem(this.#r(fr))}listThreads(){let e=this.#t().sort((n,r)=>r.updatedAt-n.updatedAt).map(({threadId:n,title:r,updatedAt:o,preview:i})=>({threadId:n,title:r,updatedAt:o,preview:i}));return Promise.resolve(e)}setActiveThread(e){sessionStorage.setItem(this.#r(fr),e)}renameThread(e,n){let r=this.#t(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#s(r))}#e(e,n){let r=this.#t(),o=r.find(a=>a.threadId===e),i=Uv(n),s=Date.now();o===void 0?r.push({threadId:e,title:Yu(n),titleCustom:!1,preview:i,updatedAt:s}):(o.preview=i,o.updatedAt=s,o.titleCustom||(o.title=Yu(n))),this.#s(r)}#t(){return this.#o(this.#r(Ca))??[]}#s(e){let n=this.#r(Ca);if(e.length===0){sessionStorage.removeItem(n);return}sessionStorage.setItem(n,JSON.stringify(e))}#r(e){return`${this.#n}:${e}`}#a(){let e=`${Ia}:`,n=[];for(let r=0;r<sessionStorage.length;r+=1){let o=sessionStorage.key(r);if(o===null||!o.startsWith(e))continue;let i=o.slice(e.length);Dv(i)&&n.push([o,this.#r(i)])}for(let[r,o]of n){let i=sessionStorage.getItem(r);i!==null&&sessionStorage.getItem(o)===null&&sessionStorage.setItem(o,i),sessionStorage.removeItem(r)}}#o(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function Dv(t){return t===fr||t===Ca||t.startsWith(Ti)||t.startsWith(wi)}function Yu(t){for(let e of t)if(e.role==="user"){let n=Ku(e.content);if(n!=="")return Zu(n,Mv)}return Pv}function Uv(t){for(let e of[...t].reverse()){let n=Ku(e.content);if(n!=="")return Zu(n,Lv)}return""}function Ku(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function Zu(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function Ra(t){return new ru({url:t.endpoint,headers:t.headers??{},initialState:{...t.initialState??{}},fetch:(e,n)=>{let r=t.getHeaders?.();if(r===void 0)return fetch(e,n);let o=new Headers(n?.headers);for(let[i,s]of Object.entries(r))o.set(i,s);return fetch(e,{...n,headers:o})},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}var mr=class{#n;#e;#t;#s=new Set;#r=new Map;constructor(e,n=()=>({}),r=new ft){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n,this.#t=r}threadId(){return this.#t.threadId()}setActiveThread(e){this.#t.setActiveThread(e)}saveMessages(e,n){this.#t.saveMessages(e,n)}loadCheckpoint(e){return this.#t.loadCheckpoint(e)}saveCheckpoint(e,n){this.#t.saveCheckpoint(e,n)}renameThread(e,n){this.#t.renameThread(e,n),this.#r.set(e,n),this.#c(e,"PATCH",{title:n})}clear(e){this.#t.clear(e),this.#s.add(e),this.#c(e,"DELETE")}async listThreads(){let e=await this.#a();return e===null?this.#t.listThreads():e.filter(n=>!this.#s.has(n.thread_id)).map(n=>this.#i(n))}async loadMessages(e){let n=await this.#l(`${this.#n}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#t.loadMessages(e);let r=await this.#o(n);return r===null?this.#t.loadMessages(e):r.messages??null}async#a(){let e=await this.#l(this.#n);if(e===null||!e.ok)return null;let n=await this.#o(e);return n===null?null:n.threads??[]}async#o(e){try{return await e.json()}catch{return null}}#i(e){return{threadId:e.thread_id,title:this.#r.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#l(e){try{return await fetch(e,{headers:this.#e()})}catch{return null}}async#c(e,n,r){let o=this.#e();try{await fetch(`${this.#n}${encodeURIComponent(e)}/`,{method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)})}catch{}}};var gr=class{#n;#e;constructor(e,n=()=>({})){this.#n=e.endsWith("/")?e:`${e}/`,this.#e=n}async list(){try{let e=await fetch(this.#n,{method:"GET",headers:{Accept:"application/json",...this.#e()}});return e.ok?(await e.json()).runs??[]:[]}catch{return[]}}async continuable(){return(await this.list()).filter(e=>e.continuable)}resumeUrl(e){return this.#t("resume",e)}forkUrl(e){return this.#t("fork",e)}#t(e,n){return`${this.#n.slice(0,-5)}${e}/${encodeURIComponent(n)}/`}};async function Na(t,e){let n=new FormData;n.append("audio",t,"recording.webm");let r=await fetch(e.url,{method:"POST",headers:{...e.headers??{}},body:n});if(!r.ok)throw new Error(await Hv(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 Hv(t){try{let e=await t.json();if(typeof e.error=="string")return e.error}catch{}return`transcription failed (${t.status})`}function Oa(t,e){return new Promise((n,r)=>{let o=new FormData;o.append("file",t);let i=new XMLHttpRequest;i.open("POST",e.url);for(let[l,c]of Object.entries(e.headers??{}))i.setRequestHeader(l,c);let s=e.onProgress;s!==void 0&&i.upload.addEventListener("progress",l=>{l.lengthComputable&&s(l.total===0?0:l.loaded/l.total)}),i.addEventListener("load",()=>{if(i.status>=200&&i.status<300)try{n(Gv(JSON.parse(i.responseText)))}catch{r(new Error("upload returned an unreadable response"))}else r(new Error(zv(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 Gv(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 zv(t){try{let e=JSON.parse(t.responseText);if(typeof e.error=="string")return e.error}catch{}return`upload failed (${t.status})`}var Fv=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],Ju="ag-ui-chat:collapsed",Qu="ag-ui-chat:size",ed="ag-ui-chat:theme",vr=class extends HTMLElement{agentFactory=Ra;headers={};allowImages=!1;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;confirmPredicate=null;getTools=()=>[...this.#ce().map(e=>({name:e.name,description:e.description,parameters:e.parameters})),...this.#t.tools()];getContext=()=>[...us(this.getPageMap,this.autoInjectPageMap),...this.#je()];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;conversationStore=new ft;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};strings={};resolvePageTarget=e=>document.querySelector(e);#n={};#e=ae;#t=new $n;#s=new Map;#r=new Set;#a;#o;#i;#l;#c;#d;#u;#f;#h;#k=null;#y;#v;#b;#H;#S;#_;#I;#m=null;#G;#q=null;#z=!1;#L=[];#C=null;#N={};#P=!1;#W=null;#x=null;#E=null;#X=0;#F=null;#A=null;#R=null;#p="";#O="";#Y=0;#K=[];#se=[];#ae=[];#le=[];constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#o=document.createElement("div"),this.#i=document.createElement("div"),this.#l=document.createElement("textarea"),this.#c=document.createElement("button"),this.#d=document.createElement("span"),this.#y=document.createElement("div"),this.#v=document.createElement("button"),this.#b=document.createElement("input"),this.#H=document.createElement("div"),this.#G=document.createElement("span"),this.#S=document.createElement("button"),this.#_=document.createElement("button"),this.#I=document.createElement("div"),this.#u=new vi(e=>this.#Ze(e)),this.#f=new yi({onSelect:e=>{this.#tt(e)},onNew:()=>{this.newChat(),this.#B()},onRename:(e,n)=>{this.conversationStore.renameThread(e,n),this.#B()},onDelete:e=>{this.#nt(e)}}),this.#h=new ir((e,n)=>{this.#Ce(e,n)})}#Z(){let e=this.getAttribute("data-runs-url");return e===null||e===""?null:(this.#k===null&&(this.#k=new gr(e,()=>this.headers)),this.#k)}async#Ce(e,n){let r=this.#Z();if(r===null)return;let o=this.#l.value.trim();if(o==="")return;this.#l.value="";let i=n==="resume"?r.resumeUrl(e):r.forkUrl(e),s=this.agentFactory({endpoint:i,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#p,initialMessages:[]});await new Ln({agent:s,handlers:this.#_e(),getTools:()=>this.getTools(),getContext:()=>this.#ve(),executeTool:l=>this.#we(l),resolveInterrupts:l=>this.#Se(l),connectionLostMessage:this.#e.connectionLost}).send(o)}async#Re(){let e=this.#Z();this.#h.setRuns(e===null?[]:await e.continuable())}static get observedAttributes(){return["title-text","placement",...Fv]}attributeChangedCallback(e,n,r){if(e==="placement"){this.#Qe(),requestAnimationFrame(()=>this.#ee());return}if(e==="title-text"){this.#d.textContent=r??this.#e.title;return}n===r||!this.#z||console.warn(`<ag-ui-chat>: "${e}" was changed after the element connected, and is read only while connecting \u2014 this assignment has no effect. Set it before the element enters the DOM (in the markup, or on the element before appending it); frameworks that patch attributes after mount should bind it at creation. To apply a new value now, remove and re-insert the element.`)}registerTool(e){this.#t.register(e)}get sharedState(){return this.#C?.state??this.#N}set sharedState(e){this.#N={...e},this.#C?.setState(this.#N)}registerPageState(e){for(let n of Lr(e))this.#t.register(n)}registerStateHook(e){this.registerPageState(e)}#Ne(){return this.routeMap.length===0?[]:ps(()=>this.routeMap,()=>this.navigate)}#Oe(){let e=this.getPageMap;return e===null?[]:[{name:Xi,description:"Read the current page's structure (fields, buttons, route). Call after acting to observe the result within the same turn.",parameters:{type:"object",properties:{},required:[],[Le]:"Read the page"},handler:()=>e()}]}#Me(){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 cs(n,r=>this.resolvePageTarget(r))}#ce(){return[...this.#Ne(),...this.#Oe(),...this.#Me(),...this.#Le()]}#Le(){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.#Pe(e)}]:[]}async#Pe(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.#x=new AbortController;let i=this.#x.signal;this.#w();let s=this.askUserRenderer!==null?await this.askUserRenderer(r,{signal:i}):await aa(this.#T(),r,{signal:i,strings:this.#e});return this.#x=null,this.#g(),this.#i.scrollTop=this.#i.scrollHeight,s}#ue(e){let n=this.#ce().find(r=>r.name===e);return n!==void 0?n:this.#t.has(e)?this.#t.get(e):null}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===dn.INLINE||e===dn.MINIMAL||e===dn.COMPACT?e:dn.FULL}set toolDisplay(e){this.setAttribute("data-tool-display",e)}connectedCallback(){if(this.#O=this.id!==""?this.id:this.endpoint,this.#te(this.#fe()),requestAnimationFrame(()=>this.#ee()),this.#e=hs({...this.#De(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let e=this.#ne(ed);e!==null&&this.setAttribute("theme",e)}this.#lt(),this.#f.setStrings(this.#e),this.#h.setStrings(this.#e),this.#ne(Ju)==="1"&&this.setAttribute("collapsed",""),this.#xe(),this.#Xe(),this.#We(),this.#O!==""&&this.conversationStore instanceof ft&&(this.conversationStore=new ft(this.#O)),this.#qe(),this.#Ue(),this.#Ge(),this.#p=this.conversationStore.threadId(),this.#ge(),this.#z=!0}disconnectedCallback(){this.#z=!1,this.#M(),this.#m?.dispose(),this.#q?.dispose()}#de(e){let n=this.getAttribute(e);return n!==null&&n!=="false"}#De(){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{}}#Ue(){let e=this.getAttribute("data-attachments-url"),n=this.uploadHandler??this.#He(e);if(n===null)return;let r=this.getAttribute("data-attachment-accept")??"",o=new li({upload:n,maxBytes:this.#$e(),accept:r,strings:this.#e,onChange:()=>this.#ut(o)});this.#m=o,this.#H.appendChild(this.#m.element),this.#b.accept=r,this.#v.hidden=!1,this.#Ve()}#He(e){return e===null?null:(n,r,o)=>Oa(n,{url:e,headers:this.headers,onProgress:r,signal:o})}#Ge(){let e=this.getAttribute("data-transcribe-url"),n=this.transcribeHandler??this.#ze(e);n!==null&&(this.#q=new xi({transcribe:n,onText:r=>this.#Fe(r),strings:this.#e}),this.#G.appendChild(this.#q.element))}#ze(e){return e===null?null:n=>Na(n,{url:e,headers:this.headers})}#Fe(e){let n=this.#l.value.trim();this.#l.value=n===""?e:`${n} ${e}`,this.#Ee(),this.#l.focus()}#$e(){let e=this.getAttribute("data-attachment-max-bytes");if(e===null)return Ki;let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=0?n:Ki}#Be(){let e=this.#b.files;if(e!==null)for(let n of Array.from(e))this.#m?.add(n);this.#b.value=""}#Ve(){this.#o.addEventListener("dragover",e=>{e.preventDefault(),this.#o.classList.add("chat--dragover")}),this.#o.addEventListener("dragleave",()=>{this.#o.classList.remove("chat--dragover")}),this.#o.addEventListener("drop",e=>{e.preventDefault(),this.#o.classList.remove("chat--dragover");let n=e.dataTransfer?.files;if(n!==void 0)for(let r of Array.from(n))this.#m?.add(r)})}#je(){return this.#L.length===0?[]:[{description:"Files the user attached to this message",value:`${this.#L.map(n=>`- ${n.name} (id: ${n.id}, ${n.mime||"unknown type"}, ${n.size} bytes)`).join(`
1867
1867
  `)}
1868
- Use the read_attachment tool with an id to read a file's contents.`}]}#je(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new mr(e,()=>this.headers,this.conversationStore))}async#qe(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=ds(await n.json())}catch{}}setSkills(e){this.#ae=e,this.#J()}#We(){this.#u.enableChips(this.#ue("data-prompt-chips")),this.#u.enableSlash(this.#ue("data-slash-commands")),this.#se=this.#Xe(),this.#J(),this.#Ye()}#Xe(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Qi(JSON.parse(e))}catch{return[]}}async#Ye(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#ie=Qi(await n.json()),this.#J()}catch{}}#J(){let e=new Map;for(let n of[...this.#ie,...this.#se,...this.#ae])e.set(n.name,n);this.#u.setSkills([...e.values()])}#Ke(e){if(e.prompt===void 0){this.#y.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=sl(e.prompt,this.skillContext());if(r.length>0){this.#y.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#y.hidden=!1,this.#l.value=n,this.#l.focus(),this.#Ze(n);return}if(this.#y.hidden=!0,this.#l.value=n,e.sendImmediately===!1){this.#l.focus();return}this.#re()}#Ze(e){let n=e.indexOf("{");this.#l.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#$(Ju),e?"1":"0"),this.#ye(),this.dispatchEvent(new CustomEvent(Vi,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#$(ed),e),this.#fe()}#Je(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#de(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height");this.#ee({width:e.width+1,height:e.height+1});let o=this.getBoundingClientRect();return this.#pe("--ag-ui-width",n),this.#pe("--ag-ui-height",r),{x:Math.abs(o.left-e.left)<.5?"left":"right",y:Math.abs(o.top-e.top)<.5?"top":"bottom"}}#Q(){if(!this.#z)return;let e=this.#de();this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`)}#pe(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#ee(e){e.width!==void 0&&this.style.setProperty("--ag-ui-width",`${e.width}px`),e.height!==void 0&&this.style.setProperty("--ag-ui-height",`${e.height}px`)}#Qe(e){let n={...this.#he(),...e};sessionStorage.setItem(this.#$(Qu),JSON.stringify(n))}#he(){let e=this.#te(Qu);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#$(e){return this.#O===""?e:`${e}:${this.#O}`}#te(e){let n=sessionStorage.getItem(this.#$(e));return n!==null||this.#O===""?n:sessionStorage.getItem(e)}#fe(){let e=this.getAttribute("theme")==="dark";this.#S.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#M(),this.conversationStore.clear(this.#p),this.#ne(),this.#p=this.conversationStore.threadId(),this.#D(!1)}#ne(){this.#C=null,this.#E=null,this.#A=null,this.#R=null,this.#w(),this.#s.clear(),this.#r.clear(),this.#K=[],this.#L=[],this.#m?.clear(),this.#i.replaceChildren(this.#I),this.#g()}async#et(e){e!==this.#p&&(this.#M(),this.#ne(),this.conversationStore.setActiveThread(e),this.#p=e,this.#D(!1),await this.#me())}#tt(e){let n=e===this.#p;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#ne(),this.#p=this.conversationStore.threadId(),this.#D(!1)),this.#B()}async#B(){this.#f.setThreads(await this.conversationStore.listThreads(),this.#p)}async#me(){this.#Y+=1;let e=this.#Y,n=await this.conversationStore.loadMessages(this.#p);if(e!==this.#Y)return;if(n!==null){this.#K=n;for(let o of n)this.#ot(o)}let r=this.conversationStore.loadCheckpoint(this.#p);if(r!==null){await this.#st(r);return}this.#rt(n)}#ge(){return this.#W=window.location.href,this.getContext()}#nt(){return this.#W!==null&&this.#W!==window.location.href}#rt(e){let n=e?.at(-1);n===void 0||n.role!==Ve.USER||this.#j("\u26A0",this.#e.runInterrupted,"interrupted")}#ot(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ve.USER){let r=ka(e);if(n!==""||r.length>0){let o=this.appendMessage(Ve.USER,n);r.length>0&&o.appendChild(gs(r))}return}if(e.role===Ve.ASSISTANT){n!==""&&this.appendMessage(Ve.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r){let i={id:o.id,name:o.function.name,args:this.#it(o.function.arguments)};this.#ke(i)||this.#oe(i)}return}if(e.role==="tool"){let r=this.#s.get(e.toolCallId);r!==void 0&&r.settle(pe.DONE,e.content)}}#it(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#ve(e){this.getAttribute("data-text-animation")==="word"&&ju(e)}async#st(e){this.conversationStore.saveCheckpoint(this.#p,null);let n=this.#Ee();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===Ve.ASSISTANT?(r.innerHTML=gi(n,{allowImages:this.allowImages}),ms(r,this.#e),this.#T().appendChild(r)):(this.#A=null,r.textContent=n,this.#i.appendChild(r)),this.#g(),this.#i.scrollTop=this.#i.scrollHeight,r}#T(){if(this.#A===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#A=e,this.#i.appendChild(e),this.#g()}return this.#A}#at(){let e=document.createElement("style");e.textContent=Wu,this.#o.className="chat",this.#o.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#d;r.className="header-title",r.setAttribute("part","title"),r.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&n.append(this.#be("icon","icon",null));let o=document.createElement("slot");o.name="header-actions";let i=document.createElement("div");i.className="header-controls",i.setAttribute("part","header-controls");let s=this.#V("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#B(),this.#f.open()});let a=this.#V("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>{this.#Ce(),this.#h.open()});let l=this.#V("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#V("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#Z()!==null?i.append(s,a,l):i.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#S.type="button",this.#S.className="header-btn header-btn--theme",this.#S.setAttribute("part","header-button theme-toggle"),this.#S.title=this.#e.toggleTheme,this.#S.setAttribute("aria-label",this.#e.toggleTheme),this.#S.addEventListener("click",()=>this.toggleTheme()),this.#fe(),i.append(this.#S)),i.append(c),n.append(r,o,i),this.#i.className="messages",this.#i.setAttribute("part","messages"),this.#i.setAttribute("role","log"),this.#i.setAttribute("aria-live","polite"),this.#i.setAttribute("aria-label",this.#e.conversation),this.#I.className="empty",this.#I.setAttribute("part","empty");let h=document.createElement("slot");h.name="empty",this.#I.append(h),this.#i.append(this.#I);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=2,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",f=>this.#lt(f)),this.#l.addEventListener("input",()=>this.#xe()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.textContent=this.#e.send,this.#c.setAttribute("aria-label",this.#e.send),this.#c.dataset.state="idle",this.#c.addEventListener("click",()=>{if(this.#P){this.#M();return}this.#re()}),this.#y.className="skill-hint",this.#y.setAttribute("part","skill-hint"),this.#y.hidden=!0,this.#v.className="attach-btn",this.#v.type="button",this.#v.setAttribute("part","attach-button"),this.#v.textContent="\u{1F4CE}",this.#v.title=this.#e.attachFiles,this.#v.setAttribute("aria-label",this.#e.attachFiles),this.#v.hidden=!0,this.#v.addEventListener("click",()=>this.#b.click()),this.#b.className="attach-input",this.#b.type="file",this.#b.multiple=!0,this.#b.hidden=!0,this.#b.addEventListener("change",()=>this.#$e()),this.#H.className="attachment-slot",this.#G.className="voice-slot";let y=document.createElement("slot");y.name="footer",m.append(this.#v,this.#G,this.#l,this.#c,this.#b),this.#o.append(n,this.#i,this.#u.palette,this.#u.chips,this.#y,this.#H,m,y,this.#f.element,this.#h.element),this.#_.className="rail",this.#_.type="button",this.#_.setAttribute("part","launcher"),this.#_.setAttribute("aria-label",this.#e.expand),this.#_.append(this.#be("launcher","launcher-icon","\u{1F4AC}")),this.#_.addEventListener("click",()=>this.setCollapsed(!1)),this.#o.append(Bu({axis:()=>this.#Je(),anchor:()=>this.#de(),rect:()=>this.getBoundingClientRect(),apply:f=>this.#ee(f),commit:f=>{this.#Qe(f),this.#Q()},label:this.#e.resizePanel})),this.#a.append(e,this.#o,this.#_)}#V(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}#be(e,n,r){let o=document.createElement("span");o.className="icon-holder",o.setAttribute("part",n);let i=document.createElement("slot");i.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",i.append(a)}else r!==null&&i.append(document.createTextNode(r));return o.append(i),o}#ye(){this.#_.setAttribute("aria-expanded",String(!this.collapsed))}#g(){this.#I.hidden=this.#i.childElementCount>1}#xe(){this.#u.onInput(this.#l.value),this.#y.hidden=!0}#lt(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#P){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#re())}#M(){this.#x?.abort(),this.#C?.cancel()}#D(e){this.#P=e;let n=e?this.#e.stop:this.#e.send;this.#c.textContent=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}async#re(){if(this.#P)return;let e=this.#l.value.trim(),n=this.#m?.readyRefs()??[];e===""&&n.length===0||(this.#l.value="",this.#m?.hasPending()===!0&&this.#j("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#m.pendingCount())),"attachment-pending"),this.#m?.clearReady(),await this.sendMessage(e,n))}async sendMessage(e,n=[]){if(this.#P||e===""&&n.length===0)return;let r=this.appendMessage(Ve.USER,e);n.length>0&&r.appendChild(gs(n)),this.#L=n,this.dispatchEvent(new CustomEvent(Bi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#ut(e,n)}attachFile(e){return this.#m===null?!1:(this.#m.add(e),!0)}#ct(e){this.dispatchEvent(new CustomEvent(qi,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#ut(e,n){this.endpoint!==""&&await this.#Ee().send(e,n)}#Ee(){if(this.#C===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#p,initialMessages:this.#K,initialState:this.#N});this.#C=new Ln({agent:e,handlers:this.#Se(),getTools:()=>this.getTools(),getContext:()=>this.#ge(),executeTool:n=>this.#Te(n),resolveInterrupts:n=>this.#we(n),onPersist:n=>this.conversationStore.saveMessages(this.#p,n),onStateChanged:n=>this.#dt(n),connectionLostMessage:this.#e.connectionLost})}return this.#C}#dt(e){this.#N={...e},this.dispatchEvent(new CustomEvent(ji,{detail:{state:this.#N},bubbles:!0,composed:!0}))}async#pt(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:es(n.parameters)}async#Te(e){if(td(e)!==null)return null;let n=this.#oe(e);this.#s.delete(e.id);let r=this.#ce(e.name);if(r===null)return this.#r.has(e.id)||n.settle(pe.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Xi&&!Nr(r.parameters)&&this.#nt()){let i=this.#e.pageMoved;return n.settle(pe.ERROR,i),this.#U(),{content:`Error: ${i}`,error:i}}if(await this.#pt(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Wi];typeof s=="string"&&(i.message=s),this.#x=new AbortController;let a=ia(this.#T(),i,{signal:this.#x.signal,strings:this.#e});this.#g(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#x=null,n.recordDecision(l?"approved":"declined"),!l){let c=this.#e.declinedAction;return n.settle(pe.DECLINED,c),this.#U(),{content:c}}}let o=Nr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#p,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(pe.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(pe.DONE,s),this.#U(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#p,null);let s=i instanceof Error?i.message:String(i);return n.settle(pe.ERROR,s),this.#U(),{content:`Error: ${s}`,error:s}}}async#we(e){let n={};this.#x=new AbortController,this.#w();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#s.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#x.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await fs(this.#T(),o,{signal:a,strings:this.#e});this.#g(),this.#i.scrollTop=this.#i.scrollHeight,i?.recordDecision(l?"approved":"declined"),l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(pe.DECLINED,this.#e.declinedAction))}return this.#x=null,n}#Se(){return{onRunStart:()=>{this.#D(!0),this.#T(),this.#U()},onReasoningStart:()=>{this.#w(),this.#_e()},onReasoningDelta:e=>{this.#_e().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#w(),this.#R?.collapse(),this.#Ae(e),this.#X+=1},onTextEnd:e=>{let n=this.#Ae(e);this.#X<=1&&this.#ve(n),ms(n,this.#e),this.#E=null},onToolCall:e=>{this.#w(),!this.#ke(e)&&this.#oe(e)},onActivity:(e,n)=>{if(e!==Zi)return;let r=$v(n);r!==null&&this.#j("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#s.get(e);r!==void 0&&(r.settle(pe.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#w(),this.#E=null},onError:e=>{this.#w(),this.#ve(this.appendMessage(Ve.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#E=null},onCancelled:()=>{this.#w(),this.#ht(),this.#E=null},onSettled:()=>{this.#w(),this.#D(!1),this.#E=null,this.#L=[];for(let e of this.#s.values())e.settled||e.settle(pe.DONE,this.#e.noResult);this.#A!==null&&this.#A.childElementCount===0&&(this.#A.remove(),this.#g()),this.#A=null,this.#R=null}}}#ht(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#T().appendChild(e),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}#U(){if(this.#F!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#F=e,this.#T().appendChild(e),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}#w(){this.#F?.remove(),this.#F=null}#_e(){if(this.#R===null){this.#R=new bi(this.#e);let e=this.#T();e.insertBefore(this.#R.element,e.firstChild),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}return this.#R}#Ae(e){return this.#E===null&&(this.#E=this.appendMessage(Ve.ASSISTANT,""),this.#X=0),this.#E.innerHTML=gi(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#E}#ke(e){let n=td(e);return n===null?!1:(this.#j("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#j(e,n,r){this.#T().appendChild(qu(e,n,r)),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}#oe(e){let n=this.#s.get(e.id);if(n!==void 0)return n;let r=this.#ce(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??sa(e.name),i=new hr(e.name,e.args,o,this.#e);return this.#s.set(e.id,i),this.#T().appendChild(i.element),this.#g(),this.#i.scrollTop=this.#i.scrollHeight,i}};function td(t){if(t.name!==Ji)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function $v(t){let e=t?.removed;return typeof e=="number"?e:null}function Bv(){customElements.get(Rr)===void 0&&customElements.define(Rr,vr)}async function Vv(t,e,n={}){at(t),await rs(t,{flashMs:n.flashMs??0}),await ts(t,e,n)}async function jv(t,e={}){at(t),await ns(t,e)}async function qv(t,e={}){at(t),await is(t,e)}async function Wv(t,e,n={}){at(t),await ss(t,e,n)}async function Xv(t,e,n={}){at(t),await as(t,e,n)}function Yv(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Bn(t,!!e):Rt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Kv="0.20.0";export{qi as ATTACHMENT_EVENT,vr as AgUiChat,Ln as AgUiClient,Zi as COMPACTION_ACTIVITY_TYPE,ir as CheckpointMenu,$n as ClientToolRegistry,Ei as ConnectionLostError,ae as DEFAULT_UI_STRINGS,Rr as ELEMENT_TAG,Ji as LOAD_CAPABILITY_TOOL,Yi as MAX_TOOL_ROUNDS,Ve as MESSAGE_ROLE,ls as PAGE_ACTIONS,mr as RemoteConversationStore,gr as RunIndex,ji as STATE_EVENT,Bi as SUBMIT_EVENT,ft as SessionStorageStore,Vi as TOGGLE_EVENT,pe as TOOL_CALL_STATUS,dn as TOOL_DISPLAY,hr as ToolCallCard,Kv as VERSION,Wi as X_CONFIRM_KEY,zn as X_DESTRUCTIVE_KEY,Fn as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,jv as clickElement,Ra as createHttpAgent,cs as createPageActionTools,us as createPageMapContext,Lr as createPageStateTools,ps as createRouteTools,Fd as createStateHookTools,Bv as defineAgUiChat,Vv as fillField,rs as focusWithFlash,ns as highlightThenClick,es as isDestructive,Nr as isNavigates,hs as mergeUiStrings,ka as messageAttachments,ds as parseToolCatalog,cl as prefersReducedMotion,qv as pressButton,is as pressThenClick,sa as prettifyToolName,gi as renderMarkdown,fs as requestApproval,ia as requestConfirmation,aa as requestQuestion,at as scrollIntoCenterView,Wv as selectControl,ss as selectOption,Yv as setControlValue,Bn as setNativeChecked,Rt as setNativeValue,Xv as toggleCheckbox,as as toggleControl,Na as transcribeAudio,ts as typeInto,Oa as uploadAttachment};
1868
+ Use the read_attachment tool with an id to read a file's contents.`}]}#qe(){let e=this.getAttribute("data-threads-url");e!==null&&(this.conversationStore=new mr(e,()=>this.headers,this.conversationStore))}async#We(){let e=this.getAttribute("data-tools-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#n=ds(await n.json())}catch{}}setSkills(e){this.#le=e,this.#J()}#Xe(){this.#u.enableChips(this.#de("data-prompt-chips")),this.#u.enableSlash(this.#de("data-slash-commands")),this.#ae=this.#Ye(),this.#J(),this.#Ke()}#Ye(){let e=this.getAttribute("data-skills");if(e===null)return[];try{return Qi(JSON.parse(e))}catch{return[]}}async#Ke(){let e=this.getAttribute("data-skills-url");if(e!==null)try{let n=await fetch(e,{headers:this.headers});this.#se=Qi(await n.json()),this.#J()}catch{}}#J(){let e=new Map;for(let n of[...this.#se,...this.#ae,...this.#le])e.set(n.name,n);this.#u.setSkills([...e.values()])}#Ze(e){if(e.prompt===void 0){this.#y.hidden=!0,this.sendMessage(`/${e.name}`);return}let{text:n,missing:r}=sl(e.prompt,this.skillContext());if(r.length>0){this.#y.textContent=this.#e.skillNeeds.replace("{title}",e.title).replace("{fields}",r.join(", ")),this.#y.hidden=!1,this.#l.value=n,this.#l.focus(),this.#Je(n);return}if(this.#y.hidden=!0,this.#l.value=n,e.sendImmediately===!1){this.#l.focus();return}this.#oe()}#Je(e){let n=e.indexOf("{");this.#l.setSelectionRange(n,e.indexOf("}",n)+1)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}setCollapsed(e){e?this.setAttribute("collapsed",""):this.removeAttribute("collapsed"),sessionStorage.setItem(this.#$(Ju),e?"1":"0"),this.#xe(),this.dispatchEvent(new CustomEvent(Vi,{detail:{collapsed:e},bubbles:!0,composed:!0}))}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")==="dark"?"light":"dark";this.setAttribute("theme",e),sessionStorage.setItem(this.#$(ed),e),this.#me()}#Q(){switch(this.getAttribute("placement")){case"full":case"page":return"none";case"sidebar":case"side":return"width";default:return"both"}}#pe(){let e=this.getBoundingClientRect(),n=this.style.getPropertyValue("--ag-ui-width"),r=this.style.getPropertyValue("--ag-ui-height");this.#te({width:e.width+1,height:e.height+1});let o=this.getBoundingClientRect();return this.#he("--ag-ui-width",n),this.#he("--ag-ui-height",r),{x:Math.abs(o.left-e.left)<.5?"left":"right",y:Math.abs(o.top-e.top)<.5?"top":"bottom"}}#ee(){if(!this.#z)return;let e=this.#pe();this.setAttribute("data-resize-anchor",`${e.y}-${e.x}`)}#he(e,n){if(n===""){this.style.removeProperty(e);return}this.style.setProperty(e,n)}#te(e){let n=this.#Q();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`))}#Qe(){let e=this.#Q();e!=="both"&&this.style.removeProperty("--ag-ui-height"),e==="none"&&this.style.removeProperty("--ag-ui-width")}#et(e){let n={...this.#fe(),...e};sessionStorage.setItem(this.#$(Qu),JSON.stringify(n))}#fe(){let e=this.#ne(Qu);if(e===null)return{};try{let n=JSON.parse(e);return typeof n=="object"&&n!==null?n:{}}catch{return{}}}#$(e){return this.#O===""?e:`${e}:${this.#O}`}#ne(e){let n=sessionStorage.getItem(this.#$(e));return n!==null||this.#O===""?n:sessionStorage.getItem(e)}#me(){let e=this.getAttribute("theme")==="dark";this.#S.textContent=e?"\u2600\uFE0F":"\u{1F319}"}newChat(){this.#M(),this.conversationStore.clear(this.#p),this.#re(),this.#p=this.conversationStore.threadId(),this.#D(!1)}#re(){this.#C=null,this.#E=null,this.#A=null,this.#R=null,this.#w(),this.#s.clear(),this.#r.clear(),this.#K=[],this.#L=[],this.#m?.clear(),this.#i.replaceChildren(this.#I),this.#g()}async#tt(e){e!==this.#p&&(this.#M(),this.#re(),this.conversationStore.setActiveThread(e),this.#p=e,this.#D(!1),await this.#ge())}#nt(e){let n=e===this.#p;n&&this.#M(),this.conversationStore.clear(e),n&&(this.#re(),this.#p=this.conversationStore.threadId(),this.#D(!1)),this.#B()}async#B(){this.#f.setThreads(await this.conversationStore.listThreads(),this.#p)}async#ge(){this.#Y+=1;let e=this.#Y,n=await this.conversationStore.loadMessages(this.#p);if(e!==this.#Y)return;if(n!==null){this.#K=n;for(let o of n)this.#it(o)}let r=this.conversationStore.loadCheckpoint(this.#p);if(r!==null){await this.#at(r);return}this.#ot(n)}#ve(){return this.#W=window.location.href,this.getContext()}#rt(){return this.#W!==null&&this.#W!==window.location.href}#ot(e){let n=e?.at(-1);n===void 0||n.role!==Ve.USER||this.#j("\u26A0",this.#e.runInterrupted,"interrupted")}#it(e){let n=typeof e.content=="string"?e.content:"";if(e.role===Ve.USER){let r=ka(e);if(n!==""||r.length>0){let o=this.appendMessage(Ve.USER,n);r.length>0&&o.appendChild(gs(r))}return}if(e.role===Ve.ASSISTANT){n!==""&&this.appendMessage(Ve.ASSISTANT,n).classList.add("message--restored");let r=e.toolCalls;if(r!==void 0)for(let o of r){let i={id:o.id,name:o.function.name,args:this.#st(o.function.arguments)};this.#Ie(i)||this.#ie(i)}return}if(e.role==="tool"){let r=this.#s.get(e.toolCallId);r!==void 0&&r.settle(pe.DONE,e.content)}}#st(e){try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null)return n}catch{}return{}}#be(e){this.getAttribute("data-text-animation")==="word"&&ju(e)}async#at(e){this.conversationStore.saveCheckpoint(this.#p,null);let n=this.#Te();n.addToolResult(e.toolCallId,JSON.stringify(this.navigationResult(e))),await n.resume()}appendMessage(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===Ve.ASSISTANT?(r.innerHTML=gi(n,{allowImages:this.allowImages}),ms(r,this.#e),this.#T().appendChild(r)):(this.#A=null,r.textContent=n,this.#i.appendChild(r)),this.#g(),this.#i.scrollTop=this.#i.scrollHeight,r}#T(){if(this.#A===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#A=e,this.#i.appendChild(e),this.#g()}return this.#A}#lt(){let e=document.createElement("style");e.textContent=Wu,this.#o.className="chat",this.#o.setAttribute("part","panel");let n=document.createElement("div");n.className="header",n.setAttribute("part","header");let r=this.#d;r.className="header-title",r.setAttribute("part","title"),r.textContent=this.getAttribute("title-text")??this.#e.title,(this.querySelector('[slot="icon"]')!==null||this.getAttribute("data-icon-url")!==null)&&n.append(this.#ye("icon","icon",null));let o=document.createElement("slot");o.name="header-actions";let i=document.createElement("div");i.className="header-controls",i.setAttribute("part","header-controls");let s=this.#V("history",this.#e.chatHistory,"\u2630");s.addEventListener("click",()=>{this.#B(),this.#f.open()});let a=this.#V("checkpoints",this.#e.checkpoints,"\u2B6F");a.addEventListener("click",()=>{this.#Re(),this.#h.open()});let l=this.#V("new",this.#e.newChat,"\u271A");l.addEventListener("click",()=>this.newChat());let c=this.#V("collapse",this.#e.collapse,"\u2014");c.addEventListener("click",()=>this.toggleCollapsed()),this.#Z()!==null?i.append(s,a,l):i.append(s,l),this.getAttribute("data-theme-toggle")!==null&&(this.#S.type="button",this.#S.className="header-btn header-btn--theme",this.#S.setAttribute("part","header-button theme-toggle"),this.#S.title=this.#e.toggleTheme,this.#S.setAttribute("aria-label",this.#e.toggleTheme),this.#S.addEventListener("click",()=>this.toggleTheme()),this.#me(),i.append(this.#S)),i.append(c),n.append(r,o,i),this.#i.className="messages",this.#i.setAttribute("part","messages"),this.#i.setAttribute("role","log"),this.#i.setAttribute("aria-live","polite"),this.#i.setAttribute("aria-label",this.#e.conversation),this.#I.className="empty",this.#I.setAttribute("part","empty");let h=document.createElement("slot");h.name="empty",this.#I.append(h),this.#i.append(this.#I);let m=document.createElement("div");m.className="input-row",m.setAttribute("part","composer"),this.#l.className="input",this.#l.setAttribute("part","input"),this.#l.setAttribute("aria-label",this.#e.message),this.#l.rows=2,this.#l.placeholder=this.#e.inputPlaceholder,this.#l.addEventListener("keydown",f=>this.#ct(f)),this.#l.addEventListener("input",()=>this.#Ee()),this.#c.className="send",this.#c.type="button",this.#c.setAttribute("part","send"),this.#c.textContent=this.#e.send,this.#c.setAttribute("aria-label",this.#e.send),this.#c.dataset.state="idle",this.#c.addEventListener("click",()=>{if(this.#P){this.#M();return}this.#oe()}),this.#y.className="skill-hint",this.#y.setAttribute("part","skill-hint"),this.#y.hidden=!0,this.#v.className="attach-btn",this.#v.type="button",this.#v.setAttribute("part","attach-button"),this.#v.textContent="\u{1F4CE}",this.#v.title=this.#e.attachFiles,this.#v.setAttribute("aria-label",this.#e.attachFiles),this.#v.hidden=!0,this.#v.addEventListener("click",()=>this.#b.click()),this.#b.className="attach-input",this.#b.type="file",this.#b.multiple=!0,this.#b.hidden=!0,this.#b.addEventListener("change",()=>this.#Be()),this.#H.className="attachment-slot",this.#G.className="voice-slot";let y=document.createElement("slot");y.name="footer",m.append(this.#v,this.#G,this.#l,this.#c,this.#b),this.#o.append(n,this.#i,this.#u.palette,this.#u.chips,this.#y,this.#H,m,y,this.#f.element,this.#h.element),this.#_.className="rail",this.#_.type="button",this.#_.setAttribute("part","launcher"),this.#_.setAttribute("aria-label",this.#e.expand),this.#_.append(this.#ye("launcher","launcher-icon","\u{1F4AC}")),this.#_.addEventListener("click",()=>this.setCollapsed(!1)),this.#o.append(Bu({axis:()=>this.#Q(),anchor:()=>this.#pe(),rect:()=>this.getBoundingClientRect(),apply:f=>this.#te(f),commit:f=>{this.#et(f),this.#ee()},label:this.#e.resizePanel})),this.#a.append(e,this.#o,this.#_)}#V(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}#ye(e,n,r){let o=document.createElement("span");o.className="icon-holder",o.setAttribute("part",n);let i=document.createElement("slot");i.name=e;let s=this.getAttribute("data-icon-url");if(s!==null){let a=document.createElement("img");a.className="icon-img",a.src=s,a.alt="",i.append(a)}else r!==null&&i.append(document.createTextNode(r));return o.append(i),o}#xe(){this.#_.setAttribute("aria-expanded",String(!this.collapsed))}#g(){this.#I.hidden=this.#i.childElementCount>1}#Ee(){this.#u.onInput(this.#l.value),this.#y.hidden=!0}#ct(e){if(this.#u.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#P){e.preventDefault(),this.#M();return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this.#oe())}#M(){this.#x?.abort(),this.#C?.cancel()}#D(e){this.#P=e;let n=e?this.#e.stop:this.#e.send;this.#c.textContent=n,this.#c.setAttribute("aria-label",n),this.#c.dataset.state=e?"running":"idle"}async#oe(){if(this.#P)return;let e=this.#l.value.trim(),n=this.#m?.readyRefs()??[];e===""&&n.length===0||(this.#l.value="",this.#m?.hasPending()===!0&&this.#j("\u{1F4CE}",this.#e.attachmentsStillUploading.replace("{n}",String(this.#m.pendingCount())),"attachment-pending"),this.#m?.clearReady(),await this.sendMessage(e,n))}async sendMessage(e,n=[]){if(this.#P||e===""&&n.length===0)return;let r=this.appendMessage(Ve.USER,e);n.length>0&&r.appendChild(gs(n)),this.#L=n,this.dispatchEvent(new CustomEvent(Bi,{detail:{content:e,attachments:n},bubbles:!0,composed:!0})),await this.#dt(e,n)}attachFile(e){return this.#m===null?!1:(this.#m.add(e),!0)}#ut(e){this.dispatchEvent(new CustomEvent(qi,{detail:{attachments:e.readyRefs(),pending:e.pendingCount()},bubbles:!0,composed:!0}))}async#dt(e,n){this.endpoint!==""&&await this.#Te().send(e,n)}#Te(){if(this.#C===null){let e=this.agentFactory({endpoint:this.endpoint,headers:this.headers,getHeaders:()=>this.headers,threadId:this.#p,initialMessages:this.#K,initialState:this.#N});this.#C=new Ln({agent:e,handlers:this.#_e(),getTools:()=>this.getTools(),getContext:()=>this.#ve(),executeTool:n=>this.#we(n),resolveInterrupts:n=>this.#Se(n),onPersist:n=>this.conversationStore.saveMessages(this.#p,n),onStateChanged:n=>this.#pt(n),connectionLostMessage:this.#e.connectionLost})}return this.#C}#pt(e){this.#N={...e},this.dispatchEvent(new CustomEvent(ji,{detail:{state:this.#N},bubbles:!0,composed:!0}))}async#ht(e,n){return this.autoConfirm?!1:this.confirmPredicate!==null?await this.confirmPredicate(e.name,e.args)===!0:es(n.parameters)}async#we(e){if(td(e)!==null)return null;let n=this.#ie(e);this.#s.delete(e.id);let r=this.#ue(e.name);if(r===null)return this.#r.has(e.id)||n.settle(pe.DONE,this.#e.noResult),null;if(this.getPageMap!==null&&e.name!==Xi&&!Nr(r.parameters)&&this.#rt()){let i=this.#e.pageMoved;return n.settle(pe.ERROR,i),this.#U(),{content:`Error: ${i}`,error:i}}if(await this.#ht(e,r)){let i={toolName:e.name,args:e.args},s=r.parameters[Wi];typeof s=="string"&&(i.message=s),this.#x=new AbortController;let a=ia(this.#T(),i,{signal:this.#x.signal,strings:this.#e});this.#g(),this.#i.scrollTop=this.#i.scrollHeight;let l=await a;if(this.#x=null,n.recordDecision(l?"approved":"declined"),!l){let c=this.#e.declinedAction;return n.settle(pe.DECLINED,c),this.#U(),{content:c}}}let o=Nr(r.parameters)&&this.navigate===null;o&&this.conversationStore.saveCheckpoint(this.#p,{toolCallId:e.id});try{let i=await r.handler(e.args);if(o)return n.settle(pe.DONE,this.#e.navigating),{content:"",halt:!0};let s=JSON.stringify(i??null);return n.settle(pe.DONE,s),this.#U(),{content:s}}catch(i){o&&this.conversationStore.saveCheckpoint(this.#p,null);let s=i instanceof Error?i.message:String(i);return n.settle(pe.ERROR,s),this.#U(),{content:`Error: ${s}`,error:s}}}async#Se(e){let n={};this.#x=new AbortController,this.#w();for(let r of e){let o={};r.message!==void 0&&(o.message=r.message);let i=r.toolCallId!==void 0?this.#s.get(r.toolCallId):void 0,s=i?.element.getAttribute("data-tool-name");s!=null&&(o.toolName=s);let a=this.#x.signal,l=this.approvalRenderer!==null?await this.approvalRenderer(o,{signal:a}):await fs(this.#T(),o,{signal:a,strings:this.#e});this.#g(),this.#i.scrollTop=this.#i.scrollHeight,i?.recordDecision(l?"approved":"declined"),l?n[r.id]={status:"resolved",payload:{approved:!0}}:(n[r.id]={status:"cancelled"},i?.settle(pe.DECLINED,this.#e.declinedAction))}return this.#x=null,n}#_e(){return{onRunStart:()=>{this.#D(!0),this.#T(),this.#U()},onReasoningStart:()=>{this.#w(),this.#Ae()},onReasoningDelta:e=>{this.#Ae().stream(e)},onReasoningEnd:()=>{},onTextDelta:e=>{this.#w(),this.#R?.collapse(),this.#ke(e),this.#X+=1},onTextEnd:e=>{let n=this.#ke(e);this.#X<=1&&this.#be(n),ms(n,this.#e),this.#E=null},onToolCall:e=>{this.#w(),!this.#Ie(e)&&this.#ie(e)},onActivity:(e,n)=>{if(e!==Zi)return;let r=$v(n);r!==null&&this.#j("\u{1F5DC}",this.#e.historyCompacted.replace("{count}",String(r)),"compaction")},onToolResult:(e,n)=>{let r=this.#s.get(e);r!==void 0&&(r.settle(pe.DONE,n),this.#r.add(e))},onRunEnd:()=>{this.#w(),this.#E=null},onError:e=>{this.#w(),this.#be(this.appendMessage(Ve.ASSISTANT,`\u26A0\uFE0F ${e}`)),this.#E=null},onCancelled:()=>{this.#w(),this.#ft(),this.#E=null},onSettled:()=>{this.#w(),this.#D(!1),this.#E=null,this.#L=[];for(let e of this.#s.values())e.settled||e.settle(pe.DONE,this.#e.noResult);this.#A!==null&&this.#A.childElementCount===0&&(this.#A.remove(),this.#g()),this.#A=null,this.#R=null}}}#ft(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.stopped,this.#T().appendChild(e),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}#U(){if(this.#F!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#F=e,this.#T().appendChild(e),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}#w(){this.#F?.remove(),this.#F=null}#Ae(){if(this.#R===null){this.#R=new bi(this.#e);let e=this.#T();e.insertBefore(this.#R.element,e.firstChild),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}return this.#R}#ke(e){return this.#E===null&&(this.#E=this.appendMessage(Ve.ASSISTANT,""),this.#X=0),this.#E.innerHTML=gi(e,{allowImages:this.allowImages}),this.#i.scrollTop=this.#i.scrollHeight,this.#E}#Ie(e){let n=td(e);return n===null?!1:(this.#j("\u2728",this.#e.usingSkill.replace("{name}",n),"skill"),!0)}#j(e,n,r){this.#T().appendChild(qu(e,n,r)),this.#g(),this.#i.scrollTop=this.#i.scrollHeight}#ie(e){let n=this.#s.get(e.id);if(n!==void 0)return n;let r=this.#ue(e.name)?.parameters[Le],o=typeof r=="string"?r:this.toolSummaries[e.name]??this.#n[e.name]??sa(e.name),i=new hr(e.name,e.args,o,this.#e);return this.#s.set(e.id,i),this.#T().appendChild(i.element),this.#g(),this.#i.scrollTop=this.#i.scrollHeight,i}};function td(t){if(t.name!==Ji)return null;let e=t.args?.id;return typeof e=="string"&&e!==""?e:null}function $v(t){let e=t?.removed;return typeof e=="number"?e:null}function Bv(){customElements.get(Rr)===void 0&&customElements.define(Rr,vr)}async function Vv(t,e,n={}){at(t),await rs(t,{flashMs:n.flashMs??0}),await ts(t,e,n)}async function jv(t,e={}){at(t),await ns(t,e)}async function qv(t,e={}){at(t),await is(t,e)}async function Wv(t,e,n={}){at(t),await ss(t,e,n)}async function Xv(t,e,n={}){at(t),await as(t,e,n)}function Yv(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Bn(t,!!e):Rt(t,String(e)),t.dispatchEvent(new Event("input",{bubbles:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}var Kv="0.20.1";export{qi as ATTACHMENT_EVENT,vr as AgUiChat,Ln as AgUiClient,Zi as COMPACTION_ACTIVITY_TYPE,ir as CheckpointMenu,$n as ClientToolRegistry,Ei as ConnectionLostError,ae as DEFAULT_UI_STRINGS,Rr as ELEMENT_TAG,Ji as LOAD_CAPABILITY_TOOL,Yi as MAX_TOOL_ROUNDS,Ve as MESSAGE_ROLE,ls as PAGE_ACTIONS,mr as RemoteConversationStore,gr as RunIndex,ji as STATE_EVENT,Bi as SUBMIT_EVENT,ft as SessionStorageStore,Vi as TOGGLE_EVENT,pe as TOOL_CALL_STATUS,dn as TOOL_DISPLAY,hr as ToolCallCard,Kv as VERSION,Wi as X_CONFIRM_KEY,zn as X_DESTRUCTIVE_KEY,Fn as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,jv as clickElement,Ra as createHttpAgent,cs as createPageActionTools,us as createPageMapContext,Lr as createPageStateTools,ps as createRouteTools,Fd as createStateHookTools,Bv as defineAgUiChat,Vv as fillField,rs as focusWithFlash,ns as highlightThenClick,es as isDestructive,Nr as isNavigates,hs as mergeUiStrings,ka as messageAttachments,ds as parseToolCatalog,cl as prefersReducedMotion,qv as pressButton,is as pressThenClick,sa as prettifyToolName,gi as renderMarkdown,fs as requestApproval,ia as requestConfirmation,aa as requestQuestion,at as scrollIntoCenterView,Wv as selectControl,ss as selectOption,Yv as setControlValue,Bn as setNativeChecked,Rt as setNativeValue,Xv as toggleCheckbox,as as toggleControl,Na as transcribeAudio,ts as typeInto,Oa as uploadAttachment};
1869
1869
  /*! Bundled license information:
1870
1870
 
1871
1871
  fast-json-patch/module/helpers.mjs: