@cuttlely/chat 1.4.4 → 1.4.5

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.
Files changed (2) hide show
  1. package/dist/chat.js +1 -1
  2. package/package.json +1 -1
package/dist/chat.js CHANGED
@@ -5,4 +5,4 @@
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 n of r.split(/\r?\n/))n.startsWith("data:")&&i.push(n.slice(n[5]===" "?6:5));if(!i.length)return;let a=i.join(`
8
- `),o;try{o=JSON.parse(a)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let a=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(a)}},end(){e.trim()&&t(e),e=""}}}var J=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function R(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new J(s.status,String(e||"").slice(0,300))}function se({apiHost:s,flowId:e,fetchImpl:t}){let r=W(s||""),i=encodeURIComponent(e),a=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await a(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await R(o);let n=await o.text();try{return JSON.parse(n)}catch{return{}}},async send(o,n={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,S]of Object.entries(h))S!=null&&A.append(k,typeof S=="object"?JSON.stringify(S):String(S));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await a(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await R(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ie(F=>{var B;return(B=n.onEvent)==null?void 0:B.call(n,F)}),k=p.body.getReader(),S=new TextDecoder;for(;;){let{value:F,done:B}=await k.read();if(B)break;A.push(S.decode(F,{stream:!0}))}A.push(S.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=n.onJson)==null||b.call(n,y)},async feedback({messageId:o,chatId:n,rating:d}){let l=await a(`${r}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:n,messageId:o,rating:d})});if(!l.ok)throw await R(l)},fileUrl(o,n){let d=String(n||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,n){let d=await a(o,{headers:n?{"x-cuttlely-session-token":n}:{}});if(!d.ok)throw await R(d);return d.blob()}}}function $(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Me={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},$e=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!$e.test(t)||e&&((r=Me[e])!=null&&r.includes(t.toLowerCase()))?"":t}function E(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function ae(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>E(t,300)).filter(Boolean).slice(0,6)}function Le(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let a of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof a=="string"&&e.add(a);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function H(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},a=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},n=Le(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:E(t.title,80),avatar:w(E(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(E(r.avatarSrc),{image:!0})||"",welcome:E(t.welcomeMessage),errorMessage:E(t.errorMessage,300),placeholder:E(a.placeholder,120),starterPrompts:ae(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&n.types.length?n:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(a.backgroundColor,"inputBackground"),inputText:T(a.textColor,"inputText"),accent:T(a.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=ae(u):p==="avatar"?l.avatar=w(E(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=E(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ne(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},O='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function U(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function G(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let a=s.slice();return a[i]={...a[i],...t},a}function L(s,e,t={}){var a,o;let r=s||U(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let n of Array.isArray(t.steps)?t.steps:[])i.specialists=G(i.specialists,n.specialist,{task:typeof n.task=="string"?n.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=G(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=G(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let n=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;n?i.specialists=n.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((a=t.trace)==null?void 0:a.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Y(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Be={A:["href","target","rel"],BLOCKQUOTE:[],BR:[],BUTTON:["type","class","data-copy-code","aria-label"],CODE:[],DEL:[],DIV:["class"],EM:[],H1:[],H2:[],H3:[],H4:[],H5:[],H6:[],HR:[],IMG:["src","alt","loading"],LI:[],OL:["start"],P:[],PRE:[],SPAN:["class","aria-hidden"],STRONG:[],TABLE:[],TBODY:[],TD:["style"],TH:["style"],THEAD:[],TR:[],UL:[]},ze=/^text-align:(left|right|center)$/;function oe(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Be[r.tagName];if(!i)t.push(r);else{for(let a of Array.from(r.attributes)){let o=a.name.toLowerCase(),n=i.includes(o);n&&(o==="href"||o==="src")&&(n=w(a.value,{image:o==="src"})!==null),n&&o==="style"&&(n=ze.test(a.value)),n&&o==="target"&&(n=a.value==="_blank"),n||r.removeAttribute(a.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ce=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-figure .dc-image-download{border:0;border-top:1px solid var(--dc-border);border-radius:0;padding:8px 12px}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Re="cuttlely-chat:v1:",He=60,Oe="https://github.com/cuttlely/cuttlely",Ue=0,_=s=>`${s}-${Date.now().toString(36)}-${(Ue++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,a]of Object.entries(e||{}))a==null||a===!1||(i==="class"?r.className=a:i==="text"?r.textContent=a:i==="html"?r.innerHTML=a:i.startsWith("on")&&typeof a=="function"?r.addEventListener(i.slice(2),a):r.setAttribute(i,a===!0?"":String(a)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function de(s,e){let t=document.createElement("template");t.innerHTML=V(s,{base:e}),oe(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function le(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let a=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof a.url=="string"?a.url:typeof a.source=="string"?a.source:""),n=a.title||a.source||a.url||a.name||i.title||"",d=String(n||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function K(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var pe=["pdf","docx","xlsx","pptx","csv"];function he(s){let e=typeof(s==null?void 0:s.name)=="string"?s.name:"",t=String((s==null?void 0:s.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(s==null?void 0:s.type)||"bin"}`}function fe(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function ue(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let a=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof a=="string"&&a.trim())return a}return""}var N=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=se({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=H({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=_("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:ce});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,a,o;let e=this.options.theme,t=n=>this.wrap.classList.toggle("dark",n);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var n;return t(!!((n=this.media)!=null&&n.matches))},this.onMedia(),(o=(a=this.media)==null?void 0:a.addEventListener)==null||o.call(a,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ne(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=H(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=$(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${Re}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:_("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:K(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-He).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let a=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==a)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=a,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,a)=>i!==e[a]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(a=>c("img",{src:a,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(a=>c("span",{class:"dc-file-chip",html:f.doc},[a])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var n,d,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=O;let a=c("div",{class:"dc-body"});e.run&&a.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=de(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&a.append(o),(n=e.artifacts)!=null&&n.length&&a.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&a.append(this.renderSources(e.sources)),e.error&&a.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&a.append(this.renderAction(e)),e.status==="done"&&e.text&&a.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&a.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),a])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,a={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:t?"Working\u2026":"",n=c("details",{class:"dc-run"});!r&&t&&(n.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:a}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return n.append(d),i&&n.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Y(l.ms)}):null])))),n}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(pe.includes(r.type)&&r.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(r));else{if(pe.includes(r.type))continue;if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(de(r.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,he(e),e.type.toUpperCase())}renderDownloadLink(e,t,r,i=""){let a=!e.data.startsWith("data:"),o=()=>a?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,n=c("a",{class:`dc-file${i}`,href:o(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:r}),c("span",{class:"dc-file-name",text:t})]);return n.addEventListener("click",async d=>{if(!a||!this.sessionToken||!this.chatId){n.href=o();return}d.preventDefault();try{let l=await this.api.fileBlob(o(),this.sessionToken),h=URL.createObjectURL(l);c("a",{href:h,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(h),3e4)}catch{n.replaceWith(c("div",{class:"dc-figure-missing",html:f.alert},[`${t} could not be downloaded here.`]))}}),n}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":he(e),r=e.type==="jpeg"?"jpg":e.type;return(r==="jpg"?/\.jpe?g$/i:new RegExp(`\\.${r}$`,"i")).test(t)?t:`${t.replace(/\.[^.]*$/,"")||"image"}.${r}`}renderImageArtifact(e){let t=e.type==="jpg"?"jpeg":e.type,r=new RegExp(`^data:image/${t};base64,[A-Za-z0-9+/]+={0,2}$`).test(e.data),i=e.data.startsWith("FILE-STORAGE::")||!/[:/\\]/.test(e.data),a=r?e.data:w(e.data,{image:!0,base:this.base}),o=a&&!e.data.startsWith("/")?a:this.api.fileUrl(this.chatId,e.data),n=c("figure",{class:"dc-figure"}),d=c("img",{src:o,alt:"Chart from the answer",loading:"lazy"});d.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let l=!1;if(d.addEventListener("error",async()=>{if(!l&&!a&&this.sessionToken&&this.chatId){l=!0;try{let h=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);d.src=URL.createObjectURL(h);return}catch{}}d.replaceWith(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),n.append(d),i||r){let h=this.imageArtifactName(e),g=(e.type==="jpeg"?"jpg":e.type).toUpperCase();n.append(this.renderDownloadLink(e,h,g," dc-image-download"))}return n}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((a,o)=>{let n=[c("b",{text:String(o+1)}),c("span",{text:a.title})],d;a.url?d=c("a",{class:"dc-source",href:a.url,target:"_blank",rel:"noopener noreferrer nofollow",title:a.title},n):(d=c("button",{class:"dc-source",type:"button",title:a.title,"aria-expanded":"false"},n),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&a.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:a.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,a)=>c("button",{class:`dc-chip${a===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,a,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:a,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let a=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);a.length&&(i.preventDefault(),this.addFiles(a))}),this.window.addEventListener("dragover",i=>{i.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",i=>{i.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",i=>{var a;i.preventDefault(),this.clearDrop(),this.addFiles(((a=i.dataTransfer)==null?void 0:a.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Oe,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(a=>{let o=new FileReader;o.onload=()=>a(typeof o.result=="string"?o.result:""),o.onerror=()=>a(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let a=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:a,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",a=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!a.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:_("m"),role:"user",text:i.trim(),images:a.map(p=>p.data),status:"done",rev:0},n={id:_("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,n),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let d={question:i.trim()};this.chatId&&(d.chatId=this.chatId),this.sessionToken&&(d.sessionToken=this.sessionToken),a.length&&(d.uploads=a),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{n.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(n,p,h),onJson:p=>this.onJson(n,p)},l.signal),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.text=n.fallbackText||""),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.error="The answer was empty. Try asking another way.")}catch(p){if(l.signal.aborted)n.text||(n.text="_Stopped._");else{let u=$(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}n.error=u.message,n.retry={text:i.trim(),extra:t,uploads:a}}}finally{this.controller===l&&(this.controller=null)}n.status="done",n.run&&n.run.phase!=="done"&&n.run.phase!=="failed"&&(n.run=L(n.run,n.error?"error":"final",{})),n.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(n.error?n.error:`Answer: ${n.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,r){let{event:i,data:a}=t;if(i==="token"&&typeof a=="string")return e.text+=a,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=le(a),r();if(i==="artifacts")return e.artifacts=K(a),r();if(i==="action")return e.action=a&&typeof a=="object"?a:null,e.actionRaw=a,r();if(i==="agentFlowExecutedData"){e.fallbackText=ue(a)||e.fallbackText;return}if(i==="metadata"&&a&&typeof a=="object")return typeof a.chatId=="string"&&(this.chatId=a.chatId),typeof a.sessionToken=="string"&&(this.sessionToken=a.sessionToken),typeof a.chatMessageId=="string"&&(e.messageId=a.chatMessageId),a.followUpPrompts&&(e.followUps=fe(a.followUpPrompts)),a.action&&!e.action&&(e.action=a.action,e.actionRaw=a.action),r();if(i==="error"){let o=typeof t.status=="number"?t.status:0,n=o?$({status:o},this.config.errorMessage):null;return e.error=n&&n.kind!=="error"?n.message:this.config.errorMessage||(typeof a=="string"&&a?a.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=L(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let n=a&&typeof a=="object"?a:{};return e.run=L(e.run||U(n.harness),o,n),o==="partial"&&n.phase==="answer"&&!n.streamedAsToken&&typeof n.text=="string"&&(e.text+=n.text),o==="final"&&!e.text&&typeof n.text=="string"&&(e.fallbackText=n.text),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=ue(t.agentFlowExecutedData)),e.sources=le(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=fe(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?_e(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=L(U(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function _e(s){try{return JSON.parse(s)}catch{return null}}var ge="cuttlely-chat";function j(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new N(s,e);return s.__cuttlelyChat=t,t}function D(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function me(s){if(typeof customElements>"u"||customElements.get(ge))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,a){!this.isConnected||i===a||(r==="theme"&&this.widget?this.widget.setTheme(a||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=D(this,"flow-id");r&&(this.widget=j(this,{flowId:r,apiHost:D(this,"api-host")||s,mode:D(this,"mode")==="page"?"page":"bubble",theme:D(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(ge,e)}var I=typeof document<"u"?document.currentScript:null,X=(()=>{try{return I&&I.src?new URL(I.src).origin:location.origin}catch{return location.origin}})();me(X);function be(){let s=(I==null?void 0:I.dataset)||{},e=s.flowId||s.flowid;if(!e)return;let t=s.mode==="page"?"page":"bubble",r;t==="page"&&s.target&&(r=document.querySelector(s.target)),r||(r=document.createElement("cuttlely-chat-root"),r.style.display=t==="page"?"block":"contents",t==="page"&&(r.style.height="100%"),document.body.append(r)),j(r,{flowId:e,apiHost:s.apiHost||X,mode:t,theme:s.theme||"auto",open:s.open==="true"})}var Ne={mount:(s,e)=>j(s,{apiHost:X,...e}),version:"1.4.4"};typeof window<"u"&&(window.cuttlelyChat=Ne);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",be,{once:!0}):be());})();
8
+ `),o;try{o=JSON.parse(a)}catch{return}o&&typeof o=="object"&&typeof o.event=="string"&&s(o)};return{push(r){e+=r;let i;for(;i=/\r?\n\r?\n/.exec(e);){let a=e.slice(0,i.index);e=e.slice(i.index+i[0].length),t(a)}},end(){e.trim()&&t(e),e=""}}}var J=class extends Error{constructor(e,t,r){super(t||`Request failed (${e})`),this.status=e,this.code=r||""}};async function R(s){let e="";try{let t=await s.text();try{let r=JSON.parse(t);e=typeof(r==null?void 0:r.message)=="string"?r.message:typeof(r==null?void 0:r.error)=="string"?r.error:""}catch{e=t}}catch{}return new J(s.status,String(e||"").slice(0,300))}function se({apiHost:s,flowId:e,fetchImpl:t}){let r=W(s||""),i=encodeURIComponent(e),a=t||((...o)=>globalThis.fetch(...o));return{host:r,async loadConfig(){let o=await a(`${r}/api/v1/public-chatbotConfig/${i}`,{headers:{Accept:"application/json"}});if(!o.ok)throw await R(o);let n=await o.text();try{return JSON.parse(n)}catch{return{}}},async send(o,n={},d){var b;let l=Array.isArray(o.files)?o.files:[],h={...o,streaming:!0};delete h.files;let g;if(l.length){let A=new FormData;for(let[k,S]of Object.entries(h))S!=null&&A.append(k,typeof S=="object"?JSON.stringify(S):String(S));for(let k of l)A.append("files",k,k.name);g={method:"POST",body:A,signal:d,headers:{Accept:"text/event-stream, application/json"}}}else g={method:"POST",body:JSON.stringify(h),signal:d,headers:{"Content-Type":"application/json",Accept:"text/event-stream, application/json"}};let p=await a(`${r}/api/v1/prediction/${i}`,g);if(!p.ok)throw await R(p);if((p.headers.get("content-type")||"").includes("text/event-stream")&&p.body&&typeof p.body.getReader=="function"){let A=ie(F=>{var B;return(B=n.onEvent)==null?void 0:B.call(n,F)}),k=p.body.getReader(),S=new TextDecoder;for(;;){let{value:F,done:B}=await k.read();if(B)break;A.push(S.decode(F,{stream:!0}))}A.push(S.decode()),A.end();return}let m=await p.text(),y;try{y=JSON.parse(m)}catch{y={text:m}}(b=n.onJson)==null||b.call(n,y)},async feedback({messageId:o,chatId:n,rating:d}){let l=await a(`${r}/api/v1/feedback/${i}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({chatflowid:e,chatId:n,messageId:o,rating:d})});if(!l.ok)throw await R(l)},fileUrl(o,n){let d=String(n||"").replace(/^FILE-STORAGE::/,""),l=new URLSearchParams({chatflowId:e,chatId:o||"",fileName:d});return`${r}/api/v1/get-upload-file?${l.toString()}`},async fileBlob(o,n){let d=await a(o,{headers:n?{"x-cuttlely-session-token":n}:{}});if(!d.ok)throw await R(d);return d.blob()}}}function $(s,e){let t=s==null?void 0:s.status;return t===401?{kind:"private",message:"This chat is private or needs a key."}:t===403?{kind:"origin",message:"This chat is not available on this site."}:t===404?{kind:"missing",message:"This chat could not be found."}:t===429?{kind:"busy",message:"Too many messages. Wait a moment and try again."}:(s==null?void 0:s.name)==="TypeError"||t===0?{kind:"offline",message:"Could not reach the chat. Check your connection and try again."}:{kind:"error",message:e||"Something went wrong. Try again."}}var Me={titleBackgroundColor:["#3b81f6"],titleTextColor:["#ffffff"],backgroundColor:["#ffffff"],poweredByTextColor:["#303235"],botBackground:["#f7f8ff"],botText:["#303235"],userBackground:["#3b81f6"],userText:["#ffffff"],inputBackground:["#ffffff"],inputText:["#303235"],sendButton:["#3b81f6"]},$e=/^(#[0-9a-f]{3,8}|rgba?\(\s*[\d.]+%?\s*,\s*[\d.]+%?\s*,\s*[\d.]+%?\s*(,\s*[\d.]+%?\s*)?\)|hsla?\(\s*[\d.]+(deg)?\s*,\s*[\d.]+%\s*,\s*[\d.]+%\s*(,\s*[\d.]+%?\s*)?\))$/i;function T(s,e){var r;if(typeof s!="string")return"";let t=s.trim();return!$e.test(t)||e&&((r=Me[e])!=null&&r.includes(t.toLowerCase()))?"":t}function E(s,e=2e3){return typeof s=="string"?s.trim().slice(0,e):""}function ae(s){return!s||typeof s!="object"?[]:(Array.isArray(s)?s:Object.keys(s).map(t=>s[t])).map(t=>typeof t=="string"?t:t==null?void 0:t.prompt).map(t=>E(t,300)).filter(Boolean).slice(0,6)}function Le(s){if(!Array.isArray(s))return{types:[],maxMB:0};let e=new Set,t=0;for(let r of s){for(let a of Array.isArray(r==null?void 0:r.fileTypes)?r.fileTypes:[])typeof a=="string"&&e.add(a);let i=Number(r==null?void 0:r.maxUploadSize);Number.isFinite(i)&&i>t&&(t=i)}return{types:[...e],maxMB:t||5}}function H(s,e={}){var h,g;let t=s&&typeof s=="object"?s:{},r=t.botMessage&&typeof t.botMessage=="object"?t.botMessage:{},i=t.userMessage&&typeof t.userMessage=="object"?t.userMessage:{},a=t.textInput&&typeof t.textInput=="object"?t.textInput:{},o=t.uploads&&typeof t.uploads=="object"?t.uploads:{},n=Le(o.imgUploadSizeAndTypes),d=Number(t.fontSize),l={title:E(t.title,80),avatar:w(E(t.titleAvatarSrc),{image:!0})||"",botAvatar:r.showAvatar&&w(E(r.avatarSrc),{image:!0})||"",welcome:E(t.welcomeMessage),errorMessage:E(t.errorMessage,300),placeholder:E(a.placeholder,120),starterPrompts:ae(t.starterPrompts),feedback:!!((h=t.chatFeedback)!=null&&h.status),followUps:!!((g=t.followUpPrompts)!=null&&g.status),newSessionEachVisit:!!t.generateNewSession,imageUpload:o.isImageUploadAllowed&&n.types.length?n:null,fontSize:Number.isFinite(d)&&d>=12&&d<=22?d:0,colors:{headerBg:T(t.titleBackgroundColor,"titleBackgroundColor"),headerText:T(t.titleTextColor,"titleTextColor"),background:T(t.backgroundColor,"backgroundColor"),botBg:T(r.backgroundColor,"botBackground"),botText:T(r.textColor,"botText"),userBg:T(i.backgroundColor,"userBackground"),userText:T(i.textColor,"userText"),inputBg:T(a.backgroundColor,"inputBackground"),inputText:T(a.textColor,"inputText"),accent:T(a.sendButtonColor,"sendButton")}};for(let[p,u]of Object.entries(e||{}))if(!(u==null||u===""))if(p==="colors"&&typeof u=="object")for(let[m,y]of Object.entries(u)){let b=T(y);b&&m in l.colors&&(l.colors[m]=b)}else p==="starterPrompts"?l.starterPrompts=ae(u):p==="avatar"?l.avatar=w(E(u),{image:!0})||l.avatar:typeof l[p]=="string"?l[p]=E(u):typeof l[p]=="boolean"&&(l[p]=!!u);return l}function ne(s){return Object.entries({headerBg:"--dc-header-bg",headerText:"--dc-header-fg",background:"--dc-bg",botBg:"--dc-bot-bg",botText:"--dc-bot-fg",userBg:"--dc-user-bg",userText:"--dc-user-fg",inputBg:"--dc-input-bg",inputText:"--dc-input-fg",accent:"--dc-accent"}).map(([t,r])=>T(s==null?void 0:s[t])?`${r}:${s[t]};`:"").join("")}var x=(s,e="")=>`<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"${e}>${s}</svg>`,f={chat:x('<path d="M5 5.5h14a1.5 1.5 0 0 1 1.5 1.5v8.5A1.5 1.5 0 0 1 19 17H10l-4.5 3.5V17H5a1.5 1.5 0 0 1-1.5-1.5V7A1.5 1.5 0 0 1 5 5.5z"/><path d="M8 10h8M8 13h5"/>'),close:x('<path d="M6 6l12 12M18 6L6 18"/>'),send:x('<path d="M12 19V5M6 11l6-6 6 6"/>'),stop:x('<rect x="7" y="7" width="10" height="10" rx="2" fill="currentColor" stroke="none"/>'),copy:x('<rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/>'),check:x('<path d="M5 12.5l4.5 4.5L19 7.5"/>'),up:x('<path d="M8 11v8.5H5.5A1.5 1.5 0 0 1 4 18v-5.5A1.5 1.5 0 0 1 5.5 11H8zm0 0l3.6-6.3a1.6 1.6 0 0 1 3 .9L14 9.5h4.6a1.8 1.8 0 0 1 1.8 2.1l-1.1 6.2a2 2 0 0 1-2 1.7H8"/>'),down:x('<path d="M16 13V4.5h2.5A1.5 1.5 0 0 1 20 6v5.5a1.5 1.5 0 0 1-1.5 1.5H16zm0 0l-3.6 6.3a1.6 1.6 0 0 1-3-.9l.6-3.9H5.4a1.8 1.8 0 0 1-1.8-2.1l1.1-6.2a2 2 0 0 1 2-1.7H16"/>'),attach:x('<path d="M19.5 11.5l-7.3 7.3a4.6 4.6 0 0 1-6.5-6.5l7.6-7.6a3 3 0 0 1 4.3 4.3l-7.6 7.6a1.5 1.5 0 0 1-2.1-2.1l7-7"/>'),refresh:x('<path d="M19.5 12a7.5 7.5 0 1 1-2.2-5.3"/><path d="M19.5 4.5v4h-4"/>'),lock:x('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V8a4 4 0 0 1 8 0v2.5"/>'),alert:x('<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5v5.5M12 16.2v.3"/>'),retry:x('<path d="M4.5 12a7.5 7.5 0 0 1 12.8-5.3L19.5 9"/><path d="M19.5 4.5V9H15"/><path d="M19.5 12a7.5 7.5 0 0 1-12.8 5.3L4.5 15"/><path d="M4.5 19.5V15H9"/>'),spark:x('<path d="M12 3.5l1.9 5.1 5.1 1.9-5.1 1.9L12 17.5l-1.9-5.1L5 10.5l5.1-1.9z"/><path d="M18.5 16v4M16.5 18h4"/>'),doc:x('<path d="M7 3.5h7l4.5 4.5v11A1.5 1.5 0 0 1 17 20.5H7A1.5 1.5 0 0 1 5.5 19V5A1.5 1.5 0 0 1 7 3.5z"/><path d="M13.5 3.5V8.5h5"/>'),image:x('<rect x="3.5" y="5" width="17" height="14" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="M20.5 16l-5-5L6 19"/>')},O='<svg viewBox="0 0 1000 1000" width="28" height="28" aria-hidden="true" focusable="false"><defs><linearGradient id="dc-cw" x1="60" x2="1060" y1="420" y2="820" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#6534EE"/><stop offset=".35" stop-color="#5D47F4"/><stop offset=".62" stop-color="#5872FA"/><stop offset=".85" stop-color="#55A0FC"/><stop offset="1" stop-color="#5EC2FD"/></linearGradient></defs><g fill="url(#dc-cw)" transform="translate(60 100.75)scale(.7985)"><path d="M612 1c-48.2 5.2-120.3 29.7-169 57.3-62.2 35.5-113.6 90-154.8 164.4a461 461 0 0 0-50 157c-1.1 11.3-2.5 12.3-21.5 16A329 329 0 0 0 95.9 451c-26.7 20-53.4 52-71.3 85.3C12 559.7-4 609.3.9 609.3c1.7 0 4-3.3 14.7-19.2 38.7-58.3 112.6-97.6 195.2-104 47.4-3.6 113 13.3 162.7 41.7a746 746 0 0 1 127.3 92.8c80.3 71.6 131.4 102.2 191.8 114.8 19.8 4.2 47.7 4.8 64 1.4 36.5-7.8 77.9-30.2 95.7-51.6 20-24.2 22.8-45.6 9.4-73-16.3-33.6-56.3-51.4-83.9-37.4-2.5 1.2-10.5 6.2-17.9 11-50.2 32.9-89.5 40.9-144.4 29.2-44-9.4-77.6-26.3-105.5-53.6-36.8-35.6-48-57.1-56-107-6.5-42.3-.8-79.2 18.6-118.3 21.6-43.6 48.2-72 84.6-90.4C594 227.2 624.5 220 659.9 221c37.6 1.2 65.7 10.6 102.6 34.4 27.2 17.5 38.2 21 62.2 20a82 82 0 0 0 38.8-9.6c17.6-8.7 33.5-23 44.5-39.3a111 111 0 0 0 15.4-83.8 158 158 0 0 0-62.9-86.9c-37.4-24.6-96.7-45.5-149.7-52.7C690 .4 629.8-1 611.9 1M190.5 550.5A258 258 0 0 0 98 588.1c-12.8 8.7-39 34.5-48.4 47.8A196 196 0 0 0 18.4 706c-3.3 13-3.5 15.2-3.5 38.9 0 27.6 1.2 34.3 8.8 53A161 161 0 0 0 44 831.7c6.8 7.5 10.2 5.8 12.3-5.7 2.7-14.4 11.6-24.8 28.6-33.4a72 72 0 0 1 37-8.2c12.7 0 14.8.3 27 4.5 36.5 12.3 58.5 31.3 101 86.9a385 385 0 0 0 48.7 51.6c39.5 32.2 105 60.9 156.8 68.4 28.5 4 68 5.5 70.4 2.5 3-3.5 2.3-4-19-16.4a478 478 0 0 1-90-67.9c-13.2-12.9-26-27.4-61.3-70-50.4-61-67-77.2-100.9-98.5-48.4-30.5-89.5-39-133.1-27.6-27 7.2-43.8 18.4-65.6 44.6-6.8 8-8 8.3-8 2.3 0-14.9 18-49.7 33.5-65a144 144 0 0 1 56.3-31.4c48-13.7 104-.7 161.4 37.4 24.4 16.3 54.7 45 83.4 79 65.8 77.7 108.4 118.5 150.8 143.6 49.2 29.4 126 48.8 175 44a304 304 0 0 0 94.5-28.6 516 516 0 0 0 72.8-47.3c34.2-27.3 84.5-84.4 113.8-129.2 23.5-36 46.3-86.8 54.7-122 4.3-17.6-.8-19.7-13.4-5.5-36.5 41.5-66.7 64.7-126.4 97-33.3 18-65 30.1-108.2 41.3-70.2 18.2-105.3 19.4-151.8 5-50-15.5-89.8-40.5-154-96.6-93-81.3-137-109.6-199.2-128-31.8-9.5-74.5-12.8-100.4-8"/><circle cx="963.32" cy="410.62" r="57.4"/></g></svg>';function U(s=""){return{harness:s,phase:"planning",specialists:[],startedAt:Date.now(),totalMs:null,failed:""}}function G(s,e,t){let r=typeof e=="string"&&e?e:"specialist",i=s.findIndex(o=>o.name===r);if(i===-1)return[...s,{name:r,status:"queued",ms:null,task:"",...t}];let a=s.slice();return a[i]={...a[i],...t},a}function L(s,e,t={}){var a,o;let r=s||U(t.harness),i={...r,harness:t.harness||r.harness};if(e==="route"&&t.phase==="done"){i.phase="working";for(let n of Array.isArray(t.steps)?t.steps:[])i.specialists=G(i.specialists,n.specialist,{task:typeof n.task=="string"?n.task:""});t.direct&&(i.phase="writing")}else if(e==="specialist"&&t.phase==="start")i.phase="working",i.specialists=G(i.specialists,t.name,{status:"running"});else if(e==="specialist"&&(t.phase==="done"||t.phase==="failed"))i.specialists=G(i.specialists,t.name,{status:t.phase==="failed"||t.status==="failed"?"failed":"done",ms:typeof t.ms=="number"?t.ms:null});else if(e==="handoff"&&t.phase==="start")i.phase="writing";else if(e==="partial"&&t.phase==="answer")i.phase="writing";else if(e==="final"){i.phase="done";let n=t.trace&&Array.isArray(t.trace.specialists)?t.trace.specialists:null;n?i.specialists=n.map(l=>({name:String(l.name||"specialist"),status:l.status==="failed"?"failed":"done",ms:typeof l.ms=="number"?l.ms:null,task:typeof l.task=="string"?l.task:""})):i.specialists=i.specialists.map(l=>l.status==="failed"?l:{...l,status:"done"});let d=((a=t.trace)==null?void 0:a.wallMs)??((o=t.timings)==null?void 0:o.totalMs);i.totalMs=typeof d=="number"?d:Date.now()-r.startedAt}else e==="error"&&(i.phase="failed",i.failed=typeof t.message=="string"?t.message:"The run stopped.");return i}function Y(s){if(typeof s!="number"||!Number.isFinite(s))return"";if(s<1e3)return`${Math.max(1,Math.round(s))} ms`;let e=s/1e3;return e<60?`${e.toFixed(1)} s`:`${Math.floor(e/60)} min ${Math.round(e%60)} s`}var Be={A:["href","target","rel"],BLOCKQUOTE:[],BR:[],BUTTON:["type","class","data-copy-code","aria-label"],CODE:[],DEL:[],DIV:["class"],EM:[],H1:[],H2:[],H3:[],H4:[],H5:[],H6:[],HR:[],IMG:["src","alt","loading"],LI:[],OL:["start"],P:[],PRE:[],SPAN:["class","aria-hidden"],STRONG:[],TABLE:[],TBODY:[],TD:["style"],TH:["style"],THEAD:[],TR:[],UL:[]},ze=/^text-align:(left|right|center)$/;function oe(s){let e=s.ownerDocument.createTreeWalker(s,1),t=[],r=e.nextNode();for(;r;){let i=Be[r.tagName];if(!i)t.push(r);else{for(let a of Array.from(r.attributes)){let o=a.name.toLowerCase(),n=i.includes(o);n&&(o==="href"||o==="src")&&(n=w(a.value,{image:o==="src"})!==null),n&&o==="style"&&(n=ze.test(a.value)),n&&o==="target"&&(n=a.value==="_blank"),n||r.removeAttribute(a.name)}r.tagName==="A"&&r.setAttribute("rel","noopener noreferrer nofollow")}r=e.nextNode()}for(let i of t)i.replaceWith(s.ownerDocument.createTextNode(i.textContent||""));return s}var ce=':host{all:initial;display:block}:host([mode="page"]){height:100%}*{box-sizing:border-box}.dc{--dc-font: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;--dc-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;--dc-bg: #ffffff;--dc-surface: #f5f6fc;--dc-surface-2: #eceef8;--dc-border: #e1e4f0;--dc-fg: #11142e;--dc-muted: #515874;--dc-accent: #6a3df2;--dc-accent-fg: #ffffff;--dc-accent-soft: #eeeafe;--dc-highlight: #4f8dfc;--dc-danger: #b42318;--dc-danger-soft: #fdeceb;--dc-code-bg: #0e1124;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(14, 16, 46, .35), 0 4px 14px rgba(14, 16, 46, .08);--dc-ring: 0 0 0 3px rgba(106, 61, 242, .45);font-family:var(--dc-font);font-size:var(--dc-size, 15px);line-height:1.55;color:var(--dc-fg);-webkit-font-smoothing:antialiased;text-align:left}.dc.dark{--dc-bg: #0d1020;--dc-surface: #151935;--dc-surface-2: #1e2242;--dc-border: #2a2f52;--dc-fg: #e8eaf6;--dc-muted: #a5acc9;--dc-accent: #a08cff;--dc-accent-fg: #130c36;--dc-accent-soft: #241e4c;--dc-highlight: #6fb6fd;--dc-ring: 0 0 0 3px rgba(160, 140, 255, .55);--dc-danger: #ff9a8c;--dc-danger-soft: #3a1f1c;--dc-code-bg: #080a18;--dc-code-fg: #e6e9f6;--dc-shadow: 0 24px 60px -18px rgba(0, 0, 0, .7), 0 4px 14px rgba(0, 0, 0, .35)}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,textarea:focus-visible,a:focus-visible,summary:focus-visible{outline:none;box-shadow:var(--dc-ring)}button:disabled{cursor:default;opacity:.5}.dc-window{display:flex;flex-direction:column;background:var(--dc-bg);color:var(--dc-fg);overflow:hidden;min-height:0}.dc-page{height:100%;min-height:320px}.dc-page .dc-window{height:100%;position:relative}.dc-launcher{position:fixed;right:20px;bottom:20px;z-index:2147483000;width:56px;height:56px;border-radius:18px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;box-shadow:var(--dc-shadow);transition:transform .18s ease,border-radius .18s ease}.dc-launcher:hover{transform:translateY(-2px)}.dc-launcher svg{width:26px;height:26px}.dc-launcher[aria-expanded=true]{border-radius:50%}.dc-panel{position:fixed;right:20px;bottom:88px;z-index:2147483000;width:min(410px,calc(100vw - 40px));height:min(660px,calc(100vh - 120px));border-radius:20px;border:1px solid var(--dc-border);box-shadow:var(--dc-shadow);transform-origin:bottom right;animation:dc-pop .2s ease-out}.dc-panel[hidden]{display:none}@keyframes dc-pop{0%{opacity:0;transform:translateY(8px) scale(.98)}to{opacity:1;transform:none}}.dc-header{display:flex;align-items:center;gap:10px;padding:12px 14px 12px 16px;background:var(--dc-header-bg, var(--dc-bg));color:var(--dc-header-fg, var(--dc-fg));border-bottom:1px solid var(--dc-border);flex:none}.dc-page .dc-header{padding:14px 20px}.dc-brand{width:34px;height:34px;border-radius:10px;display:grid;place-items:center;flex:none;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-brand{color:var(--dc-fg)}.dc-brand img{width:100%;height:100%;object-fit:cover}.dc-titles{min-width:0;flex:1}.dc-title{font-weight:650;font-size:1em;letter-spacing:-.01em;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.dc-status{font-size:.8em;color:var(--dc-header-fg, var(--dc-muted));opacity:.85;display:flex;align-items:center;gap:6px}.dc-dot{width:7px;height:7px;border-radius:50%;background:#2f9e6b;flex:none}.dc-busy .dc-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-off .dc-dot{background:var(--dc-muted)}@keyframes dc-pulse{50%{opacity:.35}}.dc-icon-btn{width:34px;height:34px;display:grid;place-items:center;border-radius:10px;border:0;background:transparent;color:inherit;opacity:.8;flex:none}.dc-icon-btn:hover{background:color-mix(in srgb,currentColor 10%,transparent);opacity:1}.dc-scroll{flex:1;overflow-y:auto;overscroll-behavior:contain;scroll-behavior:smooth;background:var(--dc-bg)}.dc-thread{padding:18px 16px 8px;display:flex;flex-direction:column;gap:18px;max-width:780px;margin:0 auto}.dc-page .dc-thread{padding:28px 24px 12px}.dc-welcome{display:flex;flex-direction:column;align-items:flex-start;gap:10px;padding:8px 2px 4px}.dc-page .dc-welcome{padding-top:6vh}.dc-welcome-mark{width:44px;height:44px;border-radius:14px;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden}.dc.dark .dc-welcome-mark{color:var(--dc-fg)}.dc-welcome-mark img{width:100%;height:100%;object-fit:cover}.dc-welcome h2{margin:6px 0 0;font-size:1.35em;line-height:1.25;letter-spacing:-.02em;font-weight:700}.dc-welcome p{margin:0;color:var(--dc-muted);white-space:pre-line}.dc-prompts{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:8px;width:100%;margin-top:8px}.dc-prompts>div{display:flex}.dc-prompt{width:100%;text-align:left;padding:11px 13px;border-radius:12px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.92em;line-height:1.4;transition:border-color .15s ease,background .15s ease}.dc-prompt:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-msg{display:flex;gap:10px;align-items:flex-start;animation:dc-in .18s ease-out}@keyframes dc-in{0%{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}.dc-msg.user{justify-content:flex-end}.dc-avatar{width:28px;height:28px;border-radius:9px;flex:none;display:grid;place-items:center;background:var(--dc-accent-soft);color:var(--dc-accent);overflow:hidden;margin-top:2px}.dc.dark .dc-avatar{color:var(--dc-fg)}.dc-avatar svg{width:20px;height:20px}.dc-avatar img{width:100%;height:100%;object-fit:cover}.dc-body{min-width:0;flex:1}.dc-msg.user .dc-body{flex:0 1 auto;max-width:85%;display:flex;flex-direction:column;align-items:flex-end;gap:6px}.dc-user-bubble{background:var(--dc-user-bg, var(--dc-accent));color:var(--dc-user-fg, var(--dc-accent-fg));padding:9px 14px;border-radius:18px 18px 6px;white-space:pre-wrap;overflow-wrap:anywhere}.dc-bot-bubble{color:var(--dc-bot-fg, var(--dc-fg))}.dc.has-bot-bg .dc-bot-bubble{background:var(--dc-bot-bg);padding:10px 14px;border-radius:6px 18px 18px}.dc-thumbs{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}.dc-thumbs img{width:84px;height:84px;object-fit:cover;border-radius:12px;border:1px solid var(--dc-border)}.dc-file-chip{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border-radius:10px;background:var(--dc-surface);font-size:.85em}.dc-md{overflow-wrap:anywhere}.dc-md>:first-child{margin-top:0}.dc-md>:last-child{margin-bottom:0}.dc-md p{margin:0 0 .7em}.dc-md h1,.dc-md h2,.dc-md h3,.dc-md h4,.dc-md h5,.dc-md h6{margin:1em 0 .45em;line-height:1.3;letter-spacing:-.01em}.dc-md h1{font-size:1.3em}.dc-md h2{font-size:1.18em}.dc-md h3{font-size:1.06em}.dc-md h4,.dc-md h5,.dc-md h6{font-size:1em}.dc-md ul,.dc-md ol{margin:0 0 .7em;padding-left:1.4em}.dc-md li{margin:.2em 0}.dc-md li::marker{color:var(--dc-muted)}.dc-md a{color:inherit;text-decoration:underline;text-decoration-color:var(--dc-highlight);text-decoration-thickness:2px;text-underline-offset:2px}.dc-md blockquote{margin:0 0 .7em;padding:2px 0 2px 12px;border-left:3px solid var(--dc-highlight);color:var(--dc-muted)}.dc-md hr{border:0;border-top:1px solid var(--dc-border);margin:1em 0}.dc-md code{font-family:var(--dc-mono);font-size:.88em;background:var(--dc-surface-2);padding:.1em .38em;border-radius:6px}.dc-md img{max-width:100%;border-radius:12px;display:block;margin:.4em 0}.md-code{margin:0 0 .8em;border-radius:12px;overflow:hidden;background:var(--dc-code-bg);color:var(--dc-code-fg)}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:6px 8px 6px 14px;font-size:.75em;color:#b5c4ba;font-family:var(--dc-mono);border-bottom:1px solid rgba(255,255,255,.08)}.md-copy{border:0;background:#ffffff14;color:#e4ece6;border-radius:7px;padding:3px 9px;font-size:1em}.md-copy:hover{background:#ffffff29}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto}.md-code code{background:none;padding:0;color:inherit;font-size:.85em;line-height:1.6;white-space:pre}.md-table{overflow-x:auto;margin:0 0 .8em;border:1px solid var(--dc-border);border-radius:12px}.md-table table{border-collapse:collapse;width:100%;font-size:.9em}.md-table th,.md-table td{padding:8px 12px;border-bottom:1px solid var(--dc-border);text-align:left;vertical-align:top}.md-table th{background:var(--dc-surface);font-weight:600;white-space:nowrap}.md-table tr:last-child td{border-bottom:0}.md-task{color:var(--dc-muted)}.dc-artifacts{display:grid;gap:10px;margin-top:10px}.dc-figure{margin:0;border:1px solid var(--dc-border);border-radius:14px;overflow:hidden;background:#fff}.dc-figure img{display:block;width:100%;height:auto}.dc-figure-missing{padding:14px;font-size:.88em;color:var(--dc-muted);background:var(--dc-surface);display:flex;gap:8px;align-items:center}.dc-file{display:flex;gap:10px;align-items:center;padding:10px 12px;border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);color:inherit;text-decoration:none}.dc-file:hover,.dc-file:focus-visible{border-color:var(--dc-accent, currentColor)}.dc-file-type{font-size:.72em;font-weight:700;letter-spacing:.04em;padding:3px 6px;border-radius:6px;background:var(--dc-border)}.dc-file-name{font-size:.9em;overflow-wrap:anywhere}.dc-figure .dc-image-download{border:0;border-top:1px solid var(--dc-border);border-radius:0;padding:8px 12px}.dc-html-frame{width:100%;min-height:220px;border:1px solid var(--dc-border);border-radius:14px;background:#fff}.dc-sources{margin-top:10px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.dc-sources-label{font-size:.78em;font-weight:600;color:var(--dc-muted);text-transform:uppercase;letter-spacing:.04em;margin-right:2px}.dc-source{display:inline-flex;align-items:center;gap:6px;max-width:240px;padding:4px 10px 4px 4px;border-radius:999px;border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);font-size:.82em;text-decoration:none}.dc-source:hover{border-color:var(--dc-accent)}.dc-source b{display:grid;place-items:center;min-width:20px;height:20px;border-radius:999px;background:var(--dc-accent-soft);color:var(--dc-fg);font-size:.85em;font-weight:650}.dc-source span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dc-source-preview{margin-top:8px;padding:10px 12px;border-radius:12px;background:var(--dc-surface);font-size:.86em;color:var(--dc-fg);white-space:pre-wrap;max-height:180px;overflow:auto}.dc-followups{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}.dc-chip{border:1px solid var(--dc-border);background:var(--dc-bg);color:var(--dc-fg);border-radius:999px;padding:6px 12px;font-size:.86em}.dc-chip:hover{border-color:var(--dc-accent);background:var(--dc-accent-soft)}.dc-chip.primary{background:var(--dc-accent);color:var(--dc-accent-fg);border-color:var(--dc-accent)}.dc-tools{display:flex;gap:2px;margin-top:6px;margin-left:-6px}.dc-tool{width:30px;height:30px;border:0;border-radius:8px;background:transparent;color:var(--dc-muted);display:grid;place-items:center}.dc-tool svg{width:17px;height:17px}.dc-tool:hover{background:var(--dc-surface);color:var(--dc-fg)}.dc-tool[aria-pressed=true]{color:var(--dc-accent);background:var(--dc-accent-soft)}.dc.dark .dc-tool[aria-pressed=true]{color:var(--dc-fg)}.dc-run{border:1px solid var(--dc-border);border-radius:14px;background:var(--dc-surface);margin-bottom:10px;overflow:hidden}.dc-run summary{list-style:none;display:flex;align-items:center;gap:10px;padding:9px 12px;cursor:pointer;font-size:.88em}.dc-run summary::-webkit-details-marker{display:none}.dc-run-icon{width:26px;height:26px;border-radius:8px;display:grid;place-items:center;background:var(--dc-bg);color:var(--dc-highlight);flex:none}.dc-run-icon svg{width:16px;height:16px}.dc-run-title{font-weight:600}.dc-run-meta{color:var(--dc-muted);margin-left:auto;white-space:nowrap;font-variant-numeric:tabular-nums}.dc-run-chev{transition:transform .15s ease;color:var(--dc-muted)}.dc-run[open] .dc-run-chev{transform:rotate(90deg)}.dc-run ol{list-style:none;margin:0;padding:0 12px 10px 48px;display:grid;gap:6px;font-size:.86em}.dc-run li{display:flex;gap:8px;align-items:baseline}.dc-run li .dc-step-dot{width:8px;height:8px;border-radius:50%;background:var(--dc-border);flex:none;transform:translateY(-1px)}.dc-run li.running .dc-step-dot{background:var(--dc-highlight);animation:dc-pulse 1.2s ease-in-out infinite}.dc-run li.done .dc-step-dot{background:#2f9e6b}.dc-run li.failed .dc-step-dot{background:var(--dc-danger)}.dc-run li em{font-style:normal;color:var(--dc-muted);margin-left:auto;font-variant-numeric:tabular-nums}.dc-typing{display:inline-flex;gap:4px;padding:10px 2px}.dc-typing i{width:7px;height:7px;border-radius:50%;background:var(--dc-muted);opacity:.4;animation:dc-bounce 1.1s ease-in-out infinite}.dc-typing i:nth-child(2){animation-delay:.15s}.dc-typing i:nth-child(3){animation-delay:.3s}@keyframes dc-bounce{0%,80%,to{opacity:.35;transform:none}40%{opacity:1;transform:translateY(-3px)}}.dc-caret:after{content:"";display:inline-block;width:.5em;height:1em;margin-left:2px;vertical-align:-.15em;background:var(--dc-highlight);border-radius:2px;animation:dc-pulse 1s steps(2) infinite}.dc-error{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border-radius:12px;background:var(--dc-danger-soft);color:var(--dc-fg);font-size:.92em}.dc-error svg{color:var(--dc-danger);flex:none;width:18px;height:18px;margin-top:2px}.dc-error .dc-chip{margin-top:8px}.dc-notice{flex:1;display:grid;place-items:center;padding:32px 24px;text-align:center}.dc-notice-card{max-width:340px;display:grid;justify-items:center;gap:10px}.dc-notice-icon{width:52px;height:52px;border-radius:16px;display:grid;place-items:center;background:var(--dc-surface);color:var(--dc-fg)}.dc-notice-icon svg{width:26px;height:26px}.dc-notice h2{margin:4px 0 0;font-size:1.15em}.dc-notice p{margin:0;color:var(--dc-muted);font-size:.93em}.dc-loading{flex:1;display:grid;place-items:center;color:var(--dc-muted)}.dc-composer{flex:none;padding:10px 12px 12px;background:var(--dc-bg)}.dc-page .dc-composer{padding:12px 24px 18px}.dc-compose-inner{max-width:780px;margin:0 auto}.dc-box{display:flex;align-items:flex-end;gap:6px;padding:6px;border-radius:16px;border:1px solid var(--dc-border);background:var(--dc-input-bg, var(--dc-surface));color:var(--dc-input-fg, var(--dc-fg));transition:border-color .15s ease,box-shadow .15s ease}.dc-box:focus-within{border-color:var(--dc-accent);box-shadow:0 0 0 3px color-mix(in srgb,var(--dc-accent) 18%,transparent)}.dc-box textarea{flex:1;min-width:0;resize:none;border:0;outline:none;background:transparent;color:inherit;font:inherit;line-height:1.45;padding:8px 6px;max-height:160px;min-height:38px}.dc-box textarea::placeholder{color:var(--dc-muted);opacity:1}.dc-box textarea:focus-visible{box-shadow:none}.dc-send{width:38px;height:38px;border-radius:12px;border:0;background:var(--dc-accent);color:var(--dc-accent-fg);display:grid;place-items:center;flex:none}.dc-send:disabled{opacity:.35}.dc-attach{width:38px;height:38px;border-radius:12px;border:0;background:transparent;color:var(--dc-muted);display:grid;place-items:center;flex:none}.dc-attach:hover{color:var(--dc-fg);background:var(--dc-surface-2)}.dc-pending{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:8px}.dc-pending-item{position:relative}.dc-pending-item img{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--dc-border);display:block}.dc-pending-item button{position:absolute;top:-6px;right:-6px;width:22px;height:22px;border-radius:50%;border:0;background:var(--dc-fg);color:var(--dc-bg);display:grid;place-items:center;padding:0}.dc-pending-item button svg{width:12px;height:12px}.dc-foot{text-align:center;font-size:.72em;color:var(--dc-muted);margin-top:8px}.dc-foot a{color:inherit;text-decoration:none;font-weight:600}.dc-foot a:hover{text-decoration:underline}.dc-drop{position:absolute;inset:0;display:grid;place-items:center;background:color-mix(in srgb,var(--dc-bg) 88%,transparent);border:2px dashed var(--dc-accent);border-radius:inherit;font-weight:600;z-index:2}@media(max-width:520px){.dc-panel{right:0;bottom:0;width:100vw;height:100%;max-height:100dvh;border-radius:0;border:0}.dc-panel:not([hidden])~.dc-launcher,.dc-launcher.is-open{display:none}.dc-page .dc-thread{padding:18px 14px 8px}.dc-page .dc-composer{padding:10px 12px 12px}.dc-page .dc-header{padding:12px 14px}.dc-prompts{grid-template-columns:1fr}}@media(prefers-reduced-motion:reduce){.dc *,.dc *:before,.dc *:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}}';var Re="cuttlely-chat:v1:",He=60,Oe="https://github.com/cuttlely/cuttlely",Ue=0,_=s=>`${s}-${Date.now().toString(36)}-${(Ue++).toString(36)}`;function c(s,e={},t=[]){let r=document.createElement(s);for(let[i,a]of Object.entries(e||{}))a==null||a===!1||(i==="class"?r.className=a:i==="text"?r.textContent=a:i==="html"?r.innerHTML=a:i.startsWith("on")&&typeof a=="function"?r.addEventListener(i.slice(2),a):r.setAttribute(i,a===!0?"":String(a)));for(let i of[].concat(t))i==null||i===!1||r.append(typeof i=="string"?document.createTextNode(i):i);return r}function de(s,e){let t=document.createElement("template");t.innerHTML=V(s,{base:e}),oe(t.content);let r=c("div",{class:"dc-md"});return r.append(t.content),r}function le(s){let e=Array.isArray(s)?s:[],t=new Set,r=[];for(let i of e){if(!i||typeof i!="object")continue;let a=i.metadata&&typeof i.metadata=="object"?i.metadata:{},o=w(typeof a.url=="string"?a.url:typeof a.source=="string"?a.source:""),n=a.title||a.source||a.url||a.name||i.title||"",d=String(n||"Source").split(/[\\/]/).filter(Boolean).pop().slice(0,120),l=`${o||""}|${d}`;if(!t.has(l)&&(t.add(l),r.push({title:d||"Source",url:o,excerpt:typeof i.pageContent=="string"?i.pageContent.slice(0,600):""}),r.length>=8))break}return r}function K(s){return(Array.isArray(s)?s:[]).filter(t=>t&&typeof t=="object"&&typeof t.data=="string").map(t=>({type:String(t.type||""),data:t.data,...typeof t.name=="string"&&t.name?{name:t.name.slice(0,200)}:{}})).slice(0,8)}var pe=["pdf","docx","xlsx","pptx","csv"];function he(s){let e=typeof(s==null?void 0:s.name)=="string"?s.name:"",t=String((s==null?void 0:s.data)||"").replace(/^FILE-STORAGE::/,"").replace(/^harness_[A-Za-z0-9_-]*?_\d+_\d+_/,"");return(e||t).split("/").pop().replace(/[^A-Za-z0-9._-]/g,"_")||`file.${(s==null?void 0:s.type)||"bin"}`}function fe(s){let e=s;for(let t=0;t<2&&typeof e=="string";t++)try{e=JSON.parse(e)}catch{return[]}return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim()).map(t=>t.trim().slice(0,200)).slice(0,4):[]}function ue(s){var e,t,r;if(!Array.isArray(s))return"";for(let i=s.length-1;i>=0;i--){let a=(r=(t=(e=s[i])==null?void 0:e.data)==null?void 0:t.output)==null?void 0:r.content;if(typeof a=="string"&&a.trim())return a}return""}var N=class{constructor(e,t={}){this.host=e,this.options={mode:"bubble",theme:"auto",storage:!0,...t},this.mode=this.options.mode==="page"?"page":"bubble",this.api=se({apiHost:this.options.apiHost||location.origin,flowId:this.options.flowId,fetchImpl:this.options.fetch}),this.base=this.api.host,this.config=H({},this.options.config),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.busy=!1,this.state="loading",this.blocked=null,this.isOpen=this.mode==="page"||!!this.options.open,this.nodes=new Map,this.frame=0,this.root=e.shadowRoot||e.attachShadow({mode:"open"}),this.panelId=_("dc-panel"),this.build(),this.applyTheme(),this.options.blocked?this.block({kind:this.options.blocked,message:$({status:this.blockedStatus(this.options.blocked)}).message}):this.load()}blockedStatus(e){return{private:401,origin:403,missing:404}[e]||500}build(){this.root.innerHTML="";let e=c("style",{text:ce});this.wrap=c("div",{class:`dc ${this.mode==="page"?"dc-page":"dc-bubble"}`}),this.live=c("div",{class:"sr-only",role:"status","aria-live":"polite"}),this.window=c("section",{class:`dc-window${this.mode==="bubble"?" dc-panel":""}`,id:this.panelId,role:this.mode==="bubble"?"dialog":"region","aria-label":"Chat"}),this.window.addEventListener("keydown",t=>{t.key==="Escape"&&this.mode==="bubble"&&(t.stopPropagation(),this.close(!0))}),this.wrap.append(this.window,this.live),this.mode==="bubble"&&(this.launcher=c("button",{class:"dc-launcher",type:"button","aria-label":"Open chat","aria-controls":this.panelId,"aria-expanded":"false",html:f.chat,onclick:()=>this.toggle()}),this.wrap.append(this.launcher),this.window.hidden=!this.isOpen),this.root.append(e,this.wrap),this.renderShell()}applyTheme(){var r,i,a,o;let e=this.options.theme,t=n=>this.wrap.classList.toggle("dark",n);if((i=(r=this.media)==null?void 0:r.removeEventListener)==null||i.call(r,"change",this.onMedia),e==="dark"||e==="light")return t(e==="dark");this.media=typeof matchMedia=="function"?matchMedia("(prefers-color-scheme: dark)"):null,this.onMedia=()=>{var n;return t(!!((n=this.media)!=null&&n.matches))},this.onMedia(),(o=(a=this.media)==null?void 0:a.addEventListener)==null||o.call(a,"change",this.onMedia)}setTheme(e){this.options.theme=e,this.applyTheme()}applyConfigStyles(){let e=ne(this.config.colors),t=this.config.fontSize?`--dc-size:${this.config.fontSize}px;`:"";this.wrap.setAttribute("style",e+t),this.wrap.classList.toggle("has-bot-bg",!!this.config.colors.botBg),this.window.setAttribute("aria-label",this.config.title||"Chat")}async load(){var e,t;this.state="loading",this.renderShell();try{let r=await this.api.loadConfig();this.config=H(r,this.options.config),this.state="ready",this.restore()}catch(r){let i=$(r);this.block(i.kind==="error"?{kind:"missing",message:"This chat could not be found."}:i);return}this.applyConfigStyles(),this.renderShell(),(t=(e=this.options).onReady)==null||t.call(e,this)}block(e){this.state="blocked",this.blocked=e,this.abort(),this.renderShell(),this.announce(e.message)}storageKey(){return`${Re}${this.base}:${this.options.flowId}`}restore(){if(!(!this.options.storage||this.config.newSessionEachVisit))try{let e=JSON.parse(localStorage.getItem(this.storageKey())||"null");if(!e||typeof e!="object")return;this.chatId=typeof e.chatId=="string"?e.chatId:"",this.sessionToken=typeof e.sessionToken=="string"?e.sessionToken:"";let t=Array.isArray(e.messages)?e.messages:[];this.messages=t.filter(r=>r&&(r.role==="user"||r.role==="bot")&&typeof r.text=="string").map(r=>({id:_("m"),role:r.role,text:r.text,images:Array.isArray(r.images)?r.images.filter(i=>w(i,{image:!0})):[],sources:Array.isArray(r.sources)?r.sources:[],artifacts:K(r.artifacts),run:r.run&&typeof r.run=="object"?r.run:null,messageId:typeof r.messageId=="string"?r.messageId:"",feedback:r.feedback==="up"||r.feedback==="down"?r.feedback:null,status:"done",rev:0}))}catch{}}save(){if(this.options.storage)try{let e=this.messages.filter(t=>t.status==="done"&&!t.error).slice(-He).map(t=>({role:t.role,text:t.text,images:(t.images||[]).filter(r=>r.length<15e4),sources:t.sources||[],artifacts:t.artifacts||[],run:t.run||null,messageId:t.messageId||"",feedback:t.feedback||null}));localStorage.setItem(this.storageKey(),JSON.stringify({chatId:this.chatId,sessionToken:this.sessionToken,messages:e}))}catch{}}reset(){this.abort(),this.messages=[],this.pending=[],this.chatId="",this.sessionToken="",this.nodes.clear();try{localStorage.removeItem(this.storageKey())}catch{}this.renderShell(),this.announce("Started a new chat"),this.focusInput()}open(){this.mode==="bubble"&&(this.isOpen=!0,this.window.hidden=!1,this.launcher.setAttribute("aria-expanded","true"),this.launcher.setAttribute("aria-label","Close chat"),this.launcher.innerHTML=f.close,this.launcher.classList.add("is-open"),this.scrollToEnd(!0),this.focusInput())}close(e){this.mode==="bubble"&&(this.isOpen=!1,this.window.hidden=!0,this.launcher.setAttribute("aria-expanded","false"),this.launcher.setAttribute("aria-label","Open chat"),this.launcher.innerHTML=f.chat,this.launcher.classList.remove("is-open"),e&&this.launcher.focus())}toggle(){this.isOpen?this.close(!0):this.open()}focusInput(){setTimeout(()=>{var e;return(e=this.input)==null?void 0:e.focus()},30)}announce(e){this.live.textContent="",setTimeout(()=>{this.live.textContent=e},50)}renderShell(){if(this.window.innerHTML="",this.nodes.clear(),this.window.append(this.renderHeader()),this.state==="loading"){this.window.append(c("div",{class:"dc-loading",role:"status"},[c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]),c("span",{class:"sr-only",text:"Loading chat"})]));return}if(this.state==="blocked"){this.window.append(this.renderNotice());return}this.scroller=c("div",{class:"dc-scroll"}),this.stick=!0,this.scroller.addEventListener("scroll",()=>{this.stick=this.nearBottom()}),this.thread=c("div",{class:"dc-thread"}),this.scroller.append(this.thread),this.window.append(this.scroller,this.renderComposer()),this.renderThread(),this.scrollToEnd(!0)}renderHeader(){let e=this.config,t=c("div",{class:"dc-brand"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready";this.statusEl=c("div",{class:this.statusClass()},[c("span",{class:"dc-dot","aria-hidden":"true"}),c("span",{text:r})]);let i=[];return this.state==="ready"&&this.messages.length&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Start a new chat",title:"New chat",html:f.refresh,onclick:()=>this.reset()})),this.mode==="bubble"&&i.push(c("button",{class:"dc-icon-btn",type:"button","aria-label":"Close chat",title:"Close",html:f.close,onclick:()=>this.close(!0)})),c("header",{class:"dc-header"},[t,c("div",{class:"dc-titles"},[c("h1",{class:"dc-title",text:e.title||"Chat"}),this.statusEl]),...i])}updateStatus(){this.statusEl&&(this.statusEl.className=this.statusClass(),this.statusEl.lastChild.textContent=this.busy?"Answering":this.state==="blocked"?"Unavailable":"Ready")}statusClass(){return`dc-status${this.busy?" dc-busy":this.state==="blocked"?" dc-off":""}`}renderNotice(){let e=this.blocked||{},t={private:["This chat is private","This chat is private or needs a key. Ask the person who shared it for a public link.",f.lock],origin:["Not available here","This chat is not available on this site.",f.lock],missing:["Chat not found","This chat could not be found. The link may be old or the chat may have been removed.",f.alert]}[e.kind]||["Chat unavailable",e.message||"Something went wrong.",f.alert];return c("div",{class:"dc-notice"},[c("div",{class:"dc-notice-card"},[c("div",{class:"dc-notice-icon",html:t[2]}),c("h2",{text:t[0]}),c("p",{text:t[1]})])])}renderWelcome(){let e=this.config,t=c("div",{class:"dc-welcome-mark"});e.avatar?t.append(c("img",{src:e.avatar,alt:""})):t.innerHTML=O;let r=e.starterPrompts.length?c("div",{class:"dc-prompts",role:"list","aria-label":"Suggested questions"},e.starterPrompts.map(i=>c("div",{role:"listitem"},[c("button",{class:"dc-prompt",type:"button",text:i,onclick:()=>this.send(i)})]))):null;return c("div",{class:"dc-welcome"},[t,c("h2",{text:e.title?`Ask ${e.title}`:"How can I help?"}),c("p",{text:e.welcome||"Ask a question to get started."}),r])}renderThread(){if(!this.thread)return;let e=[];if(!this.messages.length){this.thread.replaceChildren(this.renderWelcome()),this.nodes.clear();return}let t=this.messages[this.messages.length-1];for(let i of this.messages){let a=`${i.id}:${i.rev}:${i===t?"last":""}`,o=this.nodes.get(i.id);(!o||o.dataset.key!==a)&&(o=i.role==="user"?this.renderUser(i):this.renderBot(i,i===t),o.dataset.key=a,this.nodes.set(i.id,o)),e.push(o)}let r=Array.from(this.thread.children);(r.length!==e.length||r.some((i,a)=>i!==e[a]))&&this.thread.replaceChildren(...e)}renderUser(e){var r,i;let t=c("div",{class:"dc-body"});return(r=e.images)!=null&&r.length&&t.append(c("div",{class:"dc-thumbs"},e.images.map(a=>c("img",{src:a,alt:"Attached image"})))),(i=e.files)!=null&&i.length&&t.append(c("div",{class:"dc-thumbs"},e.files.map(a=>c("span",{class:"dc-file-chip",html:f.doc},[a])))),e.text&&t.append(c("div",{class:"dc-user-bubble",text:e.text})),c("div",{class:"dc-msg user","data-id":e.id},[c("span",{class:"sr-only",text:"You said:"}),t])}renderBot(e,t){var n,d,l;let r=this.config,i=c("div",{class:"dc-avatar"});r.botAvatar||r.avatar?i.append(c("img",{src:r.botAvatar||r.avatar,alt:""})):i.innerHTML=O;let a=c("div",{class:"dc-body"});e.run&&a.append(this.renderRun(e.run,e.status==="streaming"));let o=c("div",{class:"dc-bot-bubble"});if(e.text){let h=de(e.text,this.base);e.status==="streaming"&&h.classList.add("dc-caret"),o.append(h)}else e.status==="streaming"&&o.append(c("div",{class:"dc-typing","aria-hidden":"true"},[c("i"),c("i"),c("i")]));return o.childNodes.length&&a.append(o),(n=e.artifacts)!=null&&n.length&&a.append(this.renderArtifacts(e.artifacts)),(d=e.sources)!=null&&d.length&&a.append(this.renderSources(e.sources)),e.error&&a.append(this.renderError(e,t)),e.action&&t&&e.status==="done"&&a.append(this.renderAction(e)),e.status==="done"&&e.text&&a.append(this.renderTools(e)),t&&e.status==="done"&&((l=e.followUps)!=null&&l.length)&&!this.busy&&a.append(c("div",{class:"dc-followups",role:"group","aria-label":"Suggested follow-ups"},e.followUps.map(h=>c("button",{class:"dc-chip",type:"button",text:h,onclick:()=>this.send(h)})))),c("div",{class:"dc-msg bot","data-id":e.id},[i,c("span",{class:"sr-only",text:"Assistant said:"}),a])}renderRun(e,t){let r=e.phase==="done",i=e.specialists.length,a={planning:"Planning the work",working:"Specialists working",writing:"Writing the answer",done:"Run complete",failed:"Run stopped"}[e.phase]||"Working",o=r&&e.totalMs?`${i?`${i} specialist${i===1?"":"s"} \xB7 `:""}${Y(e.totalMs)}`:t?"Working\u2026":"",n=c("details",{class:"dc-run"});!r&&t&&(n.open=!0);let d=c("summary",{},[c("span",{class:"dc-run-icon",html:f.spark}),c("span",{class:"dc-run-title",text:a}),c("span",{class:"dc-run-meta",text:o}),c("span",{class:"dc-run-chev","aria-hidden":"true",text:"\u203A"})]);return n.append(d),i&&n.append(c("ol",{"aria-label":"Run steps"},e.specialists.map(l=>c("li",{class:l.status},[c("span",{class:"dc-step-dot","aria-hidden":"true"}),c("span",{text:l.name}),c("span",{class:"sr-only",text:`, ${l.status}`}),l.ms?c("em",{text:Y(l.ms)}):null])))),n}renderArtifacts(e){let t=c("div",{class:"dc-artifacts"});for(let r of e)if(r.type==="png"||r.type==="jpeg"||r.type==="jpg"||r.type==="gif"||r.type==="webp")t.append(this.renderImageArtifact(r));else if(pe.includes(r.type)&&r.data.startsWith("FILE-STORAGE::"))t.append(this.renderFileArtifact(r));else{if(pe.includes(r.type))continue;if(r.type==="html"){let i=c("iframe",{class:"dc-html-frame",sandbox:"",title:"Answer content",loading:"lazy"});i.srcdoc=r.data,t.append(i)}else r.data&&t.append(de(r.data,this.base))}return t}renderFileArtifact(e){return this.renderDownloadLink(e,he(e),e.type.toUpperCase())}renderDownloadLink(e,t,r,i=""){let a=!e.data.startsWith("data:"),o=()=>a?`${this.api.fileUrl(this.chatId,e.data)}&download=true`:e.data,n=c("a",{class:`dc-file${i}`,href:o(),download:t,rel:"noopener",title:`Download ${t}`},[c("span",{class:"dc-file-type",text:r}),c("span",{class:"dc-file-name",text:t})]);return n.addEventListener("click",async d=>{if(!a||!this.sessionToken||!this.chatId){n.href=o();return}d.preventDefault();try{let l=await this.api.fileBlob(o(),this.sessionToken),h=URL.createObjectURL(l);c("a",{href:h,download:t}).click(),setTimeout(()=>URL.revokeObjectURL(h),3e4)}catch{n.replaceWith(c("div",{class:"dc-figure-missing",html:f.alert},[`${t} could not be downloaded here.`]))}}),n}imageArtifactName(e){let t=e.data.startsWith("data:")&&typeof e.name!="string"?"":he(e),r=e.type==="jpeg"?"jpg":e.type;return(r==="jpg"?/\.jpe?g$/i:new RegExp(`\\.${r}$`,"i")).test(t)?t:`${t.replace(/\.[^.]*$/,"")||"image"}.${r}`}renderImageArtifact(e){let t=e.type==="jpg"?"jpeg":e.type,r=new RegExp(`^data:image/${t};base64,[A-Za-z0-9+/]+={0,2}$`).test(e.data),i=e.data.startsWith("FILE-STORAGE::")||!/[:/\\]/.test(e.data),a=r?e.data:w(e.data,{image:!0,base:this.base}),o=a&&!e.data.startsWith("/")?a:this.api.fileUrl(this.chatId,e.data),n=c("figure",{class:"dc-figure"}),d=c("img",{src:o,alt:"Chart from the answer",loading:"lazy"});d.addEventListener("load",()=>{this.stick&&this.scrollToEnd()});let l=!1;if(d.addEventListener("error",async()=>{if(!l&&!a&&this.sessionToken&&this.chatId){l=!0;try{let h=await this.api.fileBlob(this.api.fileUrl(this.chatId,e.data),this.sessionToken);d.src=URL.createObjectURL(h);return}catch{}}d.replaceWith(c("div",{class:"dc-figure-missing",html:f.image},["This chart could not be shown here."]))}),n.append(d),i||r){let h=this.imageArtifactName(e),g=(e.type==="jpeg"?"jpg":e.type).toUpperCase();n.append(this.renderDownloadLink(e,h,g," dc-image-download"))}return n}renderSources(e){let t=c("div",{class:"dc-sources-wrap"}),r=c("div",{class:"dc-sources",role:"list","aria-label":"Sources"},[c("span",{class:"dc-sources-label","aria-hidden":"true",text:"Sources"})]),i=null;return e.forEach((a,o)=>{let n=[c("b",{text:String(o+1)}),c("span",{text:a.title})],d;a.url?d=c("a",{class:"dc-source",href:a.url,target:"_blank",rel:"noopener noreferrer nofollow",title:a.title},n):(d=c("button",{class:"dc-source",type:"button",title:a.title,"aria-expanded":"false"},n),d.addEventListener("click",()=>{let l=d.getAttribute("aria-expanded")!=="true";r.querySelectorAll("button.dc-source").forEach(h=>h.setAttribute("aria-expanded","false")),i==null||i.remove(),i=null,l&&a.excerpt&&(d.setAttribute("aria-expanded","true"),i=c("div",{class:"dc-source-preview",text:a.excerpt}),t.append(i))})),r.append(c("div",{role:"listitem",style:"display:contents"},[d]))}),t.append(r),t}renderError(e,t){let r=[c("div",{text:e.error})];return t&&e.retry&&r.push(c("button",{class:"dc-chip",type:"button",text:"Try again",onclick:()=>this.retry(e)})),c("div",{class:"dc-error",role:"alert"},[c("span",{html:f.alert}),c("div",{},r)])}renderAction(e){var r;let t=Array.isArray((r=e.action)==null?void 0:r.elements)?e.action.elements:[];return c("div",{class:"dc-followups",role:"group","aria-label":"Choose an option"},t.filter(i=>i&&typeof i.label=="string").map((i,a)=>c("button",{class:`dc-chip${a===0?" primary":""}`,type:"button",text:i.label,onclick:()=>this.chooseAction(e,i)})))}renderTools(e){let t=c("button",{class:"dc-tool",type:"button","aria-label":"Copy answer",title:"Copy",html:f.copy});t.addEventListener("click",()=>this.copy(e.text,t));let r=[t];if(this.config.feedback&&e.messageId)for(let[i,a,o]of[["up",f.up,"Good answer"],["down",f.down,"Bad answer"]])r.push(c("button",{class:"dc-tool",type:"button","aria-label":o,title:o,"aria-pressed":e.feedback===i?"true":"false",html:a,onclick:()=>this.rate(e,i)}));return c("div",{class:"dc-tools"},r)}renderComposer(){let e=this.config.imageUpload;this.pendingEl=c("div",{class:"dc-pending",hidden:!0}),this.input=c("textarea",{rows:"1","aria-label":"Message",placeholder:this.config.placeholder||"Ask a question\u2026",maxlength:"8000"}),this.input.addEventListener("input",()=>this.autosize()),this.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&(i.preventDefault(),this.send())});let t=[];e&&(this.fileInput=c("input",{type:"file",accept:e.types.join(","),multiple:!0,hidden:!0,tabindex:"-1","aria-hidden":"true"}),this.fileInput.addEventListener("change",()=>{this.addFiles(this.fileInput.files),this.fileInput.value=""}),t.push(this.fileInput,c("button",{class:"dc-attach",type:"button","aria-label":"Attach an image",title:"Attach an image",html:f.attach,onclick:()=>this.fileInput.click()})),this.input.addEventListener("paste",i=>{var o;let a=Array.from(((o=i.clipboardData)==null?void 0:o.files)||[]);a.length&&(i.preventDefault(),this.addFiles(a))}),this.window.addEventListener("dragover",i=>{i.preventDefault(),this.dropEl||(this.dropEl=c("div",{class:"dc-drop",text:"Drop an image to attach"}),this.window.append(this.dropEl))}),this.window.addEventListener("dragleave",i=>{i.target===this.dropEl&&this.clearDrop()}),this.window.addEventListener("drop",i=>{var a;i.preventDefault(),this.clearDrop(),this.addFiles(((a=i.dataTransfer)==null?void 0:a.files)||[])})),this.sendBtn=c("button",{class:"dc-send",type:"button"}),this.sendBtn.addEventListener("click",()=>this.busy?this.abort(!0):this.send()),t.push(this.input,this.sendBtn),this.updateSendButton();let r=c("div",{class:"dc-foot"},["Built with ",c("a",{href:Oe,target:"_blank",rel:"noopener noreferrer",text:"Cuttlely"})]);return c("div",{class:"dc-composer"},[c("div",{class:"dc-compose-inner"},[this.pendingEl,c("div",{class:"dc-box"},t),r])])}clearDrop(){var e;(e=this.dropEl)==null||e.remove(),this.dropEl=null}updateSendButton(){this.sendBtn&&(this.sendBtn.innerHTML=this.busy?f.stop:f.send,this.sendBtn.setAttribute("aria-label",this.busy?"Stop the answer":"Send message"),this.sendBtn.title=this.busy?"Stop":"Send")}autosize(){let e=this.input;e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,160)}px`}renderPending(){this.pendingEl&&(this.pendingEl.hidden=!this.pending.length,this.pendingEl.replaceChildren(...this.pending.map((e,t)=>c("div",{class:"dc-pending-item"},[c("img",{src:e.data,alt:e.name}),c("button",{type:"button","aria-label":`Remove ${e.name}`,html:f.close,onclick:()=>{this.pending.splice(t,1),this.renderPending(),this.focusInput()}})]))))}async addFiles(e){let t=this.config.imageUpload;if(t){for(let r of Array.from(e||[])){if(this.pending.length>=4)break;if(!t.types.includes(r.type)){this.announce(`${r.name} is not an image this chat accepts.`);continue}if(r.size>t.maxMB*1024*1024){this.announce(`${r.name} is larger than ${t.maxMB} MB.`);continue}let i=await new Promise(a=>{let o=new FileReader;o.onload=()=>a(typeof o.result=="string"?o.result:""),o.onerror=()=>a(""),o.readAsDataURL(r)});i&&w(i,{image:!0})&&this.pending.push({data:i,name:r.name,mime:r.type})}this.renderPending()}}scheduleRender(){if(this.frame)return;let e=typeof requestAnimationFrame=="function"?requestAnimationFrame:t=>setTimeout(t,16);this.frame=e(()=>{this.frame=0;let t=this.nearBottom();this.renderThread(),t&&this.scrollToEnd()})}nearBottom(){let e=this.scroller;return!e||e.scrollHeight-e.scrollTop-e.clientHeight<120}scrollToEnd(e){var r;let t=this.scroller;t&&(e?t.scrollTop=t.scrollHeight:(r=t.scrollTo)==null||r.call(t,{top:t.scrollHeight,behavior:"smooth"}))}async copy(e,t){let r=!1;try{await navigator.clipboard.writeText(e),r=!0}catch{let i=c("textarea",{style:"position:fixed;opacity:0"});i.value=e,this.root.append(i),i.select();try{r=document.execCommand("copy")}catch{r=!1}i.remove()}t&&(t.innerHTML=r?f.check:f.copy,setTimeout(()=>{t.innerHTML=f.copy},1500)),this.announce(r?"Copied":"Could not copy")}async rate(e,t){if(!e.messageId||e.feedback===t)return;let r=e.feedback;e.feedback=t,e.rev++,this.scheduleRender();try{await this.api.feedback({messageId:e.messageId,chatId:this.chatId,rating:t==="up"?"THUMBS_UP":"THUMBS_DOWN"}),this.announce("Thanks for the feedback"),this.save()}catch{e.feedback=r,e.rev++,this.scheduleRender(),this.announce("Could not send feedback")}}chooseAction(e,t){var i;let r=((i=e.action)==null?void 0:i.data)||{};if(e.action=null,e.rev++,String(t.type||"").includes("agentflowv2")){let a=String(t.type).includes("approve")?"proceed":"reject";this.send(t.label,{humanInput:{type:a,startNodeId:r.nodeId,feedback:""}})}else this.send(t.label,{action:e.actionRaw})}retry(e){var i;let t=this.messages.indexOf(e),r=e.retry;t>0&&((i=this.messages[t-1])==null?void 0:i.role)==="user"?this.messages.splice(t-1,2):this.messages.splice(t,1),this.nodes.clear(),this.send(r.text,r.extra,r.uploads)}abort(e){this.controller&&(this.controller.abort(),this.controller=null),e&&this.announce("Stopped")}async send(e,t={},r){var g;if(this.state!=="ready"||this.busy)return;let i=typeof e=="string"?e:((g=this.input)==null?void 0:g.value)||"",a=r||this.pending.map(p=>({data:p.data,type:"file",name:p.name,mime:p.mime}));if(!i.trim()&&!a.length)return;this.input&&typeof e!="string"&&(this.input.value="",this.autosize()),this.pending=[],this.renderPending();let o={id:_("m"),role:"user",text:i.trim(),images:a.map(p=>p.data),status:"done",rev:0},n={id:_("m"),role:"bot",text:"",status:"streaming",sources:[],artifacts:[],rev:0};this.messages.push(o,n),this.setBusy(!0),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce("Answering");let d={question:i.trim()};this.chatId&&(d.chatId=this.chatId),this.sessionToken&&(d.sessionToken=this.sessionToken),a.length&&(d.uploads=a),t.humanInput&&(d.humanInput=t.humanInput),t.action&&(d.action=t.action),this.options.overrideConfig&&typeof this.options.overrideConfig=="object"&&(d.overrideConfig=this.options.overrideConfig);let l=new AbortController;this.controller=l;let h=()=>{n.rev++,this.scheduleRender()};try{await this.api.send(d,{onEvent:p=>this.onEvent(n,p,h),onJson:p=>this.onJson(n,p)},l.signal),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.text=n.fallbackText||""),!n.text&&!n.error&&!n.artifacts.length&&!n.action&&(n.error="The answer was empty. Try asking another way.")}catch(p){if(l.signal.aborted)n.text||(n.text="_Stopped._");else{let u=$(p,this.config.errorMessage);if(u.kind==="private"||u.kind==="origin"){this.setBusy(!1),this.block(u);return}n.error=u.message,n.retry={text:i.trim(),extra:t,uploads:a}}}finally{this.controller===l&&(this.controller=null)}n.status="done",n.run&&n.run.phase!=="done"&&n.run.phase!=="failed"&&(n.run=L(n.run,n.error?"error":"final",{})),n.rev++,this.setBusy(!1),this.renderShellHeaderOnly(),this.renderThread(),this.scrollToEnd(),this.announce(n.error?n.error:`Answer: ${n.text.replace(/[#*_`>|]/g,"").slice(0,280)}`),this.save(),this.focusInput()}setBusy(e){this.busy=e,this.updateSendButton(),this.updateStatus()}renderShellHeaderOnly(){let e=this.window.querySelector(".dc-header");e&&e.replaceWith(this.renderHeader())}onEvent(e,t,r){let{event:i,data:a}=t;if(i==="token"&&typeof a=="string")return e.text+=a,r();if(i==="start")return r();if(i==="sourceDocuments")return e.sources=le(a),r();if(i==="artifacts")return e.artifacts=K(a),r();if(i==="action")return e.action=a&&typeof a=="object"?a:null,e.actionRaw=a,r();if(i==="agentFlowExecutedData"){e.fallbackText=ue(a)||e.fallbackText;return}if(i==="metadata"&&a&&typeof a=="object")return typeof a.chatId=="string"&&(this.chatId=a.chatId),typeof a.sessionToken=="string"&&(this.sessionToken=a.sessionToken),typeof a.chatMessageId=="string"&&(e.messageId=a.chatMessageId),a.followUpPrompts&&(e.followUps=fe(a.followUpPrompts)),a.action&&!e.action&&(e.action=a.action,e.actionRaw=a.action),r();if(i==="error"){let o=typeof t.status=="number"?t.status:0,n=o?$({status:o},this.config.errorMessage):null;return e.error=n&&n.kind!=="error"?n.message:this.config.errorMessage||(typeof a=="string"&&a?a.slice(0,300):"Something went wrong. Try again."),e.run&&(e.run=L(e.run,"error",{message:e.error})),r()}if(typeof i=="string"&&i.startsWith("harness.")){let o=i.slice(8);if(o==="recorded")return;let n=a&&typeof a=="object"?a:{};return e.run=L(e.run||U(n.harness),o,n),o==="partial"&&n.phase==="answer"&&!n.streamedAsToken&&typeof n.text=="string"&&(e.text+=n.text),o==="final"&&!e.text&&typeof n.text=="string"&&(e.fallbackText=n.text),r()}}onJson(e,t){!t||typeof t!="object"||(typeof t.chatId=="string"&&(this.chatId=t.chatId),typeof t.sessionToken=="string"&&(this.sessionToken=t.sessionToken),typeof t.chatMessageId=="string"&&(e.messageId=t.chatMessageId),typeof t.text=="string"?e.text=t.text:t.json!==void 0&&(e.text="```json\n"+JSON.stringify(t.json,null,2)+"\n```"),e.text||(e.fallbackText=ue(t.agentFlowExecutedData)),e.sources=le(t.sourceDocuments),e.artifacts=K(t.artifacts),t.followUpPrompts&&(e.followUps=fe(t.followUpPrompts)),t.action&&(e.action=typeof t.action=="string"?_e(t.action):t.action,e.actionRaw=e.action),(t.harness||Array.isArray(t.agents))&&(e.run=L(U(t.harness||""),"final",{harness:t.harness,trace:Array.isArray(t.agents)?{specialists:t.agents}:void 0,timings:t.timings})))}destroy(){var e,t;this.abort(),(t=(e=this.media)==null?void 0:e.removeEventListener)==null||t.call(e,"change",this.onMedia),this.root.innerHTML=""}};function _e(s){try{return JSON.parse(s)}catch{return null}}var ge="cuttlely-chat";function j(s,e={}){var r;if(!s)throw new Error("Cuttlely chat: mount needs a target element");if(!e.flowId)throw new Error("Cuttlely chat: flowId is required");(r=s.__cuttlelyChat)==null||r.destroy();let t=new N(s,e);return s.__cuttlelyChat=t,t}function D(s,e){let t=s.getAttribute(e);return t===null||t===""?void 0:t}function me(s){if(typeof customElements>"u"||customElements.get(ge))return;class e extends HTMLElement{static get observedAttributes(){return["flow-id","api-host","mode","theme"]}connectedCallback(){this.render()}attributeChangedCallback(r,i,a){!this.isConnected||i===a||(r==="theme"&&this.widget?this.widget.setTheme(a||"auto"):this.render())}disconnectedCallback(){var r;(r=this.widget)==null||r.destroy(),this.widget=null}render(){let r=D(this,"flow-id");r&&(this.widget=j(this,{flowId:r,apiHost:D(this,"api-host")||s,mode:D(this,"mode")==="page"?"page":"bubble",theme:D(this,"theme")||"auto",open:this.hasAttribute("open")}))}open(){var r;(r=this.widget)==null||r.open()}close(){var r;(r=this.widget)==null||r.close()}reset(){var r;(r=this.widget)==null||r.reset()}}customElements.define(ge,e)}var I=typeof document<"u"?document.currentScript:null,X=(()=>{try{return I&&I.src?new URL(I.src).origin:location.origin}catch{return location.origin}})();me(X);function be(){let s=(I==null?void 0:I.dataset)||{},e=s.flowId||s.flowid;if(!e)return;let t=s.mode==="page"?"page":"bubble",r;t==="page"&&s.target&&(r=document.querySelector(s.target)),r||(r=document.createElement("cuttlely-chat-root"),r.style.display=t==="page"?"block":"contents",t==="page"&&(r.style.height="100%"),document.body.append(r)),j(r,{flowId:e,apiHost:s.apiHost||X,mode:t,theme:s.theme||"auto",open:s.open==="true"})}var Ne={mount:(s,e)=>j(s,{apiHost:X,...e}),version:"1.4.5"};typeof window<"u"&&(window.cuttlelyChat=Ne);typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",be,{once:!0}):be());})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cuttlely/chat",
3
- "version": "1.4.4",
3
+ "version": "1.4.5",
4
4
  "description": "Embeddable Cuttlely chat widget for applications",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",