dewee-webchat 0.5.0-beta.2 → 0.5.0-beta.4

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.
@@ -1,24 +1,24 @@
1
- "use strict";(()=>{var be=Object.defineProperty;var Qe=(t,s,e)=>s in t?be(t,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):t[s]=e;var Xe=(t,s)=>()=>(t&&(s=t(t=0)),s);var we=(t,s)=>{for(var e in s)be(t,e,{get:s[e],enumerable:!0})};var f=(t,s,e)=>Qe(t,typeof s!="symbol"?s+"":s,e);var Ve={};we(Ve,{capturePageContext:()=>Mt,providedPageContext:()=>Pt,safePageUrl:()=>Ue});function Ue(t){try{let s=new URL(t);if(s.protocol!=="https:"&&s.protocol!=="http:")return;s.username="",s.password="",s.hash="";for(let e of[...s.searchParams.keys()]){let n=e.replace(/(\p{Lu}+)(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/([\p{Ll}\p{N}])(\p{Lu})/gu,"$1 $2").replace(/(\p{L})(\p{N})/gu,"$1 $2").replace(/(\p{N})(\p{L})/gu,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean),i=n.join(""),r=["api","access","auth","oauth","secret","private","client","session","signing","verification","reset","recovery","activation","confirmation","invite","license","encryption"];(n.some((c,a)=>["token","secret","password","passwd","pwd","auth","authorization","cookie","apikey","session","sid","sig","signature","otp","jwt","credential","credentials","nonce","bearer","ticket"].includes(c)||["code","key","state"].includes(c)&&(n.length===1||a>0&&r.includes(n[a-1])))||/token|secret|passw|apikey|credential|sessid|session|authorization|samlresponse/.test(i))&&s.searchParams.set(e,"[REDACTED]")}return new TextEncoder().encode(s.href).length<=2048?s.href:void 0}catch{return}}function I(t,s){return Array.from(t).slice(0,s).join("")}function Je(t){if(t.content&&new TextEncoder().encode(JSON.stringify(t)).length>65536){let s=Array.from(t.content.text),e=0,n=s.length;for(;e<n;){let i=Math.ceil((e+n)/2);t.content.text=s.slice(0,i).join(""),t.content.truncated=!0,new TextEncoder().encode(JSON.stringify(t)).length<=65536?e=i:n=i-1}t.content.text=s.slice(0,e).join(""),t.content.truncated=!0}return t}function Pt(t,s,e){if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("Invalid page context");let n=t,i={version:1,url:s.url,captured_at:s.captured_at};for(let[r,o]of[["title",300],["description",1e3]])typeof n[r]=="string"&&(i[r]=I(n[r].replace(/\s+/g," ").trim(),o));if(e==="content"&&(typeof n.selection=="string"&&(i.selection=I(n.selection,2e3)),n.content&&typeof n.content=="object"&&!Array.isArray(n.content))){let r=n.content;if(typeof r.text!="string"||r.format!=="text"&&r.format!=="markdown")throw new TypeError("Invalid page content");let o=I(r.text,12e3);i.content={format:r.format,text:o,truncated:r.truncated===!0||Array.from(r.text).length>12e3}}return Je(i)}function V(t,s){for(let e=t;e;e=e.parentElement){if(e.matches(Lt)||s.some(i=>e.matches(i))||e instanceof HTMLDialogElement&&!e.open)return!1;if(e instanceof HTMLDetailsElement&&!e.open){let i=[...e.children].find(r=>r.tagName==="SUMMARY");if(!i||!t||i!==t&&!i.contains(t))return!1}if(e.hasAttribute("popover"))try{if(!e.matches(":popover-open"))return!1}catch{return!1}let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse"||n.opacity==="0"||n.contentVisibility==="hidden")return!1}return!(t&&typeof t.checkVisibility=="function"&&!t.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0}))}function Mt(t,s){let e=Ue(t.location.href);if(!e)return;let n=s.excludeSelectors??[];for(let m of n)t.documentElement.matches(m);let i=t.querySelector(s.selector||"main, article, [role='main']"),r={version:1,url:e,captured_at:new Date().toISOString()},o=I(t.title.replace(/\s+/g," ").trim(),300),c=I((t.querySelector('meta[name="description" i]')?.getAttribute("content")??"").replace(/\s+/g," ").trim(),1e3);if(o&&(r.title=o),c&&(r.description=c),s.mode!=="content"||!i||!V(i,n))return r;let a=t.createTreeWalker(i,NodeFilter.SHOW_TEXT),d=[],l=0,p=0,g=!1;for(;a.nextNode();){if(++p>5e3){g=!0;break}let m=a.currentNode;if(!V(m.parentElement,n))continue;let b=(m.textContent??"").replace(/\s+/g," ").trim();if(!b)continue;let x=12e3-l,w=I(b,x);if(d.push(w),l+=Array.from(w).length+1,Array.from(b).length>x||l>=12e3){g=!0;break}}let h=I(d.join(`
2
- `),12e3);h&&(r.content={format:"text",text:h,truncated:g});let u=t.getSelection();if(u&&!u.isCollapsed&&u.rangeCount){let m=u.getRangeAt(0),b=m.commonAncestorContainer,x=b.nodeType===Node.ELEMENT_NODE?b:b.parentElement;if(x&&i.contains(x)&&V(x,n)){let w=i.querySelectorAll("*");if(w.length<=5e3&&![...w].some(y=>m.intersectsNode(y)&&!V(y,n))){let y=I(u.toString().trim(),2e3);y&&(r.selection=y)}}}return Je(r)}var Lt,Ke=Xe(()=>{"use strict";Lt="script,style,noscript,template,svg,canvas,iframe,form,input,textarea,select,option,button,[contenteditable]:not([contenteditable='false']),[hidden],[aria-hidden='true'],[inert],dewee-chat"});var me={};we(me,{ApiClient:()=>M,ApiError:()=>E,DOM_ACTION_NAMES:()=>_e,DeweeChatElement:()=>D,RESERVED_HEADERS:()=>he,defineDeweeChat:()=>fe,mount:()=>qt,renderMarkdown:()=>R});var Ze=["IDENTITY_REQUIRED","IDENTITY_LINK_REQUIRED","IDENTITY_CONFLICT","LINK_EXPIRED","LINK_REVOKED","PERMISSION_DENIED","SOURCE_UNAVAILABLE"];function Y(t){return typeof t=="string"&&Ze.includes(t)}var et=["POLICY_DENIED","RATE_LIMITED","CHALLENGE_REQUIRED"];function G(t){return typeof t=="string"&&et.includes(t)}var tt=["idempotency_key_reused","link_in_progress","linking_unavailable"];function ye(t){return typeof t=="string"&&tt.includes(t)}var W="x-dewee-gateway-url",F="x-dewee-gateway-token";var xe="dewee-action",ve="dewee-action-result",$={maxCalls:8,maxBlockBytes:8192},nt=/^[A-Za-z0-9_.:-]{1,64}$/,it=/^\s{0,3}```\s*$/,Ee=t=>new RegExp("^\\s{0,3}```"+t.replace(/[.-]/g,"\\$&")+"\\s*$"),ke=Ee(xe),st=Ee(ve);function Q(t,s){let e=[];for(let n=0;n<t.length;n++){if(!s.test(t[n]))continue;let i=n,r=[],o=!1;for(n++;n<t.length;n++){if(it.test(t[n])){o=!0;break}r.push(t[n])}e.push({start:i,end:Math.min(n,t.length-1),body:r,closed:o})}return e}var Ae=(t,s)=>{let e=new Set;for(let n of s)for(let i=n.start;i<=n.end;i++)e.add(i);return t.filter((n,i)=>!e.has(i)).join(`
1
+ "use strict";(()=>{var xe=Object.defineProperty;var it=(n,s,e)=>s in n?xe(n,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[s]=e;var st=(n,s)=>()=>(n&&(s=n(n=0)),s);var ve=(n,s)=>{for(var e in s)xe(n,e,{get:s[e],enumerable:!0})};var f=(n,s,e)=>it(n,typeof s!="symbol"?s+"":s,e);var We={};ve(We,{capturePageContext:()=>$t,providedPageContext:()=>qt,safePageUrl:()=>Fe});function Fe(n){try{let s=new URL(n);if(s.protocol!=="https:"&&s.protocol!=="http:")return;s.username="",s.password="",s.hash="";for(let e of[...s.searchParams.keys()]){let t=e.replace(/(\p{Lu}+)(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/([\p{Ll}\p{N}])(\p{Lu})/gu,"$1 $2").replace(/(\p{L})(\p{N})/gu,"$1 $2").replace(/(\p{N})(\p{L})/gu,"$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean),i=t.join(""),r=["api","access","auth","oauth","secret","private","client","session","signing","verification","reset","recovery","activation","confirmation","invite","license","encryption"];(t.some((c,a)=>["token","secret","password","passwd","pwd","auth","authorization","cookie","apikey","session","sid","sig","signature","otp","jwt","credential","credentials","nonce","bearer","ticket"].includes(c)||["code","key","state"].includes(c)&&(t.length===1||a>0&&r.includes(t[a-1])))||/token|secret|passw|apikey|credential|sessid|session|authorization|samlresponse/.test(i))&&s.searchParams.set(e,"[REDACTED]")}return new TextEncoder().encode(s.href).length<=2048?s.href:void 0}catch{return}}function R(n,s){return Array.from(n).slice(0,s).join("")}function Ye(n){if(n.content&&new TextEncoder().encode(JSON.stringify(n)).length>65536){let s=Array.from(n.content.text),e=0,t=s.length;for(;e<t;){let i=Math.ceil((e+t)/2);n.content.text=s.slice(0,i).join(""),n.content.truncated=!0,new TextEncoder().encode(JSON.stringify(n)).length<=65536?e=i:t=i-1}n.content.text=s.slice(0,e).join(""),n.content.truncated=!0}return n}function qt(n,s,e){if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError("Invalid page context");let t=n,i={version:1,url:s.url,captured_at:s.captured_at};for(let[r,o]of[["title",300],["description",1e3]])typeof t[r]=="string"&&(i[r]=R(t[r].replace(/\s+/g," ").trim(),o));if(e==="content"&&(typeof t.selection=="string"&&(i.selection=R(t.selection,2e3)),t.content&&typeof t.content=="object"&&!Array.isArray(t.content))){let r=t.content;if(typeof r.text!="string"||r.format!=="text"&&r.format!=="markdown")throw new TypeError("Invalid page content");let o=R(r.text,12e3);i.content={format:r.format,text:o,truncated:r.truncated===!0||Array.from(r.text).length>12e3}}return Ye(i)}function F(n,s){for(let e=n;e;e=e.parentElement){if(e.matches(Ht)||s.some(i=>e.matches(i))||e instanceof HTMLDialogElement&&!e.open)return!1;if(e instanceof HTMLDetailsElement&&!e.open){let i=[...e.children].find(r=>r.tagName==="SUMMARY");if(!i||!n||i!==n&&!i.contains(n))return!1}if(e.hasAttribute("popover"))try{if(!e.matches(":popover-open"))return!1}catch{return!1}let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"||t.opacity==="0"||t.contentVisibility==="hidden")return!1}return!(n&&typeof n.checkVisibility=="function"&&!n.checkVisibility({checkOpacity:!0,checkVisibilityCSS:!0}))}function $t(n,s){let e=Fe(n.location.href);if(!e)return;let t=s.excludeSelectors??[];for(let m of t)n.documentElement.matches(m);let i=n.querySelector(s.selector||"main, article, [role='main']"),r={version:1,url:e,captured_at:new Date().toISOString()},o=R(n.title.replace(/\s+/g," ").trim(),300),c=R((n.querySelector('meta[name="description" i]')?.getAttribute("content")??"").replace(/\s+/g," ").trim(),1e3);if(o&&(r.title=o),c&&(r.description=c),s.mode!=="content"||!i||!F(i,t))return r;let a=n.createTreeWalker(i,NodeFilter.SHOW_TEXT),d=[],l=0,u=0,g=!1;for(;a.nextNode();){if(++u>5e3){g=!0;break}let m=a.currentNode;if(!F(m.parentElement,t))continue;let b=(m.textContent??"").replace(/\s+/g," ").trim();if(!b)continue;let x=12e3-l,w=R(b,x);if(d.push(w),l+=Array.from(w).length+1,Array.from(b).length>x||l>=12e3){g=!0;break}}let p=R(d.join(`
2
+ `),12e3);p&&(r.content={format:"text",text:p,truncated:g});let h=n.getSelection();if(h&&!h.isCollapsed&&h.rangeCount){let m=h.getRangeAt(0),b=m.commonAncestorContainer,x=b.nodeType===Node.ELEMENT_NODE?b:b.parentElement;if(x&&i.contains(x)&&F(x,t)){let w=i.querySelectorAll("*");if(w.length<=5e3&&![...w].some(y=>m.intersectsNode(y)&&!F(y,t))){let y=R(h.toString().trim(),2e3);y&&(r.selection=y)}}}return Ye(r)}var Ht,Qe=st(()=>{"use strict";Ht="script,style,noscript,template,svg,canvas,iframe,form,input,textarea,select,option,button,[contenteditable]:not([contenteditable='false']),[hidden],[aria-hidden='true'],[inert],dewee-chat"});var ye={};ve(ye,{ApiClient:()=>_,ApiError:()=>v,DOM_ACTION_NAMES:()=>De,DeweeChatElement:()=>q,RESERVED_HEADERS:()=>fe,defineDeweeChat:()=>we,mount:()=>Wt,renderMarkdown:()=>M});var rt=["IDENTITY_REQUIRED","IDENTITY_LINK_REQUIRED","IDENTITY_CONFLICT","LINK_EXPIRED","LINK_REVOKED","PERMISSION_DENIED","SOURCE_UNAVAILABLE"];function W(n){return typeof n=="string"&&rt.includes(n)}var ot=["POLICY_DENIED","RATE_LIMITED","CHALLENGE_REQUIRED"];function Q(n){return typeof n=="string"&&ot.includes(n)}var at=["idempotency_key_reused","link_in_progress","linking_unavailable"];function Ce(n){return typeof n=="string"&&at.includes(n)}var X="x-dewee-gateway-url",Z="x-dewee-gateway-token";var Ee="dewee-action",ke="dewee-action-result",$={maxCalls:8,maxBlockBytes:8192},ct=/^[A-Za-z0-9_.:-]{1,64}$/,lt=/^\s{0,3}```\s*$/,Ae=n=>new RegExp("^\\s{0,3}```"+n.replace(/[.-]/g,"\\$&")+"\\s*$"),Se=Ae(Ee),dt=Ae(ke);function ee(n,s){let e=[];for(let t=0;t<n.length;t++){if(!s.test(n[t]))continue;let i=t,r=[],o=!1;for(t++;t<n.length;t++){if(lt.test(n[t])){o=!0;break}r.push(n[t])}e.push({start:i,end:Math.min(t,n.length-1),body:r,closed:o})}return e}var Te=(n,s)=>{let e=new Set;for(let t of s)for(let i=t.start;i<=t.end;i++)e.add(i);return n.filter((t,i)=>!e.has(i)).join(`
3
3
  `).replace(/\n{3,}/g,`
4
4
 
5
- `).trim()};function X(t){let s=t.replace(/\r\n?/g,`
5
+ `).trim()};function te(n){let s=n.replace(/\r\n?/g,`
6
6
  `).split(`
7
- `),e=Q(s,ke),n=[],i=new Set;return e.forEach((r,o)=>{let c=`call-${o+1}`,a=r.body.join(`
8
- `),d=(u,m=c,b="")=>n.push({ok:!1,id:m,name:b,error:u});if(o>=$.maxCalls)return d(`Too many action calls in one reply (max ${$.maxCalls})`);if(!r.closed)return d("Unclosed dewee-action block");if(new TextEncoder().encode(a).length>$.maxBlockBytes)return d(`Action block exceeds ${$.maxBlockBytes} bytes`);let l;try{l=JSON.parse(a)}catch{return d("Action block is not valid JSON")}if(typeof l!="object"||l===null||Array.isArray(l))return d("Action block must be a JSON object");let p=typeof l.id=="string"&&nt.test(l.id)?l.id:c,g=typeof l.name=="string"?l.name.slice(0,64):"";if(i.has(p))return d(`Duplicate action call id "${p}"`,`${p}-${o+1}`,g);if(i.add(p),!g)return d("Action name is required",p);let h=l.args??{};if(typeof h!="object"||h===null||Array.isArray(h))return d("args must be a JSON object",p,g);n.push({ok:!0,id:p,name:g,args:h})}),{text:e.length?Ae(s,e):t,calls:n}}function Ce(t){if(!t.includes("```"+xe))return t;let s=t.replace(/\r\n?/g,`
7
+ `),e=ee(s,Se),t=[],i=new Set;return e.forEach((r,o)=>{let c=`call-${o+1}`,a=r.body.join(`
8
+ `),d=(h,m=c,b="")=>t.push({ok:!1,id:m,name:b,error:h});if(o>=$.maxCalls)return d(`Too many action calls in one reply (max ${$.maxCalls})`);if(!r.closed)return d("Unclosed dewee-action block");if(new TextEncoder().encode(a).length>$.maxBlockBytes)return d(`Action block exceeds ${$.maxBlockBytes} bytes`);let l;try{l=JSON.parse(a)}catch{return d("Action block is not valid JSON")}if(typeof l!="object"||l===null||Array.isArray(l))return d("Action block must be a JSON object");let u=typeof l.id=="string"&&ct.test(l.id)?l.id:c,g=typeof l.name=="string"?l.name.slice(0,64):"";if(i.has(u))return d(`Duplicate action call id "${u}"`,`${u}-${o+1}`,g);if(i.add(u),!g)return d("Action name is required",u);let p=l.args??{};if(typeof p!="object"||p===null||Array.isArray(p))return d("args must be a JSON object",u,g);t.push({ok:!0,id:u,name:g,args:p})}),{text:e.length?Te(s,e):n,calls:t}}function Pe(n){if(!n.includes("```"+Ee))return n;let s=n.replace(/\r\n?/g,`
9
9
  `).split(`
10
- `);return Ae(s,Q(s,ke))}function Z(t){return/^\s*```dewee-action-result(?:\s|$)/.test(t)}function rt(t){let s=/```dewee-action-result\s+/g,e=[],n;for(;n=s.exec(t);){let i=s.lastIndex;if(t[i]!=="{")continue;let r=0,o=!1,c=!1;for(let a=i;a<t.length;a++){let d=t[a];if(o)c?c=!1:d==="\\"?c=!0:d==='"'&&(o=!1);else if(d==='"')o=!0;else if(d==="{")r++;else if(d==="}"&&--r===0){let l=/^\s*```/.exec(t.slice(a+1));l&&(e.push(t.slice(i,a+1)),s.lastIndex=a+1+l[0].length);break}}}return e}function Se(t){let s=t.replace(/\r\n?/g,`
10
+ `);return Te(s,ee(s,Se))}function ne(n){return/^\s*```dewee-action-result(?:\s|$)/.test(n)}function ut(n){let s=/```dewee-action-result\s+/g,e=[],t;for(;t=s.exec(n);){let i=s.lastIndex;if(n[i]!=="{")continue;let r=0,o=!1,c=!1;for(let a=i;a<n.length;a++){let d=n[a];if(o)c?c=!1:d==="\\"?c=!0:d==='"'&&(o=!1);else if(d==='"')o=!0;else if(d==="{")r++;else if(d==="}"&&--r===0){let l=/^\s*```/.exec(n.slice(a+1));l&&(e.push(n.slice(i,a+1)),s.lastIndex=a+1+l[0].length);break}}}return e}function Re(n){let s=n.replace(/\r\n?/g,`
11
11
  `).split(`
12
- `),e=[],n=Q(s,st),i=n.length?n.map(r=>r.body.join(`
13
- `)):rt(t);for(let r of i)try{let o=JSON.parse(r);o&&typeof o.id=="string"&&["ok","denied","error"].includes(o.status)&&e.push(o)}catch{}return e}var N=t=>"```"+ve+`
14
- `+JSON.stringify(t)+"\n```";function Te(t,s=4e3){let e=Math.max(64,Math.floor((s-16)/Math.max(1,t.length)));return t.map(i=>{let r={...i,result:ee(i.result)};if(r.result===void 0&&delete r.result,N(r).length<=e)return N(r);let o=JSON.stringify(r.result??null),c=e-N({...r,result:{truncated:!0,preview:""}}).length-8,a=N({...r,result:{truncated:!0,preview:o.slice(0,Math.max(0,c))}});return a.length<=e?a:N({id:i.id,name:i.name.slice(0,64),status:i.status,result:{truncated:!0}})}).join(`
12
+ `),e=[],t=ee(s,dt),i=t.length?t.map(r=>r.body.join(`
13
+ `)):ut(n);for(let r of i)try{let o=JSON.parse(r);o&&typeof o.id=="string"&&["ok","denied","error"].includes(o.status)&&e.push(o)}catch{}return e}var O=n=>"```"+ke+`
14
+ `+JSON.stringify(n)+"\n```";function Le(n,s=4e3){let e=Math.max(64,Math.floor((s-16)/Math.max(1,n.length)));return n.map(i=>{let r={...i,result:ie(i.result)};if(r.result===void 0&&delete r.result,O(r).length<=e)return O(r);let o=JSON.stringify(r.result??null),c=e-O({...r,result:{truncated:!0,preview:""}}).length-8,a=O({...r,result:{truncated:!0,preview:o.slice(0,Math.max(0,c))}});return a.length<=e?a:O({id:i.id,name:i.name.slice(0,64),status:i.status,result:{truncated:!0}})}).join(`
15
15
 
16
- `).slice(0,s)}function ee(t){if(t!==void 0)try{let s=JSON.stringify(t);return s===void 0?null:JSON.parse(s)}catch{return"[unserializable result]"}}var te=t=>t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t,ot=(t,s)=>{let e=te(t);return e===s||s==="number"&&e==="integer"};function j(t,s,e="args",n=0){if(!s||typeof s!="object")return null;if(n>32)return`${e}: schema is nested too deeply`;let i=s;if(i.type!==void 0){let r=Array.isArray(i.type)?i.type:[i.type];if(!r.some(o=>ot(t,o)))return`${e}: expected ${r.join(" or ")}, got ${te(t)}`}if(Array.isArray(i.enum)&&!i.enum.some(r=>Ie(r,t)))return`${e}: must be one of ${i.enum.map(r=>JSON.stringify(r)).join(", ")}`;if("const"in i&&!Ie(i.const,t))return`${e}: must equal ${JSON.stringify(i.const)}`;if(typeof t=="string"){if(typeof i.minLength=="number"&&t.length<i.minLength)return`${e}: shorter than ${i.minLength} characters`;if(typeof i.maxLength=="number"&&t.length>i.maxLength)return`${e}: longer than ${i.maxLength} characters`;if(typeof i.pattern=="string"){let r=null;try{r=new RegExp(i.pattern,"u")}catch{return`${e}: schema pattern is invalid`}if(!r.test(t))return`${e}: does not match ${i.pattern}`}}if(typeof t=="number"){if(typeof i.minimum=="number"&&t<i.minimum)return`${e}: must be >= ${i.minimum}`;if(typeof i.maximum=="number"&&t>i.maximum)return`${e}: must be <= ${i.maximum}`}if(Array.isArray(t)){if(typeof i.minItems=="number"&&t.length<i.minItems)return`${e}: needs at least ${i.minItems} items`;if(typeof i.maxItems=="number"&&t.length>i.maxItems)return`${e}: allows at most ${i.maxItems} items`;if(i.items&&typeof i.items=="object")for(let r=0;r<t.length;r++){let o=j(t[r],i.items,`${e}[${r}]`,n+1);if(o)return o}}if(te(t)==="object"){let r=t,o=i.properties&&typeof i.properties=="object"?i.properties:{};for(let c of Array.isArray(i.required)?i.required:[])if(!(c in r))return`${e}.${c}: is required`;for(let[c,a]of Object.entries(r))if(Object.prototype.hasOwnProperty.call(o,c)){let d=j(a,o[c],`${e}.${c}`,n+1);if(d)return d}else if(i.additionalProperties===!1)return`${e}.${c}: is not allowed`}return null}function Ie(t,s){return JSON.stringify(t)===JSON.stringify(s)}var Pe=/^[a-z][a-z0-9_.-]{0,63}$/,ne=["read","navigate","mutate","destructive"],S={maxActions:32,maxDescription:1e3,maxParametersBytes:4096,maxManifestBytes:16384,maxPageContextBytes:4096},at="[[dewee-page v1]]",Le="[[/dewee-page]]";function ie(t){if(!t.startsWith(at))return t;let s=t.indexOf(`
17
- `+Le);return s<0?t:t.slice(s+Le.length+1).replace(/^\n+/,"")}var ct=t=>t==="mutate"||t==="destructive",O=class{constructor(){f(this,"map",new Map)}get size(){return this.map.size}get(s){return this.map.get(s)}names(){return[...this.map.keys()]}register(s){let e=Array.isArray(s)?s:[s];for(let n of e)lt(n);if(new Set([...this.map.keys(),...e.map(n=>n.name)]).size>S.maxActions)throw new TypeError(`dewee-webchat: at most ${S.maxActions} page actions`);for(let n of e)this.map.set(n.name,n)}unregister(s){return this.map.delete(s)}manifest(){return[...this.map.values()].map(s=>({name:s.name,description:s.description,sensitivity:s.sensitivity,parameters:s.parameters??{type:"object",properties:{}}}))}};function lt(t){let s=e=>{throw new TypeError(`dewee-webchat: invalid page action ${JSON.stringify(t?.name)}: ${e}`)};(!t||typeof t!="object")&&s("not an object"),(typeof t.name!="string"||!Pe.test(t.name))&&s("name must match ^[a-z][a-z0-9_.-]{0,63}$"),(typeof t.description!="string"||t.description.length>S.maxDescription)&&s(`description must be a string up to ${S.maxDescription} chars`),ne.includes(t.sensitivity)||s(`sensitivity must be one of ${ne.join(", ")}`),typeof t.handler!="function"&&s("handler must be a function"),t.parameters!==void 0&&(typeof t.parameters!="object"||t.parameters===null||Array.isArray(t.parameters))&&s("parameters must be a JSON Schema object")}async function Re(t,s){let e=a=>(s.onStatus?.("error"),{id:t.id,name:t.name,status:"error",error:a});if(!t.ok)return e(t.error);if(s.signal.aborted)return e("Cancelled");let n=s.registry.get(t.name);if(!n)return e(`Unknown action "${t.name}". Available: ${s.registry.names().join(", ")||"none"}`);let i=j(t.args,n.parameters??{type:"object"});if(i)return e(`Invalid arguments: ${i}`);if(ct(n.sensitivity)){s.onStatus?.("awaiting-confirmation");let{handler:a,...d}=n,l=!1;try{l=await Me(Promise.resolve(s.confirm({...d,callId:t.id},t.args)),s.signal)===!0}catch{l=!1}if(!l||s.signal.aborted)return s.onStatus?.("denied"),{id:t.id,name:t.name,status:"denied",error:"The user declined this action."}}s.onStatus?.("running");let r=new AbortController,o=()=>r.abort();s.signal.addEventListener("abort",o,{once:!0});let c=setTimeout(o,s.timeoutMs??3e4);try{let a=await Me(Promise.resolve().then(()=>n.handler(t.args,{callId:t.id,conversationId:s.conversationId,agent:s.agent,signal:r.signal})),r.signal);return s.onStatus?.("done"),{id:t.id,name:t.name,status:"ok",result:ee(a)??null}}catch(a){return e(r.signal.aborted?s.signal.aborted?"Cancelled":"Timed out":String(a?.message??a).slice(0,500)||"Action failed")}finally{clearTimeout(c),s.signal.removeEventListener("abort",o)}}function Me(t,s){return s.aborted?Promise.reject(new Error("aborted")):new Promise((e,n)=>{let i=()=>n(new Error("aborted"));s.addEventListener("abort",i,{once:!0}),t.then(e,n).finally(()=>s.removeEventListener("abort",i))})}var _e=["page.snapshot","page.scroll","page.click","page.fill"],dt=["a[href]","button","input","select","textarea","summary","[contenteditable]:not([contenteditable=false])",...["button","link","checkbox","radio","switch","tab","menuitem","option","combobox","textbox","searchbox"].map(t=>`[role=${t}]`)].join(","),pt=new Set(["checkbox","radio","file","submit","button","image","reset","hidden","password"]),ht=/\b(cc-[a-z-]+|one-time-code|current-password|new-password)\b/i,ut=/(passw|passcode|\bpin\b|otp|one.?time|cvv|cvc|card.?(num|no)|cc.?num|security.?code|\bssn\b)/i,le=80,pe=60,gt=40,P=(t,s)=>t.length>s?t.slice(0,s-1)+"\u2026":t,k=t=>(t??"").replace(/\s+/g," ").trim(),se={type:"string",pattern:"^e[0-9]{1,4}$"},re={type:"integer",minimum:1};function Ne(t){let s=0,e=new Map,n=()=>{let l=t.root(),p=typeof l=="string"?document.querySelector(l):l;if(l!==void 0&&!p)throw new Error(`domActionsRoot ${JSON.stringify(l)} matches no element`);return p??document.body},i=(l,p)=>l.isConnected&&p.contains(l)&&!t.exclude?.(l)&&!l.closest("[data-dewee-ignore]")&&!mt(l)&&bt(l),r=l=>{if(l.generation!==s)throw new Error(`Stale ref: generation ${l.generation} is not the latest snapshot (${s||"none"}). Call page.snapshot again.`);let p=e.get(l.ref);if(!p)throw new Error(`Unknown ref "${l.ref}". Call page.snapshot again.`);if(!i(p,n()))throw new Error(`Ref "${l.ref}" is no longer available. Call page.snapshot again.`);return p};return{actions:[{name:"page.snapshot",description:'List the interactive elements visible on the page (links, buttons, form fields) as lines `ref role "name" [state]`. Use the ref together with the returned generation in page.scroll, page.click and page.fill. Every snapshot invalidates older refs. Use query to filter by visible name, offset/limit to page through long lists.',sensitivity:"read",parameters:{type:"object",properties:{query:{type:"string",maxLength:100},offset:{type:"integer",minimum:0},limit:{type:"integer",minimum:1,maximum:100}},additionalProperties:!1},handler:({query:l,offset:p=0,limit:g=gt})=>{let h=n();s++,e=new Map;let u=k(l).toLowerCase(),m=[],b=0;for(let x of h.querySelectorAll(dt)){if(!i(x,h))continue;let w=ae(x);if(u&&!w.toLowerCase().includes(u)||(b++,b<=p||m.length>=g))continue;let y=`e${b}`;e.set(y,x),m.push(`${y} ${w}`)}return{generation:s,url:location.pathname+location.search,title:P(document.title,le),total:b,offset:p,elements:m,...ce(h)}}},{name:"page.scroll",description:"Scroll the page by about one screen (direction up/down) or to the top/bottom, or scroll an element from page.snapshot into view (ref + generation).",sensitivity:"read",parameters:{type:"object",properties:{direction:{type:"string",enum:["up","down","top","bottom"]},ref:se,generation:re},additionalProperties:!1},handler:({direction:l,ref:p,generation:g})=>{let h=n();if(p!==void 0){if(g===void 0)throw new Error("generation is required with ref");return r({ref:p,generation:g}).scrollIntoView?.({block:"center",inline:"nearest"}),{ref:p,...ce(h)}}if(!l)throw new Error("Give a direction or a ref");let u=He(h),m=u===null?window.innerHeight:u.clientHeight,b=u===null?window.scrollY:u.scrollTop,x=u===null?document.documentElement.scrollHeight:u.scrollHeight,w=l==="top"?0:l==="bottom"?x:b+(l==="down"?.8:-.8)*m;return u===null?window.scrollTo({top:w}):u.scrollTop=w,{direction:l,...ce(h)}}},{name:"page.click",description:"Click an element from page.snapshot (ref + generation). The visitor approves every click.",sensitivity:"mutate",parameters:{type:"object",properties:{ref:se,generation:re},required:["ref","generation"],additionalProperties:!1},handler:l=>{let p=r(l);if(de(p))throw new Error(`Ref "${l.ref}" is disabled`);return p.scrollIntoView?.({block:"center",inline:"nearest"}),p instanceof HTMLElement?(p.focus({preventScroll:!0}),p.click()):p.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,composed:!0})),{ref:l.ref,clicked:ae(p)}}},{name:"page.fill",description:"Replace the value of a text field, textarea, select (option value or label) or editable area from page.snapshot (ref + generation). The visitor approves every fill.",sensitivity:"mutate",parameters:{type:"object",properties:{ref:se,generation:re,text:{type:"string",maxLength:1e4}},required:["ref","generation","text"],additionalProperties:!1},handler:l=>{let p=r(l);if(de(p)||p.readOnly)throw new Error(`Ref "${l.ref}" is not editable`);return ft(p,l.text),{ref:l.ref,value:P(Oe(p),pe)}}}],target:l=>{try{return ae(r(l))}catch{return}}}}function ft(t,s){if(t instanceof HTMLInputElement){if(pt.has(t.type))throw new Error(`Inputs of type "${t.type}" cannot be filled; use page.click`);oe(HTMLInputElement.prototype,t,s)}else if(t instanceof HTMLTextAreaElement)oe(HTMLTextAreaElement.prototype,t,s);else if(t instanceof HTMLSelectElement){let e=[...t.options].find(n=>n.value===s)??[...t.options].find(n=>k(n.textContent).toLowerCase()===k(s).toLowerCase());if(!e)throw new Error(`No option "${P(s,pe)}"`);oe(HTMLSelectElement.prototype,t,e.value)}else if(t instanceof HTMLElement&&t.isContentEditable){t.focus({preventScroll:!0}),t.textContent=s,t.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,inputType:"insertReplacementText",data:s}));return}else throw new Error("This element cannot be filled; use page.click");t.focus({preventScroll:!0}),t.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),t.dispatchEvent(new Event("change",{bubbles:!0}))}function oe(t,s,e){let n=Object.getOwnPropertyDescriptor(t,"value")?.set;n?n.call(s,e):s.value=e}function Oe(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?t.value:k(t.textContent)}function de(t){return t.disabled===!0||t.closest("fieldset[disabled]")!==null||t.getAttribute("aria-disabled")==="true"}function mt(t){if(t instanceof HTMLInputElement&&t.type==="password")return!0;if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement))return!1;if(ht.test(t.getAttribute("autocomplete")??""))return!0;let s=[t.name,t.id,t.getAttribute("aria-label"),t.placeholder].filter(Boolean).join(" ");return ut.test(s)}function bt(t){if(t instanceof HTMLInputElement&&t.type==="hidden"||t.closest("[hidden],[inert],[aria-hidden=true]"))return!1;for(let s=t;s;s=s.parentElement){let e=getComputedStyle(s);if(e.display==="none"||s===t&&(e.visibility==="hidden"||e.visibility==="collapse"))return!1}return!0}function wt(t){let s=t.getAttribute("role");if(s)return s;let e=t.tagName.toLowerCase();if(e==="a")return"link";if(e==="select")return"combobox";if(e==="textarea")return"textbox";if(e==="summary")return"button";if(t instanceof HTMLInputElement){let n=t.type;return n==="checkbox"||n==="radio"?n:n==="submit"||n==="button"||n==="reset"||n==="image"?"button":n==="search"?"searchbox":n==="range"?"slider":n==="text"?"textbox":`textbox:${n}`}return t.isContentEditable?"textbox":e}function yt(t){let s=t.getAttribute("aria-labelledby");if(s){let r=s.split(/\s+/).map(o=>k(document.getElementById(o)?.textContent)).filter(Boolean).join(" ");if(r)return r}let e=k(t.getAttribute("aria-label"));if(e)return e;let n=t.labels;if(n?.length){let r=k([...n].map(o=>o.textContent).join(" "));if(r)return r}return t instanceof HTMLInputElement&&["submit","button","reset"].includes(t.type)?k(t.value):(t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?"":k(t.textContent))||k(t.getAttribute("placeholder"))||k(t.getAttribute("title"))||k(t.querySelector("img[alt]")?.getAttribute("alt"))||k(t.getAttribute("name"))}function ae(t){let s=[wt(t),JSON.stringify(P(yt(t),le))];if(t instanceof HTMLInputElement&&(t.type==="checkbox"||t.type==="radio"))s.push(t.checked?"checked":"unchecked");else if(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){let e=Oe(t);e&&!(t instanceof HTMLInputElement&&["submit","button","reset"].includes(t.type))&&s.push(`value=${JSON.stringify(P(e,pe))}`)}return t instanceof HTMLAnchorElement&&s.push(`href=${JSON.stringify(P(t.getAttribute("href")??"",le))}`),de(t)&&s.push("disabled"),s.join(" ")}function He(t){return t===document.body||t===document.documentElement?null:t.scrollHeight>t.clientHeight?t:null}function ce(t){let s=He(t);return s===null?{scrollY:Math.round(window.scrollY),maxScrollY:Math.max(0,Math.round(document.documentElement.scrollHeight-window.innerHeight))}:{scrollY:Math.round(s.scrollTop),maxScrollY:Math.max(0,Math.round(s.scrollHeight-s.clientHeight))}}function B(t){let s=()=>{throw new Error("Job access is unavailable")};if(!t||typeof t!="object"||Array.isArray(t))return s();let e=t;if(typeof e.bootstrap_url!="string"||typeof e.launch_token!="string"||!/^[A-Za-z0-9_.-]{16,16384}$/.test(e.launch_token)||typeof e.expires_at!="string")return s();let n;try{n=new URL(e.bootstrap_url)}catch{return s()}if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/identity/job-access/launch"||n.href!==e.bootstrap_url)return s();let i=Date.parse(e.expires_at);return!Number.isFinite(i)||i<=Date.now()||i>Date.now()+6e4?s():{bootstrap_url:n.href,launch_token:e.launch_token,expires_at:e.expires_at}}var xt=new Set(["LINK_EXPIRED","LINK_REVOKED"]),vt=6e4,he=["content-type","authorization",W,F],E=class extends Error{constructor(e,n,i,r,o){super(e);f(this,"status",n);f(this,"code",i);f(this,"remediation",r);f(this,"retryAfterMs",o)}};function Et(t,s){if(typeof t=="number"&&Number.isFinite(t)&&t>0)return t;let e=Number(s.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e*1e3:void 0}var De=t=>({get(s){try{return t().getItem(s)}catch{return null}},set(s,e){try{t().setItem(s,e)}catch{}},del(s){try{t().removeItem(s)}catch{}}}),z=De(()=>localStorage),L=De(()=>sessionStorage),M=class{constructor(s){f(this,"o",s);f(this,"session",null);f(this,"config",null);f(this,"sessionPromise",null);f(this,"supersededSessions",new Map);f(this,"sessionGeneration",0);f(this,"refreshAt",new WeakMap)}url(s,e){let n=this.o.endpoint.replace(/\/+$/,""),i=e?"?"+new URLSearchParams(e).toString():"";return`${n}/${s}${i}`}get storageKey(){return`dewee-webchat:session:${this.o.endpoint}`}get reuseKey(){return`dewee-webchat:reuse:${this.o.endpoint}`}reuseHint(){return L.get(this.reuseKey)}request(s,e){return(this.o.fetch??globalThis.fetch)(s,e)}async headers(s=!1){let e={},n=typeof this.o.headers=="function"?await this.o.headers():this.o.headers;for(let[i,r]of Object.entries(n??{}))typeof r=="string"&&!he.includes(i.toLowerCase())&&(e[i.toLowerCase()]=r);if(e["content-type"]="application/json",this.o.gatewayUrl&&this.o.gatewayToken&&(e[W]=this.o.gatewayUrl,e[F]=this.o.gatewayToken),s){let i=await this.ensureSession();e.authorization=`Bearer ${i.token}`}return e}async parse(s){let e=await s.json().catch(()=>({}));if(!s.ok){let n=e?.error?.remediation,i=n&&typeof n.action=="string"&&typeof n.audience=="string"?{action:n.action,audience:n.audience}:void 0;throw new E(e?.error?.message||`HTTP ${s.status}`,s.status,e?.error?.code,i,Et(e?.error?.retryAfterMs,s))}return e}async imageUrl(s,e){let n=await this.request(this.url("image-ticket"),{method:"POST",headers:await this.headers(!0),body:JSON.stringify({url:s}),redirect:"error",signal:e}),i=await this.parse(n);if(typeof i.ticket!="string"||!/^[A-Za-z0-9_-]{1,8192}$/.test(i.ticket))throw new Error("Invalid image ticket");return this.url("image",{ticket:i.ticket})}async getConfig(s=!1,e=!1){return this.config&&!s?this.config:(this.config=await this.parse(await this.request(this.url("config",e?{pageContext:"1"}:void 0),{headers:await this.headers()})),this.config)}fresh(s){if(s.verified)return Date.now()<(this.refreshAt.get(s)??0);let e=typeof s.expiresIn=="number"&&s.expiresIn>=0&&s.obtainedAt,n=e?s.obtainedAt+s.expiresIn:s.expiresAt,i=e?s.expiresIn:s.obtainedAt?s.expiresAt-s.obtainedAt:1/0,r=Math.min(864e5,i/2,Math.max(3e4,i*.1));return n-Date.now()>r}scheduleRefresh(s,e){let n=typeof s.expiresIn=="number"&&s.expiresIn>0?s.expiresIn:s.expiresAt-e;this.refreshAt.set(s,e+n-Math.min(vt,n/2))}stored(){let s=z.get(this.storageKey);if(!s)return null;try{let e=JSON.parse(s);return e.verified?(z.del(this.storageKey),null):e}catch{return null}}visitorId(){return this.session?.visitorId??null}ensureSession(){if(this.sessionPromise)return this.sessionPromise;if(this.session&&this.fresh(this.session))return Promise.resolve(this.session);let s=this.sessionGeneration,e=this.loadSession(s).catch(n=>{if(s!==this.sessionGeneration)return this.supersededSessions.get(s);throw n}).finally(()=>{this.sessionPromise===e&&(this.sessionPromise=null),this.supersededSessions.delete(s)});return this.sessionPromise=e}async loadSession(s){if(!this.session){let e=this.stored();if(e){if(this.fresh(e)){let n=await this.getConfig();if(s!==this.sessionGeneration)return this.supersededSessions.get(s);if(!n.identity)return this.session=e}this.session=e}}return this.createSession(s)}async createSession(s){let e=await this.getConfig();if(s!==this.sessionGeneration)return this.supersededSessions.get(s);let n={},i=this.session&&!this.session.verified?this.session:this.stored();if(i?.token&&(n.token=i.token),e.identity){let l=this.session?.verified?this.session.reuseHint:L.get(this.reuseKey);l&&(n.reuseHint=l)}let r=async()=>this.parse(await this.request(this.url("session"),{method:"POST",headers:await this.headers(),body:JSON.stringify(n)})),o=async()=>{if(!this.o.turnstile)throw new E("Verification is required but no Turnstile handler is set",403,"turnstile_required");n.turnstileToken=await this.o.turnstile(e.turnstileSiteKey)},c;try{e.turnstileSiteKey&&!(e.refreshWithoutTurnstile&&!e.identity&&n.token&&!n.reuseHint)&&await o();try{c=await r()}catch(l){if(!(e.turnstileSiteKey&&!n.turnstileToken&&l instanceof E&&l.code==="turnstile_failed"))throw l;await o(),c=await r()}}catch(l){if(s!==this.sessionGeneration)return this.supersededSessions.get(s);throw this.session=null,l instanceof E&&l.status===401&&L.del(this.reuseKey),l}if(s!==this.sessionGeneration)return this.supersededSessions.get(s);let a=Date.now(),d={...c,obtainedAt:a};if(this.session=d,d.verified)this.scheduleRefresh(d,a),typeof d.reuseHint=="string"&&d.reuseHint!==""?L.set(this.reuseKey,d.reuseHint):L.del(this.reuseKey);else{L.del(this.reuseKey);let{reuseHint:l,...p}=d;z.set(this.storageKey,JSON.stringify(p))}return d}forgetSession(){if(this.session?.verified){L.del(this.reuseKey),this.session=null;return}this.session=null,z.del(this.storageKey)}async renewSession(){let s=this.sessionGeneration,e=this.sessionPromise;this.sessionGeneration++,this.session=null,this.sessionPromise=null;let n=this.ensureSession();return e&&this.supersededSessions.set(s,n),n}async jobAccess(s){try{if(!(await this.ensureSession()).verified)throw new E("Sign in to open job access",401,"IDENTITY_REQUIRED");if(s.aborted)throw new E("Job access was cancelled",0,"job_access_unavailable");let n=await this.request(this.url("job-access"),{method:"POST",headers:await this.headers(!0),body:"{}",signal:s,redirect:"error"});return B(await this.parse(n))}catch(e){let n=e instanceof E&&typeof e.code=="string"&&["IDENTITY_REQUIRED","LINK_EXPIRED","LINK_REVOKED","PERMISSION_DENIED","SOURCE_UNAVAILABLE"].includes(e.code)?e.code:"job_access_unavailable";throw new E("Job access is unavailable. Sign in again or retry.",e instanceof E?e.status:0,n)}}async link(){let s=await this.signedInRequest(async()=>this.request(this.url("link"),{method:"POST",headers:await this.headers(!0),body:"{}"}));return this.parse(s)}async history(s,e){let n=await this.signedInRequest(async()=>this.request(this.url("history",{agent:s,conversationId:e}),{headers:await this.headers(!0)}));return(await this.parse(n)).messages}async signedInRequest(s){await this.ensureSession();let e=await s();return e.status!==401||!this.session?.verified?e:(this.forgetSession(),await this.ensureSession(),s())}async chat(s,e,n){await this.ensureSession();let i=await this.request(this.url("chat"),{method:"POST",headers:await this.headers(!0),body:JSON.stringify(s),signal:n});if(i.status===401){let a=this.visitorId();this.forgetSession(),await this.ensureSession(),s.actionsHash&&this.visitorId()!==a&&(s={...s,actionsHash:void 0}),i=await this.request(this.url("chat"),{method:"POST",headers:await this.headers(!0),body:JSON.stringify(s),signal:n})}(!i.ok||!i.body)&&await this.parse(i);let r=i.body.pipeThrough(new TextDecoderStream).getReader(),o="",c=!1;for(;;){let{done:a,value:d}=await r.read();if(a)break;o+=d;let l;for(;(l=o.indexOf(`
16
+ `).slice(0,s)}function ie(n){if(n!==void 0)try{let s=JSON.stringify(n);return s===void 0?null:JSON.parse(s)}catch{return"[unserializable result]"}}var se=n=>n===null?"null":Array.isArray(n)?"array":typeof n=="number"?Number.isInteger(n)?"integer":"number":typeof n,pt=(n,s)=>{let e=se(n);return e===s||s==="number"&&e==="integer"};function B(n,s,e="args",t=0){if(!s||typeof s!="object")return null;if(t>32)return`${e}: schema is nested too deeply`;let i=s;if(i.type!==void 0){let r=Array.isArray(i.type)?i.type:[i.type];if(!r.some(o=>pt(n,o)))return`${e}: expected ${r.join(" or ")}, got ${se(n)}`}if(Array.isArray(i.enum)&&!i.enum.some(r=>Ie(r,n)))return`${e}: must be one of ${i.enum.map(r=>JSON.stringify(r)).join(", ")}`;if("const"in i&&!Ie(i.const,n))return`${e}: must equal ${JSON.stringify(i.const)}`;if(typeof n=="string"){if(typeof i.minLength=="number"&&n.length<i.minLength)return`${e}: shorter than ${i.minLength} characters`;if(typeof i.maxLength=="number"&&n.length>i.maxLength)return`${e}: longer than ${i.maxLength} characters`;if(typeof i.pattern=="string"){let r=null;try{r=new RegExp(i.pattern,"u")}catch{return`${e}: schema pattern is invalid`}if(!r.test(n))return`${e}: does not match ${i.pattern}`}}if(typeof n=="number"){if(typeof i.minimum=="number"&&n<i.minimum)return`${e}: must be >= ${i.minimum}`;if(typeof i.maximum=="number"&&n>i.maximum)return`${e}: must be <= ${i.maximum}`}if(Array.isArray(n)){if(typeof i.minItems=="number"&&n.length<i.minItems)return`${e}: needs at least ${i.minItems} items`;if(typeof i.maxItems=="number"&&n.length>i.maxItems)return`${e}: allows at most ${i.maxItems} items`;if(i.items&&typeof i.items=="object")for(let r=0;r<n.length;r++){let o=B(n[r],i.items,`${e}[${r}]`,t+1);if(o)return o}}if(se(n)==="object"){let r=n,o=i.properties&&typeof i.properties=="object"?i.properties:{};for(let c of Array.isArray(i.required)?i.required:[])if(!(c in r))return`${e}.${c}: is required`;for(let[c,a]of Object.entries(r))if(Object.prototype.hasOwnProperty.call(o,c)){let d=B(a,o[c],`${e}.${c}`,t+1);if(d)return d}else if(i.additionalProperties===!1)return`${e}.${c}: is not allowed`}return null}function Ie(n,s){return JSON.stringify(n)===JSON.stringify(s)}var Me=/^[a-z][a-z0-9_.-]{0,63}$/,re=["read","navigate","mutate","destructive"],T={maxActions:32,maxDescription:1e3,maxParametersBytes:4096,maxManifestBytes:16384,maxPageContextBytes:4096},ht="[[dewee-page v1]]",_e="[[/dewee-page]]";function oe(n){if(!n.startsWith(ht))return n;let s=n.indexOf(`
17
+ `+_e);return s<0?n:n.slice(s+_e.length+1).replace(/^\n+/,"")}var gt=n=>n==="mutate"||n==="destructive",D=class{constructor(){f(this,"map",new Map)}get size(){return this.map.size}get(s){return this.map.get(s)}names(){return[...this.map.keys()]}register(s){let e=Array.isArray(s)?s:[s];for(let t of e)ft(t);if(new Set([...this.map.keys(),...e.map(t=>t.name)]).size>T.maxActions)throw new TypeError(`dewee-webchat: at most ${T.maxActions} page actions`);for(let t of e)this.map.set(t.name,t)}unregister(s){return this.map.delete(s)}manifest(){return[...this.map.values()].map(s=>({name:s.name,description:s.description,sensitivity:s.sensitivity,parameters:s.parameters??{type:"object",properties:{}}}))}};function ft(n){let s=e=>{throw new TypeError(`dewee-webchat: invalid page action ${JSON.stringify(n?.name)}: ${e}`)};(!n||typeof n!="object")&&s("not an object"),(typeof n.name!="string"||!Me.test(n.name))&&s("name must match ^[a-z][a-z0-9_.-]{0,63}$"),(typeof n.description!="string"||n.description.length>T.maxDescription)&&s(`description must be a string up to ${T.maxDescription} chars`),re.includes(n.sensitivity)||s(`sensitivity must be one of ${re.join(", ")}`),typeof n.handler!="function"&&s("handler must be a function"),n.parameters!==void 0&&(typeof n.parameters!="object"||n.parameters===null||Array.isArray(n.parameters))&&s("parameters must be a JSON Schema object")}async function Oe(n,s){let e=a=>(s.onStatus?.("error"),{id:n.id,name:n.name,status:"error",error:a});if(!n.ok)return e(n.error);if(s.signal.aborted)return e("Cancelled");let t=s.registry.get(n.name);if(!t)return e(`Unknown action "${n.name}". Available: ${s.registry.names().join(", ")||"none"}`);let i=B(n.args,t.parameters??{type:"object"});if(i)return e(`Invalid arguments: ${i}`);if(gt(t.sensitivity)){s.onStatus?.("awaiting-confirmation");let{handler:a,...d}=t,l=!1;try{l=await Ne(Promise.resolve(s.confirm({...d,callId:n.id},n.args)),s.signal)===!0}catch{l=!1}if(!l||s.signal.aborted)return s.onStatus?.("denied"),{id:n.id,name:n.name,status:"denied",error:"The user declined this action."}}s.onStatus?.("running");let r=new AbortController,o=()=>r.abort();s.signal.addEventListener("abort",o,{once:!0});let c=setTimeout(o,s.timeoutMs??3e4);try{let a=await Ne(Promise.resolve().then(()=>t.handler(n.args,{callId:n.id,conversationId:s.conversationId,agent:s.agent,signal:r.signal})),r.signal);return s.onStatus?.("done"),{id:n.id,name:n.name,status:"ok",result:ie(a)??null}}catch(a){return e(r.signal.aborted?s.signal.aborted?"Cancelled":"Timed out":String(a?.message??a).slice(0,500)||"Action failed")}finally{clearTimeout(c),s.signal.removeEventListener("abort",o)}}function Ne(n,s){return s.aborted?Promise.reject(new Error("aborted")):new Promise((e,t)=>{let i=()=>t(new Error("aborted"));s.addEventListener("abort",i,{once:!0}),n.then(e,t).finally(()=>s.removeEventListener("abort",i))})}var De=["page.snapshot","page.scroll","page.click","page.fill"],mt=["a[href]","button","input","select","textarea","summary","[contenteditable]:not([contenteditable=false])",...["button","link","checkbox","radio","switch","tab","menuitem","option","combobox","textbox","searchbox"].map(n=>`[role=${n}]`)].join(","),bt=new Set(["checkbox","radio","file","submit","button","image","reset","hidden","password"]),wt=/\b(cc-[a-z-]+|one-time-code|current-password|new-password)\b/i,yt=/(passw|passcode|\bpin\b|otp|one.?time|cvv|cvc|card.?(num|no)|cc.?num|security.?code|\bssn\b)/i,pe=80,ge=60,xt=40,I=(n,s)=>n.length>s?n.slice(0,s-1)+"\u2026":n,E=n=>(n??"").replace(/\s+/g," ").trim(),ae={type:"string",pattern:"^e[0-9]{1,4}$"},ce={type:"integer",minimum:1};function He(n){let s=0,e=new Map,t=()=>{let l=n.root(),u=typeof l=="string"?document.querySelector(l):l;if(l!==void 0&&!u)throw new Error(`domActionsRoot ${JSON.stringify(l)} matches no element`);return u??document.body},i=(l,u)=>l.isConnected&&u.contains(l)&&!n.exclude?.(l)&&!l.closest("[data-dewee-ignore]")&&!Ct(l)&&Et(l),r=l=>{if(l.generation!==s)throw new Error(`Stale ref: generation ${l.generation} is not the latest snapshot (${s||"none"}). Call page.snapshot again.`);let u=e.get(l.ref);if(!u)throw new Error(`Unknown ref "${l.ref}". Call page.snapshot again.`);if(!i(u,t()))throw new Error(`Ref "${l.ref}" is no longer available. Call page.snapshot again.`);return u};return{actions:[{name:"page.snapshot",description:'List the interactive elements visible on the page (links, buttons, form fields) as lines `ref role "name" [state]`. Use the ref together with the returned generation in page.scroll, page.click and page.fill. Every snapshot invalidates older refs. Use query to filter by visible name, offset/limit to page through long lists.',sensitivity:"read",parameters:{type:"object",properties:{query:{type:"string",maxLength:100},offset:{type:"integer",minimum:0},limit:{type:"integer",minimum:1,maximum:100}},additionalProperties:!1},handler:({query:l,offset:u=0,limit:g=xt})=>{let p=t();s++,e=new Map;let h=E(l).toLowerCase(),m=[],b=0;for(let x of p.querySelectorAll(mt)){if(!i(x,p))continue;let w=de(x);if(h&&!w.toLowerCase().includes(h)||(b++,b<=u||m.length>=g))continue;let y=`e${b}`;e.set(y,x),m.push(`${y} ${w}`)}return{generation:s,url:location.pathname+location.search,title:I(document.title,pe),total:b,offset:u,elements:m,...ue(p)}}},{name:"page.scroll",description:"Scroll the page by about one screen (direction up/down) or to the top/bottom, or scroll an element from page.snapshot into view (ref + generation).",sensitivity:"read",parameters:{type:"object",properties:{direction:{type:"string",enum:["up","down","top","bottom"]},ref:ae,generation:ce},additionalProperties:!1},handler:({direction:l,ref:u,generation:g})=>{let p=t();if(u!==void 0){if(g===void 0)throw new Error("generation is required with ref");return r({ref:u,generation:g}).scrollIntoView?.({block:"center",inline:"nearest"}),{ref:u,...ue(p)}}if(!l)throw new Error("Give a direction or a ref");let h=$e(p),m=h===null?window.innerHeight:h.clientHeight,b=h===null?window.scrollY:h.scrollTop,x=h===null?document.documentElement.scrollHeight:h.scrollHeight,w=l==="top"?0:l==="bottom"?x:b+(l==="down"?.8:-.8)*m;return h===null?window.scrollTo({top:w}):h.scrollTop=w,{direction:l,...ue(p)}}},{name:"page.click",description:"Click an element from page.snapshot (ref + generation). The visitor approves every click.",sensitivity:"mutate",parameters:{type:"object",properties:{ref:ae,generation:ce},required:["ref","generation"],additionalProperties:!1},handler:l=>{let u=r(l);if(he(u))throw new Error(`Ref "${l.ref}" is disabled`);return u.scrollIntoView?.({block:"center",inline:"nearest"}),u instanceof HTMLElement?(u.focus({preventScroll:!0}),u.click()):u.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,composed:!0})),{ref:l.ref,clicked:de(u)}}},{name:"page.fill",description:"Replace the value of a text field, textarea, select (option value or label) or editable area from page.snapshot (ref + generation). The visitor approves every fill.",sensitivity:"mutate",parameters:{type:"object",properties:{ref:ae,generation:ce,text:{type:"string",maxLength:1e4}},required:["ref","generation","text"],additionalProperties:!1},handler:l=>{let u=r(l);if(he(u)||u.readOnly)throw new Error(`Ref "${l.ref}" is not editable`);return vt(u,l.text),{ref:l.ref,value:I(qe(u),ge)}}}],target:l=>{try{return de(r(l))}catch{return}}}}function vt(n,s){if(n instanceof HTMLInputElement){if(bt.has(n.type))throw new Error(`Inputs of type "${n.type}" cannot be filled; use page.click`);le(HTMLInputElement.prototype,n,s)}else if(n instanceof HTMLTextAreaElement)le(HTMLTextAreaElement.prototype,n,s);else if(n instanceof HTMLSelectElement){let e=[...n.options].find(t=>t.value===s)??[...n.options].find(t=>E(t.textContent).toLowerCase()===E(s).toLowerCase());if(!e)throw new Error(`No option "${I(s,ge)}"`);le(HTMLSelectElement.prototype,n,e.value)}else if(n instanceof HTMLElement&&n.isContentEditable){n.focus({preventScroll:!0}),n.textContent=s,n.dispatchEvent(new InputEvent("input",{bubbles:!0,composed:!0,inputType:"insertReplacementText",data:s}));return}else throw new Error("This element cannot be filled; use page.click");n.focus({preventScroll:!0}),n.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}function le(n,s,e){let t=Object.getOwnPropertyDescriptor(n,"value")?.set;t?t.call(s,e):s.value=e}function qe(n){return n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement?n.value:E(n.textContent)}function he(n){return n.disabled===!0||n.closest("fieldset[disabled]")!==null||n.getAttribute("aria-disabled")==="true"}function Ct(n){if(n instanceof HTMLInputElement&&n.type==="password")return!0;if(!(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement))return!1;if(wt.test(n.getAttribute("autocomplete")??""))return!0;let s=[n.name,n.id,n.getAttribute("aria-label"),n.placeholder].filter(Boolean).join(" ");return yt.test(s)}function Et(n){if(n instanceof HTMLInputElement&&n.type==="hidden"||n.closest("[hidden],[inert],[aria-hidden=true]"))return!1;for(let s=n;s;s=s.parentElement){let e=getComputedStyle(s);if(e.display==="none"||s===n&&(e.visibility==="hidden"||e.visibility==="collapse"))return!1}return!0}function kt(n){let s=n.getAttribute("role");if(s)return s;let e=n.tagName.toLowerCase();if(e==="a")return"link";if(e==="select")return"combobox";if(e==="textarea")return"textbox";if(e==="summary")return"button";if(n instanceof HTMLInputElement){let t=n.type;return t==="checkbox"||t==="radio"?t:t==="submit"||t==="button"||t==="reset"||t==="image"?"button":t==="search"?"searchbox":t==="range"?"slider":t==="text"?"textbox":`textbox:${t}`}return n.isContentEditable?"textbox":e}function At(n){let s=n.getAttribute("aria-labelledby");if(s){let r=s.split(/\s+/).map(o=>E(document.getElementById(o)?.textContent)).filter(Boolean).join(" ");if(r)return r}let e=E(n.getAttribute("aria-label"));if(e)return e;let t=n.labels;if(t?.length){let r=E([...t].map(o=>o.textContent).join(" "));if(r)return r}return n instanceof HTMLInputElement&&["submit","button","reset"].includes(n.type)?E(n.value):(n instanceof HTMLSelectElement||n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?"":E(n.textContent))||E(n.getAttribute("placeholder"))||E(n.getAttribute("title"))||E(n.querySelector("img[alt]")?.getAttribute("alt"))||E(n.getAttribute("name"))}function de(n){let s=[kt(n),JSON.stringify(I(At(n),pe))];if(n instanceof HTMLInputElement&&(n.type==="checkbox"||n.type==="radio"))s.push(n.checked?"checked":"unchecked");else if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){let e=qe(n);e&&!(n instanceof HTMLInputElement&&["submit","button","reset"].includes(n.type))&&s.push(`value=${JSON.stringify(I(e,ge))}`)}return n instanceof HTMLAnchorElement&&s.push(`href=${JSON.stringify(I(n.getAttribute("href")??"",pe))}`),he(n)&&s.push("disabled"),s.join(" ")}function $e(n){return n===document.body||n===document.documentElement?null:n.scrollHeight>n.clientHeight?n:null}function ue(n){let s=$e(n);return s===null?{scrollY:Math.round(window.scrollY),maxScrollY:Math.max(0,Math.round(document.documentElement.scrollHeight-window.innerHeight))}:{scrollY:Math.round(s.scrollTop),maxScrollY:Math.max(0,Math.round(s.scrollHeight-s.clientHeight))}}function j(n){let s=()=>{throw new Error("Job access is unavailable")};if(!n||typeof n!="object"||Array.isArray(n))return s();let e=n;if(typeof e.bootstrap_url!="string"||typeof e.launch_token!="string"||!/^[A-Za-z0-9_.-]{16,16384}$/.test(e.launch_token)||typeof e.expires_at!="string")return s();let t;try{t=new URL(e.bootstrap_url)}catch{return s()}if(t.protocol!=="https:"||t.username||t.password||t.search||t.hash||t.pathname!=="/identity/job-access/launch"||t.href!==e.bootstrap_url)return s();let i=Date.parse(e.expires_at);return!Number.isFinite(i)||i<=Date.now()||i>Date.now()+6e4?s():{bootstrap_url:t.href,launch_token:e.launch_token,expires_at:e.expires_at}}var St=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Tt=new Set(["pending","applying","resolved","cancelled","expired","failed"]),V=n=>n&&typeof n=="object"&&!Array.isArray(n)?n:null,S=(n,s)=>typeof n=="string"&&n.length<=s,Be=n=>S(n,64)&&Number.isFinite(Date.parse(n));function z(n,s){let e=V(n),t=V(e?.target);if(!e||!t||!S(e.id,36)||!St.test(e.id)||e.schema_version!=="webchat-credential-request.v1"||typeof e.status!="string"||!Tt.has(e.status)||!S(e.title,300)||!S(e.purpose,4e3)||!S(t.type,100)||!S(t.mode,100)||!Array.isArray(e.fields)||e.fields.length>32||!Be(e.expires_at)||e.agent_key!==s||e.completion!=="hosted"||typeof e.resumable!="boolean")return null;let i=[];for(let r of e.fields){let o=V(r);if(!o||!S(o.key,100)||!/^[A-Za-z0-9_.-]+$/.test(o.key)||!S(o.label,300)||!S(o.kind,100)||typeof o.required!="boolean")return null;i.push({key:o.key,label:o.label,kind:o.kind,required:o.required})}return{id:e.id,schema_version:"webchat-credential-request.v1",status:e.status,title:e.title,purpose:e.purpose,target:{type:t.type,mode:t.mode},fields:i,expires_at:e.expires_at,agent_key:s,completion:"hosted",resumable:e.resumable}}function je(n,s,e){let t=V(n);if(!t||t.credential_request_id!==s||!S(t.url,4096)||!Be(t.expires_at)||Date.parse(t.expires_at)<=Date.now())return null;try{let i=new URL(t.url);return i.protocol!=="https:"||i.origin!==e||i.username||i.password||i.hash||i.pathname!=="/credential-requests/open"||!/^\?token=[A-Za-z0-9_-]{43}$/.test(i.search)?null:{credential_request_id:s,url:i.href,expires_at:t.expires_at}}catch{return null}}var Pt=new Set(["LINK_EXPIRED","LINK_REVOKED"]),Rt=6e4,fe=["content-type","authorization",X,Z],v=class extends Error{constructor(e,t,i,r,o){super(e);f(this,"status",t);f(this,"code",i);f(this,"remediation",r);f(this,"retryAfterMs",o)}};function Lt(n,s){if(typeof n=="number"&&Number.isFinite(n)&&n>0)return n;let e=Number(s.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e*1e3:void 0}var Ve=n=>({get(s){try{return n().getItem(s)}catch{return null}},set(s,e){try{n().setItem(s,e)}catch{}},del(s){try{n().removeItem(s)}catch{}}}),U=Ve(()=>localStorage),L=Ve(()=>sessionStorage),_=class{constructor(s){f(this,"o",s);f(this,"session",null);f(this,"config",null);f(this,"sessionPromise",null);f(this,"supersededSessions",new Map);f(this,"sessionGeneration",0);f(this,"refreshAt",new WeakMap)}url(s,e){let t=this.o.endpoint.replace(/\/+$/,""),i=e?"?"+new URLSearchParams(e).toString():"";return`${t}/${s}${i}`}get storageKey(){return`dewee-webchat:session:${this.o.endpoint}`}get reuseKey(){return`dewee-webchat:reuse:${this.o.endpoint}`}reuseHint(){return L.get(this.reuseKey)}request(s,e){return(this.o.fetch??globalThis.fetch)(s,e)}async headers(s=!1){let e={},t=typeof this.o.headers=="function"?await this.o.headers():this.o.headers;for(let[i,r]of Object.entries(t??{}))typeof r=="string"&&!fe.includes(i.toLowerCase())&&(e[i.toLowerCase()]=r);if(e["content-type"]="application/json",this.o.gatewayUrl&&this.o.gatewayToken&&(e[X]=this.o.gatewayUrl,e[Z]=this.o.gatewayToken),s){let i=await this.ensureSession();e.authorization=`Bearer ${i.token}`}return e}async parse(s){let e=await s.json().catch(()=>({}));if(!s.ok){let t=e?.error?.remediation,i=t&&typeof t.action=="string"&&typeof t.audience=="string"?{action:t.action,audience:t.audience}:void 0;throw new v(e?.error?.message||`HTTP ${s.status}`,s.status,e?.error?.code,i,Lt(e?.error?.retryAfterMs,s))}return e}async imageUrl(s,e){let t=await this.request(this.url("image-ticket"),{method:"POST",headers:await this.headers(!0),body:JSON.stringify({url:s}),redirect:"error",signal:e}),i=await this.parse(t);if(typeof i.ticket!="string"||!/^[A-Za-z0-9_-]{1,8192}$/.test(i.ticket))throw new Error("Invalid image ticket");return this.url("image",{ticket:i.ticket})}async getConfig(s=!1,e=!1){return this.config&&!s?this.config:(this.config=await this.parse(await this.request(this.url("config",e?{pageContext:"1"}:void 0),{headers:await this.headers()})),this.config)}fresh(s){if(s.verified)return Date.now()<(this.refreshAt.get(s)??0);let e=typeof s.expiresIn=="number"&&s.expiresIn>=0&&s.obtainedAt,t=e?s.obtainedAt+s.expiresIn:s.expiresAt,i=e?s.expiresIn:s.obtainedAt?s.expiresAt-s.obtainedAt:1/0,r=Math.min(864e5,i/2,Math.max(3e4,i*.1));return t-Date.now()>r}scheduleRefresh(s,e){let t=typeof s.expiresIn=="number"&&s.expiresIn>0?s.expiresIn:s.expiresAt-e;this.refreshAt.set(s,e+t-Math.min(Rt,t/2))}stored(){let s=U.get(this.storageKey);if(!s)return null;try{let e=JSON.parse(s);return e.verified?(U.del(this.storageKey),null):e}catch{return null}}visitorId(){return this.session?.visitorId??null}ensureSession(){if(this.sessionPromise)return this.sessionPromise;if(this.session&&this.fresh(this.session))return Promise.resolve(this.session);let s=this.sessionGeneration,e=this.loadSession(s).catch(t=>{if(s!==this.sessionGeneration)return this.supersededSessions.get(s);throw t}).finally(()=>{this.sessionPromise===e&&(this.sessionPromise=null),this.supersededSessions.delete(s)});return this.sessionPromise=e}async loadSession(s){if(!this.session){let e=this.stored();if(e){if(this.fresh(e)){let t=await this.getConfig();if(s!==this.sessionGeneration)return this.supersededSessions.get(s);if(!t.identity)return this.session=e}this.session=e}}return this.createSession(s)}async createSession(s){let e=await this.getConfig();if(s!==this.sessionGeneration)return this.supersededSessions.get(s);let t={},i=this.session&&!this.session.verified?this.session:this.stored();if(i?.token&&(t.token=i.token),e.identity){let l=this.session?.verified?this.session.reuseHint:L.get(this.reuseKey);l&&(t.reuseHint=l)}let r=async()=>this.parse(await this.request(this.url("session"),{method:"POST",headers:await this.headers(),body:JSON.stringify(t)})),o=async()=>{if(!this.o.turnstile)throw new v("Verification is required but no Turnstile handler is set",403,"turnstile_required");t.turnstileToken=await this.o.turnstile(e.turnstileSiteKey)},c;try{e.turnstileSiteKey&&!(e.refreshWithoutTurnstile&&!e.identity&&t.token&&!t.reuseHint)&&await o();try{c=await r()}catch(l){if(!(e.turnstileSiteKey&&!t.turnstileToken&&l instanceof v&&l.code==="turnstile_failed"))throw l;await o(),c=await r()}}catch(l){if(s!==this.sessionGeneration)return this.supersededSessions.get(s);throw this.session=null,l instanceof v&&l.status===401&&L.del(this.reuseKey),l}if(s!==this.sessionGeneration)return this.supersededSessions.get(s);let a=Date.now(),d={...c,obtainedAt:a};if(this.session=d,d.verified)this.scheduleRefresh(d,a),typeof d.reuseHint=="string"&&d.reuseHint!==""?L.set(this.reuseKey,d.reuseHint):L.del(this.reuseKey);else{L.del(this.reuseKey);let{reuseHint:l,...u}=d;U.set(this.storageKey,JSON.stringify(u))}return d}forgetSession(){if(this.session?.verified){L.del(this.reuseKey),this.session=null;return}this.session=null,U.del(this.storageKey)}async renewSession(){let s=this.sessionGeneration,e=this.sessionPromise;this.sessionGeneration++,this.session=null,this.sessionPromise=null;let t=this.ensureSession();return e&&this.supersededSessions.set(s,t),t}async jobAccess(s){try{if(!(await this.ensureSession()).verified)throw new v("Sign in to open job access",401,"IDENTITY_REQUIRED");if(s.aborted)throw new v("Job access was cancelled",0,"job_access_unavailable");let t=await this.request(this.url("job-access"),{method:"POST",headers:await this.headers(!0),body:"{}",signal:s,redirect:"error"});return j(await this.parse(t))}catch(e){let t=e instanceof v&&typeof e.code=="string"&&["IDENTITY_REQUIRED","LINK_EXPIRED","LINK_REVOKED","PERMISSION_DENIED","SOURCE_UNAVAILABLE"].includes(e.code)?e.code:"job_access_unavailable";throw new v("Job access is unavailable. Sign in again or retry.",e instanceof v?e.status:0,t)}}async link(){let s=await this.signedInRequest(async()=>this.request(this.url("link"),{method:"POST",headers:await this.headers(!0),body:"{}"}));return this.parse(s)}async history(s,e){return(await this.historyDetails(s,e)).messages}async historyDetails(s,e){let t=await this.signedInRequest(async()=>this.request(this.url("history",{agent:s,conversationId:e}),{headers:await this.headers(!0)})),i=await this.parse(t),r=this.session?.verified&&this.config?.credentialFormOrigin&&Array.isArray(i.credentialRequests)?i.credentialRequests.slice(0,100).map(o=>z(o,s)).filter(o=>o!==null):[];return{messages:i.messages,credentialRequests:r}}async credentialRequest(s,e,t,i,r){let o=await this.ensureSession(),c=(await this.getConfig()).credentialFormOrigin;if(!o.verified||!c)throw new v("Credential request is unavailable",403,"credential_request_unavailable");try{let a=await this.headers(!0);if(this.session!==o)throw new Error("identity changed");let d=await this.request(this.url(s),{method:"POST",headers:a,body:JSON.stringify({agent:e,conversationId:t,credentialRequestId:i}),redirect:"error",signal:r}),l=await this.parse(d);if(this.session!==o)throw new Error("identity changed");let u=s==="credential-request-handoff"?je(l,i,c):z(l.credentialRequest,e);if(!u||"id"in u&&u.id!==i)throw new Error("invalid credential request");return u}catch(a){let d=a instanceof v&&["credential_requests_unavailable","credential_request_not_found","credential_request_not_ready","credential_request_resumed"].includes(a.code??"")?a.code:"credential_request_unavailable";throw new v("Credential request is unavailable",a instanceof v?a.status:0,d)}}async signedInRequest(s){await this.ensureSession();let e=await s();return e.status!==401||!this.session?.verified?e:(this.forgetSession(),await this.ensureSession(),s())}async chat(s,e,t){await this.ensureSession();let i=await this.request(this.url("chat"),{method:"POST",headers:await this.headers(!0),body:JSON.stringify(s),signal:t});if(i.status===401&&!s.credentialRequestId){let a=this.visitorId();this.forgetSession(),await this.ensureSession(),s.actionsHash&&this.visitorId()!==a&&(s={...s,actionsHash:void 0}),i=await this.request(this.url("chat"),{method:"POST",headers:await this.headers(!0),body:JSON.stringify(s),signal:t})}(!i.ok||!i.body)&&await this.parse(i);let r=i.body.pipeThrough(new TextDecoderStream).getReader(),o="",c=!1;for(;;){let{done:a,value:d}=await r.read();if(a)break;o+=d;let l;for(;(l=o.indexOf(`
18
18
 
19
- `))>=0;){let p=o.slice(0,l);o=o.slice(l+2);let g=p.split(`
20
- `).filter(u=>u.startsWith("data:")).map(u=>u.slice(5).trimStart()).join(`
21
- `);if(!g)continue;let h;try{h=JSON.parse(g)}catch{continue}h.type==="error"&&h.code&&xt.has(h.code)&&(c=!0);try{e(h)}catch{}}}c&&this.session?.verified&&(this.forgetSession(),await this.ensureSession().catch(()=>{}))}};var A=class extends Error{constructor(e){super("Job access could not be opened");f(this,"code",e)}};async function $e(t,s){let e=`dewee-job-access-${crypto.randomUUID()}`,n;try{n=window.open("about:blank",e,"popup,width=720,height=800")}catch{throw new A("popup_blocked")}if(!n)throw new A("popup_blocked");let i=new AbortController,r=()=>i.abort(),o,c=new Promise((w,y)=>{o=()=>y(new A(n.closed?"popup_closed":"job_access_unavailable"))});i.signal.addEventListener("abort",o,{once:!0}),s?.addEventListener("abort",r,{once:!0});let a=setTimeout(r,3e4),d=!1,l,p,g=new Promise((w,y)=>{l=w,p=()=>y(new A("job_access_unavailable"))}),h=setInterval(()=>{if(n.closed){r();return}if(d)try{n.location.href!=="about:blank"&&l()}catch{l()}},200);window.addEventListener("pagehide",r,{once:!0});let u,m,b,x=w=>{w.disposition==="enforce"&&(w.effectiveDirective==="form-action"||w.violatedDirective==="form-action")&&p()};try{n.opener=null,s?.aborted&&r();let w=B(await Promise.race([t(i.signal),c]));if(n.closed)throw new A("popup_closed");if(i.signal.aborted)throw new A("job_access_unavailable");b=n.document;let y=b.createElement("meta");y.name="referrer",y.content="strict-origin",b.head.append(y),u=b.createElement("form"),u.method="POST",u.action=w.bootstrap_url,u.target="_self",u.hidden=!0,m=b.createElement("input"),m.type="hidden",m.name="launch_token",m.value=w.launch_token,u.append(m),b.body.append(u),b.addEventListener("securitypolicyviolation",x),HTMLFormElement.prototype.submit.call(u),d=!0,m.value="",w.launch_token="",u.remove(),await Promise.race([g,c])}catch(w){let y=n.closed;try{n.close()}catch{}throw y?new A("popup_closed"):(w instanceof A,w)}finally{m&&(m.value=""),u?.remove(),b?.removeEventListener("securitypolicyviolation",x),clearTimeout(a),clearInterval(h),window.removeEventListener("pagehide",r),s?.removeEventListener("abort",r),i.signal.removeEventListener("abort",o),i.abort()}}var kt=0;function je(t,s,e,n,i){let r=`dw-confirm-${++kt}`,o=t.getRootNode(),c=o.activeElement,a=document.createElement("div");a.className="confirm-backdrop",a.innerHTML=`
19
+ `))>=0;){let u=o.slice(0,l);o=o.slice(l+2);let g=u.split(`
20
+ `).filter(h=>h.startsWith("data:")).map(h=>h.slice(5).trimStart()).join(`
21
+ `);if(!g)continue;let p;try{p=JSON.parse(g)}catch{continue}if(p.type==="credential_request"){let h=this.session?.verified&&this.config?.credentialFormOrigin?z(p.credentialRequest,s.agent):null;if(!h)continue;p={type:"credential_request",credentialRequest:h}}p.type==="error"&&p.code&&Pt.has(p.code)&&(c=!0);try{e(p)}catch{}}}c&&this.session?.verified&&(this.forgetSession(),await this.ensureSession().catch(()=>{}))}};var k=class extends Error{constructor(e){super("Job access could not be opened");f(this,"code",e)}};async function ze(n,s){let e=`dewee-job-access-${crypto.randomUUID()}`,t;try{t=window.open("about:blank",e,"popup,width=720,height=800")}catch{throw new k("popup_blocked")}if(!t)throw new k("popup_blocked");let i=new AbortController,r=()=>i.abort(),o,c=new Promise((w,y)=>{o=()=>y(new k(t.closed?"popup_closed":"job_access_unavailable"))});i.signal.addEventListener("abort",o,{once:!0}),s?.addEventListener("abort",r,{once:!0});let a=setTimeout(r,3e4),d=!1,l,u,g=new Promise((w,y)=>{l=w,u=()=>y(new k("job_access_unavailable"))}),p=setInterval(()=>{if(t.closed){r();return}if(d)try{t.location.href!=="about:blank"&&l()}catch{l()}},200);window.addEventListener("pagehide",r,{once:!0});let h,m,b,x=w=>{w.disposition==="enforce"&&(w.effectiveDirective==="form-action"||w.violatedDirective==="form-action")&&u()};try{t.opener=null,s?.aborted&&r();let w=j(await Promise.race([n(i.signal),c]));if(t.closed)throw new k("popup_closed");if(i.signal.aborted)throw new k("job_access_unavailable");b=t.document;let y=b.createElement("meta");y.name="referrer",y.content="strict-origin",b.head.append(y),h=b.createElement("form"),h.method="POST",h.action=w.bootstrap_url,h.target="_self",h.hidden=!0,m=b.createElement("input"),m.type="hidden",m.name="launch_token",m.value=w.launch_token,h.append(m),b.body.append(h),b.addEventListener("securitypolicyviolation",x),HTMLFormElement.prototype.submit.call(h),d=!0,m.value="",w.launch_token="",h.remove(),await Promise.race([g,c])}catch(w){let y=t.closed;try{t.close()}catch{}throw y?new k("popup_closed"):(w instanceof k,w)}finally{m&&(m.value=""),h?.remove(),b?.removeEventListener("securitypolicyviolation",x),clearTimeout(a),clearInterval(p),window.removeEventListener("pagehide",r),s?.removeEventListener("abort",r),i.signal.removeEventListener("abort",o),i.abort()}}var It=0;function Ue(n,s,e,t,i){let r=`dw-confirm-${++It}`,o=n.getRootNode(),c=o.activeElement,a=document.createElement("div");a.className="confirm-backdrop",a.innerHTML=`
22
22
  <div class="confirm" role="alertdialog" aria-modal="true" aria-labelledby="${r}-t" aria-describedby="${r}-d">
23
23
  <h3 id="${r}-t"></h3>
24
24
  <div id="${r}-d" class="confirm-desc">
@@ -31,12 +31,12 @@
31
31
  <button type="button" class="btn deny"></button>
32
32
  <button type="button" class="btn allow"></button>
33
33
  </div>
34
- </div>`;let d=m=>a.querySelector(m);d("h3").textContent=s.confirmTitle,d("code").textContent=e.name;let l=d(".sens");if(l.textContent=e.sensitivity,l.dataset.level=e.sensitivity,d(".confirm-text").textContent=e.description,e.sensitivity==="destructive"){let m=d(".confirm-warn");m.hidden=!1,m.textContent=s.confirmDestructive}let p=JSON.stringify(n,null,2),g=d(".confirm-args");p&&p!=="{}"?g.textContent=p:g.remove();let h=d(".deny"),u=d(".allow");return h.textContent=s.deny,u.textContent=s.allow,e.sensitivity==="destructive"&&u.classList.add("danger"),new Promise(m=>{let b=!1,x=y=>{b||(b=!0,i?.removeEventListener("abort",w),a.remove(),c?.focus?.(),m(y))},w=()=>x(!1);if(i?.aborted)return x(!1);i?.addEventListener("abort",w,{once:!0}),h.addEventListener("click",()=>x(!1)),u.addEventListener("click",()=>x(!0)),a.addEventListener("keydown",y=>{y.key==="Escape"?(y.preventDefault(),y.stopPropagation(),x(!1)):y.key==="Tab"&&(y.preventDefault(),(o.activeElement===h?u:h).focus())}),t.appendChild(a),h.focus()})}var At={title:"Assistant",greeting:"Hi there \u{1F44B}",greetingBody:"Ask me anything. I can look things up and use tools to help you.",placeholder:"Type a message\u2026",send:"Send",stop:"Stop",newChat:"New conversation",close:"Close chat",open:"Open chat",thinking:"Thinking\u2026",thoughtFor:t=>`Thought for ${t}s`,reasoning:"Reasoning",toolRunning:"running",toolDone:"done",toolError:"error",args:"Arguments",result:"Result",online:"Online",poweredBy:"Powered by",errorGeneric:"Something went wrong. Please try again.",stopped:"Stopped.",actionStatus:{pending:"queued","awaiting-confirmation":"needs approval",running:"running",done:"done",denied:"declined",error:"failed"},confirmTitle:"Allow this action?",confirmDestructive:"This can't be undone.",allow:"Allow",deny:"Deny",actionLimit:t=>`Stopped after ${t} automatic action rounds. Send a message to continue.`,identityErrors:{IDENTITY_REQUIRED:"Please sign in to chat.",IDENTITY_LINK_REQUIRED:"Link your chat account to continue.",IDENTITY_CONFLICT:"This chat account is already linked to another user. Unlink it there first.",LINK_EXPIRED:"Your session expired. Send your message again.",LINK_REVOKED:"Your access has ended. Sign in again to continue.",PERMISSION_DENIED:"You don't have access to this.",SOURCE_UNAVAILABLE:"We couldn't check your sign-in right now. Please try again shortly."},admissionErrors:{POLICY_DENIED:"This message can't be sent. Try shortening or rephrasing it.",RATE_LIMITED:"You're sending messages too quickly.",CHALLENGE_REQUIRED:"Extra verification is needed. Please try again later."},cooldown:t=>`You can send again in ${t}s`,cooldownStart:t=>`Sending is paused. You can send again in ${t} second${t===1?"":"s"}.`,cooldownOver:"You can send messages again.",linkErrors:{idempotency_key_reused:"This link request was already used. Please try again.",link_in_progress:"A link is already in progress. Use the code you got, or wait for it to expire.",linking_unavailable:"Linking is not available right now. Please try again later."},linkIntro:"Send this code in a direct message from the chat account you want to link:",linkContinueOn:t=>`Continue on ${t}`,linkExpires:t=>`The code expires in ${t} min.`,linkNoTargets:"No chat app is set up for linking yet.",jobAccess:"Job access",jobAccessOpened:"Job access opened in a new window. Review and confirm any permissions there.",jobAccessUnavailable:"Job access could not be opened. Sign in again or retry.",jobAccessPopupBlocked:"Allow popups for this site, then choose Job access again.",jobAccessPopupClosed:"The window was closed. Choose Job access again to retry.",pageShare:"Share this page with the assistant for this message",pageChanged:"The page changed. Review it and choose to share again before sending.",pageUnavailable:"Page details are unavailable. You can send without them."},Ct={title:"Tr\u1EE3 l\xFD",greeting:"Xin ch\xE0o \u{1F44B}",greetingBody:"B\u1EA1n c\u1EA7n h\u1ECFi g\xEC c\u1EE9 nh\u1EAFn nh\xE9. M\xECnh c\xF3 th\u1EC3 tra c\u1EE9u v\xE0 d\xF9ng c\xF4ng c\u1EE5 \u0111\u1EC3 h\u1ED7 tr\u1EE3 b\u1EA1n.",placeholder:"Nh\u1EADp tin nh\u1EAFn\u2026",send:"G\u1EEDi",stop:"D\u1EEBng",newChat:"Cu\u1ED9c tr\xF2 chuy\u1EC7n m\u1EDBi",close:"\u0110\xF3ng khung chat",open:"M\u1EDF khung chat",thinking:"\u0110ang suy ngh\u0129\u2026",thoughtFor:t=>`\u0110\xE3 suy ngh\u0129 ${t} gi\xE2y`,reasoning:"Suy lu\u1EADn",toolRunning:"\u0111ang ch\u1EA1y",toolDone:"xong",toolError:"l\u1ED7i",args:"Tham s\u1ED1",result:"K\u1EBFt qu\u1EA3",online:"\u0110ang tr\u1EF1c tuy\u1EBFn",poweredBy:"V\u1EADn h\xE0nh b\u1EDFi",errorGeneric:"C\xF3 l\u1ED7i x\u1EA3y ra. B\u1EA1n th\u1EED l\u1EA1i gi\xFAp m\xECnh nh\xE9.",stopped:"\u0110\xE3 d\u1EEBng.",actionStatus:{pending:"ch\u1EDD","awaiting-confirmation":"c\u1EA7n x\xE1c nh\u1EADn",running:"\u0111ang ch\u1EA1y",done:"xong",denied:"\u0111\xE3 t\u1EEB ch\u1ED1i",error:"l\u1ED7i"},confirmTitle:"Cho ph\xE9p thao t\xE1c n\xE0y?",confirmDestructive:"Thao t\xE1c n\xE0y kh\xF4ng th\u1EC3 ho\xE0n t\xE1c.",allow:"Cho ph\xE9p",deny:"T\u1EEB ch\u1ED1i",actionLimit:t=>`\u0110\xE3 d\u1EEBng sau ${t} l\u01B0\u1EE3t thao t\xE1c t\u1EF1 \u0111\u1ED9ng. G\u1EEDi tin nh\u1EAFn \u0111\u1EC3 ti\u1EBFp t\u1EE5c.`,identityErrors:{IDENTITY_REQUIRED:"B\u1EA1n \u0111\u0103ng nh\u1EADp \u0111\u1EC3 tr\xF2 chuy\u1EC7n nh\xE9.",IDENTITY_LINK_REQUIRED:"B\u1EA1n c\u1EA7n li\xEAn k\u1EBFt t\xE0i kho\u1EA3n chat \u0111\u1EC3 ti\u1EBFp t\u1EE5c.",IDENTITY_CONFLICT:"T\xE0i kho\u1EA3n chat n\xE0y \u0111\xE3 li\xEAn k\u1EBFt v\u1EDBi ng\u01B0\u1EDDi d\xF9ng kh\xE1c. H\xE3y h\u1EE7y li\xEAn k\u1EBFt \u1EDF \u0111\xF3 tr\u01B0\u1EDBc.",LINK_EXPIRED:"Phi\xEAn \u0111\u0103ng nh\u1EADp \u0111\xE3 h\u1EBFt h\u1EA1n. B\u1EA1n g\u1EEDi l\u1EA1i tin nh\u1EAFn gi\xFAp m\xECnh nh\xE9.",LINK_REVOKED:"Quy\u1EC1n truy c\u1EADp c\u1EE7a b\u1EA1n \u0111\xE3 k\u1EBFt th\xFAc. H\xE3y \u0111\u0103ng nh\u1EADp l\u1EA1i \u0111\u1EC3 ti\u1EBFp t\u1EE5c.",PERMISSION_DENIED:"B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n th\u1EF1c hi\u1EC7n vi\u1EC7c n\xE0y.",SOURCE_UNAVAILABLE:"Hi\u1EC7n ch\u01B0a ki\u1EC3m tra \u0111\u01B0\u1EE3c \u0111\u0103ng nh\u1EADp c\u1EE7a b\u1EA1n. B\u1EA1n th\u1EED l\u1EA1i sau \xEDt ph\xFAt nh\xE9."},admissionErrors:{POLICY_DENIED:"Kh\xF4ng g\u1EEDi \u0111\u01B0\u1EE3c tin nh\u1EAFn n\xE0y. B\u1EA1n th\u1EED r\xFAt g\u1ECDn ho\u1EB7c di\u1EC5n \u0111\u1EA1t l\u1EA1i nh\xE9.",RATE_LIMITED:"B\u1EA1n \u0111ang g\u1EEDi tin nh\u1EAFn h\u01A1i nhanh.",CHALLENGE_REQUIRED:"C\u1EA7n x\xE1c minh th\xEAm. B\u1EA1n th\u1EED l\u1EA1i sau nh\xE9."},cooldown:t=>`B\u1EA1n c\xF3 th\u1EC3 g\u1EEDi l\u1EA1i sau ${t} gi\xE2y`,cooldownStart:t=>`T\u1EA1m d\u1EEBng g\u1EEDi tin nh\u1EAFn. B\u1EA1n c\xF3 th\u1EC3 g\u1EEDi l\u1EA1i sau ${t} gi\xE2y.`,cooldownOver:"B\u1EA1n c\xF3 th\u1EC3 g\u1EEDi tin nh\u1EAFn ti\u1EBFp r\u1ED3i.",linkErrors:{idempotency_key_reused:"Y\xEAu c\u1EA7u li\xEAn k\u1EBFt n\xE0y \u0111\xE3 \u0111\u01B0\u1EE3c d\xF9ng. B\u1EA1n th\u1EED l\u1EA1i nh\xE9.",link_in_progress:"\u0110ang c\xF3 m\u1ED9t li\xEAn k\u1EBFt ch\u01B0a ho\xE0n t\u1EA5t. H\xE3y d\xF9ng m\xE3 \u0111\xE3 nh\u1EADn ho\u1EB7c ch\u1EDD m\xE3 h\u1EBFt h\u1EA1n.",linking_unavailable:"Hi\u1EC7n ch\u01B0a th\u1EC3 li\xEAn k\u1EBFt. B\u1EA1n th\u1EED l\u1EA1i sau nh\xE9."},linkIntro:"G\u1EEDi m\xE3 n\xE0y trong tin nh\u1EAFn ri\xEAng t\u1EEB t\xE0i kho\u1EA3n chat b\u1EA1n mu\u1ED1n li\xEAn k\u1EBFt:",linkContinueOn:t=>`Ti\u1EBFp t\u1EE5c tr\xEAn ${t}`,linkExpires:t=>`M\xE3 h\u1EBFt h\u1EA1n sau ${t} ph\xFAt.`,linkNoTargets:"Ch\u01B0a c\xF3 \u1EE9ng d\u1EE5ng chat n\xE0o \u0111\u01B0\u1EE3c thi\u1EBFt l\u1EADp \u0111\u1EC3 li\xEAn k\u1EBFt.",jobAccess:"Quy\u1EC1n c\xF4ng vi\u1EC7c",jobAccessOpened:"\u0110\xE3 m\u1EDF c\u1EEDa s\u1ED5 quy\u1EC1n c\xF4ng vi\u1EC7c. H\xE3y xem l\u1EA1i v\xE0 x\xE1c nh\u1EADn quy\u1EC1n t\u1EA1i \u0111\xF3.",jobAccessUnavailable:"Ch\u01B0a m\u1EDF \u0111\u01B0\u1EE3c quy\u1EC1n c\xF4ng vi\u1EC7c. H\xE3y \u0111\u0103ng nh\u1EADp l\u1EA1i ho\u1EB7c th\u1EED l\u1EA1i.",jobAccessPopupBlocked:"Cho ph\xE9p c\u1EEDa s\u1ED5 b\u1EADt l\xEAn cho trang n\xE0y r\u1ED3i ch\u1ECDn Quy\u1EC1n c\xF4ng vi\u1EC7c l\u1EA7n n\u1EEFa.",jobAccessPopupClosed:"C\u1EEDa s\u1ED5 \u0111\xE3 \u0111\xF3ng. Ch\u1ECDn Quy\u1EC1n c\xF4ng vi\u1EC7c l\u1EA7n n\u1EEFa \u0111\u1EC3 th\u1EED l\u1EA1i.",pageShare:"Chia s\u1EBB trang n\xE0y v\u1EDBi tr\u1EE3 l\xFD trong tin nh\u1EAFn n\xE0y",pageChanged:"Trang \u0111\xE3 thay \u0111\u1ED5i. H\xE3y xem l\u1EA1i v\xE0 ch\u1ECDn chia s\u1EBB tr\u01B0\u1EDBc khi g\u1EEDi.",pageUnavailable:"Kh\xF4ng th\u1EC3 \u0111\u1ECDc n\u1ED9i dung trang. B\u1EA1n v\u1EABn c\xF3 th\u1EC3 g\u1EEDi tin nh\u1EAFn."};function ue(t){return(t||(typeof document<"u"?document.documentElement.lang:"")||(typeof navigator<"u"?navigator.language:"")||"en").toLowerCase().startsWith("vi")?Ct:At}var C={jobAccess:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m12 3 8 4v5c0 5-8 9-8 9s-8-4-8-9V7l8-4Z"/><path d="m8 12 3 3 5-6"/></svg>',action:'<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z"/></svg>',chat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a8.5 8.5 0 0 1-12.4 7.6L3 21l1.4-5.1A8.5 8.5 0 1 1 21 12Z"/><path d="M8.5 11h.01M12 11h.01M15.5 11h.01"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',down:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>',newChat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.4 3.6a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4Z"/></svg>',send:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',stop:'<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2.5"/></svg>',brain:'<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24A2.5 2.5 0 0 1 9.5 2Z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24A2.5 2.5 0 0 0 14.5 2Z"/></svg>',tool:'<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z"/></svg>'};var q=new WeakMap,H=new WeakMap;function U(t){for(let s of t.querySelectorAll("img.md-image"))q.get(s)?.disconnect(),q.delete(s),H.get(s)?.abort(),H.delete(s)}function St(t,s,e){try{if(!s||/[\u0000-\u0020\u007f\\]/.test(s)||s.startsWith("//"))return null;let n=decodeURIComponent(s);if(/[\u0000-\u0020\u007f\\]/.test(n)||n.startsWith("//"))return null;let i=new URL(t.defaultView?.location.href??t.baseURI),r=new URL(s,t.baseURI);return r.username||r.password||!["http:","https:"].includes(r.protocol)||/\.svg$/i.test(decodeURIComponent(r.pathname))?null:r.origin===i.origin?r.href:r.protocol!=="https:"?null:e.some(c=>{try{let a=new URL(c);return a.protocol==="https:"&&!a.username&&!a.password&&a.href===a.origin+"/"&&a.origin===r.origin}catch{return!1}})?r.href:null}catch{return null}}function v(t,s,e){let n=t.createElement(s);return e&&(n.className=e),n}function Tt(t){let s=t.trim();return/^(https?:|mailto:|tel:)/i.test(s)||/^[/#?]/.test(s)&&!s.startsWith("//")?s:null}var It=/\\!\[[^\]]*\]\([^)\s]+\)|(`+)([\s\S]*?[^`])\1(?!`)|\*\*([^*]+?)\*\*|__([^_]+?)__|~~([^~]+?)~~|\*([^*\s][^*]*?)\*|(?<![\w])_([^_\s][^_]*?)_(?![\w])|(?<!\\)!\[([^\]]*)\]\(([^)\s]+)\)|\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"])/;function T(t,s,e,n={}){let i=new RegExp(It.source,"g"),r=0;for(let o;o=i.exec(s);)if(o.index>r&&e.appendChild(t.createTextNode(s.slice(r,o.index))),r=o.index+o[0].length,o[0].startsWith("\\!"))e.appendChild(t.createTextNode(o[0].slice(1)));else if(o[2]!==void 0){let c=v(t,"code");c.textContent=o[2],e.appendChild(c)}else if(o[3]!==void 0||o[4]!==void 0){let c=v(t,"strong");T(t,o[3]??o[4],c,n),e.appendChild(c)}else if(o[5]!==void 0){let c=v(t,"del");T(t,o[5],c,n),e.appendChild(c)}else if(o[6]!==void 0||o[7]!==void 0){let c=v(t,"em");T(t,o[6]??o[7],c,n),e.appendChild(c)}else if(o[8]!==void 0){let c=n.deferImages?null:St(t,o[9],n.imageOrigins??[]);if(!c||!n.imageProxy)e.appendChild(t.createTextNode(o[8]));else{let a=v(t,"img","md-image");a.alt=o[8],a.setAttribute("loading","lazy"),a.setAttribute("decoding","async"),a.referrerPolicy="no-referrer";let d=!1,l=()=>{let g=new AbortController;return H.set(a,g),n.imageProxy(c,g.signal).then(h=>{!g.signal.aborted&&a.isConnected&&(a.src=h)}).catch(()=>{!g.signal.aborted&&a.isConnected&&a.replaceWith(t.createTextNode(a.alt))}).finally(()=>{H.get(a)===g&&H.delete(a)})};a.addEventListener("error",()=>{d?a.replaceWith(t.createTextNode(a.alt)):(d=!0,l())}),e.appendChild(a);let p=t.defaultView?.IntersectionObserver;if(p){let g=new p(h=>{h.some(u=>u.isIntersecting)&&(g.disconnect(),q.delete(a),a.parentNode&&l())},{rootMargin:"200px"});q.set(a,g),g.observe(a)}else l()}}else if(o[10]!==void 0){let c=Tt(o[11]);if(c){let a=v(t,"a");a.href=c,a.target="_blank",a.rel="noopener noreferrer nofollow",T(t,o[10],a,n),e.appendChild(a)}else e.appendChild(t.createTextNode(o[10]))}else if(o[12]!==void 0){let c=v(t,"a");c.href=o[12],c.target="_blank",c.rel="noopener noreferrer nofollow",c.textContent=o[12],e.appendChild(c)}r<s.length&&e.appendChild(t.createTextNode(s.slice(r)))}var Be=t=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(t),ze=t=>t.trim().replace(/^\||\|$/g,"").split("|").map(s=>s.trim());function R(t,s,e={}){let n=t.createDocumentFragment(),i=s.replace(/\r\n?/g,`
34
+ </div>`;let d=m=>a.querySelector(m);d("h3").textContent=s.confirmTitle,d("code").textContent=e.name;let l=d(".sens");if(l.textContent=e.sensitivity,l.dataset.level=e.sensitivity,d(".confirm-text").textContent=e.description,e.sensitivity==="destructive"){let m=d(".confirm-warn");m.hidden=!1,m.textContent=s.confirmDestructive}let u=JSON.stringify(t,null,2),g=d(".confirm-args");u&&u!=="{}"?g.textContent=u:g.remove();let p=d(".deny"),h=d(".allow");return p.textContent=s.deny,h.textContent=s.allow,e.sensitivity==="destructive"&&h.classList.add("danger"),new Promise(m=>{let b=!1,x=y=>{b||(b=!0,i?.removeEventListener("abort",w),a.remove(),c?.focus?.(),m(y))},w=()=>x(!1);if(i?.aborted)return x(!1);i?.addEventListener("abort",w,{once:!0}),p.addEventListener("click",()=>x(!1)),h.addEventListener("click",()=>x(!0)),a.addEventListener("keydown",y=>{y.key==="Escape"?(y.preventDefault(),y.stopPropagation(),x(!1)):y.key==="Tab"&&(y.preventDefault(),(o.activeElement===p?h:p).focus())}),n.appendChild(a),p.focus()})}var _t={title:"Assistant",greeting:"Hi there \u{1F44B}",greetingBody:"Ask me anything. I can look things up and use tools to help you.",placeholder:"Type a message\u2026",send:"Send",stop:"Stop",newChat:"New conversation",close:"Close chat",open:"Open chat",thinking:"Thinking\u2026",thoughtFor:n=>`Thought for ${n}s`,reasoning:"Reasoning",toolRunning:"running",toolDone:"done",toolError:"error",args:"Arguments",result:"Result",online:"Online",poweredBy:"Powered by",errorGeneric:"Something went wrong. Please try again.",stopped:"Stopped.",actionStatus:{pending:"queued","awaiting-confirmation":"needs approval",running:"running",done:"done",denied:"declined",error:"failed"},confirmTitle:"Allow this action?",confirmDestructive:"This can't be undone.",allow:"Allow",deny:"Deny",actionLimit:n=>`Stopped after ${n} automatic action rounds. Send a message to continue.`,identityErrors:{IDENTITY_REQUIRED:"Please sign in to chat.",IDENTITY_LINK_REQUIRED:"Link your chat account to continue.",IDENTITY_CONFLICT:"This chat account is already linked to another user. Unlink it there first.",LINK_EXPIRED:"Your session expired. Send your message again.",LINK_REVOKED:"Your access has ended. Sign in again to continue.",PERMISSION_DENIED:"You don't have access to this.",SOURCE_UNAVAILABLE:"We couldn't check your sign-in right now. Please try again shortly."},admissionErrors:{POLICY_DENIED:"This message can't be sent. Try shortening or rephrasing it.",RATE_LIMITED:"You're sending messages too quickly.",CHALLENGE_REQUIRED:"Extra verification is needed. Please try again later."},cooldown:n=>`You can send again in ${n}s`,cooldownStart:n=>`Sending is paused. You can send again in ${n} second${n===1?"":"s"}.`,cooldownOver:"You can send messages again.",linkErrors:{idempotency_key_reused:"This link request was already used. Please try again.",link_in_progress:"A link is already in progress. Use the code you got, or wait for it to expire.",linking_unavailable:"Linking is not available right now. Please try again later."},linkIntro:"Send this code in a direct message from the chat account you want to link:",linkContinueOn:n=>`Continue on ${n}`,linkExpires:n=>`The code expires in ${n} min.`,linkNoTargets:"No chat app is set up for linking yet.",jobAccess:"Job access",jobAccessOpened:"Job access opened in a new window. Review and confirm any permissions there.",jobAccessUnavailable:"Job access could not be opened. Sign in again or retry.",jobAccessPopupBlocked:"Allow popups for this site, then choose Job access again.",jobAccessPopupClosed:"The window was closed. Choose Job access again to retry.",pageShare:"Share this page with the assistant for this message",pageChanged:"The page changed. Review it and choose to share again before sending.",pageUnavailable:"Page details are unavailable. You can send without them.",credential:{open:"Open secure form",cancel:"Cancel request",continue:"Continue conversation",unavailable:"Could not open or update the request. Please try again.",intro:"Enter credentials only on the authenticated Dewee form.",required:"required",optional:"optional",expires:"Expires",status:{pending:"Waiting for you",applying:"Processing",resolved:"Completed",cancelled:"Cancelled",expired:"Expired",failed:"Failed"}}},Mt={title:"Tr\u1EE3 l\xFD",greeting:"Xin ch\xE0o \u{1F44B}",greetingBody:"B\u1EA1n c\u1EA7n h\u1ECFi g\xEC c\u1EE9 nh\u1EAFn nh\xE9. M\xECnh c\xF3 th\u1EC3 tra c\u1EE9u v\xE0 d\xF9ng c\xF4ng c\u1EE5 \u0111\u1EC3 h\u1ED7 tr\u1EE3 b\u1EA1n.",placeholder:"Nh\u1EADp tin nh\u1EAFn\u2026",send:"G\u1EEDi",stop:"D\u1EEBng",newChat:"Cu\u1ED9c tr\xF2 chuy\u1EC7n m\u1EDBi",close:"\u0110\xF3ng khung chat",open:"M\u1EDF khung chat",thinking:"\u0110ang suy ngh\u0129\u2026",thoughtFor:n=>`\u0110\xE3 suy ngh\u0129 ${n} gi\xE2y`,reasoning:"Suy lu\u1EADn",toolRunning:"\u0111ang ch\u1EA1y",toolDone:"xong",toolError:"l\u1ED7i",args:"Tham s\u1ED1",result:"K\u1EBFt qu\u1EA3",online:"\u0110ang tr\u1EF1c tuy\u1EBFn",poweredBy:"V\u1EADn h\xE0nh b\u1EDFi",errorGeneric:"C\xF3 l\u1ED7i x\u1EA3y ra. B\u1EA1n th\u1EED l\u1EA1i gi\xFAp m\xECnh nh\xE9.",stopped:"\u0110\xE3 d\u1EEBng.",actionStatus:{pending:"ch\u1EDD","awaiting-confirmation":"c\u1EA7n x\xE1c nh\u1EADn",running:"\u0111ang ch\u1EA1y",done:"xong",denied:"\u0111\xE3 t\u1EEB ch\u1ED1i",error:"l\u1ED7i"},confirmTitle:"Cho ph\xE9p thao t\xE1c n\xE0y?",confirmDestructive:"Thao t\xE1c n\xE0y kh\xF4ng th\u1EC3 ho\xE0n t\xE1c.",allow:"Cho ph\xE9p",deny:"T\u1EEB ch\u1ED1i",actionLimit:n=>`\u0110\xE3 d\u1EEBng sau ${n} l\u01B0\u1EE3t thao t\xE1c t\u1EF1 \u0111\u1ED9ng. G\u1EEDi tin nh\u1EAFn \u0111\u1EC3 ti\u1EBFp t\u1EE5c.`,identityErrors:{IDENTITY_REQUIRED:"B\u1EA1n \u0111\u0103ng nh\u1EADp \u0111\u1EC3 tr\xF2 chuy\u1EC7n nh\xE9.",IDENTITY_LINK_REQUIRED:"B\u1EA1n c\u1EA7n li\xEAn k\u1EBFt t\xE0i kho\u1EA3n chat \u0111\u1EC3 ti\u1EBFp t\u1EE5c.",IDENTITY_CONFLICT:"T\xE0i kho\u1EA3n chat n\xE0y \u0111\xE3 li\xEAn k\u1EBFt v\u1EDBi ng\u01B0\u1EDDi d\xF9ng kh\xE1c. H\xE3y h\u1EE7y li\xEAn k\u1EBFt \u1EDF \u0111\xF3 tr\u01B0\u1EDBc.",LINK_EXPIRED:"Phi\xEAn \u0111\u0103ng nh\u1EADp \u0111\xE3 h\u1EBFt h\u1EA1n. B\u1EA1n g\u1EEDi l\u1EA1i tin nh\u1EAFn gi\xFAp m\xECnh nh\xE9.",LINK_REVOKED:"Quy\u1EC1n truy c\u1EADp c\u1EE7a b\u1EA1n \u0111\xE3 k\u1EBFt th\xFAc. H\xE3y \u0111\u0103ng nh\u1EADp l\u1EA1i \u0111\u1EC3 ti\u1EBFp t\u1EE5c.",PERMISSION_DENIED:"B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n th\u1EF1c hi\u1EC7n vi\u1EC7c n\xE0y.",SOURCE_UNAVAILABLE:"Hi\u1EC7n ch\u01B0a ki\u1EC3m tra \u0111\u01B0\u1EE3c \u0111\u0103ng nh\u1EADp c\u1EE7a b\u1EA1n. B\u1EA1n th\u1EED l\u1EA1i sau \xEDt ph\xFAt nh\xE9."},admissionErrors:{POLICY_DENIED:"Kh\xF4ng g\u1EEDi \u0111\u01B0\u1EE3c tin nh\u1EAFn n\xE0y. B\u1EA1n th\u1EED r\xFAt g\u1ECDn ho\u1EB7c di\u1EC5n \u0111\u1EA1t l\u1EA1i nh\xE9.",RATE_LIMITED:"B\u1EA1n \u0111ang g\u1EEDi tin nh\u1EAFn h\u01A1i nhanh.",CHALLENGE_REQUIRED:"C\u1EA7n x\xE1c minh th\xEAm. B\u1EA1n th\u1EED l\u1EA1i sau nh\xE9."},cooldown:n=>`B\u1EA1n c\xF3 th\u1EC3 g\u1EEDi l\u1EA1i sau ${n} gi\xE2y`,cooldownStart:n=>`T\u1EA1m d\u1EEBng g\u1EEDi tin nh\u1EAFn. B\u1EA1n c\xF3 th\u1EC3 g\u1EEDi l\u1EA1i sau ${n} gi\xE2y.`,cooldownOver:"B\u1EA1n c\xF3 th\u1EC3 g\u1EEDi tin nh\u1EAFn ti\u1EBFp r\u1ED3i.",linkErrors:{idempotency_key_reused:"Y\xEAu c\u1EA7u li\xEAn k\u1EBFt n\xE0y \u0111\xE3 \u0111\u01B0\u1EE3c d\xF9ng. B\u1EA1n th\u1EED l\u1EA1i nh\xE9.",link_in_progress:"\u0110ang c\xF3 m\u1ED9t li\xEAn k\u1EBFt ch\u01B0a ho\xE0n t\u1EA5t. H\xE3y d\xF9ng m\xE3 \u0111\xE3 nh\u1EADn ho\u1EB7c ch\u1EDD m\xE3 h\u1EBFt h\u1EA1n.",linking_unavailable:"Hi\u1EC7n ch\u01B0a th\u1EC3 li\xEAn k\u1EBFt. B\u1EA1n th\u1EED l\u1EA1i sau nh\xE9."},linkIntro:"G\u1EEDi m\xE3 n\xE0y trong tin nh\u1EAFn ri\xEAng t\u1EEB t\xE0i kho\u1EA3n chat b\u1EA1n mu\u1ED1n li\xEAn k\u1EBFt:",linkContinueOn:n=>`Ti\u1EBFp t\u1EE5c tr\xEAn ${n}`,linkExpires:n=>`M\xE3 h\u1EBFt h\u1EA1n sau ${n} ph\xFAt.`,linkNoTargets:"Ch\u01B0a c\xF3 \u1EE9ng d\u1EE5ng chat n\xE0o \u0111\u01B0\u1EE3c thi\u1EBFt l\u1EADp \u0111\u1EC3 li\xEAn k\u1EBFt.",jobAccess:"Quy\u1EC1n c\xF4ng vi\u1EC7c",jobAccessOpened:"\u0110\xE3 m\u1EDF c\u1EEDa s\u1ED5 quy\u1EC1n c\xF4ng vi\u1EC7c. H\xE3y xem l\u1EA1i v\xE0 x\xE1c nh\u1EADn quy\u1EC1n t\u1EA1i \u0111\xF3.",jobAccessUnavailable:"Ch\u01B0a m\u1EDF \u0111\u01B0\u1EE3c quy\u1EC1n c\xF4ng vi\u1EC7c. H\xE3y \u0111\u0103ng nh\u1EADp l\u1EA1i ho\u1EB7c th\u1EED l\u1EA1i.",jobAccessPopupBlocked:"Cho ph\xE9p c\u1EEDa s\u1ED5 b\u1EADt l\xEAn cho trang n\xE0y r\u1ED3i ch\u1ECDn Quy\u1EC1n c\xF4ng vi\u1EC7c l\u1EA7n n\u1EEFa.",jobAccessPopupClosed:"C\u1EEDa s\u1ED5 \u0111\xE3 \u0111\xF3ng. Ch\u1ECDn Quy\u1EC1n c\xF4ng vi\u1EC7c l\u1EA7n n\u1EEFa \u0111\u1EC3 th\u1EED l\u1EA1i.",pageShare:"Chia s\u1EBB trang n\xE0y v\u1EDBi tr\u1EE3 l\xFD trong tin nh\u1EAFn n\xE0y",pageChanged:"Trang \u0111\xE3 thay \u0111\u1ED5i. H\xE3y xem l\u1EA1i v\xE0 ch\u1ECDn chia s\u1EBB tr\u01B0\u1EDBc khi g\u1EEDi.",pageUnavailable:"Kh\xF4ng th\u1EC3 \u0111\u1ECDc n\u1ED9i dung trang. B\u1EA1n v\u1EABn c\xF3 th\u1EC3 g\u1EEDi tin nh\u1EAFn.",credential:{open:"M\u1EDF bi\u1EC3u m\u1EABu b\u1EA3o m\u1EADt",cancel:"H\u1EE7y y\xEAu c\u1EA7u",continue:"Ti\u1EBFp t\u1EE5c tr\xF2 chuy\u1EC7n",unavailable:"Ch\u01B0a th\u1EC3 m\u1EDF ho\u1EB7c c\u1EADp nh\u1EADt y\xEAu c\u1EA7u. B\u1EA1n th\u1EED l\u1EA1i nh\xE9.",intro:"Ch\u1EC9 nh\u1EADp th\xF4ng tin x\xE1c th\u1EF1c tr\xEAn bi\u1EC3u m\u1EABu Dewee sau khi \u0111\u0103ng nh\u1EADp.",required:"b\u1EAFt bu\u1ED9c",optional:"t\xF9y ch\u1ECDn",expires:"H\u1EBFt h\u1EA1n",status:{pending:"\u0110ang ch\u1EDD b\u1EA1n",applying:"\u0110ang x\u1EED l\xFD",resolved:"\u0110\xE3 ho\xE0n t\u1EA5t",cancelled:"\u0110\xE3 h\u1EE7y",expired:"\u0110\xE3 h\u1EBFt h\u1EA1n",failed:"Kh\xF4ng th\xE0nh c\xF4ng"}}};function me(n){return(n||(typeof document<"u"?document.documentElement.lang:"")||(typeof navigator<"u"?navigator.language:"")||"en").toLowerCase().startsWith("vi")?Mt:_t}var A={jobAccess:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m12 3 8 4v5c0 5-8 9-8 9s-8-4-8-9V7l8-4Z"/><path d="m8 12 3 3 5-6"/></svg>',action:'<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 2 4 14h7l-1 8 9-12h-7l1-8Z"/></svg>',chat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a8.5 8.5 0 0 1-12.4 7.6L3 21l1.4-5.1A8.5 8.5 0 1 1 21 12Z"/><path d="M8.5 11h.01M12 11h.01M15.5 11h.01"/></svg>',close:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12"/></svg>',down:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>',newChat:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9"/><path d="M16.4 3.6a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4Z"/></svg>',send:'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 19V5M5 12l7-7 7 7"/></svg>',stop:'<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="6" y="6" width="12" height="12" rx="2.5"/></svg>',brain:'<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96.44 2.5 2.5 0 0 1-2.96-3.08 3 3 0 0 1-.34-5.58 2.5 2.5 0 0 1 1.32-4.24A2.5 2.5 0 0 1 9.5 2Z"/><path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96.44 2.5 2.5 0 0 0 2.96-3.08 3 3 0 0 0 .34-5.58 2.5 2.5 0 0 0-1.32-4.24A2.5 2.5 0 0 0 14.5 2Z"/></svg>',tool:'<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76Z"/></svg>'};var J=new WeakMap,H=new WeakMap;function K(n){for(let s of n.querySelectorAll("img.md-image"))J.get(s)?.disconnect(),J.delete(s),H.get(s)?.abort(),H.delete(s)}function Nt(n,s,e){try{if(!s||/[\u0000-\u0020\u007f\\]/.test(s)||s.startsWith("//"))return null;let t=decodeURIComponent(s);if(/[\u0000-\u0020\u007f\\]/.test(t)||t.startsWith("//"))return null;let i=new URL(n.defaultView?.location.href??n.baseURI),r=new URL(s,n.baseURI);return r.username||r.password||!["http:","https:"].includes(r.protocol)||/\.svg$/i.test(decodeURIComponent(r.pathname))?null:r.origin===i.origin?r.href:r.protocol!=="https:"?null:e.some(c=>{try{let a=new URL(c);return a.protocol==="https:"&&!a.username&&!a.password&&a.href===a.origin+"/"&&a.origin===r.origin}catch{return!1}})?r.href:null}catch{return null}}function C(n,s,e){let t=n.createElement(s);return e&&(t.className=e),t}function Ot(n){let s=n.trim();return/^(https?:|mailto:|tel:)/i.test(s)||/^[/#?]/.test(s)&&!s.startsWith("//")?s:null}var Dt=/\\!\[[^\]]*\]\([^)\s]+\)|(`+)([\s\S]*?[^`])\1(?!`)|\*\*([^*]+?)\*\*|__([^_]+?)__|~~([^~]+?)~~|\*([^*\s][^*]*?)\*|(?<![\w])_([^_\s][^_]*?)_(?![\w])|(?<!\\)!\[([^\]]*)\]\(([^)\s]+)\)|\[([^\]]+)\]\(([^)\s]+)(?:\s+"[^"]*")?\)|(https?:\/\/[^\s<>()]+[^\s<>().,;:!?'"])/;function P(n,s,e,t={}){let i=new RegExp(Dt.source,"g"),r=0;for(let o;o=i.exec(s);)if(o.index>r&&e.appendChild(n.createTextNode(s.slice(r,o.index))),r=o.index+o[0].length,o[0].startsWith("\\!"))e.appendChild(n.createTextNode(o[0].slice(1)));else if(o[2]!==void 0){let c=C(n,"code");c.textContent=o[2],e.appendChild(c)}else if(o[3]!==void 0||o[4]!==void 0){let c=C(n,"strong");P(n,o[3]??o[4],c,t),e.appendChild(c)}else if(o[5]!==void 0){let c=C(n,"del");P(n,o[5],c,t),e.appendChild(c)}else if(o[6]!==void 0||o[7]!==void 0){let c=C(n,"em");P(n,o[6]??o[7],c,t),e.appendChild(c)}else if(o[8]!==void 0){let c=t.deferImages?null:Nt(n,o[9],t.imageOrigins??[]);if(!c||!t.imageProxy)e.appendChild(n.createTextNode(o[8]));else{let a=C(n,"img","md-image");a.alt=o[8],a.setAttribute("loading","lazy"),a.setAttribute("decoding","async"),a.referrerPolicy="no-referrer";let d=!1,l=()=>{let g=new AbortController;return H.set(a,g),t.imageProxy(c,g.signal).then(p=>{!g.signal.aborted&&a.isConnected&&(a.src=p)}).catch(()=>{!g.signal.aborted&&a.isConnected&&a.replaceWith(n.createTextNode(a.alt))}).finally(()=>{H.get(a)===g&&H.delete(a)})};a.addEventListener("error",()=>{d?a.replaceWith(n.createTextNode(a.alt)):(d=!0,l())}),e.appendChild(a);let u=n.defaultView?.IntersectionObserver;if(u){let g=new u(p=>{p.some(h=>h.isIntersecting)&&(g.disconnect(),J.delete(a),a.parentNode&&l())},{rootMargin:"200px"});J.set(a,g),g.observe(a)}else l()}}else if(o[10]!==void 0){let c=Ot(o[11]);if(c){let a=C(n,"a");a.href=c,a.target="_blank",a.rel="noopener noreferrer nofollow",P(n,o[10],a,t),e.appendChild(a)}else e.appendChild(n.createTextNode(o[10]))}else if(o[12]!==void 0){let c=C(n,"a");c.href=o[12],c.target="_blank",c.rel="noopener noreferrer nofollow",c.textContent=o[12],e.appendChild(c)}r<s.length&&e.appendChild(n.createTextNode(s.slice(r)))}var Je=n=>/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(n),Ke=n=>n.trim().replace(/^\||\|$/g,"").split("|").map(s=>s.trim());function M(n,s,e={}){let t=n.createDocumentFragment(),i=s.replace(/\r\n?/g,`
35
35
  `).split(`
36
- `),r=0;for(;r<i.length;){let o=i[r];if(!o.trim()){r++;continue}let c=o.match(/^\s*(```+|~~~+)\s*([\w+-]*)/);if(c){let g=[];for(r++;r<i.length&&!i[r].trim().startsWith(c[1]);)g.push(i[r++]);r++;let h=v(t,"pre"),u=v(t,"code");c[2]&&(u.dataset.lang=c[2]),u.textContent=g.join(`
37
- `),h.appendChild(u),n.appendChild(h);continue}let a=o.match(/^(#{1,6})\s+(.*)$/);if(a){let g=`h${Math.min(6,a[1].length+2)}`,h=v(t,g);T(t,a[2],h,e),n.appendChild(h),r++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(o)){n.appendChild(v(t,"hr")),r++;continue}if(o.includes("|")&&r+1<i.length&&Be(i[r+1])){let g=v(t,"div","table"),h=v(t,"table"),u=v(t,"thead"),m=v(t,"tr");for(let x of ze(o)){let w=v(t,"th");T(t,x,w,e),m.appendChild(w)}u.appendChild(m),h.appendChild(u);let b=v(t,"tbody");for(r+=2;r<i.length&&i[r].includes("|")&&i[r].trim();){let x=v(t,"tr");for(let w of ze(i[r])){let y=v(t,"td");T(t,w,y,e),x.appendChild(y)}b.appendChild(x),r++}h.appendChild(b),g.appendChild(h),n.appendChild(g);continue}if(/^\s*>/.test(o)){let g=[];for(;r<i.length&&/^\s*>/.test(i[r]);)g.push(i[r++].replace(/^\s*>\s?/,""));let h=v(t,"blockquote");h.appendChild(R(t,g.join(`
38
- `),e)),n.appendChild(h);continue}let d=o.match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(d){let g=/\d/.test(d[2]),h=v(t,g?"ol":"ul");g&&parseInt(d[2],10)!==1&&h.setAttribute("start",String(parseInt(d[2],10)));let u=d[1].length;for(;r<i.length;){let m=i[r].match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(!m||m[1].length<u||/\d/.test(m[2])!==g)break;if(m[1].length>u){let x=[];for(;r<i.length&&/^\s+/.test(i[r])&&i[r].match(/^(\s*)/)[1].length>u;)x.push(i[r++].slice(u+2));h.lastElementChild?.appendChild(R(t,x.join(`
39
- `),e));continue}let b=v(t,"li");T(t,m[3],b,e),h.appendChild(b),r++}n.appendChild(h);continue}let l=[];for(;r<i.length&&i[r].trim()&&!/^\s*(```|~~~|#{1,6}\s|>|([-*+]|\d+[.)])\s)/.test(i[r])&&!(i[r].includes("|")&&r+1<i.length&&Be(i[r+1]));)l.push(i[r++]);l.length||l.push(i[r++]);let p=v(t,"p");l.forEach((g,h)=>{h&&p.appendChild(v(t,"br")),T(t,g,p,e)}),n.appendChild(p)}return n}var J=class{constructor(s,e){f(this,"onTick",s);f(this,"onEnd",e);f(this,"until",0);f(this,"tick");f(this,"done")}get active(){return Date.now()<this.until}get secondsLeft(){return Math.max(0,Math.ceil((this.until-Date.now())/1e3))}start(s){let e=Date.now()+Math.max(0,s);e<=this.until||(this.until=e,this.clear(),this.tick=setInterval(()=>this.onTick(this.secondsLeft),1e3),this.done=setTimeout(()=>{this.until=0,this.clear(),this.onEnd()},e-Date.now()))}clear(){clearInterval(this.tick),clearTimeout(this.done)}};var qe=`
36
+ `),r=0;for(;r<i.length;){let o=i[r];if(!o.trim()){r++;continue}let c=o.match(/^\s*(```+|~~~+)\s*([\w+-]*)/);if(c){let g=[];for(r++;r<i.length&&!i[r].trim().startsWith(c[1]);)g.push(i[r++]);r++;let p=C(n,"pre"),h=C(n,"code");c[2]&&(h.dataset.lang=c[2]),h.textContent=g.join(`
37
+ `),p.appendChild(h),t.appendChild(p);continue}let a=o.match(/^(#{1,6})\s+(.*)$/);if(a){let g=`h${Math.min(6,a[1].length+2)}`,p=C(n,g);P(n,a[2],p,e),t.appendChild(p),r++;continue}if(/^\s*([-*_])(\s*\1){2,}\s*$/.test(o)){t.appendChild(C(n,"hr")),r++;continue}if(o.includes("|")&&r+1<i.length&&Je(i[r+1])){let g=C(n,"div","table"),p=C(n,"table"),h=C(n,"thead"),m=C(n,"tr");for(let x of Ke(o)){let w=C(n,"th");P(n,x,w,e),m.appendChild(w)}h.appendChild(m),p.appendChild(h);let b=C(n,"tbody");for(r+=2;r<i.length&&i[r].includes("|")&&i[r].trim();){let x=C(n,"tr");for(let w of Ke(i[r])){let y=C(n,"td");P(n,w,y,e),x.appendChild(y)}b.appendChild(x),r++}p.appendChild(b),g.appendChild(p),t.appendChild(g);continue}if(/^\s*>/.test(o)){let g=[];for(;r<i.length&&/^\s*>/.test(i[r]);)g.push(i[r++].replace(/^\s*>\s?/,""));let p=C(n,"blockquote");p.appendChild(M(n,g.join(`
38
+ `),e)),t.appendChild(p);continue}let d=o.match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(d){let g=/\d/.test(d[2]),p=C(n,g?"ol":"ul");g&&parseInt(d[2],10)!==1&&p.setAttribute("start",String(parseInt(d[2],10)));let h=d[1].length;for(;r<i.length;){let m=i[r].match(/^(\s*)([-*+]|\d+[.)])\s+(.*)$/);if(!m||m[1].length<h||/\d/.test(m[2])!==g)break;if(m[1].length>h){let x=[];for(;r<i.length&&/^\s+/.test(i[r])&&i[r].match(/^(\s*)/)[1].length>h;)x.push(i[r++].slice(h+2));p.lastElementChild?.appendChild(M(n,x.join(`
39
+ `),e));continue}let b=C(n,"li");P(n,m[3],b,e),p.appendChild(b),r++}t.appendChild(p);continue}let l=[];for(;r<i.length&&i[r].trim()&&!/^\s*(```|~~~|#{1,6}\s|>|([-*+]|\d+[.)])\s)/.test(i[r])&&!(i[r].includes("|")&&r+1<i.length&&Je(i[r+1]));)l.push(i[r++]);l.length||l.push(i[r++]);let u=C(n,"p");l.forEach((g,p)=>{p&&u.appendChild(C(n,"br")),P(n,g,u,e)}),t.appendChild(u)}return t}var G=class{constructor(s,e){f(this,"onTick",s);f(this,"onEnd",e);f(this,"until",0);f(this,"tick");f(this,"done")}get active(){return Date.now()<this.until}get secondsLeft(){return Math.max(0,Math.ceil((this.until-Date.now())/1e3))}start(s){let e=Date.now()+Math.max(0,s);e<=this.until||(this.until=e,this.clear(),this.tick=setInterval(()=>this.onTick(this.secondsLeft),1e3),this.done=setTimeout(()=>{this.until=0,this.clear(),this.onEnd()},e-Date.now()))}clear(){clearInterval(this.tick),clearTimeout(this.done)}};var Ge=`
40
40
  :host {
41
41
  --dw-accent: #5446e8;
42
42
  --dw-accent-contrast: #fff;
@@ -276,6 +276,11 @@ details > summary svg.ic { width: 14px; height: 14px; flex: none; }
276
276
  .btn.allow { background: var(--dw-accent); border-color: var(--dw-accent); color: var(--dw-accent-contrast); }
277
277
  .btn.allow.danger { background: #c2334f; border-color: #c2334f; color: #fff; }
278
278
  .btn:focus-visible { outline: 3px solid color-mix(in srgb, var(--dw-accent) 45%, transparent); outline-offset: 2px; }
279
+ .credential-request .bubble { overflow-wrap: anywhere; max-width: 100%; }
280
+ .credential-request p { margin: 8px 0; }
281
+ .credential-request .spin { display: inline-block; vertical-align: middle; }
282
+ .credential-request ul { margin: 8px 0; padding-inline-start: 20px; }
283
+ .credential-actions { display: flex; flex-wrap: wrap; gap: 8px; }
279
284
 
280
285
  /* ---------- composer ---------- */
281
286
  .composer { padding: 10px 12px 12px; border-top: 1px solid var(--dw-border); background: var(--dw-bg); }
@@ -309,8 +314,8 @@ textarea::placeholder { color: var(--dw-muted); }
309
314
  .agent-select { font-size: 16px; max-width: 200px; }
310
315
  }
311
316
  @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
312
- `;var Rt=5e3,Fe=["show-reasoning","show-tool-calls","allow-agent-switch","open","persist","hide-branding","launcher-avatar","dom-actions"],Ye=["endpoint","agent","title","subtitle","greeting","intro","placeholder","suggestions","avatar","position","mode","theme","accent-color","locale","gateway-url","gateway-token","width","height","z-index","dom-actions-root","image-origins","page-context","context-selector","exclude-selectors",...Fe],Ge=t=>t.replace(/-([a-z])/g,(s,e)=>e.toUpperCase()),_t=t=>t!==null&&!/^(false|0|off|no)$/i.test(t),We=()=>{let t=crypto.getRandomValues(new Uint8Array(9));return Array.from(t,s=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"[s&63]).join("")},Nt=t=>t.replace(/^mcp_[^_]+(?:_[^_]+)*?__/,"").replace(/_/g," "),_={get(t){try{return localStorage.getItem(t)}catch{return null}},set(t,s){try{localStorage.setItem(t,s)}catch{}}},Ot=null;function Ht(){return Ot??(Ot=new Promise((t,s)=>{if(window.turnstile)return t();let e=document.createElement("script");e.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",e.async=!0,e.onload=()=>t(),e.onerror=()=>s(new Error("Could not load Turnstile")),document.head.appendChild(e)}))}var Dt=typeof HTMLElement>"u"?class{}:HTMLElement,D=class extends Dt{constructor(){super();f(this,"root");f(this,"overrides",{});f(this,"api",null);f(this,"apiKey","");f(this,"server",null);f(this,"sharedPage");f(this,"preparingPage",!1);f(this,"pagePending",!1);f(this,"pageGeneration",0);f(this,"agentId","");f(this,"conversationId","");f(this,"messages",[]);f(this,"running",null);f(this,"jobAccessLaunch",null);f(this,"activated",!1);f(this,"probedPage",!1);f(this,"strings",ue());f(this,"mql",null);f(this,"registry",new O);f(this,"propActionNames",new Set);f(this,"hooks",{});f(this,"dom",null);f(this,"acks",new Map);f(this,"cooldown",new J(e=>this.renderCooldown(e),()=>this.endCooldown()));f(this,"els");f(this,"onScheme",()=>this.applyTheme());f(this,"pendingFrame",0);f(this,"following",!0);this.root=this.attachShadow({mode:"open"})}static get observedAttributes(){return Ye}get config(){let e={endpoint:"/api/dewee"};for(let n of Ye){let i=this.getAttribute(n);i!==null&&(Fe.includes(n)?e[Ge(n)]=_t(i):n==="suggestions"?e.suggestions=i.trim().startsWith("[")?ge(i,[]):i.split("|").map(r=>r.trim()).filter(Boolean):n==="image-origins"?e.imageOrigins=i.trim().startsWith("[")?ge(i,[]):i.split(",").map(r=>r.trim()).filter(Boolean):n==="exclude-selectors"?e.excludeSelectors=i.trim().startsWith("[")?ge(i,[]):i.split(",").map(r=>r.trim()).filter(Boolean):n==="z-index"?e.zIndex=Number(i):e[Ge(n)]=i)}return{...e,...this.overrides,...this.hooks}}configure(e){let{actions:n,confirm:i,getPageContext:r,headers:o,fetch:c,domActionsRoot:a,contextProvider:d,...l}=e,p=g=>Object.prototype.hasOwnProperty.call(e,g);p("actions")&&this.setPropActions(n??[]),p("confirm")&&(this.hooks.confirm=i),p("getPageContext")&&(this.hooks.getPageContext=r),p("headers")&&(this.hooks.headers=o),p("fetch")&&(this.hooks.fetch=c),p("contextProvider")&&(this.hooks.contextProvider=d),p("domActionsRoot")&&(a===void 0?delete this.hooks.domActionsRoot:this.hooks.domActionsRoot=a),Object.keys(l).length&&(this.overrides={...this.overrides,...l},this.els&&this.applyConfig())}registerActions(e){this.registry.register(e)}unregisterAction(e){return this.propActionNames.delete(e),this.registry.unregister(e)}get headers(){return this.hooks.headers}set headers(e){this.hooks.headers=e}get fetch(){return this.hooks.fetch}set fetch(e){this.hooks.fetch=e}get actionNames(){return this.actionRegistry().names()}actionRegistry(){if(!this.config.domActions)return this.registry;this.dom??(this.dom=Ne({root:()=>this.hooks.domActionsRoot??this.getAttribute("dom-actions-root")??void 0,exclude:o=>o===this||this.contains(o)||o.closest("dewee-chat")!==null}));let e=this.registry.names().map(o=>this.registry.get(o)),n=S.maxActions-e.length,i=this.dom.actions.filter(o=>!this.registry.get(o.name)).slice(0,Math.max(0,n)),r=new O;return r.register([...e,...i]),r}setPropActions(e){let n=new Set(e.map(i=>i.name));for(let i of this.propActionNames)n.has(i)||this.registry.unregister(i);e.length&&this.registry.register(e),this.propActionNames=n}open(){this.config.mode!=="inline"&&(this.setAttribute("data-open",""),this.removeAttribute("data-unread"),this.els.launcher.setAttribute("aria-expanded","true"),this.activate(),setTimeout(()=>this.els.input.focus(),120),this.emit("dewee:open"))}close(){this.config.mode!=="inline"&&(this.removeAttribute("data-open"),this.els.launcher.setAttribute("aria-expanded","false"),this.emit("dewee:close"))}toggle(){this.hasAttribute("data-open")?this.close():this.open()}async send(e){let n=e.trim();if(!n||this.running||this.preparingPage||this.cooldown.active)return;this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.open(),await this.activate();let i;if(this.els.pageChoice.checked){if(this.pagePending){this.showNotice(this.strings.pageUnavailable);return}this.preparingPage=!0;let o=this.pageGeneration;try{let c=this.sharedPage,a=await this.captureCurrentPage();if(!this.els.pageChoice.checked||o!==this.pageGeneration)return;if(!c||!a||this.pageFingerprint(c)!==this.pageFingerprint(a)){this.sharedPage=a,this.renderPagePreview(),this.els.pageChoice.checked=!1,this.showNotice(this.strings.pageChanged);return}i=a}catch{this.sharedPage=void 0,this.els.pageChoice.checked=!1,this.renderPagePreview(),this.showNotice(this.strings.pageUnavailable);return}finally{this.preparingPage=!1}this.els.pageChoice.checked=!1,this.sharedPage=void 0,this.renderPagePreview()}this.els.input.value="",this.autosize();let r={message:n,hidden:!1};for(let o=0;r;o++){let c=await this.runTurn(r.message,r.hidden,o===0?i:void 0);if(r=null,c.status!=="done"||c.stopped||!this.actionRegistry().size)break;let{calls:a}=X(c.content);if(!a.length)break;c.actions=a.map(p=>({id:p.id,name:p.name,args:p.ok?p.args:void 0,status:"pending"}));let d=this.config.maxActionRounds??5;if(o>=d){for(let p of c.actions)Object.assign(p,{status:"error",error:"Automatic action limit reached"});this.updateMessage(c),this.showNotice(this.strings.actionLimit(d));break}this.updateMessage(c);let l=await this.runActions(c,a);l&&(r={message:Te(l,this.server?.maxMessageLength??4e3),hidden:!0})}}async runTurn(e,n,i){this.pushMessage({role:"user",content:e,hidden:n});let r={role:"assistant",content:"",status:"streaming",startedAt:Date.now()};this.pushMessage(r),this.setRunning(new AbortController),this.emit("dewee:send",{message:e,agent:this.agentId,conversationId:this.conversationId,auto:n||void 0});try{await this.client().ensureSession(),await this.client().chat({...this.chatBody(e),...i?{page_context:i}:{}},o=>this.onStreamEvent(r,o),this.running.signal),r.status==="streaming"&&(r.status="done")}catch(o){o.name==="AbortError"?(r.status="done",r.stopped=!0,r.content||(r.content=`_${this.strings.stopped}_`)):(r.status="error",this.showError(r,o))}finally{this.finishThinking(r),this.updateMessage(r),this.setRunning(null),r.status==="done"&&(r.actionsHash&&r.ackVisitor&&!r.stopped&&this.setAck(r.actionsHash,r.ackVisitor),this.emit("dewee:reply",{content:r.content,agent:this.agentId,conversationId:this.conversationId}),this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.setAttribute("data-unread",""))}return r}chatBody(e){let n={message:e,agent:this.agentId,conversationId:this.conversationId},i=this.actionRegistry();if(i.size){n.actions=i.manifest();let o=this.client().visitorId(),c=o?this.getAck(o):void 0;c&&(n.actionsHash=c)}let r=this.pageContext();return r!==void 0&&(n.pageContext=r),n}pageContext(){let e=this.hooks.getPageContext;if(e)try{let n=e();if(n==null)return;let i=new TextEncoder().encode(JSON.stringify(n)).length;return i<=S.maxPageContextBytes?n:(console.warn(`[dewee-webchat] getPageContext() returned ${i} bytes; the limit is ${S.maxPageContextBytes}. Context not sent.`),{truncated:!0})}catch(n){console.warn("[dewee-webchat] getPageContext() failed:",n);return}}ackKey(e){return`dewee-webchat:actions:${this.config.endpoint}:${this.agentId}:${e}:${this.conversationId}`}getAck(e){let n=this.ackKey(e);return this.acks.get(n)??(this.config.persist!==!1?_.get(n)??void 0:void 0)}setAck(e,n){let i=this.ackKey(n);this.acks.set(i,e),this.config.persist!==!1&&_.set(i,e)}async runActions(e,n){let i=new AbortController;this.setRunning(i);let r=[],o={agent:this.agentId,conversationId:this.conversationId},c=this.actionRegistry();try{for(let[a,d]of n.entries()){let l=e.actions[a],p=d.ok?c.get(d.name)?.sensitivity:void 0,g=d.ok?d.args:void 0;this.emit("dewee:action",{phase:"start",id:d.id,name:d.name,sensitivity:p,args:g,...o});let h=await Re(d,{registry:c,confirm:(u,m)=>this.confirmAction(c,u,m,i.signal),signal:i.signal,timeoutMs:this.config.actionTimeoutMs,...o,onStatus:u=>{l.status=u,this.updateMessage(e)}});h.error&&(l.error=h.error),this.updateMessage(e),r.push(h),this.emit("dewee:action",{phase:"result",id:h.id,name:h.name,sensitivity:p,args:g,status:h.status,result:h.result,error:h.error,...o})}}finally{this.setRunning(null)}return i.signal.aborted?null:r}confirmAction(e,n,i,r){let c=this.dom?.actions.includes(e.get(n.name))?this.dom.target(i):void 0,a=c?{...i,target:c}:i;return this.hooks.confirm?this.hooks.confirm(n,a):(this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.open(),je(this.els.panel,this.strings,n,a,r))}showNotice(e){let n=document.createElement("div");n.className="notice",n.setAttribute("role","status"),n.textContent=e,this.els.log.appendChild(n),this.scrollToBottom(!0)}stop(){this.running?.abort()}async renewSession(){this.stop();try{await this.client().renewSession()}catch(e){this.showError(null,e);return}this.activated&&await this.loadConversation()}reuseHint(){return this.client().reuseHint()}async startLink(){this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.open(),await this.activate();try{let e=await this.client().link();return this.renderLink(e),this.emit("dewee:link",{expiresAt:e.expiresAt,deepLinks:e.deepLinks}),e}catch(e){return this.showError(null,e),null}}async openJobAccess(){if(this.jobAccessLaunch)return;let e=new AbortController;this.jobAccessLaunch=e,this.els.jobAccess.disabled=!0;try{await $e(n=>this.client().jobAccess(n),e.signal),this.showNotice(this.strings.jobAccessOpened)}catch(n){if(e.signal.aborted)return;n instanceof A?this.showNotice(n.code==="popup_blocked"?this.strings.jobAccessPopupBlocked:n.code==="popup_closed"?this.strings.jobAccessPopupClosed:this.strings.jobAccessUnavailable):n instanceof E&&Y(n.code)?this.showError(null,n):this.showNotice(this.strings.jobAccessUnavailable)}finally{this.jobAccessLaunch=null,this.els.jobAccess.disabled=!1}}renderLink(e){let n=this.strings,i=document.createElement("div");i.className="msg assistant link";let r=document.createElement("div");r.className="bubble";let o=document.createElement("div");o.className="md";let c=l=>{let p=document.createElement("p");return p.textContent=l,p},a=document.createElement("code");a.textContent=e.proofCode;let d=document.createElement("p");if(d.appendChild(a),o.append(c(n.linkIntro),d),e.deepLinks.length){let l=document.createElement("ul");for(let p of e.deepLinks){let g=document.createElement("li"),h=p.displayName||p.name;g.textContent=n.linkContinueOn(Bt(p.channelType))+(h?` \xB7 ${h}`:""),l.appendChild(g)}o.appendChild(l)}else o.appendChild(c(n.linkNoTargets));o.appendChild(c(n.linkExpires(Math.max(1,Math.round((e.expiresAt-Date.now())/6e4))))),r.appendChild(o),i.appendChild(r),this.messages.length||this.els.log.replaceChildren(),this.els.log.appendChild(i),this.scrollToBottom(!0)}newConversation(){this.stop(),this.conversationId=We(),this.config.persist!==!1&&_.set(this.convKey(),this.conversationId),this.messages=[],this.renderLog(),this.els.input.focus()}connectedCallback(){this.els||this.renderShell(),this.applyConfig(),(this.config.mode==="inline"||this.config.open)&&(this.config.mode!=="inline"?this.open():this.activate())}disconnectedCallback(){this.pageGeneration++,this.sharedPage=void 0,this.els.pageChoice.checked=!1,this.renderPagePreview(),U(this.root);for(let e of this.messages)e.view&&(e.view.mdKey=void 0);this.jobAccessLaunch?.abort(),this.stop(),this.mql?.removeEventListener("change",this.onScheme)}attributeChangedCallback(){this.els&&this.applyConfig()}emit(e,n){this.dispatchEvent(new CustomEvent(e,{detail:n,bubbles:!0,composed:!0}))}client(){let e=this.config,n=[e.endpoint,e.gatewayUrl,e.gatewayToken].join("|");return(!this.api||n!==this.apiKey)&&(this.apiKey=n,this.api=new M({endpoint:e.endpoint,gatewayUrl:e.gatewayUrl,gatewayToken:e.gatewayToken,turnstile:i=>this.challenge(i),headers:()=>{let i=this.hooks.headers;return(typeof i=="function"?i():i)??{}},fetch:(i,r)=>(this.hooks.fetch??globalThis.fetch)(i,r)})),this.api}convKey(){return`dewee-webchat:conv:${this.config.endpoint}:${this.config.gatewayUrl||""}:${this.agentId}`}applyTheme(){let e=this.config.theme||"light",n=e==="dark"||e==="auto"&&!!this.mql?.matches;this.setAttribute("data-theme",n?"dark":"light")}applyConfig(){let e=this.config;this.strings=ue(e.locale);let n=this.strings;this.setAttribute("data-position",e.position||"bottom-right"),this.setAttribute("data-mode",e.mode||"floating"),e.theme==="auto"&&!this.mql&&(this.mql=matchMedia("(prefers-color-scheme: dark)"),this.mql.addEventListener("change",this.onScheme)),this.applyTheme();let i=(o,c)=>c!==void 0&&c!==""?this.style.setProperty(o,String(c)):this.style.removeProperty(o);i("--dw-accent",e.accentColor),i("--dw-width",e.width),i("--dw-height",e.height),i("--dw-z",e.zIndex);let r=this.els;if(r.title.textContent=e.title||n.title,r.avatar.replaceChildren(),e.avatar){let o=document.createElement("img");o.src=e.avatar,o.alt="",r.avatar.appendChild(o)}else r.avatar.textContent=(e.title||n.title).trim().charAt(0).toUpperCase();if(r.launcher.innerHTML=e.avatar&&e.launcherAvatar?"":C.chat,e.avatar&&e.launcherAvatar){let o=document.createElement("img");o.src=e.avatar,o.alt="",r.launcher.appendChild(o)}if(r.launcher.insertAdjacentHTML("beforeend",'<span class="badge"></span>'),r.launcher.setAttribute("aria-label",n.open),r.close.setAttribute("aria-label",n.close),r.close.title=n.close,r.newChat.setAttribute("aria-label",n.newChat),r.newChat.title=n.newChat,r.jobAccess.setAttribute("aria-label",n.jobAccess),r.jobAccess.title=n.jobAccess,r.input.placeholder=e.placeholder||n.placeholder,r.pageLabel.textContent=n.pageShare,this.updatePageChoice(),r.foot.hidden=!!e.hideBranding,r.foot.querySelector(".by").textContent=n.poweredBy+" ",this.renderSubtitle(),this.updateSendButton(),this.activated&&this.api&&this.apiKey!==[e.endpoint,e.gatewayUrl,e.gatewayToken].join("|"))this.activated=!1,this.server=null,this.probedPage=!1,this.activate();else if(this.activated&&!this.probedPage&&(e.pageContext==="metadata"||e.pageContext==="content"))this.activated=!1,this.activate();else if(this.activated&&e.agent&&e.agent!==this.agentId&&this.server)this.switchAgent(e.agent);else if(this.activated)if(!this.messages.length)this.renderLog();else for(let o of this.messages)this.updateMessage(o)}renderShell(){this.root.innerHTML=`
313
- <style>${qe}</style>
317
+ `;var Bt=5e3,Xe=new Set(["credential_requests_unavailable","credential_request_not_found"]),nt=["show-reasoning","show-tool-calls","allow-agent-switch","open","persist","hide-branding","launcher-avatar","dom-actions"],Ze=["endpoint","agent","title","subtitle","greeting","intro","placeholder","suggestions","avatar","position","mode","theme","accent-color","locale","gateway-url","gateway-token","width","height","z-index","dom-actions-root","image-origins","page-context","context-selector","exclude-selectors",...nt],et=n=>n.replace(/-([a-z])/g,(s,e)=>e.toUpperCase()),jt=n=>n!==null&&!/^(false|0|off|no)$/i.test(n),tt=()=>{let n=crypto.getRandomValues(new Uint8Array(9));return Array.from(n,s=>"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"[s&63]).join("")},Vt=n=>n.replace(/^mcp_[^_]+(?:_[^_]+)*?__/,"").replace(/_/g," "),N={get(n){try{return localStorage.getItem(n)}catch{return null}},set(n,s){try{localStorage.setItem(n,s)}catch{}}},zt=null;function Ut(){return zt??(zt=new Promise((n,s)=>{if(window.turnstile)return n();let e=document.createElement("script");e.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",e.async=!0,e.onload=()=>n(),e.onerror=()=>s(new Error("Could not load Turnstile")),document.head.appendChild(e)}))}var Jt=typeof HTMLElement>"u"?class{}:HTMLElement,q=class extends Jt{constructor(){super();f(this,"root");f(this,"overrides",{});f(this,"api",null);f(this,"apiKey","");f(this,"server",null);f(this,"sharedPage");f(this,"preparingPage",!1);f(this,"pagePending",!1);f(this,"pageGeneration",0);f(this,"agentId","");f(this,"conversationId","");f(this,"messages",[]);f(this,"running",null);f(this,"jobAccessLaunch",null);f(this,"credentialCards",new Map);f(this,"credentialGeneration",0);f(this,"credentialBusy",new Set);f(this,"credentialPopups",new Map);f(this,"credentialRequestsInFlight",new Set);f(this,"activated",!1);f(this,"probedPage",!1);f(this,"strings",me());f(this,"mql",null);f(this,"registry",new D);f(this,"propActionNames",new Set);f(this,"hooks",{});f(this,"dom",null);f(this,"acks",new Map);f(this,"cooldown",new G(e=>this.renderCooldown(e),()=>this.endCooldown()));f(this,"els");f(this,"onScheme",()=>this.applyTheme());f(this,"pendingFrame",0);f(this,"following",!0);this.root=this.attachShadow({mode:"open"})}static get observedAttributes(){return Ze}get config(){let e={endpoint:"/api/dewee"};for(let t of Ze){let i=this.getAttribute(t);i!==null&&(nt.includes(t)?e[et(t)]=jt(i):t==="suggestions"?e.suggestions=i.trim().startsWith("[")?be(i,[]):i.split("|").map(r=>r.trim()).filter(Boolean):t==="image-origins"?e.imageOrigins=i.trim().startsWith("[")?be(i,[]):i.split(",").map(r=>r.trim()).filter(Boolean):t==="exclude-selectors"?e.excludeSelectors=i.trim().startsWith("[")?be(i,[]):i.split(",").map(r=>r.trim()).filter(Boolean):t==="z-index"?e.zIndex=Number(i):e[et(t)]=i)}return{...e,...this.overrides,...this.hooks}}configure(e){let{actions:t,confirm:i,getPageContext:r,headers:o,fetch:c,domActionsRoot:a,contextProvider:d,...l}=e,u=g=>Object.prototype.hasOwnProperty.call(e,g);u("actions")&&this.setPropActions(t??[]),u("confirm")&&(this.hooks.confirm=i),u("getPageContext")&&(this.hooks.getPageContext=r),u("headers")&&(this.hooks.headers=o),u("fetch")&&(this.hooks.fetch=c),u("contextProvider")&&(this.hooks.contextProvider=d),u("domActionsRoot")&&(a===void 0?delete this.hooks.domActionsRoot:this.hooks.domActionsRoot=a),Object.keys(l).length&&(this.overrides={...this.overrides,...l},this.els&&this.applyConfig())}registerActions(e){this.registry.register(e)}unregisterAction(e){return this.propActionNames.delete(e),this.registry.unregister(e)}get headers(){return this.hooks.headers}set headers(e){this.hooks.headers=e}get fetch(){return this.hooks.fetch}set fetch(e){this.hooks.fetch=e}get actionNames(){return this.actionRegistry().names()}actionRegistry(){if(!this.config.domActions)return this.registry;this.dom??(this.dom=He({root:()=>this.hooks.domActionsRoot??this.getAttribute("dom-actions-root")??void 0,exclude:o=>o===this||this.contains(o)||o.closest("dewee-chat")!==null}));let e=this.registry.names().map(o=>this.registry.get(o)),t=T.maxActions-e.length,i=this.dom.actions.filter(o=>!this.registry.get(o.name)).slice(0,Math.max(0,t)),r=new D;return r.register([...e,...i]),r}setPropActions(e){let t=new Set(e.map(i=>i.name));for(let i of this.propActionNames)t.has(i)||this.registry.unregister(i);e.length&&this.registry.register(e),this.propActionNames=t}open(){this.config.mode!=="inline"&&(this.setAttribute("data-open",""),this.removeAttribute("data-unread"),this.els.launcher.setAttribute("aria-expanded","true"),this.activate(),setTimeout(()=>this.els.input.focus(),120),this.emit("dewee:open"))}close(){this.config.mode!=="inline"&&(this.removeAttribute("data-open"),this.els.launcher.setAttribute("aria-expanded","false"),this.emit("dewee:close"))}toggle(){this.hasAttribute("data-open")?this.close():this.open()}async send(e){let t=e.trim();if(!t||this.running||this.preparingPage||this.cooldown.active)return;this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.open(),await this.activate();let i;if(this.els.pageChoice.checked){if(this.pagePending){this.showNotice(this.strings.pageUnavailable);return}this.preparingPage=!0;let o=this.pageGeneration;try{let c=this.sharedPage,a=await this.captureCurrentPage();if(!this.els.pageChoice.checked||o!==this.pageGeneration)return;if(!c||!a||this.pageFingerprint(c)!==this.pageFingerprint(a)){this.sharedPage=a,this.renderPagePreview(),this.els.pageChoice.checked=!1,this.showNotice(this.strings.pageChanged);return}i=a}catch{this.sharedPage=void 0,this.els.pageChoice.checked=!1,this.renderPagePreview(),this.showNotice(this.strings.pageUnavailable);return}finally{this.preparingPage=!1}this.els.pageChoice.checked=!1,this.sharedPage=void 0,this.renderPagePreview()}this.els.input.value="",this.autosize();let r={message:t,hidden:!1};for(let o=0;r;o++){let c=await this.runTurn(r.message,r.hidden,o===0?i:void 0);if(r=null,c.status!=="done"||c.stopped||!this.actionRegistry().size)break;let{calls:a}=te(c.content);if(!a.length)break;c.actions=a.map(u=>({id:u.id,name:u.name,args:u.ok?u.args:void 0,status:"pending"}));let d=this.config.maxActionRounds??5;if(o>=d){for(let u of c.actions)Object.assign(u,{status:"error",error:"Automatic action limit reached"});this.updateMessage(c),this.showNotice(this.strings.actionLimit(d));break}this.updateMessage(c);let l=await this.runActions(c,a);l&&(r={message:Le(l,this.server?.maxMessageLength??4e3),hidden:!0})}}async runTurn(e,t,i){let r=this.credentialGeneration;this.pushMessage({role:"user",content:e,hidden:t});let o={role:"assistant",content:"",status:"streaming",startedAt:Date.now()};this.pushMessage(o),this.setRunning(new AbortController),this.emit("dewee:send",{message:e,agent:this.agentId,conversationId:this.conversationId,auto:t||void 0});try{await this.client().ensureSession(),await this.client().chat({...this.chatBody(e),...i?{page_context:i}:{}},c=>{r===this.credentialGeneration&&this.onStreamEvent(o,c)},this.running.signal),o.status==="streaming"&&(o.status="done")}catch(c){c.name==="AbortError"?(o.status="done",o.stopped=!0,o.content||(o.content=`_${this.strings.stopped}_`)):(o.status="error",this.showError(o,c))}finally{this.finishThinking(o),this.updateMessage(o),this.setRunning(null),o.status==="done"&&(o.actionsHash&&o.ackVisitor&&!o.stopped&&this.setAck(o.actionsHash,o.ackVisitor),this.emit("dewee:reply",{content:o.content,agent:this.agentId,conversationId:this.conversationId}),this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.setAttribute("data-unread",""))}return o}chatBody(e){let t={message:e,agent:this.agentId,conversationId:this.conversationId},i=this.actionRegistry();if(i.size){t.actions=i.manifest();let o=this.client().visitorId(),c=o?this.getAck(o):void 0;c&&(t.actionsHash=c)}let r=this.pageContext();return r!==void 0&&(t.pageContext=r),t}pageContext(){let e=this.hooks.getPageContext;if(e)try{let t=e();if(t==null)return;let i=new TextEncoder().encode(JSON.stringify(t)).length;return i<=T.maxPageContextBytes?t:(console.warn(`[dewee-webchat] getPageContext() returned ${i} bytes; the limit is ${T.maxPageContextBytes}. Context not sent.`),{truncated:!0})}catch(t){console.warn("[dewee-webchat] getPageContext() failed:",t);return}}ackKey(e){return`dewee-webchat:actions:${this.config.endpoint}:${this.agentId}:${e}:${this.conversationId}`}getAck(e){let t=this.ackKey(e);return this.acks.get(t)??(this.config.persist!==!1?N.get(t)??void 0:void 0)}setAck(e,t){let i=this.ackKey(t);this.acks.set(i,e),this.config.persist!==!1&&N.set(i,e)}async runActions(e,t){let i=new AbortController;this.setRunning(i);let r=[],o={agent:this.agentId,conversationId:this.conversationId},c=this.actionRegistry();try{for(let[a,d]of t.entries()){let l=e.actions[a],u=d.ok?c.get(d.name)?.sensitivity:void 0,g=d.ok?d.args:void 0;this.emit("dewee:action",{phase:"start",id:d.id,name:d.name,sensitivity:u,args:g,...o});let p=await Oe(d,{registry:c,confirm:(h,m)=>this.confirmAction(c,h,m,i.signal),signal:i.signal,timeoutMs:this.config.actionTimeoutMs,...o,onStatus:h=>{l.status=h,this.updateMessage(e)}});p.error&&(l.error=p.error),this.updateMessage(e),r.push(p),this.emit("dewee:action",{phase:"result",id:p.id,name:p.name,sensitivity:u,args:g,status:p.status,result:p.result,error:p.error,...o})}}finally{this.setRunning(null)}return i.signal.aborted?null:r}confirmAction(e,t,i,r){let c=this.dom?.actions.includes(e.get(t.name))?this.dom.target(i):void 0,a=c?{...i,target:c}:i;return this.hooks.confirm?this.hooks.confirm(t,a):(this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.open(),Ue(this.els.panel,this.strings,t,a,r))}showNotice(e){let t=document.createElement("div");t.className="notice",t.setAttribute("role","status"),t.textContent=e,this.els.log.appendChild(t),this.scrollToBottom(!0)}stop(){this.running?.abort()}async renewSession(){this.stop(),this.clearCredentials(),this.renderLog();try{await this.client().renewSession()}catch(e){this.showError(null,e);return}this.activated&&await this.loadConversation()}reuseHint(){return this.client().reuseHint()}async startLink(){this.config.mode!=="inline"&&!this.hasAttribute("data-open")&&this.open(),await this.activate();try{let e=await this.client().link();return this.renderLink(e),this.emit("dewee:link",{expiresAt:e.expiresAt,deepLinks:e.deepLinks}),e}catch(e){return this.showError(null,e),null}}async openJobAccess(){if(this.jobAccessLaunch)return;let e=new AbortController;this.jobAccessLaunch=e,this.els.jobAccess.disabled=!0;try{await ze(t=>this.client().jobAccess(t),e.signal),this.showNotice(this.strings.jobAccessOpened)}catch(t){if(e.signal.aborted)return;t instanceof k?this.showNotice(t.code==="popup_blocked"?this.strings.jobAccessPopupBlocked:t.code==="popup_closed"?this.strings.jobAccessPopupClosed:this.strings.jobAccessUnavailable):t instanceof v&&W(t.code)?this.showError(null,t):this.showNotice(this.strings.jobAccessUnavailable)}finally{this.jobAccessLaunch=null,this.els.jobAccess.disabled=!1}}renderLink(e){let t=this.strings,i=document.createElement("div");i.className="msg assistant link";let r=document.createElement("div");r.className="bubble";let o=document.createElement("div");o.className="md";let c=l=>{let u=document.createElement("p");return u.textContent=l,u},a=document.createElement("code");a.textContent=e.proofCode;let d=document.createElement("p");if(d.appendChild(a),o.append(c(t.linkIntro),d),e.deepLinks.length){let l=document.createElement("ul");for(let u of e.deepLinks){let g=document.createElement("li"),p=u.displayName||u.name;g.textContent=t.linkContinueOn(Ft(u.channelType))+(p?` \xB7 ${p}`:""),l.appendChild(g)}o.appendChild(l)}else o.appendChild(c(t.linkNoTargets));o.appendChild(c(t.linkExpires(Math.max(1,Math.round((e.expiresAt-Date.now())/6e4))))),r.appendChild(o),i.appendChild(r),this.messages.length||this.els.log.replaceChildren(),this.els.log.appendChild(i),this.scrollToBottom(!0)}newConversation(){this.stop(),this.clearCredentials(),this.conversationId=tt(),this.config.persist!==!1&&N.set(this.convKey(),this.conversationId),this.messages=[],this.renderLog(),this.els.input.focus()}connectedCallback(){this.els||this.renderShell(),this.applyConfig(),(this.config.mode==="inline"||this.config.open)&&(this.config.mode!=="inline"?this.open():this.activate())}disconnectedCallback(){this.clearCredentials(),this.pageGeneration++,this.sharedPage=void 0,this.els.pageChoice.checked=!1,this.renderPagePreview(),K(this.root);for(let e of this.messages)e.view&&(e.view.mdKey=void 0);this.jobAccessLaunch?.abort(),this.stop(),this.mql?.removeEventListener("change",this.onScheme)}attributeChangedCallback(){this.els&&this.applyConfig()}emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}client(){let e=this.config,t=[e.endpoint,e.gatewayUrl,e.gatewayToken].join("|");return(!this.api||t!==this.apiKey)&&(this.apiKey=t,this.api=new _({endpoint:e.endpoint,gatewayUrl:e.gatewayUrl,gatewayToken:e.gatewayToken,turnstile:i=>this.challenge(i),headers:()=>{let i=this.hooks.headers;return(typeof i=="function"?i():i)??{}},fetch:(i,r)=>(this.hooks.fetch??globalThis.fetch)(i,r)})),this.api}convKey(){return`dewee-webchat:conv:${this.config.endpoint}:${this.config.gatewayUrl||""}:${this.agentId}`}applyTheme(){let e=this.config.theme||"light",t=e==="dark"||e==="auto"&&!!this.mql?.matches;this.setAttribute("data-theme",t?"dark":"light")}applyConfig(){let e=this.config;this.strings=me(e.locale);let t=this.strings;this.setAttribute("data-position",e.position||"bottom-right"),this.setAttribute("data-mode",e.mode||"floating"),e.theme==="auto"&&!this.mql&&(this.mql=matchMedia("(prefers-color-scheme: dark)"),this.mql.addEventListener("change",this.onScheme)),this.applyTheme();let i=(o,c)=>c!==void 0&&c!==""?this.style.setProperty(o,String(c)):this.style.removeProperty(o);i("--dw-accent",e.accentColor),i("--dw-width",e.width),i("--dw-height",e.height),i("--dw-z",e.zIndex);let r=this.els;if(r.title.textContent=e.title||t.title,r.avatar.replaceChildren(),e.avatar){let o=document.createElement("img");o.src=e.avatar,o.alt="",r.avatar.appendChild(o)}else r.avatar.textContent=(e.title||t.title).trim().charAt(0).toUpperCase();if(r.launcher.innerHTML=e.avatar&&e.launcherAvatar?"":A.chat,e.avatar&&e.launcherAvatar){let o=document.createElement("img");o.src=e.avatar,o.alt="",r.launcher.appendChild(o)}if(r.launcher.insertAdjacentHTML("beforeend",'<span class="badge"></span>'),r.launcher.setAttribute("aria-label",t.open),r.close.setAttribute("aria-label",t.close),r.close.title=t.close,r.newChat.setAttribute("aria-label",t.newChat),r.newChat.title=t.newChat,r.jobAccess.setAttribute("aria-label",t.jobAccess),r.jobAccess.title=t.jobAccess,r.input.placeholder=e.placeholder||t.placeholder,r.pageLabel.textContent=t.pageShare,this.updatePageChoice(),r.foot.hidden=!!e.hideBranding,r.foot.querySelector(".by").textContent=t.poweredBy+" ",this.renderSubtitle(),this.updateSendButton(),this.activated&&this.api&&this.apiKey!==[e.endpoint,e.gatewayUrl,e.gatewayToken].join("|"))this.activated=!1,this.server=null,this.probedPage=!1,this.activate();else if(this.activated&&!this.probedPage&&(e.pageContext==="metadata"||e.pageContext==="content"))this.activated=!1,this.activate();else if(this.activated&&e.agent&&e.agent!==this.agentId&&this.server)this.switchAgent(e.agent);else if(this.activated)if(!this.messages.length)this.renderLog();else for(let o of this.messages)this.updateMessage(o)}renderShell(){this.root.innerHTML=`
318
+ <style>${Ge}</style>
314
319
  <button class="launcher" part="launcher" aria-expanded="false" aria-haspopup="dialog"></button>
315
320
  <section class="panel" part="panel" role="dialog" aria-label="Chat">
316
321
  <header class="head" part="header">
@@ -319,9 +324,9 @@ textarea::placeholder { color: var(--dw-muted); }
319
324
  <div class="title"></div>
320
325
  <div class="subtitle"><span class="dot"></span><span class="status"></span><select class="agent-select" hidden></select></div>
321
326
  </div>
322
- <button class="icon-btn new">${C.newChat}</button>
323
- <button class="icon-btn job-access" hidden>${C.jobAccess}</button>
324
- <button class="icon-btn close">${C.close}</button>
327
+ <button class="icon-btn new">${A.newChat}</button>
328
+ <button class="icon-btn job-access" hidden>${A.jobAccess}</button>
329
+ <button class="icon-btn close">${A.close}</button>
325
330
  </header>
326
331
  <div class="log" part="log" role="log" aria-live="polite"></div>
327
332
  <div class="challenge"><slot name="challenge"></slot></div>
@@ -335,9 +340,9 @@ textarea::placeholder { color: var(--dw-muted); }
335
340
  </div>
336
341
  <div class="foot"><span><span class="by"></span><a href="https://dewee.sh" target="_blank" rel="noopener">dewee</a></span><span class="meta"></span></div>
337
342
  </form>
338
- </section>`;let e=i=>this.root.querySelector(i);this.els={launcher:e(".launcher"),panel:e(".panel"),log:e(".log"),title:e(".title"),subtitle:e(".subtitle"),status:e(".status"),avatar:e(".avatar"),select:e(".agent-select"),input:e("textarea"),send:e(".send"),newChat:e(".new"),jobAccess:e(".job-access"),close:e(".close"),foot:e(".foot"),cooldown:e(".cooldown"),announcer:e(".announcer"),pageChoice:e(".page-choice"),pageWrap:e(".page-context"),pageLabel:e(".page-label"),pagePreview:e(".page-preview")};let n=this.els;n.launcher.addEventListener("click",()=>this.toggle()),n.close.addEventListener("click",()=>this.close()),n.log.addEventListener("scroll",()=>{this.following=this.nearBottom()},{passive:!0}),n.newChat.addEventListener("click",()=>this.newConversation()),n.jobAccess.addEventListener("click",()=>{this.openJobAccess()}),n.pageChoice.addEventListener("change",()=>{this.choosePage()}),n.select.addEventListener("change",()=>this.switchAgent(n.select.value)),e("form").addEventListener("submit",i=>{i.preventDefault(),this.running?this.stop():this.send(n.input.value)}),n.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&i.keyCode!==229&&(i.preventDefault(),this.running||this.send(n.input.value))}),n.input.addEventListener("input",()=>{this.autosize(),this.updateSendButton()}),n.panel.addEventListener("keydown",i=>{i.key==="Escape"&&this.close()})}autosize(){let e=this.els.input;e.style.height="auto",e.style.height=Math.min(e.scrollHeight,140)+"px"}updatePageChoice(){let e=this.config.pageContext,n=(e==="metadata"||e==="content")&&this.server?.pageContextVersions?.includes(1)===!0;this.els.pageWrap.hidden=!n,n||(this.pageGeneration++,this.pagePending=!1,this.els.pageChoice.checked=!1,this.sharedPage=void 0,this.renderPagePreview())}async captureCurrentPage(){let e=this.config;if(e.pageContext!=="metadata"&&e.pageContext!=="content"||!this.server?.pageContextVersions?.includes(1))return;let n=document.location.href,{capturePageContext:i,providedPageContext:r}=await Promise.resolve().then(()=>(Ke(),Ve)),o=this.hooks.contextProvider,c=JSON.stringify([e.pageContext,e.contextSelector,e.excludeSelectors]),a=i(document,{mode:o?"metadata":e.pageContext,selector:e.contextSelector,excludeSelectors:e.excludeSelectors}),d=a;if(a&&o){let p;try{let g=await Promise.race([o(),new Promise((h,u)=>{p=setTimeout(()=>u(new Error("Page context timed out")),5e3)})]);d=r(g,a,e.pageContext)}finally{p&&clearTimeout(p)}}let l=this.config;if(!(!this.isConnected||n!==document.location.href||o!==this.hooks.contextProvider||c!==JSON.stringify([l.pageContext,l.contextSelector,l.excludeSelectors])))return d}pageFingerprint(e){let{captured_at:n,...i}=e;return JSON.stringify(i)}renderPagePreview(){let e=this.els.pagePreview;e.hidden=!this.sharedPage,e.textContent=this.sharedPage?[this.sharedPage.title,this.sharedPage.url,this.sharedPage.description,this.sharedPage.selection,this.sharedPage.content?.text].filter(Boolean).join(`
343
+ </section>`;let e=i=>this.root.querySelector(i);this.els={launcher:e(".launcher"),panel:e(".panel"),log:e(".log"),title:e(".title"),subtitle:e(".subtitle"),status:e(".status"),avatar:e(".avatar"),select:e(".agent-select"),input:e("textarea"),send:e(".send"),newChat:e(".new"),jobAccess:e(".job-access"),close:e(".close"),foot:e(".foot"),cooldown:e(".cooldown"),announcer:e(".announcer"),pageChoice:e(".page-choice"),pageWrap:e(".page-context"),pageLabel:e(".page-label"),pagePreview:e(".page-preview")};let t=this.els;t.launcher.addEventListener("click",()=>this.toggle()),t.close.addEventListener("click",()=>this.close()),t.log.addEventListener("scroll",()=>{this.following=this.nearBottom()},{passive:!0}),t.newChat.addEventListener("click",()=>this.newConversation()),t.jobAccess.addEventListener("click",()=>{this.openJobAccess()}),t.pageChoice.addEventListener("change",()=>{this.choosePage()}),t.select.addEventListener("change",()=>this.switchAgent(t.select.value)),e("form").addEventListener("submit",i=>{i.preventDefault(),this.running?this.stop():this.send(t.input.value)}),t.input.addEventListener("keydown",i=>{i.key==="Enter"&&!i.shiftKey&&!i.isComposing&&i.keyCode!==229&&(i.preventDefault(),this.running||this.send(t.input.value))}),t.input.addEventListener("input",()=>{this.autosize(),this.updateSendButton()}),t.panel.addEventListener("keydown",i=>{i.key==="Escape"&&this.close()})}autosize(){let e=this.els.input;e.style.height="auto",e.style.height=Math.min(e.scrollHeight,140)+"px"}updatePageChoice(){let e=this.config.pageContext,t=(e==="metadata"||e==="content")&&this.server?.pageContextVersions?.includes(1)===!0;this.els.pageWrap.hidden=!t,t||(this.pageGeneration++,this.pagePending=!1,this.els.pageChoice.checked=!1,this.sharedPage=void 0,this.renderPagePreview())}async captureCurrentPage(){let e=this.config;if(e.pageContext!=="metadata"&&e.pageContext!=="content"||!this.server?.pageContextVersions?.includes(1))return;let t=document.location.href,{capturePageContext:i,providedPageContext:r}=await Promise.resolve().then(()=>(Qe(),We)),o=this.hooks.contextProvider,c=JSON.stringify([e.pageContext,e.contextSelector,e.excludeSelectors]),a=i(document,{mode:o?"metadata":e.pageContext,selector:e.contextSelector,excludeSelectors:e.excludeSelectors}),d=a;if(a&&o){let u;try{let g=await Promise.race([o(),new Promise((p,h)=>{u=setTimeout(()=>h(new Error("Page context timed out")),5e3)})]);d=r(g,a,e.pageContext)}finally{u&&clearTimeout(u)}}let l=this.config;if(!(!this.isConnected||t!==document.location.href||o!==this.hooks.contextProvider||c!==JSON.stringify([l.pageContext,l.contextSelector,l.excludeSelectors])))return d}pageFingerprint(e){let{captured_at:t,...i}=e;return JSON.stringify(i)}renderPagePreview(){let e=this.els.pagePreview;e.hidden=!this.sharedPage,e.textContent=this.sharedPage?[this.sharedPage.title,this.sharedPage.url,this.sharedPage.description,this.sharedPage.selection,this.sharedPage.content?.text].filter(Boolean).join(`
339
344
 
340
- `):""}async choosePage(){let e=++this.pageGeneration;if(!this.els.pageChoice.checked){this.pagePending=!1,this.sharedPage=void 0,this.renderPagePreview();return}this.sharedPage=void 0,this.renderPagePreview(),this.pagePending=!0;try{let n=await this.captureCurrentPage();if(e!==this.pageGeneration||!this.els.pageChoice.checked)return;if(!n)throw new Error("Page unavailable");this.sharedPage=n,this.renderPagePreview(),this.emit("dewee:context-ready",{available:!0})}catch{if(e!==this.pageGeneration)return;this.sharedPage=void 0,this.els.pageChoice.checked=!1,this.renderPagePreview(),this.showNotice(this.strings.pageUnavailable),this.emit("dewee:context-error",{code:"page_unavailable"})}finally{e===this.pageGeneration&&(this.pagePending=!1)}}updateSendButton(){let e=this.els.send;e.innerHTML=this.running?C.stop:C.send,e.setAttribute("aria-label",this.running?this.strings.stop:this.strings.send),e.title=e.getAttribute("aria-label"),e.disabled=!this.running&&(this.cooldown.active||!this.els.input.value.trim())}startCooldown(e){this.cooldown.start(typeof e=="number"&&Number.isFinite(e)&&e>0?e:Rt),this.cooldown.active&&(this.renderCooldown(this.cooldown.secondsLeft),this.els.announcer.textContent=this.strings.cooldownStart(this.cooldown.secondsLeft),this.updateSendButton())}renderCooldown(e){this.els.cooldown.hidden=!1,this.els.cooldown.textContent=this.strings.cooldown(e)}endCooldown(){this.els.cooldown.hidden=!0,this.els.cooldown.textContent="",this.els.announcer.textContent=this.strings.cooldownOver,this.updateSendButton()}setRunning(e){this.running=e,this.updateSendButton()}renderSubtitle(){this.els.jobAccess.hidden=this.server?.identity!==!0;let e=this.els,n=this.config,i=this.server?.agents??[],r=n.allowAgentSwitch!==!1&&!!this.server?.allowAgentSwitch&&i.length>1;e.select.hidden=!r,e.status.hidden=r,r&&(e.select.replaceChildren(...i.map(c=>new Option(c.name||c.id,c.id,!1,c.id===this.agentId))),e.select.setAttribute("aria-label","Agent"));let o=i.find(c=>c.id===this.agentId);e.status.textContent=n.subtitle||(o?.name&&o.name!==n.title?`${this.strings.online} \xB7 ${o.name}`:this.strings.online)}async activate(){if(!this.activated){this.activated=!0,this.renderLog();try{this.probedPage=this.config.pageContext==="metadata"||this.config.pageContext==="content",this.server=await this.client().getConfig(!0,this.probedPage),this.els.input.maxLength=this.server.maxMessageLength;let e=this.config.agent,n=i=>!!i&&(this.server.agents.length===0||this.server.agents.some(r=>r.id===i));this.agentId=n(e)?e:this.server.defaultAgent||this.server.agents[0]?.id||e||"",await this.loadConversation()}catch(e){this.activated=!1,this.renderLog(),this.showError(null,e)}this.renderSubtitle(),this.updatePageChoice(),this.emit("dewee:ready",{agent:this.agentId,config:this.server})}}async switchAgent(e){e!==this.agentId&&(this.stop(),this.agentId=e,this.renderSubtitle(),await this.loadConversation())}async loadConversation(){let e=this.config.persist!==!1,n=e?_.get(this.convKey()):null;if(this.conversationId=n||We(),e&&!n&&_.set(this.convKey(),this.conversationId),this.messages=[],this.renderLog(),!!n)try{let i=await this.client().history(this.agentId,this.conversationId);this.messages=$t(i.map(r=>({...r,status:"done"}))),this.renderLog()}catch{}}renderLog(){let e=this.els.log;U(e),e.replaceChildren(),this.messages.length||e.appendChild(this.renderWelcome());for(let n of this.messages)e.appendChild(this.renderMessage(n));e.scrollTop=e.scrollHeight}renderWelcome(){let e=this.config,n=this.strings,i=document.createElement("div");i.className="welcome";let r=document.createElement("h2");r.textContent=e.greeting||n.greeting;let o=document.createElement("p");if(o.textContent=e.intro||n.greetingBody,i.append(r,o),e.suggestions?.length){let c=document.createElement("div");c.className="suggestions";for(let a of e.suggestions){let d=document.createElement("button");d.className="chip",d.type="button",d.textContent=a,d.addEventListener("click",()=>this.send(a)),c.appendChild(d)}i.appendChild(c)}return i}pushMessage(e){this.messages.length||this.els.log.replaceChildren(),this.messages.push(e),this.els.log.appendChild(this.renderMessage(e)),this.scrollToBottom(!0)}renderMessage(e){let n=document.createElement("div");n.className=`msg ${e.role}${e.status==="error"?" error":""}`,n.hidden=!!e.hidden;let i=document.createElement("div");i.className="bubble",n.appendChild(i);let r=document.createElement("div");r.className="trace";let o=document.createElement("div");o.className=e.role==="assistant"?"md":"";let c=document.createElement("div");return c.className="actions",c.hidden=!0,e.role==="assistant"&&i.appendChild(r),i.appendChild(o),e.role==="assistant"&&i.appendChild(c),e.view={root:n,trace:r,md:o,tools:new Map,actions:c},this.updateMessage(e),n}updateMessage(e){let n=e.view;if(!n)return;let i=this.config;if(e.role==="user"){n.md.textContent=e.content,n.root.classList.toggle("refused",!!e.refusal);let a=n.root.querySelector(".refusal");e.refusal&&!a&&(a=document.createElement("div"),a.className="refusal",n.root.appendChild(a)),a&&e.refusal?a.textContent=`\u26A0\uFE0F ${e.refusal}`:a?.remove();return}if(n.root.classList.toggle("error",e.status==="error"),i.showReasoning!==!1&&e.thinking){n.thinking||(n.thinking=document.createElement("details"),n.thinking.className="thinking",n.thinking.innerHTML='<summary></summary><div class="thinking-body"></div>',n.trace.prepend(n.thinking));let a=e.status==="streaming"&&!e.thinkingMs,d=a?this.strings.thinking:e.thinkingMs?this.strings.thoughtFor(Math.max(1,Math.round(e.thinkingMs/1e3))):this.strings.reasoning,l=n.thinking.querySelector("summary");l.innerHTML=`${a?'<span class="spin"></span>':C.brain}<span></span>${C.down.replace("<svg",'<svg class="chev"')}`,l.querySelector("span:not(.spin)").textContent=d,n.thinking.querySelector(".thinking-body").textContent=e.thinking}else n.thinking&&(n.thinking.remove(),n.thinking=void 0);if(i.showToolCalls!==!1)for(let a of e.toolCalls??[])this.renderTool(n,a);else n.tools.forEach(a=>a.remove()),n.tools.clear();n.trace.hidden=!n.trace.childElementCount;let r=this.actionRegistry().size||e.actions?Ce(e.content):e.content,o=e.status==="streaming"&&!r;n.md.hidden=!o&&!r&&!!e.actions?.length;let c=JSON.stringify([r,o,e.status==="streaming",i.endpoint,i.imageOrigins,this.strings.thinking]);n.mdKey!==c&&(n.mdKey=c,U(n.md),o?n.md.innerHTML=`<span class="typing" aria-label="${this.strings.thinking}"><i></i><i></i><i></i></span>`:n.md.replaceChildren(R(document,r,{imageOrigins:Array.isArray(i.imageOrigins)?i.imageOrigins:[],imageProxy:(a,d)=>this.client().imageUrl(a,d),deferImages:e.status==="streaming"})),n.md.classList.toggle("cursor",e.status==="streaming")),this.renderActions(n,e.actions??[])}renderActions(e,n){e.actions.hidden=!n.length,e.actions.replaceChildren(...n.map(i=>{let r=document.createElement("div");r.className="action",r.dataset.status=i.status;let o=i.status==="running"||i.status==="awaiting-confirmation";r.innerHTML=`${o?'<span class="spin"></span>':C.action}<span class="action-name"></span><span class="action-state"></span>`,r.querySelector(".action-name").textContent=i.name||"?",r.querySelector(".action-state").textContent=this.strings.actionStatus[i.status];let c=[i.args&&Object.keys(i.args).length?JSON.stringify(i.args):"",i.error??""].filter(Boolean).join(`
341
- `);return c&&(r.title=c),r}))}renderTool(e,n){let i=e.tools.get(n.id);i||(i=document.createElement("details"),i.className="tool",i.innerHTML=`<summary><span class="lead"></span><span class="tool-name"></span><span class="tool-state"></span>${C.down.replace("<svg",'<svg class="chev"')}</summary><div class="tool-body"></div>`,e.tools.set(n.id,i),e.trace.appendChild(i)),i.dataset.status=n.status,i.querySelector(".lead").innerHTML=n.status==="running"?'<span class="spin"></span>':C.tool;let r=i.querySelector(".tool-name");r.textContent=Nt(n.name),r.setAttribute("title",n.name),i.querySelector(".tool-state").textContent=n.status==="running"?this.strings.toolRunning:n.status==="error"?this.strings.toolError:this.strings.toolDone;let o=i.querySelector(".tool-body");o.replaceChildren();let c=(a,d)=>{if(d==null||d==="")return;let l=document.createElement("div");l.className="label",l.textContent=a;let p=document.createElement("pre");p.textContent=typeof d=="string"?zt(d):JSON.stringify(d,null,2),o.append(l,p)};c(this.strings.args,n.arguments),c(this.strings.result,n.result)}onStreamEvent(e,n){switch(n.type){case"start":n.actionsHash&&(e.actionsHash=n.actionsHash,e.ackVisitor=this.client().visitorId()??void 0),n.conversationId&&n.conversationId!==this.conversationId&&(this.conversationId=n.conversationId,this.config.persist!==!1&&_.set(this.convKey(),n.conversationId));break;case"thinking":e.thinking=(e.thinking||"")+n.text;break;case"delta":this.finishThinking(e),e.content+=n.text;break;case"tool_call":this.finishThinking(e),(e.toolCalls??(e.toolCalls=[])).push({id:n.id,name:n.name,arguments:n.arguments,status:"running"});break;case"tool_result":{let i=e.toolCalls?.find(r=>r.id===n.id)??(e.toolCalls??(e.toolCalls=[]))[e.toolCalls.push({id:n.id,name:n.name,status:"running"})-1];i.status=n.isError?"error":"done",i.result=n.result,i.isError=n.isError;break}case"done":this.finishThinking(e),n.content&&n.content.length>=e.content.length&&(e.content=n.content),e.status="done";break;case"error":e.status="error",this.showError(e,new E(n.message,500,n.code,n.remediation,n.retryAfterMs));break}this.scheduleUpdate(e)}scheduleUpdate(e){this.pendingFrame||(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=0,this.updateMessage(e),this.following&&this.scrollToBottom(!0)}))}finishThinking(e){e.thinking&&!e.thinkingMs&&e.startedAt&&(e.thinkingMs=Date.now()-e.startedAt)}nearBottom(){let e=this.els.log;return e.scrollHeight-e.scrollTop-e.clientHeight<96}scrollToBottom(e=!1){let n=this.els.log;(e||this.nearBottom())&&(n.scrollTop=n.scrollHeight,this.following=!0)}showError(e,n){let{code:i,remediation:r,retryAfterMs:o}=n,a=(Y(i)?this.strings.identityErrors[i]:G(i)?this.strings.admissionErrors[i]:ye(i)?this.strings.linkErrors[i]:"")||n.message||this.strings.errorGeneric;if(this.emit("dewee:error",{message:a,code:i,...r&&{remediation:r},...o&&{retryAfterMs:o}}),i==="RATE_LIMITED"&&this.startCooldown(o),e&&G(i)&&this.refuseInline(e,i,a))return;if(e){e.content=e.content?`${e.content}
345
+ `):""}async choosePage(){let e=++this.pageGeneration;if(!this.els.pageChoice.checked){this.pagePending=!1,this.sharedPage=void 0,this.renderPagePreview();return}this.sharedPage=void 0,this.renderPagePreview(),this.pagePending=!0;try{let t=await this.captureCurrentPage();if(e!==this.pageGeneration||!this.els.pageChoice.checked)return;if(!t)throw new Error("Page unavailable");this.sharedPage=t,this.renderPagePreview(),this.emit("dewee:context-ready",{available:!0})}catch{if(e!==this.pageGeneration)return;this.sharedPage=void 0,this.els.pageChoice.checked=!1,this.renderPagePreview(),this.showNotice(this.strings.pageUnavailable),this.emit("dewee:context-error",{code:"page_unavailable"})}finally{e===this.pageGeneration&&(this.pagePending=!1)}}updateSendButton(){let e=this.els.send;e.innerHTML=this.running?A.stop:A.send,e.setAttribute("aria-label",this.running?this.strings.stop:this.strings.send),e.title=e.getAttribute("aria-label"),e.disabled=!this.running&&(this.cooldown.active||!this.els.input.value.trim())}startCooldown(e){this.cooldown.start(typeof e=="number"&&Number.isFinite(e)&&e>0?e:Bt),this.cooldown.active&&(this.renderCooldown(this.cooldown.secondsLeft),this.els.announcer.textContent=this.strings.cooldownStart(this.cooldown.secondsLeft),this.updateSendButton())}renderCooldown(e){this.els.cooldown.hidden=!1,this.els.cooldown.textContent=this.strings.cooldown(e)}endCooldown(){this.els.cooldown.hidden=!0,this.els.cooldown.textContent="",this.els.announcer.textContent=this.strings.cooldownOver,this.updateSendButton()}setRunning(e){this.running=e,this.updateSendButton()}renderSubtitle(){this.els.jobAccess.hidden=this.server?.identity!==!0;let e=this.els,t=this.config,i=this.server?.agents??[],r=t.allowAgentSwitch!==!1&&!!this.server?.allowAgentSwitch&&i.length>1;e.select.hidden=!r,e.status.hidden=r,r&&(e.select.replaceChildren(...i.map(c=>new Option(c.name||c.id,c.id,!1,c.id===this.agentId))),e.select.setAttribute("aria-label","Agent"));let o=i.find(c=>c.id===this.agentId);e.status.textContent=t.subtitle||(o?.name&&o.name!==t.title?`${this.strings.online} \xB7 ${o.name}`:this.strings.online)}async activate(){if(!this.activated){this.activated=!0,this.renderLog();try{this.probedPage=this.config.pageContext==="metadata"||this.config.pageContext==="content",this.server=await this.client().getConfig(!0,this.probedPage),this.els.input.maxLength=this.server.maxMessageLength;let e=this.config.agent,t=i=>!!i&&(this.server.agents.length===0||this.server.agents.some(r=>r.id===i));this.agentId=t(e)?e:this.server.defaultAgent||this.server.agents[0]?.id||e||"",await this.loadConversation()}catch(e){this.activated=!1,this.renderLog(),this.showError(null,e)}this.renderSubtitle(),this.updatePageChoice(),this.emit("dewee:ready",{agent:this.agentId,config:this.server})}}async switchAgent(e){e!==this.agentId&&(this.stop(),this.agentId=e,this.renderSubtitle(),await this.loadConversation())}async loadConversation(){this.clearCredentials();let e=this.credentialGeneration,t=this.config.persist!==!1,i=t?N.get(this.convKey()):null;if(this.conversationId=i||tt(),t&&!i&&N.set(this.convKey(),this.conversationId),this.messages=[],this.renderLog(),!!i)try{let r=await this.client().historyDetails(this.agentId,this.conversationId);if(e!==this.credentialGeneration)return;this.messages=Kt(r.messages.map(o=>({...o,status:"done"})));for(let o of r.credentialRequests)this.credentialCards.set(o.id,o);this.renderLog()}catch{}}renderLog(){let e=this.els.log;K(e),e.replaceChildren(),this.messages.length||e.appendChild(this.renderWelcome());for(let t of this.messages)e.appendChild(this.renderMessage(t));for(let t of this.credentialCards.values())e.appendChild(this.renderCredential(t));e.scrollTop=e.scrollHeight}clearCredentials(){this.credentialGeneration++;for(let e of this.credentialPopups.keys())this.closeCredentialPopup(e);for(let e of this.credentialRequestsInFlight)e.abort();this.credentialRequestsInFlight.clear(),this.credentialCards.clear(),this.credentialBusy.clear()}closeCredentialPopup(e){let t=this.credentialPopups.get(e);if(t){this.credentialPopups.delete(e),t.timer&&clearTimeout(t.timer),t.controller.abort();try{t.popup.close()}catch{}}}discardCredential(e){this.closeCredentialPopup(e),this.credentialCards.delete(e)}credentialButton(e,t,i,r=!1){let o=document.createElement("button");return o.type="button",o.className="btn",o.textContent=t,o.disabled=r||this.credentialBusy.has(e.id),o.addEventListener("click",i),o}renderCredential(e){let t=document.createElement("section");t.className="msg assistant credential-request";let i=document.createElement("div");i.className="bubble";let r=document.createElement("strong");r.textContent=e.title;let o=document.createElement("p");o.textContent=e.purpose;let c=document.createElement("p");c.textContent=this.strings.credential.intro;let a=document.createElement("p");a.textContent=[e.target.type,e.target.mode].filter(Boolean).join(" \xB7 ");let d=document.createElement("p");d.setAttribute("role","status");let l=e.status==="pending"&&Date.parse(e.expires_at)<=Date.now()?"expired":e.status;if(this.credentialBusy.has(e.id)){t.setAttribute("aria-busy","true");let h=document.createElement("span");h.className="spin",h.setAttribute("aria-hidden","true"),d.append(h,` ${this.strings.credential.status.applying}`)}else d.textContent=this.strings.credential.status[l];let u=document.createElement("ul");for(let h of e.fields){let m=document.createElement("li");m.textContent=`${h.label} (${h.required?this.strings.credential.required:this.strings.credential.optional})`,u.appendChild(m)}let g=document.createElement("p");g.textContent=`${this.strings.credential.expires}: ${new Date(e.expires_at).toLocaleString()}`;let p=document.createElement("div");return p.className="credential-actions",l==="pending"&&p.append(this.credentialButton(e,this.strings.credential.open,()=>{this.openCredential(e)},this.credentialPopups.has(e.id)),this.credentialButton(e,this.strings.credential.cancel,()=>{this.updateCredential(e,"credential-request-cancel")})),e.resumable&&p.append(this.credentialButton(e,this.strings.credential.continue,()=>{this.resumeCredential(e)})),i.append(r,o,a,u,c,g,d,p),t.appendChild(i),t}async updateCredential(e,t){if(!this.credentialCards.has(e.id)||this.credentialBusy.has(e.id))return;let i=this.credentialGeneration,r=this.agentId,o=this.conversationId,c=new AbortController;this.credentialRequestsInFlight.add(c),this.credentialBusy.add(e.id),this.renderLog();try{let a=await this.client().credentialRequest(t,r,o,e.id,c.signal);if(i!==this.credentialGeneration||!("id"in a))return;this.credentialCards.set(a.id,a),t==="credential-request-cancel"&&this.closeCredentialPopup(e.id)}catch(a){i===this.credentialGeneration&&a instanceof v&&Xe.has(a.code??"")?this.discardCredential(e.id):i===this.credentialGeneration&&t!=="credential-request"&&this.showNotice(this.strings.credential.unavailable)}finally{this.credentialRequestsInFlight.delete(c),i===this.credentialGeneration&&(this.credentialBusy.delete(e.id),this.renderLog())}}async openCredential(e){if(this.credentialCards.get(e.id)!==e||this.credentialBusy.has(e.id)||this.credentialPopups.has(e.id))return;let t;try{t=window.open("about:blank",`dewee-credential-${crypto.randomUUID()}`,"popup,width=720,height=800")}catch{t=null}if(!t){this.showNotice(this.strings.credential.unavailable);return}let i=this.credentialGeneration,r=this.agentId,o=this.conversationId,c={popup:t,controller:new AbortController,timer:void 0};this.credentialPopups.set(e.id,c),this.credentialBusy.add(e.id),this.renderLog();try{t.opener=null;let a=await this.client().credentialRequest("credential-request-handoff",r,o,e.id,c.controller.signal);if(i!==this.credentialGeneration||t.closed||!("url"in a))throw new Error("cancelled");let d=t.document.createElement("meta");d.name="referrer",d.content="no-referrer",t.document.head.append(d),t.location.replace(a.url);let l=async()=>{if(i!==this.credentialGeneration)return;let u=this.credentialCards.get(e.id);u&&(u.status==="pending"||u.status==="applying")&&await this.updateCredential(u,"credential-request");let g=this.credentialCards.get(e.id);i===this.credentialGeneration&&!t.closed&&g&&Date.parse(g.expires_at)>Date.now()&&this.credentialPopups.get(e.id)===c?g.status==="pending"||g.status==="applying"?c.timer=setTimeout(l,4e3):(this.closeCredentialPopup(e.id),this.renderLog()):(this.credentialPopups.get(e.id)===c&&this.closeCredentialPopup(e.id),i===this.credentialGeneration&&this.renderLog())};c.timer=setTimeout(l,4e3)}catch{this.credentialPopups.get(e.id)===c&&this.closeCredentialPopup(e.id),i===this.credentialGeneration&&this.showNotice(this.strings.credential.unavailable)}finally{i===this.credentialGeneration&&(this.credentialBusy.delete(e.id),this.renderLog())}}async resumeCredential(e){if(this.credentialCards.get(e.id)!==e||this.running||this.credentialBusy.has(e.id))return;let t=this.credentialGeneration,i=this.agentId,r=this.conversationId,o={role:"assistant",content:"",status:"streaming",startedAt:Date.now()},c=new AbortController;this.credentialBusy.add(e.id),this.pushMessage(o),this.setRunning(c);try{await this.client().chat({message:"",agent:i,conversationId:r,credentialRequestId:e.id},a=>{t===this.credentialGeneration&&this.onStreamEvent(o,a)},this.running.signal),o.status==="streaming"&&(o.status="done"),t===this.credentialGeneration&&(this.credentialBusy.delete(e.id),await this.updateCredential(e,"credential-request"))}catch(a){t===this.credentialGeneration&&(this.messages=this.messages.filter(d=>d!==o),a instanceof v&&Xe.has(a.code??"")?this.discardCredential(e.id):a instanceof v&&a.code==="credential_request_resumed"?(this.credentialBusy.delete(e.id),await this.updateCredential(e,"credential-request")):this.showNotice(this.strings.credential.unavailable))}finally{this.running===c&&this.setRunning(null),t===this.credentialGeneration&&(this.credentialBusy.delete(e.id),this.updateMessage(o),this.renderLog())}}renderWelcome(){let e=this.config,t=this.strings,i=document.createElement("div");i.className="welcome";let r=document.createElement("h2");r.textContent=e.greeting||t.greeting;let o=document.createElement("p");if(o.textContent=e.intro||t.greetingBody,i.append(r,o),e.suggestions?.length){let c=document.createElement("div");c.className="suggestions";for(let a of e.suggestions){let d=document.createElement("button");d.className="chip",d.type="button",d.textContent=a,d.addEventListener("click",()=>this.send(a)),c.appendChild(d)}i.appendChild(c)}return i}pushMessage(e){this.messages.length||this.els.log.replaceChildren(),this.messages.push(e),this.els.log.appendChild(this.renderMessage(e)),this.scrollToBottom(!0)}renderMessage(e){let t=document.createElement("div");t.className=`msg ${e.role}${e.status==="error"?" error":""}`,t.hidden=!!e.hidden;let i=document.createElement("div");i.className="bubble",t.appendChild(i);let r=document.createElement("div");r.className="trace";let o=document.createElement("div");o.className=e.role==="assistant"?"md":"";let c=document.createElement("div");return c.className="actions",c.hidden=!0,e.role==="assistant"&&i.appendChild(r),i.appendChild(o),e.role==="assistant"&&i.appendChild(c),e.view={root:t,trace:r,md:o,tools:new Map,actions:c},this.updateMessage(e),t}updateMessage(e){let t=e.view;if(!t)return;let i=this.config;if(e.role==="user"){t.md.textContent=e.content,t.root.classList.toggle("refused",!!e.refusal);let a=t.root.querySelector(".refusal");e.refusal&&!a&&(a=document.createElement("div"),a.className="refusal",t.root.appendChild(a)),a&&e.refusal?a.textContent=`\u26A0\uFE0F ${e.refusal}`:a?.remove();return}if(t.root.classList.toggle("error",e.status==="error"),i.showReasoning!==!1&&e.thinking){t.thinking||(t.thinking=document.createElement("details"),t.thinking.className="thinking",t.thinking.innerHTML='<summary></summary><div class="thinking-body"></div>',t.trace.prepend(t.thinking));let a=e.status==="streaming"&&!e.thinkingMs,d=a?this.strings.thinking:e.thinkingMs?this.strings.thoughtFor(Math.max(1,Math.round(e.thinkingMs/1e3))):this.strings.reasoning,l=t.thinking.querySelector("summary");l.innerHTML=`${a?'<span class="spin"></span>':A.brain}<span></span>${A.down.replace("<svg",'<svg class="chev"')}`,l.querySelector("span:not(.spin)").textContent=d,t.thinking.querySelector(".thinking-body").textContent=e.thinking}else t.thinking&&(t.thinking.remove(),t.thinking=void 0);if(i.showToolCalls!==!1)for(let a of e.toolCalls??[])this.renderTool(t,a);else t.tools.forEach(a=>a.remove()),t.tools.clear();t.trace.hidden=!t.trace.childElementCount;let r=this.actionRegistry().size||e.actions?Pe(e.content):e.content,o=e.status==="streaming"&&!r;t.md.hidden=!o&&!r&&!!e.actions?.length;let c=JSON.stringify([r,o,e.status==="streaming",i.endpoint,i.imageOrigins,this.strings.thinking]);t.mdKey!==c&&(t.mdKey=c,K(t.md),o?t.md.innerHTML=`<span class="typing" aria-label="${this.strings.thinking}"><i></i><i></i><i></i></span>`:t.md.replaceChildren(M(document,r,{imageOrigins:Array.isArray(i.imageOrigins)?i.imageOrigins:[],imageProxy:(a,d)=>this.client().imageUrl(a,d),deferImages:e.status==="streaming"})),t.md.classList.toggle("cursor",e.status==="streaming")),this.renderActions(t,e.actions??[])}renderActions(e,t){e.actions.hidden=!t.length,e.actions.replaceChildren(...t.map(i=>{let r=document.createElement("div");r.className="action",r.dataset.status=i.status;let o=i.status==="running"||i.status==="awaiting-confirmation";r.innerHTML=`${o?'<span class="spin"></span>':A.action}<span class="action-name"></span><span class="action-state"></span>`,r.querySelector(".action-name").textContent=i.name||"?",r.querySelector(".action-state").textContent=this.strings.actionStatus[i.status];let c=[i.args&&Object.keys(i.args).length?JSON.stringify(i.args):"",i.error??""].filter(Boolean).join(`
346
+ `);return c&&(r.title=c),r}))}renderTool(e,t){let i=e.tools.get(t.id);i||(i=document.createElement("details"),i.className="tool",i.innerHTML=`<summary><span class="lead"></span><span class="tool-name"></span><span class="tool-state"></span>${A.down.replace("<svg",'<svg class="chev"')}</summary><div class="tool-body"></div>`,e.tools.set(t.id,i),e.trace.appendChild(i)),i.dataset.status=t.status,i.querySelector(".lead").innerHTML=t.status==="running"?'<span class="spin"></span>':A.tool;let r=i.querySelector(".tool-name");r.textContent=Vt(t.name),r.setAttribute("title",t.name),i.querySelector(".tool-state").textContent=t.status==="running"?this.strings.toolRunning:t.status==="error"?this.strings.toolError:this.strings.toolDone;let o=i.querySelector(".tool-body");o.replaceChildren();let c=(a,d)=>{if(d==null||d==="")return;let l=document.createElement("div");l.className="label",l.textContent=a;let u=document.createElement("pre");u.textContent=typeof d=="string"?Yt(d):JSON.stringify(d,null,2),o.append(l,u)};c(this.strings.args,t.arguments),c(this.strings.result,t.result)}onStreamEvent(e,t){switch(t.type){case"start":t.actionsHash&&(e.actionsHash=t.actionsHash,e.ackVisitor=this.client().visitorId()??void 0),t.conversationId&&t.conversationId!==this.conversationId&&(this.conversationId=t.conversationId,this.config.persist!==!1&&N.set(this.convKey(),t.conversationId));break;case"thinking":e.thinking=(e.thinking||"")+t.text;break;case"delta":this.finishThinking(e),e.content+=t.text;break;case"tool_call":this.finishThinking(e),(e.toolCalls??(e.toolCalls=[])).push({id:t.id,name:t.name,arguments:t.arguments,status:"running"});break;case"tool_result":{let i=e.toolCalls?.find(r=>r.id===t.id)??(e.toolCalls??(e.toolCalls=[]))[e.toolCalls.push({id:t.id,name:t.name,status:"running"})-1];i.status=t.isError?"error":"done",i.result=t.result,i.isError=t.isError;break}case"credential_request":this.credentialCards.set(t.credentialRequest.id,t.credentialRequest),this.renderLog();break;case"done":this.finishThinking(e),t.content&&t.content.length>=e.content.length&&(e.content=t.content),e.status="done";break;case"error":e.status="error",this.showError(e,new v(t.message,500,t.code,t.remediation,t.retryAfterMs));break}this.scheduleUpdate(e)}scheduleUpdate(e){this.pendingFrame||(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=0,this.updateMessage(e),this.following&&this.scrollToBottom(!0)}))}finishThinking(e){e.thinking&&!e.thinkingMs&&e.startedAt&&(e.thinkingMs=Date.now()-e.startedAt)}nearBottom(){let e=this.els.log;return e.scrollHeight-e.scrollTop-e.clientHeight<96}scrollToBottom(e=!1){let t=this.els.log;(e||this.nearBottom())&&(t.scrollTop=t.scrollHeight,this.following=!0)}showError(e,t){let{code:i,remediation:r,retryAfterMs:o}=t,a=(W(i)?this.strings.identityErrors[i]:Q(i)?this.strings.admissionErrors[i]:Ce(i)?this.strings.linkErrors[i]:"")||t.message||this.strings.errorGeneric;if(this.emit("dewee:error",{message:a,code:i,...r&&{remediation:r},...o&&{retryAfterMs:o}}),i==="RATE_LIMITED"&&this.startCooldown(o),e&&Q(i)&&this.refuseInline(e,i,a))return;if(e){e.content=e.content?`${e.content}
342
347
 
343
- > \u26A0\uFE0F ${a}`:`\u26A0\uFE0F ${a}`,e.status="error",this.updateMessage(e);return}let d=document.createElement("div");d.className="msg error",d.innerHTML='<div class="bubble"></div>',d.firstElementChild.textContent=`\u26A0\uFE0F ${a}`,this.els.log.appendChild(d)}refuseInline(e,n,i){let r=this.messages.indexOf(e),o=r>0?this.messages[r-1]:void 0;return o?.role!=="user"||o.hidden||(this.els.input.value.trim()||(this.els.input.value=o.content,this.autosize()),n!=="POLICY_DENIED"||e.content)?!1:(e.status="error",e.hidden=!0,e.view&&(e.view.root.hidden=!0),o.refusal=i,this.updateMessage(o),!0)}async challenge(e){await Ht();let n=document.createElement("div");n.slot="challenge",this.appendChild(n);try{return await new Promise((i,r)=>{window.turnstile.render(n,{sitekey:e,appearance:"interaction-only",theme:this.getAttribute("data-theme")==="dark"?"dark":"light",callback:i,"error-callback":()=>r(new E("Verification failed",403,"turnstile_failed"))})})}finally{n.remove()}}};function $t(t){return t.forEach((s,e)=>{if(s.role==="user"){s.content=ie(s.content),Z(s.content)&&(s.hidden=!0);return}if(!s.content.includes("```dewee-action"))return;let{calls:n}=X(s.content);if(!n.length)return;let i=t[e+1],r=i?.role==="user"?ie(i.content):"",o=Z(r)?Se(r):[];s.actions=n.map(c=>{let a=o.find(l=>l.id===c.id),d=a?a.status==="ok"?"done":a.status:"error";return{id:c.id,name:c.name,args:c.ok?c.args:void 0,status:d,error:a?a.error:"Not run"}})}),t}var jt={telegram:"Telegram",discord:"Discord",zalo:"Zalo",slack:"Slack",whatsapp:"WhatsApp",messenger:"Messenger",feishu:"Feishu",line:"LINE"};function Bt(t){let s=t.toLowerCase().split(/[_-]/)[0];return jt[s]??(t?t.charAt(0).toUpperCase()+t.slice(1):"chat")}function ge(t,s){try{return JSON.parse(t)}catch{return s}}function zt(t){let s=t.trim();if(!/^[[{]/.test(s))return t;try{return JSON.stringify(JSON.parse(s),null,2)}catch{return t}}function fe(t="dewee-chat"){typeof window>"u"||!window.customElements||customElements.get(t)||customElements.define(t,class extends D{})}function qt(t={},s){fe();let e=document.createElement("dewee-chat");return e.configure(t),((typeof s=="string"?document.querySelector(s):s)??document.body).appendChild(e),e}fe();var Ut=document.currentScript,K=Ut?.dataset;if(K&&K.endpoint&&K.autoMount!=="false"){let t=()=>{let s=document.createElement("dewee-chat");for(let[e,n]of Object.entries(K))e==="autoMount"||n===void 0||s.setAttribute(e.replace(/[A-Z]/g,i=>"-"+i.toLowerCase()),n);document.body.appendChild(s)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}window.DeweeWebchat=me;})();
348
+ > \u26A0\uFE0F ${a}`:`\u26A0\uFE0F ${a}`,e.status="error",this.updateMessage(e);return}let d=document.createElement("div");d.className="msg error",d.innerHTML='<div class="bubble"></div>',d.firstElementChild.textContent=`\u26A0\uFE0F ${a}`,this.els.log.appendChild(d)}refuseInline(e,t,i){let r=this.messages.indexOf(e),o=r>0?this.messages[r-1]:void 0;return o?.role!=="user"||o.hidden||(this.els.input.value.trim()||(this.els.input.value=o.content,this.autosize()),t!=="POLICY_DENIED"||e.content)?!1:(e.status="error",e.hidden=!0,e.view&&(e.view.root.hidden=!0),o.refusal=i,this.updateMessage(o),!0)}async challenge(e){await Ut();let t=document.createElement("div");t.slot="challenge",this.appendChild(t);try{return await new Promise((i,r)=>{window.turnstile.render(t,{sitekey:e,appearance:"interaction-only",theme:this.getAttribute("data-theme")==="dark"?"dark":"light",callback:i,"error-callback":()=>r(new v("Verification failed",403,"turnstile_failed"))})})}finally{t.remove()}}};function Kt(n){return n.forEach((s,e)=>{if(s.role==="user"){s.content=oe(s.content),ne(s.content)&&(s.hidden=!0);return}if(!s.content.includes("```dewee-action"))return;let{calls:t}=te(s.content);if(!t.length)return;let i=n[e+1],r=i?.role==="user"?oe(i.content):"",o=ne(r)?Re(r):[];s.actions=t.map(c=>{let a=o.find(l=>l.id===c.id),d=a?a.status==="ok"?"done":a.status:"error";return{id:c.id,name:c.name,args:c.ok?c.args:void 0,status:d,error:a?a.error:"Not run"}})}),n}var Gt={telegram:"Telegram",discord:"Discord",zalo:"Zalo",slack:"Slack",whatsapp:"WhatsApp",messenger:"Messenger",feishu:"Feishu",line:"LINE"};function Ft(n){let s=n.toLowerCase().split(/[_-]/)[0];return Gt[s]??(n?n.charAt(0).toUpperCase()+n.slice(1):"chat")}function be(n,s){try{return JSON.parse(n)}catch{return s}}function Yt(n){let s=n.trim();if(!/^[[{]/.test(s))return n;try{return JSON.stringify(JSON.parse(s),null,2)}catch{return n}}function we(n="dewee-chat"){typeof window>"u"||!window.customElements||customElements.get(n)||customElements.define(n,class extends q{})}function Wt(n={},s){we();let e=document.createElement("dewee-chat");return e.configure(n),((typeof s=="string"?document.querySelector(s):s)??document.body).appendChild(e),e}we();var Qt=document.currentScript,Y=Qt?.dataset;if(Y&&Y.endpoint&&Y.autoMount!=="false"){let n=()=>{let s=document.createElement("dewee-chat");for(let[e,t]of Object.entries(Y))e==="autoMount"||t===void 0||s.setAttribute(e.replace(/[A-Z]/g,i=>"-"+i.toLowerCase()),t);document.body.appendChild(s)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n):n()}window.DeweeWebchat=ye;})();