@cuttlely/chat 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.js CHANGED
@@ -1,8 +1,8 @@
1
- (()=>{var me={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(s){return String(s??"").replace(/[&<>"']/g,e=>me[e])}function W(s){let e=String(s??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Q=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function w(s,{image:e=!1,base:t=""}={}){if(typeof s!="string")return null;let r=s.trim();return!r||r.length>4096||/[\u0000-\u001f\u007f\s]/.test(r)&&!(e&&Q.test(r))?null:e&&/^data:/i.test(r)?Q.test(r)?r.replace(/\s+/g,""):null:/^https?:\/\//i.test(r)||!e&&/^mailto:[^/]/i.test(r)?r:r.startsWith("/")&&!r.startsWith("//")&&!r.startsWith("/\\")?t?W(t)+r:r:null}var be=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function xe(s,e){let t=0;for(let r=e;r<s.length;r++){let i=s[r];if(i==="\\"){r++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return r}return-1}function ye(s,e){if(s[e]!=="(")return null;let t=e+1;for(;s[t]===" ";)t++;let r="";if(s[t]==="<"){let i=s.indexOf(">",t);if(i===-1)return null;r=s.slice(t+1,i),t=i+1}else{let i=0,n=t;for(;t<s.length;t++){let o=s[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")break}r=s.slice(n,t)}for(;s[t]===" ";)t++;if(s[t]==='"'||s[t]==="'"){let i=s[t],n=s.indexOf(i,t+1);if(n===-1)return null;for(t=n+1;s[t]===" ";)t++}return s[t]!==")"?null:{url:r,end:t+1}}var we=/^https?:\/\/[^\s<>"'`]+/i;function ve(s){let e=s.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function ke(s,e,t){let r=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,n]of r){if(!s.startsWith(i,e))continue;let o=s[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(s[e-1]))continue;let a=s.indexOf(i,e+i.length+1);for(;a!==-1;){let l=s[a-1],h=s[a+i.length],g=i[0]==="_"&&h&&/[a-z0-9]/i.test(h),p=i.length===1&&h===i;if(l&&!/\s/.test(l)&&!g&&!p)break;a=s.indexOf(i,a+1)}if(a===-1)continue;let d=s.slice(e+i.length,a);return{html:`<${n}>${C(d,t)}</${n}>`,end:a+i.length}}return null}function C(s,e={}){let t="",r="",i=()=>{r&&(t+=v(r).replace(/\n/g,"<br>")),r=""};for(let n=0;n<s.length;){let o=s[n];if(o==="\\"&&be.test(s[n+1]||"")){r+=s[n+1],n+=2;continue}if(o==="`"){let a=1;for(;s[n+a]==="`";)a++;let d="`".repeat(a),l=s.indexOf(d,n+a);if(l!==-1){i();let h=s.slice(n+a,l).replace(/\n/g," ");/^ .* $/.test(h)&&(h=h.slice(1,-1)),t+=`<code>${v(h)}</code>`,n=l+a;continue}r+=d,n+=a;continue}if(o==="!"&&s[n+1]==="["||o==="["){let a=o==="!",d=a?n+1:n,l=xe(s,d),h=l!==-1?ye(s,l+1):null;if(h){let g=s.slice(d+1,l),p=w(h.url,{image:a,base:e.base});i(),a?t+=p?`<img src="${v(p)}" alt="${v(g)}" loading="lazy">`:v(g):p&&!e.inLink?t+=`<a href="${v(p)}" target="_blank" rel="noopener noreferrer nofollow">${C(g,{...e,inLink:!0})}</a>`:t+=C(g,e),n=h.end;continue}}if(o==="<"){let a=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(s.slice(n));if(a){let d=w(a[1]);if(d&&!e.inLink){i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(a[1])}</a>`,n+=a[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(n===0||/[\s(]/.test(s[n-1]))){let a=we.exec(s.slice(n));if(a){let d=ve(a[0]);i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(d)}</a>`,n+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let a=ke(s,n,e);if(a){i(),t+=a.html,n=a.end;continue}}r+=o,n++}return i(),t}var Z=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,ee=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,te=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,z=/^ {0,3}> ?(.*)$/,I=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,re=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function F(s){let e=s.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],r="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(r+="|",i++):e[i]==="|"?(t.push(r.trim()),r=""):r+=e[i];return t.push(r.trim()),t}function Te(s,e){return Z.test(s)||ee.test(s)||te.test(s)||z.test(s)||I.test(s)||s.includes("|")&&e!==void 0&&re.test(e)&&e.includes("-")}function Ae(s,e){return`<div class="md-code"><div class="md-code-head"><span>${s?v(s.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${v(e)}</code></pre></div>`}function Se(s,e){let t=F(s[0]),r=F(s[1]).map(o=>{let a=o.startsWith(":"),d=o.endsWith(":");return a&&d?"center":d?"right":a?"left":""}),i=(o,a,d)=>{let l=r[d]?` style="text-align:${r[d]}"`:"";return`<${o}${l}>${C(a,e)}</${o}>`},n='<div class="md-table"><table><thead><tr>';n+=t.map((o,a)=>i("th",o,a)).join(""),n+="</tr></thead><tbody>";for(let o of s.slice(2)){let a=F(o);n+="<tr>"+t.map((d,l)=>i("td",a[l]??"",l)).join("")+"</tr>"}return n+"</tbody></table></div>"}function Ee(s,e,t){let r=I.exec(s[e]),i=/\d/.test(r[2]),n=r[1].length,o=[],a=e,d=!1;for(;a<s.length;){let p=I.exec(s[a]);if(!p||p[1].length!==n||/\d/.test(p[2])!==i)break;let u=n+p[2].length+1,m=[p[3]??""];a++;let y=!1;for(;a<s.length;){let b=s[a];if(!b.trim()){y=!0,m.push(""),a++;continue}let A=b.length-b.trimStart().length,k=I.exec(b);if(k&&k[1].length<=n)break;if(A<Math.min(u,n+2)&&!k){if(y)break;m.push(b.trim()),a++;continue}y&&(d=!0),y=!1,m.push(b.slice(Math.min(A,u))),a++}for(;m.length&&!m[m.length-1].trim();)m.pop();o.push(m)}let l=i&&parseInt(r[2],10)!==1?` start="${parseInt(r[2],10)}"`:"",h=i?"ol":"ul",g=o.map(p=>{let u=p.join(`
1
+ (()=>{var be={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(s){return String(s??"").replace(/[&<>"']/g,e=>be[e])}function W(s){let e=String(s??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Q=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function w(s,{image:e=!1,base:t=""}={}){if(typeof s!="string")return null;let r=s.trim();return!r||r.length>4096||/[\u0000-\u001f\u007f\s]/.test(r)&&!(e&&Q.test(r))?null:e&&/^data:/i.test(r)?Q.test(r)?r.replace(/\s+/g,""):null:/^https?:\/\//i.test(r)||!e&&/^mailto:[^/]/i.test(r)?r:r.startsWith("/")&&!r.startsWith("//")&&!r.startsWith("/\\")?t?W(t)+r:r:null}var xe=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function ye(s,e){let t=0;for(let r=e;r<s.length;r++){let i=s[r];if(i==="\\"){r++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return r}return-1}function we(s,e){if(s[e]!=="(")return null;let t=e+1;for(;s[t]===" ";)t++;let r="";if(s[t]==="<"){let i=s.indexOf(">",t);if(i===-1)return null;r=s.slice(t+1,i),t=i+1}else{let i=0,n=t;for(;t<s.length;t++){let o=s[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")break}r=s.slice(n,t)}for(;s[t]===" ";)t++;if(s[t]==='"'||s[t]==="'"){let i=s[t],n=s.indexOf(i,t+1);if(n===-1)return null;for(t=n+1;s[t]===" ";)t++}return s[t]!==")"?null:{url:r,end:t+1}}var ve=/^https?:\/\/[^\s<>"'`]+/i;function ke(s){let e=s.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function Te(s,e,t){let r=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,n]of r){if(!s.startsWith(i,e))continue;let o=s[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(s[e-1]))continue;let a=s.indexOf(i,e+i.length+1);for(;a!==-1;){let l=s[a-1],h=s[a+i.length],g=i[0]==="_"&&h&&/[a-z0-9]/i.test(h),p=i.length===1&&h===i;if(l&&!/\s/.test(l)&&!g&&!p)break;a=s.indexOf(i,a+1)}if(a===-1)continue;let d=s.slice(e+i.length,a);return{html:`<${n}>${C(d,t)}</${n}>`,end:a+i.length}}return null}function C(s,e={}){let t="",r="",i=()=>{r&&(t+=v(r).replace(/\n/g,"<br>")),r=""};for(let n=0;n<s.length;){let o=s[n];if(o==="\\"&&xe.test(s[n+1]||"")){r+=s[n+1],n+=2;continue}if(o==="`"){let a=1;for(;s[n+a]==="`";)a++;let d="`".repeat(a),l=s.indexOf(d,n+a);if(l!==-1){i();let h=s.slice(n+a,l).replace(/\n/g," ");/^ .* $/.test(h)&&(h=h.slice(1,-1)),t+=`<code>${v(h)}</code>`,n=l+a;continue}r+=d,n+=a;continue}if(o==="!"&&s[n+1]==="["||o==="["){let a=o==="!",d=a?n+1:n,l=ye(s,d),h=l!==-1?we(s,l+1):null;if(h){let g=s.slice(d+1,l),p=w(h.url,{image:a,base:e.base});i(),a?t+=p?`<img src="${v(p)}" alt="${v(g)}" loading="lazy">`:v(g):p&&!e.inLink?t+=`<a href="${v(p)}" target="_blank" rel="noopener noreferrer nofollow">${C(g,{...e,inLink:!0})}</a>`:t+=C(g,e),n=h.end;continue}}if(o==="<"){let a=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(s.slice(n));if(a){let d=w(a[1]);if(d&&!e.inLink){i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(a[1])}</a>`,n+=a[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(n===0||/[\s(]/.test(s[n-1]))){let a=ve.exec(s.slice(n));if(a){let d=ke(a[0]);i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(d)}</a>`,n+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let a=Te(s,n,e);if(a){i(),t+=a.html,n=a.end;continue}}r+=o,n++}return i(),t}var Z=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,ee=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,te=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,z=/^ {0,3}> ?(.*)$/,M=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,re=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function j(s){let e=s.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],r="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(r+="|",i++):e[i]==="|"?(t.push(r.trim()),r=""):r+=e[i];return t.push(r.trim()),t}function Ae(s,e){return Z.test(s)||ee.test(s)||te.test(s)||z.test(s)||M.test(s)||s.includes("|")&&e!==void 0&&re.test(e)&&e.includes("-")}function Ee(s,e){return`<div class="md-code"><div class="md-code-head"><span>${s?v(s.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${v(e)}</code></pre></div>`}function Se(s,e){let t=j(s[0]),r=j(s[1]).map(o=>{let a=o.startsWith(":"),d=o.endsWith(":");return a&&d?"center":d?"right":a?"left":""}),i=(o,a,d)=>{let l=r[d]?` style="text-align:${r[d]}"`:"";return`<${o}${l}>${C(a,e)}</${o}>`},n='<div class="md-table"><table><thead><tr>';n+=t.map((o,a)=>i("th",o,a)).join(""),n+="</tr></thead><tbody>";for(let o of s.slice(2)){let a=j(o);n+="<tr>"+t.map((d,l)=>i("td",a[l]??"",l)).join("")+"</tr>"}return n+"</tbody></table></div>"}function Ce(s,e,t){let r=M.exec(s[e]),i=/\d/.test(r[2]),n=r[1].length,o=[],a=e,d=!1;for(;a<s.length;){let p=M.exec(s[a]);if(!p||p[1].length!==n||/\d/.test(p[2])!==i)break;let u=n+p[2].length+1,m=[p[3]??""];a++;let y=!1;for(;a<s.length;){let b=s[a];if(!b.trim()){y=!0,m.push(""),a++;continue}let A=b.length-b.trimStart().length,k=M.exec(b);if(k&&k[1].length<=n)break;if(A<Math.min(u,n+2)&&!k){if(y)break;m.push(b.trim()),a++;continue}y&&(d=!0),y=!1,m.push(b.slice(Math.min(A,u))),a++}for(;m.length&&!m[m.length-1].trim();)m.pop();o.push(m)}let l=i&&parseInt(r[2],10)!==1?` start="${parseInt(r[2],10)}"`:"",h=i?"ol":"ul",g=o.map(p=>{let u=p.join(`
2
2
  `),m="",y=/^\[([ xX])\]\s+/.exec(u);y&&(m=`<span class="md-task" aria-hidden="true">${y[1]===" "?"\u2610":"\u2611"}</span> `,u=u.slice(y[0].length));let b=q(u.split(`
3
- `),t);return d||(b=b.replace(/^<p>([\s\S]*?)<\/p>/,(A,k)=>k)),`<li>${m}${b}</li>`}).join("");return{html:`<${h}${l}>${g}</${h}>`,end:a}}function q(s,e){let t="",r=0;for(;r<s.length;){let i=s[r];if(!i.trim()){r++;continue}let n=Z.exec(i);if(n){let d=n[1],l=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(s[r]);)l.push(s[r]),r++;r++,t+=Ae(n[2],l.join(`
4
- `));continue}let o=ee.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,r++;continue}if(te.test(i)){t+="<hr>",r++;continue}if(z.test(i)){let d=[];for(;r<s.length&&s[r].trim()&&z.test(s[r]);)d.push(z.exec(s[r])[1]),r++;t+=`<blockquote>${q(d,e)}</blockquote>`;continue}if(i.includes("|")&&r+1<s.length&&re.test(s[r+1])&&s[r+1].includes("-")){let d=[i,s[r+1]];for(r+=2;r<s.length&&s[r].trim()&&s[r].includes("|");)d.push(s[r]),r++;t+=Se(d,e);continue}if(I.test(i)){let d=Ee(s,r,e);t+=d.html,r=d.end;continue}let a=[i.trim()];for(r++;r<s.length&&s[r].trim()&&!Te(s[r],s[r+1]);)a.push(s[r].trim()),r++;t+=`<p>${C(a.join(`
3
+ `),t);return d||(b=b.replace(/^<p>([\s\S]*?)<\/p>/,(A,k)=>k)),`<li>${m}${b}</li>`}).join("");return{html:`<${h}${l}>${g}</${h}>`,end:a}}function q(s,e){let t="",r=0;for(;r<s.length;){let i=s[r];if(!i.trim()){r++;continue}let n=Z.exec(i);if(n){let d=n[1],l=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(s[r]);)l.push(s[r]),r++;r++,t+=Ee(n[2],l.join(`
4
+ `));continue}let o=ee.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,r++;continue}if(te.test(i)){t+="<hr>",r++;continue}if(z.test(i)){let d=[];for(;r<s.length&&s[r].trim()&&z.test(s[r]);)d.push(z.exec(s[r])[1]),r++;t+=`<blockquote>${q(d,e)}</blockquote>`;continue}if(i.includes("|")&&r+1<s.length&&re.test(s[r+1])&&s[r+1].includes("-")){let d=[i,s[r+1]];for(r+=2;r<s.length&&s[r].trim()&&s[r].includes("|");)d.push(s[r]),r++;t+=Se(d,e);continue}if(M.test(i)){let d=Ce(s,r,e);t+=d.html,r=d.end;continue}let a=[i.trim()];for(r++;r<s.length&&s[r].trim()&&!Ae(s[r],s[r+1]);)a.push(s[r].trim()),r++;t+=`<p>${C(a.join(`
5
5
  `),e)}</p>`}return t}function V(s,e={}){if(typeof s!="string"||!s)return"";let t=s.replace(/\r\n?/g,`
6
6
  `).replace(/\t/g," ").split(`
7
7
  `);return q(t,{base:e.base||""})}function ie(s){let e="",t=r=>{let i=[];for(let a of r.split(/\r?\n/))a.startsWith("data:")&&i.push(a.slice(a[5]===" "?6:5));if(!i.length)return;let n=i.join(`
8
- `),o;try{o=JSON.parse(n)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let n=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(n)}},end(){e.trim()&&t(e),e=""}}}var J=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function H(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new J(s.status,String(e||"").slice(0,300))}function se({apiHost:s,flowId:e,fetchImpl:t}){let r=W(s||""),i=encodeURIComponent(e),n=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await n(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await H(o);let a=await o.text();try{return JSON.parse(a)}catch{return{}}},async send(o,a={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,E]of Object.entries(h))E!=null&&A.append(k,typeof E=="object"?JSON.stringify(E):String(E));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await n(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await H(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ie(j=>{var B;return(B=a.onEvent)==null?void 0:B.call(a,j)}),k=p.body.getReader(),E=new TextDecoder;for(;;){let{value:j,done:B}=await k.read();if(B)break;A.push(E.decode(j,{stream:!0}))}A.push(E.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=a.onJson)==null||b.call(a,y)},async feedback({messageId:o,chatId:a,rating:d}){let l=await n(`${r}/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(!l.ok)throw await H(l)},fileUrl(o,a){let d=String(a||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,a){let d=await n(o,{headers:a?{"x-cuttlely-session-token":a}:{}});if(!d.ok)throw await H(d);return d.blob()}}}function $(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Ce={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},Me=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!Me.test(t)||e&&((r=Ce[e])!=null&&r.includes(t.toLowerCase()))?"":t}function S(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function ne(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>S(t,300)).filter(Boolean).slice(0,6)}function Ie(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let n of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof n=="string"&&e.add(n);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function O(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},n=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},a=Ie(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:S(t.title,80),avatar:w(S(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(S(r.avatarSrc),{image:!0})||"",welcome:S(t.welcomeMessage),errorMessage:S(t.errorMessage,300),placeholder:S(n.placeholder,120),starterPrompts:ne(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&a.types.length?a:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(n.backgroundColor,"inputBackground"),inputText:T(n.textColor,"inputText"),accent:T(n.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=ne(u):p==="avatar"?l.avatar=w(S(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=S(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ae(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},R='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function U(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function G(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let n=s.slice();return n[i]={...n[i],...t},n}function L(s,e,t={}){var n,o;let r=s||U(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let a of Array.isArray(t.steps)?t.steps:[])i.specialists=G(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=G(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=G(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let a=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;a?i.specialists=a.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((n=t.trace)==null?void 0:n.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Y(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var $e={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:[]},Le=/^text-align:(left|right|center)$/;function oe(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=$e[r.tagName];if(!i)t.push(r);else{for(let n of Array.from(r.attributes)){let o=n.name.toLowerCase(),a=i.includes(o);a&&(o==="href"||o==="src")&&(a=w(n.value,{image:o==="src"})!==null),a&&o==="style"&&(a=Le.test(n.value)),a&&o==="target"&&(a=n.value==="_blank"),a||r.removeAttribute(n.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ce=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Be="cuttlely-chat:v1:",ze=60,He="https://github.com/cuttlely/cuttlely",Oe=0,_=s=>`${s}-${Date.now().toString(36)}-${(Oe++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,n]of Object.entries(e||{}))n==null||n===!1||(i==="class"?r.className=n:i==="text"?r.textContent=n:i==="html"?r.innerHTML=n:i.startsWith("on")&&typeof n=="function"?r.addEventListener(i.slice(2),n):r.setAttribute(i,n===!0?"":String(n)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function de(s,e){let t=document.createElement("template");t.innerHTML=V(s,{base:e}),oe(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function le(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let n=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof n.url=="string"?n.url:typeof n.source=="string"?n.source:""),a=n.title||n.source||n.url||n.name||i.title||"",d=String(a||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function K(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data})).slice(0,8)}function pe(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function he(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let n=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof n=="string"&&n.trim())return n}return""}var N=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=se({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=O({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=_("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:ce});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,n,o;let e=this.options.theme,t=a=>this.wrap.classList.toggle("dark",a);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var a;return t(!!((a=this.media)!=null&&a.matches))},this.onMedia(),(o=(n=this.media)==null?void 0:n.addEventListener)==null||o.call(n,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ae(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=O(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=$(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${Be}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:_("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:K(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-ze).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=R;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=R;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let n=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==n)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=n,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,n)=>i!==e[n]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(n=>c("img",{src:n,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(n=>c("span",{class:"dc-file-chip",html:f.doc},[n])))),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,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=R;let n=c("div",{class:"dc-body"});e.run&&n.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=de(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&n.append(o),(a=e.artifacts)!=null&&a.length&&n.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&n.append(this.renderSources(e.sources)),e.error&&n.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&n.append(this.renderAction(e)),e.status==="done"&&e.text&&n.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&n.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),n])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,n={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:t?"Working\u2026":"",a=c("details",{class:"dc-run"});!r&&t&&(a.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:n}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return a.append(d),i&&a.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Y(l.ms)}):null])))),a}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(de(r.data,this.base));return t}renderImageArtifact(e){let t=w(e.data,{image:!0,base:this.base}),r=t&&!e.data.startsWith("/")?t:this.api.fileUrl(this.chatId,e.data),i=c("figure",{class:"dc-figure"}),n=c("img",{src:r,alt:"Chart from the answer",loading:"lazy"});n.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let o=!1;return n.addEventListener("error",async()=>{if(!o&&!t&&this.sessionToken&&this.chatId){o=!0;try{let a=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);n.src=URL.createObjectURL(a);return}catch{}}i.replaceChildren(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),i.append(n),i}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((n,o)=>{let a=[c("b",{text:String(o+1)}),c("span",{text:n.title})],d;n.url?d=c("a",{class:"dc-source",href:n.url,target:"_blank",rel:"noopener noreferrer nofollow",title:n.title},a):(d=c("button",{class:"dc-source",type:"button",title:n.title,"aria-expanded":"false"},a),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&n.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:n.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,n)=>c("button",{class:`dc-chip${n===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,n,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:n,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let n=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);n.length&&(i.preventDefault(),this.addFiles(n))}),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 n;i.preventDefault(),this.clearDrop(),this.addFiles(((n=i.dataTransfer)==null?void 0:n.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:He,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(n=>{let o=new FileReader;o.onload=()=>n(typeof o.result=="string"?o.result:""),o.onerror=()=>n(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let n=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:n,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",n=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!n.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:_("m"),role:"user",text:i.trim(),images:n.map(p=>p.data),status:"done",rev:0},a={id:_("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),n.length&&(d.uploads=n),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{a.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(a,p,h),onJson:p=>this.onJson(a,p)},l.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(p){if(l.signal.aborted)a.text||(a.text="_Stopped._");else{let u=$(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}a.error=u.message,a.retry={text:i.trim(),extra:t,uploads:n}}}finally{this.controller===l&&(this.controller=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,r){let{event:i,data:n}=t;if(i==="token"&&typeof n=="string")return e.text+=n,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=le(n),r();if(i==="artifacts")return e.artifacts=K(n),r();if(i==="action")return e.action=n&&typeof n=="object"?n:null,e.actionRaw=n,r();if(i==="agentFlowExecutedData"){e.fallbackText=he(n)||e.fallbackText;return}if(i==="metadata"&&n&&typeof n=="object")return typeof n.chatId=="string"&&(this.chatId=n.chatId),typeof n.sessionToken=="string"&&(this.sessionToken=n.sessionToken),typeof n.chatMessageId=="string"&&(e.messageId=n.chatMessageId),n.followUpPrompts&&(e.followUps=pe(n.followUpPrompts)),n.action&&!e.action&&(e.action=n.action,e.actionRaw=n.action),r();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 n=="string"&&n?n.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=L(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let a=n&&typeof n=="object"?n:{};return e.run=L(e.run||U(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),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=he(t.agentFlowExecutedData)),e.sources=le(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=pe(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?Re(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=L(U(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function Re(s){try{return JSON.parse(s)}catch{return null}}var fe="cuttlely-chat";function P(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new N(s,e);return s.__cuttlelyChat=t,t}function D(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function ue(s){if(typeof customElements>"u"||customElements.get(fe))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,n){!this.isConnected||i===n||(r==="theme"&&this.widget?this.widget.setTheme(n||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=D(this,"flow-id");r&&(this.widget=P(this,{flowId:r,apiHost:D(this,"api-host")||s,mode:D(this,"mode")==="page"?"page":"bubble",theme:D(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(fe,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}})();ue(X);function ge(){let s=(M==null?void 0:M.dataset)||{},e=s.flowId||s.flowid;if(!e)return;let t=s.mode==="page"?"page":"bubble",r;t==="page"&&s.target&&(r=document.querySelector(s.target)),r||(r=document.createElement("cuttlely-chat-root"),r.style.display=t==="page"?"block":"contents",t==="page"&&(r.style.height="100%"),document.body.append(r)),P(r,{flowId:e,apiHost:s.apiHost||X,mode:t,theme:s.theme||"auto",open:s.open==="true"})}var Ue={mount:(s,e)=>P(s,{apiHost:X,...e}),version:"1.3.1"};typeof window<"u"&&(window.cuttlelyChat=Ue);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",ge,{once:!0}):ge());})();
8
+ `),o;try{o=JSON.parse(n)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let n=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(n)}},end(){e.trim()&&t(e),e=""}}}var J=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function H(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new J(s.status,String(e||"").slice(0,300))}function se({apiHost:s,flowId:e,fetchImpl:t}){let r=W(s||""),i=encodeURIComponent(e),n=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await n(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await H(o);let a=await o.text();try{return JSON.parse(a)}catch{return{}}},async send(o,a={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,S]of Object.entries(h))S!=null&&A.append(k,typeof S=="object"?JSON.stringify(S):String(S));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await n(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await H(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ie(P=>{var B;return(B=a.onEvent)==null?void 0:B.call(a,P)}),k=p.body.getReader(),S=new TextDecoder;for(;;){let{value:P,done:B}=await k.read();if(B)break;A.push(S.decode(P,{stream:!0}))}A.push(S.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=a.onJson)==null||b.call(a,y)},async feedback({messageId:o,chatId:a,rating:d}){let l=await n(`${r}/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(!l.ok)throw await H(l)},fileUrl(o,a){let d=String(a||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,a){let d=await n(o,{headers:a?{"x-cuttlely-session-token":a}:{}});if(!d.ok)throw await H(d);return d.blob()}}}function $(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Ie={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},Me=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!Me.test(t)||e&&((r=Ie[e])!=null&&r.includes(t.toLowerCase()))?"":t}function E(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function ne(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>E(t,300)).filter(Boolean).slice(0,6)}function $e(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let n of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof n=="string"&&e.add(n);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function O(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},n=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},a=$e(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:E(t.title,80),avatar:w(E(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(E(r.avatarSrc),{image:!0})||"",welcome:E(t.welcomeMessage),errorMessage:E(t.errorMessage,300),placeholder:E(n.placeholder,120),starterPrompts:ne(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&a.types.length?a:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(n.backgroundColor,"inputBackground"),inputText:T(n.textColor,"inputText"),accent:T(n.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=ne(u):p==="avatar"?l.avatar=w(E(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=E(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ae(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},R='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function U(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function G(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let n=s.slice();return n[i]={...n[i],...t},n}function L(s,e,t={}){var n,o;let r=s||U(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let a of Array.isArray(t.steps)?t.steps:[])i.specialists=G(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=G(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=G(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let a=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;a?i.specialists=a.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((n=t.trace)==null?void 0:n.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Y(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Le={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:[]},Be=/^text-align:(left|right|center)$/;function oe(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Le[r.tagName];if(!i)t.push(r);else{for(let n of Array.from(r.attributes)){let o=n.name.toLowerCase(),a=i.includes(o);a&&(o==="href"||o==="src")&&(a=w(n.value,{image:o==="src"})!==null),a&&o==="style"&&(a=Be.test(n.value)),a&&o==="target"&&(a=n.value==="_blank"),a||r.removeAttribute(n.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ce=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var ze="cuttlely-chat:v1:",He=60,Oe="https://github.com/cuttlely/cuttlely",Re=0,_=s=>`${s}-${Date.now().toString(36)}-${(Re++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,n]of Object.entries(e||{}))n==null||n===!1||(i==="class"?r.className=n:i==="text"?r.textContent=n:i==="html"?r.innerHTML=n:i.startsWith("on")&&typeof n=="function"?r.addEventListener(i.slice(2),n):r.setAttribute(i,n===!0?"":String(n)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function de(s,e){let t=document.createElement("template");t.innerHTML=V(s,{base:e}),oe(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function le(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let n=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof n.url=="string"?n.url:typeof n.source=="string"?n.source:""),a=n.title||n.source||n.url||n.name||i.title||"",d=String(a||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function K(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var pe=["pdf","docx","xlsx","csv"];function Ue(s){let e=typeof(s==null?void 0:s.name)=="string"?s.name:"",t=String((s==null?void 0:s.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(s==null?void 0:s.type)||"bin"}`}function he(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function fe(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let n=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof n=="string"&&n.trim())return n}return""}var N=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=se({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=O({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=_("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:ce});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,n,o;let e=this.options.theme,t=a=>this.wrap.classList.toggle("dark",a);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var a;return t(!!((a=this.media)!=null&&a.matches))},this.onMedia(),(o=(n=this.media)==null?void 0:n.addEventListener)==null||o.call(n,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ae(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=O(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=$(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${ze}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:_("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:K(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-He).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=R;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=R;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let n=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==n)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=n,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,n)=>i!==e[n]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(n=>c("img",{src:n,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(n=>c("span",{class:"dc-file-chip",html:f.doc},[n])))),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,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=R;let n=c("div",{class:"dc-body"});e.run&&n.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=de(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&n.append(o),(a=e.artifacts)!=null&&a.length&&n.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&n.append(this.renderSources(e.sources)),e.error&&n.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&n.append(this.renderAction(e)),e.status==="done"&&e.text&&n.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&n.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),n])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,n={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:t?"Working\u2026":"",a=c("details",{class:"dc-run"});!r&&t&&(a.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:n}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return a.append(d),i&&a.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Y(l.ms)}):null])))),a}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(pe.includes(r.type)&&r.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(r));else{if(pe.includes(r.type))continue;if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(de(r.data,this.base))}return t}renderFileArtifact(e){let t=Ue(e),r=()=>`${this.api.fileUrl(this.chatId,e.data)}&download=true`,i=c("a",{class:"dc-file",href:r(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:e.type.toUpperCase()}),c("span",{class:"dc-file-name",text:t})]);return i.addEventListener("click",async n=>{if(!this.sessionToken||!this.chatId){i.href=r();return}n.preventDefault();try{let o=await this.api.fileBlob(r(),this.sessionToken),a=URL.createObjectURL(o);c("a",{href:a,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(a),3e4)}catch{i.replaceWith(c("div",{class:"dc-figure-missing",html:f.alert},[`${t} could not be downloaded here.`]))}}),i}renderImageArtifact(e){let t=w(e.data,{image:!0,base:this.base}),r=t&&!e.data.startsWith("/")?t:this.api.fileUrl(this.chatId,e.data),i=c("figure",{class:"dc-figure"}),n=c("img",{src:r,alt:"Chart from the answer",loading:"lazy"});n.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let o=!1;return n.addEventListener("error",async()=>{if(!o&&!t&&this.sessionToken&&this.chatId){o=!0;try{let a=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);n.src=URL.createObjectURL(a);return}catch{}}i.replaceChildren(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),i.append(n),i}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((n,o)=>{let a=[c("b",{text:String(o+1)}),c("span",{text:n.title})],d;n.url?d=c("a",{class:"dc-source",href:n.url,target:"_blank",rel:"noopener noreferrer nofollow",title:n.title},a):(d=c("button",{class:"dc-source",type:"button",title:n.title,"aria-expanded":"false"},a),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&n.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:n.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,n)=>c("button",{class:`dc-chip${n===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,n,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:n,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let n=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);n.length&&(i.preventDefault(),this.addFiles(n))}),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 n;i.preventDefault(),this.clearDrop(),this.addFiles(((n=i.dataTransfer)==null?void 0:n.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Oe,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(n=>{let o=new FileReader;o.onload=()=>n(typeof o.result=="string"?o.result:""),o.onerror=()=>n(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let n=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:n,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",n=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!n.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:_("m"),role:"user",text:i.trim(),images:n.map(p=>p.data),status:"done",rev:0},a={id:_("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),n.length&&(d.uploads=n),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{a.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(a,p,h),onJson:p=>this.onJson(a,p)},l.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(p){if(l.signal.aborted)a.text||(a.text="_Stopped._");else{let u=$(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}a.error=u.message,a.retry={text:i.trim(),extra:t,uploads:n}}}finally{this.controller===l&&(this.controller=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,r){let{event:i,data:n}=t;if(i==="token"&&typeof n=="string")return e.text+=n,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=le(n),r();if(i==="artifacts")return e.artifacts=K(n),r();if(i==="action")return e.action=n&&typeof n=="object"?n:null,e.actionRaw=n,r();if(i==="agentFlowExecutedData"){e.fallbackText=fe(n)||e.fallbackText;return}if(i==="metadata"&&n&&typeof n=="object")return typeof n.chatId=="string"&&(this.chatId=n.chatId),typeof n.sessionToken=="string"&&(this.sessionToken=n.sessionToken),typeof n.chatMessageId=="string"&&(e.messageId=n.chatMessageId),n.followUpPrompts&&(e.followUps=he(n.followUpPrompts)),n.action&&!e.action&&(e.action=n.action,e.actionRaw=n.action),r();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 n=="string"&&n?n.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=L(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let a=n&&typeof n=="object"?n:{};return e.run=L(e.run||U(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),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=fe(t.agentFlowExecutedData)),e.sources=le(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=he(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?_e(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=L(U(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function _e(s){try{return JSON.parse(s)}catch{return null}}var ue="cuttlely-chat";function F(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new N(s,e);return s.__cuttlelyChat=t,t}function D(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function ge(s){if(typeof customElements>"u"||customElements.get(ue))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,n){!this.isConnected||i===n||(r==="theme"&&this.widget?this.widget.setTheme(n||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=D(this,"flow-id");r&&(this.widget=F(this,{flowId:r,apiHost:D(this,"api-host")||s,mode:D(this,"mode")==="page"?"page":"bubble",theme:D(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(ue,e)}var I=typeof document<"u"?document.currentScript:null,X=(()=>{try{return I&&I.src?new URL(I.src).origin:location.origin}catch{return location.origin}})();ge(X);function me(){let s=(I==null?void 0:I.dataset)||{},e=s.flowId||s.flowid;if(!e)return;let t=s.mode==="page"?"page":"bubble",r;t==="page"&&s.target&&(r=document.querySelector(s.target)),r||(r=document.createElement("cuttlely-chat-root"),r.style.display=t==="page"?"block":"contents",t==="page"&&(r.style.height="100%"),document.body.append(r)),F(r,{flowId:e,apiHost:s.apiHost||X,mode:t,theme:s.theme||"auto",open:s.open==="true"})}var Ne={mount:(s,e)=>F(s,{apiHost:X,...e}),version:"1.3.2"};typeof window<"u"&&(window.cuttlelyChat=Ne);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",me,{once:!0}):me());})();
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
- var pe={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(s){return String(s??"").replace(/[&<>"']/g,e=>pe[e])}function j(s){let e=String(s??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Y=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function w(s,{image:e=!1,base:t=""}={}){if(typeof s!="string")return null;let r=s.trim();return!r||r.length>4096||/[\u0000-\u001f\u007f\s]/.test(r)&&!(e&&Y.test(r))?null:e&&/^data:/i.test(r)?Y.test(r)?r.replace(/\s+/g,""):null:/^https?:\/\//i.test(r)||!e&&/^mailto:[^/]/i.test(r)?r:r.startsWith("/")&&!r.startsWith("//")&&!r.startsWith("/\\")?t?j(t)+r:r:null}var he=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function fe(s,e){let t=0;for(let r=e;r<s.length;r++){let i=s[r];if(i==="\\"){r++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return r}return-1}function ue(s,e){if(s[e]!=="(")return null;let t=e+1;for(;s[t]===" ";)t++;let r="";if(s[t]==="<"){let i=s.indexOf(">",t);if(i===-1)return null;r=s.slice(t+1,i),t=i+1}else{let i=0,a=t;for(;t<s.length;t++){let o=s[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")break}r=s.slice(a,t)}for(;s[t]===" ";)t++;if(s[t]==='"'||s[t]==="'"){let i=s[t],a=s.indexOf(i,t+1);if(a===-1)return null;for(t=a+1;s[t]===" ";)t++}return s[t]!==")"?null:{url:r,end:t+1}}var ge=/^https?:\/\/[^\s<>"'`]+/i;function me(s){let e=s.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function be(s,e,t){let r=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,a]of r){if(!s.startsWith(i,e))continue;let o=s[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(s[e-1]))continue;let n=s.indexOf(i,e+i.length+1);for(;n!==-1;){let l=s[n-1],h=s[n+i.length],g=i[0]==="_"&&h&&/[a-z0-9]/i.test(h),p=i.length===1&&h===i;if(l&&!/\s/.test(l)&&!g&&!p)break;n=s.indexOf(i,n+1)}if(n===-1)continue;let d=s.slice(e+i.length,n);return{html:`<${a}>${C(d,t)}</${a}>`,end:n+i.length}}return null}function C(s,e={}){let t="",r="",i=()=>{r&&(t+=v(r).replace(/\n/g,"<br>")),r=""};for(let a=0;a<s.length;){let o=s[a];if(o==="\\"&&he.test(s[a+1]||"")){r+=s[a+1],a+=2;continue}if(o==="`"){let n=1;for(;s[a+n]==="`";)n++;let d="`".repeat(n),l=s.indexOf(d,a+n);if(l!==-1){i();let h=s.slice(a+n,l).replace(/\n/g," ");/^ .* $/.test(h)&&(h=h.slice(1,-1)),t+=`<code>${v(h)}</code>`,a=l+n;continue}r+=d,a+=n;continue}if(o==="!"&&s[a+1]==="["||o==="["){let n=o==="!",d=n?a+1:a,l=fe(s,d),h=l!==-1?ue(s,l+1):null;if(h){let g=s.slice(d+1,l),p=w(h.url,{image:n,base:e.base});i(),n?t+=p?`<img src="${v(p)}" alt="${v(g)}" loading="lazy">`:v(g):p&&!e.inLink?t+=`<a href="${v(p)}" target="_blank" rel="noopener noreferrer nofollow">${C(g,{...e,inLink:!0})}</a>`:t+=C(g,e),a=h.end;continue}}if(o==="<"){let n=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(s.slice(a));if(n){let d=w(n[1]);if(d&&!e.inLink){i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(n[1])}</a>`,a+=n[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(a===0||/[\s(]/.test(s[a-1]))){let n=ge.exec(s.slice(a));if(n){let d=me(n[0]);i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(d)}</a>`,a+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let n=be(s,a,e);if(n){i(),t+=n.html,a=n.end;continue}}r+=o,a++}return i(),t}var K=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,X=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,Q=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,L=/^ {0,3}> ?(.*)$/,M=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,Z=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function P(s){let e=s.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],r="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(r+="|",i++):e[i]==="|"?(t.push(r.trim()),r=""):r+=e[i];return t.push(r.trim()),t}function xe(s,e){return K.test(s)||X.test(s)||Q.test(s)||L.test(s)||M.test(s)||s.includes("|")&&e!==void 0&&Z.test(e)&&e.includes("-")}function ye(s,e){return`<div class="md-code"><div class="md-code-head"><span>${s?v(s.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${v(e)}</code></pre></div>`}function we(s,e){let t=P(s[0]),r=P(s[1]).map(o=>{let n=o.startsWith(":"),d=o.endsWith(":");return n&&d?"center":d?"right":n?"left":""}),i=(o,n,d)=>{let l=r[d]?` style="text-align:${r[d]}"`:"";return`<${o}${l}>${C(n,e)}</${o}>`},a='<div class="md-table"><table><thead><tr>';a+=t.map((o,n)=>i("th",o,n)).join(""),a+="</tr></thead><tbody>";for(let o of s.slice(2)){let n=P(o);a+="<tr>"+t.map((d,l)=>i("td",n[l]??"",l)).join("")+"</tr>"}return a+"</tbody></table></div>"}function ve(s,e,t){let r=M.exec(s[e]),i=/\d/.test(r[2]),a=r[1].length,o=[],n=e,d=!1;for(;n<s.length;){let p=M.exec(s[n]);if(!p||p[1].length!==a||/\d/.test(p[2])!==i)break;let u=a+p[2].length+1,m=[p[3]??""];n++;let y=!1;for(;n<s.length;){let b=s[n];if(!b.trim()){y=!0,m.push(""),n++;continue}let A=b.length-b.trimStart().length,k=M.exec(b);if(k&&k[1].length<=a)break;if(A<Math.min(u,a+2)&&!k){if(y)break;m.push(b.trim()),n++;continue}y&&(d=!0),y=!1,m.push(b.slice(Math.min(A,u))),n++}for(;m.length&&!m[m.length-1].trim();)m.pop();o.push(m)}let l=i&&parseInt(r[2],10)!==1?` start="${parseInt(r[2],10)}"`:"",h=i?"ol":"ul",g=o.map(p=>{let u=p.join(`
2
- `),m="",y=/^\[([ xX])\]\s+/.exec(u);y&&(m=`<span class="md-task" aria-hidden="true">${y[1]===" "?"\u2610":"\u2611"}</span> `,u=u.slice(y[0].length));let b=F(u.split(`
3
- `),t);return d||(b=b.replace(/^<p>([\s\S]*?)<\/p>/,(A,k)=>k)),`<li>${m}${b}</li>`}).join("");return{html:`<${h}${l}>${g}</${h}>`,end:n}}function F(s,e){let t="",r=0;for(;r<s.length;){let i=s[r];if(!i.trim()){r++;continue}let a=K.exec(i);if(a){let d=a[1],l=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(s[r]);)l.push(s[r]),r++;r++,t+=ye(a[2],l.join(`
4
- `));continue}let o=X.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,r++;continue}if(Q.test(i)){t+="<hr>",r++;continue}if(L.test(i)){let d=[];for(;r<s.length&&s[r].trim()&&L.test(s[r]);)d.push(L.exec(s[r])[1]),r++;t+=`<blockquote>${F(d,e)}</blockquote>`;continue}if(i.includes("|")&&r+1<s.length&&Z.test(s[r+1])&&s[r+1].includes("-")){let d=[i,s[r+1]];for(r+=2;r<s.length&&s[r].trim()&&s[r].includes("|");)d.push(s[r]),r++;t+=we(d,e);continue}if(M.test(i)){let d=ve(s,r,e);t+=d.html,r=d.end;continue}let n=[i.trim()];for(r++;r<s.length&&s[r].trim()&&!xe(s[r],s[r+1]);)n.push(s[r].trim()),r++;t+=`<p>${C(n.join(`
1
+ var he={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function v(s){return String(s??"").replace(/[&<>"']/g,e=>he[e])}function P(s){let e=String(s??""),t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return e.slice(0,t)}var Y=/^data:image\/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]+$/i;function w(s,{image:e=!1,base:t=""}={}){if(typeof s!="string")return null;let r=s.trim();return!r||r.length>4096||/[\u0000-\u001f\u007f\s]/.test(r)&&!(e&&Y.test(r))?null:e&&/^data:/i.test(r)?Y.test(r)?r.replace(/\s+/g,""):null:/^https?:\/\//i.test(r)||!e&&/^mailto:[^/]/i.test(r)?r:r.startsWith("/")&&!r.startsWith("//")&&!r.startsWith("/\\")?t?P(t)+r:r:null}var fe=/[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;function ue(s,e){let t=0;for(let r=e;r<s.length;r++){let i=s[r];if(i==="\\"){r++;continue}if(i==="[")t++;else if(i==="]"&&(t--,t===0))return r}return-1}function ge(s,e){if(s[e]!=="(")return null;let t=e+1;for(;s[t]===" ";)t++;let r="";if(s[t]==="<"){let i=s.indexOf(">",t);if(i===-1)return null;r=s.slice(t+1,i),t=i+1}else{let i=0,a=t;for(;t<s.length;t++){let o=s[t];if(o==="\\"){t++;continue}if(o==="(")i++;else if(o===")"){if(i===0)break;i--}else if(o===" ")break}r=s.slice(a,t)}for(;s[t]===" ";)t++;if(s[t]==='"'||s[t]==="'"){let i=s[t],a=s.indexOf(i,t+1);if(a===-1)return null;for(t=a+1;s[t]===" ";)t++}return s[t]!==")"?null:{url:r,end:t+1}}var me=/^https?:\/\/[^\s<>"'`]+/i;function be(s){let e=s.replace(/[.,;:!?*_~]+$/,"");for(;e.endsWith(")")&&(e.match(/\(/g)||[]).length<(e.match(/\)/g)||[]).length;)e=e.slice(0,-1);return e}function xe(s,e,t){let r=[["**","strong"],["__","strong"],["~~","del"],["*","em"],["_","em"]];for(let[i,a]of r){if(!s.startsWith(i,e))continue;let o=s[e+i.length];if(!o||/\s/.test(o)||i[0]==="_"&&e>0&&/[a-z0-9]/i.test(s[e-1]))continue;let n=s.indexOf(i,e+i.length+1);for(;n!==-1;){let l=s[n-1],h=s[n+i.length],g=i[0]==="_"&&h&&/[a-z0-9]/i.test(h),p=i.length===1&&h===i;if(l&&!/\s/.test(l)&&!g&&!p)break;n=s.indexOf(i,n+1)}if(n===-1)continue;let d=s.slice(e+i.length,n);return{html:`<${a}>${C(d,t)}</${a}>`,end:n+i.length}}return null}function C(s,e={}){let t="",r="",i=()=>{r&&(t+=v(r).replace(/\n/g,"<br>")),r=""};for(let a=0;a<s.length;){let o=s[a];if(o==="\\"&&fe.test(s[a+1]||"")){r+=s[a+1],a+=2;continue}if(o==="`"){let n=1;for(;s[a+n]==="`";)n++;let d="`".repeat(n),l=s.indexOf(d,a+n);if(l!==-1){i();let h=s.slice(a+n,l).replace(/\n/g," ");/^ .* $/.test(h)&&(h=h.slice(1,-1)),t+=`<code>${v(h)}</code>`,a=l+n;continue}r+=d,a+=n;continue}if(o==="!"&&s[a+1]==="["||o==="["){let n=o==="!",d=n?a+1:a,l=ue(s,d),h=l!==-1?ge(s,l+1):null;if(h){let g=s.slice(d+1,l),p=w(h.url,{image:n,base:e.base});i(),n?t+=p?`<img src="${v(p)}" alt="${v(g)}" loading="lazy">`:v(g):p&&!e.inLink?t+=`<a href="${v(p)}" target="_blank" rel="noopener noreferrer nofollow">${C(g,{...e,inLink:!0})}</a>`:t+=C(g,e),a=h.end;continue}}if(o==="<"){let n=/^<(https?:\/\/[^\s<>]+|mailto:[^\s<>]+)>/i.exec(s.slice(a));if(n){let d=w(n[1]);if(d&&!e.inLink){i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(n[1])}</a>`,a+=n[0].length;continue}}}if((o==="h"||o==="H")&&!e.inLink&&(a===0||/[\s(]/.test(s[a-1]))){let n=me.exec(s.slice(a));if(n){let d=be(n[0]);i(),t+=`<a href="${v(d)}" target="_blank" rel="noopener noreferrer nofollow">${v(d)}</a>`,a+=d.length;continue}}if(o==="*"||o==="_"||o==="~"){let n=xe(s,a,e);if(n){i(),t+=n.html,a=n.end;continue}}r+=o,a++}return i(),t}var K=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/,X=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*#*\s*$/,Q=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,B=/^ {0,3}> ?(.*)$/,M=/^( {0,12})([-*+]|\d{1,9}[.)])(?:\s+(.*))?$/,Z=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function F(s){let e=s.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));let t=[],r="";for(let i=0;i<e.length;i++)e[i]==="\\"&&e[i+1]==="|"?(r+="|",i++):e[i]==="|"?(t.push(r.trim()),r=""):r+=e[i];return t.push(r.trim()),t}function ye(s,e){return K.test(s)||X.test(s)||Q.test(s)||B.test(s)||M.test(s)||s.includes("|")&&e!==void 0&&Z.test(e)&&e.includes("-")}function we(s,e){return`<div class="md-code"><div class="md-code-head"><span>${s?v(s.slice(0,24)):"code"}</span><button type="button" class="md-copy" data-copy-code aria-label="Copy code">Copy</button></div><pre><code>${v(e)}</code></pre></div>`}function ve(s,e){let t=F(s[0]),r=F(s[1]).map(o=>{let n=o.startsWith(":"),d=o.endsWith(":");return n&&d?"center":d?"right":n?"left":""}),i=(o,n,d)=>{let l=r[d]?` style="text-align:${r[d]}"`:"";return`<${o}${l}>${C(n,e)}</${o}>`},a='<div class="md-table"><table><thead><tr>';a+=t.map((o,n)=>i("th",o,n)).join(""),a+="</tr></thead><tbody>";for(let o of s.slice(2)){let n=F(o);a+="<tr>"+t.map((d,l)=>i("td",n[l]??"",l)).join("")+"</tr>"}return a+"</tbody></table></div>"}function ke(s,e,t){let r=M.exec(s[e]),i=/\d/.test(r[2]),a=r[1].length,o=[],n=e,d=!1;for(;n<s.length;){let p=M.exec(s[n]);if(!p||p[1].length!==a||/\d/.test(p[2])!==i)break;let u=a+p[2].length+1,m=[p[3]??""];n++;let y=!1;for(;n<s.length;){let b=s[n];if(!b.trim()){y=!0,m.push(""),n++;continue}let A=b.length-b.trimStart().length,k=M.exec(b);if(k&&k[1].length<=a)break;if(A<Math.min(u,a+2)&&!k){if(y)break;m.push(b.trim()),n++;continue}y&&(d=!0),y=!1,m.push(b.slice(Math.min(A,u))),n++}for(;m.length&&!m[m.length-1].trim();)m.pop();o.push(m)}let l=i&&parseInt(r[2],10)!==1?` start="${parseInt(r[2],10)}"`:"",h=i?"ol":"ul",g=o.map(p=>{let u=p.join(`
2
+ `),m="",y=/^\[([ xX])\]\s+/.exec(u);y&&(m=`<span class="md-task" aria-hidden="true">${y[1]===" "?"\u2610":"\u2611"}</span> `,u=u.slice(y[0].length));let b=j(u.split(`
3
+ `),t);return d||(b=b.replace(/^<p>([\s\S]*?)<\/p>/,(A,k)=>k)),`<li>${m}${b}</li>`}).join("");return{html:`<${h}${l}>${g}</${h}>`,end:n}}function j(s,e){let t="",r=0;for(;r<s.length;){let i=s[r];if(!i.trim()){r++;continue}let a=K.exec(i);if(a){let d=a[1],l=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${d[0]}{${d.length},}\\s*$`).test(s[r]);)l.push(s[r]),r++;r++,t+=we(a[2],l.join(`
4
+ `));continue}let o=X.exec(i);if(o){let d=o[1].length;t+=`<h${d}>${C(o[2]||"",e)}</h${d}>`,r++;continue}if(Q.test(i)){t+="<hr>",r++;continue}if(B.test(i)){let d=[];for(;r<s.length&&s[r].trim()&&B.test(s[r]);)d.push(B.exec(s[r])[1]),r++;t+=`<blockquote>${j(d,e)}</blockquote>`;continue}if(i.includes("|")&&r+1<s.length&&Z.test(s[r+1])&&s[r+1].includes("-")){let d=[i,s[r+1]];for(r+=2;r<s.length&&s[r].trim()&&s[r].includes("|");)d.push(s[r]),r++;t+=ve(d,e);continue}if(M.test(i)){let d=ke(s,r,e);t+=d.html,r=d.end;continue}let n=[i.trim()];for(r++;r<s.length&&s[r].trim()&&!ye(s[r],s[r+1]);)n.push(s[r].trim()),r++;t+=`<p>${C(n.join(`
5
5
  `),e)}</p>`}return t}function W(s,e={}){if(typeof s!="string"||!s)return"";let t=s.replace(/\r\n?/g,`
6
6
  `).replace(/\t/g," ").split(`
7
- `);return F(t,{base:e.base||""})}function ee(s){let e="",t=r=>{let i=[];for(let n of r.split(/\r?\n/))n.startsWith("data:")&&i.push(n.slice(n[5]===" "?6:5));if(!i.length)return;let a=i.join(`
8
- `),o;try{o=JSON.parse(a)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let a=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(a)}},end(){e.trim()&&t(e),e=""}}}var q=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function z(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new q(s.status,String(e||"").slice(0,300))}function te({apiHost:s,flowId:e,fetchImpl:t}){let r=j(s||""),i=encodeURIComponent(e),a=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await a(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await z(o);let n=await o.text();try{return JSON.parse(n)}catch{return{}}},async send(o,n={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,E]of Object.entries(h))E!=null&&A.append(k,typeof E=="object"?JSON.stringify(E):String(E));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await a(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await z(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ee(D=>{var B;return(B=n.onEvent)==null?void 0:B.call(n,D)}),k=p.body.getReader(),E=new TextDecoder;for(;;){let{value:D,done:B}=await k.read();if(B)break;A.push(E.decode(D,{stream:!0}))}A.push(E.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=n.onJson)==null||b.call(n,y)},async feedback({messageId:o,chatId:n,rating:d}){let l=await a(`${r}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:n,messageId:o,rating:d})});if(!l.ok)throw await z(l)},fileUrl(o,n){let d=String(n||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,n){let d=await a(o,{headers:n?{"x-cuttlely-session-token":n}:{}});if(!d.ok)throw await z(d);return d.blob()}}}function I(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var ke={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},Te=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!Te.test(t)||e&&((r=ke[e])!=null&&r.includes(t.toLowerCase()))?"":t}function S(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function re(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>S(t,300)).filter(Boolean).slice(0,6)}function Ae(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let a of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof a=="string"&&e.add(a);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function H(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},a=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},n=Ae(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:S(t.title,80),avatar:w(S(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(S(r.avatarSrc),{image:!0})||"",welcome:S(t.welcomeMessage),errorMessage:S(t.errorMessage,300),placeholder:S(a.placeholder,120),starterPrompts:re(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&n.types.length?n:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(a.backgroundColor,"inputBackground"),inputText:T(a.textColor,"inputText"),accent:T(a.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=re(u):p==="avatar"?l.avatar=w(S(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=S(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ie(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},O='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function R(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function J(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let a=s.slice();return a[i]={...a[i],...t},a}function $(s,e,t={}){var a,o;let r=s||R(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let n of Array.isArray(t.steps)?t.steps:[])i.specialists=J(i.specialists,n.specialist,{task:typeof n.task=="string"?n.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=J(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=J(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let n=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;n?i.specialists=n.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((a=t.trace)==null?void 0:a.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function V(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Se={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:[]},Ee=/^text-align:(left|right|center)$/;function se(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Se[r.tagName];if(!i)t.push(r);else{for(let a of Array.from(r.attributes)){let o=a.name.toLowerCase(),n=i.includes(o);n&&(o==="href"||o==="src")&&(n=w(a.value,{image:o==="src"})!==null),n&&o==="style"&&(n=Ee.test(a.value)),n&&o==="target"&&(n=a.value==="_blank"),n||r.removeAttribute(a.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ae=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Ce="cuttlely-chat:v1:",Me=60,Ie="https://github.com/cuttlely/cuttlely",$e=0,U=s=>`${s}-${Date.now().toString(36)}-${($e++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,a]of Object.entries(e||{}))a==null||a===!1||(i==="class"?r.className=a:i==="text"?r.textContent=a:i==="html"?r.innerHTML=a:i.startsWith("on")&&typeof a=="function"?r.addEventListener(i.slice(2),a):r.setAttribute(i,a===!0?"":String(a)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function ne(s,e){let t=document.createElement("template");t.innerHTML=W(s,{base:e}),se(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function oe(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let a=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof a.url=="string"?a.url:typeof a.source=="string"?a.source:""),n=a.title||a.source||a.url||a.name||i.title||"",d=String(n||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function G(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data})).slice(0,8)}function ce(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function de(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let a=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof a=="string"&&a.trim())return a}return""}var N=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=te({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=H({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=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:ae});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,a,o;let e=this.options.theme,t=n=>this.wrap.classList.toggle("dark",n);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var n;return t(!!((n=this.media)!=null&&n.matches))},this.onMedia(),(o=(a=this.media)==null?void 0:a.addEventListener)==null||o.call(a,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ie(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=H(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=I(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${Ce}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:U("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:G(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-Me).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let a=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==a)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=a,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,a)=>i!==e[a]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(a=>c("img",{src:a,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(a=>c("span",{class:"dc-file-chip",html:f.doc},[a])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var n,d,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=O;let a=c("div",{class:"dc-body"});e.run&&a.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=ne(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&a.append(o),(n=e.artifacts)!=null&&n.length&&a.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&a.append(this.renderSources(e.sources)),e.error&&a.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&a.append(this.renderAction(e)),e.status==="done"&&e.text&&a.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&a.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),a])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,a={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${V(e.totalMs)}`:t?"Working\u2026":"",n=c("details",{class:"dc-run"});!r&&t&&(n.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:a}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return n.append(d),i&&n.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:V(l.ms)}):null])))),n}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(ne(r.data,this.base));return t}renderImageArtifact(e){let t=w(e.data,{image:!0,base:this.base}),r=t&&!e.data.startsWith("/")?t:this.api.fileUrl(this.chatId,e.data),i=c("figure",{class:"dc-figure"}),a=c("img",{src:r,alt:"Chart from the answer",loading:"lazy"});a.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let o=!1;return a.addEventListener("error",async()=>{if(!o&&!t&&this.sessionToken&&this.chatId){o=!0;try{let n=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);a.src=URL.createObjectURL(n);return}catch{}}i.replaceChildren(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),i.append(a),i}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((a,o)=>{let n=[c("b",{text:String(o+1)}),c("span",{text:a.title})],d;a.url?d=c("a",{class:"dc-source",href:a.url,target:"_blank",rel:"noopener noreferrer nofollow",title:a.title},n):(d=c("button",{class:"dc-source",type:"button",title:a.title,"aria-expanded":"false"},n),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&a.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:a.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,a)=>c("button",{class:`dc-chip${a===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,a,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:a,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let a=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);a.length&&(i.preventDefault(),this.addFiles(a))}),this.window.addEventListener("dragover",i=>{i.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",i=>{i.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",i=>{var a;i.preventDefault(),this.clearDrop(),this.addFiles(((a=i.dataTransfer)==null?void 0:a.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Ie,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(a=>{let o=new FileReader;o.onload=()=>a(typeof o.result=="string"?o.result:""),o.onerror=()=>a(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let a=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:a,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",a=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!a.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:U("m"),role:"user",text:i.trim(),images:a.map(p=>p.data),status:"done",rev:0},n={id:U("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,n),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let d={question:i.trim()};this.chatId&&(d.chatId=this.chatId),this.sessionToken&&(d.sessionToken=this.sessionToken),a.length&&(d.uploads=a),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{n.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(n,p,h),onJson:p=>this.onJson(n,p)},l.signal),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.text=n.fallbackText||""),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.error="The answer was empty. Try asking another way.")}catch(p){if(l.signal.aborted)n.text||(n.text="_Stopped._");else{let u=I(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}n.error=u.message,n.retry={text:i.trim(),extra:t,uploads:a}}}finally{this.controller===l&&(this.controller=null)}n.status="done",n.run&&n.run.phase!=="done"&&n.run.phase!=="failed"&&(n.run=$(n.run,n.error?"error":"final",{})),n.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(n.error?n.error:`Answer: ${n.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,r){let{event:i,data:a}=t;if(i==="token"&&typeof a=="string")return e.text+=a,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=oe(a),r();if(i==="artifacts")return e.artifacts=G(a),r();if(i==="action")return e.action=a&&typeof a=="object"?a:null,e.actionRaw=a,r();if(i==="agentFlowExecutedData"){e.fallbackText=de(a)||e.fallbackText;return}if(i==="metadata"&&a&&typeof a=="object")return typeof a.chatId=="string"&&(this.chatId=a.chatId),typeof a.sessionToken=="string"&&(this.sessionToken=a.sessionToken),typeof a.chatMessageId=="string"&&(e.messageId=a.chatMessageId),a.followUpPrompts&&(e.followUps=ce(a.followUpPrompts)),a.action&&!e.action&&(e.action=a.action,e.actionRaw=a.action),r();if(i==="error"){let o=typeof t.status=="number"?t.status:0,n=o?I({status:o},this.config.errorMessage):null;return e.error=n&&n.kind!=="error"?n.message:this.config.errorMessage||(typeof a=="string"&&a?a.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=$(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let n=a&&typeof a=="object"?a:{};return e.run=$(e.run||R(n.harness),o,n),o==="partial"&&n.phase==="answer"&&!n.streamedAsToken&&typeof n.text=="string"&&(e.text+=n.text),o==="final"&&!e.text&&typeof n.text=="string"&&(e.fallbackText=n.text),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=de(t.agentFlowExecutedData)),e.sources=oe(t.sourceDocuments),e.artifacts=G(t.artifacts),t.followUpPrompts&&(e.followUps=ce(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?Be(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=$(R(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function Be(s){try{return JSON.parse(s)}catch{return null}}var le="cuttlely-chat";function Le(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new N(s,e);return s.__cuttlelyChat=t,t}function _(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function et(s){if(typeof customElements>"u"||customElements.get(le))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,a){!this.isConnected||i===a||(r==="theme"&&this.widget?this.widget.setTheme(a||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=_(this,"flow-id");r&&(this.widget=Le(this,{flowId:r,apiHost:_(this,"api-host")||s,mode:_(this,"mode")==="page"?"page":"bubble",theme:_(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(le,e)}export{N as ChatWidget,le as ELEMENT_NAME,et as defineElement,v as escapeHtml,Le as mount,H as normalizeConfig,W as renderMarkdown,w as safeUrl};
7
+ `);return j(t,{base:e.base||""})}function ee(s){let e="",t=r=>{let i=[];for(let n of r.split(/\r?\n/))n.startsWith("data:")&&i.push(n.slice(n[5]===" "?6:5));if(!i.length)return;let a=i.join(`
8
+ `),o;try{o=JSON.parse(a)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let a=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(a)}},end(){e.trim()&&t(e),e=""}}}var q=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function z(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new q(s.status,String(e||"").slice(0,300))}function te({apiHost:s,flowId:e,fetchImpl:t}){let r=P(s||""),i=encodeURIComponent(e),a=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await a(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await z(o);let n=await o.text();try{return JSON.parse(n)}catch{return{}}},async send(o,n={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,S]of Object.entries(h))S!=null&&A.append(k,typeof S=="object"?JSON.stringify(S):String(S));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await a(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await z(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ee(D=>{var L;return(L=n.onEvent)==null?void 0:L.call(n,D)}),k=p.body.getReader(),S=new TextDecoder;for(;;){let{value:D,done:L}=await k.read();if(L)break;A.push(S.decode(D,{stream:!0}))}A.push(S.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=n.onJson)==null||b.call(n,y)},async feedback({messageId:o,chatId:n,rating:d}){let l=await a(`${r}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:n,messageId:o,rating:d})});if(!l.ok)throw await z(l)},fileUrl(o,n){let d=String(n||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,n){let d=await a(o,{headers:n?{"x-cuttlely-session-token":n}:{}});if(!d.ok)throw await z(d);return d.blob()}}}function I(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Te={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},Ae=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!Ae.test(t)||e&&((r=Te[e])!=null&&r.includes(t.toLowerCase()))?"":t}function E(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function re(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>E(t,300)).filter(Boolean).slice(0,6)}function Ee(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let a of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof a=="string"&&e.add(a);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function H(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},a=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},n=Ee(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:E(t.title,80),avatar:w(E(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(E(r.avatarSrc),{image:!0})||"",welcome:E(t.welcomeMessage),errorMessage:E(t.errorMessage,300),placeholder:E(a.placeholder,120),starterPrompts:re(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&n.types.length?n:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(a.backgroundColor,"inputBackground"),inputText:T(a.textColor,"inputText"),accent:T(a.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=re(u):p==="avatar"?l.avatar=w(E(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=E(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ie(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},O='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function R(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function J(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let a=s.slice();return a[i]={...a[i],...t},a}function $(s,e,t={}){var a,o;let r=s||R(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let n of Array.isArray(t.steps)?t.steps:[])i.specialists=J(i.specialists,n.specialist,{task:typeof n.task=="string"?n.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=J(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=J(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let n=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;n?i.specialists=n.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((a=t.trace)==null?void 0:a.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function V(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Se={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:[]},Ce=/^text-align:(left|right|center)$/;function se(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Se[r.tagName];if(!i)t.push(r);else{for(let a of Array.from(r.attributes)){let o=a.name.toLowerCase(),n=i.includes(o);n&&(o==="href"||o==="src")&&(n=w(a.value,{image:o==="src"})!==null),n&&o==="style"&&(n=Ce.test(a.value)),n&&o==="target"&&(n=a.value==="_blank"),n||r.removeAttribute(a.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ae=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Me="cuttlely-chat:v1:",Ie=60,$e="https://github.com/cuttlely/cuttlely",Le=0,U=s=>`${s}-${Date.now().toString(36)}-${(Le++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,a]of Object.entries(e||{}))a==null||a===!1||(i==="class"?r.className=a:i==="text"?r.textContent=a:i==="html"?r.innerHTML=a:i.startsWith("on")&&typeof a=="function"?r.addEventListener(i.slice(2),a):r.setAttribute(i,a===!0?"":String(a)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function ne(s,e){let t=document.createElement("template");t.innerHTML=W(s,{base:e}),se(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function oe(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let a=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof a.url=="string"?a.url:typeof a.source=="string"?a.source:""),n=a.title||a.source||a.url||a.name||i.title||"",d=String(n||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function G(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var ce=["pdf","docx","xlsx","csv"];function Be(s){let e=typeof(s==null?void 0:s.name)=="string"?s.name:"",t=String((s==null?void 0:s.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(s==null?void 0:s.type)||"bin"}`}function de(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function le(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let a=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof a=="string"&&a.trim())return a}return""}var _=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=te({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=H({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=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:ae});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,a,o;let e=this.options.theme,t=n=>this.wrap.classList.toggle("dark",n);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var n;return t(!!((n=this.media)!=null&&n.matches))},this.onMedia(),(o=(a=this.media)==null?void 0:a.addEventListener)==null||o.call(a,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ie(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=H(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=I(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${Me}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:U("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:G(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-Ie).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let a=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==a)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=a,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,a)=>i!==e[a]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(a=>c("img",{src:a,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(a=>c("span",{class:"dc-file-chip",html:f.doc},[a])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var n,d,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=O;let a=c("div",{class:"dc-body"});e.run&&a.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=ne(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&a.append(o),(n=e.artifacts)!=null&&n.length&&a.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&a.append(this.renderSources(e.sources)),e.error&&a.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&a.append(this.renderAction(e)),e.status==="done"&&e.text&&a.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&a.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),a])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,a={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${V(e.totalMs)}`:t?"Working\u2026":"",n=c("details",{class:"dc-run"});!r&&t&&(n.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:a}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return n.append(d),i&&n.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:V(l.ms)}):null])))),n}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(ce.includes(r.type)&&r.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(r));else{if(ce.includes(r.type))continue;if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(ne(r.data,this.base))}return t}renderFileArtifact(e){let t=Be(e),r=()=>`${this.api.fileUrl(this.chatId,e.data)}&download=true`,i=c("a",{class:"dc-file",href:r(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:e.type.toUpperCase()}),c("span",{class:"dc-file-name",text:t})]);return i.addEventListener("click",async a=>{if(!this.sessionToken||!this.chatId){i.href=r();return}a.preventDefault();try{let o=await this.api.fileBlob(r(),this.sessionToken),n=URL.createObjectURL(o);c("a",{href:n,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(n),3e4)}catch{i.replaceWith(c("div",{class:"dc-figure-missing",html:f.alert},[`${t} could not be downloaded here.`]))}}),i}renderImageArtifact(e){let t=w(e.data,{image:!0,base:this.base}),r=t&&!e.data.startsWith("/")?t:this.api.fileUrl(this.chatId,e.data),i=c("figure",{class:"dc-figure"}),a=c("img",{src:r,alt:"Chart from the answer",loading:"lazy"});a.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let o=!1;return a.addEventListener("error",async()=>{if(!o&&!t&&this.sessionToken&&this.chatId){o=!0;try{let n=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);a.src=URL.createObjectURL(n);return}catch{}}i.replaceChildren(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),i.append(a),i}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((a,o)=>{let n=[c("b",{text:String(o+1)}),c("span",{text:a.title})],d;a.url?d=c("a",{class:"dc-source",href:a.url,target:"_blank",rel:"noopener noreferrer nofollow",title:a.title},n):(d=c("button",{class:"dc-source",type:"button",title:a.title,"aria-expanded":"false"},n),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&a.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:a.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,a)=>c("button",{class:`dc-chip${a===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,a,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:a,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let a=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);a.length&&(i.preventDefault(),this.addFiles(a))}),this.window.addEventListener("dragover",i=>{i.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",i=>{i.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",i=>{var a;i.preventDefault(),this.clearDrop(),this.addFiles(((a=i.dataTransfer)==null?void 0:a.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:$e,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(a=>{let o=new FileReader;o.onload=()=>a(typeof o.result=="string"?o.result:""),o.onerror=()=>a(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let a=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:a,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",a=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!a.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:U("m"),role:"user",text:i.trim(),images:a.map(p=>p.data),status:"done",rev:0},n={id:U("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,n),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let d={question:i.trim()};this.chatId&&(d.chatId=this.chatId),this.sessionToken&&(d.sessionToken=this.sessionToken),a.length&&(d.uploads=a),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{n.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(n,p,h),onJson:p=>this.onJson(n,p)},l.signal),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.text=n.fallbackText||""),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.error="The answer was empty. Try asking another way.")}catch(p){if(l.signal.aborted)n.text||(n.text="_Stopped._");else{let u=I(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}n.error=u.message,n.retry={text:i.trim(),extra:t,uploads:a}}}finally{this.controller===l&&(this.controller=null)}n.status="done",n.run&&n.run.phase!=="done"&&n.run.phase!=="failed"&&(n.run=$(n.run,n.error?"error":"final",{})),n.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(n.error?n.error:`Answer: ${n.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,r){let{event:i,data:a}=t;if(i==="token"&&typeof a=="string")return e.text+=a,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=oe(a),r();if(i==="artifacts")return e.artifacts=G(a),r();if(i==="action")return e.action=a&&typeof a=="object"?a:null,e.actionRaw=a,r();if(i==="agentFlowExecutedData"){e.fallbackText=le(a)||e.fallbackText;return}if(i==="metadata"&&a&&typeof a=="object")return typeof a.chatId=="string"&&(this.chatId=a.chatId),typeof a.sessionToken=="string"&&(this.sessionToken=a.sessionToken),typeof a.chatMessageId=="string"&&(e.messageId=a.chatMessageId),a.followUpPrompts&&(e.followUps=de(a.followUpPrompts)),a.action&&!e.action&&(e.action=a.action,e.actionRaw=a.action),r();if(i==="error"){let o=typeof t.status=="number"?t.status:0,n=o?I({status:o},this.config.errorMessage):null;return e.error=n&&n.kind!=="error"?n.message:this.config.errorMessage||(typeof a=="string"&&a?a.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=$(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let n=a&&typeof a=="object"?a:{};return e.run=$(e.run||R(n.harness),o,n),o==="partial"&&n.phase==="answer"&&!n.streamedAsToken&&typeof n.text=="string"&&(e.text+=n.text),o==="final"&&!e.text&&typeof n.text=="string"&&(e.fallbackText=n.text),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=le(t.agentFlowExecutedData)),e.sources=oe(t.sourceDocuments),e.artifacts=G(t.artifacts),t.followUpPrompts&&(e.followUps=de(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?ze(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=$(R(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function ze(s){try{return JSON.parse(s)}catch{return null}}var pe="cuttlely-chat";function He(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new _(s,e);return s.__cuttlelyChat=t,t}function N(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function rt(s){if(typeof customElements>"u"||customElements.get(pe))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,a){!this.isConnected||i===a||(r==="theme"&&this.widget?this.widget.setTheme(a||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=N(this,"flow-id");r&&(this.widget=He(this,{flowId:r,apiHost:N(this,"api-host")||s,mode:N(this,"mode")==="page"?"page":"bubble",theme:N(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(pe,e)}export{_ as ChatWidget,pe as ELEMENT_NAME,rt as defineElement,v as escapeHtml,He as mount,H as normalizeConfig,W as renderMarkdown,w as safeUrl};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuttlely/chat",
3
- "version": "1.3.1",
3
+ "version": "1.3.2",
4
4
  "description": "Embeddable Cuttlely chat widget for applications",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",