@marketrix.ai/widget 3.8.467 → 3.8.469

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.
@@ -36,5 +36,18 @@ export declare const isTerminalTaskStatus: (status: string) => status is keyof t
36
36
  export declare function reduceError(state: SseState, messageId: string, text: string): SseState;
37
37
  /** The transport gave up, so no id-bearing event is coming for whatever is still pending. */
38
38
  export declare function reduceTransportFailure(state: SseState, text: string): SseState;
39
+ /**
40
+ * A per-request watchdog: the stream can stay healthy (no `StreamGaveUpError`) while a single
41
+ * dispatch's reply never arrives — a dropped correlation or a silent backend failure before it ever
42
+ * acknowledges the request. `reduceTransportFailure` cannot see that, since nothing told the transport
43
+ * it failed, so without this the bubble sits on "thinking" and the composer stays disabled forever.
44
+ *
45
+ * Only fires on a message that received ZERO signs of life — still `thinking` with no progress line
46
+ * and no streamed text. A `do`/`show` task that is genuinely still running has already advanced past
47
+ * this (a `tool/call` flips `placeholderState` or adds a line, a `chat/delta` adds a part) and must
48
+ * never be cut off just because it is taking a while; a task that never even started is what this
49
+ * catches.
50
+ */
51
+ export declare function reduceStaleReply(state: SseState, messageId: string, text: string): SseState;
39
52
  export declare function reduceSse(state: SseState, event: WidgetEvent, currentMode: InstructionType): ReduceResult;
40
53
  export {};
@@ -4,6 +4,7 @@ export declare const EntityStatusSchema: z.ZodEnum<{
4
4
  active: "active";
5
5
  suspended: "suspended";
6
6
  }>;
7
+ export type EntityStatus = z.infer<typeof EntityStatusSchema>;
7
8
  export declare const BaseEntitySchema: z.ZodObject<{
8
9
  id: z.ZodOptional<z.ZodNumber>;
9
10
  created_at: z.ZodOptional<z.ZodCoercedDate<unknown>>;
@@ -29,6 +29,7 @@ export declare const WorkspaceMemberRoleSchema: z.ZodEnum<{
29
29
  admin: "admin";
30
30
  member: "member";
31
31
  }>;
32
+ export type WorkspaceMemberRole = z.infer<typeof WorkspaceMemberRoleSchema>;
32
33
  export declare const UserEntitySchema: z.ZodObject<{
33
34
  id: z.ZodOptional<z.ZodNumber>;
34
35
  created_at: z.ZodOptional<z.ZodCoercedDate<unknown>>;
package/dist/widget.mjs CHANGED
@@ -11,7 +11,7 @@ return g(Iu,{position:"fixed",animate:c?"none":"fadeIn",style:{zIndex:Jc,maxWidt
11
11
  /* @__PURE__ */g(vd,{src:Uc,alt:"",size:28,rounded:"full"}),
12
12
  /* @__PURE__ */y(Au,{grow:!0,minWidth:"0",children:[/* @__PURE__ */g(Lu,{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(Lu,{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(xu,{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(Nu,{label:"Dismiss",onClick:e=>{e.stopPropagation(),d()},size:"xs",tone:"inherit",style:{color:u.closeColor,padding:"2px"},children:/* @__PURE__ */g(Mu,{name:"closeSmall",size:12})})]})})};function Fu(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 Uu({videoStream:e,...t}){return{...t,timestamp:t.timestamp.toISOString()}}function Wu(e){return!e.isPlaceholder||("thinking"===e.placeholderState||"waiting-for-user"===e.placeholderState||e.parts.length>0)}var Bu=new class{restored=!1;restore(){const{chat_id:e,config:t,timestamp:n,messages:r,...o}=us.getContext();return this.restored=!0,{...o,messages:r.map(Fu)}}persist(e){this.restored&&us.updateContext({...e,messages:e.messages.filter(Wu).map(Uu)})}};function Hu(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 Zu=(e,t,n="user-message")=>Hu(n,"user",e.trim(),{mode:t}),qu=e=>Hu("agent-message","agent",e.trim()),Vu=(e,t,n,r)=>Hu(r,n,e,{mode:t,isSystemMessage:!0});async function Gu(e,t,n,r){if(!e.mtxId||!e.mtxKey)throw new Error("mtxId + mtxKey is required");const o=await ps.getOrCreateChatId();!function(e,t,n){const r={question:t,mode:n,chat_id:us.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),is.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>{})}(e,t,n);const i={type:`chat/${n}`,request_id:r,content:t},s=Pc.getInstance();s.isConnected()||await s.connect(o),await s.send(i)}var Yu={show:"Show",tell:"Tell",do:"Do"},Ju=e=>Yu[e],Xu=e=>(e??/* @__PURE__ */new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});function Ku(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function Qu({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=Ku(e,s);if(t>=0)return{index:t,message:e[t]}}return null}var ep=/* @__PURE__ */new Set(["click_element","type_text","select_dropdown_option","send_keys","upload_file"]);function tp(e){return e?e.replace(/\(?cancelled by cleanup\)?/gi,"").replace(/\s+/g," ").trim():e}var np=e=>"progress"===e.type&&"in_progress"===e.status;function rp(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}function op(e,t,n){if(t<0)return e;const r=[...e.parts];return r[t]={...r[t],...n},{...e,parts:r}}var ip=/* @__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"]]),sp=/* @__PURE__ */new Set(["button","link","textbox","checkbox","radio","switch","tab","menuitem"]);function*ap(e){let t=e;for(;t;){yield t;const e=t.getRootNode();t=t.parentElement??(e instanceof ShadowRoot?e.host:null)}}function cp(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")||sp.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 ap(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 ap(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 lp=["type","role","aria-label","name","href"],dp=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:lp.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||cp(r))&&(this.index.set(n,{element:r,selector:this.generateSelector(r),id:r.id,identity:lp.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}}},up=null;function pp(){return up?.active&&"live"===up.getVideoTracks()[0]?.readyState?up:(up=null,null)}async function hp(){const e=pp();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 up=t,t.getVideoTracks()[0].addEventListener("ended",()=>{up=null}),t}var fp=["scroll","resize","touchmove","wheel"],mp=320,gp=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 fp)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 fp)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-mp-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+mp<=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-mp-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=dp.getSequenceForElement(this.currentElement)??-1,t=dp.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}},yp=e=>({success:!0,data:{text:e}}),bp=e=>({success:!0,data:e}),vp=e=>({success:!1,data:{text:""},error:e}),wp=e=>({success:!1,data:{options:[]},error:e}),xp=new class{async executeTool(e,t,n="do",r=""){const o=t;try{if("show"===n&&ep.has(e)){const t=o.index;if(void 0!==t){const{element:n,error:o}=dp.getValidatedElement(t);if(!n)return vp(o||`Element ${t} not found`);if(!(await gp.showToolAction({element:n,explanation:r||`Execute ${e}`,browserToolName:e,isClickAction:"click_element"===e})))return vp("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 vp(`Unknown tool: ${e}`)}}catch(i){return gp.cleanup(),vp(i instanceof Error?i.message:String(i))}}navigate(e){return e.url?e.new_tab?(window.open(e.url,"_blank"),yp(`Opened ${e.url} in new tab`)):(window.location.href=e.url,yp(`Navigating to ${e.url}`)):vp("URL is required")}search(e){if(!e.query)return vp("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,yp(`Searching for "${e.query}" on ${t}`)}async clickElement(e){if(void 0===e.index)return vp("Index required");const{element:t,error:n}=dp.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),yp(`Clicked element ${e.index}`)):vp(n||`Element ${e.index} not found`)}typeText(e){if(void 0===e.index||void 0===e.text)return vp("Index and text required");const t=!1!==e.clear,{element:n,error:r}=dp.getValidatedElement(e.index);if(!n)return vp(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 vp(`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 vp(`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 vp(`Failed to set textContent: ${o instanceof Error?o.message:String(o)}`)}return yp(`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 vp("Invalid direction")}return yp(`Scrolled ${e.direction}`)}scrollToText(e){if(!e.text)return vp("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"}),yp(`Scrolled to "${e.text}"`);return vp(`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 bp(n)}goBack(){return window.history.length>1?(window.history.back(),yp("Navigated back")):vp("No history")}async wait({seconds:e}){return void 0===e?vp("Seconds required"):(await new Promise(t=>setTimeout(t,1e3*e)),yp(`Waited ${e}s`))}selectDropdownOption(e){if(void 0===e.index||!e.option)return vp("Index/Option required");const{element:t,error:n}=dp.getValidatedElement(e.index);if(!t)return vp(n||`Select ${e.index} not found`);if(!(t instanceof HTMLSelectElement))return vp(`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})),yp(`Selected ${e.option}`)):vp(`Option ${e.option} not found`)}getDropdownOptions(e){const t=e.index;if(void 0===t)return wp("Index required");const{element:n,error:r}=dp.getValidatedElement(t);if(!n)return wp(r||`Select ${t} not found`);if(!(n instanceof HTMLSelectElement))return wp(`Element ${t} is not a select element`);const o=Array.from(n.options).map(e=>({value:e.value,text:e.text}));return bp({options:o})}sendKeys(e){if(void 0===e.index||!e.keys)return vp("Index/Keys required");const{element:t,error:n}=dp.getValidatedElement(e.index);if(!t)return vp(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 yp(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 vp("File upload not supported via script")}closeTab(){return window.close(),yp("Attempted close")}done(e){if(void 0===e.success)return vp("success parameter is required");const t=e.message||(e.success?"Task completed":"Task failed");return yp(t)}getHtml(){try{const e=dp.getSnapshotHtml();return yp(e)}catch(e){return vp(String(e))}}async getScreenshot(){try{const e=await hp(),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(),yp(r)}catch(e){return vp(String(e))}}},kp=e=>({state:e,effects:[]});function Sp(e,t,n,r,o,i,s){const a=Qu({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=rp(e.parts,e=>"progress"===e.type&&e.browserToolName===t),o=r>=0?r:rp(e.parts,np);if(o<0)return e;const i=tp(e.parts[o].content);if(n.toLowerCase().includes("cancelled by cleanup"))return op(e,o,{status:"completed",content:i});const s=tp(n);return op(e,o,{status:"failed",content:s?`${i} (${s})`:i})}(c,r,s||""):"done"!==r&&(c="in_progress"===i?function(e,t,n){const r=tp(n),o=e.parts.findIndex(e=>np(e)&&e.browserToolName===t);return o>=0?op(e,o,{content:r}):{...e,parts:[...e.parts,{type:"progress",content:r,status:"in_progress",browserToolName:t}]}}(c,r,o||(e=>ip.get(e)??e)(r)):op(l=c,rp(l.parts,np),{status:"completed"})),t&&("show"===n||"do"===n)){const e="in_progress"===i&&"show"===n&&ep.has(r);c={...c,placeholderState:e?"waiting-for-user":"thinking"}}const d=[...e];return d[a.index]=c,d}var _p=e=>({...e,isPlaceholder:!1});function Ep(e,t,n){const r=Qu({messages:e.messages,isTaskRunning:e.task.isTaskRunning,currentMode:t}),o=[...e.messages];return r&&(o[r.index]=_p(n(r.message))),{messages:o,task:{isTaskRunning:!1}}}var Cp={completed:"done",failed:"failed",stopped:"stopped"};function Ip(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}}var Tp=(e,t)=>({..._p(e),content:t,placeholderState:void 0,parts:[...e.parts,{type:"text",content:t}]});function zp(e,t,n){const r=e.messages.map(e=>e.id===t?Tp(e,n):e);return{...e,messages:r}}var Mp=n(void 0),Op=({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(Mp.Provider,{value:{uiState:t,uiActions:r},children:e})},Rp=()=>{const e=s(Mp);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},Np=n(void 0),Ap=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Rp(),[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(Zu(e,i)),void m(qu("This is a preview. In production, I'll respond to your messages here."));const s=us.getConfig();if(!s||!s.mtxId&&!s.mtxKey&&!s.mtxApp)return void m(qu("Configuration error: Missing API credentials. Please check your widget settings."));o||m(Zu(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 Gu(s,e,i,a)}catch(c){f(e=>zp(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=Pc.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await xp.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:Sp(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 Ep(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))),!ip.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 Cp&&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:Sp(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 kp(e);const r=t.message?{content:t.message}:{},o=t.status;return{state:Ep(e,n,"has_question"===o?e=>({...e,placeholderState:"waiting-for-user",...r}):e=>({...e,taskStatus:Cp[o],...r})),effects:[]}}case"chat/delta":return{state:Ip(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:Ip(e,t.request_id,t.text,!1),effects:[{type:"setLoading",value:!1}]};case"chat/error":return{state:zp(e,t.request_id,`Error: ${t.error}`),effects:[{type:"setLoading",value:!1}]};default:return kp(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),e instanceof Ac&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Tp(e,t):e),task:{isTaskRunning:!1}}}(t,e.message))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const S=i(async()=>{f(e=>function(e,t){return Ep(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||Pc.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(Mp.Provider,{value:{uiState:t,uiActions:r},children:e})},Rp=()=>{const e=s(Mp);if(!e)throw new Error("useUIStateContext must be used within UIStateProvider");return e},Np=n(void 0),Ap=({children:e,previewMode:t=!1})=>{const{uiState:n,uiActions:r}=Rp(),[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(Zu(e,i)),void m(qu("This is a preview. In production, I'll respond to your messages here."));const s=us.getConfig();if(!s||!s.mtxId&&!s.mtxKey&&!s.mtxApp)return void m(qu("Configuration error: Missing API credentials. Please check your widget settings."));o||m(Zu(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),setTimeout(()=>{f(e=>function(e,t,n){const r=e.messages.find(e=>e.id===t);return r?.isPlaceholder&&"thinking"===r.placeholderState&&0===r.parts.length?zp(e,t,n):e}(e,a,"This is taking longer than expected. Please try again."))},12e4);try{await Gu(s,e,i,a)}catch(c){f(e=>zp(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=Pc.getInstance(),n=async t=>{const{toolCallId:n,tool:r,args:o,mode:i,explanation:s}=t,a=await xp.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:Sp(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 Ep(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))),!ip.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 Cp&&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:Sp(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 kp(e);const r=t.message?{content:t.message}:{},o=t.status;return{state:Ep(e,n,"has_question"===o?e=>({...e,placeholderState:"waiting-for-user",...r}):e=>({...e,taskStatus:Cp[o],...r})),effects:[]}}case"chat/delta":return{state:Ip(e,t.request_id,t.text,!0),effects:[]};case"chat/response":return{state:Ip(e,t.request_id,t.text,!1),effects:[{type:"setLoading",value:!1}]};case"chat/error":return{state:zp(e,t.request_id,`Error: ${t.error}`),effects:[{type:"setLoading",value:!1}]};default:return kp(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),e instanceof Ac&&f(t=>function(e,t){return{messages:e.messages.map(e=>e.isPlaceholder?Tp(e,t):e),task:{isTaskRunning:!1}}}(t,e.message))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[t,f,r]);const S=i(async()=>{f(e=>function(e,t){return Ep(e,t,e=>({...e,taskStatus:"stopped"}))}(e,l.current)),t||Pc.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(Np.Provider,{value:{messages:o.messages,chatActions:_,taskState:o.task,taskActions:E},children:e})},Pp=()=>{const e=s(Np);if(!e)throw new Error("useChatContext must be used within ChatProvider");return e},$p=n(null),Dp=({previewMode:e})=>{const{uiState:t}=Rp(),{messages:n,taskState:r}=Pp();return a(()=>{if(e)return;const{currentMode:o,isOpen:i}=t;Bu.persist({messages:n,...r,currentMode:o,isOpen:i})},[e,n,r,t]),null},Lp=({children:e,previewMode:t})=>{const{uiActions:n}=Rp(),{chatActions:r,taskActions:o}=Pp();return a(()=>{if(t)return;let e=!1;return(async()=>{const t=await ps.getOrCreateChatId();if(e)return;const{messages:i,isTaskRunning:s,...a}=Bu.restore();n.applyState(a),r.setMessages(i),o.setTaskState(s),Pc.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(Dp,{previewMode:t})]})},jp=({children:e,previewMode:t=!1})=>/* @__PURE__ */g(Op,{children:/* @__PURE__ */g(Ap,{previewMode:t,children:/* @__PURE__ */g(Lp,{previewMode:t,children:e})})});function Fp(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 Up(e){return function(e){const t=Fp(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 Wp(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=Fp(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:e}var Bp={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280"};function Hp(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:Wp(e.widget_text_color,.6),foregroundFaint:Wp(e.widget_text_color,.4),border:e.widget_border_color,primary:e.widget_accent_color,primaryForeground:Up(e.widget_accent_color),primaryHover:Wp(e.widget_accent_color,.85),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:Wp(e.widget_secondary_color,.2),secondaryHover:Wp(e.widget_secondary_color,.3)},radius:"12px",motion:{durationAnimation:"300ms",durationFade:"200ms"}}}({...Bp,...t})}var Zp=n(null),qp=()=>{const e=s(Zp);if(!e)throw new Error("useWidgetConfig must be used within MarketrixWidget");return e},Vp=()=>{const{uiState:e,uiActions:t}=Rp(),{messages:n,chatActions:r,taskState:o,taskActions:s}=Pp(),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])}},Gp=20,Yp={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"}},Jp=e=>Yp[e]??Yp.bottom_right,Xp=e=>{const{vertical:t,horizontal:n}=Jp(e);return{[t]:"20px",[n]:"20px"}},Kp=(e,t,n,r,o)=>{const{vertical:i,horizontal:s}=Jp(e);return{x:"left"===s?Gp:t-Gp-r,y:"top"===i?Gp:n-Gp-o}},Qp="cubic-bezier(0.16, 1, 0.3, 1)";function eh({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,_=Kp(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=Kp(e,k,S,c.w,c.h),d=Kp(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 ${Qp}, top 600ms ${Qp}`,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=Kp(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(Yp)){const e=Kp(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 th=({onDrag:e})=>{const{isPreviewMode:t=!1,widget_accent_color:n,widget_background_color:r,widget_position:o,widget_position_z_index:i}=qp(),{state:s,actions:a}=Vp(),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}=eh({position:o,onDrag:e,isPreviewMode:t,wrapperRef:b}),C=(e=>Jp(e).classes)(o);/* @__PURE__ */
16
16
  return g(Iu,{ref:b,className:`${t?"absolute":"fixed"} ${w?"":C} ${v?"":"transition-transform duration-300 ease-in-out"}`,style:{zIndex:i,pointerEvents:c?"none":"auto",...t?Xp(o):{},...w},children:/* @__PURE__ */y(Iu,{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(Iu,{className:f,"aria-hidden":!0}),h&&!v&&/* @__PURE__ */g(xu,{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(xu,{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(Tu,{className:"w-full h-full items-center justify-center relative",children:/* @__PURE__ */y(Iu,{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:Wc.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})}),