@marketrix.ai/widget 3.8.462 → 3.8.463

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.
@@ -26,6 +26,12 @@ type ProgressStatus = 'in_progress' | 'completed' | 'failed';
26
26
  export declare function reduceToolProgress(state: SseState, browserToolName: string, explanation: string, status: ProgressStatus, currentMode: InstructionType, error?: string): SseState;
27
27
  export declare function reduceToolDone(state: SseState, currentMode: InstructionType): SseState;
28
28
  export declare function reduceStop(state: SseState, currentMode: InstructionType): SseState;
29
+ declare const TASK_STATUS: {
30
+ readonly completed: "done";
31
+ readonly failed: "failed";
32
+ readonly stopped: "stopped";
33
+ };
34
+ export declare const isTerminalTaskStatus: (status: string) => status is keyof typeof TASK_STATUS;
29
35
  /** Settles a pending message into a plain error bubble — the one shape for both a failed POST and a chat/error. */
30
36
  export declare function reduceError(state: SseState, messageId: string, text: string): SseState;
31
37
  export declare function reduceSse(state: SseState, event: WidgetEvent, currentMode: InstructionType): ReduceResult;
package/dist/widget.mjs CHANGED
@@ -11,7 +11,7 @@ return g(Eu,{position:"fixed",animate:c?"none":"fadeIn",style:{zIndex:Gc,maxWidt
11
11
  /* @__PURE__ */g(yd,{src:jc,alt:"",size:28,rounded:"full"}),
12
12
  /* @__PURE__ */y(Ru,{grow:!0,minWidth:"0",children:[/* @__PURE__ */g(Du,{as:"span",block:!0,inheritColor:!0,weight:"medium",style:{fontSize:"13px",color:u.titleColor,whiteSpace:o?"normal":"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:t}),n&&/* @__PURE__ */g(Du,{as:"span",block:!0,inheritColor:!0,style:{fontSize:"12px",color:u.bodyColor,opacity:.8,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:n})]}),o&&/* @__PURE__ */g(vu,{type:"button",variant:"ghost",shape:"pill",size:"sm",onClick:()=>{o(),d()},style:{color:u.titleColor,backgroundColor:u.actionBackground,border:u.border},"aria-label":"Retry",children:"Retry"}),
13
13
  /* @__PURE__ */g(Ou,{label:"Dismiss",onClick:e=>{e.stopPropagation(),d()},size:"xs",tone:"inherit",style:{color:u.closeColor,padding:"2px"},children:/* @__PURE__ */g(Tu,{name:"closeSmall",size:12})})]})})};function Lu(e){if(e.id.startsWith("screenshare-")){const t="Screenshare ended";return{...e,content:t,isSystemMessage:!0,timestamp:new Date(e.timestamp),parts:[{type:"text",content:t}]}}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}}function ju({videoStream:e,...t}){return{...t,timestamp:t.timestamp.toISOString()}}function Fu(e){return!e.isPlaceholder||("thinking"===e.placeholderState||"waiting-for-user"===e.placeholderState||e.parts.length>0)}var Uu=new class{restored=!1;restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=ds.getContext();return this.restored=!0,{...o,messages:r.map(Lu)}}persist(e){this.restored&&ds.updateContext({...e,messages:e.messages.filter(Fu).map(ju)})}};function Wu(e,t,n,r={}){return{id:`${e}-${Date.now()}`,content:n,sender:t,timestamp:/* @__PURE__ */new Date,parts:n?[{type:"text",content:n}]:[],...r}}var Bu=(e,t,n="user-message")=>Wu(n,"user",e.trim(),{mode:t}),Hu=e=>Wu("agent-message","agent",e.trim()),Zu=(e,t,n,r)=>Wu(r,n,e,{mode:t,isSystemMessage:!0});async function qu(e,t,n,r){if(!e.mtxId||!e.mtxKey)throw new Error("mtxId + mtxKey is required");const o=await us.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:ds.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString()};e.userId&&(r.user_id=e.userId),e.mtxId&&e.mtxKey&&(r.marketrix_id=e.mtxId,r.marketrix_key=e.mtxKey),os.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>{})}(e,t,n);const i={type:`chat/${n}`,request_id:r,content:t},s=Nc.getInstance();s.isConnected()||await s.connect(o),await s.send(i)}var Vu={show:"Show",tell:"Tell",do:"Do"},Gu=e=>Vu[e],Yu=e=>(e??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});function Ju(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function Xu({messages:e,isTaskRunning:t,currentMode:n}){const r=e=>"agent"===e.sender&&!e.isSystemMessage&&!e.isScreenAccessRequest,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);for(const s of i){const t=Ju(e,s);if(t>=0)return{index:t,message:e[t]}}return null}var Ku=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys","upload_file"]);function Qu(e){return e?e.replace(/\(?cancelled by cleanup\)?/gi,"").replace(/\s+/g," ").trim():e}var ep=e=>"progress"===e.type&&"in_progress"===e.status;function tp(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function np(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var rp=/* @__PURE__ */new Map([["navigate","Navigating"],["search","Searching"],["click_element","Clicking element"],["type_text","Typing text"],["scroll","Scrolling"],["scroll_to_text","Scrolling to text"],["send_keys","Pressing key"],["extract","Extracting content"],["get_dropdown_options","Reading dropdown options"],["select_dropdown_option","Selecting option"],["upload_file","Uploading file"],["go_back","Going back"],["wait","Waiting"],["close_tab","Closing tab"],["done","Done"],["get_html","Viewed your screen"],["get_screenshot","Taking screenshot"]]),op=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*ip(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function sp(e){if(!(e instanceof Element))return!1;try{if(!function(e){const t=e.tagName.toLowerCase();return"button"===t||"input"===t||"textarea"===t||"select"===t||"a"===t&&e.hasAttribute("href")||op.has(e.getAttribute("role")??"")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||parseInt(e.getAttribute("tabindex")??"-1",10)>=0}(e))return!1;if(!0===e.disabled)return!1;if("true"===e.getAttribute("aria-disabled"))return!1;for(const r of ip(e))if(r instanceof HTMLElement&&r.inert)return!1;const t=window.getComputedStyle(e);if("none"===t.display||"none"===t.pointerEvents)return!1;const n=e.getBoundingClientRect();if(n.width<=0||n.height<=0)return!1;for(const r of ip(e))if(r!==e){const e=window.getComputedStyle(r).overflow;if("hidden"===e||"clip"===e){const e=r.getBoundingClientRect();if(n.right<e.left||n.left>e.right||n.bottom<e.top||n.top>e.bottom)return!1}if(r===document.body)break}for(let r=e.getRootNode();r instanceof ShadowRoot;r=r.host.getRootNode()){const e=r.host.getBoundingClientRect();if(e.width<=0||e.height<=0)return!1}return!0}catch(t){return!1}}var ap=["type","role","aria-label","name","href"],cp=new class{index=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;generateSelector(e){if(e.id&&1===document.querySelectorAll(`#${CSS.escape(e.id)}`).length)return`#${CSS.escape(e.id)}`;const t=[];let n=e;for(;n&&n!==document.body&&n.parentElement;){let e=n.tagName.toLowerCase();if(n.id){e+=`#${CSS.escape(n.id)}`,t.unshift(e);break}{const t=n.parentElement;if(!t)break;const r=n.tagName,o=Array.from(t.children).filter(e=>e.tagName===r);if(o.length>1){e+=`:nth-of-type(${o.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}staleReason(e){return document.contains(e.element)?e.id&&e.element.id===e.id?null:ap.some((t,n)=>e.identity[n]&&e.element.getAttribute(t)!==e.identity[n])?"has changed":null:"no longer exists"}indexInteractableElements(){this.clearIndex();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||sp(r))&&(this.index.set(n,{element:r,selector:this.generateSelector(r),id:r.id,identity:ap.map(e=>r.getAttribute(e))}),this.elementToSequence.set(r,n),n++)}t=e.nextNode()}}getSnapshotHtml(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,{selector:r}]of this.index.entries())try{(e.querySelector("body")||e).querySelector(r)?.setAttribute("data-id",n.toString())}catch(t){}return e.outerHTML}getSequenceForElement(e){return this.elementToSequence.get(e)}clearIndex(){this.index.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap}checkElementInteractable(e,t){if(!document.body.contains(e))return`ELEMENT_NOT_INTERACTABLE: Element ${t} is not in the DOM`;const n=window.getComputedStyle(e);if("none"===n.display)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has display:none`;if("hidden"===n.visibility)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has visibility:hidden`;if(0===parseFloat(n.opacity))return`ELEMENT_NOT_INTERACTABLE: Element ${t} has opacity:0`;const r=e.getBoundingClientRect();if(0===r.width||0===r.height)return`ELEMENT_NOT_INTERACTABLE: Element ${t} has zero dimensions`;if(r.bottom<0||r.top>window.innerHeight||r.right<0||r.left>window.innerWidth)return`ELEMENT_NOT_INTERACTABLE: Element ${t} is off-screen`;const o=r.left+r.width/2,i=r.top+r.height/2,s=document.elementFromPoint(o,i);if(s&&s!==e&&!e.contains(s)&&!(s.closest("#marketrix-show-highlight")||s.closest("#marketrix-show-popup")||s.closest("[data-marketrix-widget]"))){const e=s.tagName.toLowerCase();return`ELEMENT_OBSCURED: Element ${t} is covered by ${s.className?`${e}.${s.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=this.staleReason(t);if(n)return{element:null,error:`DOM_CHANGED: Element at index ${e} ${n}. Call get_html to get updated indices.`};const r=this.checkElementInteractable(t.element,e);return r?{element:null,error:r}:{element:t.element}}},lp=null;function dp(){return lp?.active&&"live"===lp.getVideoTracks()[0]?.readyState?lp:(lp=null,null)}async function up(){const e=dp();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 lp=t,t.getVideoTracks()[0].addEventListener("ended",()=>{lp=null}),t}var pp=["scroll","resize","touchmove","wheel"],hp=320,fp=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:"smooth",block:"center",inline:"center"}),this.createHighlight(t),this.createPopup(n,r),this.setupPositionUpdates(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t}).finally(()=>{this.cleanup()})),this.currentPromise}cleanup(){if(this.takeSettlers().reject?.("Cancelled by cleanup"),this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler){for(const e of pp)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}takeSettlers(){const e={resolve:this.resolvePromise,reject:this.rejectPromise};return this.resolvePromise=null,this.rejectPromise=null,e}createHighlight(e){const t=e.getBoundingClientRect(),n=document.createElement("div");n.id="marketrix-show-highlight",n.style.cssText=`\n position: fixed;\n top: ${t.top}px;\n left: ${t.left}px;\n width: ${t.width}px;\n height: ${t.height}px;\n border: 3px solid #3b82f6;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2), 0 0 20px rgba(59, 130, 246, 0.4);\n z-index: 2147483645;\n pointer-events: none;\n transition: none;\n `,document.body.appendChild(n),this.currentHighlight=n}createPopup(e,t){const n=document.createElement("div");n.id="marketrix-show-popup",n.innerHTML=t?`<div style="font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>`:`<div style="margin-bottom: 12px; font-weight: 500; color: #1f2937; font-size: 12px;">${this.escapeHtml(e)}</div>\n <div style="display: flex; gap: 8px; justify-content: flex-end;">\n <button id="marketrix-show-continue" style="\n background: #3b82f6; color: white; border: none; border-radius: 6px;\n padding: 8px 16px; font-size: 12px; font-weight: 500; cursor: pointer;\n ">Continue</button>\n </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||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.scrollHandler=()=>{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()};for(const e of pp)window.addEventListener(e,this.scrollHandler,{capture:!0,passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=120,n=10,r=e.left+e.width/2,o=e.top+e.height/2,i=[{left:e.right+20,top:o-60},{left:e.left-hp-20,top:o-60},{left:r-160,top:e.top-t-20},{left:r-160,top:e.bottom+20}];let s=i[0];for(const a of i)if(a.left>=n&&a.left+hp<=window.innerWidth-n&&a.top>=n&&a.top+t<=window.innerHeight-n){s=a;break}this.currentPopup.style.left=`${Math.max(n,Math.min(s.left,window.innerWidth-hp-n))}px`,this.currentPopup.style.top=`${Math.max(n,Math.min(s.top,window.innerHeight-t-n))}px`}setupClickHandler(){this.clickHandler=e=>{this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)&&(e.preventDefault(),e.stopPropagation(),this.takeSettlers().resolve?.(!0))},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{e.querySelector("#marketrix-show-continue")?.addEventListener("click",e=>{e.stopPropagation(),this.takeSettlers().resolve?.(!0)})})}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{if(!this.currentElement)return;const e=cp.getSequenceForElement(this.currentElement)??-1,t=cp.checkElementInteractable(this.currentElement,e);t&&this.failWithElementGone(t)},200)}failWithElementGone(e){this.takeSettlers().reject?.(/* @__PURE__ */new Error(`ELEMENT_GONE: ${e}`)),this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}},mp=e=>({success:!0,data:{text:e}}),gp=e=>({success:!0,data:e}),yp=e=>({success:!1,data:{text:""},error:e}),bp=e=>({success:!1,data:{options:[]},error:e}),vp=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&Ku.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=cp.getValidatedElement(t);if(!n)return yp(o||`Element ${t} not found`);if(!(await fp.showToolAction({element:n,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})))return yp("User cancelled action")}}switch(e){case"navigate":return this.navigate(o);case"search":return this.search(o);case"click_element":return await this.clickElement(o);case"type_text":return this.typeText(o);case"scroll":return this.scroll(o);case"scroll_to_text":return this.scrollToText(o);case"extract":return this.extract(o);case"go_back":return this.goBack();case"wait":return await this.wait(o);case"select_dropdown_option":return this.selectDropdownOption(o);case"get_dropdown_options":return this.getDropdownOptions(o);case"send_keys":return this.sendKeys(o);case"upload_file":return this.uploadFile();case"close_tab":return this.closeTab();case"done":return this.done(o);case"get_html":return this.getHtml();case"get_screenshot":return await this.getScreenshot();default:return yp(`Unknown tool: ${e}`)}}catch(i){return fp.cleanup(),yp(i instanceof Error?i.message:String(i))}}navigate(e){return e.url?e.new_tab?(window.open(e.url,"_blank"),mp(`Opened ${e.url} in new tab`)):(window.location.href=e.url,mp(`Navigating to ${e.url}`)):yp("URL is required")}search(e){if(!e.query)return yp("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}`),window.location.href=r,mp(`Searching for "${e.query}" on ${t}`)}async clickElement(e){if(void 0===e.index)return yp("Index required");const{element:t,error:n}=cp.getValidatedElement(e.index);return t?(t.scrollIntoView({behavior:"smooth",block:"center"}),await new Promise(e=>setTimeout(e,100)),setTimeout(()=>{try{t.click()}catch(e){try{t.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window}))}catch(n){}}},50),mp(`Clicked element ${e.index}`)):yp(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return yp("Index and text required");const t=!1!==e.clear,{element:n,error:r}=cp.getValidatedElement(e.index);if(!n)return yp(r||`Element ${e.index} not found`);if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n.isContentEditable){const r=n;try{r.focus()}catch(o){}const i=t?e.text:r.value+e.text;let s=null;const a=(e,t)=>{try{return t()}catch(o){return s=o,!1}};if(!(a("Native setter",()=>{const e="TEXTAREA"===r.tagName.toUpperCase(),t=Object.getOwnPropertyDescriptor(e?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value");return!!t?.set&&(t.set.call(r,i),!0)})||a("Direct assignment",()=>(r.value=i,!0))||a("execCommand",()=>(r.focus(),t&&r.select(),document.execCommand("insertText",!1,e.text)))))return yp(`Failed to set value: ${s instanceof Error?s.message:String(s)}`);try{const t=new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:e.text});r.dispatchEvent(t),r.dispatchEvent(new Event("change",{bubbles:!0})),r.dispatchEvent(new Event("blur",{bubbles:!0}))}catch(o){}}else if("value"in n)try{n.value=e.text,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0}))}catch(o){return yp(`Failed to set value on element: ${o instanceof Error?o.message:String(o)}`)}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(o){return yp(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return mp(`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 yp("Invalid direction")}return mp(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return yp("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"}),mp(`Scrolled to "${e.text}"`);return yp(`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 gp(n)}goBack(){return window.history.length>1?(window.history.back(),mp("Navigated back")):yp("No history")}async wait({seconds:e}){return void 0===e?yp("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),mp(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return yp("Index/Option required");const{element:t,error:n}=cp.getValidatedElement(e.index);if(!t)return yp(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return yp(`Element ${e.index} is not a select element`);const r=Array.from(t.options).find(t=>t.value===e.option||t.text===e.option);return r?(t.value=r.value,t.dispatchEvent(new Event("change",{bubbles:!0})),mp(`Selected ${e.option}`)):yp(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return bp("Index required");const{element:n,error:r}=cp.getValidatedElement(t);if(!n)return bp(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return bp(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return gp({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return yp("Index/Keys required");const{element:t,error:n}=cp.getValidatedElement(e.index);if(!t)return yp(n||`Element ${e.index} not found`);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 r=this.simulateKeyAction(t,e.keys);return mp(r||`Sent keys ${e.keys}`)}simulateKeyAction(e,t){switch(t){case"Tab":case"Shift+Tab":{const n="Tab"===t?1:-1,r=Array.from(document.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent),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(e instanceof HTMLButtonElement||"button"===e.getAttribute("role"))return e.click(),"Enter: clicked button";if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){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}`):e instanceof HTMLButtonElement||"button"===e.getAttribute("role")?(e.click(),"Space: clicked button"):"Space: dispatched event";case"ArrowDown":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t<e.options.length-1?(e.selectedIndex=t+1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowDown: selected "${e.options[e.selectedIndex].text}"`):"ArrowDown: already at last option"}return"ArrowDown: dispatched event";case"ArrowUp":if(e instanceof HTMLSelectElement){const t=e.selectedIndex;return t>0?(e.selectedIndex=t-1,e.dispatchEvent(new Event("change",{bubbles:!0})),`ArrowUp: selected "${e.options[e.selectedIndex].text}"`):"ArrowUp: already at first option"}return"ArrowUp: dispatched event";case"Home":return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement?(e.setSelectionRange(0,0),"Home: moved cursor to start"):"Home: dispatched event";case"End":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value.length;return e.setSelectionRange(t,t),"End: moved cursor to end"}return"End: dispatched event";case"Backspace":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.value;if(!t||0===t.length)return"Backspace: input is empty, nothing to delete";let n,r,o=e.selectionStart??t.length,i=e.selectionEnd??t.length;if(0===o&&0===i&&(o=t.length,i=t.length),o===i&&o>0)n=t.slice(0,o-1)+t.slice(i),r=o-1;else{if(o===i)return"Backspace: cursor at start, nothing to delete";n=t.slice(0,o)+t.slice(i),r=o}return this.setValueAndCaret(e,n,r),`Backspace: deleted character, value is now "${n}"`}return"Backspace: dispatched event";case"Delete":if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement){const t=e.selectionStart||0,n=e.selectionEnd||0,r=e.value;let o;if(t===n&&t<r.length)o=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";o=r.slice(0,t)+r.slice(n)}return this.setValueAndCaret(e,o,t),`Delete: deleted character, value is now "${o}"`}return"Delete: dispatched event";default:return null}}setValueAndCaret(e,t,n){const r=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;r?r.call(e,t):e.value=t,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(n,n)}uploadFile(){return yp("File upload not supported via script")}closeTab(){return window.close(),mp("Attempted close")}done(e){if(void 0===e.success)return yp("success parameter is required");const t=e.message||(e.success?"Task completed":"Task failed");return mp(t)}getHtml(){try{const e=cp.getSnapshotHtml();return mp(e)}catch(e){return yp(String(e))}}async getScreenshot(){try{const e=await up(),t=document.createElement("video");t.srcObject=e,t.autoplay=!0,t.style.display="none",document.body.appendChild(t),await new Promise(e=>{t.onloadeddata=()=>e()});const n=document.createElement("canvas");n.width=t.videoWidth,n.height=t.videoHeight,n.getContext("2d")?.drawImage(t,0,0);const r=n.toDataURL("image/jpeg",.75);return t.remove(),mp(r)}catch(e){return yp(String(e))}}},wp=e=>({state:e,effects:[]});function xp(e,t,n,r,o,i,s){const a=Xu({messages:e,isTaskRunning:t,currentMode:n});if(!a)return e;let c=a.message;var l;if("failed"===i?c=function(e,t,n){const r=tp(e.parts,e=>"progress"===e.type&&e.browserToolName===t),o=r>=0?r:tp(e.parts,ep);if(o<0)return e;const i=Qu(e.parts[o].content);if(n.toLowerCase().includes("cancelled by cleanup"))return np(e,o,{status:"completed",content:i});const s=Qu(n);return np(e,o,{status:"failed",content:s?`${i} (${s})`:i})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=Qu(n),o=e.parts.findIndex(e=>ep(e)&&e.browserToolName===t);return o>=0?np(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>rp.get(e)??e)(r)):np(l=c,tp(l.parts,ep),{status:"completed"})),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&Ku.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const d=[...e];return d[a.index]=c,d}function kp(e,t,n){const r=Xu({messages:e.messages,isTaskRunning:e.task.isTaskRunning,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=n(r.message)),{messages:o,task:{isTaskRunning:!1}}}var Sp={completed:"done",failed:"failed",stopped:"stopped"};function _p(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=r&&s?i.content+n:n,c={type:"text",content:a,...r&&{streaming:!0}};return s?o[o.length-1]=c:o.push(c),{...e,content:a,isPlaceholder:!1,placeholderState:void 0,parts:o}});return{...e,messages:o}}function Ep(e,t,n){const r=e.messages.map(e=>e.id!==t?e:{...e,content:n,isPlaceholder:!1,placeholderState:void 0,parts:[...e.parts,{type:"text",content:n}]});return{...e,messages:r}}var Cp=n(void 0),Ip=({children:e})=>{const[t,n]=p({isOpen:!1,activeView:"home",currentMode:"tell",isLoading:!1}),r=d(()=>({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})),setLoading:e=>n(t=>({...t,isLoading:e})),setError:e=>n(t=>({...t,error:e})),applyState:e=>n(t=>({...t,...e}))}),[]);/* @__PURE__ */
14
- return g(Cp.Provider,{value:{uiState:t,uiActions:r},children:e})},Tp=()=>{const e=s(Cp);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},zp=n(void 0),Mp=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Tp(),[o,s]=p(()=>({messages:[],task:{isTaskRunning:!1}})),c=u(o),l=u(n.currentMode);l.current=n.currentMode;const h=u(/* @__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]),y=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),b=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(e=>{f(t=>({...t,task:{isTaskRunning:e}}))},[f]),k=i(async(e,n,o)=>{const i=n??l.current;if(t)return o||m(Bu(e,i)),void m(Hu("This is a preview. In production, I'll respond to your messages here."));const s=ds.getConfig();if(!s||!s.mtxId&&!s.mtxKey&&!s.mtxApp)return void m(Hu("Configuration error: Missing API credentials. Please check your widget settings."));o||m(Bu(e,i));const a=`temp-${globalThis.crypto.randomUUID()}`;m({id:a,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:i,isPlaceholder:!0,placeholderState:"thinking",parts:[]}),r.setLoading(!0);try{await qu(s,e,i,a)}catch(c){f(e=>Ep(e,a,"I'm sorry, I encountered an error processing your request. Please try again."))}finally{r.setLoading(!1)}},[t,m,f,r]);a(()=>{if(t)return;const e=Nc.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await vp.executeTool(r,o,i,s),c=a.success?void 0:a.error??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:xp(e.messages,e.task.isTaskRunning,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return kp(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>{})},o={onMessage:async t=>{if("tool/call"===t.type){const n=t.tool_call_id;if(h.current.has(n))return;if(h.current.add(n),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500))),!rp.has(t.browser_tool))return void e.send({type:"tool/response",tool_call_id:n,success:!1,error:`Unknown tool: ${t.browser_tool}`}).catch(e=>{})}else"task/status"!==t.type||"completed"!==t.status&&"failed"!==t.status&&"stopped"!==t.status||h.current.clear();let o=[];f(e=>{const n=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isTaskRunning?e.task:{isTaskRunning:!0},o=t.explanation||"";return{state:{messages:xp(e.messages,r.isTaskRunning,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||"do",explanation:o}]}}case"task/status":{if("running"===t.status)return wp(e);const r=t.message?{content:t.message}:{},o=t.status;return{state:kp(e,n,"has_question"===o?e=>({...e,placeholderState:"waiting-for-user",...r}):e=>({...e,taskStatus:Sp[o],...r})),effects:[]}}case"chat/delta":return{state:_p(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:_p(e,t.request_id,t.text,!1),effects:[{type:"setLoading",value:!1}]};case"chat/error":return{state:Ep(e,t.request_id,`Error: ${t.error}`),effects:[{type:"setLoading",value:!1}]};default:return wp(e)}}(e,t,l.current);return o=n.effects,n.state});for(const e of o)"setLoading"===e.type?r.setLoading(e.value):await n(e)},onError:e=>{r.setError(e.message)}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const S=i(async()=>{f(e=>function(e,t){return kp(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||Nc.getInstance().send({type:"chat/stop"}).catch(e=>{r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),_=d(()=>({addMessage:m,updateMessage:y,removeMessage:b,setMessages:v,clearMessages:w,messageDispatch:k}),[m,y,b,v,w,k]),E=d(()=>({setTaskState:x,stopTask:S}),[x,S]);/* @__PURE__ */
14
+ return g(Cp.Provider,{value:{uiState:t,uiActions:r},children:e})},Tp=()=>{const e=s(Cp);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},zp=n(void 0),Mp=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Tp(),[o,s]=p(()=>({messages:[],task:{isTaskRunning:!1}})),c=u(o),l=u(n.currentMode);l.current=n.currentMode;const h=u(/* @__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]),y=i((e,t)=>{f(n=>({...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)}))},[f]),b=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(e=>{f(t=>({...t,task:{isTaskRunning:e}}))},[f]),k=i(async(e,n,o)=>{const i=n??l.current;if(t)return o||m(Bu(e,i)),void m(Hu("This is a preview. In production, I'll respond to your messages here."));const s=ds.getConfig();if(!s||!s.mtxId&&!s.mtxKey&&!s.mtxApp)return void m(Hu("Configuration error: Missing API credentials. Please check your widget settings."));o||m(Bu(e,i));const a=`temp-${globalThis.crypto.randomUUID()}`;m({id:a,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:i,isPlaceholder:!0,placeholderState:"thinking",parts:[]}),r.setLoading(!0);try{await qu(s,e,i,a)}catch(c){f(e=>Ep(e,a,"I'm sorry, I encountered an error processing your request. Please try again."))}finally{r.setLoading(!1)}},[t,m,f,r]);a(()=>{if(t)return;const e=Nc.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await vp.executeTool(r,o,i,s),c=a.success?void 0:a.error??"Tool execution failed";f(e=>function(e,t,n,r,o,i){return{...e,messages:xp(e.messages,e.task.isTaskRunning,o,t,n,r,i)}}(e,r,s,c?"failed":"completed",l.current,c)),c||"done"!==r||f(e=>function(e,t){return kp(e,t,e=>({...e,taskStatus:"done"}))}(e,l.current)),e.send({type:"tool/response",tool_call_id:n,success:a.success,data:JSON.stringify(a.data),error:c}).catch(e=>{})},o={onMessage:async t=>{if("tool/call"===t.type){const n=t.tool_call_id;if(h.current.has(n))return;if(h.current.add(n),h.current.size>1e3&&(h.current=new Set([...h.current].slice(-500))),!rp.has(t.browser_tool))return void e.send({type:"tool/response",tool_call_id:n,success:!1,error:`Unknown tool: ${t.browser_tool}`}).catch(e=>{})}else"task/status"===t.type&&t.status in Sp&&h.current.clear();let o=[];f(e=>{const n=function(e,t,n){switch(t.type){case"tool/call":{const r=e.task.isTaskRunning?e.task:{isTaskRunning:!0},o=t.explanation||"";return{state:{messages:xp(e.messages,r.isTaskRunning,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 wp(e);const r=t.message?{content:t.message}:{},o=t.status;return{state:kp(e,n,"has_question"===o?e=>({...e,placeholderState:"waiting-for-user",...r}):e=>({...e,taskStatus:Sp[o],...r})),effects:[]}}case"chat/delta":return{state:_p(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:_p(e,t.request_id,t.text,!1),effects:[{type:"setLoading",value:!1}]};case"chat/error":return{state:Ep(e,t.request_id,`Error: ${t.error}`),effects:[{type:"setLoading",value:!1}]};default:return wp(e)}}(e,t,l.current);return o=n.effects,n.state});for(const e of o)"setLoading"===e.type?r.setLoading(e.value):await n(e)},onError:e=>{r.setError(e.message)}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const S=i(async()=>{f(e=>function(e,t){return kp(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||Nc.getInstance().send({type:"chat/stop"}).catch(e=>{r.setError("Could not stop the assistant — it may still be working.")})},[t,f,r]),_=d(()=>({addMessage:m,updateMessage:y,removeMessage:b,setMessages:v,clearMessages:w,messageDispatch:k}),[m,y,b,v,w,k]),E=d(()=>({setTaskState:x,stopTask:S}),[x,S]);/* @__PURE__ */
15
15
  return g(zp.Provider,{value:{messages:o.messages,chatActions:_,taskState:o.task,taskActions:E},children:e})},Op=()=>{const e=s(zp);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},Rp=n(null),Np=({previewMode:e})=>{const{uiState:t}=Tp(),{messages:n,taskState:r}=Op();return a(()=>{if(e)return;const{currentMode:o,isOpen:i}=t;Uu.persist({messages:n,...r,currentMode:o,isOpen:i})},[e,n,r,t]),null},Ap=({children:e,previewMode:t})=>{const{uiActions:n}=Tp(),{chatActions:r,taskActions:o}=Op();return a(()=>{if(t)return;let e=!1;return(async()=>{const t=await us.getOrCreateChatId();if(e)return;const{messages:i,isTaskRunning:s,...a}=Uu.restore();n.applyState(a),r.setMessages(i),o.setTaskState(s),Nc.getInstance().connect(t).catch(e=>{})})().catch(t=>{e||n.setError("Widget failed to initialise — please refresh the page.")}),()=>{e=!0}},[]),/* @__PURE__ */y(m,{children:[e,/* @__PURE__ */g(Np,{previewMode:t})]})},Pp=({children:e,previewMode:t=!1})=>/* @__PURE__ */g(Ip,{children:/* @__PURE__ */g(Mp,{previewMode:t,children:/* @__PURE__ */g(Ap,{previewMode:t,children:e})})});function Dp(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}function $p(e){return function(e){const t=Dp(e);if(!t)return.5;const[n,r,o]=[t.r/255,t.g/255,t.b/255].map(e=>e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4));return.2126*n+.7152*r+.0722*o}(e)>.5?"#000000":"#ffffff"}function Lp(e,t){if(e.startsWith("rgba")||e.startsWith("rgb")){const n=e.match(/(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);if(n)return`rgba(${n[1]}, ${n[2]}, ${n[3]}, ${t})`}const n=Dp(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var jp={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function Fp(e={}){const t=Object.fromEntries(Object.entries(e).filter(([,e])=>void 0!==e));return function(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:Lp(e.widget_text_color,.6),foregroundFaint:Lp(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:$p(e.widget_accent_color),primaryHover:Lp(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Lp(e.widget_secondary_color,.2),secondaryHover:Lp(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}({...jp,...t})}var Up=n(null),Wp=()=>{const e=s(Up);if(!e)throw new Error("useWidgetConfig must be used within MarketrixWidget");return e},Bp=()=>{const{uiState:e,uiActions:t}=Tp(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Op(),a=d(()=>({...e,...o,messages:n}),[e,n,o]),c=i(()=>{r.clearMessages(),s.setTaskState(!1),t.setError(void 0)},[r,s,t]);return{state:a,actions:d(()=>({...t,...s,...r,clearChatHistory:c}),[t,s,r,c])}},Hp=20,Zp={bottom_right:{classes:"bottom-5 right-5",vertical:"bottom",horizontal:"right"},bottom_left:{classes:"bottom-5 left-5",vertical:"bottom",horizontal:"left"},top_right:{classes:"top-5 right-5",vertical:"top",horizontal:"right"},top_left:{classes:"top-5 left-5",vertical:"top",horizontal:"left"}},qp=e=>Zp[e]??Zp.bottom_right,Vp=e=>{const{vertical:t,horizontal:n}=qp(e);return{[t]:"20px",[n]:"20px"}},Gp=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=qp(e);return{x:"left"===s?Hp:t-Hp-r,y:"top"===i?Hp:n-Hp-o}},Yp="cubic-bezier(0.16, 1, 0.3, 1)";function Jp({position:e,onDrag:n,isPreviewMode:r=!1,wrapperRef:o}){const[s,a]=p(!1),[c,d]=p({w:56,h:56}),[,h]=p(0),f=u(null),m=u(null),g=u(null),y=u(0),b=u([]),v=u(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();d(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 k="undefined"!=typeof window?window.innerWidth:0,S="undefined"!=typeof window?window.innerHeight:0,_=Gp(e,k,S,c.w,c.h),E=!r&&k>0&&S>0?{left:_.x,top:_.y}:void 0,C=(e,t=.999)=>e/1e3*t/(1-t),I=()=>{w(),o.current&&(o.current.style.transform="",o.current.style.willChange="",o.current.style.transition="")},T=i((e,t)=>{if(f.current)return;let r=!1;const i=()=>{r||(r=!0,f.current=null,t.style.transition="none",t.style.willChange="",n(e),a(!1),requestAnimationFrame(()=>{o.current&&(o.current.style.transition="")}))};f.current=i;const s=window.setTimeout(i,650);t.addEventListener("transitionend",function e(n){n.target===t&&"left"===n.propertyName&&(window.clearTimeout(s),t.removeEventListener("transitionend",e),i())})},[n,o]),z=i((t,r,i)=>{if(!o.current||!E)return I(),n(t),void a(!1);w();const s=o.current,l=Gp(e,k,S,c.w,c.h),d=Gp(t,k,S,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 ${Yp}, top 600ms ${Yp}`,s.style.left=`${d.x}px`,s.style.top=`${d.y}px`}),T(t,s)},[T,n,E,e,k,S,c.w,c.h,o]),M=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=(()=>{const e=b.current;if(e.length<2)return{x:0,y:0};const t=e[e.length-1].t-e[0].t;return t<=0?{x:0,y:0}:{x:(e[e.length-1].x-e[0].x)/t*1e3,y:(e[e.length-1].y-e[0].y)/t*1e3}})(),i=C(r.x),s=C(r.y),a={dx:n.lastX+i,dy:n.lastY+s},c=o.current?.getBoundingClientRect(),l=c?((e,t,n,r,o,i)=>{const s=Gp(t,n,r,o,i),a=s.x+e.dx,c=s.y+e.dy;let l=t,d=1/0;for(const u of Object.keys(Zp)){const e=Gp(u,n,r,o,i),t=Math.hypot(a-e.x,c-e.y);t<d&&(d=t,l=u)}return l})(a,e,window.innerWidth,window.innerHeight,c.width,c.height):e;return z(l,n.lastX,n.lastY),y.current=Date.now()+600,m.current=null,void t.currentTarget.releasePointerCapture(t.pointerId)}M(t)}},onPointerCancel:e=>{m.current?.pointerId===e.pointerId&&M(e)},suppressUntilRef:y}}var Xp=({onDrag:e})=>{const{isPreviewMode:t=!1,widget_accent_color:n,widget_background_color:r,widget_position:o,widget_position_z_index:i}=Wp(),{state:s,actions:a}=Bp(),c=s.isOpen,l=s.isTaskRunning,d=!!s.error,p=!c&&(s.isLoading||l),h=!c&&l,f=d?"marketrix-widget-button-error-glow":"marketrix-widget-button-processing-glow",m=d?"marketrix-widget-button-error-activity-ring":"marketrix-widget-button-processing-activity-ring",b=u(null),{isDragging:v,pixelPositionStyle:w,onPointerDown:x,onPointerMove:k,onPointerUp:S,onPointerCancel:_,suppressUntilRef:E}=Jp({position:o,onDrag:e,isPreviewMode:t,wrapperRef:b}),C=(e=>qp(e).classes)(o);/* @__PURE__ */
16
16
  return g(Eu,{ref:b,className:`${t?"absolute":"fixed"} ${w?"":C} ${v?"":"transition-transform duration-300 ease-in-out"}`,style:{zIndex:i,pointerEvents:c?"none":"auto",...t?Vp(o):{},...w},children:/* @__PURE__ */y(Eu,{className:`\n group relative w-14 h-14 overflow-visible transition-all duration-300 ease-in-out\n ${c?"scale-0 opacity-0 pointer-events-none":"scale-100 opacity-100 hover:scale-110"}\n `,children:[p&&/* @__PURE__ */g(Eu,{className:f,"aria-hidden":!0}),h&&!v&&/* @__PURE__ */g(vu,{type:"button",variant:"secondary",size:"sm",onClick:e=>{e.preventDefault(),e.stopPropagation(),a.stopTask()},className:"absolute top-1/2 z-20 -translate-y-1/2 rounded-full border border-white/25 bg-gray-900 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-wide text-white shadow-lg opacity-0 transition-opacity duration-150 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto group-focus-within:opacity-100 group-focus-within:pointer-events-auto "+(o.includes("left")?"left-full ml-2":"right-full mr-2"),style:{border:"1px solid rgba(255,255,255,0.25)"},"aria-label":"Stop simulation",children:"Stop"}),
17
17
  /* @__PURE__ */g(vu,{type:"button",variant:"bare",onClick:()=>{Date.now()<E.current||a.toggleWidget()},onDragStart:e=>e.preventDefault(),onPointerDown:x,onPointerMove:k,onPointerUp:S,onPointerCancel:_,className:"relative z-10 w-14 h-14 min-w-14",style:{touchAction:"none",cursor:v?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":c?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */g(Cu,{className:"w-full h-full items-center justify-center relative",children:/* @__PURE__ */y(Eu,{className:"\n relative w-12 h-12 overflow-hidden transition-[transform,opacity,background-color] duration-[167ms] ease-[cubic-bezier(0.33,0,0,1)]\n hover:scale-110 hover:duration-[250ms] active:scale-[0.85] active:duration-[134ms] active:ease-[cubic-bezier(0.45,0,0.2,1)]\n animate-launcher-entrance\n ",style:{borderRadius:"12px",backgroundColor:c?r:n,boxShadow:Fc.fab},children:[p&&/* @__PURE__ */g("svg",{className:m,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */g("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:13,ry:13})}),
@@ -35,13 +35,13 @@ return g(Tu,{name:t,size:14,style:{color:Lp(Wp().widget_accent_color,n),flexShri
35
35
  return y(Ru,{style:{marginTop:"10px"},role:"article","aria-roledescription":"message","aria-label":i?"You said…":"Agent says…",animate:n?"fadeIn":void 0,children:[/* @__PURE__ */y(Cu,{align:"start",gap:"sm",width:"full",children:[
36
36
  /* @__PURE__ */g(Cu,{shrink:!1,style:{width:"20px",height:"20px",marginTop:"6px"},children:!i&&/* @__PURE__ */g(yd,{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:"theme",style:{border:"none",outline:"none",display:"block",backgroundColor:"transparent"}})}),
37
37
  /* @__PURE__ */y(Ru,{grow:!0,position:"relative",rounded:"theme",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__ */g(og,{stream:e.videoStream}),!e.videoStream&&(s?/* @__PURE__ */y(Cu,{align:"start",gap:"sm",children:[/* @__PURE__ */g(Cu,{shrink:!1,style:{marginTop:"3px"},children:/* @__PURE__ */g(Tu,{name:s,size:13})}),/* @__PURE__ */g(Ru,{grow:!0,children:/* @__PURE__ */g(Qm,{message:e,isLastMessage:n})})]}):/* @__PURE__ */g(Qm,{message:e,isLastMessage:n})),e.isScreenAccessRequest&&!e.screenShareStatus&&/* @__PURE__ */y(Cu,{align:"center",gap:"sm",style:{marginTop:"6px"},children:[/* @__PURE__ */g(vu,{type:"button",variant:"primary",size:"sm",shape:"pill",onClick:()=>r?.(),children:"Yes"}),/* @__PURE__ */g(vu,{type:"button",variant:"secondary",size:"sm",shape:"pill",onClick:()=>o?.(),children:"No"})]}),e.isScreenAccessRequest&&e.screenShareStatus&&/* @__PURE__ */g(Du,{as:"div",variant:"faint",size:"xs",italic:!0,style:{marginTop:"2px"},children:"allowed"===e.screenShareStatus?"Sure":"Check HTML Instead"}),!i&&e.taskStatus&&/* @__PURE__ */g(Cu,{position:"absolute",align:"center",justify:"center",style:{bottom:"4px",right:"4px"},children:/* @__PURE__ */g(tg,{status:e.taskStatus})})]}),
38
- /* @__PURE__ */g(Cu,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */g(Du,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:Yu(e.timestamp)})]},`message-${e.id}-${t}`)},sg={boxShadow:Fc.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},ag=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Wp(),{state:o,actions:i}=Bp(),{messages:s}=o,c=r.isPreviewMode??!1,[l,h]=p(!1),[f,m]=p(!1),b=u(null),v=d(()=>({id:"welcome",content:r.widget_body??"How can I help you today?",sender:"agent",timestamp:/* @__PURE__ */new Date,isPlaceholder:!1,parts:[]}),[r.widget_body]),w=d(()=>[v,...s],[v,s]),x=()=>{if(b.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=b.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]);const k=s[s.length-1]?.content?.length??0;return a(()=>{const t=b.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[k,c,e]),/* @__PURE__ */y(Eu,{position:"relative",height:"full",children:[
38
+ /* @__PURE__ */g(Cu,{shrink:!1,style:{width:"20px"}})]}),!e.isPlaceholder&&/* @__PURE__ */g(Du,{as:"div",variant:"faint",size:"xxs",align:"right",style:{marginTop:"2px",marginRight:"26px"},children:Yu(e.timestamp)})]},`message-${e.id}-${t}`)},sg={boxShadow:Fc.button,backgroundColor:"var(--card)",border:"1px solid var(--border)",pointerEvents:"auto"},ag=({messagesEndRef:e,onScreenAccessAllow:t,onScreenAccessDeny:n})=>{const r=Wp(),{state:o,actions:i}=Bp(),{messages:s}=o,c=r.isPreviewMode??!1,[l,h]=p(!1),[f,m]=p(!1),b=u(null),v=d(()=>({id:"welcome",content:r.widget_body,sender:"agent",timestamp:/* @__PURE__ */new Date,isPlaceholder:!1,parts:[]}),[r.widget_body]),w=d(()=>[v,...s],[v,s]),x=()=>{if(b.current){const{scrollTop:e,scrollHeight:t,clientHeight:n}=b.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]);const k=s[s.length-1]?.content?.length??0;return a(()=>{const t=b.current;t&&!c&&t.scrollHeight-t.scrollTop-t.clientHeight<120&&window.requestAnimationFrame(()=>e.current?.scrollIntoView({behavior:"auto"}))},[k,c,e]),/* @__PURE__ */y(Eu,{position:"relative",height:"full",children:[
39
39
  /* @__PURE__ */y(Eu,{ref:b,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:r.widget_background_color.includes("gradient")?r.widget_background_color:`linear-gradient(135deg, ${r.widget_background_color} 0%, ${r.widget_background_color} 100%)`,scrollbarColor:`${Lp(r.widget_border_color,.3)} ${Lp(r.widget_border_color,.1)}`,scrollbarWidth:"thin"},children:[0===s.length&&o.isLoading&&/* @__PURE__ */y(Ru,{align:"center",justify:"center",gap:"lg",paddingY:"2xl",paddingX:"xl",role:"status","aria-live":"polite",children:[/* @__PURE__ */g(Xm,{size:"lg"}),/* @__PURE__ */g(Du,{as:"p",size:"sm",align:"center",children:"Connecting…"})]}),w.map((e,r)=>/* @__PURE__ */g(ig,{message:e,index:r,isLastMessage:r===w.length-1,onScreenAccessAllow:t,onScreenAccessDeny:n},`message-${e.id}-${r}`)),s.length>0&&/* @__PURE__ */g(Cu,{justify:"center",style:{marginTop:"12px",marginBottom:"4px"},children:/* @__PURE__ */g(vu,{type:"button",variant:"bare",onClick:i.clearChatHistory,children:/* @__PURE__ */g(Du,{size:"xs",variant:"muted",style:{cursor:"pointer"},children:"Clear conversation"})})}),
40
40
  /* @__PURE__ */g(Eu,{ref:e},"scroll-anchor")]},"message-list-container"),l&&/* @__PURE__ */g(Cu,{position:"absolute",justify:"center",style:{top:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */g(Ou,{variant:"secondary",size:"sm",label:"Scroll to top",onClick:()=>{b.current?.scrollTo({top:0,behavior:"smooth"})},style:sg,children:/* @__PURE__ */g(Tu,{name:"arrowUp",size:10,style:{color:r.widget_accent_color}})})}),f&&/* @__PURE__ */g(Cu,{position:"absolute",justify:"center",style:{bottom:"8px",left:0,right:0,zIndex:10,pointerEvents:"none"},children:/* @__PURE__ */g(Ou,{variant:"secondary",size:"sm",label:"Scroll to bottom",onClick:()=>{e.current&&!c&&e.current.scrollIntoView({behavior:"smooth"})},style:sg,children:/* @__PURE__ */g(Tu,{name:"arrowDown",size:10,style:{color:r.widget_accent_color}})})})]})},cg=class extends t.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(e,t){}render(){return this.state.hasError?/* @__PURE__ */g(Du,{as:"div",size:"xs",align:"center",style:{padding:"16px",color:"var(--muted-foreground)"},children:"Something went wrong displaying messages. Please refresh."}):this.props.children}},lg=[{id:"tell",icon:"chatBubble",flag:"widget_feature_tell"},{id:"show",icon:"mousePointerClick",flag:"widget_feature_show"},{id:"do",icon:"ticktick",flag:"widget_feature_do"}],dg=({onScreenSharingChange:e,onStartScreenShareRef:t,onStopScreenShareRef:n,messageInputRef:r})=>{const o=Wp(),{state:i,actions:s}=Bp(),{messages:a,currentMode:c,isTaskRunning:l}=i,[d,h]=p(""),f=u(null),[m,b]=p(null),{isScreenSharing:v,showScreenAccessDialog:w,handleScreenAccessDialogAllow:x,handleScreenAccessDialogDeny:k,handleScreenAccessAllow:S,handleScreenAccessDeny:_,requestScreenAccess:E}=sh({onScreenSharingChange:e,onStartScreenShareRef:t,onStopScreenShareRef:n,onAddMessage:s.addMessage,onUpdateMessage:s.updateMessage,onRemoveMessage:s.removeMessage,onSendMessage:s.messageDispatch,pendingMessage:m,setPendingMessage:b});/* @__PURE__ */
41
41
  return y(Ru,{height:"full",id:"view-chat",role:"tabpanel","aria-labelledby":"tab-chat",children:[w&&/* @__PURE__ */g(Ym,{open:w,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:x,confirmLabel:"Yes",cancelLabel:"No"}),
42
42
  /* @__PURE__ */g(Eu,{grow:!0,overflow:"hidden",paddingY:"xs",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */g(cg,{children:/* @__PURE__ */g(ag,{messagesEndRef:f,onScreenAccessAllow:S,onScreenAccessDeny:_})})}),
43
43
  /* @__PURE__ */g(Eu,{background:"card",border:!0,elevation:"card",paddingPreset:"card",radius:"xl",style:{margin:"0 12px 12px 12px",marginTop:"auto"},children:/* @__PURE__ */g(ch,{ref:r,value:d,onChange:h,onSubmit:()=>{const e=a.some(e=>e.isPlaceholder);if(d.trim()&&!e){const e=d.trim();h(""),s.addMessage(Bu(e,c)),!1===o.use_screenshare||"show"!==c&&"do"!==c||v?s.messageDispatch(e,c,!0):(b({content:e,mode:c,alreadyAdded:!0}),E(c))}},modes:lg.filter(({flag:e})=>o[e]).map(({id:e,icon:t})=>({id:e,icon:t,label:Gu(e)})),activeMode:c,onModeChange:e=>(e=>{e!==c&&(s.addMessage(Zu(`Switched to ${Gu(e)} mode`,e,"agent","mode-change")),s.setMode(e))})(e),disabled:a.some(e=>e.isPlaceholder),taskRunning:l,onStop:()=>{fp.cleanup(),s.stopTask()}})})]})},ug=[{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"}];var pg=({actions:e,onActionClick:t})=>{const n=Wp();return 0===e.length?null:/* @__PURE__ */g(Ru,{gap:"sm",children:e.map((e,r)=>/* @__PURE__ */g(vu,{elevation:"card",shape:"theme",size:"sm",variant:"chip",full:!0,onClick:n=>t(e,n),style:{color:n.widget_text_color,paddingTop:"8px",paddingBottom:"8px"},children:/* @__PURE__ */g(Du,{as:"span",weight:"normal",leading:"tight",children:"show"===e.type?/* @__PURE__ */y(m,{children:["Show me ",e.text.replace(/^Show me\s*/i,"")]}):"do"===e.type?/* @__PURE__ */y(m,{children:["Do ",e.text.replace(/^Do\s*/i,"")]}):e.text})},`welcome-chip-${e.id}-${r}`))})},hg=({onNavigateToChat:e,onChipClick:t})=>{const n=Wp(),{messages:r}=Bp().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:e.chip_text,type:e.chip_mode})):ug}(n);/* @__PURE__ */
44
- return y(Ru,{height:"full",overflow:"hidden",id:"view-home",role:"tabpanel","aria-labelledby":"tab-home",children:[/* @__PURE__ */y(Ru,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */y(Eu,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */g(Du,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting??"Hey There!"}),/* @__PURE__ */g(Du,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body??"How can I help you today?"})]}),/* @__PURE__ */y(Ru,{gap:"sm",children:[/* @__PURE__ */y(vu,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */g(Tu,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */g(pg,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */y(Eu,{background:"card",border:!0,elevation:"card",paddingPreset:"card",radius:"xl",style:{margin:"0 12px 12px 12px"},children:[
44
+ return y(Ru,{height:"full",overflow:"hidden",id:"view-home",role:"tabpanel","aria-labelledby":"tab-home",children:[/* @__PURE__ */y(Ru,{grow:!0,overflowY:"auto",padding:"lg",children:[/* @__PURE__ */y(Eu,{style:{textAlign:"center",paddingTop:"8px",paddingBottom:"16px"},children:[/* @__PURE__ */g(Du,{as:"h2",size:"lg",weight:"semibold",children:n.widget_greeting}),/* @__PURE__ */g(Du,{as:"p",variant:"muted",size:"sm",style:{marginTop:"2px"},children:n.widget_body})]}),/* @__PURE__ */y(Ru,{gap:"sm",children:[/* @__PURE__ */y(vu,{type:"button",variant:"primary",full:!0,onClick:e,"aria-label":"Ask a question",style:{paddingTop:"10px",paddingBottom:"10px"},children:[/* @__PURE__ */g(Tu,{name:"chat",size:16}),"Ask a question"]}),/* @__PURE__ */g(pg,{actions:o,onActionClick:async(n,r)=>{r.preventDefault(),r.stopPropagation(),e(),t(n)}})]})]}),r.length>0&&/* @__PURE__ */y(Eu,{background:"card",border:!0,elevation:"card",paddingPreset:"card",radius:"xl",style:{margin:"0 12px 12px 12px"},children:[
45
45
  /* @__PURE__ */g(Du,{as:"p",size:"xs",weight:"semibold",style:{marginBottom:"2px"},children:"Recent conversation"}),
46
46
  /* @__PURE__ */g(Du,{as:"p",size:"xs",variant:"muted",style:{display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",overflow:"hidden"},children:r[r.length-1].content||"Message"}),
47
47
  /* @__PURE__ */g(Du,{as:"p",size:"xs",variant:"muted",onClick:e,style:{marginTop:"4px",cursor:"pointer"},children:"Continue conversation →"})]})]})},fg=["top-left","top-right","bottom-left","bottom-right"];function mg(e){const t=e.startsWith("top"),n=e.endsWith("left");return{position:"absolute",width:"20px",height:"20px",padding:"4px",touchAction:"none",zIndex:10,display:"flex",alignItems:t?"flex-start":"flex-end",justifyContent:n?"flex-start":"flex-end",cursor:t&&n||!t&&!n?"nwse-resize":"nesw-resize",top:t?0:void 0,bottom:t?void 0:0,left:n?0:void 0,right:n?void 0:0}}var gg=({onResizeStart:e})=>/* @__PURE__ */g(m,{children:fg.map(t=>/* @__PURE__ */g("div",{role:"separator","aria-label":`Resize widget from ${t.replace("-"," ")}`,title:"Drag to resize",style:mg(t),onMouseDown:e(t)},t))}),yg=[{id:"home",icon:"home",label:"Home"},{id:"chat",icon:"chat",label:"Chat"}],bg=({activeView:e,onChange:t})=>/* @__PURE__ */g(Cu,{role:"tablist",align:"center",justify:"around",shrink:!1,border:"top",style:{height:48},children:yg.map(n=>{const r=e===n.id;/* @__PURE__ */
@@ -49,7 +49,7 @@ return y(vu,{role:"tab","aria-selected":r,"aria-controls":`view-${n.id}`,id:`tab
49
49
  /* @__PURE__ */g(Du,{as:"span",inheritColor:!0,"aria-hidden":"true",children:/* @__PURE__ */g(Tu,{name:n.icon,size:20})}),
50
50
  /* @__PURE__ */g(Du,{as:"span",size:"xs",align:"center",inheritColor:!0,truncate:!0,block:!0,children:n.label})]},n.id)})}),vg=()=>{const e=Wp(),{state:t,actions:n}=Bp(),{isOpen:r,activeView:o}=t,s=e.isPreviewMode??!1,{widthPx:c,heightPx:l,onResizeStart:d,containerRef:h}=rh(e.widget_width,e.widget_height,Pc(e),s),f=u(null),[m,b]=p("forward"),v=u(o);a(()=>{v.current!==o&&(b("chat"===o?"forward":"back"),v.current=o)},[o]),function(e,t,n){const r=u(!1),o=u(null),s=i(()=>{const t=e.current;if(!t)return;const r=n?.focusTargetRef?.current;if(r)return void r.focus({preventScroll:!0});const o=Qp(t);o[0]&&o[0].focus({preventScroll:!0})},[e,n?.focusTargetRef]);a(()=>{if(!t)return r.current&&(o.current?.focus({preventScroll:!0}),o.current=null),void(r.current=!1);const i=e.current;if(!i)return;r.current||(o.current=Kp(i)),r.current=!0,s();const a=e=>{if("Escape"===e.key)return void n?.onEscape?.();if("Tab"!==e.key)return;const t=Qp(i);if(0===t.length)return;const r=Kp(i),o=r?t.indexOf(r):-1;-1!==o&&(e.shiftKey?0===o&&(e.preventDefault(),t[t.length-1].focus()):o===t.length-1&&(e.preventDefault(),t[0].focus()))};return document.addEventListener("keydown",a,!0),()=>document.removeEventListener("keydown",a,!0)},[t,e,s,n?.onEscape])}(h,r,{onEscape:n.closeWidget,focusTargetRef:"chat"===o?f:void 0});const w=Vp(e.widget_position),[x,k]=p(!1),S=u(null),_=u(null);if(!r)return null;const E=e.widget_background_color.includes("gradient")?e.widget_background_color:`linear-gradient(135deg, ${e.widget_background_color} 0%, ${e.widget_background_color} 100%)`,{vertical:C,horizontal:I}=qp(e.widget_position),T="chat"===o&&!1!==e.use_screenshare?()=>{x?_.current?.():S.current?.()}:void 0;/* @__PURE__ */
51
51
  return y(Ru,{ref:h,position:s?"absolute":"fixed",rounded:"theme",border:!0,overflow:"hidden",style:{zIndex:e.widget_position_z_index,backgroundImage:E,transformOrigin:`${C} ${I}`,width:c,height:l,fontSize:"14px",...w,pointerEvents:"auto",scrollbarWidth:"thin",animation:"messenger-entrance 300ms cubic-bezier(0, 1.2, 1, 1)",boxShadow:Fc.panel},children:[
52
- /* @__PURE__ */g(oh,{title:e.widget_header??"AI Agent",subtitle:e.widget_body??"How can I help?",onClose:n.closeWidget,controls:T&&/* @__PURE__ */y(Ou,{variant:"ghost",size:"sm",label:x?"Stop screen sharing":"Start screen sharing",onClick:T,children:[x&&/* @__PURE__ */y("span",{className:"absolute top-0.5 right-0.5 inline-flex h-1.5 w-1.5",children:[/* @__PURE__ */g("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-75"}),/* @__PURE__ */g("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-current"})]}),/* @__PURE__ */g(Tu,{name:"screenShare",size:16})]})}),
52
+ /* @__PURE__ */g(oh,{title:e.widget_header,subtitle:e.widget_body,onClose:n.closeWidget,controls:T&&/* @__PURE__ */y(Ou,{variant:"ghost",size:"sm",label:x?"Stop screen sharing":"Start screen sharing",onClick:T,children:[x&&/* @__PURE__ */y("span",{className:"absolute top-0.5 right-0.5 inline-flex h-1.5 w-1.5",children:[/* @__PURE__ */g("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-75"}),/* @__PURE__ */g("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-current"})]}),/* @__PURE__ */g(Tu,{name:"screenShare",size:16})]})}),
53
53
  /* @__PURE__ */g(Eu,{grow:!0,overflow:"hidden",style:{display:"flex",flexDirection:"column",minHeight:0},children:/* @__PURE__ */y(Eu,{"data-view-transition":!0,"data-direction":m,style:{width:"100%",height:"100%"},children:["home"===o&&/* @__PURE__ */g(hg,{onNavigateToChat:()=>{b("forward"),n.setActiveView("chat")},onChipClick:e=>{n.addMessage(Bu(e.text,e.type,"chip-message")),n.setMode(e.type),n.messageDispatch(e.text,e.type,!0)}}),"chat"===o&&/* @__PURE__ */g(dg,{onScreenSharingChange:k,onStartScreenShareRef:S,onStopScreenShareRef:_,messageInputRef:f})]},o)}),
54
54
  /* @__PURE__ */g(bg,{activeView:o,onChange:n.setActiveView}),!s&&/* @__PURE__ */g(gg,{onResizeStart:d})]})},wg=class extends t.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){}render(){return this.state.hasError?null:this.props.children}},xg=({config:e})=>{const[t,n]=p(!1),[r,o]=p(null),{state:i,actions:s}=Bp(),c=Nc.getInstance(),l=e.isPreviewMode??!1,d=Ki.safeParse(e).success;var u;u=i.isOpen,a(()=>{if(!u)return;if(!window.matchMedia("(max-width: 767px)").matches)return;const e=document.documentElement,t=document.body,n=e.style.overflow,r=t.style.overflow;return e.style.overflow="hidden",t.style.overflow="hidden",()=>{e.style.overflow=n,t.style.overflow=r}},[u]);const[h,f]=p(e.widget_position??"bottom_right"),m=`marketrix_widget_position_${Pc(e)}`;a(()=>{d&&ds.setConfig(e)},[e,d]),a(()=>{const t=l?null:as(m);(e=>"string"==typeof e&&e in Zp)(t)?f(t):f(e.widget_position??"bottom_right")},[l,m,e.widget_position]),a(()=>{if(i.isOpen||l||"default"!==e.widget_appearance||!e.widget_greeting_toast)return void n(!1);const t=setTimeout(()=>n(!0),2e3);return()=>clearTimeout(t)},[i.isOpen,l,e.widget_appearance,e.widget_greeting_toast]);if(!d)return null;const b=!e.widget_enabled||!1===e.show_widget||"hidden"===e.widget_appearance;if(!l&&b)return null;const v=Math.max(e.widget_position_z_index??0,qc),w={...e,widget_position:h,widget_position_z_index:v},x=i.isLoading||i.isTaskRunning,k={"--background":(S=Fp(e)).color.background,"--foreground":S.color.foreground,"--card":S.color.background,"--card-foreground":S.color.foreground,"--primary":S.color.primary,"--foreground-muted":S.color.foregroundMuted,"--foreground-faint":S.color.foregroundFaint,"--primary-foreground":S.color.primaryForeground,"--primary-hover":S.color.primaryHover,"--secondary":S.color.secondary,"--secondary-foreground":S.color.secondaryForeground,"--secondary-bg":S.color.secondaryBg,"--secondary-hover":S.color.secondaryHover,"--muted":S.color.border,"--muted-foreground":S.color.secondary,"--border":S.color.border,"--ring":S.color.primary,"--radius":S.radius,"--duration-animation":S.motion.durationAnimation,"--duration-fade":S.motion.durationFade};var S;/* @__PURE__ */
55
55
  return g(Up,{value:w,children:/* @__PURE__ */g(Eu,{ref:o,"data-marketrix-widget":!0,position:"relative",style:{...k,...l&&{width:"100%",height:"100%"}},children:/* @__PURE__ */y(Rp,{value:r,children:[x&&/* @__PURE__ */g(Eu,{"data-screen-edge-glow":!0,position:"fixed",inset:"0",style:{boxShadow:`inset 0 0 22px 2px ${Lp(w.widget_accent_color,.72)}, inset 0 0 46px 10px ${Lp(w.widget_accent_color,.28)}`,pointerEvents:"none",zIndex:Vc}}),