@cuttlely/chat 1.5.2 → 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 Ie={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function k(r){return String(r??"").replace(/[&<>"']/g,e=>Ie[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 Le=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function Re(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 o=r[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")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 Be=/^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 Ne(r,e,t){let n=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,s]of n){if(!r.startsWith(i,e))continue;let o=r[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(r[e-1]))continue;let a=r.indexOf(i,e+i.length+1);for(;a!==-1;){let p=r[a-1],l=r[a+i.length],f=i[0]==="_"&&l&&/[a-z0-9]/i.test(l),h=i.length===1&&l===i;if(p&&!/\s/.test(p)&&!f&&!h)break;a=r.indexOf(i,a+1)}if(a===-1)continue;let d=r.slice(e+i.length,a);return{html:`<${s}>${C(d,t)}</${s}>`,end:a+i.length}}return null}function C(r,e={}){let t="",n="",i=()=>{n&&(t+=k(n).replace(/\n/g,"<br>")),n=""};for(let s=0;s<r.length;){let o=r[s];if(o==="\\"&&Le.test(r[s+1]||"")){n+=r[s+1],s+=2;continue}if(o==="`"){let a=1;for(;r[s+a]==="`";)a++;let d="`".repeat(a),p=r.indexOf(d,s+a);if(p!==-1){i();let l=r.slice(s+a,p).replace(/\n/g," ");/^ .* $/.test(l)&&(l=l.slice(1,-1)),t+=`<code>${k(l)}</code>`,s=p+a;continue}n+=d,s+=a;continue}if(o==="!"&&r[s+1]==="["||o==="["){let a=o==="!",d=a?s+1:s,p=Re(r,d),l=p!==-1?_e(r,p+1):null;if(l){let f=r.slice(d+1,p),h=v(l.url,{image:a,base:e.base});i(),a?t+=h?`<img src="${k(h)}" alt="${k(f)}" loading="lazy">`:k(f):h&&!e.inLink?t+=`<a href="${k(h)}" target="_blank" rel="noopener noreferrer nofollow">${C(f,{...e,inLink:!0})}</a>`:t+=C(f,e),s=l.end;continue}}if(o==="<"){let a=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(r.slice(s));if(a){let d=v(a[1]);if(d&&!e.inLink){i(),t+=`<a href="${k(d)}" target="_blank" rel="noopener noreferrer nofollow">${k(a[1])}</a>`,s+=a[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(s===0||/[\s(]/.test(r[s-1]))){let a=Be.exec(r.slice(s));if(a){let d=ze(a[0]);i(),t+=`<a href="${k(d)}" target="_blank" rel="noopener noreferrer nofollow">${k(d)}</a>`,s+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let a=Ne(r,s,e);if(a){i(),t+=a.html,s=a.end;continue}}n+=o,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*$/,_=/^ {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 De(r,e){return te.test(r)||ne.test(r)||ie.test(r)||_.test(r)||$.test(r)||r.includes("|")&&e!==void 0&&re.test(e)&&e.includes("-")}function He(r,e){return`<div class="md-code"><div class="md-code-head"><span>${r?k(r.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${k(e)}</code></pre></div>`}function Oe(r,e){let t=W(r[0]),n=W(r[1]).map(o=>{let a=o.startsWith(":"),d=o.endsWith(":");return a&&d?"center":d?"right":a?"left":""}),i=(o,a,d)=>{let p=n[d]?` style="text-align:${n[d]}"`:"";return`<${o}${p}>${C(a,e)}</${o}>`},s='<div class="md-table"><table><thead><tr>';s+=t.map((o,a)=>i("th",o,a)).join(""),s+="</tr></thead><tbody>";for(let o of r.slice(2)){let a=W(o);s+="<tr>"+t.map((d,p)=>i("td",a[p]??"",p)).join("")+"</tr>"}return s+"</tbody></table></div>"}function Ue(r,e,t){let n=$.exec(r[e]),i=/\d/.test(n[2]),s=n[1].length,o=[],a=e,d=!1;for(;a<r.length;){let h=$.exec(r[a]);if(!h||h[1].length!==s||/\d/.test(h[2])!==i)break;let g=s+h[2].length+1,u=[h[3]??""];a++;let b=!1;for(;a<r.length;){let x=r[a];if(!x.trim()){b=!0,u.push(""),a++;continue}let w=x.length-x.trimStart().length,S=$.exec(x);if(S&&S[1].length<=s)break;if(w<Math.min(g,s+2)&&!S){if(b)break;u.push(x.trim()),a++;continue}b&&(d=!0),b=!1,u.push(x.slice(Math.min(w,g))),a++}for(;u.length&&!u[u.length-1].trim();)u.pop();o.push(u)}let p=i&&parseInt(n[2],10)!==1?` start="${parseInt(n[2],10)}"`:"",l=i?"ol":"ul",f=o.map(h=>{let g=h.join(`
2
- `),u="",b=/^\[([ xX])\]\s+/.exec(g);b&&(u=`<span class="md-task" aria-hidden="true">${b[1]===" "?"\u2610":"\u2611"}</span> `,g=g.slice(b[0].length));let x=G(g.split(`
3
- `),t);return d||(x=x.replace(/^<p>([\s\S]*?)<\/p>/,(w,S)=>S)),`<li>${u}${x}</li>`}).join("");return{html:`<${l}${p}>${f}</${l}>`,end:a}}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+=He(s[2],p.join(`
4
- `));continue}let o=ne.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,n++;continue}if(ie.test(i)){t+="<hr>",n++;continue}if(_.test(i)){let d=[];for(;n<r.length&&r[n].trim()&&_.test(r[n]);)d.push(_.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=Ue(r,n,e);t+=d.html,n=d.end;continue}let a=[i.trim()];for(n++;n<r.length&&r[n].trim()&&!De(r[n],r[n+1]);)a.push(r[n].trim()),n++;t+=`<p>${C(a.join(`
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
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 G(t,{base:e.base||""})}function se(r){let e="",t=n=>{let i=[];for(let a of n.split(/\r?\n/))a.startsWith("data:")&&i.push(a.slice(a[5]===" "?6:5));if(!i.length)return;let s=i.join(`
8
- `),o;try{o=JSON.parse(s)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&r(o)};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 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 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||((...o)=>globalThis.fetch(...o));return{host:n,async loadConfig(){let o=await s(`${n}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await B(o);let a=await o.text();try{return JSON.parse(a)}catch{return{}}},async send(o,a={},d){var x;let p=Array.isArray(o.files)?o.files:[],l={...o,streaming:!0};delete l.files;let f;if(p.length){let w=new FormData;for(let[S,E]of Object.entries(l))E!=null&&w.append(S,typeof E=="object"?JSON.stringify(E):String(E));for(let S of p)w.append("files",S,S.name);f={method:"POST",body:w,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 h=await s(`${n}/api/v1/prediction/${i}`,f);if(!h.ok)throw await B(h);if((h.headers.get("content-type")||"").includes("text/event-stream")&&h.body&&typeof h.body.getReader=="function"){let w=se(j=>{var R;return(R=a.onEvent)==null?void 0:R.call(a,j)}),S=h.body.getReader(),E=new TextDecoder;for(;;){let{value:j,done:R}=await S.read();if(R)break;w.push(E.decode(j,{stream:!0}))}w.push(E.decode()),w.end();return}let u=await h.text(),b;try{b=JSON.parse(u)}catch{b={text:u}}(x=a.onJson)==null||x.call(a,b)},async feedback({messageId:o,chatId:a,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:a,messageId:o,rating:d})});if(!p.ok)throw await B(p)},fileUrl(o,a){let d=String(a||"").replace(/^FILE-STORAGE::/,""),p=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${n}/api/v1/get-upload-file?${p.toString()}`},async fileBlob(o,a){let d=await s(o,{headers:a?{"x-cuttlely-session-token":a}:{}});if(!d.ok)throw await B(d);return d.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"]},Fe=/^(#[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!Fe.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 je(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 z(r,e={}){var l,f,h;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:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},a=je(o.imgUploadSizeAndTypes),d=Number(t.fontSize),p={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:!!((l=t.chatFeedback)!=null&&l.status),followUps:!!((f=t.followUpPrompts)!=null&&f.status),newSessionEachVisit:!!t.generateNewSession,enhancedStatus:((h=t.enhancedStatusMessages)==null?void 0:h.status)!==!1,imageUpload:o.isImageUploadAllowed&&a.types.length?a:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d: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[g,u]of Object.entries(e||{}))if(!(u==null||u===""))if(g==="colors"&&typeof u=="object")for(let[b,x]of Object.entries(u)){let w=A(x);w&&b in p.colors&&(p.colors[b]=w)}else g==="starterPrompts"?p.starterPrompts=oe(u):g==="avatar"?p.avatar=v(T(u),{image:!0})||p.avatar:typeof p[g]=="string"?p[g]=T(u):typeof p[g]=="boolean"&&(p[g]=!!u);return p}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>`,m={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"/>')},N='<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 We={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"},qe=/^pq_[a-z0-9_]+$/i;function Ge(r){let e=String(r||"").trim(),t=/^mcp__(.+?)__(.+)$/.exec(e);return t?t[2]:e}function Ve(r,e){let t=Ge(r==null?void 0:r.name);return de[t]?de[t]:qe.test(t)?"a saved query":`${(typeof e=="function"?e(r):"")||t||"a tool"}`}function Je(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=Ve(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=Je(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 o=(p=r.route)==null?void 0:p.status,a=t.some(l=>l&&l.status!=="running"&&l.status!=="queued");return o==="running"||o==="done"&&!a?{line:"Picking specialists\u2026",phase:"route",perSpecialist:n}:o==="done"||a?{line:"Working\u2026",phase:"waiting",perSpecialist:n}:{line:"Starting\u2026",phase:"start",perSpecialist:n}}function Ye(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 Ke(r,e=Math.random){let t=[],n=null;return{next(){if(!r.length)return"";if(!t.length){t=Ye(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 o=We[n];if(!s||!o||!Number.isFinite(i)||i<4e3)return t=null,"";let a=Math.floor((i-4e3)/3500);return t&&t.phase===n&&t.slot===a||(e[n]||(e[n]=Ke(o,r)),t={phase:n,slot:a,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(o=>o.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,o;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 a of Array.isArray(t.steps)?t.steps:[])i.specialists=D(i.specialists,a.specialist,{task:typeof a.task=="string"?a.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=Ze(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 a=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;a?i.specialists=a.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)??((o=t.timings)==null?void 0:o.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 Ze(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((a,d)=>({tool:a,at:d})).reverse().find(({tool:a})=>a.name===t&&a.status==="running"),o=e.error?"failed":"done";s?i[s.at]={name:t,status:o}:i.push({name:t,status:o})}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 Qe={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:[]},Xe=/^text-align:(left|right|center)$/;function ue(r){let e=r.ownerDocument.createTreeWalker(r,1),t=[],n=e.nextNode();for(;n;){let i=Qe[n.tagName];if(!i)t.push(n);else{for(let s of Array.from(n.attributes)){let o=s.name.toLowerCase(),a=i.includes(o);a&&(o==="href"||o==="src")&&(a=v(s.value,{image:o==="src"})!==null),a&&o==="style"&&(a=Xe.test(s.value)),a&&o==="target"&&(a=s.value==="_blank"),a||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-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 et=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};function be(r){let e=r.replace(/\u2212/g,"-").trim(),t=e.startsWith("(")&&e.endsWith(")");if(t&&(e=e.slice(1,-1).trim()),e=e.replace(/^(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)\s*/i,"").replace(/\s*(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)$/i,"").replace(new RegExp("^([+-]?)\\p{Sc}\\s*","u"),"$1").replace(new RegExp("\\s*\\p{Sc}$","u"),"").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 ye(r,e,t="ascending",n=""){let i=r.map(l=>String(l[e]??"").trim()),s=i.filter(l=>!ge.test(l)),o=/\b(?:ids?|identifiers?|codes?|sku|zip|postal)\b/i.test(n),a=l=>l;!o&&s.length&&s.every(l=>be(l)!==null)?a=be:!o&&s.length&&s.every(l=>xe(l)!==null)?a=xe:/\brisk\b/i.test(n)&&s.length&&s.every(l=>Object.prototype.hasOwnProperty.call(me,l.toLowerCase()))&&(a=l=>me[l.toLowerCase()]);let d=i.map(l=>ge.test(l)?null:a(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]:et.compare(d[l],d[f]))*p||l-f)}function we(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],o=Array.from(s.rows);if(!o.length||[...i,...o.flatMap(h=>Array.from(h.cells))].some(h=>h.colSpan!==1||h.rowSpan!==1)||o.some(h=>h.cells.length!==i.length))return;let a=i.map(h=>h.textContent.trim()),d=o.map(h=>Array.from(h.cells,g=>g.textContent)),p=i.map((h,g)=>{if(!a[g]||h.querySelector("a,button,input,select,textarea"))return null;let u=t.ownerDocument.createElement("button");u.type="button",u.className="md-table-sort",u.append(...h.childNodes);let b=t.ownerDocument.createElement("span");return b.className="md-table-sort-icon",b.setAttribute("aria-hidden","true"),u.append(b),h.scope="col",h.append(u),u.addEventListener("click",()=>{let x=e.get(n);l({column:g,direction:(x==null?void 0:x.column)===g&&x.direction==="ascending"?"descending":"ascending"}),u.focus({preventScroll:!0})}),u});function l(h){h&&p[h.column]&&(e.set(n,h),s.append(...ye(d,h.column,h.direction,a[h.column]).map(g=>o[g]))),p.forEach((g,u)=>{if(!g)return;let b=(h==null?void 0:h.column)===u;i[u].setAttribute("aria-sort",b?h.direction:"none");let x=b&&h.direction==="ascending"?"descending":"ascending";g.setAttribute("aria-label",`Sort by ${a[u]}, ${x}`),g.title=`Sort displayed rows by ${a[u]} (${x})`,g.lastChild.textContent=b?h.direction==="ascending"?"\u2191":"\u2193":"\u2195"})}l(e.get(n))})}var tt="cuttlely-chat:v1:",nt=60,it="https://github.com/cuttlely/cuttlely",rt=0,O=r=>`${r}-${Date.now().toString(36)}-${(rt++).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 ve(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 ke(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:{},o=v(typeof s.url=="string"?s.url:typeof s.source=="string"?s.source:""),a=s.title||s.source||s.url||s.name||i.title||"",d=String(a||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),p=`${o||""}|${d}`;if(!t.has(p)&&(t.add(p),n.push({title:d||"Source",url:o,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 Se=["pdf","docx","xlsx","pptx","csv"];function Ae(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 Te(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 Ee(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 U=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=z({},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=O("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:m.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,o;let e=this.options.theme,t=a=>this.wrap.classList.toggle("dark",a);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 a;return t(!!((a=this.media)!=null&&a.matches))},this.onMedia(),(o=(s=this.media)==null?void 0:s.addEventListener)==null||o.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=z(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`${tt}${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:O("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(-nt).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=m.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=m.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=N;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:m.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:m.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.",m.lock],origin:["Not available here","This chat is not available on this site.",m.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",m.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",m.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=N;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":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==s)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=s,this.nodes.set(i.id,o)),e.push(o)}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:m.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 a,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=N;let s=c("div",{class:"dc-body"});e.run&&s.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let l=ve(e.text,this.base);e.status!=="streaming"&&(this.tableSorts.has(e)||this.tableSorts.set(e,new Map),we(l,this.tableSorts.get(e))),e.status==="streaming"&&l.classList.add("dc-caret"),o.append(l)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&s.append(o),(a=e.artifacts)!=null&&a.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",o=t?K(e):null,a=n&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Z(e.totalMs)}`:o?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:m.spark}),c("span",{class:"dc-run-title",text:s}),c("span",{class:o?"dc-run-meta dc-run-elapsed":"dc-run-meta",text:a,"aria-hidden":o?"true":null}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);if(d.append(p),o){let l=this.liveSinceFor(o.line,Date.now());d.append(c("div",{class:"dc-run-live"},[c("span",{class:"dc-run-line",text:o.line}),c("span",{class:"dc-run-enhanced","aria-hidden":"true",text:this.enhancedLineFor(o.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}),o&&o.perSpecialist[l.name]?c("span",{class:"dc-step-live",text:o.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),o=n.querySelector(".dc-run-elapsed");o&&(o.textContent=Y(i-e.run.startedAt));let a=n.querySelector(".dc-run-enhanced");a&&(a.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(Se.includes(n.type)&&n.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(n));else{if(Se.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(ve(n.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,Ae(e),e.type.toUpperCase())}renderDownloadLink(e,t,n,i=""){let s=!e.data.startsWith("data:"),o=()=>s?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,a=c("a",{class:`dc-file${i}`,href:o(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:n}),c("span",{class:"dc-file-name",text:t})]);return a.addEventListener("click",async d=>{if(!s||!this.sessionToken||!this.chatId){a.href=o();return}d.preventDefault();try{let p=await this.api.fileBlob(o(),this.sessionToken),l=URL.createObjectURL(p);c("a",{href:l,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}catch{a.replaceWith(c("div",{class:"dc-figure-missing",html:m.alert},[`${t} could not be downloaded here.`]))}}),a}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":Ae(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}),o=s&&!e.data.startsWith("/")?s:this.api.fileUrl(this.chatId,e.data),a=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 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:m.image},["This chart could not be shown here."]))}),a.append(d),i||n){let l=this.imageArtifactName(e),f=(e.type==="jpeg"?"jpg":e.type).toUpperCase();a.append(this.renderDownloadLink(e,l,f," dc-image-download"))}return a}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,o)=>{let a=[c("b",{text:String(o+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},a):(d=c("button",{class:"dc-source",type:"button",title:s.title,"aria-expanded":"false"},a),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:m.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:m.copy});t.addEventListener("click",()=>this.copy(e.text,t));let n=[t];if(this.config.feedback&&e.messageId)for(let[i,s,o]of[["up",m.up,"Good answer"],["down",m.down,"Bad answer"]])n.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"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;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:m.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let s=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);s.length&&(i.preventDefault(),this.addFiles(s))}),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 s;i.preventDefault(),this.clearDrop(),this.addFiles(((s=i.dataTransfer)==null?void 0:s.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 n=c("div",{class:"dc-foot"},["Built with ",c("a",{href:it,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),n])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?m.stop:m.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:m.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let n of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(n.type)){this.announce(`${n.name} is not an image this chat accepts.`);continue}if(n.size>t.maxMB*1024*1024){this.announce(`${n.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(s=>{let o=new FileReader;o.onload=()=>s(typeof o.result=="string"?o.result:""),o.onerror=()=>s(""),o.readAsDataURL(n)});i&&v(i,{image:!0})&&this.pending.push({data:i,name:n.name,mime:n.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?m.check:m.copy,setTimeout(()=>{t.innerHTML=m.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)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},n){var f;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((f=this.input)==null?void 0:f.value)||"",s=n||this.pending.map(h=>({data:h.data,type:"file",name:h.name,mime:h.mime}));if(!i.trim()&&!s.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:O("m"),role:"user",text:i.trim(),images:s.map(h=>h.data),status:"done",rev:0},a={id:O("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,a),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),s.length&&(d.uploads=s),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 p=new AbortController;this.controller=p;let l=()=>{a.rev++,this.scheduleRender()};this.liveSince=null,this.liveSpoken=null,clearInterval(this.liveTimer),this.liveTimer=setInterval(()=>this.tickLive(a),1e3);try{await this.api.send(d,{onEvent:h=>this.onEvent(a,h,l),onJson:h=>this.onJson(a,h)},p.signal),!a.text&&!a.error&&!a.artifacts.length&&!a.action&&(a.text=a.fallbackText||""),!a.text&&!a.error&&!a.artifacts.length&&!a.action&&(a.error="The answer was empty. Try asking another way.")}catch(h){if(p.signal.aborted)a.text||(a.text="_Stopped._");else{let g=I(h,this.config.errorMessage);if(g.kind==="private"||g.kind==="origin"){this.setBusy(!1),this.block(g);return}a.error=g.message,a.retry={text:i.trim(),extra:t,uploads:s}}}finally{this.controller===p&&(this.controller=null),clearInterval(this.liveTimer),this.liveTimer=null}a.status="done",a.run&&a.run.phase!=="done"&&a.run.phase!=="failed"&&(a.run=L(a.run,a.error?"error":"final",{})),a.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(a.error?a.error:`Answer: ${a.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=ke(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=Ee(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=Te(s.followUpPrompts)),s.action&&!e.action&&(e.action=s.action,e.actionRaw=s.action),n();if(i==="error"){let o=typeof t.status=="number"?t.status:0,a=o?I({status:o},this.config.errorMessage):null;return e.error=a&&a.kind!=="error"?a.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 o=i.slice(8);if(o==="recorded")return;let a=s&&typeof s=="object"?s:{};return e.run=L(e.run||H(a.harness),o,a),o==="partial"&&a.phase==="answer"&&!a.streamedAsToken&&typeof a.text=="string"&&(e.text+=a.text),o==="final"&&!e.text&&typeof a.text=="string"&&(e.fallbackText=a.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=Ee(t.agentFlowExecutedData)),e.sources=ke(t.sourceDocuments),e.artifacts=Q(t.artifacts),t.followUpPrompts&&(e.followUps=Te(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?st(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 st(r){try{return JSON.parse(r)}catch{return null}}var Ce="cuttlely-chat";function F(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 U(r,e);return r.__cuttlelyChat=t,t}function P(r,e){let t=r.getAttribute(e);return t===null||t===""?void 0:t}function Me(r){if(typeof customElements>"u"||customElements.get(Ce))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=P(this,"flow-id");n&&(this.widget=F(this,{flowId:n,apiHost:P(this,"api-host")||r,mode:P(this,"mode")==="page"?"page":"bubble",theme:P(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(Ce,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}})();Me(X);function $e(){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)),F(n,{flowId:e,apiHost:r.apiHost||X,mode:t,theme:r.theme||"auto",open:r.open==="true"})}var at={mount:(r,e)=>F(r,{apiHost:X,...e}),version:"1.5.2"};typeof window<"u"&&(window.cuttlelyChat=at);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",$e,{once:!0}):$e());})();
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 Te={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function k(r){return String(r??"").replace(/[&<>"']/g,e=>Te[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 Ee=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function Ce(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 Me(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 o=r[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")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 Ie(r){let e=r.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function Le(r,e,t){let n=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,s]of n){if(!r.startsWith(i,e))continue;let o=r[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(r[e-1]))continue;let a=r.indexOf(i,e+i.length+1);for(;a!==-1;){let p=r[a-1],l=r[a+i.length],f=i[0]==="_"&&l&&/[a-z0-9]/i.test(l),h=i.length===1&&l===i;if(p&&!/\s/.test(p)&&!f&&!h)break;a=r.indexOf(i,a+1)}if(a===-1)continue;let d=r.slice(e+i.length,a);return{html:`<${s}>${C(d,t)}</${s}>`,end:a+i.length}}return null}function C(r,e={}){let t="",n="",i=()=>{n&&(t+=k(n).replace(/\n/g,"<br>")),n=""};for(let s=0;s<r.length;){let o=r[s];if(o==="\\"&&Ee.test(r[s+1]||"")){n+=r[s+1],s+=2;continue}if(o==="`"){let a=1;for(;r[s+a]==="`";)a++;let d="`".repeat(a),p=r.indexOf(d,s+a);if(p!==-1){i();let l=r.slice(s+a,p).replace(/\n/g," ");/^ .* $/.test(l)&&(l=l.slice(1,-1)),t+=`<code>${k(l)}</code>`,s=p+a;continue}n+=d,s+=a;continue}if(o==="!"&&r[s+1]==="["||o==="["){let a=o==="!",d=a?s+1:s,p=Ce(r,d),l=p!==-1?Me(r,p+1):null;if(l){let f=r.slice(d+1,p),h=v(l.url,{image:a,base:e.base});i(),a?t+=h?`<img src="${k(h)}" alt="${k(f)}" loading="lazy">`:k(f):h&&!e.inLink?t+=`<a href="${k(h)}" target="_blank" rel="noopener noreferrer nofollow">${C(f,{...e,inLink:!0})}</a>`:t+=C(f,e),s=l.end;continue}}if(o==="<"){let a=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(r.slice(s));if(a){let d=v(a[1]);if(d&&!e.inLink){i(),t+=`<a href="${k(d)}" target="_blank" rel="noopener noreferrer nofollow">${k(a[1])}</a>`,s+=a[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(s===0||/[\s(]/.test(r[s-1]))){let a=$e.exec(r.slice(s));if(a){let d=Ie(a[0]);i(),t+=`<a href="${k(d)}" target="_blank" rel="noopener noreferrer nofollow">${k(d)}</a>`,s+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let a=Le(r,s,e);if(a){i(),t+=a.html,s=a.end;continue}}n+=o,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 F(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 Re(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 Be(r,e){return`<div class="md-code"><div class="md-code-head"><span>${r?k(r.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${k(e)}</code></pre></div>`}function ze(r,e){let t=F(r[0]),n=F(r[1]).map(o=>{let a=o.startsWith(":"),d=o.endsWith(":");return a&&d?"center":d?"right":a?"left":""}),i=(o,a,d)=>{let p=n[d]?` style="text-align:${n[d]}"`:"";return`<${o}${p}>${C(a,e)}</${o}>`},s='<div class="md-table"><table><thead><tr>';s+=t.map((o,a)=>i("th",o,a)).join(""),s+="</tr></thead><tbody>";for(let o of r.slice(2)){let a=F(o);s+="<tr>"+t.map((d,p)=>i("td",a[p]??"",p)).join("")+"</tr>"}return s+"</tbody></table></div>"}function Ne(r,e,t){let n=M.exec(r[e]),i=/\d/.test(n[2]),s=n[1].length,o=[],a=e,d=!1;for(;a<r.length;){let h=M.exec(r[a]);if(!h||h[1].length!==s||/\d/.test(h[2])!==i)break;let g=s+h[2].length+1,u=[h[3]??""];a++;let b=!1;for(;a<r.length;){let x=r[a];if(!x.trim()){b=!0,u.push(""),a++;continue}let w=x.length-x.trimStart().length,S=M.exec(x);if(S&&S[1].length<=s)break;if(w<Math.min(g,s+2)&&!S){if(b)break;u.push(x.trim()),a++;continue}b&&(d=!0),b=!1,u.push(x.slice(Math.min(w,g))),a++}for(;u.length&&!u[u.length-1].trim();)u.pop();o.push(u)}let p=i&&parseInt(n[2],10)!==1?` start="${parseInt(n[2],10)}"`:"",l=i?"ol":"ul",f=o.map(h=>{let g=h.join(`
2
- `),u="",b=/^\[([ xX])\]\s+/.exec(g);b&&(u=`<span class="md-task" aria-hidden="true">${b[1]===" "?"\u2610":"\u2611"}</span> `,g=g.slice(b[0].length));let x=W(g.split(`
3
- `),t);return d||(x=x.replace(/^<p>([\s\S]*?)<\/p>/,(w,S)=>S)),`<li>${u}${x}</li>`}).join("");return{html:`<${l}${p}>${f}</${l}>`,end:a}}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+=Be(s[2],p.join(`
4
- `));continue}let o=X.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[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=Ne(r,n,e);t+=d.html,n=d.end;continue}let a=[i.trim()];for(n++;n<r.length&&r[n].trim()&&!Re(r[n],r[n+1]);)a.push(r[n].trim()),n++;t+=`<p>${C(a.join(`
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
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 W(t,{base:e.base||""})}function ne(r){let e="",t=n=>{let i=[];for(let a of n.split(/\r?\n/))a.startsWith("data:")&&i.push(a.slice(a[5]===" "?6:5));if(!i.length)return;let s=i.join(`
8
- `),o;try{o=JSON.parse(s)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&r(o)};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||((...o)=>globalThis.fetch(...o));return{host:n,async loadConfig(){let o=await s(`${n}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await B(o);let a=await o.text();try{return JSON.parse(a)}catch{return{}}},async send(o,a={},d){var x;let p=Array.isArray(o.files)?o.files:[],l={...o,streaming:!0};delete l.files;let f;if(p.length){let w=new FormData;for(let[S,E]of Object.entries(l))E!=null&&w.append(S,typeof E=="object"?JSON.stringify(E):String(E));for(let S of p)w.append("files",S,S.name);f={method:"POST",body:w,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 h=await s(`${n}/api/v1/prediction/${i}`,f);if(!h.ok)throw await B(h);if((h.headers.get("content-type")||"").includes("text/event-stream")&&h.body&&typeof h.body.getReader=="function"){let w=ne(P=>{var L;return(L=a.onEvent)==null?void 0:L.call(a,P)}),S=h.body.getReader(),E=new TextDecoder;for(;;){let{value:P,done:L}=await S.read();if(L)break;w.push(E.decode(P,{stream:!0}))}w.push(E.decode()),w.end();return}let u=await h.text(),b;try{b=JSON.parse(u)}catch{b={text:u}}(x=a.onJson)==null||x.call(a,b)},async feedback({messageId:o,chatId:a,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:a,messageId:o,rating:d})});if(!p.ok)throw await B(p)},fileUrl(o,a){let d=String(a||"").replace(/^FILE-STORAGE::/,""),p=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${n}/api/v1/get-upload-file?${p.toString()}`},async fileBlob(o,a){let d=await s(o,{headers:a?{"x-cuttlely-session-token":a}:{}});if(!d.ok)throw await B(d);return d.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 De={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 A(r,e){var n;if(typeof r!="string")return"";let t=r.trim();return!_e.test(t)||e&&((n=De[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 z(r,e={}){var l,f,h;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:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},a=He(o.imgUploadSizeAndTypes),d=Number(t.fontSize),p={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:!!((l=t.chatFeedback)!=null&&l.status),followUps:!!((f=t.followUpPrompts)!=null&&f.status),newSessionEachVisit:!!t.generateNewSession,enhancedStatus:((h=t.enhancedStatusMessages)==null?void 0:h.status)!==!1,imageUpload:o.isImageUploadAllowed&&a.types.length?a:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d: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[g,u]of Object.entries(e||{}))if(!(u==null||u===""))if(g==="colors"&&typeof u=="object")for(let[b,x]of Object.entries(u)){let w=A(x);w&&b in p.colors&&(p.colors[b]=w)}else g==="starterPrompts"?p.starterPrompts=re(u):g==="avatar"?p.avatar=v(T(u),{image:!0})||p.avatar:typeof p[g]=="string"?p[g]=T(u):typeof p[g]=="boolean"&&(p[g]=!!u);return p}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>`,m={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"/>')},N='<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"},Ue=/^pq_[a-z0-9_]+$/i;function Pe(r){let e=String(r||"").trim(),t=/^mcp__(.+?)__(.+)$/.exec(e);return t?t[2]:e}function Fe(r,e){let t=Pe(r==null?void 0:r.name);return ae[t]?ae[t]:Ue.test(t)?"a saved query":`${(typeof e=="function"?e(r):"")||t||"a tool"}`}function je(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=Fe(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=je(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 o=(p=r.route)==null?void 0:p.status,a=t.some(l=>l&&l.status!=="running"&&l.status!=="queued");return o==="running"||o==="done"&&!a?{line:"Picking specialists\u2026",phase:"route",perSpecialist:n}:o==="done"||a?{line:"Working\u2026",phase:"waiting",perSpecialist:n}:{line:"Starting\u2026",phase:"start",perSpecialist:n}}function We(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 qe(r,e=Math.random){let t=[],n=null;return{next(){if(!r.length)return"";if(!t.length){t=We(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 o=Oe[n];if(!s||!o||!Number.isFinite(i)||i<4e3)return t=null,"";let a=Math.floor((i-4e3)/3500);return t&&t.phase===n&&t.slot===a||(e[n]||(e[n]=qe(o,r)),t={phase:n,slot:a,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(o=>o.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,o;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 a of Array.isArray(t.steps)?t.steps:[])i.specialists=D(i.specialists,a.specialist,{task:typeof a.task=="string"?a.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=Ge(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 a=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;a?i.specialists=a.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)??((o=t.timings)==null?void 0:o.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 Ge(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((a,d)=>({tool:a,at:d})).reverse().find(({tool:a})=>a.name===t&&a.status==="running"),o=e.error?"failed":"done";s?i[s.at]={name:t,status:o}:i.push({name:t,status:o})}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 Ve={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:[]},Je=/^text-align:(left|right|center)$/;function le(r){let e=r.ownerDocument.createTreeWalker(r,1),t=[],n=e.nextNode();for(;n;){let i=Ve[n.tagName];if(!i)t.push(n);else{for(let s of Array.from(n.attributes)){let o=s.name.toLowerCase(),a=i.includes(o);a&&(o==="href"||o==="src")&&(a=v(s.value,{image:o==="src"})!==null),a&&o==="style"&&(a=Je.test(s.value)),a&&o==="target"&&(a=s.value==="_blank"),a||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-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 Ye=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};function fe(r){let e=r.replace(/\u2212/g,"-").trim(),t=e.startsWith("(")&&e.endsWith(")");if(t&&(e=e.slice(1,-1).trim()),e=e.replace(/^(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)\s*/i,"").replace(/\s*(?:USD|EUR|GBP|CAD|AUD|JPY|CHF|HKD|SGD|INR)$/i,"").replace(new RegExp("^([+-]?)\\p{Sc}\\s*","u"),"$1").replace(new RegExp("\\s*\\p{Sc}$","u"),"").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 me(r,e,t="ascending",n=""){let i=r.map(l=>String(l[e]??"").trim()),s=i.filter(l=>!he.test(l)),o=/\b(?:ids?|identifiers?|codes?|sku|zip|postal)\b/i.test(n),a=l=>l;!o&&s.length&&s.every(l=>fe(l)!==null)?a=fe:!o&&s.length&&s.every(l=>ge(l)!==null)?a=ge:/\brisk\b/i.test(n)&&s.length&&s.every(l=>Object.prototype.hasOwnProperty.call(ue,l.toLowerCase()))&&(a=l=>ue[l.toLowerCase()]);let d=i.map(l=>he.test(l)?null:a(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]:Ye.compare(d[l],d[f]))*p||l-f)}function be(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],o=Array.from(s.rows);if(!o.length||[...i,...o.flatMap(h=>Array.from(h.cells))].some(h=>h.colSpan!==1||h.rowSpan!==1)||o.some(h=>h.cells.length!==i.length))return;let a=i.map(h=>h.textContent.trim()),d=o.map(h=>Array.from(h.cells,g=>g.textContent)),p=i.map((h,g)=>{if(!a[g]||h.querySelector("a,button,input,select,textarea"))return null;let u=t.ownerDocument.createElement("button");u.type="button",u.className="md-table-sort",u.append(...h.childNodes);let b=t.ownerDocument.createElement("span");return b.className="md-table-sort-icon",b.setAttribute("aria-hidden","true"),u.append(b),h.scope="col",h.append(u),u.addEventListener("click",()=>{let x=e.get(n);l({column:g,direction:(x==null?void 0:x.column)===g&&x.direction==="ascending"?"descending":"ascending"}),u.focus({preventScroll:!0})}),u});function l(h){h&&p[h.column]&&(e.set(n,h),s.append(...me(d,h.column,h.direction,a[h.column]).map(g=>o[g]))),p.forEach((g,u)=>{if(!g)return;let b=(h==null?void 0:h.column)===u;i[u].setAttribute("aria-sort",b?h.direction:"none");let x=b&&h.direction==="ascending"?"descending":"ascending";g.setAttribute("aria-label",`Sort by ${a[u]}, ${x}`),g.title=`Sort displayed rows by ${a[u]} (${x})`,g.lastChild.textContent=b?h.direction==="ascending"?"\u2191":"\u2193":"\u2195"})}l(e.get(n))})}var Ke="cuttlely-chat:v1:",Ze=60,Qe="https://github.com/cuttlely/cuttlely",Xe=0,H=r=>`${r}-${Date.now().toString(36)}-${(Xe++).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 xe(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 ye(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:{},o=v(typeof s.url=="string"?s.url:typeof s.source=="string"?s.source:""),a=s.title||s.source||s.url||s.name||i.title||"",d=String(a||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),p=`${o||""}|${d}`;if(!t.has(p)&&(t.add(p),n.push({title:d||"Source",url:o,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 we=["pdf","docx","xlsx","pptx","csv"];function ve(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 ke(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 Se(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=ie({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=z({},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=H("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:m.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,o;let e=this.options.theme,t=a=>this.wrap.classList.toggle("dark",a);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 a;return t(!!((a=this.media)!=null&&a.matches))},this.onMedia(),(o=(s=this.media)==null?void 0:s.addEventListener)==null||o.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=z(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`${Ke}${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:H("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(-Ze).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=m.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=m.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=N;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:m.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:m.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.",m.lock],origin:["Not available here","This chat is not available on this site.",m.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",m.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",m.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=N;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":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==s)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=s,this.nodes.set(i.id,o)),e.push(o)}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:m.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 a,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=N;let s=c("div",{class:"dc-body"});e.run&&s.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let l=xe(e.text,this.base);e.status!=="streaming"&&(this.tableSorts.has(e)||this.tableSorts.set(e,new Map),be(l,this.tableSorts.get(e))),e.status==="streaming"&&l.classList.add("dc-caret"),o.append(l)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&s.append(o),(a=e.artifacts)!=null&&a.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",o=t?J(e):null,a=n&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:o?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:m.spark}),c("span",{class:"dc-run-title",text:s}),c("span",{class:o?"dc-run-meta dc-run-elapsed":"dc-run-meta",text:a,"aria-hidden":o?"true":null}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);if(d.append(p),o){let l=this.liveSinceFor(o.line,Date.now());d.append(c("div",{class:"dc-run-live"},[c("span",{class:"dc-run-line",text:o.line}),c("span",{class:"dc-run-enhanced","aria-hidden":"true",text:this.enhancedLineFor(o.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}),o&&o.perSpecialist[l.name]?c("span",{class:"dc-step-live",text:o.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),o=n.querySelector(".dc-run-elapsed");o&&(o.textContent=V(i-e.run.startedAt));let a=n.querySelector(".dc-run-enhanced");a&&(a.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(we.includes(n.type)&&n.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(n));else{if(we.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(xe(n.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,ve(e),e.type.toUpperCase())}renderDownloadLink(e,t,n,i=""){let s=!e.data.startsWith("data:"),o=()=>s?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,a=c("a",{class:`dc-file${i}`,href:o(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:n}),c("span",{class:"dc-file-name",text:t})]);return a.addEventListener("click",async d=>{if(!s||!this.sessionToken||!this.chatId){a.href=o();return}d.preventDefault();try{let p=await this.api.fileBlob(o(),this.sessionToken),l=URL.createObjectURL(p);c("a",{href:l,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(l),3e4)}catch{a.replaceWith(c("div",{class:"dc-figure-missing",html:m.alert},[`${t} could not be downloaded here.`]))}}),a}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":ve(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}),o=s&&!e.data.startsWith("/")?s:this.api.fileUrl(this.chatId,e.data),a=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 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:m.image},["This chart could not be shown here."]))}),a.append(d),i||n){let l=this.imageArtifactName(e),f=(e.type==="jpeg"?"jpg":e.type).toUpperCase();a.append(this.renderDownloadLink(e,l,f," dc-image-download"))}return a}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,o)=>{let a=[c("b",{text:String(o+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},a):(d=c("button",{class:"dc-source",type:"button",title:s.title,"aria-expanded":"false"},a),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:m.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:m.copy});t.addEventListener("click",()=>this.copy(e.text,t));let n=[t];if(this.config.feedback&&e.messageId)for(let[i,s,o]of[["up",m.up,"Good answer"],["down",m.down,"Bad answer"]])n.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"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;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:m.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let s=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);s.length&&(i.preventDefault(),this.addFiles(s))}),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 s;i.preventDefault(),this.clearDrop(),this.addFiles(((s=i.dataTransfer)==null?void 0:s.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 n=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Qe,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),n])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?m.stop:m.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:m.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let n of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(n.type)){this.announce(`${n.name} is not an image this chat accepts.`);continue}if(n.size>t.maxMB*1024*1024){this.announce(`${n.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(s=>{let o=new FileReader;o.onload=()=>s(typeof o.result=="string"?o.result:""),o.onerror=()=>s(""),o.readAsDataURL(n)});i&&v(i,{image:!0})&&this.pending.push({data:i,name:n.name,mime:n.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?m.check:m.copy,setTimeout(()=>{t.innerHTML=m.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)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},n){var f;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((f=this.input)==null?void 0:f.value)||"",s=n||this.pending.map(h=>({data:h.data,type:"file",name:h.name,mime:h.mime}));if(!i.trim()&&!s.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:H("m"),role:"user",text:i.trim(),images:s.map(h=>h.data),status:"done",rev:0},a={id:H("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,a),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),s.length&&(d.uploads=s),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 p=new AbortController;this.controller=p;let l=()=>{a.rev++,this.scheduleRender()};this.liveSince=null,this.liveSpoken=null,clearInterval(this.liveTimer),this.liveTimer=setInterval(()=>this.tickLive(a),1e3);try{await this.api.send(d,{onEvent:h=>this.onEvent(a,h,l),onJson:h=>this.onJson(a,h)},p.signal),!a.text&&!a.error&&!a.artifacts.length&&!a.action&&(a.text=a.fallbackText||""),!a.text&&!a.error&&!a.artifacts.length&&!a.action&&(a.error="The answer was empty. Try asking another way.")}catch(h){if(p.signal.aborted)a.text||(a.text="_Stopped._");else{let g=$(h,this.config.errorMessage);if(g.kind==="private"||g.kind==="origin"){this.setBusy(!1),this.block(g);return}a.error=g.message,a.retry={text:i.trim(),extra:t,uploads:s}}}finally{this.controller===p&&(this.controller=null),clearInterval(this.liveTimer),this.liveTimer=null}a.status="done",a.run&&a.run.phase!=="done"&&a.run.phase!=="failed"&&(a.run=I(a.run,a.error?"error":"final",{})),a.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(a.error?a.error:`Answer: ${a.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=ye(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=Se(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=ke(s.followUpPrompts)),s.action&&!e.action&&(e.action=s.action,e.actionRaw=s.action),n();if(i==="error"){let o=typeof t.status=="number"?t.status:0,a=o?$({status:o},this.config.errorMessage):null;return e.error=a&&a.kind!=="error"?a.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 o=i.slice(8);if(o==="recorded")return;let a=s&&typeof s=="object"?s:{};return e.run=I(e.run||_(a.harness),o,a),o==="partial"&&a.phase==="answer"&&!a.streamedAsToken&&typeof a.text=="string"&&(e.text+=a.text),o==="final"&&!e.text&&typeof a.text=="string"&&(e.fallbackText=a.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=Se(t.agentFlowExecutedData)),e.sources=ye(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=ke(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?et(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 et(r){try{return JSON.parse(r)}catch{return null}}var Ae="cuttlely-chat";function tt(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 U(r,e){let t=r.getAttribute(e);return t===null||t===""?void 0:t}function Mt(r){if(typeof customElements>"u"||customElements.get(Ae))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=U(this,"flow-id");n&&(this.widget=tt(this,{flowId:n,apiHost:U(this,"api-host")||r,mode:U(this,"mode")==="page"?"page":"bubble",theme:U(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(Ae,e)}export{O as ChatWidget,Ae as ELEMENT_NAME,Mt as defineElement,k as escapeHtml,tt as mount,z as normalizeConfig,q as renderMarkdown,v as safeUrl,me as tableRowOrder};
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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuttlely/chat",
3
- "version": "1.5.2",
3
+ "version": "1.6.0",
4
4
  "description": "Embeddable Cuttlely chat widget for applications",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",