@artooi/agents-web-components 0.1.0 → 0.1.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,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.1.1] — 2026-11-14
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **Releases are published from CI by npm trusted publishing, with provenance.** 0.1.0 was
|
|
15
|
+
published from a workstation and carries none; this release has no code changes and exists to
|
|
16
|
+
put a signed build on the registry. A host opts in to nothing.
|
|
17
|
+
|
|
10
18
|
## [0.1.0] — 2026-11-14
|
|
11
19
|
|
|
12
20
|
First release of `@artooi/agents-web-components`, the successor of `@artooi/ag-ui-web-component`.
|
|
@@ -64,5 +72,6 @@ move page walks a host over. Each entry below says whether a host opts in.
|
|
|
64
72
|
kept offering the moon under `theme="dark"`. Only the toggle's own click redrew it before. A host
|
|
65
73
|
opts in to nothing.
|
|
66
74
|
|
|
67
|
-
[Unreleased]: https://github.com/Artui/agents-web-components/compare/v0.1.
|
|
75
|
+
[Unreleased]: https://github.com/Artui/agents-web-components/compare/v0.1.1...HEAD
|
|
76
|
+
[0.1.1]: https://github.com/Artui/agents-web-components/compare/v0.1.0...v0.1.1
|
|
68
77
|
[0.1.0]: https://github.com/Artui/agents-web-components/compare/v0.0.0...v0.1.0
|
|
@@ -5684,7 +5684,7 @@ ${this.parser.parse(t)}</blockquote>
|
|
|
5684
5684
|
${t}</tr>
|
|
5685
5685
|
`}tablecell(t){let e=this.parser.parseInline(t.tokens),n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>
|
|
5686
5686
|
`}strong({tokens:t}){return`<strong>${this.parser.parseInline(t)}</strong>`}em({tokens:t}){return`<em>${this.parser.parseInline(t)}</em>`}codespan({text:t}){return`<code>${at(t,!0)}</code>`}br(t){return"<br>"}del({tokens:t}){return`<del>${this.parser.parseInline(t)}</del>`}link({href:t,title:e,text:n,tokens:r,autolink:o}){let i=o?at(n,!0):this.parser.parseInline(r),a=Ax(t);if(a===null)return i;t=at(a,o);let s='<a href="'+t+'"';return e&&(s+=' title="'+at(e)+'"'),s+=">"+i+"</a>",s}image({href:t,title:e,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let o=Ax(t);if(o===null)return at(n);t=o;let i=`<img src="${at(t)}" alt="${at(n)}"`;return e&&(i+=` title="${at(e)}"`),i+=">",i}text(t){return"tokens"in t&&t.tokens?this.parser.parseInline(t.tokens):"escaped"in t&&t.escaped?t.text:at(t.text)}},Eh=class{parser;strong({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}em({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}codespan({text:t}){return t}del({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}html({text:t}){return t}text({text:t}){return t}link({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}image({text:t,tokens:e}){return e?this.parser.parseInline(e,this):t}br(){return""}checkbox({raw:t}){return t}},vt=class ph{options;renderer;textRenderer;constructor(e){this.options=e||Fn,this.options.renderer=this.options.renderer||new hl,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Eh,this.textRenderer.parser=this}static parse(e,n){return new ph(n).parse(e)}static parseInline(e,n){return new ph(n).parseInline(e)}parse(e){this.renderer.parser=this;let n="";for(let r=0;r<e.length;r++){let o=e[r];if(this.options.extensions?.renderers?.[o.type]){let a=o,s=this.options.extensions.renderers[a.type].call({parser:this},a);if(s!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(a.type)){n+=s||"";continue}}let i=o;switch(i.type){case"space":{n+=this.renderer.space(i);break}case"hr":{n+=this.renderer.hr(i);break}case"heading":{n+=this.renderer.heading(i);break}case"code":{n+=this.renderer.code(i);break}case"table":{n+=this.renderer.table(i);break}case"blockquote":{n+=this.renderer.blockquote(i);break}case"list":{n+=this.renderer.list(i);break}case"checkbox":{n+=this.renderer.checkbox(i);break}case"html":{n+=this.renderer.html(i);break}case"def":{n+=this.renderer.def(i);break}case"paragraph":{n+=this.renderer.paragraph(i);break}case"text":{n+=this.renderer.text(i);break}default:{let a='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return n}parseInline(e,n=this.renderer){this.renderer.parser=this;let r="";for(let o=0;o<e.length;o++){let i=e[o];if(this.options.extensions?.renderers?.[i.type]){let s=this.options.extensions.renderers[i.type].call({parser:this},i);if(s!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(i.type)){r+=s||"";continue}}let a=i;switch(a.type){case"escape":{r+=n.text(a);break}case"html":{r+=n.html(a);break}case"link":{r+=n.link(a);break}case"image":{r+=n.image(a);break}case"checkbox":{r+=n.checkbox(a);break}case"strong":{r+=n.strong(a);break}case"em":{r+=n.em(a);break}case"codespan":{r+=n.codespan(a);break}case"br":{r+=n.br(a);break}case"del":{r+=n.del(a);break}case"text":{r+=n.text(a);break}default:{let s='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(s),"";throw new Error(s)}}}return r}},Go=class{options;block;constructor(t){this.options=t||Fn}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(t){return t}postprocess(t){return t}processAllTokens(t){return t}emStrongMask(t){return t}provideLexer(t=this.block){return t?gt.lex:gt.lexInline}provideParser(t=this.block){return t?vt.parse:vt.parseInline}};function rn(t,e){if(Array.isArray(e))for(let n=0;n<e.length;n++)t.push(e[n]);else t.push(e)}var _h=class{defaults=fh();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=vt;Renderer=hl;TextRenderer=Eh;Lexer=gt;Tokenizer=Cr;Hooks=Go;constructor(...t){this.use(...t)}walkTokens(t,e){let n=[];for(let r of t)switch(rn(n,e.call(this,r)),r.type){case"table":{let o=r;for(let i of o.header)rn(n,this.walkTokens(i.tokens,e));for(let i of o.rows)for(let a of i)rn(n,this.walkTokens(a.tokens,e));break}case"list":{let o=r;rn(n,this.walkTokens(o.items,e));break}default:{let o=r;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(i=>{let a=o[i].flat(1/0);rn(n,this.walkTokens(a,e))}):o.tokens&&rn(n,this.walkTokens(o.tokens,e))}}return n}use(...t){let e=this.defaults.extensions||{renderers:Object.create(null),childTokens:Object.create(null)};return t.forEach(n=>{let r={...n};if(r.async=this.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let i=e.renderers[o.name];i?e.renderers[o.name]=function(...a){let s=o.renderer.apply(this,a);return s===!1&&(s=i.apply(this,a)),s}:e.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let i=e[o.level];i?i.unshift(o.tokenizer):e[o.level]=[o.tokenizer],o.start&&(o.level==="block"?e.startBlock?e.startBlock.push(o.start):e.startBlock=[o.start]:o.level==="inline"&&(e.startInline?e.startInline.push(o.start):e.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(e.childTokens[o.name]=o.childTokens)}),r.extensions=e),n.renderer){let o=this.defaults.renderer||new hl(this.defaults);for(let i in n.renderer){if(!(i in o))throw new Error(`renderer '${i}' does not exist`);if(["options","parser"].includes(i))continue;let a=i,s=n.renderer[a],l=o[a];o[a]=(...c)=>{let d=s.apply(o,c);return d===!1&&(d=l.apply(o,c)),d===!1?"":d??""}}r.renderer=o}if(n.tokenizer){let o=this.defaults.tokenizer||new Cr(this.defaults);for(let i in n.tokenizer){if(!(i in o))throw new Error(`tokenizer '${i}' does not exist`);if(["options","rules","lexer"].includes(i))continue;let a=i,s=n.tokenizer[a],l=o[a];o[a]=(...c)=>{let d=s.apply(o,c);return d===!1&&(d=l.apply(o,c)),d}}r.tokenizer=o}if(n.hooks){let o=this.defaults.hooks||new Go;for(let i in n.hooks){if(!(i in o))throw new Error(`hook '${i}' does not exist`);if(["options","block"].includes(i))continue;let a=i,s=n.hooks[a],l=o[a];Go.passThroughHooks.has(i)?o[a]=c=>{if(o.options.async&&Go.passThroughHooksRespectAsync.has(i))return(async()=>{let h=await s.call(o,c);return l.call(o,h)})();let d=s.call(o,c);return l.call(o,d)}:o[a]=(...c)=>{if(o.options.async)return(async()=>{let h=await s.apply(o,c);return h===!1&&(h=await l.apply(o,c)),h})();let d=s.apply(o,c);return d===!1&&(d=l.apply(o,c)),d}}r.hooks=o}if(n.walkTokens){let o=this.defaults.walkTokens,i=n.walkTokens;r.walkTokens=function(a){let s=[];return rn(s,i.call(this,a)),o&&rn(s,o.call(this,a)),s}}this.defaults={...this.defaults,...r}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return gt.lex(t,e??this.defaults)}parser(t,e){return vt.parse(t,e??this.defaults)}parseMarkdown(t){return(e,n)=>{let r={...n},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=t),o.async)return(async()=>{let a=o.hooks?await o.hooks.preprocess(e):e,s=await(o.hooks?await o.hooks.provideLexer(t):t?gt.lex:gt.lexInline)(a,o),l=o.hooks?await o.hooks.processAllTokens(s):s;o.walkTokens&&await Promise.all(this.walkTokens(l,o.walkTokens));let c=await(o.hooks?await o.hooks.provideParser(t):t?vt.parse:vt.parseInline)(l,o);return o.hooks?await o.hooks.postprocess(c):c})().catch(i);try{o.hooks&&(e=o.hooks.preprocess(e));let a=(o.hooks?o.hooks.provideLexer(t):t?gt.lex:gt.lexInline)(e,o);o.hooks&&(a=o.hooks.processAllTokens(a)),o.walkTokens&&this.walkTokens(a,o.walkTokens);let s=(o.hooks?o.hooks.provideParser(t):t?vt.parse:vt.parseInline)(a,o);return o.hooks&&(s=o.hooks.postprocess(s)),s}catch(a){return i(a)}}}onError(t,e){return n=>{if(n.message+=`
|
|
5687
|
-
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+at(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Gn=new _h;function me(t,e){return Gn.parse(t,e)}me.options=me.setOptions=function(t){return Gn.setOptions(t),me.defaults=Gn.defaults,Mx(me.defaults),me};me.getDefaults=fh;me.defaults=Fn;function hC(...t){return Gn.use(...t),me.defaults=Gn.defaults,Mx(me.defaults),me}me.use=hC;me.walkTokens=function(t,e){return Gn.walkTokens(t,e)};me.parseInline=Gn.parseInline;me.Parser=vt;me.parser=vt.parse;me.Renderer=hl;me.TextRenderer=Eh;me.Lexer=gt;me.lexer=gt.lex;me.Tokenizer=Cr;me.Hooks=Go;me.parse=me;var X4=me.options,J4=me.setOptions,Q4=me.walkTokens,eH=me.parseInline;var tH=vt.parse,nH=gt.lex;var pC=new _h({gfm:!0,breaks:!0}),Bx=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],Zx=["href","title","class","target","rel"],Vx={ALLOWED_TAGS:Bx,ALLOWED_ATTR:Zx,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1},fC={...Vx,ALLOWED_TAGS:[...Bx,"img"],ALLOWED_ATTR:[...Zx,"src","alt","width","height"]},mC=/^language-[A-Za-z0-9_+#.-]+$/,gC=new Set(["CODE","PRE"]);function vC(t){t.nodeName==="A"&&t.hasAttribute("href")?(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")):(t.removeAttribute("target"),t.removeAttribute("rel"));let e=t.getAttribute("class");if(e===null)return;let n=gC.has(t.nodeName)?e.split(/\s+/).filter(r=>mC.test(r)):[];if(n.length===0){t.removeAttribute("class");return}t.setAttribute("class",n.join(" "))}var Sh;function bC(){if(Sh===void 0){let t=Ex();t.addHook("afterSanitizeAttributes",vC),Sh=t}return Sh}function Vo(t,e){let n=e?.allowImages===!0,r=pC.parse(t,{async:!1});return bC().sanitize(r,n?fC:Vx).trim()}var pl=class{#e;#t=null;#n=0;#r="";#i=null;constructor(e){this.#e=e}get deltas(){return this.#n}countDelta(){this.#n+=1}queue(e){this.#r=e,this.#a(),this.#i===null&&(this.#i=requestAnimationFrame(()=>{this.#i=null,this.into(this.#r)}))}into(e){this.#i!==null&&(cancelAnimationFrame(this.#i),this.#i=null),this.#r=e;let n=this.#a();return n.innerHTML=Vo(e,{allowImages:this.#e.allowImages()}),this.#e.follow(),n}end(){this.#i!==null&&this.into(this.#r),this.#t=null}#a(){return this.#t===null&&(this.#t=this.#e.openBubble(),this.#n=0),this.#t}};function jx(t){let{messages:e,jumpButton:n,emptyWrap:r,strings:o}=t;e.className="messages",e.setAttribute("part","messages"),e.setAttribute("role","log"),e.setAttribute("aria-live","off"),e.setAttribute("aria-label",o.conversation),n.className="jump-latest",n.type="button",n.setAttribute("part","jump-latest"),n.textContent=o.jumpToLatest,r.className="empty",r.setAttribute("part","empty");let i=document.createElement("div");i.className="greeting",i.setAttribute("part","greeting");let a=document.createElement("slot");a.name="greeting",a.append(t.greetingText),i.append(a);let s=document.createElement("slot");s.name="empty",t.starters!==null&&s.append(t.starters),r.replaceChildren(i,s)}var yC=4,wC=120;function Wx(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function jo(t,e,n){let r=Wx(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let a=document.createElement("button");a.type="button",a.className="suggestion-chip",a.setAttribute("part","suggestion-chip"),a.textContent=i,a.addEventListener("click",()=>n(i)),o.appendChild(a)}return o}function qx(t,e,n){let r=t.getAttribute("data-starters");if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return jo({prompts:o},e,n)}function fl(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(xC(r,e)))}}function xC(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{EC(n).then(o=>{_C(r,o?e.copied:e.copyFailed,e)})}),r}async function EC(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function _C(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}function Wo(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}var Yx=1e3,ml=class{element;#e;#t;#n;#r;#i;#a;#o=0;#s=!1;#l=!1;constructor(e=pe,n=()=>performance.now()){this.#r=e,this.#i=n,this.#a=n(),this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#n=document.createElement("button"),this.#n.type="button",this.#n.className="thoughts-toggle",this.#n.setAttribute("part","thoughts-toggle"),this.#n.setAttribute("aria-expanded","true"),this.#e=document.createElement("span"),this.#e.className="thoughts-label",this.#e.setAttribute("part","thoughts-label"),this.#e.textContent=e.thinking,this.#t=document.createElement("pre"),this.#t.className="thoughts-body",this.#t.setAttribute("part","thoughts-body"),this.#t.hidden=!0,this.#n.addEventListener("click",()=>{this.#d(!this.#s)}),this.element.append(this.#e,this.#t)}begin(){this.#a===null&&(this.#a=this.#i(),this.element.setAttribute("data-streaming",""),this.#e.textContent=this.#r.thinking)}stream(e){this.#t.textContent=e,this.#c(e.trim()!=="")}settle(){this.#a!==null&&(this.#o+=this.#i()-this.#a,this.#a=null,this.element.removeAttribute("data-streaming"),this.#e.textContent=this.#o<Yx?this.#r.thoughts:te(this.#r.thoughtFor,{seconds:Math.round(this.#o/Yx)}))}collapse(){this.settle(),!this.#s&&this.#d(!0)}#c(e){e!==this.#l&&(this.#l=e,e?(this.#n.append(this.#e),this.element.prepend(this.#n)):(this.#n.remove(),this.element.prepend(this.#e)),this.#d(this.#s))}#d(e){this.#s=e,this.#t.hidden=e||!this.#l,this.#n.setAttribute("aria-expanded",String(!e))}};var SC=new Set([J.PENDING,J.DEFERRED]),TC=`.tool-call-subagent > .subagent:is(${[Et.STARTED,Et.TOOL_CALL,Et.TOOL_RESULT].map(t=>`[data-phase="${t}"]`).join(", ")})`,kC=["data-status","data-asking","data-has-result","data-phase","data-agent"];function AC(t,e){let n=e===Pt.MINIMAL;return!n&&e!==Pt.INLINE&&t.hasAttribute("data-has-args")||!n&&t.hasAttribute("data-has-result")||t.getAttribute("data-status")===J.DEFERRED||t.querySelector(".tool-call-subagent > *")!==null}var gl=class{element;#e;#t;#n;#r;#i;#a;#o=[];#s=!1;constructor(e,n){this.#e=e,this.#t=n,this.element=document.createElement("div"),this.element.className="tool-group",this.element.setAttribute("part","tool-group"),this.element.setAttribute("data-open","false"),this.#r=document.createElement("button"),this.#r.type="button",this.#r.className="tool-group-head",this.#r.setAttribute("part","tool-group-head"),this.#r.setAttribute("aria-expanded","false");let r=document.createElement("span");r.className="tool-group-icon",r.setAttribute("part","tool-group-icon"),r.setAttribute("aria-hidden","true"),this.#i=document.createElement("span"),this.#i.className="tool-group-label",this.#i.setAttribute("part","tool-group-label"),this.#a=document.createElement("span"),this.#a.className="tool-group-meta",this.#a.setAttribute("part","tool-group-meta");let o=document.createElement("span");o.className="tool-group-chevron",o.setAttribute("aria-hidden","true"),this.#r.append(r,this.#i,this.#a,o),this.#r.addEventListener("click",()=>{this.setOpen(this.element.getAttribute("data-open")!=="true")}),this.#n=document.createElement("div"),this.#n.className="tool-group-list",this.#n.setAttribute("part","tool-group-list"),this.element.append(this.#r,this.#n),new MutationObserver(()=>{this.refresh()}).observe(this.#n,{attributes:!0,attributeFilter:[...kC],subtree:!0})}add(e,n){let r=this.#o.filter(i=>i.name===n).length+1,o=n;if(r>1){let i=document.createElement("span");i.className="tool-call-repeat",i.setAttribute("part","tool-card-repeat"),i.textContent=te(this.#e.toolStepRepeat,{n:r}),e.querySelector(".tool-call-name")?.after(i),o=`${n} ${i.textContent}`}this.#o.push({element:e,name:n,label:o}),this.#n.append(e),this.refresh()}setOpen(e){this.element.setAttribute("data-open",String(e)),this.#r.setAttribute("aria-expanded",String(e))}#l(e){if(this.#r.disabled=!e,e){this.#r.setAttribute("aria-expanded",this.element.getAttribute("data-open"));return}this.element.setAttribute("data-open","false"),this.#r.removeAttribute("aria-expanded")}reveal(){this.#s=!0,this.setOpen(!0)}#c(){for(let{element:e}of this.#o){let n=e.getAttribute("data-status")===J.PENDING?e.querySelector(TC):null;if(n!==null){let r=n.getAttribute("data-agent");return r===null?this.#e.subAgentWorking:te(this.#e.subAgentDelegatedTo,{agent:r})}}return null}refresh(){let e=this.#e,n=this.#o,r=n.map(k=>k.element.getAttribute("data-status")??""),o=n.filter((k,E)=>SC.has(r[E])),i=k=>r.filter(E=>E===k).length,a=i(J.ERROR),s=i(J.DECLINED),l=i(J.DEFERRED),c=n.filter(k=>k.element.hasAttribute("data-asking")).length,d=l+c,h=n.length;l>0&&!this.#s?(this.#s=!0,this.setOpen(!0)):l===0&&(this.#s=!1);let v="done";d>0?v="waiting":o.length>0?v="running":a>0&&(v="error"),this.element.setAttribute("data-state",v),this.element.setAttribute("part",`tool-group tool-group-${v}`),this.element.setAttribute("data-count",String(h));let f=h===1?n[0]:void 0;if(this.#l(f===void 0||AC(f.element,this.#t())),f!==void 0)this.#i.textContent=f.label;else{let k=v==="waiting"?e.toolGroupSteps:v==="running"?e.toolGroupWorking:e.toolGroupWorked;this.#i.textContent=te(k,{count:h})}let p=[],b=this.#c(),T=o[0];d>0?p.push(te(e.toolGroupWaiting,{count:d})):b!==null?p.push(b):T!==void 0&&h>1&&p.push(T.label),a>0&&p.push(te(e.toolGroupFailed,{count:a})),s>0&&p.push(te(e.toolGroupDeclined,{count:s})),this.#a.replaceChildren(...p.map(k=>{let E=document.createElement("span");return E.className="tool-group-note",E.textContent=k,E})),this.#a.hidden=p.length===0}};function Kx(t){return t===Mt.GROUPED}function vl(t,e){try{return t()}catch(n){return console.warn(`ag-ui-chat: render failed for ${e}`,n),null}}function Xx(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):Xx(n,e)}function Jx(t){let e=[];Xx(t,e);let n=0;for(let{node:r,parent:o}of e){let i=document.createDocumentFragment();for(let a of r.data.split(/(\s+)/)){if(a==="")continue;if(/\s/.test(a)){i.appendChild(document.createTextNode(a));continue}let s=document.createElement("span");s.className="word",s.style.setProperty("--ag-ui-word-index",String(n)),s.textContent=a,i.appendChild(s),n+=1}o.replaceChild(i,r)}}function Qx({viewport:t,onMissedContent:e}){let n=!0,r=!1,o=()=>t.scrollHeight-t.scrollTop-t.clientHeight<=4,i=d=>{d!==r&&(r=d,e(r))},a=()=>{t.scrollTop=t.scrollHeight},s=()=>{n=o(),n&&i(!1)},l=()=>{if(n){a();return}i(!0)};t.addEventListener("scroll",s,{passive:!0});let c=new ResizeObserver(()=>{n&&a()});return c.observe(t),{follow:l,jump:()=>{n=!0,i(!1),a()},following:()=>n,dispose:()=>{t.removeEventListener("scroll",s),c.disconnect()}}}var bl=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;#o=null;#s=null;#l=null;#c=new WeakMap;#d=new WeakMap;#m=new WeakMap;constructor(e){this.#e=e}mountScroller(e,n){e.addEventListener("click",()=>{this.jump()},{signal:n}),this.#a=Qx({viewport:this.#e.messages,onMissedContent:r=>{e.dataset.missed=String(r)}})}disposeScroller(){this.#a.dispose()}follow(){this.#a.follow()}jump(){this.#a.jump()}isEmpty(){return!this.#e.emptyWrap.hidden}card(e){return this.#t.get(e)}cards(){return this.#t.values()}forgetCard(e){this.#t.delete(e)}setCardElement(e,n){this.#n.set(e,n)}markServerSettled(e){this.#i.add(e)}isServerSettled(e){return this.#i.has(e)}collapseThoughts(){this.#l?.collapse()}settleThoughts(){this.#l?.settle()}closeGroup(){this.#s!==null&&this.#s.childElementCount===0&&(this.#s.remove(),this.updateEmptyState()),this.settleThoughts(),this.#s=null,this.#l=null}releaseTurn(){this.#s=null,this.#l=null,this.hidePending(),this.#t.clear()}forgetCards(){this.#i.clear(),this.#n.clear(),this.#r.clear()}holdRunning(e,n){this.#r.set(e,n)}setAsking(e,n){this.#r.get(e)?.setAsking(n)}empty(){this.#e.messages.replaceChildren(this.#e.emptyWrap),this.updateEmptyState()}append(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===We.ASSISTANT?(r.innerHTML=Vo(n,{allowImages:this.#e.allowImages()}),fl(r,this.#e.strings()),this.ensureGroup().appendChild(r)):(this.#s=null,r.textContent=n,this.#e.messages.appendChild(r)),this.updateEmptyState(),e===We.USER?this.jump():this.follow(),r}ensureGroup(){if(this.#s===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#s=e,this.#e.messages.appendChild(e),this.updateEmptyState()}return this.#s}revealWords(e){this.#e.element.getAttribute("data-text-animation")==="word"&&Jx(e)}updateEmptyState(){this.#e.emptyWrap.hidden=this.#e.messages.childElementCount>1,this.#e.element.toggleAttribute("data-empty",!this.#e.emptyWrap.hidden)}appendStoppedNote(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.strings().stopped,this.ensureGroup().appendChild(e),this.updateEmptyState(),this.follow()}showPending(){if(this.#o!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.strings().thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#o=e,this.ensureGroup().appendChild(e),this.updateEmptyState(),this.follow()}hidePending(){this.#o?.remove(),this.#o=null}showThoughts(){if(this.#l===null){this.#l=new ml(this.#e.strings());let e=this.ensureGroup();e.insertBefore(this.#l.element,e.firstChild),this.updateEmptyState(),this.follow()}return this.#l}noticeIfSkillLoad(e){let n=ks(e);return n===null?!1:(this.appendNotice("\u2728",te(this.#e.strings().usingSkill,{name:n}),"skill"),!0)}appendNotice(e,n,r,o){this.ensureGroup().appendChild(Js(e,n,r,o)),this.updateEmptyState(),this.follow()}renderToolOutput(e,n){let r=vl(()=>e(n.args),`tool ${n.name}`);if(r===null)return;let o=this.#n.get(n.id),i=o?.closest(".tool-group");if(i==null)o?.after(r);else{let a=this.#d.get(i);a===void 0&&(a=document.createComment(""),i.after(a),this.#d.set(i,a));let s=r instanceof DocumentFragment?[...r.children]:[r];a.before(r);for(let l of s)this.#m.set(l,i)}this.afterGrew()}afterGrew(){this.updateEmptyState(),this.follow()}cardFor(e){let n=this.#t.get(e.id);if(n!==void 0)return n;let r=this.#e.resolveTool(e.name)?.parameters[Le],o=typeof r=="string"?r:this.#e.toolSummaries()[e.name]??this.#e.serverSummary(e.name)??Wo(e.name),i=new Po(e.name,e.args,o,this.#e.strings(),{formatPayload:a=>this.#e.formatToolPayload(a)});return this.#t.set(e.id,i),Kx(this.#e.toolDisplay())?this.#p().add(i.element,o):this.ensureGroup().appendChild(i.element),this.updateEmptyState(),this.follow(),i}refreshStepGroups(){for(let e of this.#e.messages.querySelectorAll(".tool-group"))this.#c.get(e)?.refresh()}revealStep(e){let n=e.element.closest(".tool-group");(n===null?void 0:this.#c.get(n))?.reveal()}#p(){let e=this.ensureGroup(),n=e.lastElementChild,r=n===null?void 0:this.#c.get(this.#m.get(n)??n);if(r!==void 0)return r;let o=new gl(this.#e.strings(),this.#e.toolGroupDisplay);return this.#c.set(o.element,o),n===null?e.prepend(o.element):n.after(o.element),o}};var yl=class{#e;#t=new Map;#n=new Set;#r=new Map;constructor(e){this.#e=e}register(e){this.#t.set(e.type,e),this.#n.delete(e.type)}has(e){return this.#t.has(e)}unhandledTypes(){return[...this.#n]}clearBlocks(){this.#r.clear()}draw(e,n,r){let o=this.#t.get(n);if(o===void 0){this.#n.add(n);return}let i=vl(()=>o.render(r),`activity ${n}`);if(i===null){this.#i(e,n,o.removedNotice,r);return}let a=this.#r.get(e);a===void 0?this.#e.ensureGroup().appendChild(i):a.replaceWith(i),this.#r.set(e,i),this.#e.afterTranscriptGrew()}#i(e,n,r,o){let i=this.#r.has(e);this.#r.get(e)?.remove(),this.#r.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#e.appendNotice("\u{1F4C9}",r,"chart-undrawable")}};var wl=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},qo=class{#e;#t;#n;#r;#i;#a;#o;#s=new Set;#l;#c;#d;#m;#p=!1;constructor(e){this.#e=e.agent,this.#t=e.handlers,this.#n=e.getTools??(()=>[]),this.#r=e.getContext??(()=>[]),this.#i=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost",this.#c=e.unfinishedMessage??"Not finished: the run ended or moved on before this tool call returned a result.",this.#d=e.declinedMessage??"User declined the action.";let n=e.maxToolRounds??Qn;this.#m=n>=1?Math.floor(n):Qn,this.#w();let r=e.onStateChanged;r!==void 0&&this.#e.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#e.state}setState(e){this.#e.setState({...e})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(e,n=[]){this.#p=!1;let r={id:ke(),role:"user",content:e,...n.length>0?{metadata:{attachments:n}}:{}};this.#e.addMessage(r),this.#g(),await this.#b()}truncateToLastUser(){let e=[...this.#e.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#o(r),this.#e.setMessages(r),r}async resume(){this.#p=!1,await this.#b()}addToolResult(e,n){this.#e.addMessage({id:ke(),role:"tool",content:n,toolCallId:e}),this.#g()}cancel(){this.#p=!0,this.#e.abortRun()}async#b(){try{await this.#_(),this.#p&&this.#u()}catch(e){this.#p||IC(e)?this.#u():this.#t.onError(e instanceof Error?e.message:String(e))}finally{this.#t.onSettled()}}#u(){this.#g(),this.#t.onCancelled()}#w(){let e=this.#e.messages,n=e.map(RC);n.some((r,o)=>r!==e[o])&&this.#e.setMessages(n)}#S(e){let n=this.#e.messages,r=_s(n,o=>({id:ke(),role:"tool",content:this.#c,toolCallId:o,metadata:{outcome:qe.INTERRUPTED}}),e);r!==n&&(this.#e.setMessages([...r]),this.#g())}#x(e,n){for(let r of e){let o=r.toolCallId;o!==void 0&&n[r.id]?.status==="cancelled"&&this.#e.addMessage({id:ke(),role:"tool",content:this.#d,toolCallId:o,metadata:{outcome:qe.DENIED}})}this.#g()}#g(){this.#o(this.#e.messages)}async#_(){let e,n=new Set;for(let r=0;r<this.#m;r+=1){if(this.#p)return;let o=[],i={terminal:!1,errored:!1,interrupts:[]},a={tools:this.#n(),context:this.#r()};if(e!==void 0&&(a.resume=e),this.#S(n),this.#p||(await this.#e.runAgent(a,this.#h(o,i)),e=void 0,n=new Set,this.#g(),this.#p))return;if(!i.terminal)throw new wl(this.#l);if(i.errored)return;if(i.interrupts.length>0){if(this.#a===null)return;let l=await this.#a(i.interrupts);if(this.#p){this.#x(i.interrupts,l);return}e=ky(i.interrupts,l),n=new Set(i.interrupts.flatMap(({toolCallId:c})=>c??[]));continue}if(this.#i===null||o.length===0)return;let s=!1;for(let l of o){if(this.#p)return;let c=await this.#i(l);if(c!==null){if(c.halt===!0)return;this.#e.addMessage({id:ke(),role:"tool",content:c.content,toolCallId:l.id,...c.outcome===void 0?{}:{metadata:{outcome:c.outcome}}}),this.#g(),s=!0}}if(!s)return}}#h(e,n){let r=this.#t,o=this.#s,i=()=>this.#p,a=new Set,s;return{onRunInitialized(){r.onRunStart()},onRunStartedEvent({event:l}){s=l.runId},onTextMessageStartEvent({event:l}){o.has(l.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${l.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:l}){r.onTextDelta(l)},onTextMessageEndEvent({event:l,textMessageBuffer:c}){o.add(l.messageId),r.onTextEnd(c,{messageId:l.messageId,...s===void 0?{}:{runId:s}})},onToolCallEndEvent({event:l,toolCallName:c,toolCallArgs:d}){let h={id:l.toolCallId,name:c,args:d};e.push(h),r.onToolCall(h)},onToolCallResultEvent({event:l}){let c=l.metadata?.outcome;r.onToolResult(l.toolCallId,rr(l.content),c)},onActivitySnapshotEvent({event:l,messages:c}){if(c.some(h=>h.id===l.messageId&&h.role==="activity")){r.onActivityChanged(l.messageId,l.activityType,l.content);return}r.onActivity(l.activityType,l.content,l.messageId)},onActivityDeltaEvent({event:l}){a.add(l.messageId)},onCustomEvent({event:l}){r.onCustomEvent(l.name,l.value)},onSubagentStartedEvent({event:l}){r.onSubAgentStarted(l.subagentRunId,l.name,l.parentToolCallId??null)},onSubagentFinishedEvent({event:l}){r.onSubAgentFinished(l.subagentRunId)},onSubagentErrorEvent({event:l}){r.onSubAgentError(l.subagentRunId,l.message)},onMessagesSnapshotEvent({event:l}){r.onMessagesSnapshot(l.messages)},onMessagesChanged({messages:l}){for(let c of a){let d=l.find(h=>h.id===c);d!==void 0&&d.role==="activity"&&r.onActivityChanged(c,d.activityType,d.content)}a.clear()},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningMessageEndEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(l){n.terminal=!0,l.outcome==="interrupt"&&(n.interrupts=l.interrupts)},onRunErrorEvent({event:l}){n.terminal=!0,n.errored=!0,!i()&&r.onError(l.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function IC(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function RC(t){let{outcome:e,attachments:n,...r}=t;if(e===void 0&&n===void 0)return t;let o=r.metadata;return{...r,metadata:{...e===void 0?{}:{outcome:e},...n===void 0?{}:{attachments:n},...typeof o=="object"?o:{}}}}var Mr="thread",Th="threads",Yo="messages:",El="checkpoint:",Ko="minted:",CC=60,NC=100,OC="New conversation",MC=/^\/([A-Za-z0-9][\w.-]*)$/;function Xo(t,e,n={reported:!1}){try{sessionStorage.setItem(t,e)}catch{if(n.reported)return;n.reported=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function xl(t){return t===""?xt:`${xt}@${t}`}var Qe=class{#e;#t={reported:!1};constructor(e=""){this.#e=xl(e)}static adopt(e,n){let r=`${xl(e)}:`,o=`${xl(n)}:`,i={reported:!1};for(let[a,s]of eE(r)){let l=sessionStorage.getItem(a),c=o+s;l!==null&&sessionStorage.getItem(c)===null&&Xo(c,l,i),sessionStorage.removeItem(a)}}static purge(e){for(let[n]of eE(`${xl(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#o(Mr))??this.newThread()}newThread(){let e=ke();return this.#a(this.#o(Mr),e),this.#a(this.#o(Ko+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#o(Ko+e))!==null&&sessionStorage.getItem(this.#o(Yo+e))===null}loadMessages(e){return Promise.resolve(this.#s(this.#o(Yo+e)))}saveMessages(e,n){this.#a(this.#o(Yo+e),JSON.stringify(n)),sessionStorage.removeItem(this.#o(Ko+e)),this.#n(e,n)}loadCheckpoint(e){return this.#s(this.#o(El+e))}saveCheckpoint(e,n){let r=this.#o(El+e);if(n===null){sessionStorage.removeItem(r);return}this.#a(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#o(Yo+e)),sessionStorage.removeItem(this.#o(El+e)),sessionStorage.removeItem(this.#o(Ko+e)),this.#i(this.#r().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#o(Mr))===e&&sessionStorage.removeItem(this.#o(Mr))}listThreads(){let e=this.#r().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){this.#a(this.#o(Mr),e)}renameThread(e,n){let r=this.#r(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#i(r))}#n(e,n){let r=this.#r(),o=r.find(s=>s.threadId===e),i=LC(n),a=Date.now();o===void 0?r.push({threadId:e,title:tE(n),titleCustom:!1,preview:i,updatedAt:a}):(o.preview=i,o.updatedAt=a,o.titleCustom||(o.title=tE(n))),this.#i(r)}#r(){return this.#s(this.#o(Th))??[]}#i(e){let n=this.#o(Th);if(e.length===0){sessionStorage.removeItem(n);return}this.#a(n,JSON.stringify(e))}#a(e,n){Xo(e,n,this.#t)}#o(e){return`${this.#e}:${e}`}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function eE(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);PC(o)&&e.push([r,o])}return e}function PC(t){return t===Mr||t===Th||t.startsWith(Yo)||t.startsWith(El)||t.startsWith(Ko)}function tE(t){let e=Pr(t);return e===""?OC:e}function Pr(t,e=()=>{}){for(let n of t)if(n.role==="user"){let r=nE(n.content);if(r!==""){let o=MC.exec(r)?.[1],i=o===void 0?r:e(o)??Wo(o);return rE(i,CC)}}return""}function LC(t){for(let e of[...t].reverse()){let n=nE(e.content);if(n!=="")return rE(n,NC)}return""}function nE(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function rE(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function kh(t){let e=t.headers??{},n=new Set;return new Ry({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),a=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(Es(r,a,t.trustedOrigins??[],n),i===void 0)return fetch(r,lt(o,t.credentials));let s=new Headers(o?.headers);for(let[l,c]of Object.entries(i))s.set(l,c);return fetch(r,lt({...o,headers:s},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}function oE(t,e){let n=t.getAttribute(e);return n!==null&&n!=="false"}function Ah(t,e){let n=t.getAttribute(e);if(n===null)return null;try{return JSON.parse(n)}catch{return console.warn(`<ag-ui-chat>: ${e} is not valid JSON, so it was ignored entirely and the built-in default is being used. Check the quoting -- JSON inside an HTML attribute needs single quotes around the attribute value, or its own double quotes escaped.`),null}}function iE(t){let e=t.getAttribute("data-max-tool-rounds");return e===null?Qn:Number.parseInt(e,10)}var zC="New conversation",Jo=class{#e;#t;#n;#r;#i;#a=new Set;#o=new Map;#s=new Map;#l=null;constructor(e,n=()=>({}),r=new Qe,o=()=>{},i=!0){this.#e=e.endsWith("/")?e:`${e}/`,this.#t=n,this.#n=r,this.#r=o,this.#i=i}threadId(){return this.#l=this.#n.threadId(),this.#l}setActiveThread(e){this.#n.setActiveThread(e),this.#l=e}newThread(){return this.#l=xs(this.#n),this.#l}isUnsent(e){return this.#n.isUnsent?.(e)===!0}saveMessages(e,n){this.#n.saveMessages(e,this.#i?n:[]),this.#s.set(e,{threadId:e,title:Pr(n)||zC,updatedAt:Date.now(),preview:""})}loadCheckpoint(e){return this.#n.loadCheckpoint(e)}saveCheckpoint(e,n){this.#n.saveCheckpoint(e,n)}renameThread(e,n){this.#n.renameThread(e,n),this.#o.set(e,n),this.#u(e,"PATCH",{title:n})}clear(e){this.#n.clear(e),this.#a.add(e),this.#s.delete(e),this.#u(e,"DELETE")}async listThreads(){let e=await this.#d();if(e===null)return this.#n.listThreads();let n=e.filter(o=>!this.#a.has(o.thread_id)).map(o=>this.#p(o)),r=this.#c(e);return r===null?n:[r,...n]}#c(e){for(let r of e)this.#s.delete(r.thread_id);let n=this.#l===null?void 0:this.#s.get(this.#l);return n===void 0?null:{...n,title:this.#o.get(n.threadId)??n.title}}async loadMessages(e){if(this.#n.isUnsent?.(e)===!0)return null;let n=await this.#b(`${this.#e}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#n.loadMessages(e);let r=await this.#m(n);return r===null?this.#n.loadMessages(e):r.messages??null}async#d(){let e=await this.#b(this.#e);if(e===null||!e.ok)return null;let n=await this.#m(e);return n===null?null:n.threads??[]}async#m(e){try{return await e.json()}catch{return null}}#p(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#b(e){try{return await fetch(e,lt({headers:this.#t()},this.#r()))}catch{return null}}async#u(e,n,r){let o=this.#t();try{await fetch(`${this.#e}${encodeURIComponent(e)}/`,lt({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#r()))}catch{}}};function aE(){return{tools:[],serverSettled:new Set,invalidated:new Set,announcedOutcome:!1,outcome:"completed"}}function sE(t,e){let n={};for(let[r,o]of Object.entries(t))n[r]=(...i)=>{e()&&o(...i)};return n}var _l=class{#e;#t=aE();constructor(e){this.#e=e}detach(){this.#t=aE()}forClient(e){let n=this.#t,r=()=>n===this.#t,{onSettled:o,onError:i,onCancelled:a,...s}=this.#n(n,e),l=sE({onError:i,onCancelled:a},r);return{...sE(s,r),onError:c=>{n.outcome="failed",l.onError(c)},onCancelled:()=>{n.outcome="stopped",l.onCancelled()},onSettled:()=>{r()&&o(),this.#r(n,e)}}}#n(e,n){return{onRunStart:()=>{this.#e.running()||(e.announcedOutcome=!1,this.#e.announcer.announce(this.#e.strings().announceResponding)),this.#e.setRunning(!0),this.#e.transcript.ensureGroup(),this.#e.transcript.showPending()},onReasoningStart:()=>{this.#e.transcript.hidePending(),this.#e.transcript.showThoughts().begin()},onReasoningDelta:r=>{this.#e.transcript.showThoughts().stream(r)},onReasoningEnd:()=>{this.#e.transcript.settleThoughts()},onTextDelta:r=>{this.#e.transcript.hidePending(),this.#e.transcript.collapseThoughts(),this.#e.stream.queue(r),this.#e.stream.countDelta()},onTextEnd:(r,o)=>{if(r===""){this.#e.stream.end();return}let i=this.#e.stream.into(r);this.#e.stream.deltas<=1&&this.#e.transcript.revealWords(i),fl(i,this.#e.strings()),this.#e.actions.attach(i,o),this.#e.stream.end(),this.#e.noteUnread(n)},onToolCall:r=>{this.#e.transcript.hidePending(),this.#e.transcript.settleThoughts(),!this.#e.transcript.noticeIfSkillLoad(r)&&(e.tools.push({id:r.id,name:r.name}),this.#e.transcript.cardFor(r))},onActivity:(r,o,i)=>{this.#e.activities.draw(i,r,o)},onCustomEvent:(r,o)=>{if(r===cc){this.#i(e,o);return}if(r===lp){this.#e.subagents.report(o);return}this.#e.element.dispatchEvent(new CustomEvent(ic,{detail:{name:r,value:o},bubbles:!0,composed:!0}))},onSubAgentStarted:(r,o,i)=>{this.#e.subagents.start(r,o,i)},onSubAgentFinished:r=>{this.#e.subagents.finish(r)},onSubAgentError:(r,o)=>{this.#e.subagents.fail(r,o)},onMessagesSnapshot:()=>{this.#e.transcript.appendNotice("\u{1F504}",this.#e.strings().historyReplaced,"history-replaced")},onToolResult:(r,o,i)=>{let a=this.#e.transcript.card(r);a!==void 0&&(a.settle(Ro(i),o),this.#e.transcript.markServerSettled(r),e.serverSettled.add(r),this.#e.transcript.showPending())},onActivityChanged:(r,o,i)=>{this.#e.activities.draw(r,o,i)},onRunEnd:()=>{this.#e.transcript.hidePending(),this.#e.stream.end()},onError:r=>{e.announcedOutcome=!0,this.#e.announcer.announce(this.#e.strings().announceFailed),this.#e.transcript.hidePending();let o=this.#e.appendMessage(We.ASSISTANT,`\u26A0\uFE0F ${r}`);o.classList.add("message--failed"),this.#e.actions.attach(o,{rateable:!1}),this.#e.transcript.revealWords(o),this.#e.stream.end()},onCancelled:()=>{e.announcedOutcome=!0,this.#e.announcer.announce(this.#e.strings().announceStopped),this.#e.transcript.hidePending(),this.#e.transcript.appendStoppedNote(),this.#e.stream.end()},onSettled:()=>{e.announcedOutcome||this.#e.announcer.announce(this.#e.strings().announceAnswerReady),this.#e.transcript.hidePending(),this.#e.setRunning(!1),this.#e.stream.end();for(let r of this.#e.transcript.cards())r.settled||r.settle(J.INTERRUPTED,this.#e.strings().callNotFinished);this.#e.transcript.closeGroup()}}}#r(e,n){let r=e.tools.map(({id:a,name:s})=>({name:s,side:e.serverSettled.has(a)?"server":"client"})),o=[...e.invalidated];e.tools.length=0,e.serverSettled.clear(),e.invalidated.clear();let i=e.outcome;e.outcome="completed",this.#e.element.dispatchEvent(new CustomEvent(nc,{detail:{threadId:n,tools:r,invalidated:o,outcome:i},bubbles:!0,composed:!0}))}#i(e,n){let r=n??{},o=Array.isArray(r.keys)?r.keys.filter(i=>typeof i=="string"):[];if(o.length!==0){for(let i of o)e.invalidated.add(i);this.#e.element.dispatchEvent(new CustomEvent(ac,{detail:{keys:o,reason:typeof r.reason=="string"?r.reason:null},bubbles:!0,composed:!0}))}}};var Ih=new Set,Sl=class{#e;#t="";#n=null;#r="";#i="";#a=null;#o={reported:!1};constructor(e){this.#e=e}claim(){this.#t=this.#s()}release(){this.#n!==null&&(Ih.delete(this.#n),this.#n=null)}conversationNamespace(e){return e===""?this.#t:`${this.#t}#${e}`}scopeStore(e,n){if(!(e instanceof Qe))return e;let r=this.conversationNamespace(n);return this.#a=r===""?e:new Qe(r),this.#a}rescopeStore(e,n){return e!==this.#a?null:(this.#a=new Qe(n),this.#a)}key(e){return this.#t===""?e:`${e}:${this.#t}`}readScopedItem(e){return sessionStorage.getItem(this.key(e))}readPreference(e){try{let n=localStorage.getItem(this.key(e));if(n!==null)return n}catch{}return this.readScopedItem(e)}writePreference(e,n){let r=this.key(e);try{localStorage.setItem(r,n)}catch{}Xo(r,n,this.#o)}writeSession(e,n){Xo(this.key(e),n,this.#o)}clearPreference(e){let n=this.key(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#s(){let e=this.#e.id(),n=e!==""?e:this.#e.endpoint();return n===""?"":this.#i===n?this.#r:Ih.has(n)?(this.#i=n,this.#r=`${n}~${ke()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${n}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#r):(Ih.add(n),this.#n=n,n)}};var DC=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],Nh=["omit","same-origin","include"],$C="New conversation";function UC(t){for(let e of t){let n=typeof e.content=="string"?e.content.split(/\s+/).join(" ").trim():"";if(e.role==="user"&&n!==""){let r=Array.from(n);return r.length<=60?n:`${r.slice(0,59).join("").trimEnd()}\u2026`}}return""}function Rh(t){return Nh.includes(t)}var HC="auto",Ch="(max-width: 600px)",GC=320,Bn=8,lE=`${xt}:collapsed`,cE=`${xt}:theme`,hE=["light","dark","auto"];function FC(t){return t.split(/\s+/).filter(e=>hE.includes(e)).at(-1)}function dE(t,e){return[...t.split(/\s+/).filter(r=>r!==""&&!hE.includes(r)),e].join(" ")}function BC(t,e){try{return(t instanceof ShadowRoot?t:document).querySelector(e)??document.querySelector(e)}catch{return null}}var Lr=class extends HTMLElement{agentFactory=kh;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>this.#$.defaultTools();getContext=()=>[...Cc(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;getPlace=null;conversationStore=new Qe;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#e=new Set;#t=pe;#n=new el({card:e=>this.#v.card(e),strings:()=>this.#t,follow:()=>this.#v.follow()});#r=new yl({ensureGroup:()=>this.#v.ensureGroup(),afterTranscriptGrew:()=>this.#v.afterGrew(),appendNotice:(e,n,r)=>this.#v.appendNotice(e,n,r)});#i=new il({element:this,strings:()=>this.#t,retry:()=>{this.retryLastTurn()},threadId:()=>this.#h.threadId,follow:()=>this.#v.follow()});#a;#o=null;#s=[];#l=new Xs;#c=document.createElement("button");#d;#m=document.createElement("div");#p;#b;#u;#w;#S;#x;#g;#_;#h;#M;#Z;#xe;#te;#W;#H;#P;#q=document.createElement("span");#E=document.createElement("div");#k=document.createElement("button");#L=document.createElement("div");#ue=null;#Ee=0;#Y=0;#he="right";#z=null;#ne=!1;#I=new Map;#pe;#v;#D;#fe;#K=document.createElement("span");#y;#f;#T=!1;#_e=!1;#me=null;#Ne=null;#re=[];#X=[];#G=document.createElement("div");#F=null;#oe="";#B=()=>{this.#Oe()&&this.#f.restoreLauncherPosition()};#Se=()=>{this.#Oe()&&this.#f.settleLauncherPosition()};#Oe(){return this.#f.publishVisualViewport(),this.#U(),!this.#f.dragging()&&this.#ie()}#ie(){return this.getClientRects().length>0}#Te(){this.#ie()&&this.#f.restoreLauncherPosition()}#ae;#J;#R=!1;#ke=!1;#O=new AbortController;#ge=!1;#Ae=null;#Q={};#ve={};#be=null;#ee=null;#se={};#V=!1;#A=null;#Qe=null;#Me=null;#ye=[];#$e=new Map;#we={threadId:"",title:""};#Ue=new Bs;#le=new Vs;#$=new Ts({element:this,routeMap:()=>this.routeMap,navigate:()=>this.navigate,getPageMap:()=>this.getPageMap,pageWithheld:()=>this.#le.withheld,resolvePageTarget:e=>this.resolvePageTarget(e),getTools:()=>this.getTools(),askUser:()=>this.askUser,askUserRenderer:()=>this.askUserRenderer,decision:this.#Ue,setAsking:(e,n)=>this.#v.setAsking(e,n),ensureGroup:()=>this.#v.ensureGroup(),strings:()=>this.#t,hidePending:()=>this.#v.hidePending(),updateEmptyState:()=>this.#v.updateEmptyState(),follow:()=>this.#v.follow(),fetchInit:e=>this.#ot(e)});#et=new pl({openBubble:()=>this.appendMessage(We.ASSISTANT,""),allowImages:()=>this.allowImages,follow:()=>this.#v.follow()});#tt=new er(this);#N=new Sl({id:()=>this.id,endpoint:()=>this.endpoint});#ce;constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#p=document.createElement("div"),this.#b=document.createElement("div"),this.#u=document.createElement("textarea"),this.#w=document.createElement("button"),this.#S=document.createElement("span"),this.#M=document.createElement("div"),this.#Z=document.createElement("button"),this.#xe=document.createElement("input"),this.#te=document.createElement("div"),this.#ae=document.createElement("span"),this.#W=document.createElement("button"),this.#H=document.createElement("button"),this.#P=document.createElement("span"),this.#pe=document.createElement("div"),this.#v=new bl({element:this,messages:this.#b,emptyWrap:this.#pe,strings:()=>this.#t,allowImages:()=>this.allowImages,resolveTool:e=>this.#$.resolve(e),toolSummaries:()=>this.toolSummaries,serverSummary:e=>this.#$.summary(e),toolDisplay:()=>this.toolDisplay,toolGroupDisplay:()=>this.toolGroupDisplay,formatToolPayload:e=>this.formatToolPayload?.(e)??null}),this.#D=new Is({element:this,transcript:this.#v,tools:this.#$,decision:this.#Ue,strings:()=>this.#t,announce:e=>this.#l.announce(e),autoConfirm:()=>this.autoConfirm,confirmPredicate:()=>this.confirmPredicate,navigate:()=>this.navigate,approveWithEdits:()=>this.approveWithEdits,approvalRenderer:()=>this.approvalRenderer,getContext:()=>this.#Ot(),conversationStore:()=>this.conversationStore,threadId:()=>this.#h.threadId,tenure:()=>this.#Q,conversation:()=>this.#ve}),this.#fe=new _l({element:this,transcript:this.#v,stream:this.#et,actions:this.#i,activities:this.#r,subagents:this.#n,announcer:this.#l,strings:()=>this.#t,running:()=>this.#V,setRunning:e=>this.#Ce(e),appendMessage:(e,n)=>this.appendMessage(e,n),noteUnread:e=>this.#$t(e)}),this.#f=new Ks({element:this,launcher:this.#H,root:this.#a,connected:()=>this.#R,collapsed:()=>this.collapsed,collapsible:()=>this.#C().collapseTo!==null,strings:()=>this.#t,readPreference:e=>this.#N.readPreference(e),writePreference:(e,n)=>this.#N.writePreference(e,n),clearPreference:e=>this.#N.clearPreference(e),announceSurfaceChange:(e,n)=>this.#Rt(e,n)}),this.#d=new Us({element:this,root:this.#a,messages:this.#b,messagesWrap:this.#m,input:this.#u,strings:()=>this.#t,autoGrow:()=>tn(this.#u),quote:e=>this.quote(e)}),this.#y=new Ps({element:this,chat:this.#p,slot:this.#te,fileInput:this.#xe,button:this.#Z,strings:()=>this.#t,uploadHandler:()=>this.uploadHandler,headersFor:e=>this.#Ie(e),credentialsOption:()=>this.#Ge()}),this.#J=new zs({element:this,slot:this.#ae,input:this.#u,strings:()=>this.#t,transcribeHandler:()=>this.transcribeHandler,headersFor:e=>this.#Ie(e),credentialsOption:()=>this.#Ge(),onInput:()=>this.#je()}),this.registerActivityRenderer({type:uc,render:e=>{let n=ZC(e);return n===null?null:Js("\u{1F5DC}",te(this.#t.historyCompacted,{count:n}),"compaction")}}),this.registerActivityRenderer({type:lc,render:e=>jo(e,this.#t,n=>{this.sendMessage(n)})}),this.#x=new Ds(e=>this.#ce.apply(e)),this.#ce=new mi({element:this,menu:this.#x,input:this.#u,hint:this.#M,strings:()=>this.#t,context:()=>this.skillContext(),flag:e=>oE(this,e),readJsonAttribute:e=>Ah(this,e),fetchInit:e=>this.#ot(e),send:e=>{this.sendMessage(e)},submit:()=>{this.#Xe()},autoGrow:()=>tn(this.#u)}),this.#g=new Fs({onSelect:e=>{this.#h.switchThread(e).catch(()=>{})},onNew:()=>{this.newChat(),this.#h.refreshDrawer()},onRename:(e,n)=>{this.#$e.set(e,n),this.#We(),this.#h.renameThread(e,n)},onDelete:e=>{this.#h.deleteThread(e)}}),this.#_=new Ao((e,n)=>{this.#h.continueRun(e,n).catch(r=>{console.warn("<ag-ui-chat>: continuing a run failed",r)})}),this.#h=new Gs({element:this,drawer:this.#g,checkpoints:this.#_,transcript:this.#v,actions:this.#i,activities:this.#r,tools:this.#$,input:this.#u,hint:this.#M,strings:()=>this.#t,conversationStore:()=>this.conversationStore,formatRelativeTime:()=>this.formatRelativeTime,navigationResult:()=>this.navigationResult,headersFor:e=>this.#Ie(e),requestCredentials:()=>this.#Pe(),appendMessage:(e,n)=>this.appendMessage(e,n),announceTurn:e=>this.#At(e,[]),recordTurn:e=>this.#kt(e),autoGrow:()=>tn(this.#u),continuationEnded:()=>this.#Ke(),client:()=>this.#ee,ensureClient:()=>this.#Je(),buildClient:e=>this.#It(e),releaseClient:()=>{this.#ee=null},running:()=>this.#V||this.#A!==null,holdRun:e=>{let n={};return this.#A=n,this.#Qe=e===null?null:{hold:n,restored:e},{release:()=>this.#qe(n)}},cancelRun:()=>this.#de(),resetState:()=>this.#ze(),setRunning:e=>this.#Ce(e),threadChanged:(e,n)=>this.#xt(e,n),threadsListed:e=>{this.#Ft(e),this.#Ut(e)},threadDeleted:e=>this.#wt([e])})}static get observedAttributes(){return["title-text","placement","collapse-to","anchor","anchor-side","maximized","data-side","data-small-viewport","data-threads-search","credentials","user-key","user-name","data-tool-group-display","data-collapse-icon","theme",...DC]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Rh(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${Nh.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="data-tool-group-display"){this.#v.refreshStepGroups();return}if(e==="data-threads-search"){let o=this.getAttribute("data-threads-search");this.#g.setSearchMode(o==="always"||o==="never"?o:"auto");return}if(e==="anchor"){this.#ne=!1,this.#U();return}if(e==="maximized"){this.#zt(r!==null);return}if(e==="data-collapse-icon"){this.#Le();return}if(e==="theme"){this.#W.isConnected&&this.#mt();return}if(e==="anchor-side"||e==="data-side"||e==="data-small-viewport"){this.#Le(),this.#U();return}if(e==="placement"||e==="collapse-to"){this.#Fe(),this.#f.releaseOwnedAxes(),e==="placement"&&this.#f.switchPlacement(n),this.#f.releaseLauncherPosition(),this.#C().collapseTo===null&&this.collapsed&&this.setCollapsed(!1),this.#st(),this.#Le(),e==="collapse-to"&&(this.#Ze(),this.#Be(this.#C().collapseTo==="bar"?this.#E:null)),this.#U(),requestAnimationFrame(()=>this.#f.syncResizeAnchor());return}if(e==="title-text"){this.#_t();return}if(e==="user-name"){this.#rt();return}if(e==="user-key"){this.#R&&(n??"")!==(r??"")&&this.#ht(n??"",r??"");return}n===r||!this.#R||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.#$.register(e)}get sharedState(){return this.#nt()?.state??this.#se}set sharedState(e){this.#se={...e},this.#nt()?.setState(this.#se)}#nt(){return this.#h.continuation??this.#ee}registerPageState(e){this.#$.registerPageState(e)}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get userName(){return this.getAttribute("user-name")??""}set userName(e){this.setAttribute("user-name",e)}#rt(){let e=this.userName.trim();this.#K.textContent=e===""?this.#t.greetingNoName:te(this.#t.greeting,{name:e})}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Rh(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Rh(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${Nh.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#He(){return{...this.headers,...this.getHeaders?.()}}#Ie(e){let n=this.#He();return Es(e,Object.keys(n),this.trustedOrigins,this.#e),n}#Pe(){return this.credentials??void 0}#Ge(){let e=this.#Pe();return e===void 0?{}:{credentials:e}}#ot(e){return lt({headers:this.#Ie(e)},this.#Pe())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===Mt.INLINE||e===Mt.MINIMAL||e===Mt.COMPACT||e===Mt.FULL?e:Mt.GROUPED}set toolDisplay(e){this.setAttribute("data-tool-display",e)}get toolGroupDisplay(){let e=this.getAttribute("data-tool-group-display");return e===Pt.INLINE||e===Pt.MINIMAL||e===Pt.COMPACT?e:Pt.FULL}set toolGroupDisplay(e){this.setAttribute("data-tool-group-display",e)}get extraStyles(){return this.#s}set extraStyles(e){this.#s=[...e],this.#o!==null&&(this.#a.adoptedStyleSheets=[this.#o,...this.#s])}connectedCallback(){if(this.#O=new AbortController,this.#ge&&this.#vt(),this.#ge=!0,this.#N.claim(),this.#tt.join(),this.#f.restoreSize(),requestAnimationFrame(()=>{this.#Te(),this.#f.syncResizeAnchor()}),this.#t=Ou({...this.#Nt(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let a=this.#N.readPreference(cE),s=a===null?void 0:FC(a);s!==void 0&&this.setAttribute("theme",dE(this.getAttribute("theme")??"",s))}this.#Dt(),this.#g.setStrings(this.#t),this.#_.setStrings(this.#t),this.#C().collapseTo!==null&&this.#Lt()&&this.setAttribute("collapsed",""),this.#Ze(),this.#st();let e=new ResizeObserver(()=>this.#U());e.observe(this.#E),this.#O.signal.addEventListener("abort",()=>e.disconnect());let n=new ResizeObserver(this.#Se);n.observe(this.#b),this.#O.signal.addEventListener("abort",()=>n.disconnect()),this.#f.probe.addEventListener("transitionrun",this.#Se,{signal:this.#O.signal});let r=()=>{requestAnimationFrame(()=>this.#U())};window.addEventListener("pointerup",r,{signal:this.#O.signal}),window.addEventListener("keyup",r,{signal:this.#O.signal}),this.#U(),this.collapsed&&this.setMaximized(!1),this.#C().collapseTo==="none"&&this.#j(ci,{collapsed:this.collapsed}),this.#ce.init();let o=this.#Ae,i=o!==null&&o!==this.userKey;i&&this.#ht(o,this.userKey),this.#Ae=this.userKey,this.conversationStore=this.#N.scopeStore(this.#at(),this.userKey),window.addEventListener("resize",this.#B),window.visualViewport?.addEventListener("resize",this.#B),window.visualViewport?.addEventListener("scroll",this.#B),this.#f.publishVisualViewport(),this.#it(),this.#y.wire(this.#O.signal),this.#J.wire(),this.#h.adoptActiveThread(),queueMicrotask(()=>this.#Ct()),this.#h.rehydrate(i&&o!==""?"rescope":"restore"),i&&this.#h.refreshDrawer(),this.#R=!0,this.#dt(),this.#ke&&(this.#ke=!1,this.newChat())}#Ct(){this.#R&&(this.#$.fetchCatalog(),this.#ce.fetch())}async reload(){this.#de(),this.#ze(),this.#Ce(!1),await Promise.all([this.#$.fetchCatalog(),this.#ce.fetch(),this.#h.rehydrate("restore")])}disconnectedCallback(){this.#R=!1,this.#O.abort(),window.removeEventListener("resize",this.#B),window.visualViewport?.removeEventListener("resize",this.#B),window.visualViewport?.removeEventListener("scroll",this.#B),this.#N.release(),this.#tt.leave(),this.#de(),this.#d.detachPageOffer(),this.#y.tray?.dispose(),this.#J.dispose(),this.#v.disposeScroller(),this.#l.dispose()}#Nt(){let e=Ah(this,"data-strings");return typeof e=="object"&&e!==null?e:{}}quote(e){this.#d.insert(e)}offerQuoteInPage(e=document.body){return this.#d.offerInPage(e)}#it(){this.#be=null;let e=this.getAttribute("data-threads-url");if(e!==null){let n=this.conversationStore,r=new Jo(e,()=>this.#Ie(e),n,()=>this.#Pe(),this.getAttribute("data-threads-cache")!=="false");this.#be={remote:r,inner:n},this.conversationStore=r}}#at(){let e=this.#be;return e!==null&&this.conversationStore===e.remote?e.inner:this.conversationStore}setSkills(e){this.#ce.setClientSkills(e)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}refreshPlace(){this.isConnected&&this.#le.update(this.getPlace===null?Zy(this.routeMap,window.location.pathname):this.getPlace())}#Ot(){let e=this.getContext();return[...this.#le.withheld?e.filter(r=>r.description!==ui):e,...this.#le.context()]}setCollapsed(e,n={}){e&&this.#C().collapseTo===null||(e&&this.setMaximized(!1),n.announce===!0&&e&&!this.collapsed&&this.#Rt(this.#t.chatMinimised,null),e||(this.refreshPlace(),this.#Te()),e?this.setAttribute("collapsed",""):(this.#Be(),this.removeAttribute("collapsed")),this.#U(),this.#N.writeSession(lE,e?"1":"0"),this.#Re(this.#yt()),this.dispatchEvent(new CustomEvent(ci,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){let e=0;for(let n of this.#I.values())e+=n;return e}get threadId(){let e=this.#h.threadId;return e===""?null:e}get threadTitle(){return this.#we.title}get running(){return this.#V}get barHeight(){return this.#Ee}get dockWidth(){return this.#Y}get anchor(){return this.#z}set anchor(e){this.#z=e,this.#ne=!1,this.#U()}#C(){return No(this.getAttribute("placement"),this.getAttribute("collapse-to"))}#st(){let e=this.#C().collapseTo;e===null?this.removeAttribute("data-collapsed-to"):this.setAttribute("data-collapsed-to",e)}#Mt(){let e=this.getAttribute("placement");return e!=="sidebar"&&e!=="side"||!this.#ie()||getComputedStyle(this).position==="static"?0:this.collapsed?this.#C().collapseTo==="rail"?this.#H.offsetWidth:0:this.getAttribute("data-small-viewport")!=="off"&&window.matchMedia(Ch).matches?0:this.#p.offsetWidth}#Pt(){if(this.#f.dragging())return;let e=this.#Mt(),n=this.getAttribute("data-side")==="left"?"left":"right";e===this.#Y&&(e===0||n===this.#he)||(this.#Y=e,this.#he=n,this.#j(Jl,{width:e,side:n}))}#U(){if(!this.isConnected)return;let e=this.#ie()?this.#f.syncDock(this.#E,this.#lt()):0;this.#Pt(),e!==this.#Ee&&(this.#Ee=e,this.#j(Xl,{height:e}))}#lt(){if(this.#C().collapseTo!=="none")return null;let e=this.getAttribute("anchor")??"";if(this.#z===null&&e==="")return null;let n=this.#z??BC(this.getRootNode(),e);return n?.isConnected===!0?n:(this.#ne||(this.#ne=!0,console.warn(`<ag-ui-chat>: the anchor ${this.#z===null?`"${e}"`:"element"} is not in the document, so the panel opens from its placement's own corner.`)),null)}#Lt(){let e=this.#N.readScopedItem(lE);return e!==null?e==="1":this.#C().startsCollapsed&&!this.hasAttribute("data-start-open")}describeSurface(){return this.#f.describeSurface()}moveTo(e,n={}){return this.#f.moveTo(e,n)}resetSize(){this.#f.resetSize(),this.#U()}get maximized(){return this.#T}set maximized(e){this.setMaximized(e)}setMaximized(e){e?this.setAttribute("maximized",""):this.removeAttribute("maximized")}toggleMaximized(){this.setMaximized(!this.#T)}#ct(){return this.#C().maximizes!==null&&!window.matchMedia(Ch).matches}#zt(e){let n=e&&this.#ct()&&!this.collapsed;if(e&&!n){this.removeAttribute("maximized");return}n!==this.#T&&(this.#T=n,this.#R&&(n?this.#f.enterMaximized():this.#f.leaveMaximized(),this.#U()),this.#ut(),this.#dt())}#dt(){!this.#R||this.#T===this.#_e||(this.#_e=this.#T,this.#j(Kl,{maximized:this.#T}))}#Fe(){let e=this.#ct();e||this.setMaximized(!1);let n=this.#me;n!==null&&(e?n.button.isConnected||n.before.before(n.button):n.button.remove())}#ut(){let e=this.#me?.button;if(e===void 0)return;let n=this.#T?this.#t.restore:this.#t.maximize;e.title=n,e.setAttribute("aria-label",n),uE(e,this.#T?yp:hi)}#Le(){let e=this.#Ne;if(e===null)return;let n=Ww(this.getAttribute("data-collapse-icon"),this.getAttribute("placement"),this.getAttribute("data-side"));uE(e,n)}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")??"",n=this.#ft()==="dark"?"light":"dark";this.setAttribute("theme",dE(e,n)),this.#N.writePreference(cE,n)}#ht(e,n){this.#Ae=n;let r=this.#R,o=this.#N.conversationNamespace(e),i=this.#N.conversationNamespace(n);if(e===""){Qe.adopt(o,i),r&&this.#pt(i);return}this.#Q={},Qe.purge(o),r&&this.#pt(i),this.#D.forgetWaivers(),this.#de(),this.#ze(),this.#se={},this.#u.value="",this.#je(),this.#Ce(!1),this.#wt([...this.#I.keys()],!0),r&&(this.#J.dispose(),this.#J.wire(),this.#h.adoptActiveThread(),this.#h.rehydrate("rescope"),this.#h.refreshDrawer())}#pt(e){let n=this.#N.rescopeStore(this.#at(),e);n!==null&&(this.conversationStore=n,this.#it())}#ft(){let e=(this.getAttribute("theme")??"").split(/\s+/);if(e.includes("dark"))return"dark";if(e.includes("light"))return"light";let n=getComputedStyle(this).colorScheme.split(/\s+/),r=n.includes("dark");return r!==n.includes("light")?r?"dark":"light":(r||e.includes("auto"))&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}#mt(){let e=this.#ft()==="dark";this.#W.replaceChildren(Ar("theme","theme-icon",e?bp:vp,null))}openThreads(e={}){let n=this.#C().collapseTo,r=e.anchor??this.#lt(),o=this.getAttribute("placement")!=="embedded";this.collapsed&&n==="bar"?this.#E.append(this.#g.element):this.collapsed&&n==="none"&&r!==null&&o?(this.#ue=r,this.#L.append(this.#g.element),this.#gt()):(this.collapsed&&n==="none"&&console.warn(o?'<ag-ui-chat>: openThreads() under collapse-to="none" needs an anchor to open beside; pass openThreads({ anchor }) or set the anchor attribute.':'<ag-ui-chat>: openThreads() under placement="embedded" and collapse-to="none" has no popover: the collapsed chat is not drawn. Expand it first.'),this.#Be()),this.#h.openThreads()}#gt(){let e=this.#ue;if(e===null||this.#g.element.parentNode!==this.#L)return;let n=e.getBoundingClientRect(),r=document.documentElement.clientWidth,o=document.documentElement.clientHeight,i=n.top+n.height/2<o/2,a=Math.min(GC,r-2*Bn),s=Math.min(Math.max(Bn,r-n.right),r-Bn-a),l=(i?o-n.bottom:n.top)-2*Bn;this.style.setProperty("--_threads-top",i?`${n.bottom+Bn}px`:"auto"),this.style.setProperty("--_threads-bottom",i?"auto":`${o-n.top+Bn}px`),this.style.setProperty("--_threads-right",`${Math.max(Bn,s)}px`),this.style.setProperty("--_threads-room",`${Math.max(0,l)}px`)}#Be(e=null){let n=this.#g.element.parentNode;if(n!==e&&(n===this.#E||n===this.#L)){this.#g.close(),this.#p.insertBefore(this.#g.element,this.#_.element),this.#ue=null;for(let r of["top","bottom","right","room"])this.style.removeProperty(`--_threads-${r}`)}}openCheckpoints(){this.#h.openCheckpoints()}closeThreads(){this.#g.close()}closeCheckpoints(){this.#_.close()}switchThread(e){return this.#R?this.#h.switchThread(e):Promise.resolve()}deleteThread(e){this.#R&&this.#h.deleteThread(e)}toggleCheckpoints(){if(this.#_.open_){this.#_.close();return}this.openCheckpoints()}newChat(){if(!this.#R){this.#ke=!0;return}this.#de(),this.#h.reapUnsent(),this.#ze(),this.#h.startThread(),this.#Ce(!1),this.#xt(this.#h.threadId,"new"),this.collapsed||this.#u.focus({preventScroll:!0})}#ze(){this.#vt(),this.#re.length=0,this.#F=null}#vt(){this.#ee=null,this.#fe.detach(),this.#ve={},this.#bt(),this.#h.forgetRestored()}#bt(){this.#et.end(),this.#v.releaseTurn(),this.#n.clear(),this.#v.forgetCards(),this.#r.clearBlocks(),this.#i.forget(),this.#y.tray?.clear(),this.removeAttribute("data-composer-settling"),this.removeAttribute("data-restoring"),this.#v.empty()}async retryLastTurn(){if(this.#Ye())return!1;let e={};this.#A=e;try{let n=this.#Je(),r=n.truncateToLastUser();if(r===null||this.#A!==e)return!1;this.#bt();for(let o of r)if(this.#h.replay(o),this.#A!==e)return!1;return await n.resume(),!0}finally{this.#qe(e)}}appendMessage(e,n){return this.#v.append(e,n)}#Dt(){let{signal:e}=this.#O;this.#p.className="chat",this.#p.setAttribute("part","panel");let n=this.#Et(),r=this.getAttribute("data-theme-toggle")!==null,{header:o,checkpoints:i,maximize:a,collapse:s}=Vw({host:this,title:this.#S,titleText:n,iconUrl:this.getAttribute("data-icon-url"),strings:this.#t,withCheckpoints:this.#h.runs()!==null,themeToggle:r?this.#W:null,signal:e,onHistory:()=>this.openThreads(),onCheckpoints:()=>this.toggleCheckpoints(),onNewChat:()=>this.newChat(),onCollapse:()=>this.toggleCollapsed(),onMaximize:()=>this.toggleMaximized(),onToggleTheme:()=>this.toggleTheme()});r&&this.#mt(),this.#f.enablePanelDrag(o),this.#me={button:a,before:s},this.#Ne=s,this.#Le(),this.#Fe(),this.#ut(),window.matchMedia(Ch).addEventListener("change",()=>this.#Fe(),{signal:e}),jx({messages:this.#b,jumpButton:this.#c,emptyWrap:this.#pe,greetingText:this.#K,starters:qx(this,this.#t,v=>{this.sendMessage(v)}),strings:this.#t}),this.#rt(),this.#d.mount(e),this.#v.mountScroller(this.#c,e),this.#l.mount(),this.#b.append(this.#pe),this.#v.updateEmptyState();let l=Dy({input:this.#u,send:this.#w,attachButton:this.#Z,fileInput:this.#xe,voiceSlot:this.#ae,place:this.#le.element,hint:this.#M,queuedRow:this.#G,attachSlot:this.#te,strings:this.#t,signal:e,onKeydown:v=>this.#Ht(v),onInput:()=>this.#je(),onSend:()=>{if(this.#V){this.#de();return}this.#Xe()},onFilesPicked:()=>this.#y.onFilesPicked()});this.#le.mount(e,this.#t),this.#u.addEventListener("focus",()=>this.refreshPlace(),{signal:e}),window.addEventListener("popstate",()=>this.refreshPlace(),{signal:e}),window.addEventListener("hashchange",()=>this.refreshPlace(),{signal:e}),this.refreshPlace();let c=document.createElement("slot");c.name="above-composer";let d=document.createElement("slot");d.name="footer",this.#m.className="messages-wrap",this.#m.replaceChildren(this.#b,this.#c,this.#d.button),this.#p.replaceChildren(o,this.#m,this.#x.palette,this.#x.chips,this.#M,this.#G,this.#te,c,l,d,this.#g.element,this.#_.element),this.#p.addEventListener("pointerdown",v=>{if(!this.#_.open_)return;let f=v.composedPath();f.includes(this.#_.element)||f.includes(i)||this.#_.close()},{signal:e}),jw({launcher:this.#H,badge:this.#P,railLabel:this.#q,bar:this.#E,barHistory:this.#k,barPlace:this.#le.barElement,titleText:n,iconUrl:Yw(this),strings:this.#t,signal:e,onOpen:()=>this.setCollapsed(this.#C().collapseTo==="bar"&&!this.collapsed),onHistory:()=>{this.#g.isOpen()?this.#g.close():this.openThreads()}}),document.addEventListener("pointerdown",v=>{let f=this.#g.element.parentNode;if(!this.#g.isOpen()||f!==this.#E&&f!==this.#L)return;let p=v.composedPath(),b=f===this.#E?[f]:[f,this.#ue];p.some(T=>b.includes(T))||this.#g.close()},{signal:e}),window.addEventListener("resize",()=>this.#gt(),{signal:e}),this.#f.enableLauncherDrag(e),this.#f.mountResizeGrips(this.#p),this.#o=Zw(this.#a,this.#s);let h=this.#f.probe;h.className="viewport-probe",h.setAttribute("aria-hidden","true"),h.style.borderRadius="var(--_viewport-inset-top) var(--_viewport-inset-right) var(--_viewport-inset-bottom) var(--_viewport-inset-left)",h.style.transition="border-radius 1ms",this.#L.className="threads-popover",this.#a.replaceChildren(h,this.#l.region,this.#p,this.#E,this.#L)}#Ze(){this.#H.setAttribute("aria-expanded",String(!this.collapsed));let e=this.unread;this.#P.textContent=e>9?"9+":String(e),this.#P.hidden=e===0||!this.collapsed||!qw(this);let n=!this.collapsed&&this.#C().collapseTo==="bar"?this.#t.collapse:this.#P.hidden?this.#t.expand:te(this.#t.expandUnread,{count:e});this.#H.setAttribute("aria-label",n),this.#H.title=n}#j(e,n){this.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,composed:!0}))}#Re(e){this.#Ze(),this.#j(Ql,{unread:this.unread,threadIds:e})}#$t(e){if(this.#Ve(e)){this.conversationStore.markRead?.(e);return}this.#I.set(e,(this.#I.get(e)??0)+1),this.#Re([e])}#Ve(e){return!this.collapsed&&e===this.#Me&&e===this.#h.threadId}#yt(){let e=this.#Me;return e===null||!this.#Ve(e)||!this.#I.delete(e)?[]:(this.conversationStore.markRead?.(e),[e])}#wt(e,n=!1){let r=e.filter(o=>this.#I.delete(o));(r.length>0||n)&&this.#Re(r)}#Ut(e){let n=[];for(let{threadId:r,unread:o}of e)o!==!0||this.#I.has(r)||(this.#Ve(r)?this.conversationStore.markRead?.(r):(this.#I.set(r,1),n.push(r)));n.length>0&&this.#Re(n)}#je(){this.#x.onInput(this.#u.value),this.#M.hidden=!0,tn(this.#u),this.#F=null}#Ht(e){if(this.#x.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#V){e.preventDefault(),this.#de();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#Xe();return}this.#Gt(e)}#Gt(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#x.isOpen())return;let r=this.#re;if(r.length===0||(this.#u.value!==this.#oe&&(this.#F=null),this.#F===null&&(!n||this.#u.value!=="")))return;let o=this.#F===null?0:this.#F+(n?1:-1);o>=r.length||(e.preventDefault(),this.#F=o<0?null:o,this.#u.value=o<0?"":r[o],this.#oe=this.#u.value,this.#u.setSelectionRange(this.#u.value.length,this.#u.value.length),tn(this.#u))}#de(){this.#X.length=0,this.#De(),this.#Ue.abort(),this.#ee?.cancel(),this.#A=null,this.#h.stopContinuation()}#xt(e,n){let r={threadId:e,previousThreadId:this.#Me,reason:n};this.#Me=e;let o=this.#yt();o.length>0&&this.#Re(o),this.refreshPlace(),this.#ye=this.#h.restored;let i=this.#St();this.#j(rc,r),i&&this.#Tt(),(n==="switch"||n==="restore"&&this.conversationStore instanceof Qe)&&this.#h.refreshDrawer()}#Et(){let e=this.getAttribute("title-text");return e!==HC?e??this.#t.title:this.#we.title===""?this.#t.title:this.#we.title}#_t(){this.#S.textContent=this.#Et(),this.#q.textContent=this.#S.textContent}#St(){let e=this.#h.threadId,n=this.#$e.get(e)??Pr(this.#ye,o=>this.#ce.title(o)),r=this.#we;return n===r.title&&(e===r.threadId||n==="")?!1:(this.#we={threadId:e,title:n},this.#_t(),!0)}#Tt(){this.#j(oc,{...this.#we})}#We(){this.#St()&&this.#Tt()}#Ft(e){let n=this.#h.threadId,r=e.find(i=>i.threadId===n);r===void 0||this.#ye.length===0||[Pr(this.#ye),UC(this.#ye),$C].includes(r.title)||(this.#$e.set(n,r.title),this.#We())}#Ce(e){let n=this.#V&&!e;this.#V=e,e&&(this.#A=null);let r=e?this.#t.stop:this.#t.send;this.#w.title=r,this.#w.setAttribute("aria-label",r),this.#w.dataset.state=e?"running":"idle",this.toggleAttribute("data-running",e),n&&this.#Ke()}#qe(e){this.#A===e&&(this.#A=null,this.#Ke())}#Ye(){return this.#V||this.#A!==null||this.#h.continuation!==null}#Ke(){if(this.#V||this.#h.continuation!==null)return;let e=this.#X.shift();this.#De(),e!==void 0&&this.sendMessage(e)}#De(){this.#G.replaceChildren(),this.#G.hidden=this.#X.length===0;for(let[e,n]of this.#X.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=te(this.#t.removeQueued,{text:n}),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#X.splice(e,1),this.#De()}),this.#G.appendChild(r)}}#kt(e){e!==""&&this.#re[0]!==e&&this.#re.unshift(e),this.#F=null}async#Xe(){let e=this.#u.value.trim(),n=this.#y.tray?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#kt(e),this.#Ye()){e!==""&&(this.#X.push(e),this.#De(),this.#u.value="",tn(this.#u));return}this.#u.value="",tn(this.#u),this.#y.tray?.hasPending()===!0&&this.#v.appendNotice("\u{1F4CE}",te(this.#t.attachmentsStillUploading,{n:this.#y.tray.pendingCount()}),"attachment-pending"),this.#y.tray?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(e===""&&n.length===0)return!1;let r=this.#Qe;if(r!==null&&this.#A===r.hold){let i={};return this.#A=i,await r.restored,this.#A!==i?!1:(this.#A=null,this.sendMessage(e,n))}if(this.#Ye())return!1;let o={};this.#A=o;try{if(this.#v.isEmpty()&&this.setAttribute("data-composer-settling",""),this.#At(e,n),this.#A!==o)return!1;let i=this.endpoint!=="";return await this.#Bt(e,n),i}finally{this.#qe(o)}}#At(e,n){let r=this.appendMessage(We.USER,e);n.length>0&&r.appendChild(Ns(n)),this.#j(Yl,{content:e,attachments:n})}attachFile(e){return this.#y.attach(e)}async#Bt(e,n){if(this.endpoint===""){console.error('<ag-ui-chat>: no endpoint is set, so this message was not sent and no request was made. Point the element at your AG-UI mount with the endpoint attribute (endpoint="/agent/"), or assign chat.endpoint before sending.'),this.#v.appendNotice("\u26A0",this.#t.notConnected,"not-connected");return}await this.#Je().send(e,n)}#Je(){return this.#ee===null&&(this.#ee=this.#It({endpoint:this.endpoint,initialMessages:this.#h.restored,follows:[]})),this.#ee}#It(e){let n=this.#h.threadId,r=this.#Q,o=this.agentFactory({endpoint:e.endpoint,headers:this.#He(),getHeaders:()=>this.#He(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:n,initialMessages:e.initialMessages,initialState:this.#se});return new qo({agent:o,handlers:this.#fe.forClient(n),getTools:()=>(this.refreshPlace(),this.#$.advertise()),getContext:()=>this.#D.buildContext(),executeTool:i=>this.#D.execute(i),resolveInterrupts:i=>this.#D.resolveInterrupts(i),onPersist:i=>{if(r!==this.#Q)return;let a=[...e.follows,...i];this.conversationStore.saveMessages(n,a),n===this.#h.threadId&&(this.#ye=a,this.#We()),e.onSaved?.(a)},onStateChanged:i=>{r===this.#Q&&this.#Zt(i)},connectionLostMessage:this.#t.connectionLost,unfinishedMessage:this.#t.callNotFinished,declinedMessage:this.#t.declinedAction,maxToolRounds:iE(this)})}#Zt(e){this.#se={...e},this.#j(ec,{state:this.#se})}#Rt(e,n){this.#v.appendNotice("\u2922",e,"surface",n===null?void 0:{label:this.#t.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#r.has(pi)&&!this.#$.has(Rs);e.includes("activity")&&this.registerActivityRenderer({type:pi,render:r=>{let o=Sr(r);return o===null?null:So(o)},removedNotice:this.#t.chartUndrawable}),e.includes("tool")&&this.registerTool(zy()),n&&this.isConnected&&this.reload()}registerActivityRenderer(e){this.#r.register(e)}get unhandledActivityTypes(){return this.#r.unhandledTypes()}};function uE(t,e){for(let n of t.querySelectorAll("slot"))n.innerHTML=e}function ZC(t){let e=t?.removed;return typeof e=="number"?e:null}function VC(){let t=customElements.get(Hr);if(t===void 0)customElements.define(Hr,Lr);else if(t!==Lr)throw new Error(`<${Hr}> is already defined by another class: a second copy of this package, or another package, is on the page`)}async function jC(t,e,n={}){await zt(t),await Tc(t,{...n,flashMs:n.flashMs??0}),await _c(t,e,n)}async function WC(t,e={}){await zt(t),await Sc(t,e)}async function qC(t,e={}){await zt(t),await kc(t,e)}async function YC(t,e,n={}){await zt(t),await Ac(t,e,n)}async function KC(t,e,n={}){await zt(t),await Ic(t,e,n)}function XC(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Wr(t,!!e):dn(t,String(e)),qr(t)}var JC="0.1.0";export{tc as ATTACHMENT_EVENT,Lr as AgUiChat,qo as AgUiClient,Xl as BAR_HEIGHT_EVENT,pi as CHART_ACTIVITY_TYPE,Rs as CHART_TOOL_NAME,gi as CHAT_CORNERS,uc as COMPACTION_ACTIVITY_TYPE,ic as CUSTOM_AGENT_EVENT,Ao as CheckpointMenu,Vr as ClientToolRegistry,wl as ConnectionLostError,pe as DEFAULT_UI_STRINGS,Jl as DOCK_WIDTH_EVENT,Hr as ELEMENT_TAG,sc as FEEDBACK_EVENT,cc as INVALIDATE_CUSTOM_NAME,ac as INVALIDATE_EVENT,hc as LOAD_CAPABILITY_TOOL,Kl as MAXIMIZE_EVENT,FA as MAX_QUOTE_CHARS,yC as MAX_SUGGESTIONS,wC as MAX_SUGGESTION_CHARS,Qn as MAX_TOOL_ROUNDS,cn as MESSAGE_ACTIONS,We as MESSAGE_ROLE,Kr as PAGE_ACTIONS,nc as RUN_FINISHED_EVENT,Jo as RemoteConversationStore,Io as RunIndex,ec as STATE_EVENT,Yl as SUBMIT_EVENT,lc as SUGGESTIONS_ACTIVITY_TYPE,Qe as SessionStorageStore,rc as THREAD_EVENT,oc as THREAD_TITLE_EVENT,ci as TOGGLE_EVENT,J as TOOL_CALL_STATUS,Mt as TOOL_DISPLAY,Pt as TOOL_GROUP_DISPLAY,qe as TOOL_OUTCOME,Po as ToolCallCard,Ql as UNREAD_EVENT,JC as VERSION,di as X_CONFIRM_KEY,Gr as X_DESTRUCTIVE_KEY,Fr as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,Bu as asQuote,Qu as attachMessageActions,Zu as attachQuoteOffer,Sr as chartSpecFrom,WC as clickElement,fc as createChatSurfaceTools,kh as createHttpAgent,Rc as createPageActionTools,Cc as createPageMapContext,Nc as createPageStateTools,Oc as createRouteTools,VC as defineChat,jC as fillField,u_ as flash,Tc as focusWithFlash,Sc as highlightThenClick,Hp as isChatCorner,$u as isDestructive,As as isNavigates,Ou as mergeUiStrings,rl as messageActionBar,Vu as messageAttachments,Pu as parseToolCatalog,yi as prefersReducedMotion,qC as pressButton,kc as pressThenClick,Wo as prettifyToolName,To as quotableSelection,ko as relativeTime,So as renderChart,Vo as renderMarkdown,jo as renderSuggestionChips,Lu as requestApproval,Du as requestConfirmation,Mu as requestQuestion,zt as scrollIntoCenterView,YC as selectControl,Ac as selectOption,XC as setControlValue,Wr as setNativeChecked,dn as setNativeValue,xc as showHighlightOverlay,Wx as suggestionPrompts,KC as toggleCheckbox,Ic as toggleControl,Ro as toolStatusFromOutcome,Fu as transcribeAudio,_c as typeInto,Hu as uploadAttachment};
|
|
5687
|
+
Please report this to https://github.com/markedjs/marked.`,t){let r="<p>An error occurred:</p><pre>"+at(n.message+"",!0)+"</pre>";return e?Promise.resolve(r):r}if(e)return Promise.reject(n);throw n}}},Gn=new _h;function me(t,e){return Gn.parse(t,e)}me.options=me.setOptions=function(t){return Gn.setOptions(t),me.defaults=Gn.defaults,Mx(me.defaults),me};me.getDefaults=fh;me.defaults=Fn;function hC(...t){return Gn.use(...t),me.defaults=Gn.defaults,Mx(me.defaults),me}me.use=hC;me.walkTokens=function(t,e){return Gn.walkTokens(t,e)};me.parseInline=Gn.parseInline;me.Parser=vt;me.parser=vt.parse;me.Renderer=hl;me.TextRenderer=Eh;me.Lexer=gt;me.lexer=gt.lex;me.Tokenizer=Cr;me.Hooks=Go;me.parse=me;var X4=me.options,J4=me.setOptions,Q4=me.walkTokens,eH=me.parseInline;var tH=vt.parse,nH=gt.lex;var pC=new _h({gfm:!0,breaks:!0}),Bx=["a","p","br","strong","em","b","i","u","s","del","code","pre","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","hr","span","table","thead","tbody","tr","th","td"],Zx=["href","title","class","target","rel"],Vx={ALLOWED_TAGS:Bx,ALLOWED_ATTR:Zx,ALLOW_DATA_ATTR:!1,ALLOW_ARIA_ATTR:!1},fC={...Vx,ALLOWED_TAGS:[...Bx,"img"],ALLOWED_ATTR:[...Zx,"src","alt","width","height"]},mC=/^language-[A-Za-z0-9_+#.-]+$/,gC=new Set(["CODE","PRE"]);function vC(t){t.nodeName==="A"&&t.hasAttribute("href")?(t.setAttribute("target","_blank"),t.setAttribute("rel","noopener noreferrer")):(t.removeAttribute("target"),t.removeAttribute("rel"));let e=t.getAttribute("class");if(e===null)return;let n=gC.has(t.nodeName)?e.split(/\s+/).filter(r=>mC.test(r)):[];if(n.length===0){t.removeAttribute("class");return}t.setAttribute("class",n.join(" "))}var Sh;function bC(){if(Sh===void 0){let t=Ex();t.addHook("afterSanitizeAttributes",vC),Sh=t}return Sh}function Vo(t,e){let n=e?.allowImages===!0,r=pC.parse(t,{async:!1});return bC().sanitize(r,n?fC:Vx).trim()}var pl=class{#e;#t=null;#n=0;#r="";#i=null;constructor(e){this.#e=e}get deltas(){return this.#n}countDelta(){this.#n+=1}queue(e){this.#r=e,this.#a(),this.#i===null&&(this.#i=requestAnimationFrame(()=>{this.#i=null,this.into(this.#r)}))}into(e){this.#i!==null&&(cancelAnimationFrame(this.#i),this.#i=null),this.#r=e;let n=this.#a();return n.innerHTML=Vo(e,{allowImages:this.#e.allowImages()}),this.#e.follow(),n}end(){this.#i!==null&&this.into(this.#r),this.#t=null}#a(){return this.#t===null&&(this.#t=this.#e.openBubble(),this.#n=0),this.#t}};function jx(t){let{messages:e,jumpButton:n,emptyWrap:r,strings:o}=t;e.className="messages",e.setAttribute("part","messages"),e.setAttribute("role","log"),e.setAttribute("aria-live","off"),e.setAttribute("aria-label",o.conversation),n.className="jump-latest",n.type="button",n.setAttribute("part","jump-latest"),n.textContent=o.jumpToLatest,r.className="empty",r.setAttribute("part","empty");let i=document.createElement("div");i.className="greeting",i.setAttribute("part","greeting");let a=document.createElement("slot");a.name="greeting",a.append(t.greetingText),i.append(a);let s=document.createElement("slot");s.name="empty",t.starters!==null&&s.append(t.starters),r.replaceChildren(i,s)}var yC=4,wC=120;function Wx(t){if(typeof t!="object"||t===null)return null;let e=t.prompts;if(!Array.isArray(e))return null;let n=e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r!==""&&r.length<=120).slice(0,4);return n.length===0?null:n}function jo(t,e,n){let r=Wx(t);if(r===null)return null;let o=document.createElement("div");o.className="suggestions",o.setAttribute("part","suggestions"),o.setAttribute("role","group"),o.setAttribute("aria-label",e.suggestions);for(let i of r){let a=document.createElement("button");a.type="button",a.className="suggestion-chip",a.setAttribute("part","suggestion-chip"),a.textContent=i,a.addEventListener("click",()=>n(i)),o.appendChild(a)}return o}function qx(t,e,n){let r=t.getAttribute("data-starters");if(r===null)return null;let o;try{o=JSON.parse(r)}catch{return console.warn(`<ag-ui-chat>: data-starters is not valid JSON, so no starters are shown. It takes an array of strings, e.g. data-starters='["Summarise this page"]'.`),null}return jo({prompts:o},e,n)}function fl(t,e){for(let n of Array.from(t.querySelectorAll("pre"))){let r=n.querySelector("code");r===null||n.querySelector(".code-copy")!==null||(n.classList.add("has-copy"),n.append(xC(r,e)))}}function xC(t,e){let n=t.textContent,r=document.createElement("button");return r.type="button",r.className="code-copy",r.setAttribute("part","code-copy"),r.textContent=e.copyCode,r.title=e.copyCode,r.setAttribute("aria-label",e.copyCode),r.addEventListener("click",()=>{EC(n).then(o=>{_C(r,o?e.copied:e.copyFailed,e)})}),r}async function EC(t){let e=navigator.clipboard;if(e===void 0)return!1;try{return await e.writeText(t),!0}catch{return!1}}function _C(t,e,n){t.textContent=e,t.dataset.state=e===n.copied?"copied":"failed",setTimeout(()=>{t.textContent=n.copyCode,delete t.dataset.state},1500)}function Wo(t){let e=t.replace(/[._-]+/g," ").trim();return e===""?t:e.charAt(0).toUpperCase()+e.slice(1)}var Yx=1e3,ml=class{element;#e;#t;#n;#r;#i;#a;#o=0;#s=!1;#l=!1;constructor(e=pe,n=()=>performance.now()){this.#r=e,this.#i=n,this.#a=n(),this.element=document.createElement("div"),this.element.className="thoughts",this.element.setAttribute("part","thoughts"),this.element.setAttribute("data-streaming",""),this.#n=document.createElement("button"),this.#n.type="button",this.#n.className="thoughts-toggle",this.#n.setAttribute("part","thoughts-toggle"),this.#n.setAttribute("aria-expanded","true"),this.#e=document.createElement("span"),this.#e.className="thoughts-label",this.#e.setAttribute("part","thoughts-label"),this.#e.textContent=e.thinking,this.#t=document.createElement("pre"),this.#t.className="thoughts-body",this.#t.setAttribute("part","thoughts-body"),this.#t.hidden=!0,this.#n.addEventListener("click",()=>{this.#d(!this.#s)}),this.element.append(this.#e,this.#t)}begin(){this.#a===null&&(this.#a=this.#i(),this.element.setAttribute("data-streaming",""),this.#e.textContent=this.#r.thinking)}stream(e){this.#t.textContent=e,this.#c(e.trim()!=="")}settle(){this.#a!==null&&(this.#o+=this.#i()-this.#a,this.#a=null,this.element.removeAttribute("data-streaming"),this.#e.textContent=this.#o<Yx?this.#r.thoughts:te(this.#r.thoughtFor,{seconds:Math.round(this.#o/Yx)}))}collapse(){this.settle(),!this.#s&&this.#d(!0)}#c(e){e!==this.#l&&(this.#l=e,e?(this.#n.append(this.#e),this.element.prepend(this.#n)):(this.#n.remove(),this.element.prepend(this.#e)),this.#d(this.#s))}#d(e){this.#s=e,this.#t.hidden=e||!this.#l,this.#n.setAttribute("aria-expanded",String(!e))}};var SC=new Set([J.PENDING,J.DEFERRED]),TC=`.tool-call-subagent > .subagent:is(${[Et.STARTED,Et.TOOL_CALL,Et.TOOL_RESULT].map(t=>`[data-phase="${t}"]`).join(", ")})`,kC=["data-status","data-asking","data-has-result","data-phase","data-agent"];function AC(t,e){let n=e===Pt.MINIMAL;return!n&&e!==Pt.INLINE&&t.hasAttribute("data-has-args")||!n&&t.hasAttribute("data-has-result")||t.getAttribute("data-status")===J.DEFERRED||t.querySelector(".tool-call-subagent > *")!==null}var gl=class{element;#e;#t;#n;#r;#i;#a;#o=[];#s=!1;constructor(e,n){this.#e=e,this.#t=n,this.element=document.createElement("div"),this.element.className="tool-group",this.element.setAttribute("part","tool-group"),this.element.setAttribute("data-open","false"),this.#r=document.createElement("button"),this.#r.type="button",this.#r.className="tool-group-head",this.#r.setAttribute("part","tool-group-head"),this.#r.setAttribute("aria-expanded","false");let r=document.createElement("span");r.className="tool-group-icon",r.setAttribute("part","tool-group-icon"),r.setAttribute("aria-hidden","true"),this.#i=document.createElement("span"),this.#i.className="tool-group-label",this.#i.setAttribute("part","tool-group-label"),this.#a=document.createElement("span"),this.#a.className="tool-group-meta",this.#a.setAttribute("part","tool-group-meta");let o=document.createElement("span");o.className="tool-group-chevron",o.setAttribute("aria-hidden","true"),this.#r.append(r,this.#i,this.#a,o),this.#r.addEventListener("click",()=>{this.setOpen(this.element.getAttribute("data-open")!=="true")}),this.#n=document.createElement("div"),this.#n.className="tool-group-list",this.#n.setAttribute("part","tool-group-list"),this.element.append(this.#r,this.#n),new MutationObserver(()=>{this.refresh()}).observe(this.#n,{attributes:!0,attributeFilter:[...kC],subtree:!0})}add(e,n){let r=this.#o.filter(i=>i.name===n).length+1,o=n;if(r>1){let i=document.createElement("span");i.className="tool-call-repeat",i.setAttribute("part","tool-card-repeat"),i.textContent=te(this.#e.toolStepRepeat,{n:r}),e.querySelector(".tool-call-name")?.after(i),o=`${n} ${i.textContent}`}this.#o.push({element:e,name:n,label:o}),this.#n.append(e),this.refresh()}setOpen(e){this.element.setAttribute("data-open",String(e)),this.#r.setAttribute("aria-expanded",String(e))}#l(e){if(this.#r.disabled=!e,e){this.#r.setAttribute("aria-expanded",this.element.getAttribute("data-open"));return}this.element.setAttribute("data-open","false"),this.#r.removeAttribute("aria-expanded")}reveal(){this.#s=!0,this.setOpen(!0)}#c(){for(let{element:e}of this.#o){let n=e.getAttribute("data-status")===J.PENDING?e.querySelector(TC):null;if(n!==null){let r=n.getAttribute("data-agent");return r===null?this.#e.subAgentWorking:te(this.#e.subAgentDelegatedTo,{agent:r})}}return null}refresh(){let e=this.#e,n=this.#o,r=n.map(k=>k.element.getAttribute("data-status")??""),o=n.filter((k,E)=>SC.has(r[E])),i=k=>r.filter(E=>E===k).length,a=i(J.ERROR),s=i(J.DECLINED),l=i(J.DEFERRED),c=n.filter(k=>k.element.hasAttribute("data-asking")).length,d=l+c,h=n.length;l>0&&!this.#s?(this.#s=!0,this.setOpen(!0)):l===0&&(this.#s=!1);let v="done";d>0?v="waiting":o.length>0?v="running":a>0&&(v="error"),this.element.setAttribute("data-state",v),this.element.setAttribute("part",`tool-group tool-group-${v}`),this.element.setAttribute("data-count",String(h));let f=h===1?n[0]:void 0;if(this.#l(f===void 0||AC(f.element,this.#t())),f!==void 0)this.#i.textContent=f.label;else{let k=v==="waiting"?e.toolGroupSteps:v==="running"?e.toolGroupWorking:e.toolGroupWorked;this.#i.textContent=te(k,{count:h})}let p=[],b=this.#c(),T=o[0];d>0?p.push(te(e.toolGroupWaiting,{count:d})):b!==null?p.push(b):T!==void 0&&h>1&&p.push(T.label),a>0&&p.push(te(e.toolGroupFailed,{count:a})),s>0&&p.push(te(e.toolGroupDeclined,{count:s})),this.#a.replaceChildren(...p.map(k=>{let E=document.createElement("span");return E.className="tool-group-note",E.textContent=k,E})),this.#a.hidden=p.length===0}};function Kx(t){return t===Mt.GROUPED}function vl(t,e){try{return t()}catch(n){return console.warn(`ag-ui-chat: render failed for ${e}`,n),null}}function Xx(t,e){for(let n of Array.from(t.childNodes))n.nodeType===Node.TEXT_NODE?e.push({node:n,parent:t}):Xx(n,e)}function Jx(t){let e=[];Xx(t,e);let n=0;for(let{node:r,parent:o}of e){let i=document.createDocumentFragment();for(let a of r.data.split(/(\s+)/)){if(a==="")continue;if(/\s/.test(a)){i.appendChild(document.createTextNode(a));continue}let s=document.createElement("span");s.className="word",s.style.setProperty("--ag-ui-word-index",String(n)),s.textContent=a,i.appendChild(s),n+=1}o.replaceChild(i,r)}}function Qx({viewport:t,onMissedContent:e}){let n=!0,r=!1,o=()=>t.scrollHeight-t.scrollTop-t.clientHeight<=4,i=d=>{d!==r&&(r=d,e(r))},a=()=>{t.scrollTop=t.scrollHeight},s=()=>{n=o(),n&&i(!1)},l=()=>{if(n){a();return}i(!0)};t.addEventListener("scroll",s,{passive:!0});let c=new ResizeObserver(()=>{n&&a()});return c.observe(t),{follow:l,jump:()=>{n=!0,i(!1),a()},following:()=>n,dispose:()=>{t.removeEventListener("scroll",s),c.disconnect()}}}var bl=class{#e;#t=new Map;#n=new Map;#r=new Map;#i=new Set;#a;#o=null;#s=null;#l=null;#c=new WeakMap;#d=new WeakMap;#m=new WeakMap;constructor(e){this.#e=e}mountScroller(e,n){e.addEventListener("click",()=>{this.jump()},{signal:n}),this.#a=Qx({viewport:this.#e.messages,onMissedContent:r=>{e.dataset.missed=String(r)}})}disposeScroller(){this.#a.dispose()}follow(){this.#a.follow()}jump(){this.#a.jump()}isEmpty(){return!this.#e.emptyWrap.hidden}card(e){return this.#t.get(e)}cards(){return this.#t.values()}forgetCard(e){this.#t.delete(e)}setCardElement(e,n){this.#n.set(e,n)}markServerSettled(e){this.#i.add(e)}isServerSettled(e){return this.#i.has(e)}collapseThoughts(){this.#l?.collapse()}settleThoughts(){this.#l?.settle()}closeGroup(){this.#s!==null&&this.#s.childElementCount===0&&(this.#s.remove(),this.updateEmptyState()),this.settleThoughts(),this.#s=null,this.#l=null}releaseTurn(){this.#s=null,this.#l=null,this.hidePending(),this.#t.clear()}forgetCards(){this.#i.clear(),this.#n.clear(),this.#r.clear()}holdRunning(e,n){this.#r.set(e,n)}setAsking(e,n){this.#r.get(e)?.setAsking(n)}empty(){this.#e.messages.replaceChildren(this.#e.emptyWrap),this.updateEmptyState()}append(e,n){let r=document.createElement("div");return r.className=`message message--${e}`,r.setAttribute("part",`message message-${e}`),e===We.ASSISTANT?(r.innerHTML=Vo(n,{allowImages:this.#e.allowImages()}),fl(r,this.#e.strings()),this.ensureGroup().appendChild(r)):(this.#s=null,r.textContent=n,this.#e.messages.appendChild(r)),this.updateEmptyState(),e===We.USER?this.jump():this.follow(),r}ensureGroup(){if(this.#s===null){let e=document.createElement("div");e.className="answer",e.setAttribute("part","answer"),this.#s=e,this.#e.messages.appendChild(e),this.updateEmptyState()}return this.#s}revealWords(e){this.#e.element.getAttribute("data-text-animation")==="word"&&Jx(e)}updateEmptyState(){this.#e.emptyWrap.hidden=this.#e.messages.childElementCount>1,this.#e.element.toggleAttribute("data-empty",!this.#e.emptyWrap.hidden)}appendStoppedNote(){let e=document.createElement("div");e.className="stopped-note",e.setAttribute("part","stopped"),e.setAttribute("role","status"),e.textContent=this.#e.strings().stopped,this.ensureGroup().appendChild(e),this.updateEmptyState(),this.follow()}showPending(){if(this.#o!==null)return;let e=document.createElement("div");e.className="pending",e.setAttribute("part","pending"),e.setAttribute("role","status"),e.setAttribute("aria-label",this.#e.strings().thinking);for(let n=0;n<3;n+=1){let r=document.createElement("span");r.className="pending-dot",e.appendChild(r)}this.#o=e,this.ensureGroup().appendChild(e),this.updateEmptyState(),this.follow()}hidePending(){this.#o?.remove(),this.#o=null}showThoughts(){if(this.#l===null){this.#l=new ml(this.#e.strings());let e=this.ensureGroup();e.insertBefore(this.#l.element,e.firstChild),this.updateEmptyState(),this.follow()}return this.#l}noticeIfSkillLoad(e){let n=ks(e);return n===null?!1:(this.appendNotice("\u2728",te(this.#e.strings().usingSkill,{name:n}),"skill"),!0)}appendNotice(e,n,r,o){this.ensureGroup().appendChild(Js(e,n,r,o)),this.updateEmptyState(),this.follow()}renderToolOutput(e,n){let r=vl(()=>e(n.args),`tool ${n.name}`);if(r===null)return;let o=this.#n.get(n.id),i=o?.closest(".tool-group");if(i==null)o?.after(r);else{let a=this.#d.get(i);a===void 0&&(a=document.createComment(""),i.after(a),this.#d.set(i,a));let s=r instanceof DocumentFragment?[...r.children]:[r];a.before(r);for(let l of s)this.#m.set(l,i)}this.afterGrew()}afterGrew(){this.updateEmptyState(),this.follow()}cardFor(e){let n=this.#t.get(e.id);if(n!==void 0)return n;let r=this.#e.resolveTool(e.name)?.parameters[Le],o=typeof r=="string"?r:this.#e.toolSummaries()[e.name]??this.#e.serverSummary(e.name)??Wo(e.name),i=new Po(e.name,e.args,o,this.#e.strings(),{formatPayload:a=>this.#e.formatToolPayload(a)});return this.#t.set(e.id,i),Kx(this.#e.toolDisplay())?this.#p().add(i.element,o):this.ensureGroup().appendChild(i.element),this.updateEmptyState(),this.follow(),i}refreshStepGroups(){for(let e of this.#e.messages.querySelectorAll(".tool-group"))this.#c.get(e)?.refresh()}revealStep(e){let n=e.element.closest(".tool-group");(n===null?void 0:this.#c.get(n))?.reveal()}#p(){let e=this.ensureGroup(),n=e.lastElementChild,r=n===null?void 0:this.#c.get(this.#m.get(n)??n);if(r!==void 0)return r;let o=new gl(this.#e.strings(),this.#e.toolGroupDisplay);return this.#c.set(o.element,o),n===null?e.prepend(o.element):n.after(o.element),o}};var yl=class{#e;#t=new Map;#n=new Set;#r=new Map;constructor(e){this.#e=e}register(e){this.#t.set(e.type,e),this.#n.delete(e.type)}has(e){return this.#t.has(e)}unhandledTypes(){return[...this.#n]}clearBlocks(){this.#r.clear()}draw(e,n,r){let o=this.#t.get(n);if(o===void 0){this.#n.add(n);return}let i=vl(()=>o.render(r),`activity ${n}`);if(i===null){this.#i(e,n,o.removedNotice,r);return}let a=this.#r.get(e);a===void 0?this.#e.ensureGroup().appendChild(i):a.replaceWith(i),this.#r.set(e,i),this.#e.afterTranscriptGrew()}#i(e,n,r,o){let i=this.#r.has(e);this.#r.get(e)?.remove(),this.#r.delete(e),console.warn(`ag-ui-chat: activity ${e} (${n}) was not drawable and has been removed. A chart's points must each be a finite JSON number; a numeric column serialised as a string (a Decimal, typically) is rejected rather than coerced.`,o),i&&r!==void 0&&this.#e.appendNotice("\u{1F4C9}",r,"chart-undrawable")}};var wl=class extends Error{constructor(e){super(e),this.name="ConnectionLostError"}},qo=class{#e;#t;#n;#r;#i;#a;#o;#s=new Set;#l;#c;#d;#m;#p=!1;constructor(e){this.#e=e.agent,this.#t=e.handlers,this.#n=e.getTools??(()=>[]),this.#r=e.getContext??(()=>[]),this.#i=e.executeTool??null,this.#a=e.resolveInterrupts??null,this.#o=e.onPersist??(()=>{}),this.#l=e.connectionLostMessage??"Connection lost",this.#c=e.unfinishedMessage??"Not finished: the run ended or moved on before this tool call returned a result.",this.#d=e.declinedMessage??"User declined the action.";let n=e.maxToolRounds??Qn;this.#m=n>=1?Math.floor(n):Qn,this.#w();let r=e.onStateChanged;r!==void 0&&this.#e.subscribe({onStateChanged:({state:o})=>{r(o)}})}get state(){return this.#e.state}setState(e){this.#e.setState({...e})}get running(){return this.#e.isRunning}get messages(){return this.#e.messages}async send(e,n=[]){this.#p=!1;let r={id:ke(),role:"user",content:e,...n.length>0?{metadata:{attachments:n}}:{}};this.#e.addMessage(r),this.#g(),await this.#b()}truncateToLastUser(){let e=[...this.#e.messages],n=-1;for(let[o,i]of e.entries())i.role==="user"&&(n=o);if(n===-1)return null;let r=e.slice(0,n+1);return this.#o(r),this.#e.setMessages(r),r}async resume(){this.#p=!1,await this.#b()}addToolResult(e,n){this.#e.addMessage({id:ke(),role:"tool",content:n,toolCallId:e}),this.#g()}cancel(){this.#p=!0,this.#e.abortRun()}async#b(){try{await this.#_(),this.#p&&this.#u()}catch(e){this.#p||IC(e)?this.#u():this.#t.onError(e instanceof Error?e.message:String(e))}finally{this.#t.onSettled()}}#u(){this.#g(),this.#t.onCancelled()}#w(){let e=this.#e.messages,n=e.map(RC);n.some((r,o)=>r!==e[o])&&this.#e.setMessages(n)}#S(e){let n=this.#e.messages,r=_s(n,o=>({id:ke(),role:"tool",content:this.#c,toolCallId:o,metadata:{outcome:qe.INTERRUPTED}}),e);r!==n&&(this.#e.setMessages([...r]),this.#g())}#x(e,n){for(let r of e){let o=r.toolCallId;o!==void 0&&n[r.id]?.status==="cancelled"&&this.#e.addMessage({id:ke(),role:"tool",content:this.#d,toolCallId:o,metadata:{outcome:qe.DENIED}})}this.#g()}#g(){this.#o(this.#e.messages)}async#_(){let e,n=new Set;for(let r=0;r<this.#m;r+=1){if(this.#p)return;let o=[],i={terminal:!1,errored:!1,interrupts:[]},a={tools:this.#n(),context:this.#r()};if(e!==void 0&&(a.resume=e),this.#S(n),this.#p||(await this.#e.runAgent(a,this.#h(o,i)),e=void 0,n=new Set,this.#g(),this.#p))return;if(!i.terminal)throw new wl(this.#l);if(i.errored)return;if(i.interrupts.length>0){if(this.#a===null)return;let l=await this.#a(i.interrupts);if(this.#p){this.#x(i.interrupts,l);return}e=ky(i.interrupts,l),n=new Set(i.interrupts.flatMap(({toolCallId:c})=>c??[]));continue}if(this.#i===null||o.length===0)return;let s=!1;for(let l of o){if(this.#p)return;let c=await this.#i(l);if(c!==null){if(c.halt===!0)return;this.#e.addMessage({id:ke(),role:"tool",content:c.content,toolCallId:l.id,...c.outcome===void 0?{}:{metadata:{outcome:c.outcome}}}),this.#g(),s=!0}}if(!s)return}}#h(e,n){let r=this.#t,o=this.#s,i=()=>this.#p,a=new Set,s;return{onRunInitialized(){r.onRunStart()},onRunStartedEvent({event:l}){s=l.runId},onTextMessageStartEvent({event:l}){o.has(l.messageId)&&console.warn(`<ag-ui-chat>: the server reused message id "${l.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:l}){r.onTextDelta(l)},onTextMessageEndEvent({event:l,textMessageBuffer:c}){o.add(l.messageId),r.onTextEnd(c,{messageId:l.messageId,...s===void 0?{}:{runId:s}})},onToolCallEndEvent({event:l,toolCallName:c,toolCallArgs:d}){let h={id:l.toolCallId,name:c,args:d};e.push(h),r.onToolCall(h)},onToolCallResultEvent({event:l}){let c=l.metadata?.outcome;r.onToolResult(l.toolCallId,rr(l.content),c)},onActivitySnapshotEvent({event:l,messages:c}){if(c.some(h=>h.id===l.messageId&&h.role==="activity")){r.onActivityChanged(l.messageId,l.activityType,l.content);return}r.onActivity(l.activityType,l.content,l.messageId)},onActivityDeltaEvent({event:l}){a.add(l.messageId)},onCustomEvent({event:l}){r.onCustomEvent(l.name,l.value)},onSubagentStartedEvent({event:l}){r.onSubAgentStarted(l.subagentRunId,l.name,l.parentToolCallId??null)},onSubagentFinishedEvent({event:l}){r.onSubAgentFinished(l.subagentRunId)},onSubagentErrorEvent({event:l}){r.onSubAgentError(l.subagentRunId,l.message)},onMessagesSnapshotEvent({event:l}){r.onMessagesSnapshot(l.messages)},onMessagesChanged({messages:l}){for(let c of a){let d=l.find(h=>h.id===c);d!==void 0&&d.role==="activity"&&r.onActivityChanged(c,d.activityType,d.content)}a.clear()},onReasoningStartEvent(){r.onReasoningStart()},onReasoningMessageContentEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningMessageEndEvent({reasoningMessageBuffer:l}){r.onReasoningDelta(l)},onReasoningEndEvent(){r.onReasoningEnd()},onRunFinishedEvent(l){n.terminal=!0,l.outcome==="interrupt"&&(n.interrupts=l.interrupts)},onRunErrorEvent({event:l}){n.terminal=!0,n.errored=!0,!i()&&r.onError(l.message)},onRunFinalized(){n.terminal=!0,r.onRunEnd()}}}};function IC(t){return t instanceof Error?t.name==="AbortError"||t instanceof TypeError&&/abort/i.test(t.message):!1}function RC(t){let{outcome:e,attachments:n,...r}=t;if(e===void 0&&n===void 0)return t;let o=r.metadata;return{...r,metadata:{...e===void 0?{}:{outcome:e},...n===void 0?{}:{attachments:n},...typeof o=="object"?o:{}}}}var Mr="thread",Th="threads",Yo="messages:",El="checkpoint:",Ko="minted:",CC=60,NC=100,OC="New conversation",MC=/^\/([A-Za-z0-9][\w.-]*)$/;function Xo(t,e,n={reported:!1}){try{sessionStorage.setItem(t,e)}catch{if(n.reported)return;n.reported=!0,console.warn("<ag-ui-chat>: the browser refused a sessionStorage write \u2014 the quota is full, or storage is disabled for this context. The conversation continues, but it will not survive a page reload. Deleting a long conversation from the history drawer frees the quota.")}}function xl(t){return t===""?xt:`${xt}@${t}`}var Qe=class{#e;#t={reported:!1};constructor(e=""){this.#e=xl(e)}static adopt(e,n){let r=`${xl(e)}:`,o=`${xl(n)}:`,i={reported:!1};for(let[a,s]of eE(r)){let l=sessionStorage.getItem(a),c=o+s;l!==null&&sessionStorage.getItem(c)===null&&Xo(c,l,i),sessionStorage.removeItem(a)}}static purge(e){for(let[n]of eE(`${xl(e)}:`))sessionStorage.removeItem(n)}threadId(){return sessionStorage.getItem(this.#o(Mr))??this.newThread()}newThread(){let e=ke();return this.#a(this.#o(Mr),e),this.#a(this.#o(Ko+e),"1"),e}isUnsent(e){return sessionStorage.getItem(this.#o(Ko+e))!==null&&sessionStorage.getItem(this.#o(Yo+e))===null}loadMessages(e){return Promise.resolve(this.#s(this.#o(Yo+e)))}saveMessages(e,n){this.#a(this.#o(Yo+e),JSON.stringify(n)),sessionStorage.removeItem(this.#o(Ko+e)),this.#n(e,n)}loadCheckpoint(e){return this.#s(this.#o(El+e))}saveCheckpoint(e,n){let r=this.#o(El+e);if(n===null){sessionStorage.removeItem(r);return}this.#a(r,JSON.stringify(n))}clear(e){sessionStorage.removeItem(this.#o(Yo+e)),sessionStorage.removeItem(this.#o(El+e)),sessionStorage.removeItem(this.#o(Ko+e)),this.#i(this.#r().filter(n=>n.threadId!==e)),sessionStorage.getItem(this.#o(Mr))===e&&sessionStorage.removeItem(this.#o(Mr))}listThreads(){let e=this.#r().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){this.#a(this.#o(Mr),e)}renameThread(e,n){let r=this.#r(),o=r.find(i=>i.threadId===e);o!==void 0&&(o.title=n,o.titleCustom=!0,this.#i(r))}#n(e,n){let r=this.#r(),o=r.find(s=>s.threadId===e),i=LC(n),a=Date.now();o===void 0?r.push({threadId:e,title:tE(n),titleCustom:!1,preview:i,updatedAt:a}):(o.preview=i,o.updatedAt=a,o.titleCustom||(o.title=tE(n))),this.#i(r)}#r(){return this.#s(this.#o(Th))??[]}#i(e){let n=this.#o(Th);if(e.length===0){sessionStorage.removeItem(n);return}this.#a(n,JSON.stringify(e))}#a(e,n){Xo(e,n,this.#t)}#o(e){return`${this.#e}:${e}`}#s(e){let n=sessionStorage.getItem(e);if(n===null)return null;try{return JSON.parse(n)}catch{return null}}};function eE(t){let e=[];for(let n=0;n<sessionStorage.length;n+=1){let r=sessionStorage.key(n);if(r===null||!r.startsWith(t))continue;let o=r.slice(t.length);PC(o)&&e.push([r,o])}return e}function PC(t){return t===Mr||t===Th||t.startsWith(Yo)||t.startsWith(El)||t.startsWith(Ko)}function tE(t){let e=Pr(t);return e===""?OC:e}function Pr(t,e=()=>{}){for(let n of t)if(n.role==="user"){let r=nE(n.content);if(r!==""){let o=MC.exec(r)?.[1],i=o===void 0?r:e(o)??Wo(o);return rE(i,CC)}}return""}function LC(t){for(let e of[...t].reverse()){let n=nE(e.content);if(n!=="")return rE(n,NC)}return""}function nE(t){return typeof t=="string"?t.replace(/\s+/g," ").trim():""}function rE(t,e){return t.length<=e?t:`${t.slice(0,e-1).trimEnd()}\u2026`}function kh(t){let e=t.headers??{},n=new Set;return new Ry({url:t.endpoint,headers:e,initialState:{...t.initialState??{}},fetch:(r,o)=>{let i=t.getHeaders?.(),a=[...new Set([...Object.keys(e),...Object.keys(i??{})])].sort();if(Es(r,a,t.trustedOrigins??[],n),i===void 0)return fetch(r,lt(o,t.credentials));let s=new Headers(o?.headers);for(let[l,c]of Object.entries(i))s.set(l,c);return fetch(r,lt({...o,headers:s},t.credentials))},...t.threadId!==void 0?{threadId:t.threadId}:{},...t.initialMessages!==void 0?{initialMessages:[...t.initialMessages]}:{}})}function oE(t,e){let n=t.getAttribute(e);return n!==null&&n!=="false"}function Ah(t,e){let n=t.getAttribute(e);if(n===null)return null;try{return JSON.parse(n)}catch{return console.warn(`<ag-ui-chat>: ${e} is not valid JSON, so it was ignored entirely and the built-in default is being used. Check the quoting -- JSON inside an HTML attribute needs single quotes around the attribute value, or its own double quotes escaped.`),null}}function iE(t){let e=t.getAttribute("data-max-tool-rounds");return e===null?Qn:Number.parseInt(e,10)}var zC="New conversation",Jo=class{#e;#t;#n;#r;#i;#a=new Set;#o=new Map;#s=new Map;#l=null;constructor(e,n=()=>({}),r=new Qe,o=()=>{},i=!0){this.#e=e.endsWith("/")?e:`${e}/`,this.#t=n,this.#n=r,this.#r=o,this.#i=i}threadId(){return this.#l=this.#n.threadId(),this.#l}setActiveThread(e){this.#n.setActiveThread(e),this.#l=e}newThread(){return this.#l=xs(this.#n),this.#l}isUnsent(e){return this.#n.isUnsent?.(e)===!0}saveMessages(e,n){this.#n.saveMessages(e,this.#i?n:[]),this.#s.set(e,{threadId:e,title:Pr(n)||zC,updatedAt:Date.now(),preview:""})}loadCheckpoint(e){return this.#n.loadCheckpoint(e)}saveCheckpoint(e,n){this.#n.saveCheckpoint(e,n)}renameThread(e,n){this.#n.renameThread(e,n),this.#o.set(e,n),this.#u(e,"PATCH",{title:n})}clear(e){this.#n.clear(e),this.#a.add(e),this.#s.delete(e),this.#u(e,"DELETE")}async listThreads(){let e=await this.#d();if(e===null)return this.#n.listThreads();let n=e.filter(o=>!this.#a.has(o.thread_id)).map(o=>this.#p(o)),r=this.#c(e);return r===null?n:[r,...n]}#c(e){for(let r of e)this.#s.delete(r.thread_id);let n=this.#l===null?void 0:this.#s.get(this.#l);return n===void 0?null:{...n,title:this.#o.get(n.threadId)??n.title}}async loadMessages(e){if(this.#n.isUnsent?.(e)===!0)return null;let n=await this.#b(`${this.#e}${encodeURIComponent(e)}/`);if(n===null||!n.ok)return this.#n.loadMessages(e);let r=await this.#m(n);return r===null?this.#n.loadMessages(e):r.messages??null}async#d(){let e=await this.#b(this.#e);if(e===null||!e.ok)return null;let n=await this.#m(e);return n===null?null:n.threads??[]}async#m(e){try{return await e.json()}catch{return null}}#p(e){return{threadId:e.thread_id,title:this.#o.get(e.thread_id)??e.title,updatedAt:e.updated_at===null?Number.NaN:Date.parse(e.updated_at),preview:e.preview}}async#b(e){try{return await fetch(e,lt({headers:this.#t()},this.#r()))}catch{return null}}async#u(e,n,r){let o=this.#t();try{await fetch(`${this.#e}${encodeURIComponent(e)}/`,lt({method:n,headers:r===void 0?o:{...o,"content-type":"application/json"},body:r===void 0?null:JSON.stringify(r)},this.#r()))}catch{}}};function aE(){return{tools:[],serverSettled:new Set,invalidated:new Set,announcedOutcome:!1,outcome:"completed"}}function sE(t,e){let n={};for(let[r,o]of Object.entries(t))n[r]=(...i)=>{e()&&o(...i)};return n}var _l=class{#e;#t=aE();constructor(e){this.#e=e}detach(){this.#t=aE()}forClient(e){let n=this.#t,r=()=>n===this.#t,{onSettled:o,onError:i,onCancelled:a,...s}=this.#n(n,e),l=sE({onError:i,onCancelled:a},r);return{...sE(s,r),onError:c=>{n.outcome="failed",l.onError(c)},onCancelled:()=>{n.outcome="stopped",l.onCancelled()},onSettled:()=>{r()&&o(),this.#r(n,e)}}}#n(e,n){return{onRunStart:()=>{this.#e.running()||(e.announcedOutcome=!1,this.#e.announcer.announce(this.#e.strings().announceResponding)),this.#e.setRunning(!0),this.#e.transcript.ensureGroup(),this.#e.transcript.showPending()},onReasoningStart:()=>{this.#e.transcript.hidePending(),this.#e.transcript.showThoughts().begin()},onReasoningDelta:r=>{this.#e.transcript.showThoughts().stream(r)},onReasoningEnd:()=>{this.#e.transcript.settleThoughts()},onTextDelta:r=>{this.#e.transcript.hidePending(),this.#e.transcript.collapseThoughts(),this.#e.stream.queue(r),this.#e.stream.countDelta()},onTextEnd:(r,o)=>{if(r===""){this.#e.stream.end();return}let i=this.#e.stream.into(r);this.#e.stream.deltas<=1&&this.#e.transcript.revealWords(i),fl(i,this.#e.strings()),this.#e.actions.attach(i,o),this.#e.stream.end(),this.#e.noteUnread(n)},onToolCall:r=>{this.#e.transcript.hidePending(),this.#e.transcript.settleThoughts(),!this.#e.transcript.noticeIfSkillLoad(r)&&(e.tools.push({id:r.id,name:r.name}),this.#e.transcript.cardFor(r))},onActivity:(r,o,i)=>{this.#e.activities.draw(i,r,o)},onCustomEvent:(r,o)=>{if(r===cc){this.#i(e,o);return}if(r===lp){this.#e.subagents.report(o);return}this.#e.element.dispatchEvent(new CustomEvent(ic,{detail:{name:r,value:o},bubbles:!0,composed:!0}))},onSubAgentStarted:(r,o,i)=>{this.#e.subagents.start(r,o,i)},onSubAgentFinished:r=>{this.#e.subagents.finish(r)},onSubAgentError:(r,o)=>{this.#e.subagents.fail(r,o)},onMessagesSnapshot:()=>{this.#e.transcript.appendNotice("\u{1F504}",this.#e.strings().historyReplaced,"history-replaced")},onToolResult:(r,o,i)=>{let a=this.#e.transcript.card(r);a!==void 0&&(a.settle(Ro(i),o),this.#e.transcript.markServerSettled(r),e.serverSettled.add(r),this.#e.transcript.showPending())},onActivityChanged:(r,o,i)=>{this.#e.activities.draw(r,o,i)},onRunEnd:()=>{this.#e.transcript.hidePending(),this.#e.stream.end()},onError:r=>{e.announcedOutcome=!0,this.#e.announcer.announce(this.#e.strings().announceFailed),this.#e.transcript.hidePending();let o=this.#e.appendMessage(We.ASSISTANT,`\u26A0\uFE0F ${r}`);o.classList.add("message--failed"),this.#e.actions.attach(o,{rateable:!1}),this.#e.transcript.revealWords(o),this.#e.stream.end()},onCancelled:()=>{e.announcedOutcome=!0,this.#e.announcer.announce(this.#e.strings().announceStopped),this.#e.transcript.hidePending(),this.#e.transcript.appendStoppedNote(),this.#e.stream.end()},onSettled:()=>{e.announcedOutcome||this.#e.announcer.announce(this.#e.strings().announceAnswerReady),this.#e.transcript.hidePending(),this.#e.setRunning(!1),this.#e.stream.end();for(let r of this.#e.transcript.cards())r.settled||r.settle(J.INTERRUPTED,this.#e.strings().callNotFinished);this.#e.transcript.closeGroup()}}}#r(e,n){let r=e.tools.map(({id:a,name:s})=>({name:s,side:e.serverSettled.has(a)?"server":"client"})),o=[...e.invalidated];e.tools.length=0,e.serverSettled.clear(),e.invalidated.clear();let i=e.outcome;e.outcome="completed",this.#e.element.dispatchEvent(new CustomEvent(nc,{detail:{threadId:n,tools:r,invalidated:o,outcome:i},bubbles:!0,composed:!0}))}#i(e,n){let r=n??{},o=Array.isArray(r.keys)?r.keys.filter(i=>typeof i=="string"):[];if(o.length!==0){for(let i of o)e.invalidated.add(i);this.#e.element.dispatchEvent(new CustomEvent(ac,{detail:{keys:o,reason:typeof r.reason=="string"?r.reason:null},bubbles:!0,composed:!0}))}}};var Ih=new Set,Sl=class{#e;#t="";#n=null;#r="";#i="";#a=null;#o={reported:!1};constructor(e){this.#e=e}claim(){this.#t=this.#s()}release(){this.#n!==null&&(Ih.delete(this.#n),this.#n=null)}conversationNamespace(e){return e===""?this.#t:`${this.#t}#${e}`}scopeStore(e,n){if(!(e instanceof Qe))return e;let r=this.conversationNamespace(n);return this.#a=r===""?e:new Qe(r),this.#a}rescopeStore(e,n){return e!==this.#a?null:(this.#a=new Qe(n),this.#a)}key(e){return this.#t===""?e:`${e}:${this.#t}`}readScopedItem(e){return sessionStorage.getItem(this.key(e))}readPreference(e){try{let n=localStorage.getItem(this.key(e));if(n!==null)return n}catch{}return this.readScopedItem(e)}writePreference(e,n){let r=this.key(e);try{localStorage.setItem(r,n)}catch{}Xo(r,n,this.#o)}writeSession(e,n){Xo(this.key(e),n,this.#o)}clearPreference(e){let n=this.key(e);try{localStorage.removeItem(n)}catch{}try{sessionStorage.removeItem(n)}catch{}}#s(){let e=this.#e.id(),n=e!==""?e:this.#e.endpoint();return n===""?"":this.#i===n?this.#r:Ih.has(n)?(this.#i=n,this.#r=`${n}~${ke()}`,console.warn(`<ag-ui-chat>: another element on this page already stores its conversation under "${n}", so this one has been given a throwaway namespace of its own \u2014 the two would otherwise share a thread pointer, a history drawer and every message. Give each <ag-ui-chat> its own id to keep them apart and let this one restore its conversation across reloads.`),this.#r):(Ih.add(n),this.#n=n,n)}};var DC=["data-attachments-url","data-attachment-accept","data-attachment-max-bytes","data-transcribe-url","data-threads-url","data-threads-cache","data-tools-url","data-skills-url","data-skills","data-prompt-chips","data-slash-commands","data-theme-toggle","data-strings","data-icon-url"],Nh=["omit","same-origin","include"],$C="New conversation";function UC(t){for(let e of t){let n=typeof e.content=="string"?e.content.split(/\s+/).join(" ").trim():"";if(e.role==="user"&&n!==""){let r=Array.from(n);return r.length<=60?n:`${r.slice(0,59).join("").trimEnd()}\u2026`}}return""}function Rh(t){return Nh.includes(t)}var HC="auto",Ch="(max-width: 600px)",GC=320,Bn=8,lE=`${xt}:collapsed`,cE=`${xt}:theme`,hE=["light","dark","auto"];function FC(t){return t.split(/\s+/).filter(e=>hE.includes(e)).at(-1)}function dE(t,e){return[...t.split(/\s+/).filter(r=>r!==""&&!hE.includes(r)),e].join(" ")}function BC(t,e){try{return(t instanceof ShadowRoot?t:document).querySelector(e)??document.querySelector(e)}catch{return null}}var Lr=class extends HTMLElement{agentFactory=kh;headers={};getHeaders=null;trustedOrigins=[];allowImages=!1;formatRelativeTime=null;autoConfirm=!1;askUser=!1;askUserRenderer=null;approvalRenderer=null;approveWithEdits=!1;confirmPredicate=null;getTools=()=>this.#$.defaultTools();getContext=()=>[...Cc(this.getPageMap,this.autoInjectPageMap)];routeMap=[];navigate=null;getPageMap=null;autoInjectPageMap=!0;getPlace=null;conversationStore=new Qe;uploadHandler=null;transcribeHandler=null;navigationResult=()=>({navigated:!0,url:window.location.href});skillContext=()=>({});toolSummaries={};formatToolPayload=null;strings={};resolvePageTarget=e=>document.querySelector(e);#e=new Set;#t=pe;#n=new el({card:e=>this.#v.card(e),strings:()=>this.#t,follow:()=>this.#v.follow()});#r=new yl({ensureGroup:()=>this.#v.ensureGroup(),afterTranscriptGrew:()=>this.#v.afterGrew(),appendNotice:(e,n,r)=>this.#v.appendNotice(e,n,r)});#i=new il({element:this,strings:()=>this.#t,retry:()=>{this.retryLastTurn()},threadId:()=>this.#h.threadId,follow:()=>this.#v.follow()});#a;#o=null;#s=[];#l=new Xs;#c=document.createElement("button");#d;#m=document.createElement("div");#p;#b;#u;#w;#S;#x;#g;#_;#h;#M;#Z;#xe;#te;#W;#H;#P;#q=document.createElement("span");#E=document.createElement("div");#k=document.createElement("button");#L=document.createElement("div");#ue=null;#Ee=0;#Y=0;#he="right";#z=null;#ne=!1;#I=new Map;#pe;#v;#D;#fe;#K=document.createElement("span");#y;#f;#T=!1;#_e=!1;#me=null;#Ne=null;#re=[];#X=[];#G=document.createElement("div");#F=null;#oe="";#B=()=>{this.#Oe()&&this.#f.restoreLauncherPosition()};#Se=()=>{this.#Oe()&&this.#f.settleLauncherPosition()};#Oe(){return this.#f.publishVisualViewport(),this.#U(),!this.#f.dragging()&&this.#ie()}#ie(){return this.getClientRects().length>0}#Te(){this.#ie()&&this.#f.restoreLauncherPosition()}#ae;#J;#R=!1;#ke=!1;#O=new AbortController;#ge=!1;#Ae=null;#Q={};#ve={};#be=null;#ee=null;#se={};#V=!1;#A=null;#Qe=null;#Me=null;#ye=[];#$e=new Map;#we={threadId:"",title:""};#Ue=new Bs;#le=new Vs;#$=new Ts({element:this,routeMap:()=>this.routeMap,navigate:()=>this.navigate,getPageMap:()=>this.getPageMap,pageWithheld:()=>this.#le.withheld,resolvePageTarget:e=>this.resolvePageTarget(e),getTools:()=>this.getTools(),askUser:()=>this.askUser,askUserRenderer:()=>this.askUserRenderer,decision:this.#Ue,setAsking:(e,n)=>this.#v.setAsking(e,n),ensureGroup:()=>this.#v.ensureGroup(),strings:()=>this.#t,hidePending:()=>this.#v.hidePending(),updateEmptyState:()=>this.#v.updateEmptyState(),follow:()=>this.#v.follow(),fetchInit:e=>this.#ot(e)});#et=new pl({openBubble:()=>this.appendMessage(We.ASSISTANT,""),allowImages:()=>this.allowImages,follow:()=>this.#v.follow()});#tt=new er(this);#N=new Sl({id:()=>this.id,endpoint:()=>this.endpoint});#ce;constructor(){super(),this.#a=this.attachShadow({mode:"open"}),this.#p=document.createElement("div"),this.#b=document.createElement("div"),this.#u=document.createElement("textarea"),this.#w=document.createElement("button"),this.#S=document.createElement("span"),this.#M=document.createElement("div"),this.#Z=document.createElement("button"),this.#xe=document.createElement("input"),this.#te=document.createElement("div"),this.#ae=document.createElement("span"),this.#W=document.createElement("button"),this.#H=document.createElement("button"),this.#P=document.createElement("span"),this.#pe=document.createElement("div"),this.#v=new bl({element:this,messages:this.#b,emptyWrap:this.#pe,strings:()=>this.#t,allowImages:()=>this.allowImages,resolveTool:e=>this.#$.resolve(e),toolSummaries:()=>this.toolSummaries,serverSummary:e=>this.#$.summary(e),toolDisplay:()=>this.toolDisplay,toolGroupDisplay:()=>this.toolGroupDisplay,formatToolPayload:e=>this.formatToolPayload?.(e)??null}),this.#D=new Is({element:this,transcript:this.#v,tools:this.#$,decision:this.#Ue,strings:()=>this.#t,announce:e=>this.#l.announce(e),autoConfirm:()=>this.autoConfirm,confirmPredicate:()=>this.confirmPredicate,navigate:()=>this.navigate,approveWithEdits:()=>this.approveWithEdits,approvalRenderer:()=>this.approvalRenderer,getContext:()=>this.#Ot(),conversationStore:()=>this.conversationStore,threadId:()=>this.#h.threadId,tenure:()=>this.#Q,conversation:()=>this.#ve}),this.#fe=new _l({element:this,transcript:this.#v,stream:this.#et,actions:this.#i,activities:this.#r,subagents:this.#n,announcer:this.#l,strings:()=>this.#t,running:()=>this.#V,setRunning:e=>this.#Ce(e),appendMessage:(e,n)=>this.appendMessage(e,n),noteUnread:e=>this.#$t(e)}),this.#f=new Ks({element:this,launcher:this.#H,root:this.#a,connected:()=>this.#R,collapsed:()=>this.collapsed,collapsible:()=>this.#C().collapseTo!==null,strings:()=>this.#t,readPreference:e=>this.#N.readPreference(e),writePreference:(e,n)=>this.#N.writePreference(e,n),clearPreference:e=>this.#N.clearPreference(e),announceSurfaceChange:(e,n)=>this.#Rt(e,n)}),this.#d=new Us({element:this,root:this.#a,messages:this.#b,messagesWrap:this.#m,input:this.#u,strings:()=>this.#t,autoGrow:()=>tn(this.#u),quote:e=>this.quote(e)}),this.#y=new Ps({element:this,chat:this.#p,slot:this.#te,fileInput:this.#xe,button:this.#Z,strings:()=>this.#t,uploadHandler:()=>this.uploadHandler,headersFor:e=>this.#Ie(e),credentialsOption:()=>this.#Ge()}),this.#J=new zs({element:this,slot:this.#ae,input:this.#u,strings:()=>this.#t,transcribeHandler:()=>this.transcribeHandler,headersFor:e=>this.#Ie(e),credentialsOption:()=>this.#Ge(),onInput:()=>this.#je()}),this.registerActivityRenderer({type:uc,render:e=>{let n=ZC(e);return n===null?null:Js("\u{1F5DC}",te(this.#t.historyCompacted,{count:n}),"compaction")}}),this.registerActivityRenderer({type:lc,render:e=>jo(e,this.#t,n=>{this.sendMessage(n)})}),this.#x=new Ds(e=>this.#ce.apply(e)),this.#ce=new mi({element:this,menu:this.#x,input:this.#u,hint:this.#M,strings:()=>this.#t,context:()=>this.skillContext(),flag:e=>oE(this,e),readJsonAttribute:e=>Ah(this,e),fetchInit:e=>this.#ot(e),send:e=>{this.sendMessage(e)},submit:()=>{this.#Xe()},autoGrow:()=>tn(this.#u)}),this.#g=new Fs({onSelect:e=>{this.#h.switchThread(e).catch(()=>{})},onNew:()=>{this.newChat(),this.#h.refreshDrawer()},onRename:(e,n)=>{this.#$e.set(e,n),this.#We(),this.#h.renameThread(e,n)},onDelete:e=>{this.#h.deleteThread(e)}}),this.#_=new Ao((e,n)=>{this.#h.continueRun(e,n).catch(r=>{console.warn("<ag-ui-chat>: continuing a run failed",r)})}),this.#h=new Gs({element:this,drawer:this.#g,checkpoints:this.#_,transcript:this.#v,actions:this.#i,activities:this.#r,tools:this.#$,input:this.#u,hint:this.#M,strings:()=>this.#t,conversationStore:()=>this.conversationStore,formatRelativeTime:()=>this.formatRelativeTime,navigationResult:()=>this.navigationResult,headersFor:e=>this.#Ie(e),requestCredentials:()=>this.#Pe(),appendMessage:(e,n)=>this.appendMessage(e,n),announceTurn:e=>this.#At(e,[]),recordTurn:e=>this.#kt(e),autoGrow:()=>tn(this.#u),continuationEnded:()=>this.#Ke(),client:()=>this.#ee,ensureClient:()=>this.#Je(),buildClient:e=>this.#It(e),releaseClient:()=>{this.#ee=null},running:()=>this.#V||this.#A!==null,holdRun:e=>{let n={};return this.#A=n,this.#Qe=e===null?null:{hold:n,restored:e},{release:()=>this.#qe(n)}},cancelRun:()=>this.#de(),resetState:()=>this.#ze(),setRunning:e=>this.#Ce(e),threadChanged:(e,n)=>this.#xt(e,n),threadsListed:e=>{this.#Ft(e),this.#Ut(e)},threadDeleted:e=>this.#wt([e])})}static get observedAttributes(){return["title-text","placement","collapse-to","anchor","anchor-side","maximized","data-side","data-small-viewport","data-threads-search","credentials","user-key","user-name","data-tool-group-display","data-collapse-icon","theme",...DC]}attributeChangedCallback(e,n,r){if(e==="credentials"){r!==null&&!Rh(r)&&console.error(`<ag-ui-chat>: credentials="${r}" is not a fetch credentials mode (${Nh.join(" / ")}) \u2014 it is being ignored, so requests use the browser default and cross-origin cookies will not be sent.`);return}if(e==="data-tool-group-display"){this.#v.refreshStepGroups();return}if(e==="data-threads-search"){let o=this.getAttribute("data-threads-search");this.#g.setSearchMode(o==="always"||o==="never"?o:"auto");return}if(e==="anchor"){this.#ne=!1,this.#U();return}if(e==="maximized"){this.#zt(r!==null);return}if(e==="data-collapse-icon"){this.#Le();return}if(e==="theme"){this.#W.isConnected&&this.#mt();return}if(e==="anchor-side"||e==="data-side"||e==="data-small-viewport"){this.#Le(),this.#U();return}if(e==="placement"||e==="collapse-to"){this.#Fe(),this.#f.releaseOwnedAxes(),e==="placement"&&this.#f.switchPlacement(n),this.#f.releaseLauncherPosition(),this.#C().collapseTo===null&&this.collapsed&&this.setCollapsed(!1),this.#st(),this.#Le(),e==="collapse-to"&&(this.#Ze(),this.#Be(this.#C().collapseTo==="bar"?this.#E:null)),this.#U(),requestAnimationFrame(()=>this.#f.syncResizeAnchor());return}if(e==="title-text"){this.#_t();return}if(e==="user-name"){this.#rt();return}if(e==="user-key"){this.#R&&(n??"")!==(r??"")&&this.#ht(n??"",r??"");return}n===r||!this.#R||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.#$.register(e)}get sharedState(){return this.#nt()?.state??this.#se}set sharedState(e){this.#se={...e},this.#nt()?.setState(this.#se)}#nt(){return this.#h.continuation??this.#ee}registerPageState(e){this.#$.registerPageState(e)}get endpoint(){return this.getAttribute("endpoint")??""}set endpoint(e){this.setAttribute("endpoint",e)}get userKey(){return this.getAttribute("user-key")??""}set userKey(e){this.setAttribute("user-key",e)}get userName(){return this.getAttribute("user-name")??""}set userName(e){this.setAttribute("user-name",e)}#rt(){let e=this.userName.trim();this.#K.textContent=e===""?this.#t.greetingNoName:te(this.#t.greeting,{name:e})}get credentials(){let e=this.getAttribute("credentials");return e!==null&&Rh(e)?e:null}set credentials(e){if(e===null){this.removeAttribute("credentials");return}if(!Rh(e))throw new TypeError(`<ag-ui-chat>: credentials must be one of ${Nh.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e)}).`);this.setAttribute("credentials",e)}#He(){return{...this.headers,...this.getHeaders?.()}}#Ie(e){let n=this.#He();return Es(e,Object.keys(n),this.trustedOrigins,this.#e),n}#Pe(){return this.credentials??void 0}#Ge(){let e=this.#Pe();return e===void 0?{}:{credentials:e}}#ot(e){return lt({headers:this.#Ie(e)},this.#Pe())}get toolDisplay(){let e=this.getAttribute("data-tool-display");return e===Mt.INLINE||e===Mt.MINIMAL||e===Mt.COMPACT||e===Mt.FULL?e:Mt.GROUPED}set toolDisplay(e){this.setAttribute("data-tool-display",e)}get toolGroupDisplay(){let e=this.getAttribute("data-tool-group-display");return e===Pt.INLINE||e===Pt.MINIMAL||e===Pt.COMPACT?e:Pt.FULL}set toolGroupDisplay(e){this.setAttribute("data-tool-group-display",e)}get extraStyles(){return this.#s}set extraStyles(e){this.#s=[...e],this.#o!==null&&(this.#a.adoptedStyleSheets=[this.#o,...this.#s])}connectedCallback(){if(this.#O=new AbortController,this.#ge&&this.#vt(),this.#ge=!0,this.#N.claim(),this.#tt.join(),this.#f.restoreSize(),requestAnimationFrame(()=>{this.#Te(),this.#f.syncResizeAnchor()}),this.#t=Ou({...this.#Nt(),...this.strings}),this.getAttribute("data-theme-toggle")!==null){let a=this.#N.readPreference(cE),s=a===null?void 0:FC(a);s!==void 0&&this.setAttribute("theme",dE(this.getAttribute("theme")??"",s))}this.#Dt(),this.#g.setStrings(this.#t),this.#_.setStrings(this.#t),this.#C().collapseTo!==null&&this.#Lt()&&this.setAttribute("collapsed",""),this.#Ze(),this.#st();let e=new ResizeObserver(()=>this.#U());e.observe(this.#E),this.#O.signal.addEventListener("abort",()=>e.disconnect());let n=new ResizeObserver(this.#Se);n.observe(this.#b),this.#O.signal.addEventListener("abort",()=>n.disconnect()),this.#f.probe.addEventListener("transitionrun",this.#Se,{signal:this.#O.signal});let r=()=>{requestAnimationFrame(()=>this.#U())};window.addEventListener("pointerup",r,{signal:this.#O.signal}),window.addEventListener("keyup",r,{signal:this.#O.signal}),this.#U(),this.collapsed&&this.setMaximized(!1),this.#C().collapseTo==="none"&&this.#j(ci,{collapsed:this.collapsed}),this.#ce.init();let o=this.#Ae,i=o!==null&&o!==this.userKey;i&&this.#ht(o,this.userKey),this.#Ae=this.userKey,this.conversationStore=this.#N.scopeStore(this.#at(),this.userKey),window.addEventListener("resize",this.#B),window.visualViewport?.addEventListener("resize",this.#B),window.visualViewport?.addEventListener("scroll",this.#B),this.#f.publishVisualViewport(),this.#it(),this.#y.wire(this.#O.signal),this.#J.wire(),this.#h.adoptActiveThread(),queueMicrotask(()=>this.#Ct()),this.#h.rehydrate(i&&o!==""?"rescope":"restore"),i&&this.#h.refreshDrawer(),this.#R=!0,this.#dt(),this.#ke&&(this.#ke=!1,this.newChat())}#Ct(){this.#R&&(this.#$.fetchCatalog(),this.#ce.fetch())}async reload(){this.#de(),this.#ze(),this.#Ce(!1),await Promise.all([this.#$.fetchCatalog(),this.#ce.fetch(),this.#h.rehydrate("restore")])}disconnectedCallback(){this.#R=!1,this.#O.abort(),window.removeEventListener("resize",this.#B),window.visualViewport?.removeEventListener("resize",this.#B),window.visualViewport?.removeEventListener("scroll",this.#B),this.#N.release(),this.#tt.leave(),this.#de(),this.#d.detachPageOffer(),this.#y.tray?.dispose(),this.#J.dispose(),this.#v.disposeScroller(),this.#l.dispose()}#Nt(){let e=Ah(this,"data-strings");return typeof e=="object"&&e!==null?e:{}}quote(e){this.#d.insert(e)}offerQuoteInPage(e=document.body){return this.#d.offerInPage(e)}#it(){this.#be=null;let e=this.getAttribute("data-threads-url");if(e!==null){let n=this.conversationStore,r=new Jo(e,()=>this.#Ie(e),n,()=>this.#Pe(),this.getAttribute("data-threads-cache")!=="false");this.#be={remote:r,inner:n},this.conversationStore=r}}#at(){let e=this.#be;return e!==null&&this.conversationStore===e.remote?e.inner:this.conversationStore}setSkills(e){this.#ce.setClientSkills(e)}get collapsed(){return this.hasAttribute("collapsed")}set collapsed(e){this.setCollapsed(e)}refreshPlace(){this.isConnected&&this.#le.update(this.getPlace===null?Zy(this.routeMap,window.location.pathname):this.getPlace())}#Ot(){let e=this.getContext();return[...this.#le.withheld?e.filter(r=>r.description!==ui):e,...this.#le.context()]}setCollapsed(e,n={}){e&&this.#C().collapseTo===null||(e&&this.setMaximized(!1),n.announce===!0&&e&&!this.collapsed&&this.#Rt(this.#t.chatMinimised,null),e||(this.refreshPlace(),this.#Te()),e?this.setAttribute("collapsed",""):(this.#Be(),this.removeAttribute("collapsed")),this.#U(),this.#N.writeSession(lE,e?"1":"0"),this.#Re(this.#yt()),this.dispatchEvent(new CustomEvent(ci,{detail:{collapsed:e},bubbles:!0,composed:!0})))}get unread(){let e=0;for(let n of this.#I.values())e+=n;return e}get threadId(){let e=this.#h.threadId;return e===""?null:e}get threadTitle(){return this.#we.title}get running(){return this.#V}get barHeight(){return this.#Ee}get dockWidth(){return this.#Y}get anchor(){return this.#z}set anchor(e){this.#z=e,this.#ne=!1,this.#U()}#C(){return No(this.getAttribute("placement"),this.getAttribute("collapse-to"))}#st(){let e=this.#C().collapseTo;e===null?this.removeAttribute("data-collapsed-to"):this.setAttribute("data-collapsed-to",e)}#Mt(){let e=this.getAttribute("placement");return e!=="sidebar"&&e!=="side"||!this.#ie()||getComputedStyle(this).position==="static"?0:this.collapsed?this.#C().collapseTo==="rail"?this.#H.offsetWidth:0:this.getAttribute("data-small-viewport")!=="off"&&window.matchMedia(Ch).matches?0:this.#p.offsetWidth}#Pt(){if(this.#f.dragging())return;let e=this.#Mt(),n=this.getAttribute("data-side")==="left"?"left":"right";e===this.#Y&&(e===0||n===this.#he)||(this.#Y=e,this.#he=n,this.#j(Jl,{width:e,side:n}))}#U(){if(!this.isConnected)return;let e=this.#ie()?this.#f.syncDock(this.#E,this.#lt()):0;this.#Pt(),e!==this.#Ee&&(this.#Ee=e,this.#j(Xl,{height:e}))}#lt(){if(this.#C().collapseTo!=="none")return null;let e=this.getAttribute("anchor")??"";if(this.#z===null&&e==="")return null;let n=this.#z??BC(this.getRootNode(),e);return n?.isConnected===!0?n:(this.#ne||(this.#ne=!0,console.warn(`<ag-ui-chat>: the anchor ${this.#z===null?`"${e}"`:"element"} is not in the document, so the panel opens from its placement's own corner.`)),null)}#Lt(){let e=this.#N.readScopedItem(lE);return e!==null?e==="1":this.#C().startsCollapsed&&!this.hasAttribute("data-start-open")}describeSurface(){return this.#f.describeSurface()}moveTo(e,n={}){return this.#f.moveTo(e,n)}resetSize(){this.#f.resetSize(),this.#U()}get maximized(){return this.#T}set maximized(e){this.setMaximized(e)}setMaximized(e){e?this.setAttribute("maximized",""):this.removeAttribute("maximized")}toggleMaximized(){this.setMaximized(!this.#T)}#ct(){return this.#C().maximizes!==null&&!window.matchMedia(Ch).matches}#zt(e){let n=e&&this.#ct()&&!this.collapsed;if(e&&!n){this.removeAttribute("maximized");return}n!==this.#T&&(this.#T=n,this.#R&&(n?this.#f.enterMaximized():this.#f.leaveMaximized(),this.#U()),this.#ut(),this.#dt())}#dt(){!this.#R||this.#T===this.#_e||(this.#_e=this.#T,this.#j(Kl,{maximized:this.#T}))}#Fe(){let e=this.#ct();e||this.setMaximized(!1);let n=this.#me;n!==null&&(e?n.button.isConnected||n.before.before(n.button):n.button.remove())}#ut(){let e=this.#me?.button;if(e===void 0)return;let n=this.#T?this.#t.restore:this.#t.maximize;e.title=n,e.setAttribute("aria-label",n),uE(e,this.#T?yp:hi)}#Le(){let e=this.#Ne;if(e===null)return;let n=Ww(this.getAttribute("data-collapse-icon"),this.getAttribute("placement"),this.getAttribute("data-side"));uE(e,n)}toggleCollapsed(){this.setCollapsed(!this.collapsed)}toggleTheme(){let e=this.getAttribute("theme")??"",n=this.#ft()==="dark"?"light":"dark";this.setAttribute("theme",dE(e,n)),this.#N.writePreference(cE,n)}#ht(e,n){this.#Ae=n;let r=this.#R,o=this.#N.conversationNamespace(e),i=this.#N.conversationNamespace(n);if(e===""){Qe.adopt(o,i),r&&this.#pt(i);return}this.#Q={},Qe.purge(o),r&&this.#pt(i),this.#D.forgetWaivers(),this.#de(),this.#ze(),this.#se={},this.#u.value="",this.#je(),this.#Ce(!1),this.#wt([...this.#I.keys()],!0),r&&(this.#J.dispose(),this.#J.wire(),this.#h.adoptActiveThread(),this.#h.rehydrate("rescope"),this.#h.refreshDrawer())}#pt(e){let n=this.#N.rescopeStore(this.#at(),e);n!==null&&(this.conversationStore=n,this.#it())}#ft(){let e=(this.getAttribute("theme")??"").split(/\s+/);if(e.includes("dark"))return"dark";if(e.includes("light"))return"light";let n=getComputedStyle(this).colorScheme.split(/\s+/),r=n.includes("dark");return r!==n.includes("light")?r?"dark":"light":(r||e.includes("auto"))&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}#mt(){let e=this.#ft()==="dark";this.#W.replaceChildren(Ar("theme","theme-icon",e?bp:vp,null))}openThreads(e={}){let n=this.#C().collapseTo,r=e.anchor??this.#lt(),o=this.getAttribute("placement")!=="embedded";this.collapsed&&n==="bar"?this.#E.append(this.#g.element):this.collapsed&&n==="none"&&r!==null&&o?(this.#ue=r,this.#L.append(this.#g.element),this.#gt()):(this.collapsed&&n==="none"&&console.warn(o?'<ag-ui-chat>: openThreads() under collapse-to="none" needs an anchor to open beside; pass openThreads({ anchor }) or set the anchor attribute.':'<ag-ui-chat>: openThreads() under placement="embedded" and collapse-to="none" has no popover: the collapsed chat is not drawn. Expand it first.'),this.#Be()),this.#h.openThreads()}#gt(){let e=this.#ue;if(e===null||this.#g.element.parentNode!==this.#L)return;let n=e.getBoundingClientRect(),r=document.documentElement.clientWidth,o=document.documentElement.clientHeight,i=n.top+n.height/2<o/2,a=Math.min(GC,r-2*Bn),s=Math.min(Math.max(Bn,r-n.right),r-Bn-a),l=(i?o-n.bottom:n.top)-2*Bn;this.style.setProperty("--_threads-top",i?`${n.bottom+Bn}px`:"auto"),this.style.setProperty("--_threads-bottom",i?"auto":`${o-n.top+Bn}px`),this.style.setProperty("--_threads-right",`${Math.max(Bn,s)}px`),this.style.setProperty("--_threads-room",`${Math.max(0,l)}px`)}#Be(e=null){let n=this.#g.element.parentNode;if(n!==e&&(n===this.#E||n===this.#L)){this.#g.close(),this.#p.insertBefore(this.#g.element,this.#_.element),this.#ue=null;for(let r of["top","bottom","right","room"])this.style.removeProperty(`--_threads-${r}`)}}openCheckpoints(){this.#h.openCheckpoints()}closeThreads(){this.#g.close()}closeCheckpoints(){this.#_.close()}switchThread(e){return this.#R?this.#h.switchThread(e):Promise.resolve()}deleteThread(e){this.#R&&this.#h.deleteThread(e)}toggleCheckpoints(){if(this.#_.open_){this.#_.close();return}this.openCheckpoints()}newChat(){if(!this.#R){this.#ke=!0;return}this.#de(),this.#h.reapUnsent(),this.#ze(),this.#h.startThread(),this.#Ce(!1),this.#xt(this.#h.threadId,"new"),this.collapsed||this.#u.focus({preventScroll:!0})}#ze(){this.#vt(),this.#re.length=0,this.#F=null}#vt(){this.#ee=null,this.#fe.detach(),this.#ve={},this.#bt(),this.#h.forgetRestored()}#bt(){this.#et.end(),this.#v.releaseTurn(),this.#n.clear(),this.#v.forgetCards(),this.#r.clearBlocks(),this.#i.forget(),this.#y.tray?.clear(),this.removeAttribute("data-composer-settling"),this.removeAttribute("data-restoring"),this.#v.empty()}async retryLastTurn(){if(this.#Ye())return!1;let e={};this.#A=e;try{let n=this.#Je(),r=n.truncateToLastUser();if(r===null||this.#A!==e)return!1;this.#bt();for(let o of r)if(this.#h.replay(o),this.#A!==e)return!1;return await n.resume(),!0}finally{this.#qe(e)}}appendMessage(e,n){return this.#v.append(e,n)}#Dt(){let{signal:e}=this.#O;this.#p.className="chat",this.#p.setAttribute("part","panel");let n=this.#Et(),r=this.getAttribute("data-theme-toggle")!==null,{header:o,checkpoints:i,maximize:a,collapse:s}=Vw({host:this,title:this.#S,titleText:n,iconUrl:this.getAttribute("data-icon-url"),strings:this.#t,withCheckpoints:this.#h.runs()!==null,themeToggle:r?this.#W:null,signal:e,onHistory:()=>this.openThreads(),onCheckpoints:()=>this.toggleCheckpoints(),onNewChat:()=>this.newChat(),onCollapse:()=>this.toggleCollapsed(),onMaximize:()=>this.toggleMaximized(),onToggleTheme:()=>this.toggleTheme()});r&&this.#mt(),this.#f.enablePanelDrag(o),this.#me={button:a,before:s},this.#Ne=s,this.#Le(),this.#Fe(),this.#ut(),window.matchMedia(Ch).addEventListener("change",()=>this.#Fe(),{signal:e}),jx({messages:this.#b,jumpButton:this.#c,emptyWrap:this.#pe,greetingText:this.#K,starters:qx(this,this.#t,v=>{this.sendMessage(v)}),strings:this.#t}),this.#rt(),this.#d.mount(e),this.#v.mountScroller(this.#c,e),this.#l.mount(),this.#b.append(this.#pe),this.#v.updateEmptyState();let l=Dy({input:this.#u,send:this.#w,attachButton:this.#Z,fileInput:this.#xe,voiceSlot:this.#ae,place:this.#le.element,hint:this.#M,queuedRow:this.#G,attachSlot:this.#te,strings:this.#t,signal:e,onKeydown:v=>this.#Ht(v),onInput:()=>this.#je(),onSend:()=>{if(this.#V){this.#de();return}this.#Xe()},onFilesPicked:()=>this.#y.onFilesPicked()});this.#le.mount(e,this.#t),this.#u.addEventListener("focus",()=>this.refreshPlace(),{signal:e}),window.addEventListener("popstate",()=>this.refreshPlace(),{signal:e}),window.addEventListener("hashchange",()=>this.refreshPlace(),{signal:e}),this.refreshPlace();let c=document.createElement("slot");c.name="above-composer";let d=document.createElement("slot");d.name="footer",this.#m.className="messages-wrap",this.#m.replaceChildren(this.#b,this.#c,this.#d.button),this.#p.replaceChildren(o,this.#m,this.#x.palette,this.#x.chips,this.#M,this.#G,this.#te,c,l,d,this.#g.element,this.#_.element),this.#p.addEventListener("pointerdown",v=>{if(!this.#_.open_)return;let f=v.composedPath();f.includes(this.#_.element)||f.includes(i)||this.#_.close()},{signal:e}),jw({launcher:this.#H,badge:this.#P,railLabel:this.#q,bar:this.#E,barHistory:this.#k,barPlace:this.#le.barElement,titleText:n,iconUrl:Yw(this),strings:this.#t,signal:e,onOpen:()=>this.setCollapsed(this.#C().collapseTo==="bar"&&!this.collapsed),onHistory:()=>{this.#g.isOpen()?this.#g.close():this.openThreads()}}),document.addEventListener("pointerdown",v=>{let f=this.#g.element.parentNode;if(!this.#g.isOpen()||f!==this.#E&&f!==this.#L)return;let p=v.composedPath(),b=f===this.#E?[f]:[f,this.#ue];p.some(T=>b.includes(T))||this.#g.close()},{signal:e}),window.addEventListener("resize",()=>this.#gt(),{signal:e}),this.#f.enableLauncherDrag(e),this.#f.mountResizeGrips(this.#p),this.#o=Zw(this.#a,this.#s);let h=this.#f.probe;h.className="viewport-probe",h.setAttribute("aria-hidden","true"),h.style.borderRadius="var(--_viewport-inset-top) var(--_viewport-inset-right) var(--_viewport-inset-bottom) var(--_viewport-inset-left)",h.style.transition="border-radius 1ms",this.#L.className="threads-popover",this.#a.replaceChildren(h,this.#l.region,this.#p,this.#E,this.#L)}#Ze(){this.#H.setAttribute("aria-expanded",String(!this.collapsed));let e=this.unread;this.#P.textContent=e>9?"9+":String(e),this.#P.hidden=e===0||!this.collapsed||!qw(this);let n=!this.collapsed&&this.#C().collapseTo==="bar"?this.#t.collapse:this.#P.hidden?this.#t.expand:te(this.#t.expandUnread,{count:e});this.#H.setAttribute("aria-label",n),this.#H.title=n}#j(e,n){this.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,composed:!0}))}#Re(e){this.#Ze(),this.#j(Ql,{unread:this.unread,threadIds:e})}#$t(e){if(this.#Ve(e)){this.conversationStore.markRead?.(e);return}this.#I.set(e,(this.#I.get(e)??0)+1),this.#Re([e])}#Ve(e){return!this.collapsed&&e===this.#Me&&e===this.#h.threadId}#yt(){let e=this.#Me;return e===null||!this.#Ve(e)||!this.#I.delete(e)?[]:(this.conversationStore.markRead?.(e),[e])}#wt(e,n=!1){let r=e.filter(o=>this.#I.delete(o));(r.length>0||n)&&this.#Re(r)}#Ut(e){let n=[];for(let{threadId:r,unread:o}of e)o!==!0||this.#I.has(r)||(this.#Ve(r)?this.conversationStore.markRead?.(r):(this.#I.set(r,1),n.push(r)));n.length>0&&this.#Re(n)}#je(){this.#x.onInput(this.#u.value),this.#M.hidden=!0,tn(this.#u),this.#F=null}#Ht(e){if(this.#x.onKeydown(e)){e.preventDefault();return}if(e.key==="Escape"&&this.#V){e.preventDefault(),this.#de();return}if(e.key==="Enter"&&!e.shiftKey){e.preventDefault(),this.#Xe();return}this.#Gt(e)}#Gt(e){let n=e.key==="ArrowUp";if(!n&&e.key!=="ArrowDown"||this.#x.isOpen())return;let r=this.#re;if(r.length===0||(this.#u.value!==this.#oe&&(this.#F=null),this.#F===null&&(!n||this.#u.value!=="")))return;let o=this.#F===null?0:this.#F+(n?1:-1);o>=r.length||(e.preventDefault(),this.#F=o<0?null:o,this.#u.value=o<0?"":r[o],this.#oe=this.#u.value,this.#u.setSelectionRange(this.#u.value.length,this.#u.value.length),tn(this.#u))}#de(){this.#X.length=0,this.#De(),this.#Ue.abort(),this.#ee?.cancel(),this.#A=null,this.#h.stopContinuation()}#xt(e,n){let r={threadId:e,previousThreadId:this.#Me,reason:n};this.#Me=e;let o=this.#yt();o.length>0&&this.#Re(o),this.refreshPlace(),this.#ye=this.#h.restored;let i=this.#St();this.#j(rc,r),i&&this.#Tt(),(n==="switch"||n==="restore"&&this.conversationStore instanceof Qe)&&this.#h.refreshDrawer()}#Et(){let e=this.getAttribute("title-text");return e!==HC?e??this.#t.title:this.#we.title===""?this.#t.title:this.#we.title}#_t(){this.#S.textContent=this.#Et(),this.#q.textContent=this.#S.textContent}#St(){let e=this.#h.threadId,n=this.#$e.get(e)??Pr(this.#ye,o=>this.#ce.title(o)),r=this.#we;return n===r.title&&(e===r.threadId||n==="")?!1:(this.#we={threadId:e,title:n},this.#_t(),!0)}#Tt(){this.#j(oc,{...this.#we})}#We(){this.#St()&&this.#Tt()}#Ft(e){let n=this.#h.threadId,r=e.find(i=>i.threadId===n);r===void 0||this.#ye.length===0||[Pr(this.#ye),UC(this.#ye),$C].includes(r.title)||(this.#$e.set(n,r.title),this.#We())}#Ce(e){let n=this.#V&&!e;this.#V=e,e&&(this.#A=null);let r=e?this.#t.stop:this.#t.send;this.#w.title=r,this.#w.setAttribute("aria-label",r),this.#w.dataset.state=e?"running":"idle",this.toggleAttribute("data-running",e),n&&this.#Ke()}#qe(e){this.#A===e&&(this.#A=null,this.#Ke())}#Ye(){return this.#V||this.#A!==null||this.#h.continuation!==null}#Ke(){if(this.#V||this.#h.continuation!==null)return;let e=this.#X.shift();this.#De(),e!==void 0&&this.sendMessage(e)}#De(){this.#G.replaceChildren(),this.#G.hidden=this.#X.length===0;for(let[e,n]of this.#X.entries()){let r=document.createElement("button");r.type="button",r.className="queued-chip",r.setAttribute("part","queued-chip"),r.textContent=n,r.title=te(this.#t.removeQueued,{text:n}),r.setAttribute("aria-label",r.title),r.addEventListener("click",()=>{this.#X.splice(e,1),this.#De()}),this.#G.appendChild(r)}}#kt(e){e!==""&&this.#re[0]!==e&&this.#re.unshift(e),this.#F=null}async#Xe(){let e=this.#u.value.trim(),n=this.#y.tray?.readyRefs()??[];if(!(e===""&&n.length===0)){if(this.#kt(e),this.#Ye()){e!==""&&(this.#X.push(e),this.#De(),this.#u.value="",tn(this.#u));return}this.#u.value="",tn(this.#u),this.#y.tray?.hasPending()===!0&&this.#v.appendNotice("\u{1F4CE}",te(this.#t.attachmentsStillUploading,{n:this.#y.tray.pendingCount()}),"attachment-pending"),this.#y.tray?.clearReady(),await this.sendMessage(e,n)}}async sendMessage(e,n=[]){if(e===""&&n.length===0)return!1;let r=this.#Qe;if(r!==null&&this.#A===r.hold){let i={};return this.#A=i,await r.restored,this.#A!==i?!1:(this.#A=null,this.sendMessage(e,n))}if(this.#Ye())return!1;let o={};this.#A=o;try{if(this.#v.isEmpty()&&this.setAttribute("data-composer-settling",""),this.#At(e,n),this.#A!==o)return!1;let i=this.endpoint!=="";return await this.#Bt(e,n),i}finally{this.#qe(o)}}#At(e,n){let r=this.appendMessage(We.USER,e);n.length>0&&r.appendChild(Ns(n)),this.#j(Yl,{content:e,attachments:n})}attachFile(e){return this.#y.attach(e)}async#Bt(e,n){if(this.endpoint===""){console.error('<ag-ui-chat>: no endpoint is set, so this message was not sent and no request was made. Point the element at your AG-UI mount with the endpoint attribute (endpoint="/agent/"), or assign chat.endpoint before sending.'),this.#v.appendNotice("\u26A0",this.#t.notConnected,"not-connected");return}await this.#Je().send(e,n)}#Je(){return this.#ee===null&&(this.#ee=this.#It({endpoint:this.endpoint,initialMessages:this.#h.restored,follows:[]})),this.#ee}#It(e){let n=this.#h.threadId,r=this.#Q,o=this.agentFactory({endpoint:e.endpoint,headers:this.#He(),getHeaders:()=>this.#He(),trustedOrigins:this.trustedOrigins,...this.#Ge(),threadId:n,initialMessages:e.initialMessages,initialState:this.#se});return new qo({agent:o,handlers:this.#fe.forClient(n),getTools:()=>(this.refreshPlace(),this.#$.advertise()),getContext:()=>this.#D.buildContext(),executeTool:i=>this.#D.execute(i),resolveInterrupts:i=>this.#D.resolveInterrupts(i),onPersist:i=>{if(r!==this.#Q)return;let a=[...e.follows,...i];this.conversationStore.saveMessages(n,a),n===this.#h.threadId&&(this.#ye=a,this.#We()),e.onSaved?.(a)},onStateChanged:i=>{r===this.#Q&&this.#Zt(i)},connectionLostMessage:this.#t.connectionLost,unfinishedMessage:this.#t.callNotFinished,declinedMessage:this.#t.declinedAction,maxToolRounds:iE(this)})}#Zt(e){this.#se={...e},this.#j(ec,{state:this.#se})}#Rt(e,n){this.#v.appendNotice("\u2922",e,"surface",n===null?void 0:{label:this.#t.undo,onActivate:n})}enableCharts(e=["tool","activity"]){let n=!this.#r.has(pi)&&!this.#$.has(Rs);e.includes("activity")&&this.registerActivityRenderer({type:pi,render:r=>{let o=Sr(r);return o===null?null:So(o)},removedNotice:this.#t.chartUndrawable}),e.includes("tool")&&this.registerTool(zy()),n&&this.isConnected&&this.reload()}registerActivityRenderer(e){this.#r.register(e)}get unhandledActivityTypes(){return this.#r.unhandledTypes()}};function uE(t,e){for(let n of t.querySelectorAll("slot"))n.innerHTML=e}function ZC(t){let e=t?.removed;return typeof e=="number"?e:null}function VC(){let t=customElements.get(Hr);if(t===void 0)customElements.define(Hr,Lr);else if(t!==Lr)throw new Error(`<${Hr}> is already defined by another class: a second copy of this package, or another package, is on the page`)}async function jC(t,e,n={}){await zt(t),await Tc(t,{...n,flashMs:n.flashMs??0}),await _c(t,e,n)}async function WC(t,e={}){await zt(t),await Sc(t,e)}async function qC(t,e={}){await zt(t),await kc(t,e)}async function YC(t,e,n={}){await zt(t),await Ac(t,e,n)}async function KC(t,e,n={}){await zt(t),await Ic(t,e,n)}function XC(t,e){t instanceof HTMLInputElement&&t.type==="checkbox"?Wr(t,!!e):dn(t,String(e)),qr(t)}var JC="0.1.1";export{tc as ATTACHMENT_EVENT,Lr as AgUiChat,qo as AgUiClient,Xl as BAR_HEIGHT_EVENT,pi as CHART_ACTIVITY_TYPE,Rs as CHART_TOOL_NAME,gi as CHAT_CORNERS,uc as COMPACTION_ACTIVITY_TYPE,ic as CUSTOM_AGENT_EVENT,Ao as CheckpointMenu,Vr as ClientToolRegistry,wl as ConnectionLostError,pe as DEFAULT_UI_STRINGS,Jl as DOCK_WIDTH_EVENT,Hr as ELEMENT_TAG,sc as FEEDBACK_EVENT,cc as INVALIDATE_CUSTOM_NAME,ac as INVALIDATE_EVENT,hc as LOAD_CAPABILITY_TOOL,Kl as MAXIMIZE_EVENT,FA as MAX_QUOTE_CHARS,yC as MAX_SUGGESTIONS,wC as MAX_SUGGESTION_CHARS,Qn as MAX_TOOL_ROUNDS,cn as MESSAGE_ACTIONS,We as MESSAGE_ROLE,Kr as PAGE_ACTIONS,nc as RUN_FINISHED_EVENT,Jo as RemoteConversationStore,Io as RunIndex,ec as STATE_EVENT,Yl as SUBMIT_EVENT,lc as SUGGESTIONS_ACTIVITY_TYPE,Qe as SessionStorageStore,rc as THREAD_EVENT,oc as THREAD_TITLE_EVENT,ci as TOGGLE_EVENT,J as TOOL_CALL_STATUS,Mt as TOOL_DISPLAY,Pt as TOOL_GROUP_DISPLAY,qe as TOOL_OUTCOME,Po as ToolCallCard,Ql as UNREAD_EVENT,JC as VERSION,di as X_CONFIRM_KEY,Gr as X_DESTRUCTIVE_KEY,Fr as X_NAVIGATES_KEY,Le as X_SUMMARY_KEY,Bu as asQuote,Qu as attachMessageActions,Zu as attachQuoteOffer,Sr as chartSpecFrom,WC as clickElement,fc as createChatSurfaceTools,kh as createHttpAgent,Rc as createPageActionTools,Cc as createPageMapContext,Nc as createPageStateTools,Oc as createRouteTools,VC as defineChat,jC as fillField,u_ as flash,Tc as focusWithFlash,Sc as highlightThenClick,Hp as isChatCorner,$u as isDestructive,As as isNavigates,Ou as mergeUiStrings,rl as messageActionBar,Vu as messageAttachments,Pu as parseToolCatalog,yi as prefersReducedMotion,qC as pressButton,kc as pressThenClick,Wo as prettifyToolName,To as quotableSelection,ko as relativeTime,So as renderChart,Vo as renderMarkdown,jo as renderSuggestionChips,Lu as requestApproval,Du as requestConfirmation,Mu as requestQuestion,zt as scrollIntoCenterView,YC as selectControl,Ac as selectOption,XC as setControlValue,Wr as setNativeChecked,dn as setNativeValue,xc as showHighlightOverlay,Wx as suggestionPrompts,KC as toggleCheckbox,Ic as toggleControl,Ro as toolStatusFromOutcome,Fu as transcribeAudio,_c as typeInto,Hu as uploadAttachment};
|
|
5688
5688
|
/*! Bundled license information:
|
|
5689
5689
|
|
|
5690
5690
|
fast-json-patch/module/helpers.mjs:
|