@marketrix.ai/widget 4.0.115 → 4.0.116

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.
@@ -5,6 +5,15 @@
5
5
  * the allow/deny controls of a screen-access request, and a done/failed/stopped glyph in the tenant
6
6
  * accent at a per-status opacity. The last message fades in.
7
7
  *
8
+ * **Memoized, and `isTaskRunning` arrives as a prop rather than through `useWidget()`.** `MessageList`
9
+ * commits a whole new `messages` array on every `chat/delta` token (`ChatContext`'s reducer keeps
10
+ * reference equality for every message except the one being streamed into), so a `useWidget()`/
11
+ * `useChatContext()` call anywhere inside a list row re-subscribes that row to the token stream directly
12
+ * and defeats `React.memo` regardless of props — measured at ~21 `MessageItem`/`MessageBody` renders per
13
+ * token in a 20-message transcript before this change (one per row), ~1 after (only the streaming row).
14
+ * `onScreenAccessAllow`/`onScreenAccessDeny` must stay referentially stable (`ChatView`'s `useScreenShare`
15
+ * wraps them for exactly this) or the memo comparison never bails.
16
+ *
8
17
  * `MessageBody` renders the message's `parts` — text and progress lines — and `Thinking` is the
9
18
  * spinner-and-caption row shown while a reply is pending, its caption switching to name the visitor's
10
19
  * action when the agent is blocked on them. Thinking shows while a placeholder carries no text yet, and
@@ -16,8 +25,9 @@ import type { ChatMessage } from '../../types';
16
25
  interface MessageItemProps {
17
26
  message: ChatMessage;
18
27
  isLastMessage: boolean;
28
+ isTaskRunning: boolean;
19
29
  onScreenAccessAllow?: () => void;
20
30
  onScreenAccessDeny?: () => void;
21
31
  }
22
- export declare const MessageItem: React.FC<MessageItemProps>;
32
+ export declare const MessageItem: React.NamedExoticComponent<MessageItemProps>;
23
33
  export {};
@@ -21,8 +21,11 @@
21
21
  * `useScreenShare` (this file's only other consumer) owns the screen-share lifecycle: the in-transcript
22
22
  * permission card, the browser picker, the live share message, and ending a share. `useLatest` keeps a
23
23
  * value readable from a callback that must not be re-created (the polling interval below, mounted once);
24
- its refs are listed in that effect's deps for the linter, but since `useRef` identity never changes,
25
- listing them cannot re-arm the interval.
24
+ * its refs are listed in that effect's deps for the linter, but since `useRef` identity never changes,
25
+ * listing them cannot re-arm the interval. The same idiom stabilizes `handleScreenAccessRequestAllow`/
26
+ * `handleScreenAccessRequestDeny`: both are handed to every `MessageItem` through `MessageList`, and a
27
+ * fresh closure each render (the naive `beginScreenShare`/inline-arrow form) defeats `MessageItem`'s
28
+ * `React.memo` for the whole transcript on every SSE token, not just the streaming row.
26
29
  * The hook returns `requestScreenAccess` — posting a request card carrying the queued turn, no-oping if
27
30
  * one is already open — plus that card's Allow/Deny handlers, the toolbar dialog's Allow/Dismiss
28
31
  * handlers, and `toggleScreenShareRef`, a toggle stopping a live share or opening that dialog.
package/dist/widget.mjs CHANGED
@@ -16,9 +16,9 @@ return b(e,{...h,ref:d,className:u,style:{color:Pa[n?"inherit":i],...s&&{fontSiz
16
16
  return v(bs,{toast:e,className:"mtx-toast",render:/* @__PURE__ */b(oc,{align:"center",gap:"md",rounded:"pill",paddingPreset:"toast",elevation:"panel",style:{backgroundColor:t.background,border:t.border}}),children:[
17
17
  /* @__PURE__ */b(Xa,{src:_a,alt:"",size:28,rounded:"pill"}),
18
18
  /* @__PURE__ */v(ic,{grow:!0,minWidth:"0",children:[/* @__PURE__ */b(Ms,{render:/* @__PURE__ */b(hc,{as:"span",block:!0,inheritColor:!0,truncate:!0,weight:"medium",style:{fontSize:"13px",color:t.titleColor,...e.actionProps&&{whiteSpace:"normal"}}})}),null!=e.description&&/* @__PURE__ */b(Is,{render:/* @__PURE__ */b(hc,{as:"span",block:!0,inheritColor:!0,truncate:!0,style:{fontSize:"12px",color:t.bodyColor,opacity:.8}})})]}),e.actionProps&&/* @__PURE__ */b(Ps,{render:/* @__PURE__ */b(Za,{type:"button",variant:"ghost",shape:"pill",size:"sm",style:{color:t.titleColor,backgroundColor:t.actionBackground,border:t.border}})}),
19
- /* @__PURE__ */b(Ds,{onMouseDown:e=>e.preventDefault(),render:/* @__PURE__ */b(lc,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(cc,{name:"closeSmall",size:12})})]},e.id)})},mc=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(_i,{children:[e,/* @__PURE__ */b(Vs,{container:t??void 0,children:/* @__PURE__ */b(ns,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(fc,{})})})]}),gc=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Aa();return a(()=>{null!=e?s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}):c("error")},[e,n,s,c,t]),a(()=>{r?s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}):c("greeting")},[r,o,s,c,i]),null},yc=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function bc(e){return Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!function(e){for(let t=e;t;t=t.parentElement)if("true"===t.getAttribute("aria-hidden"))return!0;return!1}(e))}function*vc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function wc(e){if(!(e instanceof Element))return!1;try{const t=e.tagName.toLowerCase();if(!("button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||yc.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0))return!1;const n=window.getComputedStyle(e);if("none"===n.display||"none"===n.pointerEvents)return!1;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;for(const o of vc(e))if(o!==e){const e=window.getComputedStyle(o).overflow;if("hidden"===e||"clip"===e){const e=o.getBoundingClientRect();if(r.right<e.left||r.left>e.right||r.bottom<e.top||r.top>e.bottom)return!1}if(o===document.body)break}for(let o=e.getRootNode();o instanceof ShadowRoot;o=o.host.getRootNode()){const e=o.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return console.error("[isIndexable] Unexpected error:",t),!1}}var xc=["id","type","role","aria-label","name","href"],Sc=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}indexElements(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap;const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||wc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:xc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){Oe(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}notInteractableReason(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=function(e){if(!0===e.disabled)return"is a disabled control";if("true"===e.getAttribute("aria-disabled"))return"is aria-disabled";for(const t of vc(e))if(t.hasAttribute("inert"))return"is inside an inert subtree";return null}(e);if(n)return`ELEMENT_NOT_INTERACTABLE: Element ${t} ${n}`;const r=window.getComputedStyle(e);if("none"===r.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===r.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(r.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const o=e.getBoundingClientRect();if(0===o.width||0===o.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const i=o.left+o.width/2,s=o.top+o.height/2,a=document.elementFromPoint(i,s);if(a&&a!==e&&!e.contains(a)&&!a.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=!document.contains(t.element),r=xc.some((e,n)=>t.element.getAttribute(e)!==t.identity[n]);if(n||r)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const o=this.notInteractableReason(t.element,e);return o?{element:null,error:o}:{element:t.element}}},kc=e=>e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement,Cc=e=>e instanceof HTMLButtonElement||"button"===e.getAttribute("role");function Ec(e,t){const n=1===t?"ArrowDown":"ArrowUp",r=e.selectedIndex+t;return r<0||r>=e.options.length?`${n}: already at ${1===t?"last":"first"} option`:(e.selectedIndex=r,e.dispatchEvent(new Event("change",{bubbles:!0})),`${n}: selected "${e.options[r]?.text??""}"`)}function Ic(e,t){const n=e.value,r=e.selectionStart??n.length,o=e.selectionEnd??n.length;let i,s;if(r!==o)i=n.slice(0,r)+n.slice(o),s=r;else if("Backspace"===t&&r>0)i=n.slice(0,r-1)+n.slice(o),s=r-1;else{if(!("Delete"===t&&r<n.length))return`${t}: ${"Backspace"===t?"cursor at start":"cursor at end"}, nothing to delete`;i=n.slice(0,r)+n.slice(r+1),s=r}return function(e,t,n){Mc(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}(e,i,s),`${t}: deleted character, value is now "${i}"`}function Mc(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}var Tc=["scroll","resize","touchmove","wheel"],Rc="#3b82f6",Oc="#1f2937",Ac=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of Tc)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}settle(e){const{resolve:t,reject:n}=this.takeSettlers();e?n?.(new Error(e)):t?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(){const e=document.createElement("div");e.id="marketrix-show-highlight",e.style.cssText=`position:fixed;border:3px solid ${Rc};border-radius:4px;box-shadow:0 0 0 4px rgba(59,130,246,0.2),0 0 20px rgba(59,130,246,0.4);z-index:2147483645;pointer-events:none;transition:none;`,document.body.appendChild(e),this.currentHighlight=e,this.trackElement()}trackElement(){if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: ${Oc}; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom:12px;font-weight:500;color:${Oc};font-size:12px;">${this.escapeHtml(e)}</div><div style="display:flex;gap:8px;justify-content:flex-end;"><button id="marketrix-show-continue" style="background:${Rc};color:white;border:none;border-radius:6px;padding:8px 16px;font-size:12px;font-weight:500;cursor:pointer;">Continue</button></div>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||window.requestAnimationFrame(()=>{n.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.settle()})}),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>this.trackElement();for(const e of Tc)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=10,n=e.left+e.width/2,r=e.top+e.height/2,o=[{left:e.right+20,top:r-60},{left:e.left-320-20,top:r-60},{left:n-160,top:e.top-120-20},{left:n-160,top:e.bottom+20}];let i=o[0];for(const s of o)if(s.left>=t&&s.left+320<=window.innerWidth-t&&s.top>=t&&s.top+120<=window.innerHeight-t){i=s;break}this.currentPopup.style.left=`${Math.max(t,Math.min(i.left,window.innerWidth-320-t))}px`,this.currentPopup.style.top=`${Math.max(t,Math.min(i.top,window.innerHeight-120-t))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.settle())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.settle("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=Sc.getSequenceForElement(e)??-1,r=Sc.notInteractableReason(e,n);r&&this.settle(r)},200)}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},_c=e=>({success:!0,data:{text:e}}),Dc=e=>({success:!0,data:e}),Pc=e=>({success:!1,error:e}),Nc=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),Lc="finish",Fc=new class{tools={navigate:{label:"Navigating",run:e=>this.navigate(e)},search_web:{label:"Searching",run:e=>this.search(e)},click_element:{label:"Clicking element",waitForUser:!0,run:e=>this.clickElement(e)},type_text:{label:"Typing text",waitForUser:!0,run:e=>this.typeText(e)},scroll:{label:"Scrolling",run:e=>this.scroll(e)},scroll_to_text:{label:"Scrolling to text",run:e=>this.scrollToText(e)},extract:{label:"Extracting content",run:e=>this.extract(e)},go_back:{label:"Going back",run:()=>this.goBack()},wait_seconds:{label:"Waiting",run:e=>this.wait(e)},select_dropdown:{label:"Selecting option",waitForUser:!0,run:e=>this.selectDropdownOption(e)},get_dropdown_options:{label:"Reading dropdown options",run:e=>this.getDropdownOptions(e)},send_keys:{label:"Pressing key",waitForUser:!0,run:e=>this.sendKeys(e)},close_tab:{label:"Closing tab",run:()=>this.closeTab()},[Lc]:{label:"Done",run:e=>this.done(e)},get_html:{label:"Reading the page",run:()=>this.getHtml()},get_screenshot:{label:"Taking screenshot",run:()=>this.getScreenshot()}};element(e){if(void 0===e)throw new Error("Index required");const{element:t,error:n}=Sc.getValidatedElement(e);if(!t)throw new Error(n||`Element ${e} not found`);return t}selectElement(e){const t=this.element(e);if(!(t instanceof HTMLSelectElement))throw new Error(`Element ${e} is not a select element`);return t}getFriendlyToolName(e){return this.tools[e]?.label??e}isWaitForUserTool(e){return!!this.tools[e]?.waitForUser}async executeTool(e,t,n,r=""){const o=t,i=this.tools[e];try{return"show"===n&&i?.waitForUser&&void 0!==o.index&&await Ac.showToolAction({element:this.element(o.index),explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e}),i?await i.run(o):Pc(`Unknown tool: ${e}`)}catch(s){return Pc(Re(s))}}navigate(e){const t=(e=>{if(!e)return null;try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}})(e.url);return t?e.new_tab?window.open(t,"_blank")?_c(`Opened ${t} in new tab`):Pc("The browser blocked opening a new tab"):Nc(`Navigating to ${t}`,()=>{window.location.href=t}):Pc("An http(s) URL is required")}search(e){if(!e.query)return Pc("Query is required");const t=e.engine||"duckduckgo",n=encodeURIComponent(e.query);let r=`https://duckduckgo.com/?q=${n}`;return"google"===t&&(r=`https://www.google.com/search?q=${n}`),"bing"===t&&(r=`https://www.bing.com/search?q=${n}`),Nc(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){const t=this.element(e.index);return t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),Nc(`Clicking element ${e.index}`,()=>t.click())}typeText(e){if(void 0===e.text)return Pc("Text required");const t=!1!==e.clear,n=this.element(e.index);if(kc(n))n.focus(),Mc(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return Pc(`Could not insert text into element ${e.index}`)}else"value"in n?(n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))):(n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})));return _c(`Typed text into element ${e.index}`)}scroll(e){const t=.8*window.innerHeight;switch(e.direction){case"down":window.scrollBy({top:t,behavior:"smooth"});break;case"up":window.scrollBy({top:-t,behavior:"smooth"});break;case"left":window.scrollBy({left:-t,behavior:"smooth"});break;case"right":window.scrollBy({left:t,behavior:"smooth"});break;default:return Pc("Invalid direction")}return _c(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return Pc("Text required");const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),_c(`Scrolled to "${e.text}"`);return Pc(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return Dc(n)}goBack(){return window.history.length<=1?Pc("No history"):Nc("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?Pc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),_c(`Waited ${e}s`))}selectDropdownOption(e){if(!e.option)return Pc("Option required");const t=this.selectElement(e.index),n=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return n?(t.value=n.value,t.dispatchEvent(new Event("change",{bubbles:!0})),_c(`Selected ${e.option}`)):Pc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=Array.from(this.selectElement(e.index).options).map(e=>({value:e.value,text:e.text}));return Dc({options:t})}sendKeys(e){if(!e.keys)return Pc("Keys required");const t=this.element(e.index);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const n=function(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=bc(document),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(Cc(e))return e.click(),"Enter: clicked button";if(kc(e)){const t=e.closest("form");if(t){const e=t.querySelector('button[type="submit"], input[type="submit"]');return e?(e.click(),"Enter: clicked form submit button"):(t.requestSubmit(),"Enter: submitted form")}}return e instanceof HTMLAnchorElement?(e.click(),"Enter: clicked link"):"Enter: dispatched event";case"Escape":return e.blur(),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),"Escape: blurred element and dispatched to document";case" ":case"Space":return e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?(e.click(),`Space: toggled ${e.type}`):Cc(e)?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":return e instanceof HTMLSelectElement?Ec(e,1):"ArrowDown: dispatched event";case"ArrowUp":return e instanceof HTMLSelectElement?Ec(e,-1):"ArrowUp: dispatched event";case"Home":return kc(e)?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(kc(e)){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":return kc(e)?Ic(e,"Backspace"):"Backspace: dispatched event";case"Delete":return kc(e)?Ic(e,"Delete"):"Delete: dispatched event";default:return null}}(t,e.keys);return _c(n||`Sent keys ${e.keys}`)}closeTab(){return window.close(),window.closed?_c("Tab closed"):Pc("The browser refused to close a tab this script did not open")}done(e){return _c(e.message||"Task ended")}getHtml(){return _c(Sc.reindexAndSnapshot())}async getScreenshot(){const e=gr();if(!e)return Pc("The visitor is not sharing their screen.");const t=document.createElement("video");try{t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise((e,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);t.onloadeddata=()=>{clearTimeout(r),e()},t.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;const r=n.getContext("2d");return r?(r.drawImage(t,0,0),_c(n.toDataURL("image/jpeg",.75))):Pc("Could not read the shared screen: the browser refused a 2d canvas context.")}finally{t.remove()}}},zc={show:"Show",tell:"Tell",do:"Do"},$c=e=>zc[e];function Bc(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(void 0!==r&&t(r))return n}return-1}function Wc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest&&!e.taskStatus,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);const s=Bc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=Bc(a,c),t=e>=0?a[e]:void 0;if(t)return{index:s+e,message:t}}return console.warn("[MessageFinder] No message found for progress update",{totalMessages:e.length,isTaskRunning:t,currentMode:n}),null}var Uc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function Hc(e,t,n){const r=t>=0?e.parts[t]:void 0;if(!r)return e;const o=[...e.parts];return o[t]={...r,...n},{...e,parts:o}}var jc=(e,t)=>e.parts.findIndex(e=>"progress"===e.type&&"in_progress"===e.status&&e.browserToolName===t);function qc(e,t,n,r={}){return{id:`${e}-${globalThis.crypto.randomUUID()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Vc=(e,t,n="user-message")=>qc(n,"user",e.trim(),{mode:t}),Yc=e=>qc("agent-message","agent",e.trim()),Kc=(e,t)=>qc(t,"agent",e,{isSystemMessage:!0}),Xc=e=>e.filter(e=>"text"===e.type).map(e=>e.content).join("\n"),Gc=e=>({state:e,effects:[]});function Jc(e,t,n,r,o,i,s){const a=Wc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=jc(e,t),o=r>=0?e.parts[r]:void 0;if(!o)return e;const i=Uc(o.content),s=Uc(n);return Hc(e,r,{status:"failed",content:s?`${i} (${s})`:i})}(c,r,s||""):"finish"!==r&&(c="in_progress"===i?function(e,t,n){const r=Uc(n),o=jc(e,t);return o>=0?Hc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||Fc.getFriendlyToolName(r)):((e,t)=>Hc(e,jc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&Fc.isWaitForUserTool(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Zc=(e,t)=>"running"===e.task.phase?e.task.mode??t:t,Qc=e=>({...e,isPlaceholder:!1}),el=e=>"stopped"===e.phase?e:{phase:"idle"};function tl(e,t,n){const r=Wc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:Zc(e,t)}),o=[...e.messages];return r&&(o[r.index]=Qc(n(r.message))),{messages:o,task:el(e.task)}}var nl={completed:"done",failed:"failed",stopped:"stopped"};function rl(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a={type:"text",content:r&&s?i.content+n:n,...r&&{streaming:!0}};return s?o[o.length-1]=a:o.push(a),{...e,content:Xc(o),isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var ol=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Xc(n),parts:n}},il=(e,t)=>({...Qc(ol(e,t)),placeholderState:void 0,taskStatus:"failed"});function sl(e,t,n){const r=e.messages.map(e=>e.id===t?il(e,n):e);return{...e,messages:r}}var al=n(void 0),cl=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell"}),r=u(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
20
- return b(al.Provider,{value:{uiState:t,uiActions:r},children:e})},ll=()=>{const e=s(al);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},ul=n(void 0),dl=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=ll(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=d(o),l=d(n.currentMode);l.current=n.currentMode;const h=d(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),m=i(e=>{f(t=>({...t,messages:[...t.messages,e]}))},[f]),g=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),y=i(e=>{f(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[f]),v=i(e=>{f(t=>({...t,messages:e}))},[f]),w=i(()=>{f(e=>({...e,messages:[]}))},[f]),x=i(()=>{f(e=>({...e,task:{phase:"idle"}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>`${e.id}:${e.parts.length}`).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>e.split(":")[0]).filter(e=>void 0!==e).map(e=>setTimeout(()=>f(t=>function(e,t){const n=e.messages.find(e=>e.id===t);return n?.isPlaceholder&&"waiting-for-user"!==n.placeholderState?sl(e,t,"This is taking longer than expected. Please try again."):e}(t,e)),12e4));return()=>e.forEach(clearTimeout)},[S,f]);const k=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||m(Vc(e,o)),void m(Yc("This is a preview. In production, I'll respond to your messages here."));if(!$e.getCredentialedConfig())return console.error("Config not loaded or incomplete"),void m(Yc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(Vc(e,o));const i=(e=>qc("temp","agent","",{mode:e,isPlaceholder:!0,placeholderState:"thinking"}))(o);f(e=>function(e,t){return{messages:[...e.messages,t],task:{phase:"idle"}}}(e,i));try{await async function(e,t,n){const r=await Be.getOrCreateChatId(),o={type:`chat/${t}`,request_id:n,content:e};await hr.ready(r),await hr.send(o)}(e,o,i.id)}catch(s){console.error("Failed to send message:",s),f(e=>sl(e,i.id,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=async e=>{const{toolCallId:t,tool:n,args:o,mode:i,explanation:s}=e,a=await Fc.executeTool(n,o,i,s),c=a.success?void 0:a.error;f(e=>function(e,t,n,r,o,i){return{...e,messages:Jc(e.messages,"running"===e.task.phase,Zc(e,o),t,n,r,i)}}(e,n,s,c?"failed":"completed",l.current,c)),c||"finish"!==n||f(e=>function(e,t){return tl(e,t,e=>({...e,taskStatus:"done",parts:e.parts.filter(e=>"progress"!==e.type)}))}(e,l.current)),await hr.send({type:"tool/response",tool_call_id:t,success:a.success,...a.success&&{data:JSON.stringify(a.data)},error:c}).catch(e=>{console.error("Failed to send tool response:",e),r.setError("Could not report that step back to the assistant — it may stop responding.")}),a.success&&a.afterResponseAttempt?.()},n={onMessage:t=>{if("tool/call"===t.type){const e=t.tool_call_id;if(h.current.has(e))return;h.current.add(e),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500)))}else"task/status"===t.type&&t.status in nl&&h.current.clear();let n=[];f(e=>{const r=function(e,t,n){switch(t.type){case"tool/call":{if("stopped"===e.task.phase)return Gc(e);const r="running"===e.task.phase?e.task:{phase:"running",mode:t.mode||n},o=t.explanation||"";return{state:{messages:Jc(e.messages,!0,r.mode??n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return Gc(e);const r=t.status,o=e=>t.message?ol(e,t.message):e;return{state:tl(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:nl[r]})),effects:[]}}case"chat/delta":return{state:rl(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:rl(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:sl(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Gc(e)}}(e,t,l.current);return n=r.effects,r.state});for(const o of n)e(o).catch(e=>{console.error("[Widget] Tool call failed:",e),r.setError("Something went wrong running that step. Please try again.")})},onError:e=>{r.setError(e.message),e instanceof pr&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?il(e,t):e),task:el(e.task)}}(t,e.message))}};return hr.addCallbacks(n),()=>{hr.removeCallbacks(n)}},[t,f,r]);const C=i(async()=>{f(e=>function(e,t){return{...tl(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||hr.send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),E=u(()=>({addMessage:m,updateMessage:g,removeMessage:y,setMessages:v,clearMessages:w,messageDispatch:k}),[m,g,y,v,w,k]),I=u(()=>({resetTask:x,stopTask:C}),[x,C]);/* @__PURE__ */
21
- return b(ul.Provider,{value:{messages:o.messages,chatActions:E,taskState:o.task,taskActions:I},children:e})},pl=()=>{const e=s(ul);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},hl=n(null),fl=()=>{const{uiState:e}=ll(),{messages:t}=pl();return a(()=>{const{currentMode:n,isOpen:r}=e;var o;o={messages:t,currentMode:n,isOpen:r},$e.updateContext({...o,messages:o.messages.map(({videoStream:e,...t})=>{const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screen sharing ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}})})},[t,e]),null},ml=({children:e,previewMode:t})=>{const{uiActions:n}=ll(),{chatActions:r}=pl(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=function(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=$e.getContext();return{...o,messages:r.map(e=>{const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}})}}();n.applyState(o),r.setMessages(t),i(!0);const s=await Be.getOrCreateChatId();e||hr.connect(s)})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[t,n,r]),/* @__PURE__ */v(y,{children:[e,o&&/* @__PURE__ */b(fl,{})]})},gl=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(cl,{children:/* @__PURE__ */b(dl,{previewMode:t,children:/* @__PURE__ */b(ml,{previewMode:t,children:e})})}),yl=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,bl=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function vl(e){const t=yl.exec(e.trim())?.[1];if(t){const[e,n,r]=3===t.length?[t.charAt(0)+t.charAt(0),t.charAt(1)+t.charAt(1),t.charAt(2)+t.charAt(2)]:[t.slice(0,2),t.slice(2,4),t.slice(4,6)];return{r:parseInt(e??"",16),g:parseInt(n??"",16),b:parseInt(r??"",16)}}const n=bl.exec(e.trim());if(!n)return null;const r=Number(n[1]),o=Number(n[2]),i=Number(n[3]);return r>255||o>255||i>255?null:{r:r,g:o,b:i}}function wl(e){const t=vl(e);if(!t)return"#000000";const n=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4);return.2126*n(t.r/255)+.7152*n(t.g/255)+.0722*n(t.b/255)>.5?"#000000":"#ffffff"}function xl(e,t){const n=vl(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}function Sl(e){return e.includes("gradient")?e:`linear-gradient(135deg, ${e} 0%, ${e} 100%)`}var kl={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"},Cl=n(null),El=()=>{const e=s(Cl);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},Il=()=>{const{uiState:e,uiActions:t}=ll(),{messages:n,chatActions:r,taskState:o,taskActions:i}=pl();return{state:u(()=>({...e,messages:n,isTaskRunning:"running"===o.phase,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),actions:u(()=>({...t,...i,...r,clearChatHistory:()=>{r.clearMessages(),i.resetTask(),t.setError(void 0)}}),[t,i,r])}},Ml={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},Tl=Object.keys(Ml),Rl=e=>Ml[e],Ol=e=>{const{vertical:t,horizontal:n}=Rl(e);return{[t]:"20px",[n]:"20px"}},Al={top:"bottom",bottom:"top",left:"right",right:"left"},_l=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Rl(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Dl=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},Pl="cubic-bezier(0.16, 1, 0.3, 1)",Nl=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=El(),{state:c,actions:u}=Il(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),y=!h&&f,w=m?"error":"processing",x=d(null),{isDragging:S,pixelPositionStyle:k,onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,suppressUntilRef:T}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,u]=p({w:56,h:56}),[,h]=p(0),f=d(null),m=d(null),g=d(null),y=d(0),b=d([]),v=d(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();u(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=_l(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=i(()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="",o.current.style.left="",o.current.style.top="")},[o]),M=i((e,t)=>{f.current?.();let r=!1;const i=()=>{r=!0,window.clearTimeout(c),t.removeEventListener("transitionend",l),f.current=null},s=()=>{r||(i(),t.style.transition="none",t.style.willChange="",t.style.left="",t.style.top="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))},c=window.setTimeout(s,650),l=e=>{e.target===t&&"left"===e.propertyName&&s()};t.addEventListener("transitionend",l),f.current=i},[n,o]),T=i((t,r,i)=>{if(!o.current||!E)return I(),n(t),void a(!1);w();const s=o.current,l=_l(e,S,k,c.w,c.h),u=_l(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${Pl}, top 600ms ${Pl}`,s.style.left=`${u.x}px`,s.style.top=`${u.y}px`}),M(t,s)},[M,n,E,e,I,S,k,c.w,c.h,o]),R=e=>{I(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=function(e,t=.999){if(e.length<2)return{x:0,y:0};const n=e[0],r=e[e.length-1];if(!n||!r)return{x:0,y:0};const o=r.t-n.t;if(o<=0)return{x:0,y:0};const i=e=>e/o*t/(1-t);return{x:i(r.x-n.x),y:i(r.y-n.y)}}(b.current),i={dx:n.lastX+r.x,dy:n.lastY+r.y},s=o.current?.getBoundingClientRect(),a=s?((e,t,n,r,o,i)=>{const s=_l(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,u=1/0;for(const d of Tl){const e=_l(d,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<u&&(u=t,l=d)}return l})(i,e,window.innerWidth,window.innerHeight,s.width,s.height):e;return T(a,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}R(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&R(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:x});/* @__PURE__ */
19
+ /* @__PURE__ */b(Ds,{onMouseDown:e=>e.preventDefault(),render:/* @__PURE__ */b(lc,{label:"Dismiss",size:"xs",tone:"inherit",style:{color:t.closeColor,padding:"2px"}}),children:/* @__PURE__ */b(cc,{name:"closeSmall",size:12})})]},e.id)})},mc=({children:e,container:t,offsetBottom:n=20})=>/* @__PURE__ */v(_i,{children:[e,/* @__PURE__ */b(Vs,{container:t??void 0,children:/* @__PURE__ */b(ns,{className:"mtx-toast-viewport",style:{zIndex:2147483004,bottom:`${n}px`},children:/* @__PURE__ */b(fc,{})})})]}),gc=({error:e,onClearError:t,onRetry:n,greeting:r,greetingBody:o,onGreetingDismiss:i})=>{const{add:s,close:c}=Aa();return a(()=>{null!=e?s({id:"error",type:"error",title:e,timeout:0,priority:"high",onClose:t,...n&&{actionProps:{children:"Retry",onClick:n}}}):c("error")},[e,n,s,c,t]),a(()=>{r?s({id:"greeting",type:"info",title:r,description:o,timeout:8e3,onClose:i}):c("greeting")},[r,o,s,c,i]),null},yc=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function bc(e){return Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!function(e){for(let t=e;t;t=t.parentElement)if("true"===t.getAttribute("aria-hidden"))return!0;return!1}(e))}function*vc(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function wc(e){if(!(e instanceof Element))return!1;try{const t=e.tagName.toLowerCase();if(!("button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||yc.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0))return!1;const n=window.getComputedStyle(e);if("none"===n.display||"none"===n.pointerEvents)return!1;const r=e.getBoundingClientRect();if(r.width<=0||r.height<=0)return!1;for(const o of vc(e))if(o!==e){const e=window.getComputedStyle(o).overflow;if("hidden"===e||"clip"===e){const e=o.getBoundingClientRect();if(r.right<e.left||r.left>e.right||r.bottom<e.top||r.top>e.bottom)return!1}if(o===document.body)break}for(let o=e.getRootNode();o instanceof ShadowRoot;o=o.host.getRootNode()){const e=o.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return console.error("[isIndexable] Unexpected error:",t),!1}}var xc=["id","type","role","aria-label","name","href"],Sc=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateAnchoredSelector(e){const t=[];let n=e;for(;n!==document.body;){const e=n.id?`#${CSS.escape(n.id)}`:"";if(e&&1===document.querySelectorAll(e).length)return t.unshift(e),t.join(" > ");const r=n.parentElement;if(!r)break;const o=n.tagName,i=Array.from(r.children).filter(e=>e.tagName===o),s=i.length>1?`:nth-of-type(${i.indexOf(n)+1})`:"";t.unshift(o.toLowerCase()+s),n=r}return["body",...t].join(" > ")}indexElements(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap;const e=document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT,{acceptNode:e=>{if(e instanceof HTMLElement&&null===e.offsetParent&&"BODY"!==e.tagName){const t=window.getComputedStyle(e),n="fixed"===t.position||"sticky"===t.position;if("none"===t.display)return NodeFilter.FILTER_REJECT;if(!n){let t=e.parentElement,n=!1;for(;t&&t!==document.body;){const e=window.getComputedStyle(t);if("fixed"===e.position||"sticky"===e.position){n=!0;break}t=t.parentElement}if(!n)return NodeFilter.FILTER_REJECT}}return NodeFilter.FILTER_ACCEPT}});let t=e.nextNode(),n=0;for(;t;){const r=t instanceof HTMLElement?t:null;if(r){const e=r.matches('a[href], button, input, textarea, select, [role="button"]'),t=r.classList.contains("cursor-pointer")||r.classList.contains("clickable"),o="function"==typeof r.onclick;(e||t||o||wc(r))&&(this.index.set(n,{element:r,selector:this.generateAnchoredSelector(r),identity:xc.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}reindexAndSnapshot(){this.indexElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{e.querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){Oe(`[DomService] Failed to tag index ${n}:`,t)}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}notInteractableReason(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=function(e){if(!0===e.disabled)return"is a disabled control";if("true"===e.getAttribute("aria-disabled"))return"is aria-disabled";for(const t of vc(e))if(t.hasAttribute("inert"))return"is inside an inert subtree";return null}(e);if(n)return`ELEMENT_NOT_INTERACTABLE: Element ${t} ${n}`;const r=window.getComputedStyle(e);if("none"===r.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===r.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(r.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const o=e.getBoundingClientRect();if(0===o.width||0===o.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;const i=o.left+o.width/2,s=o.top+o.height/2,a=document.elementFromPoint(i,s);if(a&&a!==e&&!e.contains(a)&&!a.closest("#marketrix-show-highlight, #marketrix-show-popup, .marketrix-widget-container")){const e=a.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${a.className?`${e}.${a.className.split(" ")[0]}`:e}. The obscuring element may be a modal or overlay that needs to be dismissed first.`}return null}getValidatedElement(e){const t=this.index.get(e);if(!t)return{element:null,error:`Element ${e} not found`};const n=!document.contains(t.element),r=xc.some((e,n)=>t.element.getAttribute(e)!==t.identity[n]);if(n||r)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const o=this.notInteractableReason(t.element,e);return o?{element:null,error:o}:{element:t.element}}},kc=e=>e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement,Cc=e=>e instanceof HTMLButtonElement||"button"===e.getAttribute("role");function Ec(e,t){const n=1===t?"ArrowDown":"ArrowUp",r=e.selectedIndex+t;return r<0||r>=e.options.length?`${n}: already at ${1===t?"last":"first"} option`:(e.selectedIndex=r,e.dispatchEvent(new Event("change",{bubbles:!0})),`${n}: selected "${e.options[r]?.text??""}"`)}function Ic(e,t){const n=e.value,r=e.selectionStart??n.length,o=e.selectionEnd??n.length;let i,s;if(r!==o)i=n.slice(0,r)+n.slice(o),s=r;else if("Backspace"===t&&r>0)i=n.slice(0,r-1)+n.slice(o),s=r-1;else{if(!("Delete"===t&&r<n.length))return`${t}: ${"Backspace"===t?"cursor at start":"cursor at end"}, nothing to delete`;i=n.slice(0,r)+n.slice(r+1),s=r}return function(e,t,n){Mc(e,t),e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}(e,i,s),`${t}: deleted character, value is now "${i}"`}function Mc(e,t){const n=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;n?n.call(e,t):e.value=t}var Tc=["scroll","resize","touchmove","wheel"],Rc="#3b82f6",Oc="#1f2937",Ac=new class{currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;visibilityCheckInterval=null;async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,browserToolName:o}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.browserToolName===o&&this.currentPromise||(this.cleanup(),this.currentOptions=e,this.currentElement=t,t.scrollIntoView({behavior:"instant",block:"center",inline:"center"}),this.createHighlight(),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.(/* @__PURE__ */new Error("Cancelled by cleanup")),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of Tc)window.removeEventListener(e,this.scrollHandler,{capture:!0});this.scrollHandler=null}this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.currentPopup?.remove(),this.currentHighlight?.remove(),document.getElementById("marketrix-show-popup")?.remove(),document.getElementById("marketrix-show-highlight")?.remove(),this.currentPopup=null,this.currentHighlight=null,this.currentElement=null,this.currentOptions=null,this.currentPromise=null}settle(e){const{resolve:t,reject:n}=this.takeSettlers();e?n?.(new Error(e)):t?.(),this.cleanup()}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(){const e=document.createElement("div");e.id="marketrix-show-highlight",e.style.cssText=`position:fixed;border:3px solid ${Rc};border-radius:4px;box-shadow:0 0 0 4px rgba(59,130,246,0.2),0 0 20px rgba(59,130,246,0.4);z-index:2147483645;pointer-events:none;transition:none;`,document.body.appendChild(e),this.currentHighlight=e,this.trackElement()}trackElement(){if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();Object.assign(this.currentHighlight.style,{top:`${e.top}px`,left:`${e.left}px`,width:`${e.width}px`,height:`${e.height}px`}),this.updatePopupPosition()}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: ${Oc}; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom:12px;font-weight:500;color:${Oc};font-size:12px;">${this.escapeHtml(e)}</div><div style="display:flex;gap:8px;justify-content:flex-end;"><button id="marketrix-show-continue" style="background:${Rc};color:white;border:none;border-radius:6px;padding:8px 16px;font-size:12px;font-weight:500;cursor:pointer;">Continue</button></div>`,n.style.cssText="position: fixed; width: 320px; background: white; border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); z-index: 2147483646; padding: 16px;",document.body.appendChild(n),this.currentPopup=n,t||window.requestAnimationFrame(()=>{n.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.settle()})}),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>this.trackElement();for(const e of Tc)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=10,n=e.left+e.width/2,r=e.top+e.height/2,o=[{left:e.right+20,top:r-60},{left:e.left-320-20,top:r-60},{left:n-160,top:e.top-120-20},{left:n-160,top:e.bottom+20}];let i=o[0];for(const s of o)if(s.left>=t&&s.left+320<=window.innerWidth-t&&s.top>=t&&s.top+120<=window.innerHeight-t){i=s;break}this.currentPopup.style.left=`${Math.max(t,Math.min(i.left,window.innerWidth-320-t))}px`,this.currentPopup.style.top=`${Math.max(t,Math.min(i.top,window.innerHeight-120-t))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.settle())},document.addEventListener("click",this.clickHandler,{capture:!0})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{const e=this.currentElement;if(!e)return;const t=e.getBoundingClientRect();if(t.bottom<0||t.top>window.innerHeight||t.right<0||t.left>window.innerWidth)return void this.settle("ELEMENT_OFF_SCREEN: The highlighted element scrolled out of view");const n=Sc.getSequenceForElement(e)??-1,r=Sc.notInteractableReason(e,n);r&&this.settle(r)},200)}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},_c=e=>({success:!0,data:{text:e}}),Dc=e=>({success:!0,data:e}),Pc=e=>({success:!1,error:e}),Nc=(e,t)=>({success:!0,data:{text:e},afterResponseAttempt:t}),Lc="finish",Fc=new class{tools={navigate:{label:"Navigating",run:e=>this.navigate(e)},search_web:{label:"Searching",run:e=>this.search(e)},click_element:{label:"Clicking element",waitForUser:!0,run:e=>this.clickElement(e)},type_text:{label:"Typing text",waitForUser:!0,run:e=>this.typeText(e)},scroll:{label:"Scrolling",run:e=>this.scroll(e)},scroll_to_text:{label:"Scrolling to text",run:e=>this.scrollToText(e)},extract:{label:"Extracting content",run:e=>this.extract(e)},go_back:{label:"Going back",run:()=>this.goBack()},wait_seconds:{label:"Waiting",run:e=>this.wait(e)},select_dropdown:{label:"Selecting option",waitForUser:!0,run:e=>this.selectDropdownOption(e)},get_dropdown_options:{label:"Reading dropdown options",run:e=>this.getDropdownOptions(e)},send_keys:{label:"Pressing key",waitForUser:!0,run:e=>this.sendKeys(e)},close_tab:{label:"Closing tab",run:()=>this.closeTab()},[Lc]:{label:"Done",run:e=>this.done(e)},get_html:{label:"Reading the page",run:()=>this.getHtml()},get_screenshot:{label:"Taking screenshot",run:()=>this.getScreenshot()}};element(e){if(void 0===e)throw new Error("Index required");const{element:t,error:n}=Sc.getValidatedElement(e);if(!t)throw new Error(n||`Element ${e} not found`);return t}selectElement(e){const t=this.element(e);if(!(t instanceof HTMLSelectElement))throw new Error(`Element ${e} is not a select element`);return t}getFriendlyToolName(e){return this.tools[e]?.label??e}isWaitForUserTool(e){return!!this.tools[e]?.waitForUser}async executeTool(e,t,n,r=""){const o=t,i=this.tools[e];try{return"show"===n&&i?.waitForUser&&void 0!==o.index&&await Ac.showToolAction({element:this.element(o.index),explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e}),i?await i.run(o):Pc(`Unknown tool: ${e}`)}catch(s){return Pc(Re(s))}}navigate(e){const t=(e=>{if(!e)return null;try{const t=new URL(e,window.location.href);return"http:"===t.protocol||"https:"===t.protocol?t.href:null}catch{return null}})(e.url);return t?e.new_tab?window.open(t,"_blank")?_c(`Opened ${t} in new tab`):Pc("The browser blocked opening a new tab"):Nc(`Navigating to ${t}`,()=>{window.location.href=t}):Pc("An http(s) URL is required")}search(e){if(!e.query)return Pc("Query is required");const t=e.engine||"duckduckgo",n=encodeURIComponent(e.query);let r=`https://duckduckgo.com/?q=${n}`;return"google"===t&&(r=`https://www.google.com/search?q=${n}`),"bing"===t&&(r=`https://www.bing.com/search?q=${n}`),Nc(`Searching for "${e.query}" on ${t}`,()=>{window.location.href=r})}async clickElement(e){const t=this.element(e.index);return t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),Nc(`Clicking element ${e.index}`,()=>t.click())}typeText(e){if(void 0===e.text)return Pc("Text required");const t=!1!==e.clear,n=this.element(e.index);if(kc(n))n.focus(),Mc(n,t?e.text:n.value+e.text),n.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text})),n.dispatchEvent(new Event("change",{bubbles:!0})),n.dispatchEvent(new Event("blur",{bubbles:!0}));else if(n.isContentEditable){n.focus();const r=window.getSelection();if(t?r?.selectAllChildren(n):r?.collapse(n,n.childNodes.length),!document.execCommand("insertText",!1,e.text))return Pc(`Could not insert text into element ${e.index}`)}else"value"in n?(n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))):(n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})));return _c(`Typed text into element ${e.index}`)}scroll(e){const t=.8*window.innerHeight;switch(e.direction){case"down":window.scrollBy({top:t,behavior:"smooth"});break;case"up":window.scrollBy({top:-t,behavior:"smooth"});break;case"left":window.scrollBy({left:-t,behavior:"smooth"});break;case"right":window.scrollBy({left:t,behavior:"smooth"});break;default:return Pc("Invalid direction")}return _c(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return Pc("Text required");const t=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let n;for(;n=t.nextNode();)if(n.textContent?.includes(e.text)&&n.parentElement)return n.parentElement.scrollIntoView({behavior:"smooth",block:"center"}),_c(`Scrolled to "${e.text}"`);return Pc(`Text "${e.text}" not found`)}extract(e){const t=!1!==e.extract_links,n={title:document.title,url:window.location.href,text:document.body.innerText.slice(0,1e4),links:t?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]};return Dc(n)}goBack(){return window.history.length<=1?Pc("No history"):Nc("Going back",()=>window.history.back())}async wait({seconds:e}){return void 0===e?Pc("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),_c(`Waited ${e}s`))}selectDropdownOption(e){if(!e.option)return Pc("Option required");const t=this.selectElement(e.index),n=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return n?(t.value=n.value,t.dispatchEvent(new Event("change",{bubbles:!0})),_c(`Selected ${e.option}`)):Pc(`Option ${e.option} not found`)}getDropdownOptions(e){const t=Array.from(this.selectElement(e.index).options).map(e=>({value:e.value,text:e.text}));return Dc({options:t})}sendKeys(e){if(!e.keys)return Pc("Keys required");const t=this.element(e.index);t.focus(),t.dispatchEvent(new KeyboardEvent("keydown",{key:e.keys,bubbles:!0,cancelable:!0})),t.dispatchEvent(new KeyboardEvent("keyup",{key:e.keys,bubbles:!0,cancelable:!0}));const n=function(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=bc(document),o=r.indexOf(e),i=-1===o?void 0:r[o+n];return i?(i.focus(),`${t}: moved focus to ${i.tagName.toLowerCase()}${i.id?`#${i.id}`:""}`):`${t}: no ${n>0?"next":"previous"} focusable element`}case"Enter":if(Cc(e))return e.click(),"Enter: clicked button";if(kc(e)){const t=e.closest("form");if(t){const e=t.querySelector('button[type="submit"], input[type="submit"]');return e?(e.click(),"Enter: clicked form submit button"):(t.requestSubmit(),"Enter: submitted form")}}return e instanceof HTMLAnchorElement?(e.click(),"Enter: clicked link"):"Enter: dispatched event";case"Escape":return e.blur(),document.dispatchEvent(new KeyboardEvent("keydown",{key:"Escape",bubbles:!0,cancelable:!0})),"Escape: blurred element and dispatched to document";case" ":case"Space":return e instanceof HTMLInputElement&&("checkbox"===e.type||"radio"===e.type)?(e.click(),`Space: toggled ${e.type}`):Cc(e)?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":return e instanceof HTMLSelectElement?Ec(e,1):"ArrowDown: dispatched event";case"ArrowUp":return e instanceof HTMLSelectElement?Ec(e,-1):"ArrowUp: dispatched event";case"Home":return kc(e)?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(kc(e)){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":return kc(e)?Ic(e,"Backspace"):"Backspace: dispatched event";case"Delete":return kc(e)?Ic(e,"Delete"):"Delete: dispatched event";default:return null}}(t,e.keys);return _c(n||`Sent keys ${e.keys}`)}closeTab(){return window.close(),window.closed?_c("Tab closed"):Pc("The browser refused to close a tab this script did not open")}done(e){return _c(e.message||"Task ended")}getHtml(){return _c(Sc.reindexAndSnapshot())}async getScreenshot(){const e=gr();if(!e)return Pc("The visitor is not sharing their screen.");const t=document.createElement("video");try{t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise((e,n)=>{const r=setTimeout(()=>n(/* @__PURE__ */new Error("Screen capture produced no frame")),5e3);t.onloadeddata=()=>{clearTimeout(r),e()},t.onerror=()=>{clearTimeout(r),n(/* @__PURE__ */new Error("Screen capture failed"))}});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight;const r=n.getContext("2d");return r?(r.drawImage(t,0,0),_c(n.toDataURL("image/jpeg",.75))):Pc("Could not read the shared screen: the browser refused a 2d canvas context.")}finally{t.remove()}}},zc={show:"Show",tell:"Tell",do:"Do"},$c=e=>zc[e];function Bc(e,t){for(let n=e.length-1;n>=0;n--){const r=e[n];if(void 0!==r&&t(r))return n}return-1}function Wc({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest&&!e.taskStatus,o=e=>e.isPlaceholder&&void 0===e.mode||e.mode===n,i=[];!t||"show"!==n&&"do"!==n||i.push(e=>r(e)&&o(e)&&!!e.isPlaceholder,e=>r(e)&&o(e)),i.push(e=>r(e)&&!!e.isPlaceholder,r);const s=Bc(e,e=>"agent"===e.sender&&!!e.taskStatus)+1,a=e.slice(s);for(const c of i){const e=Bc(a,c),t=e>=0?a[e]:void 0;if(t)return{index:s+e,message:t}}return Oe(`[MessageFinder] No message found for progress update: totalMessages=${e.length} isTaskRunning=${t} currentMode=${n}`),null}var Uc=e=>e.replace(/\(?cancelled by cleanup\)?/gi,"").trim();function Hc(e,t,n){const r=t>=0?e.parts[t]:void 0;if(!r)return e;const o=[...e.parts];return o[t]={...r,...n},{...e,parts:o}}var jc=(e,t)=>e.parts.findIndex(e=>"progress"===e.type&&"in_progress"===e.status&&e.browserToolName===t);function qc(e,t,n,r={}){return{id:`${e}-${globalThis.crypto.randomUUID()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Vc=(e,t,n="user-message")=>qc(n,"user",e.trim(),{mode:t}),Yc=e=>qc("agent-message","agent",e.trim()),Kc=(e,t)=>qc(t,"agent",e,{isSystemMessage:!0}),Xc=e=>e.filter(e=>"text"===e.type).map(e=>e.content).join("\n"),Gc=e=>({state:e,effects:[]});function Jc(e,t,n,r,o,i,s){const a=Wc({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;if("failed"===i?c=function(e,t,n){const r=jc(e,t),o=r>=0?e.parts[r]:void 0;if(!o)return e;const i=Uc(o.content),s=Uc(n);return Hc(e,r,{status:"failed",content:s?`${i} (${s})`:i})}(c,r,s||""):"finish"!==r&&(c="in_progress"===i?function(e,t,n){const r=Uc(n),o=jc(e,t);return o>=0?Hc(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||Fc.getFriendlyToolName(r)):((e,t)=>Hc(e,jc(e,t),{status:"completed"}))(c,r)),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&Fc.isWaitForUserTool(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const l=[...e];return l[a.index]=c,l}var Zc=(e,t)=>"running"===e.task.phase?e.task.mode??t:t,Qc=e=>({...e,isPlaceholder:!1}),el=e=>"stopped"===e.phase?e:{phase:"idle"};function tl(e,t,n){const r=Wc({messages:e.messages,isTaskRunning:"running"===e.task.phase,currentMode:Zc(e,t)}),o=[...e.messages];return r&&(o[r.index]=Qc(n(r.message))),{messages:o,task:el(e.task)}}var nl={completed:"done",failed:"failed",stopped:"stopped"};function rl(e,t,n,r){const o=e.messages.map(e=>{if(e.id!==t)return e;const o=[...e.parts],i=o[o.length-1],s="text"===i?.type&&!0===i.streaming,a={type:"text",content:r&&s?i.content+n:n,...r&&{streaming:!0}};return s?o[o.length-1]=a:o.push(a),{...e,content:Xc(o),isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}var ol=(e,t)=>{const n=[...e.parts,{type:"text",content:t}];return{...e,content:Xc(n),parts:n}},il=(e,t)=>({...Qc(ol(e,t)),placeholderState:void 0,taskStatus:"failed"});function sl(e,t,n){const r=e.messages.map(e=>e.id===t?il(e,n):e);return{...e,messages:r}}var al=n(void 0),cl=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell"}),r=u(()=>({setActiveView:e=>n(t=>({...t,activeView:e})),toggleWidget:()=>n(e=>({...e,isOpen:!e.isOpen})),closeWidget:()=>n(e=>({...e,isOpen:!1})),setMode:e=>n(t=>({...t,currentMode:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]),o=u(()=>({uiState:t,uiActions:r}),[t,r]);/* @__PURE__ */
20
+ return b(al.Provider,{value:o,children:e})},ll=()=>{const e=s(al);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},ul=n(void 0),dl=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=ll(),[o,s]=p(()=>({messages:[],task:{phase:"idle"}})),c=d(o),l=d(n.currentMode);l.current=n.currentMode;const h=d(/* @__PURE__ */new Set),f=i(e=>{const t=c.current,n=e(t);n===t||n.messages===t.messages&&n.task===t.task||(c.current=n,s(n))},[]),m=i(e=>{f(t=>({...t,messages:[...t.messages,e]}))},[f]),g=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),y=i(e=>{f(t=>({...t,messages:t.messages.filter(t=>t.id!==e)}))},[f]),v=i(e=>{f(t=>({...t,messages:e}))},[f]),w=i(()=>{f(e=>({...e,messages:[]}))},[f]),x=i(()=>{f(e=>({...e,task:{phase:"idle"}}))},[f]),S=o.messages.filter(e=>e.isPlaceholder).map(e=>`${e.id}:${e.parts.length}`).join(" ");a(()=>{const e=S.split(" ").filter(Boolean).map(e=>e.split(":")[0]).filter(e=>void 0!==e).map(e=>setTimeout(()=>f(t=>function(e,t){const n=e.messages.find(e=>e.id===t);return n?.isPlaceholder&&"waiting-for-user"!==n.placeholderState?sl(e,t,"This is taking longer than expected. Please try again."):e}(t,e)),12e4));return()=>e.forEach(clearTimeout)},[S,f]);const k=i(async(e,n,r)=>{const o=n??l.current;if(t)return r||m(Vc(e,o)),void m(Yc("This is a preview. In production, I'll respond to your messages here."));if(!$e.getCredentialedConfig())return console.error("Config not loaded or incomplete"),void m(Yc("Configuration error: Missing API credentials. Please check your widget settings."));r||m(Vc(e,o));const i=(e=>qc("temp","agent","",{mode:e,isPlaceholder:!0,placeholderState:"thinking"}))(o);f(e=>function(e,t){return{messages:[...e.messages,t],task:{phase:"idle"}}}(e,i));try{await async function(e,t,n){const r=await Be.getOrCreateChatId(),o={type:`chat/${t}`,request_id:n,content:e};await hr.ready(r),await hr.send(o)}(e,o,i.id)}catch(s){console.error("Failed to send message:",s),f(e=>sl(e,i.id,"I'm sorry, I encountered an error processing your request. Please try again."))}},[t,m,f]);a(()=>{if(t)return;const e=async e=>{const{toolCallId:t,tool:n,args:o,mode:i,explanation:s}=e,a=await Fc.executeTool(n,o,i,s),c=a.success?void 0:a.error;f(e=>function(e,t,n,r,o,i){return{...e,messages:Jc(e.messages,"running"===e.task.phase,Zc(e,o),t,n,r,i)}}(e,n,s,c?"failed":"completed",l.current,c)),c||"finish"!==n||f(e=>function(e,t){return tl(e,t,e=>({...e,taskStatus:"done",parts:e.parts.filter(e=>"progress"!==e.type)}))}(e,l.current)),await hr.send({type:"tool/response",tool_call_id:t,success:a.success,...a.success&&{data:JSON.stringify(a.data)},error:c}).catch(e=>{console.error("Failed to send tool response:",e),r.setError("Could not report that step back to the assistant — it may stop responding.")}),a.success&&a.afterResponseAttempt?.()},n={onMessage:t=>{if("tool/call"===t.type){const e=t.tool_call_id;if(h.current.has(e))return;h.current.add(e),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500)))}else"task/status"===t.type&&t.status in nl&&h.current.clear();let n=[];f(e=>{const r=function(e,t,n){switch(t.type){case"tool/call":{if("stopped"===e.task.phase)return Gc(e);const r="running"===e.task.phase?e.task:{phase:"running",mode:t.mode||n},o=t.explanation||"";return{state:{messages:Jc(e.messages,!0,r.mode??n,t.browser_tool,o,"in_progress"),task:r},effects:[{type:"executeTool",toolCallId:t.tool_call_id,tool:t.browser_tool,args:t.args,mode:t.mode||n,explanation:o}]}}case"task/status":{if("running"===t.status)return Gc(e);const r=t.status,o=e=>t.message?ol(e,t.message):e;return{state:tl(e,n,"has_question"===r?e=>({...o(e),placeholderState:"waiting-for-user"}):e=>({...o(e),taskStatus:nl[r]})),effects:[]}}case"chat/delta":return{state:rl(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:rl(e,t.request_id,t.text,!1),effects:[]};case"chat/error":return{state:sl(e,t.request_id,`Error: ${t.error}`),effects:[]};default:return Gc(e)}}(e,t,l.current);return n=r.effects,r.state});for(const o of n)e(o).catch(e=>{console.error("[Widget] Tool call failed:",e),r.setError("Something went wrong running that step. Please try again.")})},onError:e=>{r.setError(e.message),e instanceof pr&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?il(e,t):e),task:el(e.task)}}(t,e.message))}};return hr.addCallbacks(n),()=>{hr.removeCallbacks(n)}},[t,f,r]);const C=i(async()=>{f(e=>function(e,t){return{...tl(e,t,e=>({...e,taskStatus:"stopped"})),task:{phase:"stopped"}}}(e,l.current)),t||hr.send({type:"chat/stop"}).catch(e=>{console.error("Failed to stop task remotely:",e),r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),E=u(()=>({addMessage:m,updateMessage:g,removeMessage:y,setMessages:v,clearMessages:w,messageDispatch:k}),[m,g,y,v,w,k]),I=u(()=>({resetTask:x,stopTask:C}),[x,C]),M=u(()=>({messages:o.messages,chatActions:E,taskState:o.task,taskActions:I}),[o.messages,E,o.task,I]);/* @__PURE__ */
21
+ return b(ul.Provider,{value:M,children:e})},pl=()=>{const e=s(ul);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},hl=n(null),fl=()=>{const{uiState:e}=ll(),{messages:t}=pl();return a(()=>{const{currentMode:n,isOpen:r}=e;var o;o={messages:t,currentMode:n,isOpen:r},$e.updateContext({...o,messages:o.messages.map(({videoStream:e,...t})=>{const n=t.timestamp.toISOString();if(!e)return{...t,timestamp:n};const r="Screen sharing ended";return{...t,timestamp:n,content:r,isSystemMessage:!0,parts:[{type:"text",content:r}]}})})},[t,e]),null},ml=({children:e,previewMode:t})=>{const{uiActions:n}=ll(),{chatActions:r}=pl(),[o,i]=p(!1);return a(()=>{if(t)return;let e=!1;return(async()=>{const{messages:t,...o}=function(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=$e.getContext();return{...o,messages:r.map(e=>{const t=[...e.parts],n=e.content.trim();return 0===t.length&&n&&t.push({type:"text",content:n}),{...e,timestamp:new Date(e.timestamp),parts:t}})}}();n.applyState(o),r.setMessages(t),i(!0);const s=await Be.getOrCreateChatId();e||hr.connect(s)})().catch(t=>{e||(console.error("Widget initialization failed:",t),n.setError("Widget failed to initialise — please refresh the page."))}),()=>{e=!0}},[t,n,r]),/* @__PURE__ */v(y,{children:[e,o&&/* @__PURE__ */b(fl,{})]})},gl=({children:e,previewMode:t=!1})=>/* @__PURE__ */b(cl,{children:/* @__PURE__ */b(dl,{previewMode:t,children:/* @__PURE__ */b(ml,{previewMode:t,children:e})})}),yl=/^#?([a-f\d]{3}|[a-f\d]{6})$/i,bl=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i;function vl(e){const t=yl.exec(e.trim())?.[1];if(t){const[e,n,r]=3===t.length?[t.charAt(0)+t.charAt(0),t.charAt(1)+t.charAt(1),t.charAt(2)+t.charAt(2)]:[t.slice(0,2),t.slice(2,4),t.slice(4,6)];return{r:parseInt(e??"",16),g:parseInt(n??"",16),b:parseInt(r??"",16)}}const n=bl.exec(e.trim());if(!n)return null;const r=Number(n[1]),o=Number(n[2]),i=Number(n[3]);return r>255||o>255||i>255?null:{r:r,g:o,b:i}}function wl(e){const t=vl(e);if(!t)return"#000000";const n=e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4);return.2126*n(t.r/255)+.7152*n(t.g/255)+.0722*n(t.b/255)>.5?"#000000":"#ffffff"}function xl(e,t){const n=vl(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}function Sl(e){return e.includes("gradient")?e:`linear-gradient(135deg, ${e} 0%, ${e} 100%)`}var kl={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"},Cl=n(null),El=()=>{const e=s(Cl);if(!e)throw new Error("useWidgetConfig must be used within WidgetRoot");return e},Il=()=>{const{uiState:e,uiActions:t}=ll(),{messages:n,chatActions:r,taskState:o,taskActions:i}=pl();return{state:u(()=>({...e,messages:n,isTaskRunning:"running"===o.phase,isAwaitingReply:n.some(e=>e.isPlaceholder)}),[e,n,o]),actions:u(()=>({...t,...i,...r,clearChatHistory:()=>{r.clearMessages(),i.resetTask(),t.setError(void 0)}}),[t,i,r])}},Ml={bottom_right:{vertical:"bottom",horizontal:"right"},bottom_left:{vertical:"bottom",horizontal:"left"},top_right:{vertical:"top",horizontal:"right"},top_left:{vertical:"top",horizontal:"left"}},Tl=Object.keys(Ml),Rl=e=>Ml[e],Ol=e=>{const{vertical:t,horizontal:n}=Rl(e);return{[t]:"20px",[n]:"20px"}},Al={top:"bottom",bottom:"top",left:"right",right:"left"},_l=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Rl(e);return{x:"left"===s?20:t-20-r,y:"top"===i?20:n-20-o}},Dl=class extends t.Component{state={hasError:!1};static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){console.error(`${this.props.label} Error Boundary caught error:`,e,t)}render(){return this.state.hasError?this.props.fallback??null:this.props.children}},Pl="cubic-bezier(0.16, 1, 0.3, 1)",Nl=({onPositionCommit:e})=>{const{isPreviewMode:n=!1,widget_accent_color:r,widget_background_color:o,widget_position:s,widget_position_z_index:a}=El(),{state:c,actions:u}=Il(),h=c.isOpen,f=c.isTaskRunning,m=!!c.error,g=!h&&(c.isAwaitingReply||f),y=!h&&f,w=m?"error":"processing",x=d(null),{isDragging:S,pixelPositionStyle:k,onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,suppressUntilRef:T}=function({position:e,onPositionCommit:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,u]=p({w:56,h:56}),[,h]=p(0),f=d(null),m=d(null),g=d(null),y=d(0),b=d([]),v=d(0),w=()=>{null!==g.current&&window.cancelAnimationFrame(g.current),g.current=null};t.useEffect(()=>w,[]),t.useEffect(()=>{if(r)return;const e=()=>h(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[r]);const x=i(()=>{if(!o.current||"undefined"==typeof window)return;const e=o.current.getBoundingClientRect();u(t=>t.w===e.width&&t.h===e.height?t:{w:e.width,h:e.height})},[o]);l(()=>{x();const e="undefined"!=typeof window&&o.current?new ResizeObserver(x):null;return e&&o.current&&e.observe(o.current),()=>e?.disconnect()},[x,e,o]);const S="undefined"!=typeof window?window.innerWidth:0,k="undefined"!=typeof window?window.innerHeight:0,C=_l(e,S,k,c.w,c.h),E=!r&&S>0&&k>0?{left:C.x,top:C.y}:void 0,I=i(()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="",o.current.style.left="",o.current.style.top="")},[o]),M=i((e,t)=>{f.current?.();let r=!1;const i=()=>{r=!0,window.clearTimeout(c),t.removeEventListener("transitionend",l),f.current=null},s=()=>{r||(i(),t.style.transition="none",t.style.willChange="",t.style.left="",t.style.top="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))},c=window.setTimeout(s,650),l=e=>{e.target===t&&"left"===e.propertyName&&s()};t.addEventListener("transitionend",l),f.current=i},[n,o]),T=i((t,r,i)=>{if(!o.current||!E)return I(),n(t),void a(!1);w();const s=o.current,l=_l(e,S,k,c.w,c.h),u=_l(t,S,k,c.w,c.h);s.style.transition="none",s.style.transform="none",s.style.willChange="left, top",s.style.left=`${l.x+r}px`,s.style.top=`${l.y+i}px`,requestAnimationFrame(()=>{s.style.transition=`left 600ms ${Pl}, top 600ms ${Pl}`,s.style.left=`${u.x}px`,s.style.top=`${u.y}px`}),M(t,s)},[M,n,E,e,I,S,k,c.w,c.h,o]),R=e=>{I(),m.current=null,a(!1),e.currentTarget.releasePointerCapture(e.pointerId)};return{isDragging:s,pixelPositionStyle:E,onPointerDown:e=>{m.current={pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,dragging:!1,lastX:0,lastY:0},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:e=>{const t=m.current;if(t?.pointerId!==e.pointerId)return;const n=e.clientX-t.startX,r=e.clientY-t.startY;if(!t.dragging&&Math.hypot(n,r)>5&&(t.dragging=!0,a(!0),b.current=[],v.current=0,o.current&&(o.current.style.willChange="transform",o.current.style.transition="none")),!t.dragging)return;t.lastX=n,t.lastY=r;const i=Date.now();i-v.current>=10&&(v.current=i,b.current=[...b.current.slice(-5),{x:e.clientX,y:e.clientY,t:i}]),null===g.current&&(g.current=window.requestAnimationFrame(()=>{g.current=null;const e=m.current,t=o.current;t&&e&&(t.style.transform=`translate3d(${e.lastX}px, ${e.lastY}px, 0)`)}))},onPointerUp:t=>{const n=m.current;if(n?.pointerId===t.pointerId){if(n.dragging){const r=function(e,t=.999){if(e.length<2)return{x:0,y:0};const n=e[0],r=e[e.length-1];if(!n||!r)return{x:0,y:0};const o=r.t-n.t;if(o<=0)return{x:0,y:0};const i=e=>e/o*t/(1-t);return{x:i(r.x-n.x),y:i(r.y-n.y)}}(b.current),i={dx:n.lastX+r.x,dy:n.lastY+r.y},s=o.current?.getBoundingClientRect(),a=s?((e,t,n,r,o,i)=>{const s=_l(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,u=1/0;for(const d of Tl){const e=_l(d,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<u&&(u=t,l=d)}return l})(i,e,window.innerWidth,window.innerHeight,s.width,s.height):e;return T(a,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}R(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&R(e)},suppressUntilRef:y}}({position:s,onPositionCommit:e,isPreviewMode:n,wrapperRef:x});/* @__PURE__ */
22
22
  return b(rc,{ref:x,className:"mtx-fab-anchor","data-animated":S?"false":"true","data-preview":n?"true":"false",style:{zIndex:a,pointerEvents:h?"none":"auto",...S?k:Ol(s)},children:/* @__PURE__ */v(rc,{className:"mtx-fab","data-open":h?"true":"false",children:[g&&/* @__PURE__ */b(rc,{className:"mtx-fab-glow","data-tone":w,"aria-hidden":!0}),y&&!S&&/* @__PURE__ */b(Za,{type:"button",variant:"secondary",size:"sm",className:"mtx-fab-stop","data-side":s.includes("left")?"left":"right",onClick:e=>{e.preventDefault(),e.stopPropagation(),u.stopTask()},children:"Stop"}),
23
23
  /* @__PURE__ */b(Za,{type:"button",variant:"bare",onClick:()=>{Date.now()<T.current||u.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:C,onPointerMove:E,onPointerUp:I,onPointerCancel:M,className:"mtx-fab-trigger",style:{touchAction:"none",cursor:S?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":h?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */b(oc,{className:"mtx-fab-center",children:/* @__PURE__ */v(rc,{className:"mtx-fab-badge",style:{borderRadius:"12px",backgroundColor:h?o:r,boxShadow:La.fab},children:[g&&/* @__PURE__ */b("svg",{className:"mtx-fab-ring","data-tone":w,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */b("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
24
24
  /* @__PURE__ */b(oc,{className:"mtx-fab-icon-layer",style:{transform:h?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:h?0:1},"aria-hidden":h,children:/* @__PURE__ */b(Xa,{src:_a,alt:"",className:"mtx-fab-avatar",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:"12px",border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
@@ -40,16 +40,16 @@ return b($u,{open:e,onOpenChange:(e,n)=>{e||"none"===n.reason||t()},children:/*
40
40
  /* @__PURE__ */b(oc,{gap:"md",justify:"end",children:[["secondary",a,t],["primary",i,()=>o?.()]].map(([e,t,n])=>/* @__PURE__ */b(Za,{type:"button",variant:e,size:"sm",shape:"pill",onClick:e=>{e.preventDefault(),e.stopPropagation(),n()},children:t},e))})]})]})})},Uu={sm:{width:"14px",height:"14px",borderWidth:"1.5px"},md:{width:"20px",height:"20px",borderWidth:"2px"},lg:{width:"24px",height:"24px",borderWidth:"2px"}};function Hu({size:e="md",style:t,ref:n}){/* @__PURE__ */
41
41
  return v("div",{ref:n,"data-size":e,role:"status",style:{display:"inline-flex",alignItems:"center",gap:"6px",...t},children:[/* @__PURE__ */b("div",{"aria-hidden":"true",className:"mtx-spinner-ring",style:Uu[e]}),/* @__PURE__ */b("span",{className:"mtx-visually-hidden",children:"Loading"})]})}var ju="8px 8px 0 0",qu=({label:e,children:t})=>/* @__PURE__ */b(oc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{backgroundColor:"var(--overlay-dark)",borderRadius:ju,zIndex:10},children:/* @__PURE__ */v(oc,{direction:"column",align:"center",gap:"md",style:{textAlign:"center",padding:"0 16px"},children:[t,/* @__PURE__ */b(hc,{as:"span",size:"xs",weight:"medium",style:{color:"rgba(255,255,255,0.7)"},children:e})]})}),Vu=({stream:e})=>{const t=d(null),[n,r]=p(!1),[o,i]=p(!1);return a(()=>{const n=t.current;if(!n)return;r(!1),i(!1),n.srcObject=e;const o=()=>{r(!0)},s=()=>{i(!0),r(!1)};return n.addEventListener("loadedmetadata",o),n.addEventListener("error",s),n.play().catch(e=>{e instanceof Error&&"AbortError"!==e.name&&(console.error("Error playing video stream:",e),i(!0))}),()=>{n.removeEventListener("loadedmetadata",o),n.removeEventListener("error",s),n.srcObject=null}},[e]),/* @__PURE__ */v(rc,{width:"full",overflow:"hidden",position:"relative",style:{marginBottom:"4px",borderRadius:ju,backgroundColor:"#000000",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)"},children:[!n&&!o&&/* @__PURE__ */b(qu,{label:"Loading stream...",children:/* @__PURE__ */b(Hu,{size:"lg",style:{color:"white"}})}),o&&/* @__PURE__ */b(qu,{label:"Failed to load stream",children:/* @__PURE__ */b(cc,{name:"alertCircle",size:32,style:{color:"#9ca3af"}})}),
42
42
  /* @__PURE__ */b("video",{ref:t,autoPlay:!0,muted:!0,playsInline:!0,style:{width:"100%",height:"auto",maxHeight:"192px",objectFit:"contain",borderRadius:ju,transition:"opacity 500ms",opacity:n?1:0,minHeight:"120px",background:"linear-gradient(135deg, var(--overlay-dark) 0%, #374151 100%)"}}),n&&!o&&/* @__PURE__ */v(oc,{position:"absolute",align:"center",gap:"sm",animate:"fadeIn",style:{top:"8px",right:"8px",padding:"4px 8px",borderRadius:"var(--radius-pill)",backgroundColor:"rgba(55,65,81,0.9)",backdropFilter:"blur(4px)",zIndex:20,boxShadow:"0 2px 8px var(--foreground-faint)"},children:[/* @__PURE__ */b(mu,{style:{color:"white"}}),/* @__PURE__ */b(hc,{as:"span",size:"xs",weight:"semibold",style:{color:"white",textTransform:"uppercase",letterSpacing:"0.05em",fontSize:"10px"},children:"Live"})]}),
43
- /* @__PURE__ */b(oc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:ju,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(rc,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(hc,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]})},Yu={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},Ku=({isWaitingForUser:e})=>/* @__PURE__ */v(oc,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b(Hu,{size:"sm"}),/* @__PURE__ */b(hc,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),Xu=({message:e,isLastMessage:t})=>{const{isTaskRunning:n}=Il().state,r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return 0===e.parts.length?e.isPlaceholder||o?/* @__PURE__ */b(Ku,{isWaitingForUser:r}):/* @__PURE__ */b(rc,{}):/* @__PURE__ */v(ic,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(hc,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */b(oc,{align:"start",gap:"md",children:/* @__PURE__ */b(hc,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */b(Ku,{isWaitingForUser:r})]})},Gu=({message:e,isLastMessage:t,onScreenAccessAllow:n,onScreenAccessDeny:r})=>{const o=El().widget_accent_color;if(e.isSystemMessage)/* @__PURE__ */return b(oc,{justify:"center",align:"center",children:/* @__PURE__ */b(hc,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})});const i="user"===e.sender,s=i?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0,a=!i&&e.taskStatus?Yu[e.taskStatus]:void 0;/* @__PURE__ */
44
- return v(ic,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Assistant says…",animate:t?"fadeIn":void 0,children:[/* @__PURE__ */v(oc,{align:"start",gap:"sm",width:"full",children:[
45
- /* @__PURE__ */b(oc,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */b(Xa,{src:"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e",alt:"Marketrix AI",size:20,fit:"cover",rounded:"lg",style:{border:"none",outline:"none",display:"block",backgroundColor:"transparent"}})}),
46
- /* @__PURE__ */v(ic,{grow:!0,position:"relative",rounded:"lg",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:i?"var(--primary)":void 0,color:i?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */b(Vu,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */v(oc,{align:"start",gap:"sm",children:[/* @__PURE__ */b(oc,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b(cc,{name:s,size:13})}),/* @__PURE__ */b(ic,{grow:!0,children:/* @__PURE__ */b(Xu,{message:e,isLastMessage:t})})]}):/* @__PURE__ */b(Xu,{message:e,isLastMessage:t})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(oc,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(Za,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>n?.(),children:"Yes"}),/* @__PURE__ */b(Za,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(hc,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),a&&/* @__PURE__ */b(oc,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(cc,{name:a.name,size:14,style:{color:xl(o,a.opacity),flexShrink:0}})})]}),
47
- /* @__PURE__ */b(oc,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(hc,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:(c=e.timestamp,(c??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))})]});var c},Ju={boxShadow:La.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Zu=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=El(),{state:o,actions:i}=Il(),{messages:s}=o,{isPreviewMode:c}=r,[l,h]=p(!1),[f,m]=p(!1),g=d(null),y=u(()=>Yc(r.widget_body),[r.widget_body]),w=u(()=>[y,...s],[y,s]),x=()=>{if(g.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=g.current;h(e>200);const r=Math.abs(t-e-n)<50;m(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!c&&e.current.scrollIntoView({behavior:"auto"}),!c&&x())})},[s.length,c,e]);const S=s[s.length-1]?.content?.length??0;return a(()=>{const t=g.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[S,c,e]),/* @__PURE__ */v(rc,{position:"relative",height:"full",children:[/* @__PURE__ */v(rc,{ref:g,onScroll:x,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:Sl(r.widget_background_color),scrollbarColor:`${xl(r.widget_border_color,.3)} ${xl(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[w.map((e,r)=>/* @__PURE__ */b(Gu,{message:e,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */b(oc,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(Za,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(hc,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
- /* @__PURE__ */b(rc,{ref:e},"scroll-anchor")]},"message-list-container"),[{show:l,edge:{top:"8px"},label:"Scroll to top",icon:"arrowUp",onClick:()=>g.current?.scrollTo({top:0,behavior:"smooth"})},{show:f,edge:{bottom:"8px"},label:"Scroll to bottom",icon:"arrowDown",onClick:()=>!c&&e.current?.scrollIntoView({behavior:"smooth"})}].map(({show:e,edge:t,label:n,icon:o,onClick:i})=>e&&/* @__PURE__ */b(oc,{position:"absolute",justify:"center",style:{...t,left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(lc,{variant:"secondary",size:"sm",label:n,onClick:i,style:Ju,children:/* @__PURE__ */b(cc,{name:o,size:10,style:{color:r.widget_accent_color}})})},n))]})},Qu=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}];function ed(e){const t=d(e);return t.current=e,t}var td=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=El(),{state:o,actions:i}=Il(),{currentMode:s,isTaskRunning:l,isAwaitingReply:u}=o,[h,f]=p(""),m=d(null),{isScreenSharing:g,isAwaitingScreenAccess:y,showScreenAccessDialog:w,handleScreenAccessDialogAllow:x,handleScreenAccessDialogDismiss:S,handleScreenAccessRequestAllow:k,handleScreenAccessRequestDeny:C,requestScreenAccess:E}=function({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:n,onUpdateMessage:r,onRemoveMessage:o,onSendMessage:i,messages:s}){const[l,u]=p(!1),[d,h]=p(null),[f,m]=p(!1),g=ed(l),y=ed(d),b=ed(e),v=t=>{u(t),e?.(t)},w=e=>{e&&o?.(e),n(Kc("Screen sharing stopped","stopped-sharing")),h(null)},x=ed(w);a(()=>{const e=()=>{const e=null!==gr(),t=g.current,n=y.current;e!==t&&(g.current=e,u(e),b.current?.(e)),t&&!e&&n&&x.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[x,b,y,g]);const S=s[Bc(s,e=>!!e.isScreenAccessRequest&&!e.screenShareStatus)]??null,k=()=>{S?.pendingContent&&i(S.pendingContent,S.mode,!0)},C=e=>{S&&r(S.id,{screenShareStatus:e})},E=async()=>{try{const e=await async function(){if(!1===$e.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=gr();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return mr=t,t.getVideoTracks()[0]?.addEventListener("ended",()=>{mr=null}),t}();v(!0),C("allowed"),n(Kc("Screen sharing started","started-screenshare"));const t=((e,t="show")=>qc("screenshare","user","",{mode:t,videoStream:e}))(e,"show");h(t.id),n(t)}catch(e){console.error("Failed to start screen sharing:",e),v(!1),C("denied")}k()},I=E;return c(t,()=>()=>{l?(yr(),v(!1),w(d)):m(!0)}),{isScreenSharing:l,isAwaitingScreenAccess:null!==S,showScreenAccessDialog:f,handleScreenAccessDialogAllow:async()=>{m(!1),await E()},handleScreenAccessDialogDismiss:()=>{m(!1)},handleScreenAccessRequestAllow:I,handleScreenAccessRequestDeny:()=>{C("denied"),k()},requestScreenAccess:(e,t)=>{S||n(((e,t)=>qc("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0,pendingContent:t}))(e,t))}}}({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:i.addMessage,onUpdateMessage:i.updateMessage,onRemoveMessage:i.removeMessage,onSendMessage:i.messageDispatch,messages:o.messages}),I=y||u;/* @__PURE__ */
49
- return v(ic,{height:"full",children:[w&&/* @__PURE__ */b(Wu,{open:w,onClose:S,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:x,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:n}),
50
- /* @__PURE__ */b(ic,{grow:!0,overflow:"hidden",paddingY:"2xs",minHeight:"0",children:/* @__PURE__ */b(Dl,{label:"Chat",fallback:/* @__PURE__ */b(hc,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Zu,{messagesEndRef:m,onScreenAccessAllow:k,onScreenAccessDeny:C})})}),
51
- /* @__PURE__ */b(rc,{variant:"floatingCard",style:{marginTop:"auto"},children:/* @__PURE__ */b(bu,{ref:n,value:h,onChange:f,onSubmit:()=>{if(!h.trim()||I)return;const e=h.trim();f(""),i.addMessage(Vc(e,s)),!1===r.use_screenshare||"show"!==s&&"do"!==s||g?i.messageDispatch(e,s,!0):E(s,e)},modes:Qu.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:$c(e)})),activeMode:s,onModeChange:e=>{e!==s&&(i.addMessage(Kc(`Switched to ${$c(e)} mode`,"mode-change")),i.setMode(e))},disabled:I,taskRunning:l,onStop:()=>{Ac.cleanup(),i.stopTask()}})})]})},nd=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],rd=({onNavigateToChat:e,onChipClick:t})=>{const n=El(),{messages:r}=Il().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:"show"===e.chip_mode?`Show me ${e.chip_text.replace(/^Show me\s+/i,"")}`:"do"===e.chip_mode?`Do ${e.chip_text.replace(/^Do\s+/i,"")}`:e.chip_text,type:e.chip_mode})):nd}(n);/* @__PURE__ */
52
- return v(ic,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(ic,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(rc,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */b(hc,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */b(hc,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(ic,{gap:"sm",children:[/* @__PURE__ */v(Za,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */b(cc,{name:"chat",size:16}),"Ask a question"]}),o.map((r,o)=>/* @__PURE__ */b(Za,{elevation:"card",size:"sm",variant:"chip",full:!0,onClick:n=>(async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)})(r,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */b(hc,{as:"span",weight:"normal",leading:"tight",children:r.text})},`welcome-chip-${r.id}-${o}`))]})]}),r.length>0&&/* @__PURE__ */v(rc,{variant:"floatingCard",children:[
43
+ /* @__PURE__ */b(oc,{position:"absolute",inset:"0",align:"center",justify:"center",style:{borderRadius:ju,backgroundColor:"rgba(0,0,0,0)",zIndex:30,pointerEvents:"none"},children:/* @__PURE__ */b(rc,{rounded:"lg",style:{padding:"4px 12px",backgroundColor:"rgba(0,0,0,0.7)",backdropFilter:"blur(4px)"},children:/* @__PURE__ */b(hc,{as:"div",size:"xs",weight:"medium",style:{color:"white"},children:"Screen Sharing Active"})})})]})},Yu={done:{name:"checkCircle",opacity:1},failed:{name:"exclamationCircle",opacity:.75},stopped:{name:"circle",opacity:.5}},Ku=({isWaitingForUser:e})=>/* @__PURE__ */v(oc,{align:"center",gap:"sm",paddingY:"2xs",children:[/* @__PURE__ */b(Hu,{size:"sm"}),/* @__PURE__ */b(hc,{as:"span",size:"xs",weight:"normal",variant:"faint",children:e?"Waiting for you to complete the action":"Thinking"})]}),Xu=({message:e,isLastMessage:t,isTaskRunning:n})=>{const r="waiting-for-user"===e.placeholderState,o=n&&t&&("show"===e.mode||"do"===e.mode);return 0===e.parts.length?e.isPlaceholder||o?/* @__PURE__ */b(Ku,{isWaitingForUser:r}):/* @__PURE__ */b(rc,{}):/* @__PURE__ */v(ic,{gap:"sm",children:[e.parts.map((e,t)=>"text"===e.type?e.content?/* @__PURE__ */b(hc,{as:"div",size:"sm",weight:"medium",style:{wordBreak:"break-word",whiteSpace:"pre-wrap",marginBottom:"4px"},children:e.content},`part-${t}`):null:"progress"===e.type?/* @__PURE__ */b(oc,{align:"start",gap:"md",children:/* @__PURE__ */b(hc,{as:"span",size:"xs",weight:"medium",style:{flex:1,whiteSpace:"pre-wrap"},children:e.content})},`part-${t}`):null),(e.isPlaceholder&&!e.parts.some(e=>"text"===e.type)||o)&&/* @__PURE__ */b(Ku,{isWaitingForUser:r})]})},Gu=t.memo(({message:e,isLastMessage:t,isTaskRunning:n,onScreenAccessAllow:r,onScreenAccessDeny:o})=>{const i=El().widget_accent_color;if(e.isSystemMessage)/* @__PURE__ */return b(oc,{justify:"center",align:"center",children:/* @__PURE__ */b(hc,{as:"span",variant:"faint",weight:"normal",style:{fontSize:"10px"},children:e.content})});const s="user"===e.sender,a=s?"show"===e.mode||"do"===e.mode?"mousePointerClick":void 0:e.isScreenAccessRequest||"waiting-for-user"===e.placeholderState?"checkCircle":void 0,c=!s&&e.taskStatus?Yu[e.taskStatus]:void 0;/* @__PURE__ */
44
+ return v(ic,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":s?"You said…":"Assistant says…",animate:t?"fadeIn":void 0,children:[/* @__PURE__ */v(oc,{align:"start",gap:"sm",width:"full",children:[
45
+ /* @__PURE__ */b(oc,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!s&&/* @__PURE__ */b(Xa,{src:"data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20id='Layer_1'%20xmlns='http://www.w3.org/2000/svg'%20version='1.1'%20viewBox='0%200%20361%20360'%3e%3cdefs%3e%3cstyle%3e%20.st0%20{%20display:%20none;%20fill:%20none;%20stroke:%20%23cdc9c2;%20stroke-width:%201.3px;%20}%20.st1%20{%20fill:%20%23fff;%20}%20.st2,%20.st3%20{%20fill:%20%237cffa6;%20}%20.st3%20{%20stroke:%20%237cffa6;%20stroke-width:%20.38px;%20}%20.st4%20{%20fill:%20%23101828;%20}%20%3c/style%3e%3c/defs%3e%3crect%20class='st4'%20x='.5'%20width='360'%20height='360'/%3e%3cpath%20class='st2'%20d='M83.37,209.58c15.35,0,27.8-12.45,27.8-27.8s-12.44-27.79-27.8-27.79-27.8,12.44-27.8,27.79,12.44,27.8,27.8,27.8Z'/%3e%3cpath%20class='st1'%20d='M85.86,68.28l152.45,223.44h67.29l-70.62-113.77,68.13-109.67h-67.29l-41.12,65.31-41.54-65.31h-67.29Z'/%3e%3cpath%20class='st3'%20d='M176.61,249.83l-35.08-51-57.82,92.71h66.85l26.05-41.7Z'/%3e%3crect%20class='st0'%20x='1.25'%20y='.65'%20width='358.7'%20height='358.7'%20rx='43.35'%20ry='43.35'/%3e%3c/svg%3e",alt:"Marketrix AI",size:20,fit:"cover",rounded:"lg",style:{border:"none",outline:"none",display:"block",backgroundColor:"transparent"}})}),
46
+ /* @__PURE__ */v(ic,{grow:!0,position:"relative",rounded:"lg",elevation:"card",style:{padding:e.videoStream?"0":"8px 10px",border:"1px solid transparent",backgroundColor:s?"var(--primary)":void 0,color:s?"var(--primary-foreground)":"var(--foreground)"},children:[e.videoStream&&/* @__PURE__ */b(Vu,{stream:e.videoStream}),!e.videoStream&&(a?/* @__PURE__ */v(oc,{align:"start",gap:"sm",children:[/* @__PURE__ */b(oc,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */b(cc,{name:a,size:13})}),/* @__PURE__ */b(ic,{grow:!0,children:/* @__PURE__ */b(Xu,{message:e,isLastMessage:t,isTaskRunning:n})})]}):/* @__PURE__ */b(Xu,{message:e,isLastMessage:t,isTaskRunning:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */v(oc,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */b(Za,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */b(Za,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */b(hc,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"No"}),c&&/* @__PURE__ */b(oc,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */b(cc,{name:c.name,size:14,style:{color:xl(i,c.opacity),flexShrink:0}})})]}),
47
+ /* @__PURE__ */b(oc,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */b(hc,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:(l=e.timestamp,(l??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}))})]});var l}),Ju={boxShadow:La.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},Zu=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=El(),{state:o,actions:i}=Il(),{messages:s,isTaskRunning:c}=o,{isPreviewMode:l}=r,[h,f]=p(!1),[m,g]=p(!1),y=d(null),w=u(()=>Yc(r.widget_body),[r.widget_body]),x=u(()=>[w,...s],[w,s]),S=()=>{if(y.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=y.current;f(e>200);const r=Math.abs(t-e-n)<50;g(!r&&t>n)}};a(()=>{window.requestAnimationFrame(()=>{e.current&&(!l&&e.current.scrollIntoView({behavior:"auto"}),!l&&S())})},[s.length,l,e]);const k=s[s.length-1]?.content?.length??0;return a(()=>{const t=y.current;t&&!l&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[k,l,e]),/* @__PURE__ */v(rc,{position:"relative",height:"full",children:[/* @__PURE__ */v(rc,{ref:y,onScroll:S,role:"log","aria-relevant":"additions",height:"full",overflowY:"auto",paddingX:"lg",paddingY:"sm",style:{backgroundColor:r.widget_background_color.includes("gradient")?"transparent":r.widget_background_color,backgroundImage:Sl(r.widget_background_color),scrollbarColor:`${xl(r.widget_border_color,.3)} ${xl(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[x.map((e,r)=>/* @__PURE__ */b(Gu,{message:e,isLastMessage:r===x.length-1,isTaskRunning:c,onScreenAccessAllow:t,onScreenAccessDeny:n},e.id)),s.length>0&&/* @__PURE__ */b(oc,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */b(Za,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */b(hc,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
48
+ /* @__PURE__ */b(rc,{ref:e},"scroll-anchor")]},"message-list-container"),[{show:h,edge:{top:"8px"},label:"Scroll to top",icon:"arrowUp",onClick:()=>y.current?.scrollTo({top:0,behavior:"smooth"})},{show:m,edge:{bottom:"8px"},label:"Scroll to bottom",icon:"arrowDown",onClick:()=>!l&&e.current?.scrollIntoView({behavior:"smooth"})}].map(({show:e,edge:t,label:n,icon:o,onClick:i})=>e&&/* @__PURE__ */b(oc,{position:"absolute",justify:"center",style:{...t,left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */b(lc,{variant:"secondary",size:"sm",label:n,onClick:i,style:Ju,children:/* @__PURE__ */b(cc,{name:o,size:10,style:{color:r.widget_accent_color}})})},n))]})},Qu=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}];function ed(e){const t=d(e);return t.current=e,t}var td=({onScreenSharingChange:e,toggleScreenShareRef:t,messageInputRef:n})=>{const r=El(),{state:o,actions:s}=Il(),{currentMode:l,isTaskRunning:u,isAwaitingReply:h}=o,[f,m]=p(""),g=d(null),{isScreenSharing:y,isAwaitingScreenAccess:w,showScreenAccessDialog:x,handleScreenAccessDialogAllow:S,handleScreenAccessDialogDismiss:k,handleScreenAccessRequestAllow:C,handleScreenAccessRequestDeny:E,requestScreenAccess:I}=function({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:n,onUpdateMessage:r,onRemoveMessage:o,onSendMessage:s,messages:l}){const[u,d]=p(!1),[h,f]=p(null),[m,g]=p(!1),y=ed(u),b=ed(h),v=ed(e),w=t=>{d(t),e?.(t)},x=e=>{e&&o?.(e),n(Kc("Screen sharing stopped","stopped-sharing")),f(null)},S=ed(x);a(()=>{const e=()=>{const e=null!==gr(),t=y.current,n=b.current;e!==t&&(y.current=e,d(e),v.current?.(e)),t&&!e&&n&&S.current(n)};e();const t=setInterval(e,1e3);return()=>clearInterval(t)},[S,v,b,y]);const k=l[Bc(l,e=>!!e.isScreenAccessRequest&&!e.screenShareStatus)]??null,C=()=>{k?.pendingContent&&s(k.pendingContent,k.mode,!0)},E=e=>{k&&r(k.id,{screenShareStatus:e})},I=async()=>{try{const e=await async function(){if(!1===$e.getContext().config?.use_screenshare)throw new Error("Screen sharing is disabled for this widget");const e=gr();if(e)return e;const t=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!t||0===t.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return mr=t,t.getVideoTracks()[0]?.addEventListener("ended",()=>{mr=null}),t}();w(!0),E("allowed"),n(Kc("Screen sharing started","started-screenshare"));const t=((e,t="show")=>qc("screenshare","user","",{mode:t,videoStream:e}))(e,"show");f(t.id),n(t)}catch(e){console.error("Failed to start screen sharing:",e),w(!1),E("denied")}C()},M=ed(I),T=i(()=>M.current(),[M]),R=ed(()=>{E("denied"),C()}),O=i(()=>R.current(),[R]);return c(t,()=>()=>{u?(yr(),w(!1),x(h)):g(!0)}),{isScreenSharing:u,isAwaitingScreenAccess:null!==k,showScreenAccessDialog:m,handleScreenAccessDialogAllow:async()=>{g(!1),await I()},handleScreenAccessDialogDismiss:()=>{g(!1)},handleScreenAccessRequestAllow:T,handleScreenAccessRequestDeny:O,requestScreenAccess:(e,t)=>{k||n(((e,t)=>qc("screen-access-request","agent","Can I take a look at your screen?",{mode:e,isScreenAccessRequest:!0,pendingContent:t}))(e,t))}}}({onScreenSharingChange:e,toggleScreenShareRef:t,onAddMessage:s.addMessage,onUpdateMessage:s.updateMessage,onRemoveMessage:s.removeMessage,onSendMessage:s.messageDispatch,messages:o.messages}),M=w||h;/* @__PURE__ */
49
+ return v(ic,{height:"full",children:[x&&/* @__PURE__ */b(Wu,{open:x,onClose:k,title:"Can I take a look at your screen?",description:"By allowing screen access, Marketrix can understand your current context to guide you better and complete tasks on your behalf.",onConfirm:S,confirmLabel:"Yes",cancelLabel:"No",finalFocusRef:n}),
50
+ /* @__PURE__ */b(ic,{grow:!0,overflow:"hidden",paddingY:"2xs",minHeight:"0",children:/* @__PURE__ */b(Dl,{label:"Chat",fallback:/* @__PURE__ */b(hc,{as:"div",size:"xs",align:"center",variant:"muted",style:{padding:"16px"},children:"Something went wrong displaying messages. Please refresh."}),children:/* @__PURE__ */b(Zu,{messagesEndRef:g,onScreenAccessAllow:C,onScreenAccessDeny:E})})}),
51
+ /* @__PURE__ */b(rc,{variant:"floatingCard",style:{marginTop:"auto"},children:/* @__PURE__ */b(bu,{ref:n,value:f,onChange:m,onSubmit:()=>{if(!f.trim()||M)return;const e=f.trim();m(""),s.addMessage(Vc(e,l)),!1===r.use_screenshare||"show"!==l&&"do"!==l||y?s.messageDispatch(e,l,!0):I(l,e)},modes:Qu.filter(({flag:e})=>r[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:$c(e)})),activeMode:l,onModeChange:e=>{e!==l&&(s.addMessage(Kc(`Switched to ${$c(e)} mode`,"mode-change")),s.setMode(e))},disabled:M,taskRunning:u,onStop:()=>{Ac.cleanup(),s.stopTask()}})})]})},nd=[{id:"show-add-product",text:"Show me how to add a new product",type:"show"},{id:"show-login",text:"Show me how to login",type:"show"},{id:"do-login",text:"Do the login process for me",type:"do"},{id:"show-revenue",text:"Show me the revenue metrics",type:"show"},{id:"tell-conversion-rate",text:"What does my conversion rate mean and how can I improve it?",type:"tell"}],rd=({onNavigateToChat:e,onChipClick:t})=>{const n=El(),{messages:r}=Il().state,o=function(e){const t=e.widget_chips;return t?.length?t.map((e,t)=>({id:`chip-${e.chip_text.replace(/\s+/g,"-").toLowerCase()}-${t}`,text:"show"===e.chip_mode?`Show me ${e.chip_text.replace(/^Show me\s+/i,"")}`:"do"===e.chip_mode?`Do ${e.chip_text.replace(/^Do\s+/i,"")}`:e.chip_text,type:e.chip_mode})):nd}(n);/* @__PURE__ */
52
+ return v(ic,{height:"full",overflow:"hidden",children:[/* @__PURE__ */v(ic,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */v(rc,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */b(hc,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */b(hc,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */v(ic,{gap:"sm",children:[/* @__PURE__ */v(Za,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */b(cc,{name:"chat",size:16}),"Ask a question"]}),o.map(r=>/* @__PURE__ */b(Za,{elevation:"card",size:"sm",variant:"chip",full:!0,onClick:n=>(async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)})(r,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */b(hc,{as:"span",weight:"normal",leading:"tight",children:r.text})},r.id))]})]}),r.length>0&&/* @__PURE__ */v(rc,{variant:"floatingCard",children:[
53
53
  /* @__PURE__ */b(hc,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
54
54
  /* @__PURE__ */b(hc,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1]?.content||"Message"}),
55
55
  /* @__PURE__ */b(hc,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})},od=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],id=()=>/* @__PURE__ */b(fu,{render:/* @__PURE__ */b(oc,{align:"center",justify:"around",shrink:!1,border:"top"}),style:{height:48},children:od.map(e=>/* @__PURE__ */v(Ql,{value:e.id,render:/* @__PURE__ */b(Za,{stacked:!0,variant:"tab"}),children:[
@@ -62,4 +62,4 @@ return v(ic,{ref:m,position:s?"absolute":"fixed",rounded:"lg",border:!0,overflow
62
62
  return b(Cl,{value:g,children:/* @__PURE__ */b(rc,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...w,...c&&{width:"100%",height:"100%"}},children:/* @__PURE__ */b(hl,{value:r,children:/* @__PURE__ */v(mc,{container:r,offsetBottom:"top"===Rl(u).vertical?20:90,children:[y&&/* @__PURE__ */b(rc,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${xl(g.widget_accent_color,.72)}, inset 0 0 46px 10px ${xl(g.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:2147483001}}),
63
63
  /* @__PURE__ */b(Dl,{label:"Widget",children:/* @__PURE__ */b(ld,{})}),
64
64
  /* @__PURE__ */b(Nl,{onPositionCommit:e=>{d(e),c||Ne(h,e)}}),
65
- /* @__PURE__ */b(gc,{error:i.error,onClearError:()=>s.setError(void 0),...hr.canReconnect()&&{onRetry:()=>{s.setError(void 0),hr.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},dd={mount:null},pd=null,hd=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s;--radius-pill:9999px;--status-processing-rgb:49, 208, 109;--status-error-rgb:208, 52, 44;--overlay-dark:#111827}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}:where([data-marketrix-widget]) :where(h1,h2,h3){font-size:inherit;font-weight:inherit}:where([data-marketrix-widget]) :where(img,svg,video,canvas){vertical-align:middle;display:block}:where([data-marketrix-widget]) :where(img,video){max-width:100%;height:auto}:where([data-marketrix-widget]) :where(button,input,textarea){font:inherit;color:inherit;background:0 0;border-radius:0}:where([data-marketrix-widget]) :where(button){appearance:button}:where([data-marketrix-widget]) :where(textarea){resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button,.mtx-icon-button{cursor:pointer;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-button{border:1px solid #0000;gap:8px;font-weight:500}.mtx-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][aria-selected=true]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-icon-button{border-radius:var(--radius-pill);border:none;flex-shrink:0}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-button[data-disabled=true],.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-radius:var(--radius-pill);border-style:solid;border-color:#0000 currentColor currentColor;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{border-radius:var(--radius-pill);cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;transition-property:transform,opacity;transition-duration:.16s,80ms;transition-timing-function:linear;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;border-radius:var(--radius-pill);background:var(--overlay-dark);text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;border:1px solid #ffffff40;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{border-radius:var(--radius-pill);background:var(--primary);opacity:0;height:2px;position:absolute;top:0;left:25%;right:25%}[aria-selected=true]>.mtx-tab-underline{opacity:1}.mtx-live-dot{width:6px;height:6px;display:inline-flex;position:relative}.mtx-live-dot-ping{border-radius:var(--radius-pill);opacity:.75;background:currentColor;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-live-dot-core{border-radius:var(--radius-pill);background:currentColor;width:6px;height:6px;display:inline-flex;position:relative}.mtx-fab-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.mtx-fab-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.mtx-fab-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite mtx-fab-ring-travel}.mtx-fab-ring[data-tone=processing] rect{stroke:rgb(var(--status-processing-rgb));filter:drop-shadow(0 0 3px rgba(var(--status-processing-rgb), .7))}.mtx-fab-ring[data-tone=error] rect{stroke:rgb(var(--status-error-rgb));filter:drop-shadow(0 0 3px rgba(var(--status-error-rgb), .7))}.mtx-fab-glow[data-tone=processing]{animation:2s ease-in-out infinite mtx-fab-glow-processing}.mtx-fab-glow[data-tone=error]{animation:1.5s ease-in-out infinite mtx-fab-glow-error}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite mtx-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both mtx-view-slide-forward}[data-view-transition][data-direction=back]{animation:.3s both mtx-view-slide-back}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-pulse{50%{opacity:.5}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes mtx-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes mtx-fab-ring-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes mtx-fab-glow-processing{0%,to{opacity:.72;background:radial-gradient(circle, rgba(var(--status-processing-rgb), 0) 38%, rgba(var(--status-processing-rgb), .38) 58%, rgba(var(--status-processing-rgb), .24) 68%, transparent 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:1;background:radial-gradient(circle, rgba(var(--status-processing-rgb), 0) 34%, rgba(var(--status-processing-rgb), .55) 56%, rgba(var(--status-processing-rgb), .33) 68%, transparent 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes mtx-fab-glow-error{0%,to{opacity:.65;background:radial-gradient(circle, rgba(var(--status-error-rgb), 0) 38%, rgba(var(--status-error-rgb), .34) 58%, rgba(var(--status-error-rgb), .22) 68%, transparent 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:.95;background:radial-gradient(circle, rgba(var(--status-error-rgb), 0) 34%, rgba(var(--status-error-rgb), .5) 56%, rgba(var(--status-error-rgb), .3) 68%, transparent 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes mtx-view-slide-forward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes mtx-view-slide-back{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},fd=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=hd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},md=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(gl,{previewMode:r,children:/* @__PURE__ */b(ud,{config:n})})})),o},gd=()=>null!==dd.mount,yd=()=>dd.mount?.config??null,bd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;vd();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=hd(r,"marketrix-widget-notice-root");(pd=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(mc,{container:o,children:/* @__PURE__ */b(gc,{error:"error"===n?e:void 0,onClearError:vd,greeting:"error"===n?void 0:e,onGreetingDismiss:vd})})}))},vd=()=>{pd?.unmount(),pd=null,document.getElementById("marketrix-widget-notice-container")?.remove()},wd=null,xd=0,Sd=null;function kd(e,t={}){const n=Cr(e);return n.invalidFields?(console.error(`Marketrix Widget: ${Er(n.invalidFields)}`),null):{...Ir(n.settings,t),isPreviewMode:!0}}function Cd(e,t,n=!1){const{container:r,mountEl:o}=fd(t),i=md(o,e,n);dd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var Ed=(e,t)=>{if(wd)return wd;if(window.__mtx?.state)return Promise.resolve();if(gd())return console.warn("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},bd("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Ie&&(Ie=e,Me=Ee(e))})(e.mtxApiHost??""),r=await async function(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");let r;try{({items:r}=await Te.widgetPublicSearch({marketrix_id:t,marketrix_key:n}))}catch(s){const t=Re(s);throw function(e,t){return Object.assign(new Error(e),{cause:t})}(["Failed to fetch","ERR_CONNECTION_REFUSED","NetworkError","Network request failed"].some(e=>t.includes(e))?`Cannot connect to API server. Please ensure the API server is running at ${e.mtxApiHost||"configured API server"}. Error: ${t}`:`Widget validation failed: ${t}`,s)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");const i=Cr(o.settings);if(i.invalidFields)throw new Error(Er(i.invalidFields));return{...Ir(i.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id,isPreviewMode:!1}}(e)}catch(o){if(n!==xd)return;return console.error("Marketrix Widget initialization failed:",o),bd(Re(o,"Failed to initialize widget"),"error"),void(window.__mtx=void 0)}n===xd&&(vd(),r.widget_enabled?($e.setConfig(r),Cd(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await Be.getOrCreateChatId();if(n!==xd)return;const t=new fr(e,r.mtxApp);Sd=t,await t.start(),n!==xd&&(t.stop(),Sd===t&&(Sd=null))}catch(o){n===xd&&console.error("Failed to start session recording:",o)}})()):window.__mtx=void 0)}(e,t,++xd);return wd=n,n.then(()=>{wd===n&&(wd=null)},()=>{wd===n&&(wd=null)}),n},Id=()=>{xd++,hr.disconnect(),Sd?.stop(),Sd=null,yr();const e=dd.mount;dd.mount=null,e&&(e.instance.unmount(),e.container.remove()),wd=null,window.__mtx=void 0,vd()},Md=async e=>{const t=dd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};Id(),o?Cd(i,r,!0):await Ed(i,r)},Td=({settings:e,container:t})=>{const n=d(null),r=d(null),o=d(null);return a(()=>{const i=t??n.current??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidgetPreview: Invalid container");var s;const a=kd(e);if(!a)return;const{container:c,mountEl:l}=fd(i);return o.current=c,r.current=md(l,a,!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */b("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},Rd=async e=>{const t=e.container;if(void 0!==e.settings){const{settings:n,container:r,...o}=e,i=kd(e.settings,o);if(!i)return;Id(),Cd(i,t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await Ed(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{(e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if(gd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void bd("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))})(Ed)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var Od={MarketrixWidgetPreview:Td,mountWidget:Rd,initWidget:Ed,unmountWidget:Id,updateMarketrixConfig:Md,getCurrentConfig:yd};export{Td as MarketrixWidgetPreview,Od as default,yd as getCurrentConfig,Ed as initWidget,Rd as mountWidget,Id as unmountWidget,Md as updateMarketrixConfig};
65
+ /* @__PURE__ */b(gc,{error:i.error,onClearError:()=>s.setError(void 0),...hr.canReconnect()&&{onRetry:()=>{s.setError(void 0),hr.reconnectNow()}},greeting:t&&!i.error?e.widget_greeting:void 0,greetingBody:e.widget_body,onGreetingDismiss:()=>n(!1)})]})})})})},dd={mount:null},pd=null,hd=(e,t)=>{const n=e.attachShadow({mode:"closed"}),r=document.createElement("style");r.textContent=':root,:host{--foreground:oklch(14.5% 0 0);--card:oklch(100% 0 0);--card-foreground:oklch(14.5% 0 0);--primary:oklch(20.5% 0 0);--primary-foreground:oklch(98.5% 0 0);--secondary:oklch(97% 0 0);--secondary-foreground:oklch(20.5% 0 0);--border:oklch(92.2% 0 0);--ring:oklch(70.8% 0 0);--foreground-muted:#1f293799;--foreground-faint:#1f293766;--primary-hover:#3b82f6d9;--secondary-bg:#6b728033;--secondary-hover:#6b72804d;--font-sans:"Inter", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--radius:.625rem;--shadow-sm:0 1px 3px 0px #0000001a, 0 1px 2px -1px #0000001a;--shadow-lg:0 1px 3px 0px #0000001a, 0 4px 6px -1px #0000001a;--duration-animation:.3s;--duration-fade:.2s;--radius-pill:9999px;--status-processing-rgb:49, 208, 109;--status-error-rgb:208, 52, 44;--overlay-dark:#111827}*,:before,:after{box-sizing:border-box;border:0 solid var(--border);margin:0;padding:0}:host,[data-marketrix-widget]{font-family:var(--font-sans);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;line-height:1.5}:where([data-marketrix-widget]) :where(h1,h2,h3){font-size:inherit;font-weight:inherit}:where([data-marketrix-widget]) :where(img,svg,video,canvas){vertical-align:middle;display:block}:where([data-marketrix-widget]) :where(img,video){max-width:100%;height:auto}:where([data-marketrix-widget]) :where(button,input,textarea){font:inherit;color:inherit;background:0 0;border-radius:0}:where([data-marketrix-widget]) :where(button){appearance:button}:where([data-marketrix-widget]) :where(textarea){resize:vertical}[data-marketrix-widget] [hidden]{display:none!important}[data-marketrix-widget],[data-marketrix-widget] *{pointer-events:auto;transition:color .2s ease-in-out,background-color .2s ease-in-out,border-color .2s ease-in-out,opacity .2s ease-in-out,box-shadow .2s ease-in-out,transform .2s ease-in-out}[data-resizing=true],[data-resizing=true] *{transition:none!important}@media (prefers-reduced-motion:reduce){[data-marketrix-widget]{--duration-animation:0s!important;--duration-fade:0s!important}}.mtx-button,.mtx-icon-button{cursor:pointer;justify-content:center;align-items:center;transition:all .2s ease-in-out;display:inline-flex}.mtx-button{border:1px solid #0000;gap:8px;font-weight:500}.mtx-button:focus-visible{outline:2px solid var(--ring);outline-offset:2px}.mtx-button[data-size=sm]{min-height:28px;padding:4px 8px;font-size:.75rem}.mtx-button[data-size=md]{min-height:36px;padding:8px 16px;font-size:.875rem}.mtx-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-button[data-variant=primary]:hover{background:color-mix(in oklab, var(--primary) 90%, transparent)}.mtx-button[data-variant=secondary]{background:var(--secondary);color:var(--secondary-foreground)}.mtx-button[data-variant=secondary]:hover{background:color-mix(in oklab, var(--secondary) 80%, transparent)}.mtx-button[data-variant=ghost]{color:var(--foreground);border-color:var(--border);background:0 0}.mtx-button[data-variant=ghost]:hover{background:var(--border)}.mtx-button[data-variant=chip]{background:var(--secondary-bg);color:var(--foreground)}.mtx-button[data-variant=chip]:hover{background:var(--primary);color:var(--primary-foreground);border-color:var(--primary)}.mtx-button[data-variant=bare],.mtx-button[data-variant=tab]{background:0 0;border-color:#0000;min-height:0;padding:0}.mtx-button[data-variant=bare]{color:inherit}.mtx-button[data-variant=tab]{color:var(--foreground-muted);flex:1;min-width:0;height:100%;position:relative}.mtx-button[data-variant=tab]:hover{color:var(--foreground)}.mtx-button[data-variant=tab][aria-selected=true]{color:var(--primary);font-weight:600}.mtx-button[data-stacked=true]{flex-direction:column;gap:2px}.mtx-button[data-full=true]{width:100%}.mtx-icon-button{border-radius:var(--radius-pill);border:none;flex-shrink:0}.mtx-icon-button[data-size=xs]{width:20px;min-width:20px;height:20px}.mtx-icon-button[data-size=sm]{width:28px;min-width:28px;height:28px}.mtx-icon-button[data-variant=primary]{background:var(--primary);color:var(--primary-foreground)}.mtx-icon-button[data-variant=primary]:hover{background:var(--primary-hover)}.mtx-icon-button[data-variant=secondary]{background:var(--secondary-bg);color:var(--foreground)}.mtx-icon-button[data-variant=secondary]:hover{background:var(--secondary-hover)}.mtx-icon-button[data-variant=ghost]{color:var(--foreground);opacity:.6;background:0 0}.mtx-icon-button[data-variant=ghost]:hover{opacity:1}.mtx-button[data-disabled=true],.mtx-icon-button[data-disabled=true]{opacity:.5;cursor:not-allowed;pointer-events:none}.mtx-icon{flex-shrink:0;display:inline-block}.mtx-avatar{flex-shrink:0}.mtx-spinner-ring{border-radius:var(--radius-pill);border-style:solid;border-color:#0000 currentColor currentColor;flex-shrink:0;animation:1s linear infinite mtx-spin}.mtx-visually-hidden{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.mtx-composer:focus-within{border-color:var(--foreground-faint)}.mtx-composer-input{resize:none;width:100%;min-height:0;color:var(--foreground);background:0 0;border:none;padding-left:12px;padding-right:12px;font-size:.875rem;display:block}.mtx-composer-input::placeholder{color:var(--foreground-faint)}.mtx-composer-input:focus{outline:none}.mtx-composer-input:disabled{cursor:not-allowed;opacity:.5}.mtx-mode-chip{border-radius:var(--radius-pill);cursor:pointer;background:var(--secondary-bg);color:var(--foreground-muted);border:none;align-items:center;gap:2px;padding:2px 8px;font-size:11px;font-weight:500;transition:all .2s ease-in-out;display:inline-flex}.mtx-mode-chip[data-active=true]{background:var(--primary);color:var(--primary-foreground);box-shadow:var(--shadow-sm)}.mtx-toast-viewport{flex-direction:column;gap:8px;max-width:420px;display:flex;position:fixed;left:50%;transform:translate(-50%)}.mtx-toast{animation:mtx-fade-in var(--duration-animation) ease-out}.mtx-toast[data-ending-style]{opacity:0;transition:opacity var(--duration-animation) ease-out}.mtx-dialog-backdrop{animation:mtx-dialog-overlay-in var(--duration-fade) ease-out;background:#0003;position:fixed;inset:0}.mtx-dialog-popup{border-radius:var(--radius);background:var(--card);width:100%;max-width:24rem;max-height:85vh;animation:mtx-dialog-content-in var(--duration-animation) ease-out;flex-direction:column;padding:16px;display:flex;position:fixed;top:50%;left:50%;overflow:auto;transform:translate(-50%,-50%)}.mtx-dialog-title{color:var(--foreground);margin-bottom:4px;font-size:1rem;font-weight:600}.mtx-dialog-description{color:var(--foreground-muted);margin-bottom:16px;font-size:.875rem;line-height:1.625}.mtx-fab-anchor{position:fixed}.mtx-fab-anchor[data-preview=true]{position:absolute}.mtx-fab-anchor[data-animated=true]{transition:transform var(--duration-animation) ease-in-out}.mtx-fab{width:56px;height:56px;transition:all var(--duration-animation) ease-in-out;position:relative;overflow:visible}.mtx-fab[data-open=false]:hover{transform:scale(1.1)}.mtx-fab[data-open=true]{opacity:0;pointer-events:none;transform:scale(0)}.mtx-fab-trigger{z-index:10;width:56px;min-width:56px;height:56px;position:relative}.mtx-fab-center{justify-content:center;align-items:center;width:100%;height:100%;position:relative}.mtx-fab-badge{width:48px;height:48px;transition:transform .167s cubic-bezier(.33,0,0,1),opacity .167s cubic-bezier(.33,0,0,1),background-color .167s cubic-bezier(.33,0,0,1);animation:.25s ease-out forwards mtx-launcher-entrance;position:relative;overflow:hidden}.mtx-fab-badge:hover{transition-duration:.25s;transform:scale(1.1)}.mtx-fab-badge:active{transition-duration:.134s;transition-timing-function:cubic-bezier(.45,0,.2,1);transform:scale(.85)}.mtx-fab-icon-layer{justify-content:center;align-items:center;transition-property:transform,opacity;transition-duration:.16s,80ms;transition-timing-function:linear;position:absolute;inset:0}.mtx-fab-avatar{z-index:10;object-fit:contain;width:100%;height:100%;position:relative}.mtx-fab-chevron{z-index:10;color:var(--foreground);pointer-events:none;position:relative}.mtx-fab-stop{z-index:20;border-radius:var(--radius-pill);background:var(--overlay-dark);text-transform:uppercase;letter-spacing:.025em;color:#fff;box-shadow:var(--shadow-lg);opacity:0;pointer-events:none;border:1px solid #ffffff40;padding:4px 10px;font-size:11px;font-weight:600;transition:opacity .15s ease-in-out;position:absolute;top:50%;transform:translateY(-50%)}.mtx-fab-stop[data-side=left]{margin-left:8px;left:100%}.mtx-fab-stop[data-side=right]{margin-right:8px;right:100%}.mtx-fab:hover .mtx-fab-stop,.mtx-fab:focus-within .mtx-fab-stop{opacity:1;pointer-events:auto}.mtx-tab-underline{border-radius:var(--radius-pill);background:var(--primary);opacity:0;height:2px;position:absolute;top:0;left:25%;right:25%}[aria-selected=true]>.mtx-tab-underline{opacity:1}.mtx-live-dot{width:6px;height:6px;display:inline-flex;position:relative}.mtx-live-dot-ping{border-radius:var(--radius-pill);opacity:.75;background:currentColor;width:100%;height:100%;animation:1s cubic-bezier(0,0,.2,1) infinite mtx-ping;display:inline-flex;position:absolute}.mtx-live-dot-core{border-radius:var(--radius-pill);background:currentColor;width:6px;height:6px;display:inline-flex;position:relative}.mtx-fab-glow{pointer-events:none;filter:blur(14px);will-change:transform, opacity;border-radius:50%;width:140%;height:140%;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}.mtx-fab-ring{pointer-events:none;z-index:0;position:absolute;inset:-3px;overflow:visible}.mtx-fab-ring rect{fill:none;stroke-width:2.5px;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:40 120;animation:1.9s cubic-bezier(.4,0,.2,1) infinite mtx-fab-ring-travel}.mtx-fab-ring[data-tone=processing] rect{stroke:rgb(var(--status-processing-rgb));filter:drop-shadow(0 0 3px rgba(var(--status-processing-rgb), .7))}.mtx-fab-ring[data-tone=error] rect{stroke:rgb(var(--status-error-rgb));filter:drop-shadow(0 0 3px rgba(var(--status-error-rgb), .7))}.mtx-fab-glow[data-tone=processing]{animation:2s ease-in-out infinite mtx-fab-glow-processing}.mtx-fab-glow[data-tone=error]{animation:1.5s ease-in-out infinite mtx-fab-glow-error}[data-screen-edge-glow]{animation:1.6s ease-in-out infinite mtx-screen-edge-pulse}[data-view-transition][data-direction=forward]{animation:.3s both mtx-view-slide-forward}[data-view-transition][data-direction=back]{animation:.3s both mtx-view-slide-back}@keyframes mtx-spin{to{transform:rotate(360deg)}}@keyframes mtx-ping{75%,to{opacity:0;transform:scale(2)}}@keyframes mtx-pulse{50%{opacity:.5}}@keyframes mtx-dialog-overlay-in{0%{opacity:0}to{opacity:1}}@keyframes mtx-dialog-content-in{0%{opacity:0;scale:.96}to{opacity:1;scale:1}}@keyframes mtx-fade-in{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes mtx-launcher-entrance{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes mtx-screen-edge-pulse{0%,to{opacity:.55}50%{opacity:1}}@keyframes mtx-fab-ring-travel{0%{stroke-dashoffset:0;opacity:.5}18%{stroke-dashoffset:-112px;opacity:1}35%{stroke-dashoffset:-160px;opacity:.65}60%{stroke-dashoffset:-160px;opacity:.45}82%{stroke-dashoffset:-272px;opacity:1}to{stroke-dashoffset:-320px;opacity:.6}}@keyframes mtx-fab-glow-processing{0%,to{opacity:.72;background:radial-gradient(circle, rgba(var(--status-processing-rgb), 0) 38%, rgba(var(--status-processing-rgb), .38) 58%, rgba(var(--status-processing-rgb), .24) 68%, transparent 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:1;background:radial-gradient(circle, rgba(var(--status-processing-rgb), 0) 34%, rgba(var(--status-processing-rgb), .55) 56%, rgba(var(--status-processing-rgb), .33) 68%, transparent 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes mtx-fab-glow-error{0%,to{opacity:.65;background:radial-gradient(circle, rgba(var(--status-error-rgb), 0) 38%, rgba(var(--status-error-rgb), .34) 58%, rgba(var(--status-error-rgb), .22) 68%, transparent 78%);transform:translate(-50%,-50%)scale(1)}50%{opacity:.95;background:radial-gradient(circle, rgba(var(--status-error-rgb), 0) 34%, rgba(var(--status-error-rgb), .5) 56%, rgba(var(--status-error-rgb), .3) 68%, transparent 80%);transform:translate(-50%,-50%)scale(1.1)}}@keyframes mtx-view-slide-forward{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes mtx-view-slide-back{0%{opacity:0;transform:translate(-20px)}to{opacity:1;transform:translate(0)}}',n.appendChild(r);const o=document.createElement("div");return o.id=t,n.appendChild(o),{shadowRoot:n,mountEl:o}},fd=e=>{const t=e??document.body,n=document.createElement("div");n.className="marketrix-widget-container",n.style.pointerEvents="auto",e&&Object.assign(n.style,{width:"100%",height:"100%",position:"relative",overflow:"visible"}),t.appendChild(n);const{shadowRoot:r,mountEl:o}=hd(n,"marketrix-widget-root");return Object.assign(o.style,{pointerEvents:"auto",width:"100%",height:"100%",position:"relative"}),{container:n,shadowRoot:r,mountEl:o}},md=(e,n,r=!1)=>{const o=m(e);return o.render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(gl,{previewMode:r,children:/* @__PURE__ */b(ud,{config:n})})})),o},gd=()=>null!==dd.mount,yd=()=>dd.mount?.config??null,bd=(e,n="neutral")=>{if("undefined"==typeof window||"undefined"==typeof document)return;vd();const r=document.createElement("div");r.id="marketrix-widget-notice-container",r.className="marketrix-widget-notice-container",document.body.appendChild(r);const{mountEl:o}=hd(r,"marketrix-widget-notice-root");(pd=m(o)).render(/* @__PURE__ */b(t.StrictMode,{children:/* @__PURE__ */b(mc,{container:o,children:/* @__PURE__ */b(gc,{error:"error"===n?e:void 0,onClearError:vd,greeting:"error"===n?void 0:e,onGreetingDismiss:vd})})}))},vd=()=>{pd?.unmount(),pd=null,document.getElementById("marketrix-widget-notice-container")?.remove()},wd=null,xd=0,Sd=null;function kd(e,t={}){const n=Cr(e);return n.invalidFields?(console.error(`Marketrix Widget: ${Er(n.invalidFields)}`),null):{...Ir(n.settings,t),isPreviewMode:!0}}function Cd(e,t,n=!1){const{container:r,mountEl:o}=fd(t),i=md(o,e,n);dd.mount={instance:i,config:e,container:r,host:t,previewMode:n}}var Ed=(e,t)=>{if(wd)return wd;if(window.__mtx?.state)return Promise.resolve();if(gd())return Oe("Marketrix Widget: already initialized"),Promise.resolve();const n=async function(e,t,n){let r;window.__mtx={state:"initializing"},bd("Loading widget settings...");try{(e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Ie&&(Ie=e,Me=Ee(e))})(e.mtxApiHost??""),r=await async function(e){const{mtxId:t,mtxKey:n}=e;if(!t||!n)throw new Error("Please provide mtxId + mtxKey");let r;try{({items:r}=await Te.widgetPublicSearch({marketrix_id:t,marketrix_key:n}))}catch(s){const t=Re(s);throw function(e,t){return Object.assign(new Error(e),{cause:t})}(["Failed to fetch","ERR_CONNECTION_REFUSED","NetworkError","Network request failed"].some(e=>t.includes(e))?`Cannot connect to API server. Please ensure the API server is running at ${e.mtxApiHost||"configured API server"}. Error: ${t}`:`Widget validation failed: ${t}`,s)}if(!r.length)throw new Error("Widget not found or invalid credentials");const o=r.find(e=>"active"===e.status);if(!o){const e=r.map(e=>e.status).join(", ");throw new Error(`Found widget(s) but none are active. Current status(es): ${e}. Please activate the widget in the dashboard.`)}if(!o.application_id)throw new Error("Widget missing application_id");const i=Cr(o.settings);if(i.invalidFields)throw new Error(Er(i.invalidFields));return{...Ir(i.settings,e),mtxId:t,mtxKey:n,mtxApp:o.application_id,isPreviewMode:!1}}(e)}catch(o){if(n!==xd)return;return console.error("Marketrix Widget initialization failed:",o),bd(Re(o,"Failed to initialize widget"),"error"),void(window.__mtx=void 0)}n===xd&&(vd(),r.widget_enabled?($e.setConfig(r),Cd(r,t),window.__mtx={state:"active"},r.widget_recording&&r.mtxApp&&(async()=>{try{const e=await Be.getOrCreateChatId();if(n!==xd)return;const t=new fr(e,r.mtxApp);Sd=t,await t.start(),n!==xd&&(t.stop(),Sd===t&&(Sd=null))}catch(o){n===xd&&console.error("Failed to start session recording:",o)}})()):window.__mtx=void 0)}(e,t,++xd);return wd=n,n.then(()=>{wd===n&&(wd=null)},()=>{wd===n&&(wd=null)}),n},Id=()=>{xd++,hr.disconnect(),Sd?.stop(),Sd=null,yr();const e=dd.mount;dd.mount=null,e&&(e.instance.unmount(),e.container.remove()),wd=null,window.__mtx=void 0,vd()},Md=async e=>{const t=dd.mount;if(!t)return;const{config:n,host:r,previewMode:o}=t,i={...n,...e};Id(),o?Cd(i,r,!0):await Ed(i,r)},Td=({settings:e,container:t})=>{const n=d(null),r=d(null),o=d(null);return a(()=>{const i=t??n.current??document.body;if(!(i&&(s=i,s instanceof HTMLElement)))return void console.error("MarketrixWidgetPreview: Invalid container");var s;const a=kd(e);if(!a)return;const{container:c,mountEl:l}=fd(i);return o.current=c,r.current=md(l,a,!0),()=>{r.current&&(r.current.unmount(),r.current=null),o.current&&(o.current.remove(),o.current=null)}},[e,t]),t?null:/* @__PURE__ */b("div",{ref:n,style:{width:"100%",height:"100%",position:"relative"}})},Rd=async e=>{const t=e.container;if(void 0!==e.settings){const{settings:n,container:r,...o}=e,i=kd(e.settings,o);if(!i)return;Id(),Cd(i,t,!0)}else{if(void 0===e.mtxId||void 0===e.mtxKey)throw new Error("Invalid configuration: provide either settings (preview) or mtxId+mtxKey (production)");{const{container:n,...r}=e;await Ed(r,t)}}};"undefined"!=typeof window&&setTimeout(()=>{try{(e=>{if("undefined"==typeof window||"undefined"==typeof document)return;if(window.__mtx?.state)return;const t=document.querySelectorAll("script[mtx-id]"),n=t[t.length-1];if(!(n&&(r=n,r instanceof HTMLScriptElement)))return;var r;const o=n.getAttribute("mtx-id"),i=n.getAttribute("mtx-key"),s=n.getAttribute("mtx-api-host");if(!o||!i||!s){if(gd())return;return console.error("[AutoInit] Missing required attributes:",{hasMtxId:!!o,hasMtxKey:!!i,hasMtxApiHost:!!s}),void bd("Please configure mtx-id, mtx-key and mtx-api-host","error")}const a={mtxId:o,mtxKey:i,mtxApiHost:s};"false"===n.getAttribute("mtx-use-screenshare")&&(a.use_screenshare=!1),e(a).catch(e=>console.error("[AutoInit] Failed to initialize widget:",e))})(Ed)}catch(e){console.error("Marketrix Widget: Auto-init registration failed",e)}},0);var Od={MarketrixWidgetPreview:Td,mountWidget:Rd,initWidget:Ed,unmountWidget:Id,updateMarketrixConfig:Md,getCurrentConfig:yd};export{Td as MarketrixWidgetPreview,Od as default,yd as getCurrentConfig,Ed as initWidget,Rd as mountWidget,Id as unmountWidget,Md as updateMarketrixConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marketrix.ai/widget",
3
- "version": "4.0.115",
3
+ "version": "4.0.116",
4
4
  "type": "module",
5
5
  "packageManager": "bun@1.4.2",
6
6
  "sideEffects": false,