@cuttlely/chat 1.5.1 → 1.6.0

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/dist/chat.js CHANGED
@@ -1,8 +1,8 @@
1
- (()=>{var xe={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(s){return String(s??"").replace(/[&<>"']/g,e=>xe[e])}function W(s){let e=String(s??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Z=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function w(s,{image:e=!1,base:t=""}={}){if(typeof s!="string")return null;let r=s.trim();return!r||r.length>4096||/[\u0000-\u001f\u007f\s]/.test(r)&&!(e&&Z.test(r))?null:e&&/^data:/i.test(r)?Z.test(r)?r.replace(/\s+/g,""):null:/^https?:\/\//i.test(r)||!e&&/^mailto:[^/]/i.test(r)?r:r.startsWith("/")&&!r.startsWith("//")&&!r.startsWith("/\\")?t?W(t)+r:r:null}var ye=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function we(s,e){let t=0;for(let r=e;r<s.length;r++){let i=s[r];if(i==="\\"){r++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return r}return-1}function ve(s,e){if(s[e]!=="(")return null;let t=e+1;for(;s[t]===" ";)t++;let r="";if(s[t]==="<"){let i=s.indexOf(">",t);if(i===-1)return null;r=s.slice(t+1,i),t=i+1}else{let i=0,a=t;for(;t<s.length;t++){let o=s[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")break}r=s.slice(a,t)}for(;s[t]===" ";)t++;if(s[t]==='"'||s[t]==="'"){let i=s[t],a=s.indexOf(i,t+1);if(a===-1)return null;for(t=a+1;s[t]===" ";)t++}return s[t]!==")"?null:{url:r,end:t+1}}var ke=/^https?:\/\/[^\s<>"'`]+/i;function Te(s){let e=s.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function Ae(s,e,t){let r=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,a]of r){if(!s.startsWith(i,e))continue;let o=s[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(s[e-1]))continue;let n=s.indexOf(i,e+i.length+1);for(;n!==-1;){let l=s[n-1],h=s[n+i.length],g=i[0]==="_"&&h&&/[a-z0-9]/i.test(h),p=i.length===1&&h===i;if(l&&!/\s/.test(l)&&!g&&!p)break;n=s.indexOf(i,n+1)}if(n===-1)continue;let d=s.slice(e+i.length,n);return{html:`<${a}>${C(d,t)}</${a}>`,end:n+i.length}}return null}function C(s,e={}){let t="",r="",i=()=>{r&&(t+=v(r).replace(/\n/g,"<br>")),r=""};for(let a=0;a<s.length;){let o=s[a];if(o==="\\"&&ye.test(s[a+1]||"")){r+=s[a+1],a+=2;continue}if(o==="`"){let n=1;for(;s[a+n]==="`";)n++;let d="`".repeat(n),l=s.indexOf(d,a+n);if(l!==-1){i();let h=s.slice(a+n,l).replace(/\n/g," ");/^ .* $/.test(h)&&(h=h.slice(1,-1)),t+=`<code>${v(h)}</code>`,a=l+n;continue}r+=d,a+=n;continue}if(o==="!"&&s[a+1]==="["||o==="["){let n=o==="!",d=n?a+1:a,l=we(s,d),h=l!==-1?ve(s,l+1):null;if(h){let g=s.slice(d+1,l),p=w(h.url,{image:n,base:e.base});i(),n?t+=p?`<img src="${v(p)}" alt="${v(g)}" loading="lazy">`:v(g):p&&!e.inLink?t+=`<a href="${v(p)}" target="_blank" rel="noopener noreferrer nofollow">${C(g,{...e,inLink:!0})}</a>`:t+=C(g,e),a=h.end;continue}}if(o==="<"){let n=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(s.slice(a));if(n){let d=w(n[1]);if(d&&!e.inLink){i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(n[1])}</a>`,a+=n[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(a===0||/[\s(]/.test(s[a-1]))){let n=ke.exec(s.slice(a));if(n){let d=Te(n[0]);i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(d)}</a>`,a+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let n=Ae(s,a,e);if(n){i(),t+=n.html,a=n.end;continue}}r+=o,a++}return i(),t}var Q=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,ee=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,te=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,z=/^ {0,3}> ?(.*)$/,M=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,re=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function P(s){let e=s.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],r="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(r+="|",i++):e[i]==="|"?(t.push(r.trim()),r=""):r+=e[i];return t.push(r.trim()),t}function Ee(s,e){return Q.test(s)||ee.test(s)||te.test(s)||z.test(s)||M.test(s)||s.includes("|")&&e!==void 0&&re.test(e)&&e.includes("-")}function Se(s,e){return`<div class="md-code"><div class="md-code-head"><span>${s?v(s.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${v(e)}</code></pre></div>`}function Ce(s,e){let t=P(s[0]),r=P(s[1]).map(o=>{let n=o.startsWith(":"),d=o.endsWith(":");return n&&d?"center":d?"right":n?"left":""}),i=(o,n,d)=>{let l=r[d]?` style="text-align:${r[d]}"`:"";return`<${o}${l}>${C(n,e)}</${o}>`},a='<div class="md-table"><table><thead><tr>';a+=t.map((o,n)=>i("th",o,n)).join(""),a+="</tr></thead><tbody>";for(let o of s.slice(2)){let n=P(o);a+="<tr>"+t.map((d,l)=>i("td",n[l]??"",l)).join("")+"</tr>"}return a+"</tbody></table></div>"}function Ie(s,e,t){let r=M.exec(s[e]),i=/\d/.test(r[2]),a=r[1].length,o=[],n=e,d=!1;for(;n<s.length;){let p=M.exec(s[n]);if(!p||p[1].length!==a||/\d/.test(p[2])!==i)break;let u=a+p[2].length+1,m=[p[3]??""];n++;let y=!1;for(;n<s.length;){let b=s[n];if(!b.trim()){y=!0,m.push(""),n++;continue}let A=b.length-b.trimStart().length,k=M.exec(b);if(k&&k[1].length<=a)break;if(A<Math.min(u,a+2)&&!k){if(y)break;m.push(b.trim()),n++;continue}y&&(d=!0),y=!1,m.push(b.slice(Math.min(A,u))),n++}for(;m.length&&!m[m.length-1].trim();)m.pop();o.push(m)}let l=i&&parseInt(r[2],10)!==1?` start="${parseInt(r[2],10)}"`:"",h=i?"ol":"ul",g=o.map(p=>{let u=p.join(`
2
- `),m="",y=/^\[([ xX])\]\s+/.exec(u);y&&(m=`<span class="md-task" aria-hidden="true">${y[1]===" "?"\u2610":"\u2611"}</span> `,u=u.slice(y[0].length));let b=q(u.split(`
3
- `),t);return d||(b=b.replace(/^<p>([\s\S]*?)<\/p>/,(A,k)=>k)),`<li>${m}${b}</li>`}).join("");return{html:`<${h}${l}>${g}</${h}>`,end:n}}function q(s,e){let t="",r=0;for(;r<s.length;){let i=s[r];if(!i.trim()){r++;continue}let a=Q.exec(i);if(a){let d=a[1],l=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(s[r]);)l.push(s[r]),r++;r++,t+=Se(a[2],l.join(`
4
- `));continue}let o=ee.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,r++;continue}if(te.test(i)){t+="<hr>",r++;continue}if(z.test(i)){let d=[];for(;r<s.length&&s[r].trim()&&z.test(s[r]);)d.push(z.exec(s[r])[1]),r++;t+=`<blockquote>${q(d,e)}</blockquote>`;continue}if(i.includes("|")&&r+1<s.length&&re.test(s[r+1])&&s[r+1].includes("-")){let d=[i,s[r+1]];for(r+=2;r<s.length&&s[r].trim()&&s[r].includes("|");)d.push(s[r]),r++;t+=Ce(d,e);continue}if(M.test(i)){let d=Ie(s,r,e);t+=d.html,r=d.end;continue}let n=[i.trim()];for(r++;r<s.length&&s[r].trim()&&!Ee(s[r],s[r+1]);)n.push(s[r].trim()),r++;t+=`<p>${C(n.join(`
5
- `),e)}</p>`}return t}function V(s,e={}){if(typeof s!="string"||!s)return"";let t=s.replace(/\r\n?/g,`
1
+ (()=>{var Le={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function S(r){return String(r??"").replace(/[&<>"']/g,e=>Le[e])}function q(r){let e=String(r??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var ee=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function v(r,{image:e=!1,base:t=""}={}){if(typeof r!="string")return null;let n=r.trim();return!n||n.length>4096||/[\u0000-\u001f\u007f\s]/.test(n)&&!(e&&ee.test(n))?null:e&&/^data:/i.test(n)?ee.test(n)?n.replace(/\s+/g,""):null:/^https?:\/\//i.test(n)||!e&&/^mailto:[^/]/i.test(n)?n:n.startsWith("/")&&!n.startsWith("//")&&!n.startsWith("/\\")?t?q(t)+n:n:null}var Re=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function Be(r,e){let t=0;for(let n=e;n<r.length;n++){let i=r[n];if(i==="\\"){n++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return n}return-1}function Ne(r,e){if(r[e]!=="(")return null;let t=e+1;for(;r[t]===" ";)t++;let n="";if(r[t]==="<"){let i=r.indexOf(">",t);if(i===-1)return null;n=r.slice(t+1,i),t=i+1}else{let i=0,s=t;for(;t<r.length;t++){let a=r[t];if(a==="\\"){t++;continue}if(a==="(")i++;else if(a===")"){if(i===0)break;i--}else if(a===" ")break}n=r.slice(s,t)}for(;r[t]===" ";)t++;if(r[t]==='"'||r[t]==="'"){let i=r[t],s=r.indexOf(i,t+1);if(s===-1)return null;for(t=s+1;r[t]===" ";)t++}return r[t]!==")"?null:{url:n,end:t+1}}var _e=/^https?:\/\/[^\s<>"'`]+/i;function ze(r){let e=r.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function De(r,e,t){let n=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,s]of n){if(!r.startsWith(i,e))continue;let a=r[e+i.length];if(!a||/\s/.test(a)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(r[e-1]))continue;let o=r.indexOf(i,e+i.length+1);for(;o!==-1;){let p=r[o-1],l=r[o+i.length],f=i[0]==="_"&&l&&/[a-z0-9]/i.test(l),u=i.length===1&&l===i;if(p&&!/\s/.test(p)&&!f&&!u)break;o=r.indexOf(i,o+1)}if(o===-1)continue;let d=r.slice(e+i.length,o);return{html:`<${s}>${C(d,t)}</${s}>`,end:o+i.length}}return null}function C(r,e={}){let t="",n="",i=()=>{n&&(t+=S(n).replace(/\n/g,"<br>")),n=""};for(let s=0;s<r.length;){let a=r[s];if(a==="\\"&&Re.test(r[s+1]||"")){n+=r[s+1],s+=2;continue}if(a==="`"){let o=1;for(;r[s+o]==="`";)o++;let d="`".repeat(o),p=r.indexOf(d,s+o);if(p!==-1){i();let l=r.slice(s+o,p).replace(/\n/g," ");/^ .* $/.test(l)&&(l=l.slice(1,-1)),t+=`<code>${S(l)}</code>`,s=p+o;continue}n+=d,s+=o;continue}if(a==="!"&&r[s+1]==="["||a==="["){let o=a==="!",d=o?s+1:s,p=Be(r,d),l=p!==-1?Ne(r,p+1):null;if(l){let f=r.slice(d+1,p),u=v(l.url,{image:o,base:e.base});i(),o?t+=u?`<img src="${S(u)}" alt="${S(f)}" loading="lazy">`:S(f):u&&!e.inLink?t+=`<a href="${S(u)}" target="_blank" rel="noopener noreferrer nofollow">${C(f,{...e,inLink:!0})}</a>`:t+=C(f,e),s=l.end;continue}}if(a==="<"){let o=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(r.slice(s));if(o){let d=v(o[1]);if(d&&!e.inLink){i(),t+=`<a href="${S(d)}" target="_blank" rel="noopener noreferrer nofollow">${S(o[1])}</a>`,s+=o[0].length;continue}}}if((a==="h"||a==="H")&&!e.inLink&&(s===0||/[\s(]/.test(r[s-1]))){let o=_e.exec(r.slice(s));if(o){let d=ze(o[0]);i(),t+=`<a href="${S(d)}" target="_blank" rel="noopener noreferrer nofollow">${S(d)}</a>`,s+=d.length;continue}}if(a==="*"||a==="_"||a==="~"){let o=De(r,s,e);if(o){i(),t+=o.html,s=o.end;continue}}n+=a,s++}return i(),t}var te=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,ne=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,ie=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,B=/^ {0,3}> ?(.*)$/,$=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,re=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function W(r){let e=r.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],n="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(n+="|",i++):e[i]==="|"?(t.push(n.trim()),n=""):n+=e[i];return t.push(n.trim()),t}function He(r,e){return te.test(r)||ne.test(r)||ie.test(r)||B.test(r)||$.test(r)||r.includes("|")&&e!==void 0&&re.test(e)&&e.includes("-")}function Ue(r,e){return`<div class="md-code"><div class="md-code-head"><span>${r?S(r.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${S(e)}</code></pre></div>`}function Oe(r,e){let t=W(r[0]),n=W(r[1]).map(a=>{let o=a.startsWith(":"),d=a.endsWith(":");return o&&d?"center":d?"right":o?"left":""}),i=(a,o,d)=>{let p=n[d]?` style="text-align:${n[d]}"`:"";return`<${a}${p}>${C(o,e)}</${a}>`},s='<div class="md-table"><table><thead><tr>';s+=t.map((a,o)=>i("th",a,o)).join(""),s+="</tr></thead><tbody>";for(let a of r.slice(2)){let o=W(a);s+="<tr>"+t.map((d,p)=>i("td",o[p]??"",p)).join("")+"</tr>"}return s+"</tbody></table></div>"}function Fe(r,e,t){let n=$.exec(r[e]),i=/\d/.test(n[2]),s=n[1].length,a=[],o=e,d=!1;for(;o<r.length;){let u=$.exec(r[o]);if(!u||u[1].length!==s||/\d/.test(u[2])!==i)break;let m=s+u[2].length+1,h=[u[3]??""];o++;let g=!1;for(;o<r.length;){let x=r[o];if(!x.trim()){g=!0,h.push(""),o++;continue}let k=x.length-x.trimStart().length,w=$.exec(x);if(w&&w[1].length<=s)break;if(k<Math.min(m,s+2)&&!w){if(g)break;h.push(x.trim()),o++;continue}g&&(d=!0),g=!1,h.push(x.slice(Math.min(k,m))),o++}for(;h.length&&!h[h.length-1].trim();)h.pop();a.push(h)}let p=i&&parseInt(n[2],10)!==1?` start="${parseInt(n[2],10)}"`:"",l=i?"ol":"ul",f=a.map(u=>{let m=u.join(`
2
+ `),h="",g=/^\[([ xX])\]\s+/.exec(m);g&&(h=`<span class="md-task" aria-hidden="true">${g[1]===" "?"\u2610":"\u2611"}</span> `,m=m.slice(g[0].length));let x=G(m.split(`
3
+ `),t);return d||(x=x.replace(/^<p>([\s\S]*?)<\/p>/,(k,w)=>w)),`<li>${h}${x}</li>`}).join("");return{html:`<${l}${p}>${f}</${l}>`,end:o}}function G(r,e){let t="",n=0;for(;n<r.length;){let i=r[n];if(!i.trim()){n++;continue}let s=te.exec(i);if(s){let d=s[1],p=[];for(n++;n<r.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(r[n]);)p.push(r[n]),n++;n++,t+=Ue(s[2],p.join(`
4
+ `));continue}let a=ne.exec(i);if(a){let d=a[1].length;t+=`<h${d}>${C(a[2]||"",e)}</h${d}>`,n++;continue}if(ie.test(i)){t+="<hr>",n++;continue}if(B.test(i)){let d=[];for(;n<r.length&&r[n].trim()&&B.test(r[n]);)d.push(B.exec(r[n])[1]),n++;t+=`<blockquote>${G(d,e)}</blockquote>`;continue}if(i.includes("|")&&n+1<r.length&&re.test(r[n+1])&&r[n+1].includes("-")){let d=[i,r[n+1]];for(n+=2;n<r.length&&r[n].trim()&&r[n].includes("|");)d.push(r[n]),n++;t+=Oe(d,e);continue}if($.test(i)){let d=Fe(r,n,e);t+=d.html,n=d.end;continue}let o=[i.trim()];for(n++;n<r.length&&r[n].trim()&&!He(r[n],r[n+1]);)o.push(r[n].trim()),n++;t+=`<p>${C(o.join(`
5
+ `),e)}</p>`}return t}function V(r,e={}){if(typeof r!="string"||!r)return"";let t=r.replace(/\r\n?/g,`
6
6
  `).replace(/\t/g," ").split(`
7
- `);return q(t,{base:e.base||""})}function ie(s){let e="",t=r=>{let i=[];for(let n of r.split(/\r?\n/))n.startsWith("data:")&&i.push(n.slice(n[5]===" "?6:5));if(!i.length)return;let a=i.join(`
8
- `),o;try{o=JSON.parse(a)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let a=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(a)}},end(){e.trim()&&t(e),e=""}}}var J=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function R(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new J(s.status,String(e||"").slice(0,300))}function se({apiHost:s,flowId:e,fetchImpl:t}){let r=W(s||""),i=encodeURIComponent(e),a=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await a(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await R(o);let n=await o.text();try{return JSON.parse(n)}catch{return{}}},async send(o,n={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,S]of Object.entries(h))S!=null&&A.append(k,typeof S=="object"?JSON.stringify(S):String(S));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await a(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await R(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ie(F=>{var B;return(B=n.onEvent)==null?void 0:B.call(n,F)}),k=p.body.getReader(),S=new TextDecoder;for(;;){let{value:F,done:B}=await k.read();if(B)break;A.push(S.decode(F,{stream:!0}))}A.push(S.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=n.onJson)==null||b.call(n,y)},async feedback({messageId:o,chatId:n,rating:d}){let l=await a(`${r}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:n,messageId:o,rating:d})});if(!l.ok)throw await R(l)},fileUrl(o,n){let d=String(n||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,n){let d=await a(o,{headers:n?{"x-cuttlely-session-token":n}:{}});if(!d.ok)throw await R(d);return d.blob()}}}function $(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Me={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},$e=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!$e.test(t)||e&&((r=Me[e])!=null&&r.includes(t.toLowerCase()))?"":t}function E(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function ae(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>E(t,300)).filter(Boolean).slice(0,6)}function Le(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let a of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof a=="string"&&e.add(a);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function H(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},a=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},n=Le(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:E(t.title,80),avatar:w(E(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(E(r.avatarSrc),{image:!0})||"",welcome:E(t.welcomeMessage),errorMessage:E(t.errorMessage,300),placeholder:E(a.placeholder,120),starterPrompts:ae(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&n.types.length?n:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(a.backgroundColor,"inputBackground"),inputText:T(a.textColor,"inputText"),accent:T(a.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=ae(u):p==="avatar"?l.avatar=w(E(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=E(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ne(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},O='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function U(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function G(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let a=s.slice();return a[i]={...a[i],...t},a}function L(s,e,t={}){var a,o;let r=s||U(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let n of Array.isArray(t.steps)?t.steps:[])i.specialists=G(i.specialists,n.specialist,{task:typeof n.task=="string"?n.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=G(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=G(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let n=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;n?i.specialists=n.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((a=t.trace)==null?void 0:a.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Y(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Be={A:["href","target","rel"],BLOCKQUOTE:[],BR:[],BUTTON:["type","class","data-copy-code","aria-label"],CODE:[],DEL:[],DIV:["class"],EM:[],H1:[],H2:[],H3:[],H4:[],H5:[],H6:[],HR:[],IMG:["src","alt","loading"],LI:[],OL:["start"],P:[],PRE:[],SPAN:["class","aria-hidden"],STRONG:[],TABLE:[],TBODY:[],TD:["style"],TH:["style"],THEAD:[],TR:[],UL:[]},ze=/^text-align:(left|right|center)$/;function oe(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Be[r.tagName];if(!i)t.push(r);else{for(let a of Array.from(r.attributes)){let o=a.name.toLowerCase(),n=i.includes(o);n&&(o==="href"||o==="src")&&(n=w(a.value,{image:o==="src"})!==null),n&&o==="style"&&(n=ze.test(a.value)),n&&o==="target"&&(n=a.value==="_blank"),n||r.removeAttribute(a.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ce=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-figure .dc-image-download{border:0;border-top:1px solid var(--dc-border);border-radius:0;padding:8px 12px}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Re="cuttlely-chat:v1:",He=60,Oe="https://github.com/cuttlely/cuttlely",Ue=0,_=s=>`${s}-${Date.now().toString(36)}-${(Ue++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,a]of Object.entries(e||{}))a==null||a===!1||(i==="class"?r.className=a:i==="text"?r.textContent=a:i==="html"?r.innerHTML=a:i.startsWith("on")&&typeof a=="function"?r.addEventListener(i.slice(2),a):r.setAttribute(i,a===!0?"":String(a)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function de(s,e){let t=document.createElement("template");t.innerHTML=V(s,{base:e}),oe(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function le(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let a=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof a.url=="string"?a.url:typeof a.source=="string"?a.source:""),n=a.title||a.source||a.url||a.name||i.title||"",d=String(n||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function K(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var pe=["pdf","docx","xlsx","pptx","csv"];function he(s){let e=typeof(s==null?void 0:s.name)=="string"?s.name:"",t=String((s==null?void 0:s.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(s==null?void 0:s.type)||"bin"}`}function fe(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function ue(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let a=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof a=="string"&&a.trim())return a}return""}var N=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=se({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=H({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=_("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:ce});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,a,o;let e=this.options.theme,t=n=>this.wrap.classList.toggle("dark",n);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var n;return t(!!((n=this.media)!=null&&n.matches))},this.onMedia(),(o=(a=this.media)==null?void 0:a.addEventListener)==null||o.call(a,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ne(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=H(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=$(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${Re}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:_("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:K(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-He).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let a=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==a)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=a,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,a)=>i!==e[a]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(a=>c("img",{src:a,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(a=>c("span",{class:"dc-file-chip",html:f.doc},[a])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var n,d,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=O;let a=c("div",{class:"dc-body"});e.run&&a.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=de(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&a.append(o),(n=e.artifacts)!=null&&n.length&&a.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&a.append(this.renderSources(e.sources)),e.error&&a.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&a.append(this.renderAction(e)),e.status==="done"&&e.text&&a.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&a.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),a])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,a={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:t?"Working\u2026":"",n=c("details",{class:"dc-run"});!r&&t&&(n.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:a}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return n.append(d),i&&n.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Y(l.ms)}):null])))),n}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(pe.includes(r.type)&&r.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(r));else{if(pe.includes(r.type))continue;if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(de(r.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,he(e),e.type.toUpperCase())}renderDownloadLink(e,t,r,i=""){let a=!e.data.startsWith("data:"),o=()=>a?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,n=c("a",{class:`dc-file${i}`,href:o(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:r}),c("span",{class:"dc-file-name",text:t})]);return n.addEventListener("click",async d=>{if(!a||!this.sessionToken||!this.chatId){n.href=o();return}d.preventDefault();try{let l=await this.api.fileBlob(o(),this.sessionToken),h=URL.createObjectURL(l);c("a",{href:h,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(h),3e4)}catch{n.replaceWith(c("div",{class:"dc-figure-missing",html:f.alert},[`${t} could not be downloaded here.`]))}}),n}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":he(e),r=e.type==="jpeg"?"jpg":e.type;return(r==="jpg"?/\.jpe?g$/i:new RegExp(`\\.${r}$`,"i")).test(t)?t:`${t.replace(/\.[^.]*$/,"")||"image"}.${r}`}renderImageArtifact(e){let t=e.type==="jpg"?"jpeg":e.type,r=new RegExp(`^data:image/${t};base64,[A-Za-z0-9+/]+={0,2}$`).test(e.data),i=e.data.startsWith("FILE-STORAGE::")||!/[:/\\]/.test(e.data),a=r?e.data:w(e.data,{image:!0,base:this.base}),o=a&&!e.data.startsWith("/")?a:this.api.fileUrl(this.chatId,e.data),n=c("figure",{class:"dc-figure"}),d=c("img",{src:o,alt:"Chart from the answer",loading:"lazy"});d.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let l=!1;if(d.addEventListener("error",async()=>{if(!l&&!a&&this.sessionToken&&this.chatId){l=!0;try{let h=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);d.src=URL.createObjectURL(h);return}catch{}}d.replaceWith(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),n.append(d),i||r){let h=this.imageArtifactName(e),g=(e.type==="jpeg"?"jpg":e.type).toUpperCase();n.append(this.renderDownloadLink(e,h,g," dc-image-download"))}return n}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((a,o)=>{let n=[c("b",{text:String(o+1)}),c("span",{text:a.title})],d;a.url?d=c("a",{class:"dc-source",href:a.url,target:"_blank",rel:"noopener noreferrer nofollow",title:a.title},n):(d=c("button",{class:"dc-source",type:"button",title:a.title,"aria-expanded":"false"},n),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&a.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:a.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,a)=>c("button",{class:`dc-chip${a===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,a,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:a,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let a=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);a.length&&(i.preventDefault(),this.addFiles(a))}),this.window.addEventListener("dragover",i=>{i.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",i=>{i.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",i=>{var a;i.preventDefault(),this.clearDrop(),this.addFiles(((a=i.dataTransfer)==null?void 0:a.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Oe,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(a=>{let o=new FileReader;o.onload=()=>a(typeof o.result=="string"?o.result:""),o.onerror=()=>a(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let a=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:a,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",a=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!a.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:_("m"),role:"user",text:i.trim(),images:a.map(p=>p.data),status:"done",rev:0},n={id:_("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,n),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let d={question:i.trim()};this.chatId&&(d.chatId=this.chatId),this.sessionToken&&(d.sessionToken=this.sessionToken),a.length&&(d.uploads=a),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{n.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(n,p,h),onJson:p=>this.onJson(n,p)},l.signal),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.text=n.fallbackText||""),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.error="The answer was empty. Try asking another way.")}catch(p){if(l.signal.aborted)n.text||(n.text="_Stopped._");else{let u=$(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}n.error=u.message,n.retry={text:i.trim(),extra:t,uploads:a}}}finally{this.controller===l&&(this.controller=null)}n.status="done",n.run&&n.run.phase!=="done"&&n.run.phase!=="failed"&&(n.run=L(n.run,n.error?"error":"final",{})),n.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(n.error?n.error:`Answer: ${n.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,r){let{event:i,data:a}=t;if(i==="token"&&typeof a=="string")return e.text+=a,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=le(a),r();if(i==="artifacts")return e.artifacts=K(a),r();if(i==="action")return e.action=a&&typeof a=="object"?a:null,e.actionRaw=a,r();if(i==="agentFlowExecutedData"){e.fallbackText=ue(a)||e.fallbackText;return}if(i==="metadata"&&a&&typeof a=="object")return typeof a.chatId=="string"&&(this.chatId=a.chatId),typeof a.sessionToken=="string"&&(this.sessionToken=a.sessionToken),typeof a.chatMessageId=="string"&&(e.messageId=a.chatMessageId),a.followUpPrompts&&(e.followUps=fe(a.followUpPrompts)),a.action&&!e.action&&(e.action=a.action,e.actionRaw=a.action),r();if(i==="error"){let o=typeof t.status=="number"?t.status:0,n=o?$({status:o},this.config.errorMessage):null;return e.error=n&&n.kind!=="error"?n.message:this.config.errorMessage||(typeof a=="string"&&a?a.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=L(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let n=a&&typeof a=="object"?a:{};return e.run=L(e.run||U(n.harness),o,n),o==="partial"&&n.phase==="answer"&&!n.streamedAsToken&&typeof n.text=="string"&&(e.text+=n.text),o==="final"&&!e.text&&typeof n.text=="string"&&(e.fallbackText=n.text),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=ue(t.agentFlowExecutedData)),e.sources=le(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=fe(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?_e(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=L(U(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function _e(s){try{return JSON.parse(s)}catch{return null}}var ge="cuttlely-chat";function j(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new N(s,e);return s.__cuttlelyChat=t,t}function D(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function me(s){if(typeof customElements>"u"||customElements.get(ge))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,a){!this.isConnected||i===a||(r==="theme"&&this.widget?this.widget.setTheme(a||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=D(this,"flow-id");r&&(this.widget=j(this,{flowId:r,apiHost:D(this,"api-host")||s,mode:D(this,"mode")==="page"?"page":"bubble",theme:D(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(ge,e)}var I=typeof document<"u"?document.currentScript:null,X=(()=>{try{return I&&I.src?new URL(I.src).origin:location.origin}catch{return location.origin}})();me(X);function be(){let s=(I==null?void 0:I.dataset)||{},e=s.flowId||s.flowid;if(!e)return;let t=s.mode==="page"?"page":"bubble",r;t==="page"&&s.target&&(r=document.querySelector(s.target)),r||(r=document.createElement("cuttlely-chat-root"),r.style.display=t==="page"?"block":"contents",t==="page"&&(r.style.height="100%"),document.body.append(r)),j(r,{flowId:e,apiHost:s.apiHost||X,mode:t,theme:s.theme||"auto",open:s.open==="true"})}var Ne={mount:(s,e)=>j(s,{apiHost:X,...e}),version:"1.5.1"};typeof window<"u"&&(window.cuttlelyChat=Ne);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",be,{once:!0}):be());})();
7
+ `);return G(t,{base:e.base||""})}function se(r){let e="",t=n=>{let i=[];for(let o of n.split(/\r?\n/))o.startsWith("data:")&&i.push(o.slice(o[5]===" "?6:5));if(!i.length)return;let s=i.join(`
8
+ `),a;try{a=JSON.parse(s)}catch{return}a&&typeof a=="object"&&typeof a.event=="string"&&r(a)};return{push(n){e+=n;let i;for(;i=/\r?\n\r?\n/.exec(e);){let s=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(s)}},end(){e.trim()&&t(e),e=""}}}var J=class extends Error{constructor(e,t,n){super(t||`Request failed (${e})`),this.status=e,this.code=n||""}};async function N(r){let e="";try{let t=await r.text();try{let n=JSON.parse(t);e=typeof(n==null?void 0:n.message)=="string"?n.message:typeof(n==null?void 0:n.error)=="string"?n.error:""}catch{e=t}}catch{}return new J(r.status,String(e||"").slice(0,300))}function ae({apiHost:r,flowId:e,fetchImpl:t}){let n=q(r||""),i=encodeURIComponent(e),s=t||((...a)=>globalThis.fetch(...a));return{host:n,async loadConfig(){let a=await s(`${n}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!a.ok)throw await N(a);let o=await a.text();try{return JSON.parse(o)}catch{return{}}},async send(a,o={},d){var x;let p=Array.isArray(a.files)?a.files:[],l={...a,streaming:!0};delete l.files;let f;if(p.length){let k=new FormData;for(let[w,E]of Object.entries(l))E!=null&&k.append(w,typeof E=="object"?JSON.stringify(E):String(E));for(let w of p)k.append("files",w,w.name);f={method:"POST",body:k,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else f={method:"POST",body:JSON.stringify(l),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let u=await s(`${n}/api/v1/prediction/${i}`,f);if(!u.ok)throw await N(u);if((u.headers.get("content-type")||"").includes("text/event-stream")&&u.body&&typeof u.body.getReader=="function"){let k=se(j=>{var R;return(R=o.onEvent)==null?void 0:R.call(o,j)}),w=u.body.getReader(),E=new TextDecoder;for(;;){let{value:j,done:R}=await w.read();if(R)break;k.push(E.decode(j,{stream:!0}))}k.push(E.decode()),k.end();return}let h=await u.text(),g;try{g=JSON.parse(h)}catch{g={text:h}}(x=o.onJson)==null||x.call(o,g)},async feedback({messageId:a,chatId:o,rating:d}){let p=await s(`${n}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:o,messageId:a,rating:d})});if(!p.ok)throw await N(p)},fileUrl(a,o){let d=String(o||"").replace(/^FILE-STORAGE::/,""),p=new URLSearchParams({chatflowId:e,chatId:a||"",fileName:d});return`${n}/api/v1/get-upload-file?${p.toString()}`},async fileBlob(a,o){let d=o?{"x-cuttlely-session-token":o}:{},p=await s(a,{headers:d});if(p.status===403&&o&&(p=await s(a,{headers:d,credentials:"omit"})),!p.ok)throw await N(p);return p.blob()}}}function I(r,e){let t=r==null?void 0:r.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(r==null?void 0:r.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Pe={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},je=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function A(r,e){var n;if(typeof r!="string")return"";let t=r.trim();return!je.test(t)||e&&((n=Pe[e])!=null&&n.includes(t.toLowerCase()))?"":t}function T(r,e=2e3){return typeof r=="string"?r.trim().slice(0,e):""}function oe(r){return!r||typeof r!="object"?[]:(Array.isArray(r)?r:Object.keys(r).map(t=>r[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>T(t,300)).filter(Boolean).slice(0,6)}function We(r){if(!Array.isArray(r))return{types:[],maxMB:0};let e=new Set,t=0;for(let n of r){for(let s of Array.isArray(n==null?void 0:n.fileTypes)?n.fileTypes:[])typeof s=="string"&&e.add(s);let i=Number(n==null?void 0:n.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function _(r,e={}){var f,u,m;let t=r&&typeof r=="object"?r:{},n=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},s=t.textInput&&typeof t.textInput=="object"?t.textInput:{},a=t.uploads&&typeof t.uploads=="object"?t.uploads:{},o=We(a.imgUploadSizeAndTypes),d=Array.isArray(a.fullFileUploadTypes)?a.fullFileUploadTypes.filter(h=>typeof h=="string"&&/^\.[a-z0-9]+$/.test(h)):[],p=Number(t.fontSize),l={title:T(t.title,80),avatar:v(T(t.titleAvatarSrc),{image:!0})||"",botAvatar:n.showAvatar&&v(T(n.avatarSrc),{image:!0})||"",welcome:T(t.welcomeMessage),errorMessage:T(t.errorMessage,300),placeholder:T(s.placeholder,120),starterPrompts:oe(t.starterPrompts),feedback:!!((f=t.chatFeedback)!=null&&f.status),followUps:!!((u=t.followUpPrompts)!=null&&u.status),newSessionEachVisit:!!t.generateNewSession,enhancedStatus:((m=t.enhancedStatusMessages)==null?void 0:m.status)!==!1,imageUpload:a.isImageUploadAllowed&&o.types.length?o:null,fileUpload:a.isFullFileUploadAllowed&&d.length?{types:d,maxMB:25}:null,fontSize:Number.isFinite(p)&&p>=12&&p<=22?p:0,colors:{headerBg:A(t.titleBackgroundColor,"titleBackgroundColor"),headerText:A(t.titleTextColor,"titleTextColor"),background:A(t.backgroundColor,"backgroundColor"),botBg:A(n.backgroundColor,"botBackground"),botText:A(n.textColor,"botText"),userBg:A(i.backgroundColor,"userBackground"),userText:A(i.textColor,"userText"),inputBg:A(s.backgroundColor,"inputBackground"),inputText:A(s.textColor,"inputText"),accent:A(s.sendButtonColor,"sendButton")}};for(let[h,g]of Object.entries(e||{}))if(!(g==null||g===""))if(h==="colors"&&typeof g=="object")for(let[x,k]of Object.entries(g)){let w=A(k);w&&x in l.colors&&(l.colors[x]=w)}else h==="starterPrompts"?l.starterPrompts=oe(g):h==="avatar"?l.avatar=v(T(g),{image:!0})||l.avatar:typeof l[h]=="string"?l[h]=T(g):typeof l[h]=="boolean"&&(l[h]=!!g);return l}function ce(r){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,n])=>A(r==null?void 0:r[t])?`${n}:${r[t]};`:"").join("")}var y=(r,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${r}</svg>`,b={chat:y('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:y('<path d="M6 6l12 12M18 6L6 18"/>'),send:y('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:y('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:y('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:y('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:y('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:y('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:y('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:y('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:y('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:y('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:y('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:y('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:y('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:y('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},z='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';var qe={route:["Activating agent swarm\u2026","Spinning up the reasoning mesh\u2026","Checking available context windows\u2026","Mapping the intent graph\u2026","Scoring specialist affinity vectors\u2026","Bootstrapping the planner loop\u2026","Warming up the routing layer\u2026","Sharding the question into sub-goals\u2026","Negotiating the agent handshake\u2026","Resolving the task topology\u2026","Computing the optimal dispatch plan\u2026","Balancing the inference load\u2026","Embedding the request in latent space\u2026","Aligning the orchestration graph\u2026","Allocating the attention budget\u2026","Priming the zero-shot router\u2026","Consulting the mixture of experts\u2026","Plotting the agentic workflow\u2026","Tokenizing the intent\u2026","Selecting the reasoning strategy\u2026","Booting the multi-agent runtime\u2026","Assembling the dream team\u2026","Calibrating the semantic compass\u2026","Drafting the execution graph\u2026"],working:["Performing deep analysis\u2026","Running multi-hop reasoning\u2026","Orchestrating parallel inference\u2026","Expanding the chain of thought\u2026","Decomposing the problem space\u2026","Grounding the hypotheses\u2026","Traversing the knowledge graph\u2026","Hydrating the working memory\u2026","Scaling test-time compute\u2026","Exploring the solution manifold\u2026","Running agentic planning cycles\u2026","Sampling candidate trajectories\u2026","Building the reasoning scaffold\u2026","Refining the latent plan\u2026","Propagating context through the stack\u2026","Tuning the attention heads\u2026","Crunching the high-dimensional signal\u2026","Running a self-consistency pass\u2026","Simulating counterfactuals\u2026","Iterating on the inner loop\u2026","Distilling the core question\u2026","Stacking the inference layers\u2026","Optimizing the token budget\u2026","Engaging deep focus mode\u2026"],tool:["Cross-checking the numbers\u2026","Lining up the joins\u2026","Vectorizing the signal\u2026","Fusing retrieval results\u2026","Normalizing the feature space\u2026","Streaming results into the context window\u2026","Checking schema alignment\u2026","Deduplicating the evidence set\u2026","Indexing the fresh signal\u2026","Running hybrid retrieval\u2026","Chunking the payload\u2026","Computing similarity scores\u2026","Parsing structured output\u2026","Hardening the result set\u2026","Sanity-checking the aggregates\u2026","Ingesting the response stream\u2026","Warming the cache on the hot path\u2026","Pipelining the function calls\u2026","Running a semantic diff\u2026","Reconciling the data shards\u2026","Batching the inference requests\u2026","Extracting the high-signal rows\u2026","Stress-testing the edge cases\u2026","Checking the guardrails\u2026"],thinking:["Weighing a few angles\u2026","Calibrating confidence intervals\u2026","Re-ranking candidate insights\u2026","Running a reflection pass\u2026","Synthesizing emergent patterns\u2026","Scoring the evidence\u2026","Pruning the hypothesis tree\u2026","Detecting anomalies in the signal\u2026","Triangulating the findings\u2026","Running Bayesian updates\u2026","Converging on a consensus\u2026","Debating with the critic agent\u2026","Collapsing the probability cloud\u2026","Reasoning over the embeddings\u2026","Measuring semantic drift\u2026","Red-teaming the conclusions\u2026","Fact-checking the reasoning chain\u2026","Rebalancing the attention weights\u2026","Extracting latent insights\u2026","Running an ensemble vote\u2026","Grading the reasoning path\u2026","Minimizing the loss of nuance\u2026","Clustering the main findings\u2026","Looking for second-order effects\u2026"],handoff:["Polishing the wording\u2026","Double-checking the totals\u2026","Decoding the final tokens\u2026","Compressing insights into prose\u2026","Running the hallucination filter\u2026","Aligning the tone vectors\u2026","Rendering the narrative layer\u2026","Fine-tuning the phrasing\u2026","Assembling the executive summary\u2026","Applying the clarity optimizer\u2026","Grounding every claim\u2026","Formatting the output tensor\u2026","Smoothing the reasoning seams\u2026","Packaging the insight payload\u2026","Running a final coherence check\u2026","Beam-searching for the best sentence\u2026","Lowering the temperature for precision\u2026","Stitching the agent outputs together\u2026","Shipping the answer to the edge\u2026","Applying the finishing gradient\u2026","Condensing the answer to its essence\u2026","Converting thoughts to plain language\u2026","Running the last-mile alignment\u2026","Sealing the response envelope\u2026"]},de={query:"a SQL query",describe:"a table description",list_tables:"a table listing",list_relations:"a table listing",pin_definition:"a saved query lookup"},Ge=/^pq_[a-z0-9_]+$/i;function Ve(r){let e=String(r||"").trim(),t=/^mcp__(.+?)__(.+)$/.exec(e);return t?t[2]:e}function Je(r,e){let t=Ve(r==null?void 0:r.name);return de[t]?de[t]:Ge.test(t)?"a saved query":`${(typeof e=="function"?e(r):"")||t||"a tool"}`}function Ye(r,e){let t=Array.isArray(r==null?void 0:r.tools)?r.tools:[],n=t.filter(i=>(i==null?void 0:i.status)==="running").pop();if(n){let i=Je(n,e);return{phase:"tool",row:`Running ${i}\u2026`,verb:`is running ${i}\u2026`}}return t.length?{phase:"thinking",row:"Thinking about the results\u2026",verb:"is thinking about the results\u2026"}:{phase:"working",row:"Working\u2026",verb:"is working\u2026"}}function le(r,{toolLabel:e}={}){var d,p;if(!r||r.status!=="running")return null;let t=Array.isArray(r.specialists)?r.specialists:[],n={},i=null;for(let l of t){if((l==null?void 0:l.status)!=="running")continue;let f=Ye(l,e);n[l.name]=f.row,(!i||f.phase==="tool"||i.status.phase!=="tool")&&(i={name:l.name,status:f})}let s=(d=r.handoff)==null?void 0:d.status;if(s==="running"||s==="done")return{line:"Pulling it together and writing the answer\u2026",phase:"handoff",perSpecialist:n};if(i)return{line:`${i.name} ${i.status.verb}`,phase:i.status.phase,perSpecialist:n};let a=(p=r.route)==null?void 0:p.status,o=t.some(l=>l&&l.status!=="running"&&l.status!=="queued");return a==="running"||a==="done"&&!o?{line:"Picking specialists\u2026",phase:"route",perSpecialist:n}:a==="done"||o?{line:"Working\u2026",phase:"waiting",perSpecialist:n}:{line:"Starting\u2026",phase:"start",perSpecialist:n}}function Ke(r,e=Math.random){let t=[...r];for(let n=t.length-1;n>0;n--){let i=Math.floor(e()*(n+1));[t[n],t[i]]=[t[i],t[n]]}return t}function Ze(r,e=Math.random){let t=[],n=null;return{next(){if(!r.length)return"";if(!t.length){t=Ke(r,e);let i=t.length-1;i>0&&t[i]===n&&(t[i]=t[0],t[0]=n)}return n=t.pop(),n}}}function pe({random:r=Math.random}={}){let e={},t=null;return{line(n,i,s=!0){let a=qe[n];if(!s||!a||!Number.isFinite(i)||i<4e3)return t=null,"";let o=Math.floor((i-4e3)/3500);return t&&t.phase===n&&t.slot===o||(e[n]||(e[n]=Ze(a,r)),t={phase:n,slot:o,text:e[n].next()}),t.text}}}function he(r,e,t,n=4e3){let i=r||{text:"",at:-1/0};return!e||e===i.text||t-i.at<n?i:{text:e,at:t}}function Y(r){let e=Math.max(0,Math.floor((Number(r)||0)/1e3)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),i=String(e%60).padStart(2,"0");return t?`${t}:${String(n).padStart(2,"0")}:${i}`:`${n}:${i}`}function H(r=""){return{harness:r,phase:"planning",route:"pending",handoff:"pending",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function D(r,e,t){let n=typeof e=="string"&&e?e:"specialist",i=r.findIndex(a=>a.name===n);if(i===-1)return[...r,{name:n,status:"queued",ms:null,task:"",tools:[],...t}];let s=r.slice();return s[i]={...s[i],...t},s}function L(r,e,t={}){var s,a;let n=r||H(t.harness),i={...n,harness:t.harness||n.harness};if(e==="route"&&t.phase==="start")i.route="running";else if(e==="route"&&t.phase==="done"){i.route="done",i.phase="working";for(let o of Array.isArray(t.steps)?t.steps:[])i.specialists=D(i.specialists,o.specialist,{task:typeof o.task=="string"?o.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=D(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=D(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="tool"&&(t.phase==="start"||t.phase==="done"))i.specialists=Qe(i.specialists,t);else if(e==="handoff"&&t.phase==="start")i.phase="writing",i.handoff="running";else if(e==="handoff"&&t.phase==="done")i.handoff="done";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let o=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;o?i.specialists=o.map(p=>({name:String(p.name||"specialist"),status:p.status==="failed"?"failed":"done",ms:typeof p.ms=="number"?p.ms:null,task:typeof p.task=="string"?p.task:""})):i.specialists=i.specialists.map(p=>p.status==="failed"?p:{...p,status:"done"});let d=((s=t.trace)==null?void 0:s.wallMs)??((a=t.timings)==null?void 0:a.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-n.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Qe(r,e){let t=typeof e.name=="string"&&e.name?e.name:"tool",n=r.find(s=>s.name===(typeof e.specialist=="string"&&e.specialist?e.specialist:"specialist")),i=n&&Array.isArray(n.tools)?n.tools.slice():[];if(e.phase==="start")i.push({name:t,status:"running"});else{let s=i.map((o,d)=>({tool:o,at:d})).reverse().find(({tool:o})=>o.name===t&&o.status==="running"),a=e.error?"failed":"done";s?i[s.at]={name:t,status:a}:i.push({name:t,status:a})}return D(r,e.specialist,{tools:i})}function K(r){return!r||r.phase==="done"||r.phase==="failed"?null:le({status:"running",route:{status:r.route||"pending"},handoff:{status:r.handoff||"pending"},specialists:(r.specialists||[]).map(e=>({name:e.name,status:e.status,tools:e.tools||[]}))})}function Z(r){if(typeof r!="number"||!Number.isFinite(r))return"";if(r<1e3)return`${Math.max(1,Math.round(r))} ms`;let e=r/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Xe={A:["href","target","rel"],BLOCKQUOTE:[],BR:[],BUTTON:["type","class","data-copy-code","aria-label"],CODE:[],DEL:[],DIV:["class"],EM:[],H1:[],H2:[],H3:[],H4:[],H5:[],H6:[],HR:[],IMG:["src","alt","loading"],LI:[],OL:["start"],P:[],PRE:[],SPAN:["class","aria-hidden"],STRONG:[],TABLE:[],TBODY:[],TD:["style"],TH:["style"],THEAD:[],TR:[],UL:[]},et=/^text-align:(left|right|center)$/;function ue(r){let e=r.ownerDocument.createTreeWalker(r,1),t=[],n=e.nextNode();for(;n;){let i=Xe[n.tagName];if(!i)t.push(n);else{for(let s of Array.from(n.attributes)){let a=s.name.toLowerCase(),o=i.includes(a);o&&(a==="href"||a==="src")&&(o=v(s.value,{image:a==="src"})!==null),o&&a==="style"&&(o=et.test(s.value)),o&&a==="target"&&(o=s.value==="_blank"),o||n.removeAttribute(s.name)}n.tagName==="A"&&n.setAttribute("rel","noopener noreferrer nofollow")}n=e.nextNode()}for(let i of t)i.replaceWith(r.ownerDocument.createTextNode(i.textContent||""));return r}var fe=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table-sort{display:inline-flex;align-items:center;gap:.5em;padding:0;border:0;border-radius:3px;background:transparent;color:inherit;font:inherit;text-align:inherit;cursor:pointer}.md-table-sort:hover{text-decoration:underline}.md-table-sort:focus-visible{outline:2px solid var(--dc-accent);outline-offset:4px}.md-table-sort-icon{opacity:.65;font-size:.85em}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-figure .dc-image-download{border:0;border-top:1px solid var(--dc-border);border-radius:0;padding:8px 12px}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-run-live{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;padding:0 12px 8px 48px;font-size:.86em}.dc-run-enhanced{color:var(--dc-muted);font-style:italic}.dc-run-enhanced:empty{display:none}.dc-run li .dc-step-live{color:var(--dc-muted)}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-note{flex-basis:100%;font-size:.85em;color:var(--dc-muted)}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var tt=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ge=/^(?:unknown|n\/?a|not available|not provided|not recorded|not applicable|null|none(?: in window)?|[—–-])?$/i,me={"no risk":0,"low risk":1,"slight risk":1,"moderate risk":2,"medium risk":2,"high risk":3,"critical risk":4},nt=/^(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)$/i,it=new RegExp("^\\p{Sc}$","u"),rt=/\s/;function ye(r,e){let t=r.length-e;for(;t>0&&rt.test(r[t-1]);)t--;return r.slice(0,t)}function st(r){return r.length>=3&&nt.test(r.slice(-3))?ye(r,3):r}function at(r){let e=r.length,n=e>=2&&/[\uD800-\uDBFF]/.test(r[e-2])&&/[\uDC00-\uDFFF]/.test(r[e-1])?2:1;return e>=1&&it.test(r.slice(e-n))?ye(r,n):r}function be(r){let e=r.replace(/\u2212/g,"-").trim(),t=e.startsWith("(")&&e.endsWith(")");if(t&&(e=e.slice(1,-1).trim()),e=st(e.replace(/^(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)\s*/i,"")),e=at(e.replace(new RegExp("^([+-]?)\\p{Sc}\\s*","u"),"$1")).trim(),!/^[+-]?(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)%?$/.test(e))return null;let n=Number(e.replace(/[,%]/g,""))*(t?-1:1);return Number.isFinite(n)&&Math.abs(n)<=Number.MAX_SAFE_INTEGER?n:null}function xe(r){if(!/^(?:\d{4}-\d{2}-\d{2}(?:[T ].+)?|\d{1,2}[ -][A-Za-z]{3,9}[ ,/-]+\d{4}|[A-Za-z]{3,9} \d{1,2},? \d{4})$/.test(r))return null;let e=Date.parse(r);return Number.isFinite(e)?e:null}function we(r,e,t="ascending",n=""){let i=r.map(l=>String(l[e]??"").trim()),s=i.filter(l=>!ge.test(l)),a=/\b(?:ids?|identifiers?|codes?|sku|zip|postal)\b/i.test(n),o=l=>l;!a&&s.length&&s.every(l=>be(l)!==null)?o=be:!a&&s.length&&s.every(l=>xe(l)!==null)?o=xe:/\brisk\b/i.test(n)&&s.length&&s.every(l=>Object.prototype.hasOwnProperty.call(me,l.toLowerCase()))&&(o=l=>me[l.toLowerCase()]);let d=i.map(l=>ge.test(l)?null:o(l)),p=t==="descending"?-1:1;return r.map((l,f)=>f).sort((l,f)=>d[l]===null||d[f]===null?d[l]===d[f]?l-f:d[l]===null?1:-1:(typeof d[l]=="number"?d[l]-d[f]:tt.compare(d[l],d[f]))*p||l-f)}function ve(r,e=new Map){r.querySelectorAll("table").forEach((t,n)=>{var f;if(((f=t.tHead)==null?void 0:f.rows.length)!==1||t.tBodies.length!==1)return;let i=Array.from(t.tHead.rows[0].cells),s=t.tBodies[0],a=Array.from(s.rows);if(!a.length||[...i,...a.flatMap(u=>Array.from(u.cells))].some(u=>u.colSpan!==1||u.rowSpan!==1)||a.some(u=>u.cells.length!==i.length))return;let o=i.map(u=>u.textContent.trim()),d=a.map(u=>Array.from(u.cells,m=>m.textContent)),p=i.map((u,m)=>{if(!o[m]||u.querySelector("a,button,input,select,textarea"))return null;let h=t.ownerDocument.createElement("button");h.type="button",h.className="md-table-sort",h.append(...u.childNodes);let g=t.ownerDocument.createElement("span");return g.className="md-table-sort-icon",g.setAttribute("aria-hidden","true"),h.append(g),u.scope="col",u.append(h),h.addEventListener("click",()=>{let x=e.get(n);l({column:m,direction:(x==null?void 0:x.column)===m&&x.direction==="ascending"?"descending":"ascending"}),h.focus({preventScroll:!0})}),h});function l(u){u&&p[u.column]&&(e.set(n,u),s.append(...we(d,u.column,u.direction,o[u.column]).map(m=>a[m]))),p.forEach((m,h)=>{if(!m)return;let g=(u==null?void 0:u.column)===h;i[h].setAttribute("aria-sort",g?u.direction:"none");let x=g&&u.direction==="ascending"?"descending":"ascending";m.setAttribute("aria-label",`Sort by ${o[h]}, ${x}`),m.title=`Sort displayed rows by ${o[h]} (${x})`,m.lastChild.textContent=g?u.direction==="ascending"?"\u2191":"\u2193":"\u2195"})}l(e.get(n))})}var ot="cuttlely-chat:v1:",ct=60,dt="https://github.com/cuttlely/cuttlely",lt=0,U=r=>`${r}-${Date.now().toString(36)}-${(lt++).toString(36)}`;function c(r,e={},t=[]){let n=document.createElement(r);for(let[i,s]of Object.entries(e||{}))s==null||s===!1||(i==="class"?n.className=s:i==="text"?n.textContent=s:i==="html"?n.innerHTML=s:i.startsWith("on")&&typeof s=="function"?n.addEventListener(i.slice(2),s):n.setAttribute(i,s===!0?"":String(s)));for(let i of[].concat(t))i==null||i===!1||n.append(typeof i=="string"?document.createTextNode(i):i);return n}function ke(r,e){let t=document.createElement("template");t.innerHTML=V(r,{base:e}),ue(t.content);let n=c("div",{class:"dc-md"});return n.append(t.content),n}function Se(r){let e=Array.isArray(r)?r:[],t=new Set,n=[];for(let i of e){if(!i||typeof i!="object")continue;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=v(typeof s.url=="string"?s.url:typeof s.source=="string"?s.source:""),o=s.title||s.source||s.url||s.name||i.title||"",d=String(o||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),p=`${a||""}|${d}`;if(!t.has(p)&&(t.add(p),n.push({title:d||"Source",url:a,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),n.length>=8))break}return n}function Q(r){return(Array.isArray(r)?r:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var Ae=["pdf","docx","xlsx","pptx","csv"];function Te(r){let e=typeof(r==null?void 0:r.name)=="string"?r.name:"",t=String((r==null?void 0:r.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(r==null?void 0:r.type)||"bin"}`}function Ee(r){let e=r;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function Ce(r){var e,t,n;if(!Array.isArray(r))return"";for(let i=r.length-1;i>=0;i--){let s=(n=(t=(e=r[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:n.content;if(typeof s=="string"&&s.trim())return s}return""}var O=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=ae({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=_({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.tableSorts=new WeakMap,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=U("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:I({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:fe});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:b.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var n,i,s,a;let e=this.options.theme,t=o=>this.wrap.classList.toggle("dark",o);if((i=(n=this.media)==null?void 0:n.removeEventListener)==null||i.call(n,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var o;return t(!!((o=this.media)!=null&&o.matches))},this.onMedia(),(a=(s=this.media)==null?void 0:s.addEventListener)==null||a.call(s,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ce(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let n=await this.api.loadConfig();this.config=_(n,this.options.config),this.state="ready",this.restore()}catch(n){let i=I(n);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${ot}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(n=>n&&(n.role==="user"||n.role==="bot")&&typeof n.text=="string").map(n=>({id:U("m"),role:n.role,text:n.text,images:Array.isArray(n.images)?n.images.filter(i=>v(i,{image:!0})):[],sources:Array.isArray(n.sources)?n.sources:[],artifacts:Q(n.artifacts),run:n.run&&typeof n.run=="object"?n.run:null,messageId:typeof n.messageId=="string"?n.messageId:"",feedback:n.feedback==="up"||n.feedback==="down"?n.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-ct).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(n=>n.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=b.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=b.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=z;let n=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:n})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:b.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:b.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",b.lock],origin:["Not available here","This chat is not available on this site.",b.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",b.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",b.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=z;let n=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),n])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let s=`${i.id}:${i.rev}:${i===t?"last":""}`,a=this.nodes.get(i.id);(!a||a.dataset.key!==s)&&(a=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),a.dataset.key=s,this.nodes.set(i.id,a)),e.push(a)}let n=Array.from(this.thread.children);(n.length!==e.length||n.some((i,s)=>i!==e[s]))&&this.thread.replaceChildren(...e)}renderUser(e){var n,i;let t=c("div",{class:"dc-body"});return(n=e.images)!=null&&n.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(s=>c("img",{src:s,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(s=>c("span",{class:"dc-file-chip",html:b.doc},[s])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var o,d,p;let n=this.config,i=c("div",{class:"dc-avatar"});n.botAvatar||n.avatar?i.append(c("img",{src:n.botAvatar||n.avatar,alt:""})):i.innerHTML=z;let s=c("div",{class:"dc-body"});e.run&&s.append(this.renderRun(e.run,e.status==="streaming"));let a=c("div",{class:"dc-bot-bubble"});if(e.text){let l=ke(e.text,this.base);e.status!=="streaming"&&(this.tableSorts.has(e)||this.tableSorts.set(e,new Map),ve(l,this.tableSorts.get(e))),e.status==="streaming"&&l.classList.add("dc-caret"),a.append(l)}else e.status==="streaming"&&a.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return a.childNodes.length&&s.append(a),(o=e.artifacts)!=null&&o.length&&s.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&s.append(this.renderSources(e.sources)),e.error&&s.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&s.append(this.renderAction(e)),e.status==="done"&&e.text&&s.append(this.renderTools(e)),t&&e.status==="done"&&((p=e.followUps)!=null&&p.length)&&!this.busy&&s.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(l=>c("button",{class:"dc-chip",type:"button",text:l,onclick:()=>this.send(l)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),s])}renderRun(e,t){let n=e.phase==="done",i=e.specialists.length,s={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",a=t?K(e):null,o=n&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Z(e.totalMs)}`:a?Y(Date.now()-e.startedAt):t?"Working\u2026":"",d=c("details",{class:"dc-run"});!n&&t&&(d.open=!0);let p=c("summary",{},[c("span",{class:"dc-run-icon",html:b.spark}),c("span",{class:"dc-run-title",text:s}),c("span",{class:a?"dc-run-meta dc-run-elapsed":"dc-run-meta",text:o,"aria-hidden":a?"true":null}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);if(d.append(p),a){let l=this.liveSinceFor(a.line,Date.now());d.append(c("div",{class:"dc-run-live"},[c("span",{class:"dc-run-line",text:a.line}),c("span",{class:"dc-run-enhanced","aria-hidden":"true",text:this.enhancedLineFor(a.phase,Date.now()-l.at)})]))}return i&&d.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),a&&a.perSpecialist[l.name]?c("span",{class:"dc-step-live",text:a.perSpecialist[l.name]}):c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Z(l.ms)}):null])))),d}enhancedLineFor(e,t){return this.enhancedRotator||(this.enhancedRotator=pe()),this.enhancedRotator.line(e,t,this.config.enhancedStatus)}liveSinceFor(e,t){return(!this.liveSince||this.liveSince.line!==e)&&(this.liveSince={line:e,at:t}),this.liveSince}tickLive(e){let t=K(e.run),n=this.nodes.get(e.id);if(!t||!n||e.status!=="streaming")return;let i=Date.now(),s=this.liveSinceFor(t.line,i),a=n.querySelector(".dc-run-elapsed");a&&(a.textContent=Y(i-e.run.startedAt));let o=n.querySelector(".dc-run-enhanced");o&&(o.textContent=this.enhancedLineFor(t.phase,i-s.at));let d=he(this.liveSpoken,t.line,i);d!==this.liveSpoken&&(this.liveSpoken=d,this.announce(t.line))}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let n of e)if(n.type==="png"||n.type==="jpeg"||n.type==="jpg"||n.type==="gif"||n.type==="webp")t.append(this.renderImageArtifact(n));else if(Ae.includes(n.type)&&n.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(n));else{if(Ae.includes(n.type))continue;if(n.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=n.data,t.append(i)}else n.data&&t.append(ke(n.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,Te(e),e.type.toUpperCase())}renderDownloadLink(e,t,n,i=""){let s=!e.data.startsWith("data:"),a=()=>s?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,o=c("a",{class:`dc-file${i}`,href:a(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:n}),c("span",{class:"dc-file-name",text:t})]);return o.addEventListener("click",async d=>{if(!s||!this.sessionToken||!this.chatId){o.href=a();return}d.preventDefault();try{let p=await this.api.fileBlob(a(),this.sessionToken),l=URL.createObjectURL(p);c("a",{href:l,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}catch{o.replaceWith(c("div",{class:"dc-figure-missing",html:b.alert},[`${t} could not be downloaded here.`]))}}),o}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":Te(e),n=e.type==="jpeg"?"jpg":e.type;return(n==="jpg"?/\.jpe?g$/i:new RegExp(`\\.${n}$`,"i")).test(t)?t:`${t.replace(/\.[^.]*$/,"")||"image"}.${n}`}renderImageArtifact(e){let t=e.type==="jpg"?"jpeg":e.type,n=new RegExp(`^data:image/${t};base64,[A-Za-z0-9+/]+={0,2}$`).test(e.data),i=e.data.startsWith("FILE-STORAGE::")||!/[:/\\]/.test(e.data),s=n?e.data:v(e.data,{image:!0,base:this.base}),a=s&&!e.data.startsWith("/")?s:this.api.fileUrl(this.chatId,e.data),o=c("figure",{class:"dc-figure"}),d=c("img",{src:a,alt:"Chart from the answer",loading:"lazy"});d.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let p=!1;if(d.addEventListener("error",async()=>{if(!p&&!s&&this.sessionToken&&this.chatId){p=!0;try{let l=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);d.src=URL.createObjectURL(l);return}catch{}}d.replaceWith(c("div",{class:"dc-figure-missing",html:b.image},["This chart could not be shown here."]))}),o.append(d),i||n){let l=this.imageArtifactName(e),f=(e.type==="jpeg"?"jpg":e.type).toUpperCase();o.append(this.renderDownloadLink(e,l,f," dc-image-download"))}return o}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),n=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((s,a)=>{let o=[c("b",{text:String(a+1)}),c("span",{text:s.title})],d;s.url?d=c("a",{class:"dc-source",href:s.url,target:"_blank",rel:"noopener noreferrer nofollow",title:s.title},o):(d=c("button",{class:"dc-source",type:"button",title:s.title,"aria-expanded":"false"},o),d.addEventListener("click",()=>{let p=d.getAttribute("aria-expanded")!=="true";n.querySelectorAll("button.dc-source").forEach(l=>l.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,p&&s.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:s.excerpt}),t.append(i))})),n.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(n),t}renderError(e,t){let n=[c("div",{text:e.error})];return t&&e.retry&&n.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:b.alert}),c("div",{},n)])}renderAction(e){var n;let t=Array.isArray((n=e.action)==null?void 0:n.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,s)=>c("button",{class:`dc-chip${s===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:b.copy});t.addEventListener("click",()=>this.copy(e.text,t));let n=[t];if(this.config.feedback&&e.messageId)for(let[i,s,a]of[["up",b.up,"Good answer"],["down",b.down,"Bad answer"]])n.push(c("button",{class:"dc-tool",type:"button","aria-label":a,title:a,"aria-pressed":e.feedback===i?"true":"false",html:s,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},n)}renderComposer(){let e=this.config.imageUpload,t=this.config.fileUpload,n=t?"Attach a file":"Attach an image";this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",a=>{a.key==="Enter"&&!a.shiftKey&&!a.isComposing&&(a.preventDefault(),this.send())});let i=[];(e||t)&&(this.fileInput=c("input",{type:"file",accept:[...(e==null?void 0:e.types)||[],...(t==null?void 0:t.types)||[]].join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),i.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":n,title:n,html:b.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",a=>{var d;let o=Array.from(((d=a.clipboardData)==null?void 0:d.files)||[]);o.length&&(a.preventDefault(),this.addFiles(o))}),this.window.addEventListener("dragover",a=>{a.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:t?"Drop a file to attach":"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",a=>{a.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",a=>{var o;a.preventDefault(),this.clearDrop(),this.addFiles(((o=a.dataTransfer)==null?void 0:o.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),i.push(this.input,this.sendBtn),this.updateSendButton();let s=c("div",{class:"dc-foot"},["Built with ",c("a",{href:dt,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},i),s])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?b.stop:b.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length&&!this.pendingNote,this.pendingEl.replaceChildren(...this.pendingNote?[c("div",{class:"dc-pending-note",role:"status",text:this.pendingNote})]:[],...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[e.file?c("span",{class:"dc-file-chip",html:b.doc},[e.name]):c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:b.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){var i;let t=this.config.imageUpload,n=this.config.fileUpload;if(!(!t&&!n)){this.pendingNote="";for(let s of Array.from(e||[])){if(this.pending.length>=4){this.pendingNote=`Up to 4 attachments per message. ${s.name} and any later files were not added.`,this.announce(this.pendingNote);break}if(!(t!=null&&t.types.includes(s.type))){let o=((i=/\.[^./\\]+$/.exec(String(s.name||"").toLowerCase()))==null?void 0:i[0])||"";!n||!n.types.includes(o)?this.announce(`${s.name} is not a ${n?"file":"image"} this chat accepts.`):!s.size||s.size>n.maxMB*1024*1024?this.announce(`${s.name} is empty or larger than ${n.maxMB} MB.`):this.pending.push({file:s,name:s.name,mime:s.type});continue}if(s.size>t.maxMB*1024*1024){this.announce(`${s.name} is larger than ${t.maxMB} MB.`);continue}let a=await new Promise(o=>{let d=new FileReader;d.onload=()=>o(typeof d.result=="string"?d.result:""),d.onerror=()=>o(""),d.readAsDataURL(s)});a&&v(a,{image:!0})&&this.pending.push({data:a,name:s.name,mime:s.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var n;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(n=t.scrollTo)==null||n.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let n=!1;try{await navigator.clipboard.writeText(e),n=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{n=document.execCommand("copy")}catch{n=!1}i.remove()}t&&(t.innerHTML=n?b.check:b.copy,setTimeout(()=>{t.innerHTML=b.copy},1500)),this.announce(n?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let n=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=n,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let n=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let s=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:s,startNodeId:n.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),n=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(n.text,n.extra,n.uploads,n.files)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},n,i){var m;if(this.state!=="ready"||this.busy)return;let s=typeof e=="string"?e:((m=this.input)==null?void 0:m.value)||"",a=n||this.pending.filter(h=>!h.file).map(h=>({data:h.data,type:"file",name:h.name,mime:h.mime})),o=i||this.pending.filter(h=>h.file).map(h=>h.file);if(!s.trim()&&!a.length&&!o.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.pendingNote="",this.renderPending();let d={id:U("m"),role:"user",text:s.trim(),images:a.map(h=>h.data),files:o.map(h=>h.name),status:"done",rev:0},p={id:U("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(d,p),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let l={question:s.trim()};this.chatId&&(l.chatId=this.chatId),this.sessionToken&&(l.sessionToken=this.sessionToken),a.length&&(l.uploads=a),o.length&&(l.files=o),t.humanInput&&(l.humanInput=t.humanInput),t.action&&(l.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(l.overrideConfig=this.options.overrideConfig);let f=new AbortController;this.controller=f;let u=()=>{p.rev++,this.scheduleRender()};this.liveSince=null,this.liveSpoken=null,clearInterval(this.liveTimer),this.liveTimer=setInterval(()=>this.tickLive(p),1e3);try{await this.api.send(l,{onEvent:h=>this.onEvent(p,h,u),onJson:h=>this.onJson(p,h)},f.signal),!p.text&&!p.error&&!p.artifacts.length&&!p.action&&(p.text=p.fallbackText||""),!p.text&&!p.error&&!p.artifacts.length&&!p.action&&(p.error="The answer was empty. Try asking another way.")}catch(h){if(f.signal.aborted)p.text||(p.text="_Stopped._");else{let g=I(h,this.config.errorMessage);if(g.kind==="private"||g.kind==="origin"){this.setBusy(!1),this.block(g);return}p.error=g.message,p.retry={text:s.trim(),extra:t,uploads:a,files:o}}}finally{this.controller===f&&(this.controller=null),clearInterval(this.liveTimer),this.liveTimer=null}p.status="done",p.run&&p.run.phase!=="done"&&p.run.phase!=="failed"&&(p.run=L(p.run,p.error?"error":"final",{})),p.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(p.error?p.error:`Answer: ${p.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,n){let{event:i,data:s}=t;if(i==="token"&&typeof s=="string")return e.text+=s,n();if(i==="start")return n();if(i==="sourceDocuments")return e.sources=Se(s),n();if(i==="artifacts")return e.artifacts=Q(s),n();if(i==="action")return e.action=s&&typeof s=="object"?s:null,e.actionRaw=s,n();if(i==="agentFlowExecutedData"){e.fallbackText=Ce(s)||e.fallbackText;return}if(i==="metadata"&&s&&typeof s=="object")return typeof s.chatId=="string"&&(this.chatId=s.chatId),typeof s.sessionToken=="string"&&(this.sessionToken=s.sessionToken),typeof s.chatMessageId=="string"&&(e.messageId=s.chatMessageId),s.followUpPrompts&&(e.followUps=Ee(s.followUpPrompts)),s.action&&!e.action&&(e.action=s.action,e.actionRaw=s.action),n();if(i==="error"){let a=typeof t.status=="number"?t.status:0,o=a?I({status:a},this.config.errorMessage):null;return e.error=o&&o.kind!=="error"?o.message:this.config.errorMessage||(typeof s=="string"&&s?s.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=L(e.run,"error",{message:e.error})),n()}if(typeof i=="string"&&i.startsWith("harness.")){let a=i.slice(8);if(a==="recorded")return;let o=s&&typeof s=="object"?s:{};return e.run=L(e.run||H(o.harness),a,o),a==="partial"&&o.phase==="answer"&&!o.streamedAsToken&&typeof o.text=="string"&&(e.text+=o.text),a==="final"&&!e.text&&typeof o.text=="string"&&(e.fallbackText=o.text),n()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=Ce(t.agentFlowExecutedData)),e.sources=Se(t.sourceDocuments),e.artifacts=Q(t.artifacts),t.followUpPrompts&&(e.followUps=Ee(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?pt(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=L(H(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;clearInterval(this.liveTimer),this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function pt(r){try{return JSON.parse(r)}catch{return null}}var Me="cuttlely-chat";function P(r,e={}){var n;if(!r)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(n=r.__cuttlelyChat)==null||n.destroy();let t=new O(r,e);return r.__cuttlelyChat=t,t}function F(r,e){let t=r.getAttribute(e);return t===null||t===""?void 0:t}function $e(r){if(typeof customElements>"u"||customElements.get(Me))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(n,i,s){!this.isConnected||i===s||(n==="theme"&&this.widget?this.widget.setTheme(s||"auto"):this.render())}disconnectedCallback(){var n;(n=this.widget)==null||n.destroy(),this.widget=null}render(){let n=F(this,"flow-id");n&&(this.widget=P(this,{flowId:n,apiHost:F(this,"api-host")||r,mode:F(this,"mode")==="page"?"page":"bubble",theme:F(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var n;(n=this.widget)==null||n.open()}close(){var n;(n=this.widget)==null||n.close()}reset(){var n;(n=this.widget)==null||n.reset()}}customElements.define(Me,e)}var M=typeof document<"u"?document.currentScript:null,X=(()=>{try{return M&&M.src?new URL(M.src).origin:location.origin}catch{return location.origin}})();$e(X);function Ie(){let r=(M==null?void 0:M.dataset)||{},e=r.flowId||r.flowid;if(!e)return;let t=r.mode==="page"?"page":"bubble",n;t==="page"&&r.target&&(n=document.querySelector(r.target)),n||(n=document.createElement("cuttlely-chat-root"),n.style.display=t==="page"?"block":"contents",t==="page"&&(n.style.height="100%"),document.body.append(n)),P(n,{flowId:e,apiHost:r.apiHost||X,mode:t,theme:r.theme||"auto",open:r.open==="true"})}var ht={mount:(r,e)=>P(r,{apiHost:X,...e}),version:"1.6.0"};typeof window<"u"&&(window.cuttlelyChat=ht);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ie,{once:!0}):Ie());})();
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- var fe={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(s){return String(s??"").replace(/[&<>"']/g,e=>fe[e])}function F(s){let e=String(s??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Y=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function w(s,{image:e=!1,base:t=""}={}){if(typeof s!="string")return null;let r=s.trim();return!r||r.length>4096||/[\u0000-\u001f\u007f\s]/.test(r)&&!(e&&Y.test(r))?null:e&&/^data:/i.test(r)?Y.test(r)?r.replace(/\s+/g,""):null:/^https?:\/\//i.test(r)||!e&&/^mailto:[^/]/i.test(r)?r:r.startsWith("/")&&!r.startsWith("//")&&!r.startsWith("/\\")?t?F(t)+r:r:null}var ue=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function ge(s,e){let t=0;for(let r=e;r<s.length;r++){let i=s[r];if(i==="\\"){r++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return r}return-1}function me(s,e){if(s[e]!=="(")return null;let t=e+1;for(;s[t]===" ";)t++;let r="";if(s[t]==="<"){let i=s.indexOf(">",t);if(i===-1)return null;r=s.slice(t+1,i),t=i+1}else{let i=0,a=t;for(;t<s.length;t++){let o=s[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")break}r=s.slice(a,t)}for(;s[t]===" ";)t++;if(s[t]==='"'||s[t]==="'"){let i=s[t],a=s.indexOf(i,t+1);if(a===-1)return null;for(t=a+1;s[t]===" ";)t++}return s[t]!==")"?null:{url:r,end:t+1}}var be=/^https?:\/\/[^\s<>"'`]+/i;function xe(s){let e=s.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function ye(s,e,t){let r=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,a]of r){if(!s.startsWith(i,e))continue;let o=s[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(s[e-1]))continue;let n=s.indexOf(i,e+i.length+1);for(;n!==-1;){let l=s[n-1],h=s[n+i.length],g=i[0]==="_"&&h&&/[a-z0-9]/i.test(h),p=i.length===1&&h===i;if(l&&!/\s/.test(l)&&!g&&!p)break;n=s.indexOf(i,n+1)}if(n===-1)continue;let d=s.slice(e+i.length,n);return{html:`<${a}>${C(d,t)}</${a}>`,end:n+i.length}}return null}function C(s,e={}){let t="",r="",i=()=>{r&&(t+=v(r).replace(/\n/g,"<br>")),r=""};for(let a=0;a<s.length;){let o=s[a];if(o==="\\"&&ue.test(s[a+1]||"")){r+=s[a+1],a+=2;continue}if(o==="`"){let n=1;for(;s[a+n]==="`";)n++;let d="`".repeat(n),l=s.indexOf(d,a+n);if(l!==-1){i();let h=s.slice(a+n,l).replace(/\n/g," ");/^ .* $/.test(h)&&(h=h.slice(1,-1)),t+=`<code>${v(h)}</code>`,a=l+n;continue}r+=d,a+=n;continue}if(o==="!"&&s[a+1]==="["||o==="["){let n=o==="!",d=n?a+1:a,l=ge(s,d),h=l!==-1?me(s,l+1):null;if(h){let g=s.slice(d+1,l),p=w(h.url,{image:n,base:e.base});i(),n?t+=p?`<img src="${v(p)}" alt="${v(g)}" loading="lazy">`:v(g):p&&!e.inLink?t+=`<a href="${v(p)}" target="_blank" rel="noopener noreferrer nofollow">${C(g,{...e,inLink:!0})}</a>`:t+=C(g,e),a=h.end;continue}}if(o==="<"){let n=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(s.slice(a));if(n){let d=w(n[1]);if(d&&!e.inLink){i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(n[1])}</a>`,a+=n[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(a===0||/[\s(]/.test(s[a-1]))){let n=be.exec(s.slice(a));if(n){let d=xe(n[0]);i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(d)}</a>`,a+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let n=ye(s,a,e);if(n){i(),t+=n.html,a=n.end;continue}}r+=o,a++}return i(),t}var K=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,X=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,Z=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,B=/^ {0,3}> ?(.*)$/,M=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,Q=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function j(s){let e=s.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],r="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(r+="|",i++):e[i]==="|"?(t.push(r.trim()),r=""):r+=e[i];return t.push(r.trim()),t}function we(s,e){return K.test(s)||X.test(s)||Z.test(s)||B.test(s)||M.test(s)||s.includes("|")&&e!==void 0&&Q.test(e)&&e.includes("-")}function ve(s,e){return`<div class="md-code"><div class="md-code-head"><span>${s?v(s.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${v(e)}</code></pre></div>`}function ke(s,e){let t=j(s[0]),r=j(s[1]).map(o=>{let n=o.startsWith(":"),d=o.endsWith(":");return n&&d?"center":d?"right":n?"left":""}),i=(o,n,d)=>{let l=r[d]?` style="text-align:${r[d]}"`:"";return`<${o}${l}>${C(n,e)}</${o}>`},a='<div class="md-table"><table><thead><tr>';a+=t.map((o,n)=>i("th",o,n)).join(""),a+="</tr></thead><tbody>";for(let o of s.slice(2)){let n=j(o);a+="<tr>"+t.map((d,l)=>i("td",n[l]??"",l)).join("")+"</tr>"}return a+"</tbody></table></div>"}function Te(s,e,t){let r=M.exec(s[e]),i=/\d/.test(r[2]),a=r[1].length,o=[],n=e,d=!1;for(;n<s.length;){let p=M.exec(s[n]);if(!p||p[1].length!==a||/\d/.test(p[2])!==i)break;let u=a+p[2].length+1,m=[p[3]??""];n++;let y=!1;for(;n<s.length;){let b=s[n];if(!b.trim()){y=!0,m.push(""),n++;continue}let A=b.length-b.trimStart().length,k=M.exec(b);if(k&&k[1].length<=a)break;if(A<Math.min(u,a+2)&&!k){if(y)break;m.push(b.trim()),n++;continue}y&&(d=!0),y=!1,m.push(b.slice(Math.min(A,u))),n++}for(;m.length&&!m[m.length-1].trim();)m.pop();o.push(m)}let l=i&&parseInt(r[2],10)!==1?` start="${parseInt(r[2],10)}"`:"",h=i?"ol":"ul",g=o.map(p=>{let u=p.join(`
2
- `),m="",y=/^\[([ xX])\]\s+/.exec(u);y&&(m=`<span class="md-task" aria-hidden="true">${y[1]===" "?"\u2610":"\u2611"}</span> `,u=u.slice(y[0].length));let b=P(u.split(`
3
- `),t);return d||(b=b.replace(/^<p>([\s\S]*?)<\/p>/,(A,k)=>k)),`<li>${m}${b}</li>`}).join("");return{html:`<${h}${l}>${g}</${h}>`,end:n}}function P(s,e){let t="",r=0;for(;r<s.length;){let i=s[r];if(!i.trim()){r++;continue}let a=K.exec(i);if(a){let d=a[1],l=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(s[r]);)l.push(s[r]),r++;r++,t+=ve(a[2],l.join(`
4
- `));continue}let o=X.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,r++;continue}if(Z.test(i)){t+="<hr>",r++;continue}if(B.test(i)){let d=[];for(;r<s.length&&s[r].trim()&&B.test(s[r]);)d.push(B.exec(s[r])[1]),r++;t+=`<blockquote>${P(d,e)}</blockquote>`;continue}if(i.includes("|")&&r+1<s.length&&Q.test(s[r+1])&&s[r+1].includes("-")){let d=[i,s[r+1]];for(r+=2;r<s.length&&s[r].trim()&&s[r].includes("|");)d.push(s[r]),r++;t+=ke(d,e);continue}if(M.test(i)){let d=Te(s,r,e);t+=d.html,r=d.end;continue}let n=[i.trim()];for(r++;r<s.length&&s[r].trim()&&!we(s[r],s[r+1]);)n.push(s[r].trim()),r++;t+=`<p>${C(n.join(`
5
- `),e)}</p>`}return t}function W(s,e={}){if(typeof s!="string"||!s)return"";let t=s.replace(/\r\n?/g,`
1
+ var Ee={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function S(r){return String(r??"").replace(/[&<>"']/g,e=>Ee[e])}function j(r){let e=String(r??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Z=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function v(r,{image:e=!1,base:t=""}={}){if(typeof r!="string")return null;let n=r.trim();return!n||n.length>4096||/[\u0000-\u001f\u007f\s]/.test(n)&&!(e&&Z.test(n))?null:e&&/^data:/i.test(n)?Z.test(n)?n.replace(/\s+/g,""):null:/^https?:\/\//i.test(n)||!e&&/^mailto:[^/]/i.test(n)?n:n.startsWith("/")&&!n.startsWith("//")&&!n.startsWith("/\\")?t?j(t)+n:n:null}var Ce=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function Me(r,e){let t=0;for(let n=e;n<r.length;n++){let i=r[n];if(i==="\\"){n++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return n}return-1}function $e(r,e){if(r[e]!=="(")return null;let t=e+1;for(;r[t]===" ";)t++;let n="";if(r[t]==="<"){let i=r.indexOf(">",t);if(i===-1)return null;n=r.slice(t+1,i),t=i+1}else{let i=0,s=t;for(;t<r.length;t++){let a=r[t];if(a==="\\"){t++;continue}if(a==="(")i++;else if(a===")"){if(i===0)break;i--}else if(a===" ")break}n=r.slice(s,t)}for(;r[t]===" ";)t++;if(r[t]==='"'||r[t]==="'"){let i=r[t],s=r.indexOf(i,t+1);if(s===-1)return null;for(t=s+1;r[t]===" ";)t++}return r[t]!==")"?null:{url:n,end:t+1}}var Ie=/^https?:\/\/[^\s<>"'`]+/i;function Le(r){let e=r.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function Re(r,e,t){let n=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,s]of n){if(!r.startsWith(i,e))continue;let a=r[e+i.length];if(!a||/\s/.test(a)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(r[e-1]))continue;let o=r.indexOf(i,e+i.length+1);for(;o!==-1;){let p=r[o-1],l=r[o+i.length],f=i[0]==="_"&&l&&/[a-z0-9]/i.test(l),u=i.length===1&&l===i;if(p&&!/\s/.test(p)&&!f&&!u)break;o=r.indexOf(i,o+1)}if(o===-1)continue;let d=r.slice(e+i.length,o);return{html:`<${s}>${C(d,t)}</${s}>`,end:o+i.length}}return null}function C(r,e={}){let t="",n="",i=()=>{n&&(t+=S(n).replace(/\n/g,"<br>")),n=""};for(let s=0;s<r.length;){let a=r[s];if(a==="\\"&&Ce.test(r[s+1]||"")){n+=r[s+1],s+=2;continue}if(a==="`"){let o=1;for(;r[s+o]==="`";)o++;let d="`".repeat(o),p=r.indexOf(d,s+o);if(p!==-1){i();let l=r.slice(s+o,p).replace(/\n/g," ");/^ .* $/.test(l)&&(l=l.slice(1,-1)),t+=`<code>${S(l)}</code>`,s=p+o;continue}n+=d,s+=o;continue}if(a==="!"&&r[s+1]==="["||a==="["){let o=a==="!",d=o?s+1:s,p=Me(r,d),l=p!==-1?$e(r,p+1):null;if(l){let f=r.slice(d+1,p),u=v(l.url,{image:o,base:e.base});i(),o?t+=u?`<img src="${S(u)}" alt="${S(f)}" loading="lazy">`:S(f):u&&!e.inLink?t+=`<a href="${S(u)}" target="_blank" rel="noopener noreferrer nofollow">${C(f,{...e,inLink:!0})}</a>`:t+=C(f,e),s=l.end;continue}}if(a==="<"){let o=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(r.slice(s));if(o){let d=v(o[1]);if(d&&!e.inLink){i(),t+=`<a href="${S(d)}" target="_blank" rel="noopener noreferrer nofollow">${S(o[1])}</a>`,s+=o[0].length;continue}}}if((a==="h"||a==="H")&&!e.inLink&&(s===0||/[\s(]/.test(r[s-1]))){let o=Ie.exec(r.slice(s));if(o){let d=Le(o[0]);i(),t+=`<a href="${S(d)}" target="_blank" rel="noopener noreferrer nofollow">${S(d)}</a>`,s+=d.length;continue}}if(a==="*"||a==="_"||a==="~"){let o=Re(r,s,e);if(o){i(),t+=o.html,s=o.end;continue}}n+=a,s++}return i(),t}var Q=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,X=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,ee=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,R=/^ {0,3}> ?(.*)$/,M=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,te=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function P(r){let e=r.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],n="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(n+="|",i++):e[i]==="|"?(t.push(n.trim()),n=""):n+=e[i];return t.push(n.trim()),t}function Be(r,e){return Q.test(r)||X.test(r)||ee.test(r)||R.test(r)||M.test(r)||r.includes("|")&&e!==void 0&&te.test(e)&&e.includes("-")}function Ne(r,e){return`<div class="md-code"><div class="md-code-head"><span>${r?S(r.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${S(e)}</code></pre></div>`}function ze(r,e){let t=P(r[0]),n=P(r[1]).map(a=>{let o=a.startsWith(":"),d=a.endsWith(":");return o&&d?"center":d?"right":o?"left":""}),i=(a,o,d)=>{let p=n[d]?` style="text-align:${n[d]}"`:"";return`<${a}${p}>${C(o,e)}</${a}>`},s='<div class="md-table"><table><thead><tr>';s+=t.map((a,o)=>i("th",a,o)).join(""),s+="</tr></thead><tbody>";for(let a of r.slice(2)){let o=P(a);s+="<tr>"+t.map((d,p)=>i("td",o[p]??"",p)).join("")+"</tr>"}return s+"</tbody></table></div>"}function De(r,e,t){let n=M.exec(r[e]),i=/\d/.test(n[2]),s=n[1].length,a=[],o=e,d=!1;for(;o<r.length;){let u=M.exec(r[o]);if(!u||u[1].length!==s||/\d/.test(u[2])!==i)break;let m=s+u[2].length+1,h=[u[3]??""];o++;let g=!1;for(;o<r.length;){let x=r[o];if(!x.trim()){g=!0,h.push(""),o++;continue}let k=x.length-x.trimStart().length,w=M.exec(x);if(w&&w[1].length<=s)break;if(k<Math.min(m,s+2)&&!w){if(g)break;h.push(x.trim()),o++;continue}g&&(d=!0),g=!1,h.push(x.slice(Math.min(k,m))),o++}for(;h.length&&!h[h.length-1].trim();)h.pop();a.push(h)}let p=i&&parseInt(n[2],10)!==1?` start="${parseInt(n[2],10)}"`:"",l=i?"ol":"ul",f=a.map(u=>{let m=u.join(`
2
+ `),h="",g=/^\[([ xX])\]\s+/.exec(m);g&&(h=`<span class="md-task" aria-hidden="true">${g[1]===" "?"\u2610":"\u2611"}</span> `,m=m.slice(g[0].length));let x=W(m.split(`
3
+ `),t);return d||(x=x.replace(/^<p>([\s\S]*?)<\/p>/,(k,w)=>w)),`<li>${h}${x}</li>`}).join("");return{html:`<${l}${p}>${f}</${l}>`,end:o}}function W(r,e){let t="",n=0;for(;n<r.length;){let i=r[n];if(!i.trim()){n++;continue}let s=Q.exec(i);if(s){let d=s[1],p=[];for(n++;n<r.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(r[n]);)p.push(r[n]),n++;n++,t+=Ne(s[2],p.join(`
4
+ `));continue}let a=X.exec(i);if(a){let d=a[1].length;t+=`<h${d}>${C(a[2]||"",e)}</h${d}>`,n++;continue}if(ee.test(i)){t+="<hr>",n++;continue}if(R.test(i)){let d=[];for(;n<r.length&&r[n].trim()&&R.test(r[n]);)d.push(R.exec(r[n])[1]),n++;t+=`<blockquote>${W(d,e)}</blockquote>`;continue}if(i.includes("|")&&n+1<r.length&&te.test(r[n+1])&&r[n+1].includes("-")){let d=[i,r[n+1]];for(n+=2;n<r.length&&r[n].trim()&&r[n].includes("|");)d.push(r[n]),n++;t+=ze(d,e);continue}if(M.test(i)){let d=De(r,n,e);t+=d.html,n=d.end;continue}let o=[i.trim()];for(n++;n<r.length&&r[n].trim()&&!Be(r[n],r[n+1]);)o.push(r[n].trim()),n++;t+=`<p>${C(o.join(`
5
+ `),e)}</p>`}return t}function q(r,e={}){if(typeof r!="string"||!r)return"";let t=r.replace(/\r\n?/g,`
6
6
  `).replace(/\t/g," ").split(`
7
- `);return P(t,{base:e.base||""})}function ee(s){let e="",t=r=>{let i=[];for(let n of r.split(/\r?\n/))n.startsWith("data:")&&i.push(n.slice(n[5]===" "?6:5));if(!i.length)return;let a=i.join(`
8
- `),o;try{o=JSON.parse(a)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let a=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(a)}},end(){e.trim()&&t(e),e=""}}}var q=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function z(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new q(s.status,String(e||"").slice(0,300))}function te({apiHost:s,flowId:e,fetchImpl:t}){let r=F(s||""),i=encodeURIComponent(e),a=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await a(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await z(o);let n=await o.text();try{return JSON.parse(n)}catch{return{}}},async send(o,n={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,S]of Object.entries(h))S!=null&&A.append(k,typeof S=="object"?JSON.stringify(S):String(S));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await a(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await z(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ee(D=>{var L;return(L=n.onEvent)==null?void 0:L.call(n,D)}),k=p.body.getReader(),S=new TextDecoder;for(;;){let{value:D,done:L}=await k.read();if(L)break;A.push(S.decode(D,{stream:!0}))}A.push(S.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=n.onJson)==null||b.call(n,y)},async feedback({messageId:o,chatId:n,rating:d}){let l=await a(`${r}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:n,messageId:o,rating:d})});if(!l.ok)throw await z(l)},fileUrl(o,n){let d=String(n||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,n){let d=await a(o,{headers:n?{"x-cuttlely-session-token":n}:{}});if(!d.ok)throw await z(d);return d.blob()}}}function $(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Ae={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},Ee=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!Ee.test(t)||e&&((r=Ae[e])!=null&&r.includes(t.toLowerCase()))?"":t}function E(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function re(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>E(t,300)).filter(Boolean).slice(0,6)}function Se(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let a of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof a=="string"&&e.add(a);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function R(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},a=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},n=Se(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:E(t.title,80),avatar:w(E(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(E(r.avatarSrc),{image:!0})||"",welcome:E(t.welcomeMessage),errorMessage:E(t.errorMessage,300),placeholder:E(a.placeholder,120),starterPrompts:re(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&n.types.length?n:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(a.backgroundColor,"inputBackground"),inputText:T(a.textColor,"inputText"),accent:T(a.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=re(u):p==="avatar"?l.avatar=w(E(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=E(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ie(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},O='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function H(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function J(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let a=s.slice();return a[i]={...a[i],...t},a}function I(s,e,t={}){var a,o;let r=s||H(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let n of Array.isArray(t.steps)?t.steps:[])i.specialists=J(i.specialists,n.specialist,{task:typeof n.task=="string"?n.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=J(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=J(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let n=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;n?i.specialists=n.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((a=t.trace)==null?void 0:a.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function V(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Ce={A:["href","target","rel"],BLOCKQUOTE:[],BR:[],BUTTON:["type","class","data-copy-code","aria-label"],CODE:[],DEL:[],DIV:["class"],EM:[],H1:[],H2:[],H3:[],H4:[],H5:[],H6:[],HR:[],IMG:["src","alt","loading"],LI:[],OL:["start"],P:[],PRE:[],SPAN:["class","aria-hidden"],STRONG:[],TABLE:[],TBODY:[],TD:["style"],TH:["style"],THEAD:[],TR:[],UL:[]},Me=/^text-align:(left|right|center)$/;function se(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Ce[r.tagName];if(!i)t.push(r);else{for(let a of Array.from(r.attributes)){let o=a.name.toLowerCase(),n=i.includes(o);n&&(o==="href"||o==="src")&&(n=w(a.value,{image:o==="src"})!==null),n&&o==="style"&&(n=Me.test(a.value)),n&&o==="target"&&(n=a.value==="_blank"),n||r.removeAttribute(a.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ae=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-figure .dc-image-download{border:0;border-top:1px solid var(--dc-border);border-radius:0;padding:8px 12px}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var $e="cuttlely-chat:v1:",Ie=60,Le="https://github.com/cuttlely/cuttlely",Be=0,U=s=>`${s}-${Date.now().toString(36)}-${(Be++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,a]of Object.entries(e||{}))a==null||a===!1||(i==="class"?r.className=a:i==="text"?r.textContent=a:i==="html"?r.innerHTML=a:i.startsWith("on")&&typeof a=="function"?r.addEventListener(i.slice(2),a):r.setAttribute(i,a===!0?"":String(a)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function ne(s,e){let t=document.createElement("template");t.innerHTML=W(s,{base:e}),se(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function oe(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let a=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof a.url=="string"?a.url:typeof a.source=="string"?a.source:""),n=a.title||a.source||a.url||a.name||i.title||"",d=String(n||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function G(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var ce=["pdf","docx","xlsx","pptx","csv"];function de(s){let e=typeof(s==null?void 0:s.name)=="string"?s.name:"",t=String((s==null?void 0:s.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(s==null?void 0:s.type)||"bin"}`}function le(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function pe(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let a=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof a=="string"&&a.trim())return a}return""}var _=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=te({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=R({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=U("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:ae});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,a,o;let e=this.options.theme,t=n=>this.wrap.classList.toggle("dark",n);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var n;return t(!!((n=this.media)!=null&&n.matches))},this.onMedia(),(o=(a=this.media)==null?void 0:a.addEventListener)==null||o.call(a,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ie(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=R(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=$(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${$e}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:U("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:G(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-Ie).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let a=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==a)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=a,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,a)=>i!==e[a]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(a=>c("img",{src:a,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(a=>c("span",{class:"dc-file-chip",html:f.doc},[a])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var n,d,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=O;let a=c("div",{class:"dc-body"});e.run&&a.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=ne(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&a.append(o),(n=e.artifacts)!=null&&n.length&&a.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&a.append(this.renderSources(e.sources)),e.error&&a.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&a.append(this.renderAction(e)),e.status==="done"&&e.text&&a.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&a.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),a])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,a={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${V(e.totalMs)}`:t?"Working\u2026":"",n=c("details",{class:"dc-run"});!r&&t&&(n.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:a}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return n.append(d),i&&n.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:V(l.ms)}):null])))),n}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(ce.includes(r.type)&&r.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(r));else{if(ce.includes(r.type))continue;if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(ne(r.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,de(e),e.type.toUpperCase())}renderDownloadLink(e,t,r,i=""){let a=!e.data.startsWith("data:"),o=()=>a?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,n=c("a",{class:`dc-file${i}`,href:o(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:r}),c("span",{class:"dc-file-name",text:t})]);return n.addEventListener("click",async d=>{if(!a||!this.sessionToken||!this.chatId){n.href=o();return}d.preventDefault();try{let l=await this.api.fileBlob(o(),this.sessionToken),h=URL.createObjectURL(l);c("a",{href:h,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(h),3e4)}catch{n.replaceWith(c("div",{class:"dc-figure-missing",html:f.alert},[`${t} could not be downloaded here.`]))}}),n}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":de(e),r=e.type==="jpeg"?"jpg":e.type;return(r==="jpg"?/\.jpe?g$/i:new RegExp(`\\.${r}$`,"i")).test(t)?t:`${t.replace(/\.[^.]*$/,"")||"image"}.${r}`}renderImageArtifact(e){let t=e.type==="jpg"?"jpeg":e.type,r=new RegExp(`^data:image/${t};base64,[A-Za-z0-9+/]+={0,2}$`).test(e.data),i=e.data.startsWith("FILE-STORAGE::")||!/[:/\\]/.test(e.data),a=r?e.data:w(e.data,{image:!0,base:this.base}),o=a&&!e.data.startsWith("/")?a:this.api.fileUrl(this.chatId,e.data),n=c("figure",{class:"dc-figure"}),d=c("img",{src:o,alt:"Chart from the answer",loading:"lazy"});d.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let l=!1;if(d.addEventListener("error",async()=>{if(!l&&!a&&this.sessionToken&&this.chatId){l=!0;try{let h=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);d.src=URL.createObjectURL(h);return}catch{}}d.replaceWith(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),n.append(d),i||r){let h=this.imageArtifactName(e),g=(e.type==="jpeg"?"jpg":e.type).toUpperCase();n.append(this.renderDownloadLink(e,h,g," dc-image-download"))}return n}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((a,o)=>{let n=[c("b",{text:String(o+1)}),c("span",{text:a.title})],d;a.url?d=c("a",{class:"dc-source",href:a.url,target:"_blank",rel:"noopener noreferrer nofollow",title:a.title},n):(d=c("button",{class:"dc-source",type:"button",title:a.title,"aria-expanded":"false"},n),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&a.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:a.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,a)=>c("button",{class:`dc-chip${a===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,a,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:a,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let a=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);a.length&&(i.preventDefault(),this.addFiles(a))}),this.window.addEventListener("dragover",i=>{i.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",i=>{i.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",i=>{var a;i.preventDefault(),this.clearDrop(),this.addFiles(((a=i.dataTransfer)==null?void 0:a.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Le,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(a=>{let o=new FileReader;o.onload=()=>a(typeof o.result=="string"?o.result:""),o.onerror=()=>a(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let a=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:a,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",a=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!a.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:U("m"),role:"user",text:i.trim(),images:a.map(p=>p.data),status:"done",rev:0},n={id:U("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,n),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let d={question:i.trim()};this.chatId&&(d.chatId=this.chatId),this.sessionToken&&(d.sessionToken=this.sessionToken),a.length&&(d.uploads=a),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{n.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(n,p,h),onJson:p=>this.onJson(n,p)},l.signal),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.text=n.fallbackText||""),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.error="The answer was empty. Try asking another way.")}catch(p){if(l.signal.aborted)n.text||(n.text="_Stopped._");else{let u=$(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}n.error=u.message,n.retry={text:i.trim(),extra:t,uploads:a}}}finally{this.controller===l&&(this.controller=null)}n.status="done",n.run&&n.run.phase!=="done"&&n.run.phase!=="failed"&&(n.run=I(n.run,n.error?"error":"final",{})),n.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(n.error?n.error:`Answer: ${n.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,r){let{event:i,data:a}=t;if(i==="token"&&typeof a=="string")return e.text+=a,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=oe(a),r();if(i==="artifacts")return e.artifacts=G(a),r();if(i==="action")return e.action=a&&typeof a=="object"?a:null,e.actionRaw=a,r();if(i==="agentFlowExecutedData"){e.fallbackText=pe(a)||e.fallbackText;return}if(i==="metadata"&&a&&typeof a=="object")return typeof a.chatId=="string"&&(this.chatId=a.chatId),typeof a.sessionToken=="string"&&(this.sessionToken=a.sessionToken),typeof a.chatMessageId=="string"&&(e.messageId=a.chatMessageId),a.followUpPrompts&&(e.followUps=le(a.followUpPrompts)),a.action&&!e.action&&(e.action=a.action,e.actionRaw=a.action),r();if(i==="error"){let o=typeof t.status=="number"?t.status:0,n=o?$({status:o},this.config.errorMessage):null;return e.error=n&&n.kind!=="error"?n.message:this.config.errorMessage||(typeof a=="string"&&a?a.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=I(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let n=a&&typeof a=="object"?a:{};return e.run=I(e.run||H(n.harness),o,n),o==="partial"&&n.phase==="answer"&&!n.streamedAsToken&&typeof n.text=="string"&&(e.text+=n.text),o==="final"&&!e.text&&typeof n.text=="string"&&(e.fallbackText=n.text),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=pe(t.agentFlowExecutedData)),e.sources=oe(t.sourceDocuments),e.artifacts=G(t.artifacts),t.followUpPrompts&&(e.followUps=le(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?ze(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=I(H(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function ze(s){try{return JSON.parse(s)}catch{return null}}var he="cuttlely-chat";function Re(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new _(s,e);return s.__cuttlelyChat=t,t}function N(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function rt(s){if(typeof customElements>"u"||customElements.get(he))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,a){!this.isConnected||i===a||(r==="theme"&&this.widget?this.widget.setTheme(a||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=N(this,"flow-id");r&&(this.widget=Re(this,{flowId:r,apiHost:N(this,"api-host")||s,mode:N(this,"mode")==="page"?"page":"bubble",theme:N(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(he,e)}export{_ as ChatWidget,he as ELEMENT_NAME,rt as defineElement,v as escapeHtml,Re as mount,R as normalizeConfig,W as renderMarkdown,w as safeUrl};
7
+ `);return W(t,{base:e.base||""})}function ne(r){let e="",t=n=>{let i=[];for(let o of n.split(/\r?\n/))o.startsWith("data:")&&i.push(o.slice(o[5]===" "?6:5));if(!i.length)return;let s=i.join(`
8
+ `),a;try{a=JSON.parse(s)}catch{return}a&&typeof a=="object"&&typeof a.event=="string"&&r(a)};return{push(n){e+=n;let i;for(;i=/\r?\n\r?\n/.exec(e);){let s=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(s)}},end(){e.trim()&&t(e),e=""}}}var G=class extends Error{constructor(e,t,n){super(t||`Request failed (${e})`),this.status=e,this.code=n||""}};async function B(r){let e="";try{let t=await r.text();try{let n=JSON.parse(t);e=typeof(n==null?void 0:n.message)=="string"?n.message:typeof(n==null?void 0:n.error)=="string"?n.error:""}catch{e=t}}catch{}return new G(r.status,String(e||"").slice(0,300))}function ie({apiHost:r,flowId:e,fetchImpl:t}){let n=j(r||""),i=encodeURIComponent(e),s=t||((...a)=>globalThis.fetch(...a));return{host:n,async loadConfig(){let a=await s(`${n}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!a.ok)throw await B(a);let o=await a.text();try{return JSON.parse(o)}catch{return{}}},async send(a,o={},d){var x;let p=Array.isArray(a.files)?a.files:[],l={...a,streaming:!0};delete l.files;let f;if(p.length){let k=new FormData;for(let[w,E]of Object.entries(l))E!=null&&k.append(w,typeof E=="object"?JSON.stringify(E):String(E));for(let w of p)k.append("files",w,w.name);f={method:"POST",body:k,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else f={method:"POST",body:JSON.stringify(l),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let u=await s(`${n}/api/v1/prediction/${i}`,f);if(!u.ok)throw await B(u);if((u.headers.get("content-type")||"").includes("text/event-stream")&&u.body&&typeof u.body.getReader=="function"){let k=ne(F=>{var L;return(L=o.onEvent)==null?void 0:L.call(o,F)}),w=u.body.getReader(),E=new TextDecoder;for(;;){let{value:F,done:L}=await w.read();if(L)break;k.push(E.decode(F,{stream:!0}))}k.push(E.decode()),k.end();return}let h=await u.text(),g;try{g=JSON.parse(h)}catch{g={text:h}}(x=o.onJson)==null||x.call(o,g)},async feedback({messageId:a,chatId:o,rating:d}){let p=await s(`${n}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:o,messageId:a,rating:d})});if(!p.ok)throw await B(p)},fileUrl(a,o){let d=String(o||"").replace(/^FILE-STORAGE::/,""),p=new URLSearchParams({chatflowId:e,chatId:a||"",fileName:d});return`${n}/api/v1/get-upload-file?${p.toString()}`},async fileBlob(a,o){let d=o?{"x-cuttlely-session-token":o}:{},p=await s(a,{headers:d});if(p.status===403&&o&&(p=await s(a,{headers:d,credentials:"omit"})),!p.ok)throw await B(p);return p.blob()}}}function $(r,e){let t=r==null?void 0:r.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(r==null?void 0:r.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var _e={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},Ue=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function A(r,e){var n;if(typeof r!="string")return"";let t=r.trim();return!Ue.test(t)||e&&((n=_e[e])!=null&&n.includes(t.toLowerCase()))?"":t}function T(r,e=2e3){return typeof r=="string"?r.trim().slice(0,e):""}function re(r){return!r||typeof r!="object"?[]:(Array.isArray(r)?r:Object.keys(r).map(t=>r[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>T(t,300)).filter(Boolean).slice(0,6)}function He(r){if(!Array.isArray(r))return{types:[],maxMB:0};let e=new Set,t=0;for(let n of r){for(let s of Array.isArray(n==null?void 0:n.fileTypes)?n.fileTypes:[])typeof s=="string"&&e.add(s);let i=Number(n==null?void 0:n.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function N(r,e={}){var f,u,m;let t=r&&typeof r=="object"?r:{},n=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},s=t.textInput&&typeof t.textInput=="object"?t.textInput:{},a=t.uploads&&typeof t.uploads=="object"?t.uploads:{},o=He(a.imgUploadSizeAndTypes),d=Array.isArray(a.fullFileUploadTypes)?a.fullFileUploadTypes.filter(h=>typeof h=="string"&&/^\.[a-z0-9]+$/.test(h)):[],p=Number(t.fontSize),l={title:T(t.title,80),avatar:v(T(t.titleAvatarSrc),{image:!0})||"",botAvatar:n.showAvatar&&v(T(n.avatarSrc),{image:!0})||"",welcome:T(t.welcomeMessage),errorMessage:T(t.errorMessage,300),placeholder:T(s.placeholder,120),starterPrompts:re(t.starterPrompts),feedback:!!((f=t.chatFeedback)!=null&&f.status),followUps:!!((u=t.followUpPrompts)!=null&&u.status),newSessionEachVisit:!!t.generateNewSession,enhancedStatus:((m=t.enhancedStatusMessages)==null?void 0:m.status)!==!1,imageUpload:a.isImageUploadAllowed&&o.types.length?o:null,fileUpload:a.isFullFileUploadAllowed&&d.length?{types:d,maxMB:25}:null,fontSize:Number.isFinite(p)&&p>=12&&p<=22?p:0,colors:{headerBg:A(t.titleBackgroundColor,"titleBackgroundColor"),headerText:A(t.titleTextColor,"titleTextColor"),background:A(t.backgroundColor,"backgroundColor"),botBg:A(n.backgroundColor,"botBackground"),botText:A(n.textColor,"botText"),userBg:A(i.backgroundColor,"userBackground"),userText:A(i.textColor,"userText"),inputBg:A(s.backgroundColor,"inputBackground"),inputText:A(s.textColor,"inputText"),accent:A(s.sendButtonColor,"sendButton")}};for(let[h,g]of Object.entries(e||{}))if(!(g==null||g===""))if(h==="colors"&&typeof g=="object")for(let[x,k]of Object.entries(g)){let w=A(k);w&&x in l.colors&&(l.colors[x]=w)}else h==="starterPrompts"?l.starterPrompts=re(g):h==="avatar"?l.avatar=v(T(g),{image:!0})||l.avatar:typeof l[h]=="string"?l[h]=T(g):typeof l[h]=="boolean"&&(l[h]=!!g);return l}function se(r){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,n])=>A(r==null?void 0:r[t])?`${n}:${r[t]};`:"").join("")}var y=(r,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${r}</svg>`,b={chat:y('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:y('<path d="M6 6l12 12M18 6L6 18"/>'),send:y('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:y('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:y('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:y('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:y('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:y('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:y('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:y('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:y('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:y('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:y('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:y('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:y('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:y('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},z='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';var Oe={route:["Activating agent swarm\u2026","Spinning up the reasoning mesh\u2026","Checking available context windows\u2026","Mapping the intent graph\u2026","Scoring specialist affinity vectors\u2026","Bootstrapping the planner loop\u2026","Warming up the routing layer\u2026","Sharding the question into sub-goals\u2026","Negotiating the agent handshake\u2026","Resolving the task topology\u2026","Computing the optimal dispatch plan\u2026","Balancing the inference load\u2026","Embedding the request in latent space\u2026","Aligning the orchestration graph\u2026","Allocating the attention budget\u2026","Priming the zero-shot router\u2026","Consulting the mixture of experts\u2026","Plotting the agentic workflow\u2026","Tokenizing the intent\u2026","Selecting the reasoning strategy\u2026","Booting the multi-agent runtime\u2026","Assembling the dream team\u2026","Calibrating the semantic compass\u2026","Drafting the execution graph\u2026"],working:["Performing deep analysis\u2026","Running multi-hop reasoning\u2026","Orchestrating parallel inference\u2026","Expanding the chain of thought\u2026","Decomposing the problem space\u2026","Grounding the hypotheses\u2026","Traversing the knowledge graph\u2026","Hydrating the working memory\u2026","Scaling test-time compute\u2026","Exploring the solution manifold\u2026","Running agentic planning cycles\u2026","Sampling candidate trajectories\u2026","Building the reasoning scaffold\u2026","Refining the latent plan\u2026","Propagating context through the stack\u2026","Tuning the attention heads\u2026","Crunching the high-dimensional signal\u2026","Running a self-consistency pass\u2026","Simulating counterfactuals\u2026","Iterating on the inner loop\u2026","Distilling the core question\u2026","Stacking the inference layers\u2026","Optimizing the token budget\u2026","Engaging deep focus mode\u2026"],tool:["Cross-checking the numbers\u2026","Lining up the joins\u2026","Vectorizing the signal\u2026","Fusing retrieval results\u2026","Normalizing the feature space\u2026","Streaming results into the context window\u2026","Checking schema alignment\u2026","Deduplicating the evidence set\u2026","Indexing the fresh signal\u2026","Running hybrid retrieval\u2026","Chunking the payload\u2026","Computing similarity scores\u2026","Parsing structured output\u2026","Hardening the result set\u2026","Sanity-checking the aggregates\u2026","Ingesting the response stream\u2026","Warming the cache on the hot path\u2026","Pipelining the function calls\u2026","Running a semantic diff\u2026","Reconciling the data shards\u2026","Batching the inference requests\u2026","Extracting the high-signal rows\u2026","Stress-testing the edge cases\u2026","Checking the guardrails\u2026"],thinking:["Weighing a few angles\u2026","Calibrating confidence intervals\u2026","Re-ranking candidate insights\u2026","Running a reflection pass\u2026","Synthesizing emergent patterns\u2026","Scoring the evidence\u2026","Pruning the hypothesis tree\u2026","Detecting anomalies in the signal\u2026","Triangulating the findings\u2026","Running Bayesian updates\u2026","Converging on a consensus\u2026","Debating with the critic agent\u2026","Collapsing the probability cloud\u2026","Reasoning over the embeddings\u2026","Measuring semantic drift\u2026","Red-teaming the conclusions\u2026","Fact-checking the reasoning chain\u2026","Rebalancing the attention weights\u2026","Extracting latent insights\u2026","Running an ensemble vote\u2026","Grading the reasoning path\u2026","Minimizing the loss of nuance\u2026","Clustering the main findings\u2026","Looking for second-order effects\u2026"],handoff:["Polishing the wording\u2026","Double-checking the totals\u2026","Decoding the final tokens\u2026","Compressing insights into prose\u2026","Running the hallucination filter\u2026","Aligning the tone vectors\u2026","Rendering the narrative layer\u2026","Fine-tuning the phrasing\u2026","Assembling the executive summary\u2026","Applying the clarity optimizer\u2026","Grounding every claim\u2026","Formatting the output tensor\u2026","Smoothing the reasoning seams\u2026","Packaging the insight payload\u2026","Running a final coherence check\u2026","Beam-searching for the best sentence\u2026","Lowering the temperature for precision\u2026","Stitching the agent outputs together\u2026","Shipping the answer to the edge\u2026","Applying the finishing gradient\u2026","Condensing the answer to its essence\u2026","Converting thoughts to plain language\u2026","Running the last-mile alignment\u2026","Sealing the response envelope\u2026"]},ae={query:"a SQL query",describe:"a table description",list_tables:"a table listing",list_relations:"a table listing",pin_definition:"a saved query lookup"},Fe=/^pq_[a-z0-9_]+$/i;function Pe(r){let e=String(r||"").trim(),t=/^mcp__(.+?)__(.+)$/.exec(e);return t?t[2]:e}function je(r,e){let t=Pe(r==null?void 0:r.name);return ae[t]?ae[t]:Fe.test(t)?"a saved query":`${(typeof e=="function"?e(r):"")||t||"a tool"}`}function We(r,e){let t=Array.isArray(r==null?void 0:r.tools)?r.tools:[],n=t.filter(i=>(i==null?void 0:i.status)==="running").pop();if(n){let i=je(n,e);return{phase:"tool",row:`Running ${i}\u2026`,verb:`is running ${i}\u2026`}}return t.length?{phase:"thinking",row:"Thinking about the results\u2026",verb:"is thinking about the results\u2026"}:{phase:"working",row:"Working\u2026",verb:"is working\u2026"}}function oe(r,{toolLabel:e}={}){var d,p;if(!r||r.status!=="running")return null;let t=Array.isArray(r.specialists)?r.specialists:[],n={},i=null;for(let l of t){if((l==null?void 0:l.status)!=="running")continue;let f=We(l,e);n[l.name]=f.row,(!i||f.phase==="tool"||i.status.phase!=="tool")&&(i={name:l.name,status:f})}let s=(d=r.handoff)==null?void 0:d.status;if(s==="running"||s==="done")return{line:"Pulling it together and writing the answer\u2026",phase:"handoff",perSpecialist:n};if(i)return{line:`${i.name} ${i.status.verb}`,phase:i.status.phase,perSpecialist:n};let a=(p=r.route)==null?void 0:p.status,o=t.some(l=>l&&l.status!=="running"&&l.status!=="queued");return a==="running"||a==="done"&&!o?{line:"Picking specialists\u2026",phase:"route",perSpecialist:n}:a==="done"||o?{line:"Working\u2026",phase:"waiting",perSpecialist:n}:{line:"Starting\u2026",phase:"start",perSpecialist:n}}function qe(r,e=Math.random){let t=[...r];for(let n=t.length-1;n>0;n--){let i=Math.floor(e()*(n+1));[t[n],t[i]]=[t[i],t[n]]}return t}function Ge(r,e=Math.random){let t=[],n=null;return{next(){if(!r.length)return"";if(!t.length){t=qe(r,e);let i=t.length-1;i>0&&t[i]===n&&(t[i]=t[0],t[0]=n)}return n=t.pop(),n}}}function ce({random:r=Math.random}={}){let e={},t=null;return{line(n,i,s=!0){let a=Oe[n];if(!s||!a||!Number.isFinite(i)||i<4e3)return t=null,"";let o=Math.floor((i-4e3)/3500);return t&&t.phase===n&&t.slot===o||(e[n]||(e[n]=Ge(a,r)),t={phase:n,slot:o,text:e[n].next()}),t.text}}}function de(r,e,t,n=4e3){let i=r||{text:"",at:-1/0};return!e||e===i.text||t-i.at<n?i:{text:e,at:t}}function V(r){let e=Math.max(0,Math.floor((Number(r)||0)/1e3)),t=Math.floor(e/3600),n=Math.floor(e%3600/60),i=String(e%60).padStart(2,"0");return t?`${t}:${String(n).padStart(2,"0")}:${i}`:`${n}:${i}`}function _(r=""){return{harness:r,phase:"planning",route:"pending",handoff:"pending",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function D(r,e,t){let n=typeof e=="string"&&e?e:"specialist",i=r.findIndex(a=>a.name===n);if(i===-1)return[...r,{name:n,status:"queued",ms:null,task:"",tools:[],...t}];let s=r.slice();return s[i]={...s[i],...t},s}function I(r,e,t={}){var s,a;let n=r||_(t.harness),i={...n,harness:t.harness||n.harness};if(e==="route"&&t.phase==="start")i.route="running";else if(e==="route"&&t.phase==="done"){i.route="done",i.phase="working";for(let o of Array.isArray(t.steps)?t.steps:[])i.specialists=D(i.specialists,o.specialist,{task:typeof o.task=="string"?o.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=D(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=D(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="tool"&&(t.phase==="start"||t.phase==="done"))i.specialists=Ve(i.specialists,t);else if(e==="handoff"&&t.phase==="start")i.phase="writing",i.handoff="running";else if(e==="handoff"&&t.phase==="done")i.handoff="done";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let o=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;o?i.specialists=o.map(p=>({name:String(p.name||"specialist"),status:p.status==="failed"?"failed":"done",ms:typeof p.ms=="number"?p.ms:null,task:typeof p.task=="string"?p.task:""})):i.specialists=i.specialists.map(p=>p.status==="failed"?p:{...p,status:"done"});let d=((s=t.trace)==null?void 0:s.wallMs)??((a=t.timings)==null?void 0:a.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-n.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Ve(r,e){let t=typeof e.name=="string"&&e.name?e.name:"tool",n=r.find(s=>s.name===(typeof e.specialist=="string"&&e.specialist?e.specialist:"specialist")),i=n&&Array.isArray(n.tools)?n.tools.slice():[];if(e.phase==="start")i.push({name:t,status:"running"});else{let s=i.map((o,d)=>({tool:o,at:d})).reverse().find(({tool:o})=>o.name===t&&o.status==="running"),a=e.error?"failed":"done";s?i[s.at]={name:t,status:a}:i.push({name:t,status:a})}return D(r,e.specialist,{tools:i})}function J(r){return!r||r.phase==="done"||r.phase==="failed"?null:oe({status:"running",route:{status:r.route||"pending"},handoff:{status:r.handoff||"pending"},specialists:(r.specialists||[]).map(e=>({name:e.name,status:e.status,tools:e.tools||[]}))})}function Y(r){if(typeof r!="number"||!Number.isFinite(r))return"";if(r<1e3)return`${Math.max(1,Math.round(r))} ms`;let e=r/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Je={A:["href","target","rel"],BLOCKQUOTE:[],BR:[],BUTTON:["type","class","data-copy-code","aria-label"],CODE:[],DEL:[],DIV:["class"],EM:[],H1:[],H2:[],H3:[],H4:[],H5:[],H6:[],HR:[],IMG:["src","alt","loading"],LI:[],OL:["start"],P:[],PRE:[],SPAN:["class","aria-hidden"],STRONG:[],TABLE:[],TBODY:[],TD:["style"],TH:["style"],THEAD:[],TR:[],UL:[]},Ye=/^text-align:(left|right|center)$/;function le(r){let e=r.ownerDocument.createTreeWalker(r,1),t=[],n=e.nextNode();for(;n;){let i=Je[n.tagName];if(!i)t.push(n);else{for(let s of Array.from(n.attributes)){let a=s.name.toLowerCase(),o=i.includes(a);o&&(a==="href"||a==="src")&&(o=v(s.value,{image:a==="src"})!==null),o&&a==="style"&&(o=Ye.test(s.value)),o&&a==="target"&&(o=s.value==="_blank"),o||n.removeAttribute(s.name)}n.tagName==="A"&&n.setAttribute("rel","noopener noreferrer nofollow")}n=e.nextNode()}for(let i of t)i.replaceWith(r.ownerDocument.createTextNode(i.textContent||""));return r}var pe=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table-sort{display:inline-flex;align-items:center;gap:.5em;padding:0;border:0;border-radius:3px;background:transparent;color:inherit;font:inherit;text-align:inherit;cursor:pointer}.md-table-sort:hover{text-decoration:underline}.md-table-sort:focus-visible{outline:2px solid var(--dc-accent);outline-offset:4px}.md-table-sort-icon{opacity:.65;font-size:.85em}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-figure .dc-image-download{border:0;border-top:1px solid var(--dc-border);border-radius:0;padding:8px 12px}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-run-live{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;padding:0 12px 8px 48px;font-size:.86em}.dc-run-enhanced{color:var(--dc-muted);font-style:italic}.dc-run-enhanced:empty{display:none}.dc-run li .dc-step-live{color:var(--dc-muted)}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-note{flex-basis:100%;font-size:.85em;color:var(--dc-muted)}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Ke=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),he=/^(?:unknown|n\/?a|not available|not provided|not recorded|not applicable|null|none(?: in window)?|[—–-])?$/i,ue={"no risk":0,"low risk":1,"slight risk":1,"moderate risk":2,"medium risk":2,"high risk":3,"critical risk":4},Ze=/^(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)$/i,Qe=new RegExp("^\\p{Sc}$","u"),Xe=/\s/;function me(r,e){let t=r.length-e;for(;t>0&&Xe.test(r[t-1]);)t--;return r.slice(0,t)}function et(r){return r.length>=3&&Ze.test(r.slice(-3))?me(r,3):r}function tt(r){let e=r.length,n=e>=2&&/[\uD800-\uDBFF]/.test(r[e-2])&&/[\uDC00-\uDFFF]/.test(r[e-1])?2:1;return e>=1&&Qe.test(r.slice(e-n))?me(r,n):r}function fe(r){let e=r.replace(/\u2212/g,"-").trim(),t=e.startsWith("(")&&e.endsWith(")");if(t&&(e=e.slice(1,-1).trim()),e=et(e.replace(/^(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)\s*/i,"")),e=tt(e.replace(new RegExp("^([+-]?)\\p{Sc}\\s*","u"),"$1")).trim(),!/^[+-]?(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\.\d+)%?$/.test(e))return null;let n=Number(e.replace(/[,%]/g,""))*(t?-1:1);return Number.isFinite(n)&&Math.abs(n)<=Number.MAX_SAFE_INTEGER?n:null}function ge(r){if(!/^(?:\d{4}-\d{2}-\d{2}(?:[T ].+)?|\d{1,2}[ -][A-Za-z]{3,9}[ ,/-]+\d{4}|[A-Za-z]{3,9} \d{1,2},? \d{4})$/.test(r))return null;let e=Date.parse(r);return Number.isFinite(e)?e:null}function be(r,e,t="ascending",n=""){let i=r.map(l=>String(l[e]??"").trim()),s=i.filter(l=>!he.test(l)),a=/\b(?:ids?|identifiers?|codes?|sku|zip|postal)\b/i.test(n),o=l=>l;!a&&s.length&&s.every(l=>fe(l)!==null)?o=fe:!a&&s.length&&s.every(l=>ge(l)!==null)?o=ge:/\brisk\b/i.test(n)&&s.length&&s.every(l=>Object.prototype.hasOwnProperty.call(ue,l.toLowerCase()))&&(o=l=>ue[l.toLowerCase()]);let d=i.map(l=>he.test(l)?null:o(l)),p=t==="descending"?-1:1;return r.map((l,f)=>f).sort((l,f)=>d[l]===null||d[f]===null?d[l]===d[f]?l-f:d[l]===null?1:-1:(typeof d[l]=="number"?d[l]-d[f]:Ke.compare(d[l],d[f]))*p||l-f)}function xe(r,e=new Map){r.querySelectorAll("table").forEach((t,n)=>{var f;if(((f=t.tHead)==null?void 0:f.rows.length)!==1||t.tBodies.length!==1)return;let i=Array.from(t.tHead.rows[0].cells),s=t.tBodies[0],a=Array.from(s.rows);if(!a.length||[...i,...a.flatMap(u=>Array.from(u.cells))].some(u=>u.colSpan!==1||u.rowSpan!==1)||a.some(u=>u.cells.length!==i.length))return;let o=i.map(u=>u.textContent.trim()),d=a.map(u=>Array.from(u.cells,m=>m.textContent)),p=i.map((u,m)=>{if(!o[m]||u.querySelector("a,button,input,select,textarea"))return null;let h=t.ownerDocument.createElement("button");h.type="button",h.className="md-table-sort",h.append(...u.childNodes);let g=t.ownerDocument.createElement("span");return g.className="md-table-sort-icon",g.setAttribute("aria-hidden","true"),h.append(g),u.scope="col",u.append(h),h.addEventListener("click",()=>{let x=e.get(n);l({column:m,direction:(x==null?void 0:x.column)===m&&x.direction==="ascending"?"descending":"ascending"}),h.focus({preventScroll:!0})}),h});function l(u){u&&p[u.column]&&(e.set(n,u),s.append(...be(d,u.column,u.direction,o[u.column]).map(m=>a[m]))),p.forEach((m,h)=>{if(!m)return;let g=(u==null?void 0:u.column)===h;i[h].setAttribute("aria-sort",g?u.direction:"none");let x=g&&u.direction==="ascending"?"descending":"ascending";m.setAttribute("aria-label",`Sort by ${o[h]}, ${x}`),m.title=`Sort displayed rows by ${o[h]} (${x})`,m.lastChild.textContent=g?u.direction==="ascending"?"\u2191":"\u2193":"\u2195"})}l(e.get(n))})}var nt="cuttlely-chat:v1:",it=60,rt="https://github.com/cuttlely/cuttlely",st=0,U=r=>`${r}-${Date.now().toString(36)}-${(st++).toString(36)}`;function c(r,e={},t=[]){let n=document.createElement(r);for(let[i,s]of Object.entries(e||{}))s==null||s===!1||(i==="class"?n.className=s:i==="text"?n.textContent=s:i==="html"?n.innerHTML=s:i.startsWith("on")&&typeof s=="function"?n.addEventListener(i.slice(2),s):n.setAttribute(i,s===!0?"":String(s)));for(let i of[].concat(t))i==null||i===!1||n.append(typeof i=="string"?document.createTextNode(i):i);return n}function ye(r,e){let t=document.createElement("template");t.innerHTML=q(r,{base:e}),le(t.content);let n=c("div",{class:"dc-md"});return n.append(t.content),n}function we(r){let e=Array.isArray(r)?r:[],t=new Set,n=[];for(let i of e){if(!i||typeof i!="object")continue;let s=i.metadata&&typeof i.metadata=="object"?i.metadata:{},a=v(typeof s.url=="string"?s.url:typeof s.source=="string"?s.source:""),o=s.title||s.source||s.url||s.name||i.title||"",d=String(o||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),p=`${a||""}|${d}`;if(!t.has(p)&&(t.add(p),n.push({title:d||"Source",url:a,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),n.length>=8))break}return n}function K(r){return(Array.isArray(r)?r:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var ve=["pdf","docx","xlsx","pptx","csv"];function ke(r){let e=typeof(r==null?void 0:r.name)=="string"?r.name:"",t=String((r==null?void 0:r.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(r==null?void 0:r.type)||"bin"}`}function Se(r){let e=r;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function Ae(r){var e,t,n;if(!Array.isArray(r))return"";for(let i=r.length-1;i>=0;i--){let s=(n=(t=(e=r[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:n.content;if(typeof s=="string"&&s.trim())return s}return""}var H=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=ie({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=N({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.tableSorts=new WeakMap,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=U("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:pe});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:b.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var n,i,s,a;let e=this.options.theme,t=o=>this.wrap.classList.toggle("dark",o);if((i=(n=this.media)==null?void 0:n.removeEventListener)==null||i.call(n,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var o;return t(!!((o=this.media)!=null&&o.matches))},this.onMedia(),(a=(s=this.media)==null?void 0:s.addEventListener)==null||a.call(s,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=se(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let n=await this.api.loadConfig();this.config=N(n,this.options.config),this.state="ready",this.restore()}catch(n){let i=$(n);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${nt}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(n=>n&&(n.role==="user"||n.role==="bot")&&typeof n.text=="string").map(n=>({id:U("m"),role:n.role,text:n.text,images:Array.isArray(n.images)?n.images.filter(i=>v(i,{image:!0})):[],sources:Array.isArray(n.sources)?n.sources:[],artifacts:K(n.artifacts),run:n.run&&typeof n.run=="object"?n.run:null,messageId:typeof n.messageId=="string"?n.messageId:"",feedback:n.feedback==="up"||n.feedback==="down"?n.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-it).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(n=>n.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=b.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=b.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=z;let n=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:n})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:b.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:b.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",b.lock],origin:["Not available here","This chat is not available on this site.",b.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",b.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",b.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=z;let n=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),n])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let s=`${i.id}:${i.rev}:${i===t?"last":""}`,a=this.nodes.get(i.id);(!a||a.dataset.key!==s)&&(a=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),a.dataset.key=s,this.nodes.set(i.id,a)),e.push(a)}let n=Array.from(this.thread.children);(n.length!==e.length||n.some((i,s)=>i!==e[s]))&&this.thread.replaceChildren(...e)}renderUser(e){var n,i;let t=c("div",{class:"dc-body"});return(n=e.images)!=null&&n.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(s=>c("img",{src:s,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(s=>c("span",{class:"dc-file-chip",html:b.doc},[s])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var o,d,p;let n=this.config,i=c("div",{class:"dc-avatar"});n.botAvatar||n.avatar?i.append(c("img",{src:n.botAvatar||n.avatar,alt:""})):i.innerHTML=z;let s=c("div",{class:"dc-body"});e.run&&s.append(this.renderRun(e.run,e.status==="streaming"));let a=c("div",{class:"dc-bot-bubble"});if(e.text){let l=ye(e.text,this.base);e.status!=="streaming"&&(this.tableSorts.has(e)||this.tableSorts.set(e,new Map),xe(l,this.tableSorts.get(e))),e.status==="streaming"&&l.classList.add("dc-caret"),a.append(l)}else e.status==="streaming"&&a.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return a.childNodes.length&&s.append(a),(o=e.artifacts)!=null&&o.length&&s.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&s.append(this.renderSources(e.sources)),e.error&&s.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&s.append(this.renderAction(e)),e.status==="done"&&e.text&&s.append(this.renderTools(e)),t&&e.status==="done"&&((p=e.followUps)!=null&&p.length)&&!this.busy&&s.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(l=>c("button",{class:"dc-chip",type:"button",text:l,onclick:()=>this.send(l)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),s])}renderRun(e,t){let n=e.phase==="done",i=e.specialists.length,s={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",a=t?J(e):null,o=n&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:a?V(Date.now()-e.startedAt):t?"Working\u2026":"",d=c("details",{class:"dc-run"});!n&&t&&(d.open=!0);let p=c("summary",{},[c("span",{class:"dc-run-icon",html:b.spark}),c("span",{class:"dc-run-title",text:s}),c("span",{class:a?"dc-run-meta dc-run-elapsed":"dc-run-meta",text:o,"aria-hidden":a?"true":null}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);if(d.append(p),a){let l=this.liveSinceFor(a.line,Date.now());d.append(c("div",{class:"dc-run-live"},[c("span",{class:"dc-run-line",text:a.line}),c("span",{class:"dc-run-enhanced","aria-hidden":"true",text:this.enhancedLineFor(a.phase,Date.now()-l.at)})]))}return i&&d.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),a&&a.perSpecialist[l.name]?c("span",{class:"dc-step-live",text:a.perSpecialist[l.name]}):c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Y(l.ms)}):null])))),d}enhancedLineFor(e,t){return this.enhancedRotator||(this.enhancedRotator=ce()),this.enhancedRotator.line(e,t,this.config.enhancedStatus)}liveSinceFor(e,t){return(!this.liveSince||this.liveSince.line!==e)&&(this.liveSince={line:e,at:t}),this.liveSince}tickLive(e){let t=J(e.run),n=this.nodes.get(e.id);if(!t||!n||e.status!=="streaming")return;let i=Date.now(),s=this.liveSinceFor(t.line,i),a=n.querySelector(".dc-run-elapsed");a&&(a.textContent=V(i-e.run.startedAt));let o=n.querySelector(".dc-run-enhanced");o&&(o.textContent=this.enhancedLineFor(t.phase,i-s.at));let d=de(this.liveSpoken,t.line,i);d!==this.liveSpoken&&(this.liveSpoken=d,this.announce(t.line))}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let n of e)if(n.type==="png"||n.type==="jpeg"||n.type==="jpg"||n.type==="gif"||n.type==="webp")t.append(this.renderImageArtifact(n));else if(ve.includes(n.type)&&n.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(n));else{if(ve.includes(n.type))continue;if(n.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=n.data,t.append(i)}else n.data&&t.append(ye(n.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,ke(e),e.type.toUpperCase())}renderDownloadLink(e,t,n,i=""){let s=!e.data.startsWith("data:"),a=()=>s?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,o=c("a",{class:`dc-file${i}`,href:a(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:n}),c("span",{class:"dc-file-name",text:t})]);return o.addEventListener("click",async d=>{if(!s||!this.sessionToken||!this.chatId){o.href=a();return}d.preventDefault();try{let p=await this.api.fileBlob(a(),this.sessionToken),l=URL.createObjectURL(p);c("a",{href:l,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}catch{o.replaceWith(c("div",{class:"dc-figure-missing",html:b.alert},[`${t} could not be downloaded here.`]))}}),o}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":ke(e),n=e.type==="jpeg"?"jpg":e.type;return(n==="jpg"?/\.jpe?g$/i:new RegExp(`\\.${n}$`,"i")).test(t)?t:`${t.replace(/\.[^.]*$/,"")||"image"}.${n}`}renderImageArtifact(e){let t=e.type==="jpg"?"jpeg":e.type,n=new RegExp(`^data:image/${t};base64,[A-Za-z0-9+/]+={0,2}$`).test(e.data),i=e.data.startsWith("FILE-STORAGE::")||!/[:/\\]/.test(e.data),s=n?e.data:v(e.data,{image:!0,base:this.base}),a=s&&!e.data.startsWith("/")?s:this.api.fileUrl(this.chatId,e.data),o=c("figure",{class:"dc-figure"}),d=c("img",{src:a,alt:"Chart from the answer",loading:"lazy"});d.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let p=!1;if(d.addEventListener("error",async()=>{if(!p&&!s&&this.sessionToken&&this.chatId){p=!0;try{let l=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);d.src=URL.createObjectURL(l);return}catch{}}d.replaceWith(c("div",{class:"dc-figure-missing",html:b.image},["This chart could not be shown here."]))}),o.append(d),i||n){let l=this.imageArtifactName(e),f=(e.type==="jpeg"?"jpg":e.type).toUpperCase();o.append(this.renderDownloadLink(e,l,f," dc-image-download"))}return o}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),n=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((s,a)=>{let o=[c("b",{text:String(a+1)}),c("span",{text:s.title})],d;s.url?d=c("a",{class:"dc-source",href:s.url,target:"_blank",rel:"noopener noreferrer nofollow",title:s.title},o):(d=c("button",{class:"dc-source",type:"button",title:s.title,"aria-expanded":"false"},o),d.addEventListener("click",()=>{let p=d.getAttribute("aria-expanded")!=="true";n.querySelectorAll("button.dc-source").forEach(l=>l.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,p&&s.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:s.excerpt}),t.append(i))})),n.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(n),t}renderError(e,t){let n=[c("div",{text:e.error})];return t&&e.retry&&n.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:b.alert}),c("div",{},n)])}renderAction(e){var n;let t=Array.isArray((n=e.action)==null?void 0:n.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,s)=>c("button",{class:`dc-chip${s===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:b.copy});t.addEventListener("click",()=>this.copy(e.text,t));let n=[t];if(this.config.feedback&&e.messageId)for(let[i,s,a]of[["up",b.up,"Good answer"],["down",b.down,"Bad answer"]])n.push(c("button",{class:"dc-tool",type:"button","aria-label":a,title:a,"aria-pressed":e.feedback===i?"true":"false",html:s,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},n)}renderComposer(){let e=this.config.imageUpload,t=this.config.fileUpload,n=t?"Attach a file":"Attach an image";this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",a=>{a.key==="Enter"&&!a.shiftKey&&!a.isComposing&&(a.preventDefault(),this.send())});let i=[];(e||t)&&(this.fileInput=c("input",{type:"file",accept:[...(e==null?void 0:e.types)||[],...(t==null?void 0:t.types)||[]].join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),i.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":n,title:n,html:b.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",a=>{var d;let o=Array.from(((d=a.clipboardData)==null?void 0:d.files)||[]);o.length&&(a.preventDefault(),this.addFiles(o))}),this.window.addEventListener("dragover",a=>{a.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:t?"Drop a file to attach":"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",a=>{a.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",a=>{var o;a.preventDefault(),this.clearDrop(),this.addFiles(((o=a.dataTransfer)==null?void 0:o.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),i.push(this.input,this.sendBtn),this.updateSendButton();let s=c("div",{class:"dc-foot"},["Built with ",c("a",{href:rt,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},i),s])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?b.stop:b.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length&&!this.pendingNote,this.pendingEl.replaceChildren(...this.pendingNote?[c("div",{class:"dc-pending-note",role:"status",text:this.pendingNote})]:[],...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[e.file?c("span",{class:"dc-file-chip",html:b.doc},[e.name]):c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:b.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){var i;let t=this.config.imageUpload,n=this.config.fileUpload;if(!(!t&&!n)){this.pendingNote="";for(let s of Array.from(e||[])){if(this.pending.length>=4){this.pendingNote=`Up to 4 attachments per message. ${s.name} and any later files were not added.`,this.announce(this.pendingNote);break}if(!(t!=null&&t.types.includes(s.type))){let o=((i=/\.[^./\\]+$/.exec(String(s.name||"").toLowerCase()))==null?void 0:i[0])||"";!n||!n.types.includes(o)?this.announce(`${s.name} is not a ${n?"file":"image"} this chat accepts.`):!s.size||s.size>n.maxMB*1024*1024?this.announce(`${s.name} is empty or larger than ${n.maxMB} MB.`):this.pending.push({file:s,name:s.name,mime:s.type});continue}if(s.size>t.maxMB*1024*1024){this.announce(`${s.name} is larger than ${t.maxMB} MB.`);continue}let a=await new Promise(o=>{let d=new FileReader;d.onload=()=>o(typeof d.result=="string"?d.result:""),d.onerror=()=>o(""),d.readAsDataURL(s)});a&&v(a,{image:!0})&&this.pending.push({data:a,name:s.name,mime:s.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var n;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(n=t.scrollTo)==null||n.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let n=!1;try{await navigator.clipboard.writeText(e),n=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{n=document.execCommand("copy")}catch{n=!1}i.remove()}t&&(t.innerHTML=n?b.check:b.copy,setTimeout(()=>{t.innerHTML=b.copy},1500)),this.announce(n?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let n=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=n,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let n=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let s=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:s,startNodeId:n.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),n=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(n.text,n.extra,n.uploads,n.files)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},n,i){var m;if(this.state!=="ready"||this.busy)return;let s=typeof e=="string"?e:((m=this.input)==null?void 0:m.value)||"",a=n||this.pending.filter(h=>!h.file).map(h=>({data:h.data,type:"file",name:h.name,mime:h.mime})),o=i||this.pending.filter(h=>h.file).map(h=>h.file);if(!s.trim()&&!a.length&&!o.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.pendingNote="",this.renderPending();let d={id:U("m"),role:"user",text:s.trim(),images:a.map(h=>h.data),files:o.map(h=>h.name),status:"done",rev:0},p={id:U("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(d,p),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let l={question:s.trim()};this.chatId&&(l.chatId=this.chatId),this.sessionToken&&(l.sessionToken=this.sessionToken),a.length&&(l.uploads=a),o.length&&(l.files=o),t.humanInput&&(l.humanInput=t.humanInput),t.action&&(l.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(l.overrideConfig=this.options.overrideConfig);let f=new AbortController;this.controller=f;let u=()=>{p.rev++,this.scheduleRender()};this.liveSince=null,this.liveSpoken=null,clearInterval(this.liveTimer),this.liveTimer=setInterval(()=>this.tickLive(p),1e3);try{await this.api.send(l,{onEvent:h=>this.onEvent(p,h,u),onJson:h=>this.onJson(p,h)},f.signal),!p.text&&!p.error&&!p.artifacts.length&&!p.action&&(p.text=p.fallbackText||""),!p.text&&!p.error&&!p.artifacts.length&&!p.action&&(p.error="The answer was empty. Try asking another way.")}catch(h){if(f.signal.aborted)p.text||(p.text="_Stopped._");else{let g=$(h,this.config.errorMessage);if(g.kind==="private"||g.kind==="origin"){this.setBusy(!1),this.block(g);return}p.error=g.message,p.retry={text:s.trim(),extra:t,uploads:a,files:o}}}finally{this.controller===f&&(this.controller=null),clearInterval(this.liveTimer),this.liveTimer=null}p.status="done",p.run&&p.run.phase!=="done"&&p.run.phase!=="failed"&&(p.run=I(p.run,p.error?"error":"final",{})),p.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(p.error?p.error:`Answer: ${p.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,n){let{event:i,data:s}=t;if(i==="token"&&typeof s=="string")return e.text+=s,n();if(i==="start")return n();if(i==="sourceDocuments")return e.sources=we(s),n();if(i==="artifacts")return e.artifacts=K(s),n();if(i==="action")return e.action=s&&typeof s=="object"?s:null,e.actionRaw=s,n();if(i==="agentFlowExecutedData"){e.fallbackText=Ae(s)||e.fallbackText;return}if(i==="metadata"&&s&&typeof s=="object")return typeof s.chatId=="string"&&(this.chatId=s.chatId),typeof s.sessionToken=="string"&&(this.sessionToken=s.sessionToken),typeof s.chatMessageId=="string"&&(e.messageId=s.chatMessageId),s.followUpPrompts&&(e.followUps=Se(s.followUpPrompts)),s.action&&!e.action&&(e.action=s.action,e.actionRaw=s.action),n();if(i==="error"){let a=typeof t.status=="number"?t.status:0,o=a?$({status:a},this.config.errorMessage):null;return e.error=o&&o.kind!=="error"?o.message:this.config.errorMessage||(typeof s=="string"&&s?s.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=I(e.run,"error",{message:e.error})),n()}if(typeof i=="string"&&i.startsWith("harness.")){let a=i.slice(8);if(a==="recorded")return;let o=s&&typeof s=="object"?s:{};return e.run=I(e.run||_(o.harness),a,o),a==="partial"&&o.phase==="answer"&&!o.streamedAsToken&&typeof o.text=="string"&&(e.text+=o.text),a==="final"&&!e.text&&typeof o.text=="string"&&(e.fallbackText=o.text),n()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=Ae(t.agentFlowExecutedData)),e.sources=we(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=Se(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?at(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=I(_(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;clearInterval(this.liveTimer),this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function at(r){try{return JSON.parse(r)}catch{return null}}var Te="cuttlely-chat";function ot(r,e={}){var n;if(!r)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(n=r.__cuttlelyChat)==null||n.destroy();let t=new H(r,e);return r.__cuttlelyChat=t,t}function O(r,e){let t=r.getAttribute(e);return t===null||t===""?void 0:t}function Nt(r){if(typeof customElements>"u"||customElements.get(Te))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(n,i,s){!this.isConnected||i===s||(n==="theme"&&this.widget?this.widget.setTheme(s||"auto"):this.render())}disconnectedCallback(){var n;(n=this.widget)==null||n.destroy(),this.widget=null}render(){let n=O(this,"flow-id");n&&(this.widget=ot(this,{flowId:n,apiHost:O(this,"api-host")||r,mode:O(this,"mode")==="page"?"page":"bubble",theme:O(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var n;(n=this.widget)==null||n.open()}close(){var n;(n=this.widget)==null||n.close()}reset(){var n;(n=this.widget)==null||n.reset()}}customElements.define(Te,e)}export{H as ChatWidget,Te as ELEMENT_NAME,Nt as defineElement,S as escapeHtml,ot as mount,N as normalizeConfig,q as renderMarkdown,v as safeUrl,be as tableRowOrder};
package/index.d.ts CHANGED
@@ -42,3 +42,10 @@ export function renderMarkdown(source: string, options?: { base?: string }): str
42
42
  export function escapeHtml(value: unknown): string
43
43
  export function safeUrl(raw: unknown, options?: { image?: boolean; base?: string }): string
44
44
  export function normalizeConfig(raw: unknown, overrides?: Record<string, unknown>): Record<string, unknown>
45
+ /** Sort displayed table rows without changing their values. Unknowns remain last in either direction. */
46
+ export function tableRowOrder(
47
+ rows: readonly (readonly string[])[],
48
+ column: number,
49
+ direction?: 'ascending' | 'descending',
50
+ header?: string
51
+ ): number[]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuttlely/chat",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "description": "Embeddable Cuttlely chat widget for applications",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",