@marketrix.ai/widget 3.2.183 → 3.2.195

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.
package/dist/widget.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import*as e from"react";import t,{createContext as n,createElement as r,forwardRef as i,useCallback as o,useContext as s,useEffect as a,useId as l,useLayoutEffect as c,useMemo as d,useRef as u,useState as p}from"react";import{createRoot as h}from"react-dom/client";import{Fragment as m,jsx as f,jsxs as g}from"react/jsx-runtime";var y=2147483002,w=2147483001,b=2147483005;function v(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 x(e){return function(e){const t=v(e);if(!t)return.5;const[n,r,i]=[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*i}(e)>.5?"#000000":"#ffffff"}function k(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=v(e);return n?`rgba(${n.r}, ${n.g}, ${n.b}, ${t})`:(e.includes("gradient")||e.includes("linear-gradient"),e)}function _(e,t){const n=v(e);if(!n)return e;const r=1-t;return i=Math.round(n.r*r),o=Math.round(n.g*r),s=Math.round(n.b*r),`#${[i,o,s].map(e=>e.toString(16).padStart(2,"0")).join("")}`;var i,o,s}var S=e=>e?e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):/* @__PURE__ */(new Date).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),C=e=>{switch(e){case"show":return"Show";case"tell":return"Tell";case"do":return"Do";default:return e}},I={widget_background_color:"#ffffff",widget_text_color:"#1f2937",widget_border_color:"#e5e7eb",widget_accent_color:"#3b82f6",widget_secondary_color:"#6b7280",widget_border_radius:"20px",widget_font_size:"14px",widget_width:"400px",widget_height:"600px",widget_shadow:"0 5px 40px 0 rgba(0, 0, 0, 0.3)",widget_animation_duration:"300ms",widget_fade_duration:"200ms"};function E(e){return{color:{background:e.widget_background_color,foreground:e.widget_text_color,foregroundMuted:k(e.widget_text_color,.6),foregroundFaint:k(e.widget_text_color,.4),border:e.widget_border_color,borderMuted:k(e.widget_border_color,.3),primary:e.widget_accent_color,primaryForeground:x(e.widget_accent_color),primaryHover:k(e.widget_accent_color,.85),primaryMuted:k(e.widget_accent_color,.3),secondary:e.widget_secondary_color,secondaryForeground:"#ffffff",secondaryBg:k(e.widget_secondary_color,.2),secondaryHover:k(e.widget_secondary_color,.3)},radius:e.widget_border_radius,shadow:e.widget_shadow,typography:{fontSizeBase:e.widget_font_size},motion:{durationAnimation:e.widget_animation_duration,durationFade:e.widget_fade_duration},size:{widgetWidth:e.widget_width,widgetHeight:e.widget_height}}}E(I);function A(e){return Array.isArray(e)?e:null==e?[]:[e]}var T="orpc",M=class extends Error{constructor(...e){super(...e),this.name="AbortError"}};function z(e){let t;return()=>{if(t)return t.result;const n=e();return t={result:n},n}}function O(){return globalThis["__@orpc/shared@1.13.9/otel/config__"]}function R(e,t={},n){return(O()?.tracer)?.startSpan(e,t,n)}function N(e,t,n={}){if(!e)return;const r=function(e){if(e instanceof Error){const t={message:e.message,name:e.name,stack:e.stack};return!("code"in e)||"string"!=typeof e.code&&"number"!=typeof e.code||(t.code=e.code),t}return{message:String(e)}}(t);e.recordException(r),n.signal?.aborted&&n.signal.reason===t||e.setStatus({code:2,message:r.message})}async function P({name:e,context:t,...n},r){const i=O()?.tracer;if(!i)return r();const o=async e=>{try{return await r(e)}catch(t){throw N(e,t,n),t}finally{e.end()}};return t?i.startActiveSpan(e,n,t,o):i.startActiveSpan(e,n,o)}async function L(e,t){const n=O();if(!e||!n)return t();const r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}function D(e){return!(!e||"object"!=typeof e)&&("next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator])}var $=Symbol.asyncDispose??Symbol.for("asyncDispose"),j=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=function(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}(async()=>{if(this.#e)return{done:!0,value:void 0};try{const t=await e();return t.done&&(this.#e=!0),t}catch(t){throw this.#e=!0,t}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n("next"))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n("return")),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n("throw")),e}async[$](){this.#e=!0,this.#t||(this.#t=!0,await this.#n("dispose"))}[Symbol.asyncIterator](){return this}};function F({name:e,...t},n){let r;return new j(async()=>{r??=R(e);try{const e=await L(r,()=>n.next());return r?.addEvent(e.done?"completed":"yielded"),e}catch(i){throw N(r,i,t),i}},async e=>{try{"next"!==e&&await L(r,()=>n.return?.())}catch(i){throw N(r,i,t),i}finally{r?.end()}})}function U(e,t,n){const r=(t,i)=>{const o=e[i];return o?o({...t,next:(e=t)=>r(e,i+1)}):n(t)};return r(t,0)}function B(e){if(e)return JSON.parse(e)}function W(e){return JSON.stringify(e)}function G(e){if(!e||"object"!=typeof e)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function H(e){return!!e&&("object"==typeof e||"function"==typeof e)}function Z(e,...t){return"function"==typeof e?e(...t):e}function V(e){return new Proxy(e,{get(e,t,n){const r=Reflect.get(e,t,n);return"then"!==t||"function"!=typeof r?r:new Proxy(r,{apply(t,n,r){if(2!==r.length||r.some(e=>{return!("function"==typeof(t=e)&&q.test(t.toString()));var t}))return Reflect.apply(t,n,r);let i=!0;r[0].call(n,V(new Proxy(e,{get:(e,t,n)=>{if(!i||"then"!==t)return Reflect.get(e,t,n);i=!1}})))}})}})}var q=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;var J={BAD_REQUEST:{status:400,message:"Bad Request"},UNAUTHORIZED:{status:401,message:"Unauthorized"},FORBIDDEN:{status:403,message:"Forbidden"},NOT_FOUND:{status:404,message:"Not Found"},METHOD_NOT_SUPPORTED:{status:405,message:"Method Not Supported"},NOT_ACCEPTABLE:{status:406,message:"Not Acceptable"},TIMEOUT:{status:408,message:"Request Timeout"},CONFLICT:{status:409,message:"Conflict"},PRECONDITION_FAILED:{status:412,message:"Precondition Failed"},PAYLOAD_TOO_LARGE:{status:413,message:"Payload Too Large"},UNSUPPORTED_MEDIA_TYPE:{status:415,message:"Unsupported Media Type"},UNPROCESSABLE_CONTENT:{status:422,message:"Unprocessable Content"},TOO_MANY_REQUESTS:{status:429,message:"Too Many Requests"},CLIENT_CLOSED_REQUEST:{status:499,message:"Client Closed Request"},INTERNAL_SERVER_ERROR:{status:500,message:"Internal Server Error"},NOT_IMPLEMENTED:{status:501,message:"Not Implemented"},BAD_GATEWAY:{status:502,message:"Bad Gateway"},SERVICE_UNAVAILABLE:{status:503,message:"Service Unavailable"},GATEWAY_TIMEOUT:{status:504,message:"Gateway Timeout"}};var Y=Symbol.for("__@orpc/client@1.13.9/error/ORPC_ERROR_CONSTRUCTORS__");globalThis[Y]??=/* @__PURE__ */new WeakSet;var K=globalThis[Y],Q=class extends Error{defined;code;status;data;constructor(e,...t){const n=function(e){return e[0]??{}}(t);if(void 0!==n.status&&!X(n.status))throw new Error("[ORPCError] Invalid error status code.");const r=function(e,t){return t||J[e]?.message||e}(e,n.message);super(r,n),this.code=e,this.status=function(e,t){return t??J[e]?.status??500}(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(K.has(this)){const t=function(e){return H(e)?Object.getPrototypeOf(e)?.constructor:null}(e);if(t&&K.has(t))return!0}return super[Symbol.hasInstance](e)}};function X(e){return e<200||e>=400}function ee(e){if(!G(e))return!1;const t=["defined","code","status","message","data"];return!Object.keys(e).some(e=>!t.includes(e))&&("defined"in e&&"boolean"==typeof e.defined&&"code"in e&&"string"==typeof e.code&&"status"in e&&"number"==typeof e.status&&X(e.status)&&"message"in e&&"string"==typeof e.message)}function te(e,t={}){return new Q(e.code,{...t,...e})}K.add(Q);var ne=class extends TypeError{},re=class extends TypeError{},ie=class extends Error{data;constructor(e){super(e?.message??"An error event was received",e),this.data=e?.data}};function oe(e){const t=e.replace(/\n+$/,"").split(/\n/),n={data:void 0,event:void 0,id:void 0,retry:void 0,comments:[]};for(const r of t){const e=r.indexOf(":"),t=-1===e?r:r.slice(0,e),i=-1===e?"":r.slice(e+1).replace(/^\s/,"");if(0===e)n.comments.push(i);else if("data"===t)n.data??="",n.data+=`${i}\n`;else if("event"===t)n.event=i;else if("id"===t)n.id=i;else if("retry"===t){const e=Number.parseInt(i);Number.isInteger(e)&&e>=0&&e.toString()===i&&(n.retry=e)}}return n.data=n.data?.replace(/\n$/,""),n}var se=class{constructor(e={}){this.options=e}incomplete="";feed(e){this.incomplete+=e;const t=this.incomplete.lastIndexOf("\n\n");if(-1===t)return;const n=this.incomplete.slice(0,t).split(/\n\n/);this.incomplete=this.incomplete.slice(t+2);for(const r of n){const e=oe(`${r}\n\n`);this.options.onEvent&&this.options.onEvent(e)}}end(){if(this.incomplete)throw new re("Event Iterator ended before complete")}},ae=class extends TransformStream{constructor(){let e;super({start(t){e=new se({onEvent:e=>{t.enqueue(e)}})},transform(t){e.feed(t)},flush(){e.end()}})}};function le(e){if(e.includes("\n"))throw new ne("Event's id must not contain a newline character")}function ce(e){if(!Number.isInteger(e)||e<0)throw new ne("Event's retry must be a integer and >= 0")}function de(e){if(e.includes("\n"))throw new ne("Event's comment must not contain a newline character")}function ue(e){let t="";return t+=function(e){let t="";for(const n of e??[])de(n),t+=`: ${n}\n`;return t}(e.comments),void 0!==e.event&&(!function(e){if(e.includes("\n"))throw new ne("Event's event must not contain a newline character")}(e.event),t+=`event: ${e.event}\n`),void 0!==e.retry&&(ce(e.retry),t+=`retry: ${e.retry}\n`),void 0!==e.id&&(le(e.id),t+=`id: ${e.id}\n`),t+=function(e){const t=e?.split(/\n/)??[];let n="";for(const r of t)n+=`data: ${r}\n`;return n}(e.data),t+="\n",t}var pe=Symbol("ORPC_EVENT_SOURCE_META");function he(e,t){if(void 0===t.id&&void 0===t.retry&&!t.comments?.length)return e;if(void 0!==t.id&&le(t.id),void 0!==t.retry&&ce(t.retry),void 0!==t.comments)for(const n of t.comments)de(n);return new Proxy(e,{get:(e,n,r)=>n===pe?t:Reflect.get(e,n,r)})}function me(e){return H(e)?Reflect.get(e,pe):void 0}function fe(e){const t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&"string"==typeof t[2])return function(e){try{return decodeURIComponent(e)}catch{return e}}(t[2]);const n=e.match(/filename="((?:\\"|[^"])*)"/i);return n&&"string"==typeof n[1]?n[1].replace(/\\"/g,'"'):void 0}function ge(e,t){const n=async e=>{let n=await t.error(e);if(n!==e){const t=me(e);t&&H(n)&&(n=he(n,t))}return n};return new j(async()=>{const{done:r,value:i}=await(async()=>{try{return await e.next()}catch(t){throw await n(t)}})();let o=await t.value(i,r);if(o!==i){const e=me(i);e&&H(o)&&(o=he(o,e))}return{done:r,value:o}},async()=>{try{await(e.return?.())}catch(t){throw await n(t)}})}function ye(e,t={}){const n=t.path??[];return V(new Proxy(async(...[t,r={}])=>await e.call(n,t,function(e){return{...e,context:e.context??{}}}(r)),{get:(r,i)=>"string"!=typeof i?Reflect.get(r,i):ye(e,{...t,path:[...n,i]})}))}function we(e,t={}){return P({name:"parse_standard_body",signal:t.signal},async()=>{const n=e.headers.get("content-disposition");if("string"==typeof n){const t=fe(n)??"blob",r=await e.blob();return new File([r],t,{type:r.type})}const r=e.headers.get("content-type");if(!r||r.startsWith("application/json"))return B(await e.text());if(r.startsWith("multipart/form-data"))return await e.formData();if(r.startsWith("application/x-www-form-urlencoded")){const t=await e.text();return new URLSearchParams(t)}if(r.startsWith("text/event-stream"))return function(e,t={}){const n=(e?.pipeThrough(new TextDecoderStream).pipeThrough(new ae))?.getReader();let r,i=!1;return new j(async()=>{r??=R("consume_event_iterator_stream");try{for(;;){if(void 0===n)return{done:!0,value:void 0};const{done:e,value:t}=await L(r,()=>n.read());if(e){if(i)throw new M("Stream was cancelled");return{done:!0,value:void 0}}switch(t.event){case"message":{let e=B(t.data);return H(e)&&(e=he(e,t)),r?.addEvent("message"),{done:!1,value:e}}case"error":{let e=new ie({data:B(t.data)});throw e=he(e,t),r?.addEvent("error"),e}case"done":{let e=B(t.data);return H(e)&&(e=he(e,t)),r?.addEvent("done"),{done:!0,value:e}}default:r?.addEvent("maybe_keepalive")}}}catch(e){throw e instanceof ie||N(r,e,t),e}},async e=>{try{"next"!==e&&(i=!0,r?.addEvent("cancelled")),await L(r,()=>n?.cancel())}catch(o){throw N(r,o,t),o}finally{r?.end()}})}(e.body,t);if(r.startsWith("text/plain"))return await e.text();const i=await e.blob();return new File([i],"blob",{type:i.type})})}function be(e,t,n={}){const r=t.get("content-disposition");var i;if(t.delete("content-type"),t.delete("content-disposition"),void 0!==e)return e instanceof Blob?(t.set("content-type",e.type),t.set("content-length",e.size.toString()),t.set("content-disposition",r??`inline; filename="${(i=e instanceof File?e.name:"blob").replace(/"/g,'\\"')}"; filename*=utf-8''${encodeURIComponent(i).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`),e):e instanceof FormData||e instanceof URLSearchParams?e:D(e)?(t.set("content-type","text/event-stream"),function(e,t={}){const n=t.eventIteratorKeepAliveEnabled??!0,r=t.eventIteratorKeepAliveInterval??5e3,i=t.eventIteratorKeepAliveComment??"",o=t.eventIteratorInitialCommentEnabled??!0,s=t.eventIteratorInitialComment??"";let a,l,c=!1;return new ReadableStream({start(e){l=R("stream_event_iterator"),o&&e.enqueue(ue({comments:[s]}))},async pull(t){try{n&&(a=setInterval(()=>{t.enqueue(ue({comments:[i]})),l?.addEvent("keepalive")},r));const o=await L(l,()=>e.next());if(clearInterval(a),c)return;const s=me(o.value);if(!o.done||void 0!==o.value||void 0!==s){const e=o.done?"done":"message";t.enqueue(ue({...s,event:e,data:W(o.value)})),l?.addEvent(e)}o.done&&(t.close(),l?.end())}catch(o){if(clearInterval(a),c)return;o instanceof ie?(t.enqueue(ue({...me(o),event:"error",data:W(o.data)})),l?.addEvent("error"),t.close()):(N(l,o),t.error(o)),l?.end()}},async cancel(){try{c=!0,clearInterval(a),l?.addEvent("cancelled"),await L(l,()=>e.return?.())}catch(t){throw N(l,t),t}finally{l?.end()}}}).pipeThrough(new TextEncoderStream)}(e,n)):(t.set("content-type","application/json"),W(e))}function ve(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):void 0!==t[n]?t[n]=[t[n],e]:t[n]=e}),t}function xe(e,t={}){const n=function(e,t=new Headers){for(const[n,r]of Object.entries(e))if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.append(n,r);return t}(e.headers),r=be(e.body,n,t);return new Request(e.url,{signal:e.signal,method:e.method,headers:n,body:r})}var ke=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(const t of this.plugins)t.init?.(e)}},_e=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new ke(n.plugins).init(n),this.interceptors=A(n.interceptors),this.clientInterceptors=A(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return P({name:`${T}.${e.join("/")}`,signal:n.signal},r=>(r?.setAttribute("rpc.system",T),r?.setAttribute("rpc.method",e.join(".")),D(t)&&(t=F({name:"consume_event_iterator_input",signal:n.signal},t)),U(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{const i=O();let o;const s=i?.trace.getActiveSpan()??r;s&&i&&(o=i?.trace.setSpan(i.context.active(),s));const a=await P({name:"encode_request",context:o},()=>this.codec.encode(e,t,n)),l=await U(this.clientInterceptors,{...n,input:t,path:e,request:a},({input:e,path:t,request:n,...r})=>P({name:"send_request",signal:r.signal,context:o},()=>this.sender.call(n,r,t,e))),c=await P({name:"decode_response",context:o},()=>this.codec.decode(l,n,e,t));return D(c)?F({name:"consume_event_iterator_output",signal:n.signal},c):c})))}},Se=0,Ce=1,Ie=2,Ee=3,Ae=4,Te=5,Me=6,ze=7,Oe=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw new Error("Custom serializer type must be unique.")}serialize(e,t=[],n=[],r=[],i=[]){for(const o of this.customSerializers)if(o.condition(e)){const s=this.serialize(o.serialize(e),t,n,r,i);return n.push([o.type,...t]),s}if(e instanceof Blob)return r.push(t),i.push(e),[e,n,r,i];if("bigint"==typeof e)return n.push([Se,...t]),[e.toString(),n,r,i];if(e instanceof Date)return n.push([Ce,...t]),Number.isNaN(e.getTime())?[null,n,r,i]:[e.toISOString(),n,r,i];if(Number.isNaN(e))return n.push([Ie,...t]),[null,n,r,i];if(e instanceof URL)return n.push([Ae,...t]),[e.toString(),n,r,i];if(e instanceof RegExp)return n.push([Te,...t]),[e.toString(),n,r,i];if(e instanceof Set){const o=this.serialize(Array.from(e),t,n,r,i);return n.push([Me,...t]),o}if(e instanceof Map){const o=this.serialize(Array.from(e.entries()),t,n,r,i);return n.push([ze,...t]),o}if(Array.isArray(e))return[e.map((e,o)=>void 0===e?(n.push([Ee,...t,o]),e):this.serialize(e,[...t,o],n,r,i)[0]),n,r,i];if(G(e)){const o={};for(const s in e)"toJSON"===s&&"function"==typeof e[s]||(o[s]=this.serialize(e[s],[...t,s],n,r,i)[0]);return[o,n,r,i]}return[e,n,r,i]}deserialize(e,t,n,r){const i={data:e};n&&r&&n.forEach((e,t)=>{let n=i,o="data";e.forEach(e=>{if(n=n[o],o=e,!Object.hasOwn(n,o))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${o}`)}),n[o]=r(t)});for(const o of t){const e=o[0];let t=i,n="data";for(let r=1;r<o.length;r++)if(t=t[n],n=o[r],!Object.hasOwn(t,n))throw new Error(`Security error: accessing non-existent path during deserialization. Path segment: ${n}`);for(const r of this.customSerializers)if(r.type===e){t[n]=r.deserialize(t[n]);break}switch(e){case Se:t[n]=BigInt(t[n]);break;case Ce:t[n]=new Date(t[n]??"Invalid Date");break;case Ie:t[n]=NaN;break;case Ee:t[n]=void 0;break;case Ae:t[n]=new URL(t[n]);break;case Te:{const[,e,r]=t[n].match(/^\/(.*)\/([a-z]*)$/);t[n]=new RegExp(e,r);break}case Me:t[n]=new Set(t[n]);break;case ze:t[n]=new Map(t[n])}}return i.data}};var Re=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??"POST",this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=function(e){return"function"==typeof e.forEach?ve(e):e}(await Z(this.headers,n,e,t));void 0!==n.lastEventId&&(r=function(e,t){const n={...e};for(const r in t)Array.isArray(t[r])?n[r]=[...A(n[r]),...t[r]]:void 0!==t[r]&&(Array.isArray(n[r])?n[r]=[...n[r],t[r]]:void 0!==n[r]?n[r]=[n[r],t[r]]:n[r]=t[r]);return n}(r,{"last-event-id":n.lastEventId}));const i=await Z(this.expectedMethod,n,e,t),o=await Z(this.baseUrl,n,e,t),s=new URL(o);s.pathname=`${s.pathname.replace(/\/$/,"")}${function(e){return`/${e.map(encodeURIComponent).join("/")}`}(e)}`;const a=this.serializer.serialize(t);if(!("GET"!==i||a instanceof FormData||D(a))){const o=await Z(this.maxUrlLength,n,e,t),l=new URL(s);if(l.searchParams.append("data",W(a)),l.toString().length<=o)return{body:void 0,method:i,headers:r,url:l,signal:n.signal}}return{url:s,method:"GET"===i?this.fallbackMethod:i,headers:r,body:a,signal:n.signal}}async decode(e){const t=!X(e.status),n=await(async()=>{let t=!1;try{const n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(n){if(!t)throw new Error("Cannot parse response body, please check the response body and content-type.",{cause:n});throw new Error("Invalid RPC response format.",{cause:n})}})();if(!t){if(ee(n))throw te(n);throw new Q((r=e.status,Object.entries(J).find(([,e])=>e.status===r)?.[0]??"MALFORMED_ORPC_ERROR_RESPONSE"),{status:e.status,data:{...e,body:n}})}var r;return n}},Ne=class{constructor(e){this.jsonSerializer=e}serialize(e){return D(e)?ge(e,{value:async e=>this.#i(e,!1),error:async e=>{return new ie({data:this.#i((t=e,t instanceof Q?t:new Q("INTERNAL_SERVER_ERROR",{message:"Internal server error",cause:t})).toJSON(),!1),cause:e});var t}}):this.#i(e,!0)}#i(e,t){const[n,r,i,o]=this.jsonSerializer.serialize(e),s=0===r.length?void 0:r;if(!t||0===o.length)return{json:n,meta:s};const a=new FormData;return a.set("data",W({json:n,meta:s,maps:i})),o.forEach((e,t)=>{a.set(t.toString(),e)}),a}deserialize(e){return D(e)?ge(e,{value:async e=>this.#o(e),error:async e=>{if(!(e instanceof ie))return e;const t=this.#o(e.data);return ee(t)?te(t,{cause:e}):new ie({data:t,cause:e})}}):this.#o(e)}#o(e){if(void 0===e)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);const t=JSON.parse(e.get("data"));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},Pe=class extends _e{constructor(e,t){super(new Re(new Ne(new Oe(t)),t),e,t)}},Le=class extends ke{initRuntimeAdapter(e){for(const t of this.plugins)t.initRuntimeAdapter?.(e)}},De=class{fetch;toFetchRequestOptions;adapterInterceptors;constructor(e){new Le(e.plugins).initRuntimeAdapter(e),this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.toFetchRequestOptions=e,this.adapterInterceptors=A(e.adapterInterceptors)}async call(e,t,n,r){const i=xe(e,this.toFetchRequestOptions);return function(e,t={}){return{body:z(()=>we(e,t)),status:e.status,get headers(){const t=ve(e.headers);return Object.defineProperty(this,"headers",{value:t,writable:!0}),t},set headers(e){Object.defineProperty(this,"headers",{value:e,writable:!0})}}}(await U(this.adapterInterceptors,{...t,request:i,path:n,input:r,init:{redirect:"manual"}},({request:e,path:t,input:n,init:r,...i})=>this.fetch(e,r,i,t,n)),{signal:i.signal})}},$e=class extends Pe{constructor(e){super(new De(e),e)}};Object.freeze({status:"aborted"});function je(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:s,traits:/* @__PURE__ */new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);const i=s.prototype,o=Object.keys(i);for(let e=0;e<o.length;e++){const t=o[e];t in n||(n[t]=i[t].bind(n))}}const i=n?.Parent??Object;class o extends i{}function s(e){var t;const i=n?.Parent?new o:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(const n of i._zod.deferred)n();return i}return Object.defineProperty(o,"name",{value:e}),Object.defineProperty(s,"init",{value:r}),Object.defineProperty(s,Symbol.hasInstance,{value:t=>!!(n?.Parent&&t instanceof n.Parent)||t?._zod?.traits?.has(e)}),Object.defineProperty(s,"name",{value:e}),s}var Fe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ue=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},Be={};function We(e){return e&&Object.assign(Be,e),Be}function Ge(e){const t=Object.values(e).filter(e=>"number"==typeof e);return Object.entries(e).filter(([e,n])=>-1===t.indexOf(+e)).map(([e,t])=>t)}function He(e,t){return"bigint"==typeof t?t.toString():t}function Ze(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ve(e){return null==e}function qe(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}var Je=Symbol("evaluating");function Ye(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Je)return void 0===r&&(r=Je,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ke(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Qe(...e){const t={};for(const n of e)Object.assign(t,Object.getOwnPropertyDescriptors(n));return Object.defineProperties({},t)}function Xe(e){return JSON.stringify(e)}var et="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function tt(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}var nt=Ze(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function rt(e){if(!1===tt(e))return!1;const t=e.constructor;if(void 0===t)return!0;if("function"!=typeof t)return!0;const n=t.prototype;return!1!==tt(n)&&!1!==Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")}function it(e){return rt(e)?{...e}:Array.isArray(e)?[...e]:e}var ot=new Set(["string","number","symbol"]);function st(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function at(e,t,n){const r=new e._zod.constr(t??e._zod.def);return t&&!n?.parent||(r._zod.parent=e),r}function lt(e){const t=e;if(!t)return{};if("string"==typeof t)return{error:()=>t};if(void 0!==t?.message){if(void 0!==t?.error)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,"string"==typeof t.error?{...t,error:()=>t.error}:t}var ct={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function dt(e,t=0){if(!0===e.aborted)return!0;for(let n=t;n<e.issues.length;n++)if(!0!==e.issues[n]?.continue)return!0;return!1}function ut(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function pt(e){return"string"==typeof e?e:e?.message}function ht(e,t,n){const r={...e,path:e.path??[]};return e.message||(r.message=pt(e.inst?._zod.def?.error?.(e))??pt(t?.error?.(e))??pt(n.customError?.(e))??pt(n.localeError?.(e))??"Invalid input"),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function mt(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"unknown"}function ft(...e){const[t,n,r]=e;return"string"==typeof t?{message:t,code:"custom",input:n,inst:r}:{...t}}var gt=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,He,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},yt=je("$ZodError",gt),wt=je("$ZodError",gt,{Parent:Error});var bt=e=>(t,n,r,i)=>{const o=r?Object.assign(r,{async:!1}):{async:!1},s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Fe;if(s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>ht(e,o,We())));throw et(t,i?.callee),t}return s.value},vt=e=>async(t,n,r,i)=>{const o=r?Object.assign(r,{async:!0}):{async:!0};let s=t._zod.run({value:n,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){const t=new(i?.Err??e)(s.issues.map(e=>ht(e,o,We())));throw et(t,i?.callee),t}return s.value},xt=e=>(t,n,r)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Fe;return o.issues.length?{success:!1,error:new(e??yt)(o.issues.map(e=>ht(e,i,We())))}:{success:!0,data:o.value}},kt=/* @__PURE__ */xt(wt),_t=e=>async(t,n,r)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let o=t._zod.run({value:n,issues:[]},i);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new e(o.issues.map(e=>ht(e,i,We())))}:{success:!0,data:o.value}},St=/* @__PURE__ */_t(wt),Ct=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return bt(e)(t,n,i)},It=e=>(t,n,r)=>bt(e)(t,n,r),Et=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return vt(e)(t,n,i)},At=e=>async(t,n,r)=>vt(e)(t,n,r),Tt=e=>(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return xt(e)(t,n,i)},Mt=e=>(t,n,r)=>xt(e)(t,n,r),zt=e=>async(t,n,r)=>{const i=r?Object.assign(r,{direction:"backward"}):{direction:"backward"};return _t(e)(t,n,i)},Ot=e=>async(t,n,r)=>_t(e)(t,n,r),Rt=/^[cC][^\s-]{8,}$/,Nt=/^[0-9a-z]+$/,Pt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lt=/^[0-9a-vA-V]{20}$/,Dt=/^[A-Za-z0-9]{27}$/,$t=/^[a-zA-Z0-9_-]{21}$/,jt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ft=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ut=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Bt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Wt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Gt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Ht=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Zt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,qt=/^[A-Za-z0-9_-]*$/,Jt=/^\+[1-9]\d{6,14}$/,Yt="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Kt=/* @__PURE__ */new RegExp(`^${Yt}$`);function Qt(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof e.precision?-1===e.precision?`${t}`:0===e.precision?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}var Xt=/^-?\d+$/,en=/^-?\d+(?:\.\d+)?$/,tn=/^(?:true|false)$/i,nn=/^null$/i,rn=/^[^A-Z]*$/,on=/^[^a-z]*$/,sn=/* @__PURE__ */je("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),an={number:"number",bigint:"bigint",object:"date"},ln=/* @__PURE__ */je("$ZodCheckLessThan",(e,t)=>{sn.init(e,t);const n=an[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),cn=/* @__PURE__ */je("$ZodCheckGreaterThan",(e,t)=>{sn.init(e,t);const n=an[typeof t.value];e._zod.onattach.push(e=>{const n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:"object"==typeof t.value?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),dn=/* @__PURE__ */je("$ZodCheckMultipleOf",(e,t)=>{sn.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof n.value?n.value%t.value!==BigInt(0):0!==function(e,t){const n=(e.toString().split(".")[1]||"").length,r=t.toString();let i=(r.split(".")[1]||"").length;if(0===i&&/\d?e-\d?/.test(r)){const e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}const o=n>i?n:i;return Number.parseInt(e.toFixed(o).replace(".",""))%Number.parseInt(t.toFixed(o).replace(".",""))/10**o}(n.value,t.value))&&n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),un=/* @__PURE__ */je("$ZodCheckNumberFormat",(e,t)=>{sn.init(e,t),t.format=t.format||"float64";const n=t.format?.includes("int"),r=n?"int":"number",[i,o]=ct[t.format];e._zod.onattach.push(e=>{const r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=o,n&&(r.pattern=Xt)}),e._zod.check=s=>{const a=s.value;if(n){if(!Number.isInteger(a))return void s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});if(!Number.isSafeInteger(a))return void(a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}))}a<i&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:e,continue:!t.abort})}}),pn=/* @__PURE__ */je("$ZodCheckMaxLength",(e,t)=>{var n;sn.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ve(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{const r=n.value;if(r.length<=t.maximum)return;const i=mt(r);n.issues.push({origin:i,code:"too_big",maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),hn=/* @__PURE__ */je("$ZodCheckMinLength",(e,t)=>{var n;sn.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ve(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{const r=n.value;if(r.length>=t.minimum)return;const i=mt(r);n.issues.push({origin:i,code:"too_small",minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),mn=/* @__PURE__ */je("$ZodCheckLengthEquals",(e,t)=>{var n;sn.init(e,t),(n=e._zod.def).when??(n.when=e=>{const t=e.value;return!Ve(t)&&void 0!==t.length}),e._zod.onattach.push(e=>{const n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{const r=n.value,i=r.length;if(i===t.length)return;const o=mt(r),s=i>t.length;n.issues.push({origin:o,...s?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),fn=/* @__PURE__ */je("$ZodCheckStringFormat",(e,t)=>{var n,r;sn.init(e,t),e._zod.onattach.push(e=>{const n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=/* @__PURE__ */new Set),n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),gn=/* @__PURE__ */je("$ZodCheckRegex",(e,t)=>{fn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),yn=/* @__PURE__ */je("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=rn),fn.init(e,t)}),wn=/* @__PURE__ */je("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=on),fn.init(e,t)}),bn=/* @__PURE__ */je("$ZodCheckIncludes",(e,t)=>{sn.init(e,t);const n=st(t.includes),r=new RegExp("number"==typeof t.position?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),vn=/* @__PURE__ */je("$ZodCheckStartsWith",(e,t)=>{sn.init(e,t);const n=new RegExp(`^${st(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),xn=/* @__PURE__ */je("$ZodCheckEndsWith",(e,t)=>{sn.init(e,t);const n=new RegExp(`.*${st(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(e=>{const t=e._zod.bag;t.patterns??(t.patterns=/* @__PURE__ */new Set),t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),kn=/* @__PURE__ */je("$ZodCheckOverwrite",(e,t)=>{sn.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),_n=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if("function"==typeof e)return e(this,{execution:"sync"}),void e(this,{execution:"async"});const t=e.split("\n").filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>" ".repeat(2*this.indent)+e);for(const i of r)this.content.push(i)}compile(){const e=Function,t=this?.args,n=[...(this?.content??[""]).map(e=>` ${e}`)];return new e(...t,n.join("\n"))}},Sn={major:4,minor:3,patch:6},Cn=/* @__PURE__ */je("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Sn;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const t of i._zod.onattach)t(e);if(0===r.length)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const t=(e,t,n)=>{let r,i=dt(e);for(const o of t){if(o._zod.def.when){if(!o._zod.def.when(e))continue}else if(i)continue;const t=e.issues.length,s=o._zod.check(e);if(s instanceof Promise&&!1===n?.async)throw new Fe;if(r||s instanceof Promise)r=(r??Promise.resolve()).then(async()=>{await s,e.issues.length!==t&&(i||(i=dt(e,t)))});else{if(e.issues.length===t)continue;i||(i=dt(e,t))}}return r?r.then(()=>e):e},n=(n,i,o)=>{if(dt(n))return n.aborted=!0,n;const s=t(i,r,o);if(s instanceof Promise){if(!1===o.async)throw new Fe;return s.then(t=>e._zod.parse(t,o))}return e._zod.parse(s,o)};e._zod.run=(i,o)=>{if(o.skipChecks)return e._zod.parse(i,o);if("backward"===o.direction){const t=e._zod.parse({value:i.value,issues:[]},{...o,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,o)):n(t,i,o)}const s=e._zod.parse(i,o);if(s instanceof Promise){if(!1===o.async)throw new Fe;return s.then(e=>t(e,r,o))}return t(s,r,o)}}Ye(e,"~standard",()=>({validate:t=>{try{const n=kt(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch(n){return St(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),In=/* @__PURE__ */je("$ZodString",(e,t)=>{var n;Cn.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??(n=e._zod.bag,new RegExp(`^${n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*"}$`)),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(r){}return"string"==typeof n.value||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),En=/* @__PURE__ */je("$ZodStringFormat",(e,t)=>{fn.init(e,t),In.init(e,t)}),An=/* @__PURE__ */je("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Ft),En.init(e,t)}),Tn=/* @__PURE__ */je("$ZodUUID",(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(void 0===e)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Ut(e))}else t.pattern??(t.pattern=Ut());En.init(e,t)}),Mn=/* @__PURE__ */je("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=Bt),En.init(e,t)}),zn=/* @__PURE__ */je("$ZodURL",(e,t)=>{En.init(e,t),e._zod.check=n=>{try{const r=n.value.trim(),i=new URL(r);return t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),void(t.normalize?n.value=i.href:n.value=r)}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),On=/* @__PURE__ */je("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),En.init(e,t)}),Rn=/* @__PURE__ */je("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=$t),En.init(e,t)}),Nn=/* @__PURE__ */je("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Rt),En.init(e,t)}),Pn=/* @__PURE__ */je("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Nt),En.init(e,t)}),Ln=/* @__PURE__ */je("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Pt),En.init(e,t)}),Dn=/* @__PURE__ */je("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Lt),En.init(e,t)}),$n=/* @__PURE__ */je("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Dt),En.init(e,t)}),jn=/* @__PURE__ */je("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=function(e){const t=Qt({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Yt}T(?:${r})$`)}(t)),En.init(e,t)}),Fn=/* @__PURE__ */je("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Kt),En.init(e,t)}),Un=/* @__PURE__ */je("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=new RegExp(`^${Qt(t)}$`)),En.init(e,t)}),Bn=/* @__PURE__ */je("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=jt),En.init(e,t)}),Wn=/* @__PURE__ */je("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Wt),En.init(e,t),e._zod.bag.format="ipv4"}),Gn=/* @__PURE__ */je("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Gt),En.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),Hn=/* @__PURE__ */je("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Ht),En.init(e,t)}),Zn=/* @__PURE__ */je("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Zt),En.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(2!==r.length)throw new Error;const[e,t]=r;if(!t)throw new Error;const n=Number(t);if(`${n}`!==t)throw new Error;if(n<0||n>128)throw new Error;new URL(`http://[${e}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function Vn(e){if(""===e)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var qn=/* @__PURE__ */je("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Vt),En.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{Vn(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});var Jn=/* @__PURE__ */je("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=qt),En.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{(function(e){if(!qt.test(e))return!1;const t=e.replace(/[-_]/g,e=>"-"===e?"+":"/");return Vn(t.padEnd(4*Math.ceil(t.length/4),"="))})(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Yn=/* @__PURE__ */je("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Jt),En.init(e,t)});var Kn=/* @__PURE__ */je("$ZodJWT",(e,t)=>{En.init(e,t),e._zod.check=n=>{(function(e,t=null){try{const n=e.split(".");if(3!==n.length)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&"JWT"!==i?.typ||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}})(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),Qn=/* @__PURE__ */je("$ZodNumber",(e,t)=>{Cn.init(e,t),e._zod.pattern=e._zod.bag.pattern??en,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}const i=n.value;if("number"==typeof i&&!Number.isNaN(i)&&Number.isFinite(i))return n;const o="number"==typeof i?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...o?{received:o}:{}}),n}}),Xn=/* @__PURE__ */je("$ZodNumberFormat",(e,t)=>{un.init(e,t),Qn.init(e,t)}),er=/* @__PURE__ */je("$ZodBoolean",(e,t)=>{Cn.init(e,t),e._zod.pattern=tn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(o){}const i=n.value;return"boolean"==typeof i||n.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),n}}),tr=/* @__PURE__ */je("$ZodNull",(e,t)=>{Cn.init(e,t),e._zod.pattern=nn,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{const r=t.value;return null===r||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:e}),t}}),nr=/* @__PURE__ */je("$ZodUnknown",(e,t)=>{Cn.init(e,t),e._zod.parse=e=>e}),rr=/* @__PURE__ */je("$ZodNever",(e,t)=>{Cn.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:e}),t)}),ir=/* @__PURE__ */je("$ZodDate",(e,t)=>{Cn.init(e,t),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=new Date(n.value)}catch(s){}const i=n.value,o=i instanceof Date;return o&&!Number.isNaN(i.getTime())||n.issues.push({expected:"date",code:"invalid_type",input:i,...o?{received:"Invalid Date"}:{},inst:e}),n}});function or(e,t,n){e.issues.length&&t.issues.push(...ut(n,e.issues)),t.value[n]=e.value}var sr=/* @__PURE__ */je("$ZodArray",(e,t)=>{Cn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=Array(i.length);const o=[];for(let e=0;e<i.length;e++){const s=i[e],a=t.element._zod.run({value:s,issues:[]},r);a instanceof Promise?o.push(a.then(t=>or(t,n,e))):or(a,n,e)}return o.length?Promise.all(o).then(()=>n):n}});function ar(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...ut(n,e.issues))}void 0===e.value?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function lr(e){const t=Object.keys(e.shape);for(const i of t)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const n=(r=e.shape,Object.keys(r).filter(e=>"optional"===r[e]._zod.optin&&"optional"===r[e]._zod.optout));var r;return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function cr(e,t,n,r,i,o){const s=[],a=i.keySet,l=i.catchall._zod,c=l.def.type,d="optional"===l.optout;for(const u in t){if(a.has(u))continue;if("never"===c){s.push(u);continue}const i=l.run({value:t[u],issues:[]},r);i instanceof Promise?e.push(i.then(e=>ar(e,n,u,t,d))):ar(i,n,u,t,d)}return s.length&&n.issues.push({code:"unrecognized_keys",keys:s,input:t,inst:o}),e.length?Promise.all(e).then(()=>n):n}var dr=/* @__PURE__ */je("$ZodObject",(e,t)=>{if(Cn.init(e,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const e=t.shape;Object.defineProperty(t,"shape",{get:()=>{const n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}const n=Ze(()=>lr(t));Ye(e._zod,"propValues",()=>{const e=t.shape,n={};for(const t in e){const r=e[t]._zod;if(r.values){n[t]??(n[t]=/* @__PURE__ */new Set);for(const e of r.values)n[t].add(e)}}return n});const r=tt,i=t.catchall;let o;e._zod.parse=(t,s)=>{o??(o=n.value);const a=t.value;if(!r(a))return t.issues.push({expected:"object",code:"invalid_type",input:a,inst:e}),t;t.value={};const l=[],c=o.shape;for(const e of o.keys){const n=c[e],r="optional"===n._zod.optout,i=n._zod.run({value:a[e],issues:[]},s);i instanceof Promise?l.push(i.then(n=>ar(n,t,e,a,r))):ar(i,t,e,a,r)}return i?cr(l,a,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),ur=/* @__PURE__ */je("$ZodObjectJIT",(e,t)=>{dr.init(e,t);const n=e._zod.parse,r=Ze(()=>lr(t));let i;const o=tt,s=!Be.jitless,a=s&&nt.value,l=t.catchall;let c;e._zod.parse=(d,u)=>{c??(c=r.value);const p=d.value;return o(p)?s&&a&&!1===u?.async&&!0!==u.jitless?(i||(i=(e=>{const t=new _n(["shape","payload","ctx"]),n=r.value,i=e=>{const t=Xe(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write("const input = payload.value;");const o=Object.create(null);let s=0;for(const r of n.keys)o[r]="key_"+s++;t.write("const newResult = {};");for(const r of n.keys){const n=o[r],s=Xe(r),a="optional"===e[r]?._zod?.optout;t.write(`const ${n} = ${i(r)};`),a?t.write(`\n if (${n}.issues.length) {\n if (${s} in input) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `):t.write(`\n if (${n}.issues.length) {\n payload.issues = payload.issues.concat(${n}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${s}, ...iss.path] : [${s}]\n })));\n }\n \n if (${n}.value === undefined) {\n if (${s} in input) {\n newResult[${s}] = undefined;\n }\n } else {\n newResult[${s}] = ${n}.value;\n }\n \n `)}t.write("payload.value = newResult;"),t.write("return payload;");const a=t.compile();return(t,n)=>a(e,t,n)})(t.shape)),d=i(d,u),l?cr([],p,d,u,c,e):d):n(d,u):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),d)}});function pr(e,t,n,r){for(const o of e)if(0===o.issues.length)return t.value=o.value,t;const i=e.filter(e=>!dt(e));return 1===i.length?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>ht(e,r,We())))}),t)}var hr=/* @__PURE__ */je("$ZodUnion",(e,t)=>{Cn.init(e,t),Ye(e._zod,"optin",()=>t.options.some(e=>"optional"===e._zod.optin)?"optional":void 0),Ye(e._zod,"optout",()=>t.options.some(e=>"optional"===e._zod.optout)?"optional":void 0),Ye(e._zod,"values",()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),Ye(e._zod,"pattern",()=>{if(t.options.every(e=>e._zod.pattern)){const e=t.options.map(e=>e._zod.pattern);return new RegExp(`^(${e.map(e=>qe(e.source)).join("|")})$`)}});const n=1===t.options.length,r=t.options[0]._zod.run;e._zod.parse=(i,o)=>{if(n)return r(i,o);let s=!1;const a=[];for(const e of t.options){const t=e._zod.run({value:i.value,issues:[]},o);if(t instanceof Promise)a.push(t),s=!0;else{if(0===t.issues.length)return t;a.push(t)}}return s?Promise.all(a).then(t=>pr(t,i,e,o)):pr(a,i,e,o)}}),mr=/* @__PURE__ */je("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,hr.init(e,t);const n=e._zod.parse;Ye(e._zod,"propValues",()=>{const e={};for(const n of t.options){const r=n._zod.propValues;if(!r||0===Object.keys(r).length)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(n)}"`);for(const[t,n]of Object.entries(r)){e[t]||(e[t]=/* @__PURE__ */new Set);for(const r of n)e[t].add(r)}}return e});const r=Ze(()=>{const e=t.options,n=/* @__PURE__ */new Map;for(const r of e){const e=r._zod.propValues?.[t.discriminator];if(!e||0===e.size)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(const t of e){if(n.has(t))throw new Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,o)=>{const s=i.value;if(!tt(s))return i.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),i;const a=r.value.get(s?.[t.discriminator]);return a?a._zod.run(i,o):t.unionFallback?n(i,o):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:s,path:[t.discriminator],inst:e}),i)}}),fr=/* @__PURE__ */je("$ZodIntersection",(e,t)=>{Cn.init(e,t),e._zod.parse=(e,n)=>{const r=e.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([t,n])=>yr(e,t,n)):yr(e,i,o)}});function gr(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(rt(e)&&rt(t)){const n=Object.keys(t),r=Object.keys(e).filter(e=>-1!==n.indexOf(e)),i={...e,...t};for(const o of r){const n=gr(e[o],t[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};i[o]=n.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=gr(e[r],t[r]);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function yr(e,t,n){const r=/* @__PURE__ */new Map;let i;for(const a of t.issues)if("unrecognized_keys"===a.code){i??(i=a);for(const e of a.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(a);for(const a of n.issues)if("unrecognized_keys"===a.code)for(const e of a.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(a);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length&&i&&e.issues.push({...i,keys:o}),dt(e))return e;const s=gr(t.value,n.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return e.value=s.data,e}var wr=/* @__PURE__ */je("$ZodRecord",(e,t)=>{Cn.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!rt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const o=[],s=t.keyType._zod.values;if(s){n.value={};const a=/* @__PURE__ */new Set;for(const e of s)if("string"==typeof e||"number"==typeof e||"symbol"==typeof e){a.add("number"==typeof e?e.toString():e);const s=t.valueType._zod.run({value:i[e],issues:[]},r);s instanceof Promise?o.push(s.then(t=>{t.issues.length&&n.issues.push(...ut(e,t.issues)),n.value[e]=t.value})):(s.issues.length&&n.issues.push(...ut(e,s.issues)),n.value[e]=s.value)}let l;for(const e in i)a.has(e)||(l=l??[],l.push(e));l&&l.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l})}else{n.value={};for(const s of Reflect.ownKeys(i)){if("__proto__"===s)continue;let a=t.keyType._zod.run({value:s,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if("string"==typeof s&&en.test(s)&&a.issues.length){const e=t.keyType._zod.run({value:Number(s),issues:[]},r);if(e instanceof Promise)throw new Error("Async schemas not supported in object keys currently");0===e.issues.length&&(a=e)}if(a.issues.length){"loose"===t.mode?n.value[s]=i[s]:n.issues.push({code:"invalid_key",origin:"record",issues:a.issues.map(e=>ht(e,r,We())),input:s,path:[s],inst:e});continue}const l=t.valueType._zod.run({value:i[s],issues:[]},r);l instanceof Promise?o.push(l.then(e=>{e.issues.length&&n.issues.push(...ut(s,e.issues)),n.value[a.value]=e.value})):(l.issues.length&&n.issues.push(...ut(s,l.issues)),n.value[a.value]=l.value)}}return o.length?Promise.all(o).then(()=>n):n}}),br=/* @__PURE__ */je("$ZodEnum",(e,t)=>{Cn.init(e,t);const n=Ge(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(e=>ot.has(typeof e)).map(e=>"string"==typeof e?st(e):e.toString()).join("|")})$`),e._zod.parse=(t,i)=>{const o=t.value;return r.has(o)||t.issues.push({code:"invalid_value",values:n,input:o,inst:e}),t}}),vr=/* @__PURE__ */je("$ZodLiteral",(e,t)=>{if(Cn.init(e,t),0===t.values.length)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(e=>"string"==typeof e?st(e):e?st(e.toString()):String(e)).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:t.values,input:o,inst:e}),r}}),xr=/* @__PURE__ */je("$ZodTransform",(e,t)=>{Cn.init(e,t),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ue(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Fe;return n.value=i,n}});function kr(e,t){return e.issues.length&&void 0===t?{issues:[],value:void 0}:e}var _r=/* @__PURE__ */je("$ZodOptional",(e,t)=>{Cn.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Ye(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Ye(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${qe(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if("optional"===t.innerType._zod.optin){const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(t=>kr(t,e.value)):kr(r,e.value)}return void 0===e.value?e:t.innerType._zod.run(e,n)}}),Sr=/* @__PURE__ */je("$ZodExactOptional",(e,t)=>{_r.init(e,t),Ye(e._zod,"values",()=>t.innerType._zod.values),Ye(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Cr=/* @__PURE__ */je("$ZodNullable",(e,t)=>{Cn.init(e,t),Ye(e._zod,"optin",()=>t.innerType._zod.optin),Ye(e._zod,"optout",()=>t.innerType._zod.optout),Ye(e._zod,"pattern",()=>{const e=t.innerType._zod.pattern;return e?new RegExp(`^(${qe(e.source)}|null)$`):void 0}),Ye(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>null===e.value?e:t.innerType._zod.run(e,n)}),Ir=/* @__PURE__ */je("$ZodDefault",(e,t)=>{Cn.init(e,t),e._zod.optin="optional",Ye(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);if(void 0===e.value)return e.value=t.defaultValue,e;const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Er(e,t)):Er(r,t)}});function Er(e,t){return void 0===e.value&&(e.value=t.defaultValue),e}var Ar=/* @__PURE__ */je("$ZodPrefault",(e,t)=>{Cn.init(e,t),e._zod.optin="optional",Ye(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>("backward"===n.direction||void 0===e.value&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Tr=/* @__PURE__ */je("$ZodNonOptional",(e,t)=>{Cn.init(e,t),Ye(e._zod,"values",()=>{const e=t.innerType._zod.values;return e?new Set([...e].filter(e=>void 0!==e)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Mr(t,e)):Mr(i,e)}});function Mr(e,t){return e.issues.length||void 0!==e.value||e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var zr=/* @__PURE__ */je("$ZodCatch",(e,t)=>{Cn.init(e,t),Ye(e._zod,"optin",()=>t.innerType._zod.optin),Ye(e._zod,"optout",()=>t.innerType._zod.optout),Ye(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>ht(e,n,We()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>ht(e,n,We()))},input:e.value}),e.issues=[]),e)}}),Or=/* @__PURE__ */je("$ZodPipe",(e,t)=>{Cn.init(e,t),Ye(e._zod,"values",()=>t.in._zod.values),Ye(e._zod,"optin",()=>t.in._zod.optin),Ye(e._zod,"optout",()=>t.out._zod.optout),Ye(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(e,n)=>{if("backward"===n.direction){const r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Rr(e,t.in,n)):Rr(r,t.in,n)}const r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Rr(e,t.out,n)):Rr(r,t.out,n)}});function Rr(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Nr=/* @__PURE__ */je("$ZodReadonly",(e,t)=>{Cn.init(e,t),Ye(e._zod,"propValues",()=>t.innerType._zod.propValues),Ye(e._zod,"values",()=>t.innerType._zod.values),Ye(e._zod,"optin",()=>t.innerType?._zod?.optin),Ye(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if("backward"===n.direction)return t.innerType._zod.run(e,n);const r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Pr):Pr(r)}});function Pr(e){return e.value=Object.freeze(e.value),e}var Lr,Dr=/* @__PURE__ */je("$ZodCustom",(e,t)=>{sn.init(e,t),Cn.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>$r(t,n,r,e));$r(i,n,r,e)}});function $r(e,t,n,r){if(!e){const e={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ft(e))}}var jr=class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(e,...t){const n=t[0];return this._map.set(e,n),n&&"object"==typeof n&&"id"in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(e){const t=this._map.get(e);return t&&"object"==typeof t&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(Lr=globalThis).__zod_globalRegistry??(Lr.__zod_globalRegistry=new jr);var Fr=globalThis.__zod_globalRegistry;function Ur(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...lt(t)})}function Br(e,t){return new ln({check:"less_than",...lt(t),value:e,inclusive:!1})}function Wr(e,t){return new ln({check:"less_than",...lt(t),value:e,inclusive:!0})}function Gr(e,t){return new cn({check:"greater_than",...lt(t),value:e,inclusive:!1})}function Hr(e,t){return new cn({check:"greater_than",...lt(t),value:e,inclusive:!0})}function Zr(e,t){return new dn({check:"multiple_of",...lt(t),value:e})}function Vr(e,t){return new pn({check:"max_length",...lt(t),maximum:e})}function qr(e,t){return new hn({check:"min_length",...lt(t),minimum:e})}function Jr(e,t){return new mn({check:"length_equals",...lt(t),length:e})}function Yr(e){return new kn({check:"overwrite",tx:e})}function Kr(e,t){const n=new sn({check:"custom",...lt(t)});return n._zod.check=e,n}function Qr(e){let t=e?.target??"draft-2020-12";return"draft-4"===t&&(t="draft-04"),"draft-7"===t&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Fr,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:/* @__PURE__ */new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function Xr(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def,o=t.seen.get(e);if(o)return o.count++,n.schemaPath.includes(e)&&(o.cycle=n.path),o.schema;const s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s);const a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{const n=s.schema,o=t.processors[i.type];if(!o)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);o(e,t,n,r)}const o=e._zod.parent;o&&(s.ref||(s.ref=o),Xr(o,t,r),t.seen.get(o).isParent=!0)}const l=t.metadataRegistry.get(e);return l&&Object.assign(s.schema,l),"input"===t.io&&ni(e)&&(delete s.schema.examples,delete s.schema.default),"input"===t.io&&s.schema._prefault&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function ei(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=/* @__PURE__ */new Map;for(const o of e.seen.entries()){const t=e.metadataRegistry.get(o[0])?.id;if(t){const e=r.get(t);if(e&&e!==o[0])throw new Error(`Duplicate schema id "${t}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(t,o[0])}}const i=t=>{if(t[1].schema.$ref)return;const r=t[1],{ref:i,defId:o}=(t=>{const r="draft-2020-12"===e.target?"$defs":"definitions";if(e.external){const n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const o=t[1].defId??t[1].schema.id??"schema"+e.counter++;return t[1].defId=o,{defId:o,ref:`${i("__shared")}#/${r}/${o}`}}if(t[1]===n)return{ref:"#"};const i=`#/${r}/`,o=t[1].schema.id??"__schema"+e.counter++;return{defId:o,ref:i+o}})(t);r.def={...r.schema},o&&(r.defId=o);const s=r.schema;for(const e in s)delete s[e];s.$ref=i};if("throw"===e.cycles)for(const o of e.seen.entries()){const e=o[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join("/")}/<root>\n\nSet the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const n=o[1];if(t!==o[0]){if(e.external){const n=e.external.registry.get(o[0])?.id;if(t!==o[0]&&n){i(o);continue}}(e.metadataRegistry.get(o[0])?.id||n.cycle||n.count>1&&"ref"===e.reused)&&i(o)}else i(o)}}function ti(e,t){const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=t=>{const n=e.seen.get(t);if(null===n.ref)return;const i=n.def??n.schema,o={...i},s=n.ref;if(n.ref=null,s){r(s);const n=e.seen.get(s),a=n.schema;if(!a.$ref||"draft-07"!==e.target&&"draft-04"!==e.target&&"openapi-3.0"!==e.target?Object.assign(i,a):(i.allOf=i.allOf??[],i.allOf.push(a)),Object.assign(i,o),t._zod.parent===s)for(const e in i)"$ref"!==e&&"allOf"!==e&&(e in o||delete i[e]);if(a.$ref&&n.def)for(const e in i)"$ref"!==e&&"allOf"!==e&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}const a=t._zod.parent;if(a&&a!==s){r(a);const t=e.seen.get(a);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(const e in i)"$ref"!==e&&"allOf"!==e&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};for(const a of[...e.seen.entries()].reverse())r(a[0]);const i={};if("draft-2020-12"===e.target?i.$schema="https://json-schema.org/draft/2020-12/schema":"draft-07"===e.target?i.$schema="http://json-schema.org/draft-07/schema#":"draft-04"===e.target?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Object.assign(i,n.def??n.schema);const o=e.external?.defs??{};for(const a of e.seen.entries()){const e=a[1];e.def&&e.defId&&(o[e.defId]=e.def)}e.external||Object.keys(o).length>0&&("draft-2020-12"===e.target?i.$defs=o:i.definitions=o);try{const n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t["~standard"],jsonSchema:{input:ri(t,"input",e.processors),output:ri(t,"output",e.processors)}},enumerable:!1,writable:!1}),n}catch(s){throw new Error("Error converting schema to JSON.")}}function ni(e,t){const n=t??{seen:/* @__PURE__ */new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if("transform"===r.type)return!0;if("array"===r.type)return ni(r.element,n);if("set"===r.type)return ni(r.valueType,n);if("lazy"===r.type)return ni(r.getter(),n);if("promise"===r.type||"optional"===r.type||"nonoptional"===r.type||"nullable"===r.type||"readonly"===r.type||"default"===r.type||"prefault"===r.type)return ni(r.innerType,n);if("intersection"===r.type)return ni(r.left,n)||ni(r.right,n);if("record"===r.type||"map"===r.type)return ni(r.keyType,n)||ni(r.valueType,n);if("pipe"===r.type)return ni(r.in,n)||ni(r.out,n);if("object"===r.type){for(const e in r.shape)if(ni(r.shape[e],n))return!0;return!1}if("union"===r.type){for(const e of r.options)if(ni(e,n))return!0;return!1}if("tuple"===r.type){for(const e of r.items)if(ni(e,n))return!0;return!(!r.rest||!ni(r.rest,n))}return!1}var ri=(e,t,n={})=>r=>{const{libraryOptions:i,target:o}=r??{},s=Qr({...i??{},target:o,io:t,processors:n});return Xr(e,s),ei(s,e),ti(s,e)},ii={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},oi=(e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r);t.seen.get(e).ref=i.innerType},si=/* @__PURE__ */je("ZodISODateTime",(e,t)=>{jn.init(e,t),Oi.init(e,t)});function ai(e){return function(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...lt(t)})}(si,e)}var li=/* @__PURE__ */je("ZodISODate",(e,t)=>{Fn.init(e,t),Oi.init(e,t)});function ci(e){return function(e,t){return new e({type:"string",format:"date",check:"string_format",...lt(t)})}(li,e)}var di=/* @__PURE__ */je("ZodISOTime",(e,t)=>{Un.init(e,t),Oi.init(e,t)});function ui(e){return function(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...lt(t)})}(di,e)}var pi=/* @__PURE__ */je("ZodISODuration",(e,t)=>{Bn.init(e,t),Oi.init(e,t)});function hi(e){return function(e,t){return new e({type:"string",format:"duration",check:"string_format",...lt(t)})}(pi,e)}var mi=(e,t)=>{yt.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:t=>function(e,t=e=>e.message){const n={_errors:[]},r=e=>{for(const i of e.issues)if("invalid_union"===i.code&&i.errors.length)i.errors.map(e=>r({issues:e}));else if("invalid_key"===i.code)r({issues:i.issues});else if("invalid_element"===i.code)r({issues:i.issues});else if(0===i.path.length)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){const n=i.path[r];r!==i.path.length-1?e[n]=e[n]||{_errors:[]}:(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))),e=e[n],r++}}};return r(e),n}(e,t)},flatten:{value:t=>function(e,t=e=>e.message){const n={},r=[];for(const i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}(e,t)},addIssue:{value:t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,He,2)}},addIssues:{value:t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,He,2)}},isEmpty:{get:()=>0===e.issues.length}})},fi=(je("ZodError",mi),je("ZodError",mi,{Parent:Error})),gi=/* @__PURE__ */bt(fi),yi=/* @__PURE__ */vt(fi),wi=/* @__PURE__ */xt(fi),bi=/* @__PURE__ */_t(fi),vi=/* @__PURE__ */Ct(fi),xi=/* @__PURE__ */It(fi),ki=/* @__PURE__ */Et(fi),_i=/* @__PURE__ */At(fi),Si=/* @__PURE__ */Tt(fi),Ci=/* @__PURE__ */Mt(fi),Ii=/* @__PURE__ */zt(fi),Ei=/* @__PURE__ */Ot(fi),Ai=/* @__PURE__ */je("ZodType",(e,t)=>(Cn.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:ri(e,"input"),output:ri(e,"output")}}),e.toJSONSchema=((e,t={})=>n=>{const r=Qr({...n,processors:t});return Xr(e,r),ei(r,e),ti(r,e)})(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Qe(t,{checks:[...t.checks??[],...n.map(e=>"function"==typeof e?{_zod:{check:e,def:{check:"custom"},onattach:[]}}:e)]}),{parent:!0}),e.with=e.check,e.clone=(t,n)=>at(e,t,n),e.brand=()=>e,e.register=(t,n)=>(t.add(e,n),e),e.parse=(t,n)=>gi(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>wi(e,t,n),e.parseAsync=async(t,n)=>yi(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>bi(e,t,n),e.spa=e.safeParseAsync,e.encode=(t,n)=>vi(e,t,n),e.decode=(t,n)=>xi(e,t,n),e.encodeAsync=async(t,n)=>ki(e,t,n),e.decodeAsync=async(t,n)=>_i(e,t,n),e.safeEncode=(t,n)=>Si(e,t,n),e.safeDecode=(t,n)=>Ci(e,t,n),e.safeEncodeAsync=async(t,n)=>Ii(e,t,n),e.safeDecodeAsync=async(t,n)=>Ei(e,t,n),e.refine=(t,n)=>e.check(function(e,t={}){return function(e,t,n){return new e({type:"custom",check:"custom",fn:t,...lt(n)})}(Fo,e,t)}(t,n)),e.superRefine=t=>e.check(function(e){const t=/* @__PURE__ */Kr(n=>(n.addIssue=e=>{if("string"==typeof e)n.issues.push(ft(e,n.value,t._zod.def));else{const r=e;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=n.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),n.issues.push(ft(r))}},e(n.value,n)));return t}(t)),e.overwrite=t=>e.check(Yr(t)),e.optional=()=>To(e),e.exactOptional=()=>new Mo({type:"optional",innerType:e}),e.nullable=()=>Oo(e),e.nullish=()=>To(Oo(e)),e.nonoptional=t=>function(e,t){return new Po({type:"nonoptional",innerType:e,...lt(t)})}(e,t),e.array=()=>po(e),e.or=t=>go([e,t]),e.and=t=>new bo({type:"intersection",left:e,right:t}),e.transform=t=>$o(e,Eo(t)),e.default=t=>{return n=t,new Ro({type:"default",innerType:e,get defaultValue(){return"function"==typeof n?n():it(n)}});var n},e.prefault=t=>{return n=t,new No({type:"prefault",innerType:e,get defaultValue(){return"function"==typeof n?n():it(n)}});var n},e.catch=t=>{return new Lo({type:"catch",innerType:e,catchValue:"function"==typeof(n=t)?n:()=>n});var n},e.pipe=t=>$o(e,t),e.readonly=()=>new jo({type:"readonly",innerType:e}),e.describe=t=>{const n=e.clone();return Fr.add(n,{description:t}),n},Object.defineProperty(e,"description",{get:()=>Fr.get(e)?.description,configurable:!0}),e.meta=(...t)=>{if(0===t.length)return Fr.get(e);const n=e.clone();return Fr.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=t=>t(e),e)),Ti=/* @__PURE__ */je("_ZodString",(e,t)=>{In.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n;r.type="string";const{minimum:i,maximum:o,format:s,patterns:a,contentEncoding:l}=e._zod.bag;if("number"==typeof i&&(r.minLength=i),"number"==typeof o&&(r.maxLength=o),s&&(r.format=ii[s]??s,""===r.format&&delete r.format,"time"===s&&delete r.format),l&&(r.contentEncoding=l),a&&a.size>0){const e=[...a];1===e.length?r.pattern=e[0].source:e.length>1&&(r.allOf=[...e.map(e=>({..."draft-07"===t.target||"draft-04"===t.target||"openapi-3.0"===t.target?{type:"string"}:{},pattern:e.source}))])}})(e,t,n);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...t)=>e.check(function(e,t){return new gn({check:"string_format",format:"regex",...lt(t),pattern:e})}(...t)),e.includes=(...t)=>e.check(function(e,t){return new bn({check:"string_format",format:"includes",...lt(t),includes:e})}(...t)),e.startsWith=(...t)=>e.check(function(e,t){return new vn({check:"string_format",format:"starts_with",...lt(t),prefix:e})}(...t)),e.endsWith=(...t)=>e.check(function(e,t){return new xn({check:"string_format",format:"ends_with",...lt(t),suffix:e})}(...t)),e.min=(...t)=>e.check(qr(...t)),e.max=(...t)=>e.check(Vr(...t)),e.length=(...t)=>e.check(Jr(...t)),e.nonempty=(...t)=>e.check(qr(1,...t)),e.lowercase=t=>e.check(function(e){return new yn({check:"string_format",format:"lowercase",...lt(e)})}(t)),e.uppercase=t=>e.check(function(e){return new wn({check:"string_format",format:"uppercase",...lt(e)})}(t)),e.trim=()=>e.check(/* @__PURE__ */Yr(e=>e.trim())),e.normalize=(...t)=>e.check(function(e){/* @__PURE__ */
2
- return Yr(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */Yr(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(/* @__PURE__ */Yr(e=>e.toUpperCase())),e.slugify=()=>e.check(/* @__PURE__ */Yr(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),Mi=/* @__PURE__ */je("ZodString",(e,t)=>{In.init(e,t),Ti.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...lt(t)})}(Ri,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...lt(t)})}(Li,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...lt(t)})}(Ki,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...lt(t)})}(Di,t)),e.guid=t=>e.check(Ur(Ni,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...lt(t)})}(Pi,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...lt(t)})}(Pi,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...lt(t)})}(Pi,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...lt(t)})}(Pi,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...lt(t)})}($i,t)),e.guid=t=>e.check(Ur(Ni,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...lt(t)})}(ji,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...lt(t)})}(Fi,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...lt(t)})}(Ui,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...lt(t)})}(qi,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...lt(t)})}(Ji,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...lt(t)})}(Bi,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...lt(t)})}(Wi,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...lt(t)})}(Gi,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...lt(t)})}(Hi,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...lt(t)})}(Zi,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...lt(t)})}(Vi,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...lt(t)})}(Yi,t)),e.datetime=t=>e.check(ai(t)),e.date=t=>e.check(ci(t)),e.time=t=>e.check(ui(t)),e.duration=t=>e.check(hi(t))});function zi(e){return function(e,t){return new e({type:"string",...lt(t)})}(Mi,e)}var Oi=/* @__PURE__ */je("ZodStringFormat",(e,t)=>{En.init(e,t),Ti.init(e,t)}),Ri=/* @__PURE__ */je("ZodEmail",(e,t)=>{Mn.init(e,t),Oi.init(e,t)}),Ni=/* @__PURE__ */je("ZodGUID",(e,t)=>{An.init(e,t),Oi.init(e,t)}),Pi=/* @__PURE__ */je("ZodUUID",(e,t)=>{Tn.init(e,t),Oi.init(e,t)}),Li=/* @__PURE__ */je("ZodURL",(e,t)=>{zn.init(e,t),Oi.init(e,t)}),Di=/* @__PURE__ */je("ZodEmoji",(e,t)=>{On.init(e,t),Oi.init(e,t)}),$i=/* @__PURE__ */je("ZodNanoID",(e,t)=>{Rn.init(e,t),Oi.init(e,t)}),ji=/* @__PURE__ */je("ZodCUID",(e,t)=>{Nn.init(e,t),Oi.init(e,t)}),Fi=/* @__PURE__ */je("ZodCUID2",(e,t)=>{Pn.init(e,t),Oi.init(e,t)}),Ui=/* @__PURE__ */je("ZodULID",(e,t)=>{Ln.init(e,t),Oi.init(e,t)}),Bi=/* @__PURE__ */je("ZodXID",(e,t)=>{Dn.init(e,t),Oi.init(e,t)}),Wi=/* @__PURE__ */je("ZodKSUID",(e,t)=>{$n.init(e,t),Oi.init(e,t)}),Gi=/* @__PURE__ */je("ZodIPv4",(e,t)=>{Wn.init(e,t),Oi.init(e,t)}),Hi=/* @__PURE__ */je("ZodIPv6",(e,t)=>{Gn.init(e,t),Oi.init(e,t)}),Zi=/* @__PURE__ */je("ZodCIDRv4",(e,t)=>{Hn.init(e,t),Oi.init(e,t)}),Vi=/* @__PURE__ */je("ZodCIDRv6",(e,t)=>{Zn.init(e,t),Oi.init(e,t)}),qi=/* @__PURE__ */je("ZodBase64",(e,t)=>{qn.init(e,t),Oi.init(e,t)}),Ji=/* @__PURE__ */je("ZodBase64URL",(e,t)=>{Jn.init(e,t),Oi.init(e,t)}),Yi=/* @__PURE__ */je("ZodE164",(e,t)=>{Yn.init(e,t),Oi.init(e,t)}),Ki=/* @__PURE__ */je("ZodJWT",(e,t)=>{Kn.init(e,t),Oi.init(e,t)}),Qi=/* @__PURE__ */je("ZodNumber",(e,t)=>{Qn.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:o,format:s,multipleOf:a,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof i&&(r.minimum=i,"number"==typeof c&&"draft-04"!==t.target&&(c>=i?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof l&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),"number"==typeof o&&(r.maximum=o,"number"==typeof l&&"draft-04"!==t.target&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a)})(e,t,n),e.gt=(t,n)=>e.check(Gr(t,n)),e.gte=(t,n)=>e.check(Hr(t,n)),e.min=(t,n)=>e.check(Hr(t,n)),e.lt=(t,n)=>e.check(Br(t,n)),e.lte=(t,n)=>e.check(Wr(t,n)),e.max=(t,n)=>e.check(Wr(t,n)),e.int=t=>e.check(to(t)),e.safe=t=>e.check(to(t)),e.positive=t=>e.check(Gr(0,t)),e.nonnegative=t=>e.check(Hr(0,t)),e.negative=t=>e.check(Br(0,t)),e.nonpositive=t=>e.check(Wr(0,t)),e.multipleOf=(t,n)=>e.check(Zr(t,n)),e.step=(t,n)=>e.check(Zr(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Xi(e){return function(e,t){return new e({type:"number",checks:[],...lt(t)})}(Qi,e)}var eo=/* @__PURE__ */je("ZodNumberFormat",(e,t)=>{Xn.init(e,t),Qi.init(e,t)});function to(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...lt(t)})}(eo,e)}var no=/* @__PURE__ */je("ZodBoolean",(e,t)=>{er.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function ro(e){return function(e,t){return new e({type:"boolean",...lt(t)})}(no,e)}var io=/* @__PURE__ */je("ZodNull",(e,t)=>{tr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"})(0,e,t)});var oo=/* @__PURE__ */je("ZodUnknown",(e,t)=>{nr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function so(){return new oo({type:"unknown"})}var ao=/* @__PURE__ */je("ZodNever",(e,t)=>{rr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function lo(e){return function(e,t){return new e({type:"never",...lt(t)})}(ao,e)}var co=/* @__PURE__ */je("ZodDate",(e,t)=>{ir.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")})(0,e),e.min=(t,n)=>e.check(Hr(t,n)),e.max=(t,n)=>e.check(Wr(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}),uo=/* @__PURE__ */je("ZodArray",(e,t)=>{sr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Xr(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(qr(t,n)),e.nonempty=t=>e.check(qr(1,t)),e.max=(t,n)=>e.check(Vr(t,n)),e.length=(t,n)=>e.check(Jr(t,n)),e.unwrap=()=>e.element});function po(e,t){return function(e,t,n){return new e({type:"array",element:t,...lt(n)})}(uo,e,t)}var ho=/* @__PURE__ */je("ZodObject",(e,t)=>{ur.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const s=o.shape;for(const c in s)i.properties[c]=Xr(s[c],t,{...r,path:[...r.path,"properties",c]});const a=new Set(Object.keys(s)),l=new Set([...a].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(i.required=Array.from(l)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Xr(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Ye(e,"shape",()=>t.shape),e.keyof=()=>_o(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:so()}),e.loose=()=>e.clone({...e._zod.def,catchall:so()}),e.strict=()=>e.clone({...e._zod.def,catchall:lo()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!rt(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return at(e,Qe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ke(this,"shape",n),n}}))}(e,t),e.safeExtend=t=>function(e,t){if(!rt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return at(e,Qe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ke(this,"shape",n),n}}))}(e,t),e.merge=t=>{return r=t,at(n=e,Qe(n._zod.def,{get shape(){const e={...n._zod.def.shape,...r._zod.def.shape};return Ke(this,"shape",e),e},get catchall(){return r._zod.def.catchall},checks:[]}));var n,r},e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return at(e,Qe(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Ke(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return at(e,Qe(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ke(this,"shape",r),r},checks:[]}))}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return at(t,Qe(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Ke(this,"shape",i),i},checks:[]}))}(Ao,e,t[0]),e.required=(...t)=>{return n=Po,r=e,i=t[0],at(r,Qe(r._zod.def,{get shape(){const e=r._zod.def.shape,t={...e};if(i)for(const r in i){if(!(r in t))throw new Error(`Unrecognized key: "${r}"`);i[r]&&(t[r]=new n({type:"nonoptional",innerType:e[r]}))}else for(const r in e)t[r]=new n({type:"nonoptional",innerType:e[r]});return Ke(this,"shape",t),t}}));var n,r,i}});function mo(e,t){return new ho({type:"object",shape:e??{},...lt(t)})}var fo=/* @__PURE__ */je("ZodUnion",(e,t)=>{hr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,s=i.options.map((e,n)=>Xr(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});function go(e,t){return new fo({type:"union",options:e,...lt(t)})}var yo=/* @__PURE__ */je("ZodDiscriminatedUnion",(e,t)=>{fo.init(e,t),mr.init(e,t)});function wo(e,t,n){return new yo({type:"union",options:t,discriminator:e,...lt(n)})}var bo=/* @__PURE__ */je("ZodIntersection",(e,t)=>{fr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Xr(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]]})(e,t,n,r)});var vo=/* @__PURE__ */je("ZodRecord",(e,t)=>{wr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=s._zod.bag?.patterns;if("loose"===o.mode&&a&&a.size>0){const e=Xr(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of a)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Xr(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Xr(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const l=s._zod.values;if(l){const e=[...l].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function xo(e,t,n){return new vo({type:"record",keyType:e,valueType:t,...lt(n)})}var ko=/* @__PURE__ */je("ZodEnum",(e,t)=>{br.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Ge(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const o of e){if(!n.has(o))throw new Error(`Key ${o} not found in enum`);i[o]=t.entries[o]}return new ko({...t,checks:[],...lt(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new ko({...t,checks:[],...lt(r),entries:i})}});function _o(e,t){return new ko({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...lt(t)})}var So=/* @__PURE__ */je("ZodLiteral",(e,t)=>{vr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(void 0===o){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof o){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Co(e,t){return new So({type:"literal",values:Array.isArray(e)?e:[e],...lt(t)})}var Io=/* @__PURE__ */je("ZodTransform",(e,t)=>{xr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ue(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ft(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(ft(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Eo(e){return new Io({type:"transform",transform:e})}var Ao=/* @__PURE__ */je("ZodOptional",(e,t)=>{_r.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oi(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function To(e){return new Ao({type:"optional",innerType:e})}var Mo=/* @__PURE__ */je("ZodExactOptional",(e,t)=>{Sr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oi(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var zo=/* @__PURE__ */je("ZodNullable",(e,t)=>{Cr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oo(e){return new zo({type:"nullable",innerType:e})}var Ro=/* @__PURE__ */je("ZodDefault",(e,t)=>{Ir.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var No=/* @__PURE__ */je("ZodPrefault",(e,t)=>{Ar.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Po=/* @__PURE__ */je("ZodNonOptional",(e,t)=>{Tr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Lo=/* @__PURE__ */je("ZodCatch",(e,t)=>{zr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var Do=/* @__PURE__ */je("ZodPipe",(e,t)=>{Or.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o="input"===t.io?"transform"===i.in._zod.def.type?i.out:i.in:i.out;Xr(o,t,r),t.seen.get(e).ref=o})(e,t,0,r),e.in=t.in,e.out=t.out});function $o(e,t){return new Do({type:"pipe",in:e,out:t})}var jo=/* @__PURE__ */je("ZodReadonly",(e,t)=>{Nr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Fo=/* @__PURE__ */je("ZodCustom",(e,t)=>{Dr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function Uo(e,t={}){const n=new Fo({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...lt(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:"invalid_type",expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}function Bo(e,t){return $o(Eo(e),t)}function Wo(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...lt(t)})}(Qi,e)}function Go(e){return function(e,t){return new e({type:"boolean",coerce:!0,...lt(t)})}(no,e)}function Ho(e){return function(e,t){return new e({type:"date",coerce:!0,...lt(t)})}(co,e)}_o(["free","starter","growth","enterprise"]);var Zo,Vo=_o(["created","active","suspended","pending_approval"]),qo=_o(["free","starter","growth","enterprise"]),Jo=_o(["human","ai"]),Yo=_o(["male","female"]),Ko=_o(["active","learning","error"]),Qo=mo({vector_index_created:ro().nullable(),graph_index_created:ro().nullable()}),Xo=_o(["document","video"]),es=_o(["pending","processing","waiting_review","completed","failed"]),ts=(_o(["pending","running","completed","failed"]),_o(["pending","running","completed","failed","cancelled"])),ns=_o(["user","agent"]),rs=_o(["widget","app"]),is=(_o(["tell","show","do"]),_o(["app","website"])),os=_o(["widget","slack"]),ss=_o(["timer","github","slack","teams","jira"]),as=_o(["user_login","url_visit","update_workspace","create_user","update_user","delete_user","create_agent","update_agent","delete_agent","create_application","update_application","delete_application","create_widget","update_widget","delete_widget","create_knowledge","update_knowledge","delete_knowledge","approve_user","deny_user","request_workspace","widget_question","qa_run_started","start_simulation","create_automation","update_automation","delete_automation","toggle_automation"]),ls=mo({id:Xi().optional(),created_at:Ho().optional(),updated_at:Ho().optional()}),cs=mo({file:Uo(File),application_id:Wo().optional()}),ds=mo({id:Wo()}),us=mo({slug:zi()}),ps=mo({agent_id:Wo()}),hs=mo({widget_id:Wo()}),ms=mo({simulation_id:Wo()}),fs=mo({application_id:Wo()}),gs=mo({user_id:Wo()}),ys=mo({success:Co(!0)}),ws=ys.extend({message:zi()}),bs=(mo({workspace_id:Wo().optional()}),mo({application_id:Wo().optional()}),mo({limit:Wo().optional().default(50),offset:Wo().optional().default(0)})),vs=e=>mo({items:po(e),total:Xi(),limit:Xi(),offset:Xi()}),xs=e=>mo({items:po(e),count:Xi()}),ks=mo({status:zi(),timestamp:zi(),service:zi(),version:zi(),build:zi()}),_s=mo({name:zi(),version:zi(),build:zi(),status:zi(),timestamp:zi()}),Ss=_o(["password","oauth"]),Cs=ls.extend({is_super:ro(),status:Vo,email:zi().email(),external_id:zi().nullish(),first_name:zi().nullish(),last_name:zi().nullish(),password:zi().nullish(),image_url:zi().nullish(),prompt_limit:Xi().nullish(),last_login_at:Ho().nullish(),auth_method:Ss.nullish()}),Is=Cs.partial().extend({email:zi().email(),password:zi()}),Es=Cs.partial(),As=mo({users:po(Is)}),Ts=mo({users:po(Cs.partial())}),Ms=(mo({token:zi()}),ls.extend({name:zi(),slug:zi(),status:Vo,package:qo,ending_date:Ho().nullish(),external_workspace_id:zi().nullish()})),zs=Ms.partial().extend({name:zi().min(1)}),Os=Ms.partial(),Rs=_o(["active","past_due","canceled","unpaid","trialing","incomplete","incomplete_expired","paused"]),Ns=ls.extend({workspace_id:Xi(),package:qo,ending_date:Ho(),stripe_subscription_id:zi().nullable(),stripe_price_id:zi().nullable(),status:Rs.default("active").optional()}),Ps=(Ns.partial().extend({workspace_id:Xi(),package:qo}),Ns.partial(),_o(["owner","member"])),Ls=ls.extend({workspace_id:Xi(),user_id:Xi(),role:Ps}),Ds=mo({id:Xi(),agent_name:zi(),image_url:zi().nullish()}),$s=ls.extend({workspace_id:Xi(),application_id:Xi().optional(),file_name:zi().min(1),file_size:Wo(),file_type:Xo,file_url:zi(),source_url:zi().nullish(),agents:po(Ds).optional()}),js=_o(["chromium","firefox","webkit"]),Fs=mo({browsers:po(js).default(["chromium"]),parallel:ro().default(!1),fail_fast:ro().default(!1),timeout_per_browser:Xi().int().min(60).max(3600).optional()}),Us=ls.extend({workspace_id:Xi(),user_id:Xi(),application_id:Xi(),file_name:zi().min(1),file_size:Wo(),file_type:zi(),file_url:zi(),file_path:zi().nullable(),text_content:zi().nullish(),additional_instructions:zi().max(1e3).nullish(),status:es,processing_step:zi().nullish(),ultimate_goal:zi().nullish(),browser_config:Fs.nullish()}),Bs=mo({application_id:Wo(),file:Uo(File).optional(),text_content:zi().optional(),file_name:zi().optional(),additional_instructions:zi().max(1e3).optional()}),Ws=ls.extend({qa_flow_id:Xi(),workspace_id:Xi(),triggered_by:Xi(),status:ts,browser_type:js,browser_config:Fs.nullish(),total_tests:Xi().int().nonnegative(),passed_tests:Xi().int().nonnegative(),failed_tests:Xi().int().nonnegative(),started_at:Ho().nullish(),completed_at:Ho().nullish()}),Gs=mo({step:Xi(),message:zi(),timestamp:zi(),status:_o(["success","error","info"])}),Hs=mo({run_id:Xi(),status:_o(["pending","running","passed","failed","skipped"]),browser_type:js.nullish(),progress_log:po(Gs).default([]),error_message:zi().nullish(),screenshot_url:zi().nullish(),simulation_id:Xi().nullish(),duration_ms:Xi().nullish(),started_at:zi().nullish(),completed_at:zi().nullish()}),Zs=mo({version:Xi().int().positive(),test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"]),change_type:_o(["created","modified","self_healed","refined","deleted"]),change_reason:zi().nullish(),changed_by:Xi().nullish(),created_at:zi(),accepted:ro().optional()}),Vs=mo({failure_type:_o(["locator","assertion","timeout","flow_change","environment"]),failure_message:zi().nullish(),failure_context:xo(zi(),so()).nullish(),repair_strategy:zi().nullish(),repair_details:xo(zi(),so()).nullish(),confidence_score:Xi().min(0).max(1).nullish(),validation_status:_o(["pending","validated","failed","rejected"]),simulation_id:Xi().nullish(),validation_simulation_id:Xi().nullish(),healed_version:Xi().nullish(),created_at:zi()}),qs=ls.extend({qa_flow_id:Xi(),workspace_id:Xi(),order_index:Xi().int().nonnegative(),test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"]),is_active:Bo(e=>"number"==typeof e?0!==e:e,ro()),current_version:Xi().int().positive(),version_history:po(Zs).nullable(),executions:po(Hs).nullable(),healing_attempts:po(Vs).nullable(),healing_metadata:xo(zi(),so()).nullish(),last_healed_at:Ho().nullish()}),Js=(mo({qa_flow_id:Xi(),test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"]).optional()}),mo({ultimateGoal:zi(),document:Us,testCases:po(mo({id:Xi(),title:zi(),prompt:zi(),objective:zi(),steps:po(zi()),expectedOutcome:zi(),priority:_o(["Low","Medium","High"])})),summary:mo({total:Xi(),estimatedTime:zi(),complexity:_o(["Low","Medium","High"])})})),Ys=mo({ultimate_goal:zi(),test_cases:po(mo({test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"])})),summary:mo({total_tests:Xi(),high_priority:Xi(),medium_priority:Xi(),low_priority:Xi(),estimated_time_minutes:Xi()})}),Ks=(wo("event",[mo({event:Co("response.created"),data:mo({message:zi()})}),mo({event:Co("response.progress"),data:mo({message:zi()})}),mo({event:Co("response.clear"),data:mo({}).optional()}),mo({event:Co("response.completed"),data:Ys}),mo({event:Co("error"),data:mo({detail:zi()})})]),go([zi(),Xi(),ro(),po(zi()),function(e,t){return new e({type:"null",...lt(t)})}(io,Zo)])),Qs=(_o(["created","modified","self_healed","refined","deleted"]),_o(["locator","assertion","timeout","flow_change","environment"])),Xs=(_o(["pending","validated","failed","rejected"]),mo({healing_enabled:ro().default(!0),auto_apply:ro().default(!1),min_confidence_threshold:Xi().min(0).max(1).default(.85),max_healing_attempts:Xi().int().min(1).max(5).default(2),last_healing_attempt:zi().datetime().nullable(),total_healing_attempts:Xi().int().default(0),successful_heals:Xi().int().default(0)}),mo({failure_type:Qs,is_healable:ro(),is_actual_bug:ro(),failure_message:zi(),failure_context:xo(zi(),so()),suggested_repair:mo({type:_o(["update_locator","update_assertion","update_steps","skip_test"]),confidence:Xi().min(0).max(1),details:xo(zi(),so())}).nullable()})),ea=(mo({go_to_url:mo({url:zi(),new_tab:ro()})}),mo({click_element_by_index:mo({index:Xi().int().min(1)})}),mo({input_text:mo({index:Xi(),text:zi(),clear_existing:ro()})}),mo({write_file:mo({file_name:zi(),content:zi(),append:ro(),trailing_newline:ro(),leading_newline:ro()})}),mo({get_otp:mo({question:zi()})}),mo({done:mo({success:ro(),message:zi().optional()})}),mo({wait:mo({seconds:Xi()})}),mo({reload_page:mo({})}),mo({open_new_tab:mo({url:zi()})}),mo({navigate_to_url:mo({url:zi()})}),xo(zi(),so())),ta=mo({evaluation_previous_goal:zi().optional().nullable(),memory:zi().optional().nullable(),next_goal:zi().optional().nullable(),action:po(ea).optional().nullable(),thinking:zi().optional().nullable()}).passthrough(),na=mo({is_done:ro(),success:ro().optional().nullable(),long_term_memory:zi().optional().nullable(),extracted_content:zi().optional().nullable(),include_extracted_content_only_once:ro().optional().nullable(),include_in_memory:ro().optional().nullable(),error:zi().optional().nullable(),metadata:mo({click_x:Xi().optional(),click_y:Xi().optional(),new_tab_opened:ro().optional(),input_x:Xi().optional(),input_y:Xi().optional()}).passthrough().optional().nullable()}).passthrough(),ra=mo({url:zi(),title:zi(),tab_id:zi().optional(),parent_tab_id:zi().optional().nullable()}).passthrough(),ia=mo({node_id:Xi().optional(),backend_node_id:Xi().optional(),frame_id:zi().optional().nullable(),node_type:Xi().optional(),node_value:zi().optional(),node_name:zi().optional(),attributes:xo(zi(),zi()).optional().nullable(),x_path:zi().optional(),element_hash:Xi().optional(),bounds:mo({x:Xi(),y:Xi(),width:Xi(),height:Xi()}).passthrough().optional().nullable(),stable_hash:Xi().optional(),ax_name:zi().optional().nullable()}).passthrough(),oa=mo({tabs:po(ra),screenshot_path:zi().nullable(),interacted_element:po(ia.nullable()),url:zi(),title:zi()}).passthrough(),sa=mo({step_start_time:Xi().optional().nullable(),step_end_time:Xi().optional().nullable(),step_number:Xi().optional().nullable(),step_interval:Xi().optional().nullable()}).passthrough(),aa=mo({model_output:ta.nullable(),result:po(na),state:oa,metadata:sa.nullable(),state_message:zi().optional().nullable()}).passthrough(),la=(mo({history:po(aa)}),mo({step_number:Xi().int().positive(),topic:zi(),screenshot_url:zi().nullable(),title:zi().optional().nullable(),url:zi().optional().nullable()})),ca=mo({status:zi(),status_message:zi().nullable(),num_steps:Xi().int().nonnegative().nullable(),created_at:Ho()}),da=ls.extend({application_id:Xi(),agent_id:Xi(),job_id:zi(),session_id:zi().nullish(),status:zi(),status_message:zi().nullish(),path:zi().nullish(),instructions:zi().nullish(),num_steps:Xi().int().nonnegative(),pinned:ro().optional(),source:_o(["direct","qa"]).optional(),agent_name:zi().nullish(),graph_index_id:zi().nullish(),progress_log:po(ca).optional(),agents:po(Ds).optional()}),ua=(mo({user_id:Xi(),email:zi(),first_name:zi().optional().nullable(),last_name:zi().optional().nullable(),last_simulation_at:zi().optional()}),da.partial().extend({application_id:Xi(),agent_id:Xi(),instructions:zi(),max_steps:Xi().int().positive().max(1e3).optional(),timeout:Xi().positive().max(360).optional()})),pa=mo({job_id:zi().optional(),status:zi().optional(),status_message:zi().optional(),num_steps:Xi().int().nonnegative().optional(),pinned:ro().optional(),graph_index_id:zi().optional()}),ha=mo({answer:zi().min(1)}),ma=ls.extend({session_id:zi(),chat_id:zi(),application_id:Wo().nullish(),blob_url:zi().nullable(),event_count:Wo().int().nonnegative(),started_at:Ho(),ended_at:Ho().nullable(),is_active:Bo(e=>"number"==typeof e?0!==e:e,ro()),metadata:mo({userAgent:zi().optional(),url:zi().optional()}).nullable(),last_batch_index:Wo().int().nullable(),last_event_timestamp:Wo().int().nullable(),last_upload_time:Ho().nullable()}),fa=mo({session_id:zi().min(1),chat_id:zi().min(1),application_id:Xi().int().nullish(),blob_url:zi().nullish(),event_count:Xi().int().nonnegative().optional(),started_at:Ho().optional(),ended_at:Ho().nullish(),is_active:Bo(e=>"number"==typeof e?0!==e:e,ro()).optional(),metadata:mo({userAgent:zi().optional(),url:zi().optional(),applicationId:Xi().optional()}).nullable().optional(),last_batch_index:Xi().int().nonnegative().nullish(),last_event_timestamp:Xi().int().nullish(),last_upload_time:Ho().nullish()}),ga=mo({id:Xi(),simulation_id:Xi(),status:zi(),status_message:zi().nullable(),num_steps:Xi().int().nonnegative().nullable(),created_at:Ho()}),ya=mo({start:zi(),end:zi(),action:zi()}),wa=mo({id:zi(),screenshots:po(zi()),title:zi(),url:zi(),state:po(zi()),mentions:po(zi())}),ba=mo({nodes:po(wa),edges:po(ya)}),va=ls.extend({workspace_id:Xi(),user_id:Xi().nullish(),application_id:Xi(),agent_name:zi(),agent_type:Jo,agent_voice:Yo,agent_description:zi().nullish(),instructions:zi().nullish(),image_url:zi().nullish(),graph_index_id:zi().nullish(),vector_store_id:zi().nullish(),status:Ko,status_message:zi().nullish(),learning_progress:Qo.nullish(),learning_started_at:Ho().nullish(),workspace:Ms.optional(),user:Cs.optional(),knowledge:po($s).optional(),simulations:po(da).optional(),simulation_count:Xi().int().nonnegative().optional(),knowledge_count:Xi().int().nonnegative().optional()}),xa=e=>{if(Array.isArray(e))return e.map(e=>Number(e));if("string"==typeof e){const t=JSON.parse(e);return Array.isArray(t)?t.map(e=>Number(e)):[]}return[]},ka=go([po(Xi()),zi()]).transform(xa),_a=go([po(Xi()),zi()]).transform(xa),Sa=va.partial().extend({application_id:Wo(),agent_name:zi(),agent_type:Jo,agent_voice:Yo,agent_description:zi(),instructions:zi(),file:Uo(File).optional(),image_url:zi().optional(),knowledge_ids:ka,simulation_ids:_a}),Ca=va.partial().extend({file:Uo(File).optional(),knowledge_ids:ka,simulation_ids:_a}),Ia=(mo({text:zi(),task_id:zi().optional()}),mo({status:zi(),message:zi().optional()}),mo({task_id:zi().optional(),status:zi().optional(),current_step:zi().optional(),error:zi().optional(),message:zi().optional()}),mo({workflow_id:zi(),workflow_type:zi(),status:zi(),current_step:zi(),error:zi().nullable(),created_at:zi(),updated_at:zi()}),mo({session_id:zi().optional(),live_view_url:zi().nullish(),status:zi().optional(),message:zi().nullish(),success:ro().optional()}),_o(["pending","running","completed","failed","cancelled","has_question","in_progress"]),mo({contentType:_o(["document","video","automation_log","screenshot","all"]).optional(),context:zi().optional(),previousActions:po(zi()).optional(),top:Wo().min(1).max(100).optional(),minConfidence:Wo().min(0).max(1).optional(),entities:po(zi()).optional(),useVectorSearch:ro().optional(),vectorThreshold:Wo().min(0).max(1).optional()}),mo({id:zi(),content:zi(),contentType:_o(["document","video","automation_log","screenshot"]),sourceFile:zi(),sourceType:zi(),metadata:zi(),confidence:Xi(),keyPhrases:po(zi()),entities:po(zi()),sentiment:zi(),vectorContent:po(Xi())})),Ea=(mo({document:Ia,score:Xi(),highlights:xo(zi(),po(zi())).optional()}),mo({simulation_id:Wo().positive("Simulation ID must be a positive number")})),Aa=mo({agent:va,simulation_id:Xi(),knowledge_id:Xi(),message:zi()}),Ta=ls.extend({workspace_id:Xi(),name:zi(),type:is,url:zi().nullish(),username:zi().nullish(),password:zi().nullish(),allowed_domains:po(zi()).nullish().default([])}),Ma=Ta.partial().extend({type:is,name:zi().min(1),url:zi(),allowed_domains:po(zi()).optional().default([])}),za=Ta.partial().omit({workspace_id:!0}),Oa=mo({chip_mode:_o(["show","tell","do"]),chip_text:zi()}),Ra=mo({widget_enabled:ro(),widget_appearance:_o(["default","compact","full"]),widget_position:_o(["bottom_left","bottom_right","top_left","top_right"]),widget_device:_o(["desktop","mobile","desktop_mobile"]),widget_header:zi(),widget_body:zi(),widget_greeting:zi(),widget_feature_tell:ro(),widget_feature_show:ro(),widget_feature_do:ro(),widget_feature_human:ro(),widget_background_color:zi(),widget_text_color:zi(),widget_border_color:zi(),widget_accent_color:zi(),widget_secondary_color:zi(),widget_border_radius:zi(),widget_font_size:zi(),widget_width:zi(),widget_height:zi(),widget_shadow:zi(),widget_animation_duration:zi(),widget_fade_duration:zi(),widget_bounce_effect:ro(),widget_chips:po(Oa)}),Na=mo({webhook_url:zi().url(),channel:zi(),bot_token:zi(),notifications_enabled:ro()}),Pa=ls.extend({application_id:Xi(),agent_id:Xi(),type:os,settings:go([Ra,Na]),status:Vo,marketrix_id:zi(),marketrix_key:zi(),snippet:zi().nullish()}),La=(Pa.extend({application:Ta.partial(),workspace:Ms.partial(),user:Cs.partial(),agent:va.partial()}),Pa.extend({agent:va.partial().optional()})),Da=(Ta.extend({widgets:po(Pa).optional(),agents:po(va).optional()}),Pa.partial().extend({application_id:Xi().positive(),agent_id:Xi().positive(),type:os,settings:go([Ra,Na]).optional()})),$a=Pa.partial(),ja=ls.extend({widget_id:Xi(),url_pattern:zi(),message:go([zi(),po(zi())]),description:zi().optional()}),Fa=ja.partial().extend({widget_id:Xi().positive(),url_pattern:zi().min(1),message:go([zi().min(1),po(zi().min(1)).min(1)])}),Ua=ja.partial(),Ba=po(mo({step_number:Xi(),action:zi(),element:zi(),text:zi(),description:zi(),selector:zi()})),Wa=ls.extend({application_id:Xi(),question:zi(),answer:Ba}),Ga=(mo({marketrix_id:zi().optional(),marketrix_key:zi().optional(),agent_id:Xi().positive().optional(),application_id:Xi().positive().optional(),chat_id:zi().optional(),content:zi()}).refine(e=>(e.marketrix_id&&e.marketrix_key)??(e.agent_id&&e.application_id),{message:"Either marketrix_id + marketrix_key or both agent_id + application_id must be provided"}),mo({text:zi(),task_id:zi().optional()}),wo("type",[mo({type:Co("registered"),chat_id:zi(),application_id:Xi().optional()}),mo({type:Co("pong")}),mo({type:Co("heartbeat")}),mo({type:Co("chat/response"),request_id:zi(),text:zi(),task_id:zi().optional()}),mo({type:Co("chat/error"),request_id:zi(),error:zi()}),mo({type:Co("task/status"),status:_o(["started","completed","failed","stopped","in_progress","has_question"]),message:zi().optional(),task_id:zi().optional(),timestamp:Xi().optional()}),mo({type:Co("tool/call"),call_id:zi(),tool:zi(),args:xo(zi(),so()),mode:_o(["show","do"]).optional(),explanation:zi().optional(),state_version:Xi().optional()})])),Ha=wo("type",[mo({type:Co("chat/tell"),request_id:zi(),content:zi()}),mo({type:Co("chat/show"),request_id:zi(),content:zi()}),mo({type:Co("chat/do"),request_id:zi(),content:zi()}),mo({type:Co("chat/stop"),task_id:zi().optional()}),mo({type:Co("tool/response"),call_id:zi(),success:ro(),data:zi().optional(),error:zi().optional(),state_version:Xi().optional()}),mo({type:Co("ping")}),mo({type:Co("rrweb/metadata"),session_id:zi(),chat_id:zi(),application_id:Xi(),url:zi().optional(),user_agent:zi().optional(),timestamp:Xi().optional()}),mo({type:Co("rrweb/events"),session_id:zi(),events:po(so())})]),Za=_o(["simulations","agents","qa","user","jobs"]),Va=wo("type",[mo({type:Co("simulation/updated"),simulation_id:Xi(),application_id:Xi(),status:zi(),step_label:zi().optional()}),mo({type:Co("simulation/created"),simulation_id:Xi(),application_id:Xi()}),mo({type:Co("simulation/deleted"),simulation_id:Xi(),application_id:Xi()}),mo({type:Co("agent/updated"),agent_id:Xi(),application_id:Xi(),status:zi()}),mo({type:Co("agent/created"),agent_id:Xi(),application_id:Xi()}),mo({type:Co("agent/deleted"),agent_id:Xi(),application_id:Xi()}),mo({type:Co("qa-document/updated"),document_id:Xi(),application_id:Xi(),status:zi(),step_label:zi().optional()}),mo({type:Co("qa-run/updated"),run_id:Xi(),document_id:Xi(),application_id:Xi(),status:zi()}),mo({type:Co("qa-test/updated"),test_id:Xi(),run_id:Xi(),document_id:Xi(),application_id:Xi(),status:zi()}),mo({type:Co("user/updated"),user_id:Xi(),workspace_id:Xi(),status:zi()}),mo({type:Co("job/progress"),job_id:zi(),application_id:Xi(),status:zi(),message:zi().optional()}),mo({type:Co("job/completed"),job_id:zi(),application_id:Xi(),result:so().optional()}),mo({type:Co("job/failed"),job_id:zi(),application_id:Xi(),error:zi()})]),qa=mo({details:zi().optional(),id:Xi().optional(),type:zi().optional(),name:zi().optional(),target_user_id:Xi().optional(),target_user_email:zi().optional(),reason:zi().optional(),assigned_role:zi().optional(),new_role:zi().optional(),previous_role:zi().optional(),workspace_name:zi().optional(),workspace_slug:zi().optional(),ip_address:zi().optional(),user_agent:zi().optional(),widget_type:zi().optional(),created_by:Xi().optional()}).passthrough(),Ja=ls.extend({workspace_id:Xi(),user_id:Xi(),type:as,metadata:qa.optional()}),Ya=Ja.partial().extend({type:as}),Ka=(ls.extend({user_id:Xi(),application_id:Xi(),agent_id:Xi(),chat_id:zi(),role:ns,source:rs,message:zi()}),ls.extend({workspace_id:Xi(),provider:ss,name:zi().min(1).max(120),identifier:zi().max(120).nullish(),api_endpoint:zi().url().nullish(),api_token:zi().nullish(),metadata:xo(zi(),so()).nullish(),is_active:ro().default(!0),status:Vo.default("active")})),Qa=mo({id:Wo().optional(),provider:ss,name:zi().min(1).max(120),identifier:zi().max(120).nullish(),api_endpoint:zi().url().nullish(),api_token:zi().nullish(),metadata:xo(zi(),so()).nullish(),is_active:ro().optional(),status:Vo.optional()}),Xa=mo({provider:ss.optional(),status:Vo.optional(),is_active:Go().optional(),limit:Wo().int().positive().max(100).optional(),offset:Wo().int().nonnegative().optional()}),el=mo({id:Xi(),full_name:zi(),name:zi(),private:ro(),html_url:zi(),default_branch:zi().optional()}),tl=mo({id:Xi(),name:zi(),status:zi(),conclusion:zi().nullable(),created_at:zi(),updated_at:zi(),html_url:zi(),head_branch:zi(),run_attempt:Xi()}),nl=_o(["pending","running","completed","failed","stopped"]),rl=(_o(["connector","condition"]),wo("kind",[mo({kind:Co("connector"),connector_type:zi().min(1),connector_id:Xi().nullable().optional(),capability:zi().min(1),role:_o(["trigger","callback"]),config:xo(zi(),so()).default({})}),mo({kind:Co("condition"),config:mo({field:zi().min(1),operator:_o(["equals","not_equals","contains","gt","lt"]),value:so()})})])),il=mo({from:zi().min(1),to:zi().min(1),when:_o(["true","false"]).optional()}),ol=mo({nodes:xo(zi(),rl),edges:po(il)}),sl=_o(["skip","queue","replace"]).default("skip"),al=ls.extend({workspace_id:Xi(),name:zi(),graph:ol,concurrency:sl,enabled:ro(),last_run_at:Ho().nullable(),next_run_at:Ho().nullable()}),ll=mo({name:zi().min(1).max(255),graph:ol,concurrency:sl.optional(),enabled:ro().optional()}),cl=mo({id:Wo(),name:zi().min(1).max(255).optional(),graph:ol.optional(),enabled:ro().optional()}),dl=mo({enabled:Go().optional(),limit:Wo().int().positive().max(100).optional(),offset:Wo().int().nonnegative().optional()}),ul=mo({status:_o(["completed","failed","skipped","stopped"]),output:xo(zi(),so()).nullable().optional(),error:zi().nullable().optional(),duration_ms:Xi().optional()}),pl=mo({id:Xi().optional(),automation_id:Xi(),status:nl,trigger_node_id:zi(),trigger_data:xo(zi(),so()).nullable(),node_results:xo(zi(),ul),started_at:Ho(),completed_at:Ho().nullable()}),hl=mo({status:nl.optional(),limit:Wo().int().positive().max(100).optional(),offset:Wo().int().nonnegative().optional()}),ml=mo({connector_type:zi(),built_in:ro(),triggers:po(mo({capability:zi(),description:zi(),config_schema:xo(zi(),so())})),callbacks:po(mo({capability:zi(),description:zi(),config_schema:xo(zi(),so())}))}),fl=mo({migration_type:zi().optional(),dry_run:ro().default(!0)}),gl=mo({migration_type:zi().optional(),backup:ro().default(!0)}),yl=mo({url:zi()}),wl=(mo({user_id:Xi(),file:Uo(File)}),mo({user_id:Xi(),application_id:Xi(),source:rs,prompt:zi(),status:zi()}),mo({user_id:Xi(),limit:Xi(),used:Xi(),remaining:Xi()})),bl=(mo({user_id:Xi(),workspace_id:Xi(),chat_count:Xi(),prompt_text:zi(),metadata:xo(zi(),zi()).optional()}),mo({to:zi(),subject:zi(),template:zi(),context:xo(zi(),zi())}),mo({id:zi(),object:Co("event"),api_version:zi().nullish(),created:Xi(),data:mo({object:xo(zi(),so()),previous_attributes:xo(zi(),so()).optional()}),livemode:ro(),pending_webhooks:Xi(),request:mo({id:zi().nullable(),idempotency_key:zi().nullable()}).nullable().optional(),type:zi()}),mo({priceId:zi().min(1,"Price ID is required"),successUrl:zi().url("Success URL must be a valid URL"),cancelUrl:zi().url("Cancel URL must be a valid URL")})),vl=mo({returnUrl:zi().url("Return URL must be a valid URL")}),xl=mo({plan:_o(["starter","growth"]).default("starter"),interval:_o(["month","year"]).default("month")}),kl=mo({subscriptionId:zi().min(1,"Subscription ID is required"),priceId:zi().min(1,"Price ID is required")}),_l=mo({success:ro(),message:zi()}),Sl=mo({subscriptionId:zi().nullable(),customerId:zi().nullable(),status:_o(["active","past_due","canceled","unpaid","trialing","incomplete","incomplete_expired","paused"]).nullable(),planTier:_o(["free","starter","growth","enterprise"]).nullable(),billingInterval:_o(["month","year"]).nullable(),priceId:zi().nullable(),trialEndDate:Ho().nullable(),currentPeriodStart:Ho().nullable(),currentPeriodEnd:Ho().nullable(),cancelAtPeriodEnd:ro(),isTrialing:ro(),daysRemainingInTrial:Xi().nullable(),trialProvisioned:ro()}),Cl=mo({sessionId:zi(),url:zi().url()}),Il=mo({url:zi().url()}),El=mo({subscriptionId:zi(),customerId:zi(),status:Co("trialing"),trialStartDate:Ho(),trialEndDate:Ho(),planTier:_o(["starter","growth"]),daysRemainingInTrial:Xi()}),Al=mo({used:Xi().int().min(0),limit:Xi().int()}),Tl=mo({applications:Al,simulationsPerMonth:Al,userPrompts:Al}),Ml=mo({amount:Xi().int().min(0),currency:zi().default("usd"),formatted:zi()}),zl=mo({planId:_o(["free","starter","growth","enterprise"]),monthly:Ml.nullable(),annual:Ml.nullable(),priceIds:mo({monthly:zi().nullable(),annual:zi().nullable()})}),Ol=mo({plans:po(zl),lastUpdated:zi().datetime()}),Rl=mo({id:_o(["free","starter","growth","enterprise"]),name:zi(),description:zi(),features:po(zi()),cta:zi(),isPopular:ro(),customPriceDisplay:zi().optional(),priceSubtext:zi().optional(),borderColor:zi(),buttonColor:zi(),outlineColor:zi(),checkColor:zi()}),Nl=mo({plans:po(Rl)}),Pl=mo({publishableKey:zi(),priceIds:mo({starter:mo({monthly:zi().nullable(),annual:zi().nullable()}),growth:mo({monthly:zi().nullable(),annual:zi().nullable()})}),trialDays:Xi().int().min(0),calendlyUrl:zi()}),Ll=mo({widgetKey:zi(),widgetId:zi(),widgetUrl:zi()}),Dl=mo({date:zi().describe("YYYY-MM-DD"),sessions:Xi().int().nonnegative(),events:Xi().int().nonnegative()}),$l=mo({items:po(Dl)}),jl=mo({role:_o(["user","assistant","system"]),content:zi(),timestamp:zi().optional()}),Fl=ls.extend({workspace_id:Xi(),application_id:Xi().nullish(),agent_id:Xi().nullish(),simulation_id:Xi().nullish(),chat_id:zi(),chat_content:zi().nullish(),chat_history:po(jl).nullish(),chat_output:zi().nullish(),preview_video_url:zi().nullish(),metadata:xo(zi(),so()).nullish()}),Ul=mo({application_id:Xi().nullish(),agent_id:Xi().nullish(),simulation_id:Xi().nullish(),chat_id:zi(),chat_content:zi().nullish(),chat_history:po(jl).nullish(),chat_output:zi().nullish(),preview_video_url:zi().nullish(),metadata:xo(zi(),so()).nullish()}),Bl=mo({chat_id:zi().optional(),agent_id:Xi().optional(),simulation_id:Xi().optional(),limit:Xi().optional(),offset:Xi().optional()}),Wl=class extends Error{issues;data;constructor(e){super(e.message,e),this.issues=e.issues,this.data=e.data}};function Gl(e,t){return{...e,...t}}var Hl=class{"~orpc";constructor(e){if(e.route?.successStatus&&X(e.route.successStatus))throw new Error("[ContractProcedure] Invalid successStatus.");if(Object.values(e.errorMap).some(e=>e&&e.status&&!X(e.status)))throw new Error("[ContractProcedure] Invalid error status code.");this["~orpc"]=e}};function Zl(e,t){let n=e;return t.prefix&&(n=function(e,t){return e.path?{...e,path:`${t}${e.path}`}:e}(n,t.prefix)),t.tags?.length&&(n=function(e,t){return{...e,tags:[...t,...e.tags??[]]}}(n,t.tags)),n}function Vl(e,t){if((n=e)instanceof Hl||("object"==typeof n||"function"==typeof n)&&null!==n&&"~orpc"in n&&"object"==typeof n["~orpc"]&&null!==n["~orpc"]&&"errorMap"in n["~orpc"]&&"route"in n["~orpc"]&&"meta"in n["~orpc"])return new Hl({...e["~orpc"],errorMap:Gl(t.errorMap,e["~orpc"].errorMap),route:Zl(e["~orpc"].route,t)});var n;const r={};for(const i in e)r[i]=Vl(e[i],t);return r}var ql=new class e extends Hl{constructor(e){super(e),this["~orpc"].prefix=e.prefix,this["~orpc"].tags=e.tags}$meta(t){return new e({...this["~orpc"],meta:t})}$route(t){return new e({...this["~orpc"],route:t})}$input(t){return new e({...this["~orpc"],inputSchema:t})}errors(t){return new e({...this["~orpc"],errorMap:Gl(this["~orpc"].errorMap,t)})}meta(t){return new e({...this["~orpc"],meta:(n=this["~orpc"].meta,r=t,{...n,...r})});var n,r}route(t){return new e({...this["~orpc"],route:(n=this["~orpc"].route,r=t,{...n,...r})});var n,r}input(t){return new e({...this["~orpc"],inputSchema:t})}output(t){return new e({...this["~orpc"],outputSchema:t})}prefix(t){return new e({...this["~orpc"],prefix:(n=this["~orpc"].prefix,r=t,n?`${n}${r}`:r)});var n,r}tag(...t){return new e({...this["~orpc"],tags:(n=this["~orpc"].tags,r=t,n?[...n,...r]:r)});var n,r}router(e){return Vl(e,this["~orpc"])}}({errorMap:{},route:{},meta:{}}),Jl=Symbol("ORPC_EVENT_ITERATOR_DETAILS");function Yl(e,t){return{"~standard":{[Jl]:{yields:e,returns:t},vendor:"orpc",version:1,validate:n=>D(n)?{value:ge(n,{async value(n,r){const i=r?t:e;if(!i)return n;const o=await i["~standard"].validate(n);if(o.issues)throw new Q("EVENT_ITERATOR_VALIDATION_FAILED",{message:"Event iterator validation failed",cause:new Wl({issues:o.issues,message:"Event iterator validation failed",data:n})});return o.value},error:async e=>e})}:{issues:[{message:"Expect event iterator",path:[]}]}}}}ql.route({method:"GET",tags:["Root"],path:"/",summary:"Get API index information and basic system details",description:"Returns general API information, version, and available endpoints"}).output(_s),ql.route({method:"GET",tags:["Internal"],path:"/health",summary:"Health check endpoint for monitoring system status",description:"Returns current system health, database connectivity, and service status"}).output(ks),ql.route({method:"GET",tags:["Root"],path:"/validate-url",summary:"Validate URL accessibility and DNS resolution",description:"Validates a URL for format, DNS resolution, and HTTP accessibility"}).input(mo({url:zi().url(),skip_network:zi().optional()})).output(mo({valid:ro(),accessible:ro(),dnsResolves:ro(),error:zi().optional().describe("Error message if URL validation failed"),warnings:po(zi()).optional().describe("Non-fatal issues found during URL validation")})),ql.route({method:"GET",tags:["Root"],path:"/config/public",summary:"Get public client configuration",description:"Returns widget key and widget ID. No auth. Values are stored in backend env only."}).output(Ll),ql.route({method:"GET",tags:["Auth"],path:"/auth/me",summary:"Get current authenticated user and workspace information",description:"Returns user profile and workspace data based on session cookie"}).output(mo({user:Cs,workspace:Ms.nullable(),workspaces:po(mo({id:Xi(),name:zi(),slug:zi(),role:_o(["owner","member"])}))})),ql.route({method:"GET",tags:["Auth"],path:"/email-action/{token}",summary:"Process email approval/rejection action",description:"Handles approve/reject links from admin emails. Token-in-URL authentication (no session required). Returns an HTML page, not JSON."}).input(mo({token:zi().min(1)})).output(mo({result:zi().describe("HTML response page")})),ql.route({method:"POST",tags:["Onboarding"],path:"/onboard",summary:"Complete user onboarding in one atomic operation",description:"Creates workspace, updates user status, and invites team members"}).input(mo({name:zi().min(1).max(45),slug:zi().min(1).max(45).optional(),domain:zi().min(1).max(200),team_emails:po(zi().email()).optional().default([]),app_url:zi().optional(),app_username:zi().optional(),app_password:zi().optional()})).output(mo({workspace:Ms})),ql.route({method:"POST",tags:["Workspace"],path:"/workspaces",summary:"Create a new workspace",description:"Creates new workspace with specified settings and returns workspace entity"}).input(zs).output(Ms),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces",summary:"Search and filter workspaces by various criteria",description:"Returns list of workspaces matching search parameters (name, domain, email, etc.)"}).input(mo({name:zi().optional(),domain:zi().optional(),email:zi().email().optional(),app_id:Wo().optional(),workspace_id:Wo().optional(),user_id:Wo().optional()}).extend(bs.shape)).output(vs(Ms)),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces/lookup/{slug}",summary:"Look up workspace by slug for onboarding",description:"Returns workspace name and slug for join-workspace flow. Requires onboarding-level auth."}).input(us).output(mo({name:zi(),slug:zi()}).nullable()),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces/{slug}",summary:"Get specific workspace details by slug",description:"Returns complete workspace information including settings and configuration"}).input(us).output(Ms),ql.route({method:"PUT",tags:["Workspace"],path:"/workspaces/{slug}",summary:"Update workspace settings and configuration",description:"Modifies workspace properties like name, domain, or feature settings"}).input(Os.extend({slug:zi()})).output(Ms),ql.route({method:"DELETE",tags:["Workspace"],path:"/workspaces/{slug}",summary:"Delete workspace and all associated data",description:"Permanently deletes a workspace and cleans up all related resources. This action cannot be undone."}).input(us).output(ys),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces/{slug}/members",summary:"List workspace members",description:"Returns all members of the workspace with their user profile details and roles."}).input(us).output(xs(Ls.extend({user:Cs.pick({id:!0,email:!0,first_name:!0,last_name:!0,image_url:!0})}))),ql.route({method:"POST",tags:["Workspace"],path:"/workspaces/{slug}/members",summary:"Add member to workspace",description:"Invites a user by email to join the workspace with the specified role. Defaults to member role."}).input(us.extend({email:zi().email(),role:Ps.default("member")})).output(Ls),ql.route({method:"DELETE",tags:["Workspace"],path:"/workspaces/{slug}/members/{user_id}",summary:"Remove member from workspace",description:"Removes a user from the workspace by user_id. The user loses access immediately."}).input(us.extend({user_id:Xi()})).output(ys),ql.route({method:"PATCH",tags:["Workspace"],path:"/workspaces/{slug}/members/{user_id}",summary:"Update member role",description:"Changes the role of a workspace member. Valid roles: owner, member."}).input(us.extend({user_id:Xi(),role:Ps})).output(Ls),ql.route({method:"GET",tags:["Workspace"],path:"/users/me/workspaces",summary:"List workspaces for current user",description:"Returns all workspaces the authenticated user belongs to, including their role in each."}).output(xs(Ms.extend({role:Ps}))),ql.route({method:"POST",path:"/admin/reconcile",tags:["Internal"],summary:"Reconcile Stripe customers and WorkOS users",description:"Backfills missing Stripe customer IDs for workspaces and real WorkOS user IDs for users. Idempotent and safe to run repeatedly. Requires super user role."}).output(mo({workspaces_stripe_created:Xi(),users_workos_created:Xi(),workspace_plans_synced:Xi(),trials_provisioned:Xi(),stripe_plans_refreshed:Xi(),workos_profiles_synced:Xi(),errors:po(mo({type:zi(),id:Xi(),error:zi()}))})),ql.route({method:"POST",path:"/admin/maintenance",tags:["Internal"],summary:"Run periodic maintenance cleanup tasks",description:"Cleans up orphaned CosmosDB containers, QA simulations not linked to existing runs, and orphaned blob storage files. Idempotent and safe to run repeatedly. Requires super user role."}).output(mo({cosmos_containers_deleted:Xi(),orphaned_qa_simulations_deleted:Xi(),orphaned_blob_dirs_deleted:Xi(),errors:po(mo({type:zi(),detail:zi()}))})),ql.route({method:"POST",path:"/admin/rebuild",tags:["Internal"],summary:"Rebuild all agent indexes after cleanup",description:"Removes stale knowledge (missing files), stale simulations (0 steps or missing blobs), then deletes and recreates vector stores and knowledge graphs for every agent. Index creation is async. Requires super user role."}).output(mo({knowledge_removed:Xi(),simulations_removed:Xi(),agents_rebuilt:Xi(),errors:po(mo({type:zi(),detail:zi()}))})),ql.route({method:"POST",tags:["Application"],path:"/applications",summary:"Create a new application",description:"Creates a new application for the authenticated workspace and returns the created entity."}).input(Ma).output(Ta),ql.route({method:"GET",tags:["Application"],path:"/applications",summary:"Search applications for workspace",description:"Returns applications for the authenticated workspace, optionally filtered by type, always includes widgets"}).input(mo({type:is.optional(),include:po(_o(["widgets"])).optional()}).extend(bs.shape)).output(vs(Ta.extend({widgets:po(Pa).optional()}))),ql.route({method:"GET",tags:["Application"],path:"/applications/{application_id}",summary:"Get application by ID",description:"Returns specific application details by ID, always includes widgets"}).input(fs).output(Ta.extend({widgets:po(Pa)})),ql.route({method:"PUT",tags:["Application"],path:"/applications/{application_id}",summary:"Update application",description:"Updates application details and configuration"}).input(za.extend({application_id:Wo()})).output(Ta),ql.route({method:"DELETE",tags:["Application"],path:"/applications/{application_id}",summary:"Delete application",description:"Permanently deletes an application and all associated widgets. This action cannot be undone."}).input(fs).output(ys),ql.route({method:"POST",tags:["Widget"],path:"/widgets",summary:"Create a new widget",description:"Creates a new widget for an application and returns the created entity. Requires an application_id."}).input(Da).output(Pa),ql.route({method:"GET",tags:["Widget"],path:"/widgets",summary:"Search widgets for workspace",description:"Search widgets by type, application, marketrix_id, or marketrix_key"}).input(mo({type:os.optional(),application_id:Wo().optional(),marketrix_id:zi().optional(),marketrix_key:zi().optional(),include:po(_o(["agent"])).optional()}).extend(bs.shape)).output(vs(La)),ql.route({method:"GET",tags:["Widget"],path:"/widgets/defaults/{type}",summary:"Get default settings for widget type",description:"Returns default settings for the specified widget type"}).input(mo({type:os})).output(go([Ra,Na])),ql.route({method:"GET",tags:["Widget"],path:"/widgets/{widget_id}",summary:"Get widget by ID",description:"Returns specific widget details by widget ID including snippet code"}).input(hs).output(Pa),ql.route({method:"PUT",tags:["Widget"],path:"/widgets/{widget_id}",summary:"Update widget",description:"Updates widget settings and configuration"}).input($a.extend({widget_id:Wo()})).output(Pa),ql.route({method:"DELETE",tags:["Widget"],path:"/widgets/{widget_id}",summary:"Delete widget",description:"Permanently deletes a widget from an application. This action cannot be undone."}).input(hs).output(ys),ql.route({method:"POST",tags:["Chat"],path:"/chat",summary:"Create a new chat thread",description:"Initializes new chat thread and returns session ID"}).output(zi()),ql.route({method:"GET",tags:["Chat"],path:"/chat",summary:"Search chats by user",description:"Returns chat list and quota for the specified user"}).input(mo({user_id:Wo().optional(),chat_id:Wo().optional()})).output(wl),ql.route({method:"POST",tags:["Chat"],path:"/preview-video-chat",summary:"Create or update preview video chat record",description:"Persists guide preview chat content, history, output, and related simulation metadata"}).input(Ul).output(Fl),ql.route({method:"GET",tags:["Chat"],path:"/preview-video-chat",summary:"Search preview video chat records",description:"Returns preview chat records filtered by chat_id, agent_id, or simulation_id for current workspace"}).input(Bl).output(xs(Fl)),ql.route({method:"GET",tags:["Chat"],path:"/preview-video-chat/{id}",summary:"Get preview video chat record by ID",description:"Returns a single preview chat record for current workspace"}).input(ds).output(Fl.nullable()),ql.route({method:"POST",tags:["Connector"],path:"/connector",summary:"Create or update connector",description:"Stores provider credentials and API endpoint details for workspace connectors"}).input(Qa).output(Ka),ql.route({method:"GET",tags:["Connector"],path:"/connector",summary:"Search connectors",description:"Returns workspace connectors filtered by provider/status"}).input(Xa).output(vs(Ka)),ql.route({method:"GET",tags:["Connector"],path:"/connector/{id}",summary:"Get connector by ID",description:"Returns a single workspace connector"}).input(ds).output(Ka.nullable()),ql.route({method:"DELETE",tags:["Connector"],path:"/connector/{id}",summary:"Delete connector",description:"Permanently deletes a connector for current workspace. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"GET",tags:["Connector"],path:"/connector/{id}/github/repos",summary:"List GitHub repositories for a GitHub connector",description:"Uses the stored GitHub PAT from the connector to call GitHub /user/repos."}).input(mo({id:Wo(),per_page:Wo().int().min(1).max(100).optional(),page:Wo().int().min(1).optional()})).output(po(el)),ql.route({method:"GET",tags:["Connector"],path:"/connector/{id}/github/repos/{owner}/{repo}/actions/runs",summary:"List GitHub Actions workflow runs",description:"Lists workflow runs for a repository (pass/fail status)."}).input(mo({id:Wo(),owner:zi().min(1),repo:zi().min(1),per_page:Wo().int().min(1).max(100).optional(),page:Wo().int().min(1).optional()})).output(po(tl)),ql.route({method:"POST",tags:["Automation"],path:"/automation",summary:"Create automation",description:"Creates a DAG-based automation workflow"}).input(ll).output(al),ql.route({method:"GET",tags:["Automation"],path:"/automation",summary:"List automations",description:"Returns automations for the current workspace"}).input(dl).output(vs(al)),ql.route({method:"GET",tags:["Automation"],path:"/automation/{id}",summary:"Get automation",description:"Returns a single automation with its graph"}).input(ds).output(al.nullable()),ql.route({method:"PUT",tags:["Automation"],path:"/automation/{id}",summary:"Update automation",description:"Updates automation graph and settings"}).input(cl).output(al),ql.route({method:"DELETE",tags:["Automation"],path:"/automation/{id}",summary:"Delete automation",description:"Permanently deletes an automation and deregisters its triggers"}).input(ds).output(ys),ql.route({method:"PATCH",tags:["Automation"],path:"/automation/{id}/toggle",summary:"Toggle automation",description:"Enable or disable an automation"}).input(mo({id:Wo(),enabled:ro()})).output(al),ql.route({method:"POST",tags:["Automation"],path:"/automation/{id}/run",summary:"Trigger automation run",description:"Manually triggers an automation run"}).input(ds).output(pl.nullable()),ql.route({method:"GET",tags:["Automation"],path:"/automation/{id}/runs",summary:"List automation runs",description:"Returns execution history for an automation"}).input(mo({id:Wo()}).extend(hl.shape)).output(vs(pl)),ql.route({method:"GET",tags:["Automation"],path:"/automation/{id}/runs/{run_id}",summary:"Get automation run",description:"Returns a single run with per-node results"}).input(mo({id:Wo(),run_id:Wo()})).output(pl.nullable()),ql.route({method:"GET",tags:["Connector"],path:"/connector-capabilities",summary:"List connector capabilities",description:"Returns available triggers and callbacks per connector type"}).input(mo({})).output(po(ml)),ql.route({method:"GET",tags:["User"],path:"/user",summary:"Search and filter users by workspace",description:"Returns list of users associated with specified workspace"}).input(mo({workspace_id:Wo().optional(),status:Vo.optional()}).extend(bs.shape)).output(vs(Cs)),ql.route({method:"POST",tags:["User"],path:"/user/batch",summary:"Create multiple users in batch operation",description:"Processes bulk user creation and returns results for each user"}).input(As).output(po(Ts)),ql.route({method:"GET",tags:["User"],path:"/user/{user_id}",summary:"Get specific user details by ID",description:"Returns complete user information including profile and settings"}).input(gs).output(Cs),ql.route({method:"PUT",tags:["User"],path:"/user/{user_id}",summary:"Update user profile and settings",description:"Modifies user properties like name, email, or preferences"}).input(Es.extend({user_id:Wo()})).output(Cs),ql.route({method:"PUT",tags:["User"],path:"/user/{user_id}/image",summary:"Upload and update user profile image",description:"Handles file upload for user avatar and returns upload response"}).input(cs.extend({user_id:Wo()})).output(yl),ql.route({method:"DELETE",tags:["User"],path:"/user/{user_id}",summary:"Delete user account and all associated data",description:"Permanently deletes a user account and cleans up all related resources. This action cannot be undone."}).input(gs).output(ys),ql.route({method:"POST",tags:["User"],path:"/user/{user_id}/deactivate",summary:"Deactivate user account without deletion",description:"Deactivates user access while preserving data for potential reactivation"}).input(gs.extend({reason:zi().optional()})).output(ys),ql.route({method:"POST",tags:["Agent"],path:"/agent",summary:"Create new AI agent with configuration",description:"Creates agent with specified settings, prompts, and returns agent entity"}).input(Sa).output(va),ql.route({method:"GET",tags:["Agent"],path:"/agent",summary:"Search and filter agents by workspace or user",description:"Returns list of agents matching search parameters. Supports filtering by workspace_id, user_id, and application_id."}).input(mo({workspace_id:Wo().optional(),user_id:Wo().optional(),application_id:Wo().optional(),include:po(_o(["knowledge","simulations"])).optional()}).extend(bs.shape)).output(vs(va)),ql.route({method:"GET",tags:["Agent"],path:"/agent/{agent_id}",summary:"Get specific agent details by ID",description:"Returns complete agent information including configuration and settings"}).input(ps.extend({include:po(_o(["knowledge","simulations"])).optional()})).output(va),ql.route({method:"GET",tags:["Agent"],path:"/agent/{agent_id}/mindmap",summary:"Get agent mindmap by ID",description:"Returns the mindmap knowledge graph for the specified agent"}).input(ps).output(ba),ql.route({method:"PUT",tags:["Agent"],path:"/agent/{agent_id}",summary:"Update agent configuration and settings",description:"Updates agent details. For JSON requests, handled by oRPC. Also accepts multipart/form-data for logo file uploads (handled by raw Express route)."}).input(Ca.extend({agent_id:Wo(),force_reset_learning:Go().optional()})).output(va),ql.route({method:"DELETE",tags:["Agent"],path:"/agent/{agent_id}",summary:"Delete agent and all associated data",description:"Permanently deletes an agent and cleans up all related resources. This action cannot be undone."}).input(ps).output(ys),ql.route({method:"POST",tags:["Agent"],path:"/agent/{agent_id}/index",summary:"Index simulation document into agent knowledge base",description:"Adds a simulation document to an agent's knowledge base and refreshes the search index"}).input(Ea.extend({agent_id:Wo()})).output(Aa),ql.route({method:"POST",tags:["Agent"],path:"/agent/{agent_id}/reset-learning",summary:"Force reset agent from stuck learning state",description:"Resets an agent that is stuck in learning state, setting it to error status with a message explaining the reset"}).input(ps).output(va),ql.route({method:"POST",tags:["Activity Log"],path:"/log",summary:"Create new activity log entry",description:"Records user or system action for auditing and tracking purposes"}).input(Ya).output(Ja),ql.route({method:"GET",tags:["Activity Log"],path:"/log",summary:"Search and filter activity logs",description:"Returns list of activity logs matching search parameters (workspace, type)"}).input(mo({workspace_id:Wo().optional(),type:as.optional(),application_id:Wo().optional()}).extend(bs.shape)).output(vs(Ja)),ql.route({method:"GET",tags:["Tour"],path:"/tour",summary:"Search and filter tours by workspace",description:"Returns list of available tours for specified workspace"}).input(mo({workspace_id:Wo().optional(),application_id:Wo().optional()}).extend(bs.shape)).output(vs(Wa)),ql.route({method:"POST",tags:["Tour"],path:"/tour",summary:"Create new interactive tour",description:"Creates tour with specified steps and configuration"}).input(Wa).output(Wa),ql.route({method:"GET",tags:["URL Guide"],path:"/url-guide",summary:"Search URL guides by widget",description:"Returns list of URL guides for specified widget"}).input(hs.extend(bs.shape)).output(vs(ja)),ql.route({method:"POST",tags:["URL Guide"],path:"/url-guide",summary:"Create new URL guide",description:"Creates URL guide with pattern and message"}).input(Fa).output(ja),ql.route({method:"GET",tags:["URL Guide"],path:"/url-guide/{id}",summary:"Get URL guide by ID",description:"Returns URL guide details"}).input(ds).output(ja),ql.route({method:"PUT",tags:["URL Guide"],path:"/url-guide/{id}",summary:"Update URL guide",description:"Updates URL guide properties"}).input(Ua.extend({id:Wo()})).output(ja),ql.route({method:"DELETE",tags:["URL Guide"],path:"/url-guide/{id}",summary:"Delete URL guide",description:"Permanently deletes a URL guide. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"GET",tags:["URL Guide"],path:"/url-guide/match",summary:"Find matching URL guide for current URL",description:"Returns matching URL guide for a given URL pattern"}).input(mo({widget_id:Wo(),url:zi()})).output(ja.nullable()),ql.route({method:"GET",tags:["Simulation"],path:"/simulation",summary:"Search and filter simulations by workspace",description:"Returns list of simulations associated with specified workspace. Use application_id, agent_id, or pinned to filter."}).input(mo({workspace_id:Wo().optional(),application_id:Wo().optional(),agent_id:Wo().optional(),pinned:go([ro(),zi()]).optional().transform(e=>void 0===e?void 0:"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0),source:_o(["direct","qa"]).optional(),include:po(_o(["agent","application"])).optional()}).extend(bs.shape)).output(vs(da)),ql.route({method:"POST",tags:["Simulation"],path:"/simulation/start",summary:"Start new application simulation",description:"Creates and initializes simulation with specified parameters"}).input(ua).output(da),ql.route({method:"PUT",tags:["Simulation"],path:"/simulation/{simulation_id}",summary:"Update simulation configuration and status",description:"Modifies simulation parameters and updates execution state"}).input(pa.extend({simulation_id:Wo()})).output(da),ql.route({method:"PUT",tags:["Simulation"],path:"/simulation/{simulation_id}/agents",summary:"Assign agents to a simulation",description:"Sets which agents use this simulation for their knowledge. Triggers learning on affected agents."}).input(ms.extend({agent_ids:po(Xi())})).output(da),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/progress",summary:"Get simulation progress history as chat transcript",description:"Returns all progress updates for a simulation ordered chronologically"}).input(ms).output(xs(ga)),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/live-view",summary:"Get live view URL for simulation session",description:"Returns Browserbase live view URL for embedding in iframe"}).input(ms).output(mo({session_id:zi(),live_view_url:zi(),status:zi()})),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/history",summary:"Get simulation history by ID",description:"Returns the history array for the specified simulation"}).input(ms).output(xs(aa)),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/steps",summary:"Get all simulation steps with topic and screenshot link as JSON",description:"Returns each step with step_number, topic, screenshot_url, and optional title/url for the simulation"}).input(ms).output(xs(la)),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/mindmap",summary:"Get simulation mindmap by ID",description:"Returns the mindmap knowledge graph for the specified simulation"}).input(ms).output(ba),ql.route({method:"POST",tags:["Simulation"],path:"/simulation/{simulation_id}/stop",summary:"Stop running simulation",description:"Terminates a running simulation and closes its browser session."}).input(ms).output(ws),ql.route({method:"POST",tags:["Simulation"],path:"/simulation/{simulation_id}/answer",summary:"Submit answer to simulation question",description:"Submits an answer to a pending question from the simulation agent"}).input(ha.extend({simulation_id:Wo()})).output(ws),ql.route({method:"DELETE",tags:["Simulation"],path:"/simulation/{simulation_id}",summary:"Delete simulation",description:"Permanently deletes a simulation and all associated data. Only works on simulations in terminal state."}).input(ms).output(ws),ql.route({method:"POST",tags:["Session"],path:"/sessions",summary:"Create or update session",description:"Creates a new session or updates an existing one"}).input(fa).output(ma),ql.route({method:"GET",tags:["Session"],path:"/sessions/{session_id}",summary:"Get session by session ID",description:"Retrieves a session by its session_id"}).input(mo({session_id:zi().min(1)})).output(ma.nullable()),ql.route({method:"GET",tags:["Session"],path:"/sessions/chat/{chat_id}",summary:"Get sessions by chat ID",description:"Retrieves all sessions for a given chat_id"}).input(mo({chat_id:zi().min(1)})).output(xs(ma)),ql.route({method:"GET",tags:["Session"],path:"/sessions",summary:"Get all sessions",description:"Retrieves all sessions ordered by creation date, optionally filtered by application and date range"}).input(mo({application_id:Wo().optional(),start_date:zi().optional(),end_date:zi().optional()}).extend(bs.shape)).output(vs(ma)),ql.route({method:"GET",tags:["Session"],path:"/sessions/stats",summary:"Get session activity stats",description:"Returns daily aggregated session metrics for charting. Each entry is one calendar day with session count and total event count."}).input(mo({application_id:Wo(),start_date:zi().describe("YYYY-MM-DD"),end_date:zi().describe("YYYY-MM-DD")})).output($l),ql.route({method:"GET",tags:["Session"],path:"/sessions/{session_id}/events",summary:"Get session events",description:"Fetches all batches from folder, combines them in correct order, and returns events array"}).input(mo({session_id:zi().min(1)})).output(xs(mo({type:Xi(),timestamp:Xi(),data:so().describe("rrweb event payload — shape defined by rrweb library")}))),ql.route({method:"POST",tags:["Browser Session"],path:"/browser-session/create",summary:"Create browser session for application",description:"Creates a browser session and navigates to the application URL"}).input(mo({application_id:Xi(),agent_id:Xi(),url:zi().nullish()})).output(mo({session_id:zi(),live_view_url:zi()})),ql.route({method:"POST",tags:["Browser Session"],path:"/browser-session/{session_id}/stop",summary:"Stop browser session",description:"Stops all running tasks and closes the browser session. Set stop_tasks=false to skip task cleanup."}).input(mo({session_id:zi(),stop_tasks:ro().optional().default(!0)})).output(ws),ql.route({method:"GET",tags:["Knowledge"],path:"/knowledge",summary:"Search and filter knowledge base documents",description:"Returns list of knowledge documents matching search parameters. Supports filtering by workspace_id, type, and application_id."}).input(mo({workspace_id:Wo().optional(),type:Xo.optional(),application_id:Wo().optional(),include:po(_o(["agents","application"])).optional()}).extend(bs.shape)).output(vs($s)),ql.route({method:"POST",tags:["Knowledge"],path:"/knowledge",summary:"Upload new knowledge base document",description:"Upload a file, document URL, or video URL to create a knowledge entry for AI training"}).input(mo({file:Uo(File).optional(),application_id:Wo(),document_url:zi().url().optional(),document_name:zi().optional(),video_url:zi().url().optional(),video_name:zi().optional()})).output($s),ql.route({method:"GET",tags:["Knowledge"],path:"/knowledge/{id}",summary:"Get specific knowledge document by ID",description:"Returns complete knowledge document information and content"}).input(ds).output($s),ql.route({method:"DELETE",tags:["Knowledge"],path:"/knowledge/{id}",summary:"Delete knowledge document",description:"Permanently deletes a knowledge document from the database. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"POST",tags:["Knowledge"],path:"/knowledge/{id}/refresh",summary:"Refresh knowledge document",description:"Re-fetches HTML content from source URL and updates the document"}).input(ds).output($s),ql.route({method:"PUT",tags:["Knowledge"],path:"/knowledge/{knowledge_id}/agents",summary:"Assign agents to a knowledge item",description:"Sets which agents use this knowledge item. Triggers learning on affected agents."}).input(mo({knowledge_id:Wo(),agent_ids:po(Xi())})).output($s),ql.route({method:"POST",tags:["QA"],path:"/qa/document",summary:"Upload QA flow (file or text)",description:"Uploads a PDF/text file or text content for QA test generation. Also accepts multipart/form-data for file uploads (handled by raw Express route)."}).input(Bs).output(Us),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/process",summary:"Process QA flow and generate test cases",description:"Starts async processing (returns 202). Poll GET /qa/document/:id for status and processing_step until completed/failed."}).input(ds).output(mo({document:Us})),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/refine",summary:"Refine existing QA test cases",description:"Refines existing test cases with a refinement prompt via AI agent API"}).input(ds.extend({refinementPrompt:zi().min(5).max(2e3)})).output(Js),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/process/stream",summary:"Process QA flow with SSE streaming",description:"Streams processing events as Server-Sent Events. Events: response.created, response.progress, response.clear, response.completed, error."}).input(ds).output(Yl(mo({event:zi().describe("SSE event type: response.created | response.progress | response.clear | response.completed | error"),data:so().describe("Event payload object — shape varies by event type")}))),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/refine/stream",summary:"Refine QA flow test cases with SSE streaming",description:"Streams refinement events as Server-Sent Events. Requires a refinement prompt (min 5 chars)."}).input(ds.extend({refinementPrompt:zi().min(5)})).output(Yl(mo({event:zi().describe("SSE event type: response.created | response.progress | response.clear | response.completed | error"),data:so().describe("Event payload object — shape varies by event type")}))),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}",summary:"Get QA flow by ID",description:"Retrieves a QA flow by its ID"}).input(ds).output(Us),ql.route({method:"GET",tags:["QA"],path:"/qa/document",summary:"List QA flows",description:"Returns all QA flows with aggregated metrics (run_count, pass_rate, total_failed) and the last run summary. Supports filtering by application_id."}).input(mo({application_id:Wo().optional()}).extend(bs.shape)).output(vs(Us.extend({run_count:Xi(),display_title:zi(),total_failed:Xi(),pass_rate:Xi().nullable(),last_run:mo({id:Xi(),status:zi(),total_tests:Xi(),passed_tests:Xi(),failed_tests:Xi(),created_at:Ho().nullable()}).nullable()})).extend({metrics:mo({total_flows:Xi(),total_runs:Xi(),avg_pass_rate:Xi().nullable(),total_failed:Xi(),total_passed:Xi()})})),ql.route({method:"DELETE",tags:["QA"],path:"/qa/document/{id}",summary:"Delete QA flow",description:"Permanently deletes a QA flow and all its runs and test cases. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"PUT",tags:["QA"],path:"/qa/document/{id}",summary:"Update QA flow status",description:"Updates the status of a QA flow"}).input(ds.extend({status:es})).output(Us),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}/runs",summary:"List runs for a QA flow",description:"Returns all runs for a document with total/passed/failed counts"}).input(ds.extend(bs.shape)).output(vs(Ws.extend({total_tests:Xi(),passed:Xi(),failed:Xi()}))),ql.route({method:"GET",tags:["QA"],path:"/qa/run/{id}",summary:"Get a QA run by ID",description:"Returns run details with test cases"}).input(ds).output(Ws.extend({test_cases:po(qs)})),ql.route({method:"DELETE",tags:["QA"],path:"/qa/run/{id}",summary:"Delete a QA run",description:"Permanently deletes a QA run and all its test case results. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/run",summary:"Create and start a new QA run",description:"Creates a new run and starts execution. Returns 202; poll test-cases for execution status."}).input(ds).output(mo({run:Ws,simulations:po(da)})),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}/test-cases",summary:"Get test cases for a QA flow",description:"Retrieves test cases; optional run_id scopes to that run"}).input(ds.extend({run_id:Wo().optional()})).output(xs(qs)),ql.route({method:"PUT",tags:["QA"],path:"/qa/test-case/{id}",summary:"Update test case definition fields",description:"Updates a test case definition (title, objective, steps, etc.)"}).input(ds.extend({test_title:zi().optional(),test_objective:zi().optional(),test_steps:po(zi()).optional(),expected_outcome:zi().optional(),priority:_o(["Low","Medium","High"]).optional(),is_active:ro().optional()})).output(qs),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/execute",summary:"Create a run and execute all pending tests for a QA flow as simulations",description:"Creates a new QA run, then starts a simulation for every active test case. Returns the run and simulation entities."}).input(ds).output(mo({run:Ws,simulations:po(da)})),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/execute",summary:"Execute a single test case as a simulation",description:"Starts a simulation for the specified test case and returns the simulation entity."}).input(ds).output(mo({simulation:da})),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/simulation",summary:"Get the simulation linked to a test case",description:"Returns the simulation entity associated with the test case, or null if no simulation exists."}).input(ds).output(mo({simulation:da.nullable()})),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/versions",summary:"Get version history for a test case",description:"Returns all version entries from the test case version_history JSON"}).input(ds).output(xs(Zs)),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}",summary:"Get specific test case version",description:"Returns a specific version entry from the test case version_history JSON"}).input(ds.extend({version:Wo()})).output(Zs),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}/rollback",summary:"Rollback to specific version",description:"Restores test case to a previous version and appends new version entry"}).input(ds.extend({version:Wo()})).output(Zs),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/versions/compare",summary:"Compare two versions",description:"Returns differences between two test case versions"}).input(ds.extend({version1:Wo(),version2:Wo()})).output(mo({version1:Zs,version2:Zs,diff:po(mo({field:zi(),oldValue:Ks,newValue:Ks}))})),ql.route({method:"DELETE",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}",summary:"Delete a specific version",description:"Removes a version from history and reverts test case to previous version if it was the latest"}).input(ds.extend({version:Wo()})).output(ys.extend({current_version:Xi()})),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}/accept",summary:"Accept a specific version",description:"Marks a version as accepted by the user"}).input(ds.extend({version:Wo()})).output(ys),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/healing-attempts",summary:"Get healing attempts for a test case",description:"Returns all healing attempt entries from the test case healing_attempts JSON"}).input(ds).output(xs(Vs)),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/healing-attempts/{attemptIndex}/approve",summary:"Approve a healing attempt",description:"Applies the repair from a validated healing attempt by array index"}).input(ds.extend({attemptIndex:Wo()})).output(ys),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/healing-attempts/{attemptIndex}/reject",summary:"Reject a healing attempt",description:"Marks a healing attempt as rejected by array index"}).input(ds.extend({attemptIndex:Wo()})).output(ys),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/heal",summary:"Trigger self-healing for a failed test case",description:"Initiates the self-healing workflow for a test case"}).input(ds.extend({simulation_id:Xi(),config:mo({enabled:ro().optional(),autoApply:ro().optional(),minConfidenceThreshold:Xi().min(0).max(1).optional(),maxHealingAttempts:Xi().int().min(1).max(5).optional()}).optional()})).output(mo({healed:ro(),attemptIndex:Xi().nullable(),analysis:Xs.nullable(),confidence:Xi().nullable()})),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/run-cross-browser",summary:"Execute cross-browser tests",description:"Runs tests across multiple browsers (chromium, firefox, webkit)"}).input(Fs.extend({id:Wo()})).output(mo({runs:po(mo({browserType:js,runId:Xi(),status:_o(["completed","failed","skipped"]),passedTests:Xi(),failedTests:Xi(),totalTests:Xi()})),summary:mo({totalRuns:Xi(),completedRuns:Xi(),failedRuns:Xi(),overallPassed:Xi(),overallFailed:Xi()})})),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}/cross-browser-comparison",summary:"Get cross-browser comparison",description:"Returns test cases comparison across different browsers"}).input(ds).output(mo({byTest:xo(zi(),xo(zi(),mo({status:zi(),runId:Xi()}))),byBrowser:xo(zi(),mo({passed:Xi(),failed:Xi(),total:Xi()}))})),ql.route({method:"PUT",tags:["QA"],path:"/qa/document/{id}/browser-config",summary:"Update browser configuration",description:"Updates the default browser configuration for a QA flow"}).input(Fs.extend({id:Wo()})).output(ys),ql.route({method:"POST",tags:["Internal"],path:"/migrate/prepare",summary:"Prepare database migration",description:"Validates migration requirements and prepares system for migration"}).input(fl).output(mo({message:zi(),status:zi(),data:fl})),ql.route({method:"POST",tags:["Internal"],path:"/migrate/run",summary:"Execute database migration",description:"Runs migration scripts and updates database schema"}).input(gl).output(mo({message:zi(),status:zi(),data:gl})),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/trial",summary:"Create a trial subscription",description:"Creates a trial subscription for the authenticated workspace. The trial period is 30 days by default."}).input(xl).output(El),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/checkout",summary:"Create a checkout session for subscription purchase",description:"Creates a Stripe checkout session for purchasing a subscription. Returns a session URL for redirect."}).input(bl).output(Cl),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/portal",summary:"Create a customer portal session",description:"Creates a Stripe billing portal session for managing subscription, payment methods, and invoices."}).input(vl).output(Il),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/downgrade",summary:"Confirm and process a subscription downgrade",description:"Processes a confirmed subscription downgrade to a lower tier plan. No payment required."}).input(kl).output(_l),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/cancel",summary:"Cancel subscription at period end",description:"Cancels the subscription at the end of the current billing period."}).input(mo({subscriptionId:zi().min(1)})).output(mo({subscriptionId:zi(),cancelAtPeriodEnd:ro()})),ql.route({method:"GET",tags:["Stripe"],path:"/stripe/catalog",summary:"Get public Stripe catalog (pricing, plans, config)",description:"Returns pricing from Stripe, plan catalog metadata, and Stripe frontend configuration in a single call."}).output(mo({pricing:Ol,plans:Nl,config:Pl})),ql.route({method:"GET",tags:["Stripe"],path:"/stripe/subscription",summary:"Get current subscription plan and usage",description:"Returns current subscription plan information and actual usage statistics for the authenticated workspace."}).output(mo({plan:Sl,usage:Tl})),ql.route({method:"GET",tags:["Widget"],path:"/widget/stream",summary:"SSE stream for real-time widget events",description:"Typed event stream delivering tool calls, task status updates, chat responses, and registration confirmation."}).input(mo({chat_id:zi(),tab_id:zi().optional(),marketrix_id:zi().optional(),marketrix_key:zi().optional(),agent_id:Wo().optional(),application_id:Wo().optional()})).output(Yl(Ga)),ql.route({method:"POST",tags:["Widget"],path:"/widget/message",summary:"Send a typed command from widget to server",description:"Receives chat commands, tool responses, and keepalive pings from the widget."}).input(mo({chat_id:zi(),command:Ha})).output(mo({ok:ro()})),ql.route({method:"GET",tags:["App"],path:"/app/events",summary:"SSE stream for real-time app dashboard events",description:"Typed event stream delivering simulation, agent, QA, and user updates filtered by scope and application."}).input(mo({scopes:po(Za).min(1),application_id:Wo().optional()})).output(Yl(Va)),ql.route({method:"POST",tags:["Internal"],path:"/workos/webhook",summary:"WorkOS webhook receiver",description:"Receives webhook events from WorkOS (user management, SSO). Verified via workos-signature header. Not for external use."}).input(mo({event:zi(),data:xo(zi(),so())})).output(mo({received:ro()})),ql.route({method:"POST",tags:["Internal"],path:"/stripe/webhook",summary:"Stripe webhook receiver",description:"Receives webhook events from Stripe (payments, subscriptions). Verified via stripe-signature header. Not for external use."}).input(mo({id:zi(),object:zi(),type:zi(),data:xo(zi(),so())}).passthrough().describe("Stripe event payload")).output(mo({received:ro()}));var Kl,Ql=null,Xl="";function ec(e){return ye(new $e({url:e,headers:()=>{const e={};return Ql&&(e.Authorization=`Bearer ${Ql}`),e}}))}Kl=ec("");var tc=e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Xl&&(Xl=e,Kl=ec(e))},nc={setAuthToken:e=>{Ql=e},clearAuthToken:()=>{Ql=null},getAuthToken:()=>Ql,configure:tc},rc=new Proxy({},{get:(e,t)=>t in nc?nc[t]:Kl[t]}),ic=e=>e?.mtxApiHost?e.mtxApiHost:"";function oc(e,t="Unknown error"){return e instanceof Error?e.message:"string"==typeof e?e:t}function sc(e,t="Operation",n){const r=oc(e);return function(e){const t=e instanceof Error?e.message:String(e);return t.includes("Failed to fetch")||t.includes("ERR_CONNECTION_REFUSED")||t.includes("NetworkError")||t.includes("Network request failed")}(e)?{isValid:!1,error:`Cannot connect to API server. Please ensure the API server is running at ${ic(n)||"configured API server"}. Error: ${r}`}:{isValid:!1,error:`${t} failed: ${r}`}}var ac="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname&&!window.location.hostname.includes("localhost")?"error":"debug",lc={debug:0,info:1,warn:2,error:3};function cc(e){return lc[e]>=lc[ac]}var dc=(e,t,...n)=>{cc("debug")},uc=(e,t,...n)=>{cc("info")},pc=(e,t,...n)=>{cc("warn")},hc=(e,t,...n)=>{cc("error")};function mc(e){return{debug:(t,...n)=>dc(e,t,...n),info:(t,...n)=>uc(e,t,...n),warn:(t,...n)=>pc(e,t,...n),error:(t,...n)=>hc(e,t,...n)}}mc("ErrorUtils");var fc=[{id:"navigate",name:"Navigate",description:"Navigate to a URL",displayAction:"Navigating",category:"navigation",actionType:"navigate"},{id:"search",name:"Search",description:"Search the web using a search engine",displayAction:"Searching",category:"navigation",actionType:"search"},{id:"click_element",name:"Click Element",description:"Click on an element by index or coordinates",displayAction:"Clicking element",category:"interaction",actionType:"click_element"},{id:"type_text",name:"Type Text",description:"Type text into an input field",displayAction:"Typing text",category:"interaction",actionType:"type_text"},{id:"scroll",name:"Scroll",description:"Scroll the page up or down",displayAction:"Scrolling",category:"interaction",actionType:"scroll"},{id:"scroll_to_text",name:"Scroll to Text",description:"Scroll until text is visible",displayAction:"Scrolling to text",category:"interaction",actionType:"scroll_to_text"},{id:"send_keys",name:"Send Keys",description:"Send keyboard keys or shortcuts",displayAction:"Pressing key",category:"interaction",actionType:"send_keys"},{id:"extract",name:"Extract",description:"Extract content from the page",displayAction:"Extracting content",category:"extraction",actionType:"extract"},{id:"get_dropdown_options",name:"Get Dropdown Options",description:"Get available options from a dropdown",displayAction:"Reading dropdown options",category:"extraction",actionType:"get_dropdown_options"},{id:"select_dropdown_option",name:"Select Dropdown Option",description:"Select an option from a dropdown",displayAction:"Selecting option",category:"interaction",actionType:"select_dropdown_option"},{id:"upload_file",name:"Upload File",description:"Upload a file to an input field",displayAction:"Uploading file",category:"interaction",actionType:"upload_file"},{id:"go_back",name:"Go Back",description:"Browser back button",displayAction:"Going back",category:"navigation",actionType:"go_back"},{id:"wait",name:"Wait",description:"Wait for a specified duration",displayAction:"Waiting",category:"utility",actionType:"wait"},{id:"switch_tab",name:"Switch Tab",description:"Switch to a different browser tab",displayAction:"Switching tab",category:"utility",actionType:"switch_tab"},{id:"close_tab",name:"Close Tab",description:"Close the current browser tab",displayAction:"Closing tab",category:"utility",actionType:"close_tab"},{id:"done",name:"Done",description:"Mark task as complete",displayAction:"Done",category:"utility",actionType:"done"},{id:"get_html",name:"Get HTML",description:"Get full page HTML with data-id attributes",displayAction:"Viewed your screen",category:"extraction",actionType:"get_html"},{id:"get_interactable_elements",name:"Get Interactable Elements",description:"Get list of interactable elements",displayAction:"Scanning elements",category:"extraction",actionType:"get_interactable_elements"},{id:"get_screenshot",name:"Get Screenshot",description:"Capture a screenshot of the page",displayAction:"Taking screenshot",category:"extraction",actionType:"get_screenshot"}];function gc(e){return e.includes("__THINKING__")}function yc(e){return gc(e)?e:`${e}\n\n__THINKING__`}function wc(e,t,n,r,i,o){if("agent"!==e.sender||e.isSystemMessage||e.isScreenAccessRequest)return!1;if(o&&t&&("show"===n||"do"===n))if(e.isPlaceholder){if(void 0!==e.mode&&e.mode!==n)return!1}else if(e.mode!==n)return!1;if(i){const t=e.content.trim().length>0,n=e.parts&&e.parts.length>0;if(!t&&!n)return!1}return!0}function bc(e){const{messages:t,isTaskRunning:n,currentMode:r,preferPlaceholder:i,requireContent:o}=e;let s=-1;if(n&&("show"===r||"do"===r)){const e=!0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=wc(a,n,r,0,o,e),c=a.isPlaceholder,d=!o||a.content.trim().length>0||a.parts&&a.parts.length>0;if(l&&c&&d){s=i;break}}if(s<0&&!o)for(let i=t.length-1;i>=0;i--){const a=t[i],l=wc(a,n,r,0,o,e),c=a.isPlaceholder;if(l&&c){s=i;break}}if(s<0)for(let i=t.length-1;i>=0;i--){const a=t[i],l=wc(a,n,r,0,o,e),c=a.isPlaceholder;if(l&&!c){s=i;break}}}if(s<0){for(let e=t.length-1;e>=0;e--){const n=t[e],r="agent"===n.sender,i=n.isPlaceholder,a=!n.isSystemMessage,l=!n.isScreenAccessRequest,c=!o||n.content.trim().length>0||n.parts&&n.parts.length>0;if(r&&i&&a&&l&&c){s=e;break}}if(s<0&&!o)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&n.isPlaceholder&&!n.isSystemMessage&&!n.isScreenAccessRequest){s=e;break}}if(s<0&&(s=function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest&&!n.isPlaceholder)return t}return-1}(t)),s<0)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest){s=e;break}}}return s>=0?{index:s,message:t[s]}:null}function vc(e){const t={...e};if(!t.parts){t.parts=[];const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts.push({type:"text",content:e})}return t}var xc=new Set(["click_element","type_text","send_keys","select_dropdown_option","upload_file","scroll"]);function kc(e){return e?e.replace(/\(Cancelled by cleanup\)/gi,"").replace(/\(cancelled by cleanup\)/gi,"").replace(/Cancelled by cleanup/gi,"").replace(/\s+/g," ").trim():e}function _c(e,t,n,r=!1){const i=vc(e);if(!t||"show"!==n&&"do"!==n)return gc(i.content)?{...i,content:i.content.replace(/\n\n__THINKING__$/,"").replace(/__THINKING__/g,""),placeholderState:void 0}:i;const o=r?"waiting-for-user":"thinking";return gc(i.content)?i.placeholderState!==o?{...i,placeholderState:o}:i:{...i,content:yc(i.content),placeholderState:o}}var Sc=Object.fromEntries(fc.map(e=>[e.id,e.displayAction]));var Cc="marketrix_chat_context",Ic={chat_id:null,messages:[],isTaskRunning:!1,activeTaskId:null,taskProgress:[],currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1,config:null,timestamp:Date.now()},Ec=class e{static instance;context=null;constructor(){this.loadContext()}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadContext(){if("undefined"==typeof window)return this.context={...Ic},this.context;try{const e=localStorage.getItem(Cc);if(e){const t=JSON.parse(e);return Date.now()-t.timestamp>6048e5?(this.context={...Ic},this.saveContext(),this.context):(this.context=t,this.context)}}catch(e){}return this.context={...Ic},this.context}saveContext(){if("undefined"!=typeof window&&this.context)try{this.context.timestamp=Date.now(),localStorage.setItem(Cc,JSON.stringify(this.context))}catch(e){}}getContext(){return this.context?this.context:this.loadContext()}updateContext(e){this.context||this.loadContext(),this.context={...this.context,...e},this.saveContext()}isValidChatId(e){return"string"==typeof e&&""!==e.trim()}getChatId(){if("undefined"!=typeof window&&this.isValidChatId(window.name)){const e=window.name;return e!==this.getContext().chat_id&&this.updateContext({chat_id:e}),e}return this.getContext().chat_id}setChatId(e){this.updateContext({chat_id:e}),"undefined"!=typeof window&&e&&(window.name=e,window.dispatchEvent(new CustomEvent("marketrix:chatid",{detail:{chatId:e}})))}getMessages(){return this.getContext().messages}setMessages(e){this.updateContext({messages:e})}getChatState(){const e=this.getContext();return{isTaskRunning:e.isTaskRunning,activeTaskId:e.activeTaskId,taskProgress:e.taskProgress,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading}}setChatState(e){this.updateContext(e)}getConfig(){return this.getContext().config}setConfig(e){this.updateContext({config:e})}clear(){this.context={...Ic},"undefined"!=typeof window&&localStorage.removeItem(Cc)}hasValidContext(){const e=this.getContext();return null!==e.chat_id&&e.chat_id.length>0}}.getInstance(),Ac=class e{static instance;messages=[];chatId=null;isTaskRunning=!1;activeTaskId=null;taskProgress=[];currentMode="tell";isOpen=!1;isMinimized=!1;isLoading=!1;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.chatId=e,this.restoreState()}createInitialContext(e){try{if(Ec.hasValidContext())return;Ec.updateContext({chat_id:e,messages:[],isTaskRunning:!1,activeTaskId:null,taskProgress:[],currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1})}catch(t){}}getMessages(){return this.messages}getIsLoading(){return this.isLoading}getIsTaskRunning(){return this.isTaskRunning}getActiveTaskId(){return this.activeTaskId}getTaskProgress(){return this.taskProgress}getCurrentMode(){return this.currentMode}getIsOpen(){return this.isOpen}getIsMinimized(){return this.isMinimized}addMessage(e){this.messages=[...this.messages,e],this.persistState()}updateMessage(e,t){this.messages=this.messages.map(n=>n.id===e?{...n,...t}:n),this.persistState()}removeMessage(e){this.messages=this.messages.filter(t=>t.id!==e),this.persistState()}setMessages(e){this.messages=e,this.persistState()}clearMessages(){this.messages=[],this.persistState()}setTaskState(e,t,n){this.isTaskRunning=e,this.activeTaskId=t,this.taskProgress=n,this.persistState()}setMode(e){this.currentMode=e,this.persistState()}setWidgetState(e,t){this.isOpen=e,this.isMinimized=t,this.persistState()}setIsLoading(e){this.isLoading=e,this.persistState()}restoreState(){try{const e=Ec.getContext();if(!e.chat_id)return;this.chatId&&(e.chat_id,this.chatId),this.messages=e.messages.map(e=>{if(e.id.startsWith("screenshare-"))return{...e,content:"Screenshare ended",videoStream:void 0,isSystemMessage:!0,timestamp:new Date(e.timestamp),parts:[{type:"text",content:"Screenshare ended"}]};const t={...e,timestamp:new Date(e.timestamp),videoStream:void 0,placeholderState:e.placeholderState,taskStatus:e.taskStatus,parts:e.parts||[]};if(0===t.parts?.length&&t.content){const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts&&t.parts.push({type:"text",content:e})}return t}),this.isTaskRunning=e.isTaskRunning,this.activeTaskId=e.activeTaskId,this.taskProgress=e.taskProgress,this.currentMode=e.currentMode,this.isOpen=e.isOpen,this.isMinimized=e.isMinimized,this.isLoading=e.isLoading??!1}catch(e){}}persistState(){if(this.chatId)try{const e=this.messages.filter(e=>!e.isPlaceholder||("thinking"===e.placeholderState||"waiting-for-user"===e.placeholderState||(e.parts||[]).length>0)).filter(e=>!(e.isSystemMessage&&"Chat context changed"===e.content)).map(e=>{return{id:e.id,content:(t=e.content,t.replace(/__THINKING__/g,"")),sender:e.sender,timestamp:e.timestamp.toISOString(),mode:e.mode,isScreenAccessRequest:e.isScreenAccessRequest,screenShareStatus:e.screenShareStatus,isSystemMessage:e.isSystemMessage,isPlaceholder:e.isPlaceholder,placeholderState:e.placeholderState,taskStatus:e.taskStatus,parts:e.parts};var t});Ec.updateContext({chat_id:this.chatId,messages:e,isTaskRunning:this.isTaskRunning,activeTaskId:this.activeTaskId,taskProgress:this.taskProgress,currentMode:this.currentMode,isOpen:this.isOpen,isMinimized:this.isMinimized,isLoading:this.isLoading})}catch(e){}}}.getInstance();function Tc(e,t,n="user-message"){const r=[],i=e.trim();return i&&r.push({type:"text",content:i}),{id:`${n}-${Date.now()}`,content:i,sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,parts:r}}function Mc(e,t,n,r="agent-message"){const i=[],o=e.trim();return o&&i.push({type:"text",content:o}),{id:n||`${r}-${Date.now()}`,content:e,sender:"agent",timestamp:/* @__PURE__ */new Date,mode:t,parts:i}}function zc(e,t,n="agent",r="system-message"){const i=[];return e&&i.push({type:"text",content:e}),{id:`${r}-${Date.now()}`,content:e,sender:n,timestamp:/* @__PURE__ */new Date,mode:t,isSystemMessage:!0,parts:i}}function Oc(e="show"){const t="Started screenshare";return{id:`started-screenshare-${Date.now()}`,content:t,sender:"user",timestamp:/* @__PURE__ */new Date,mode:e,isSystemMessage:!0,parts:[{type:"text",content:t}]}}function Rc(e,t="show"){return{id:`screenshare-${Date.now()}`,content:"",sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,videoStream:e,parts:[]}}var Nc=mc("ChatIdManager"),Pc=class e{static instance=null;chatId=null;initializationPromise=null;constructor(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.chatId=this.getStoredChatId(),this.chatId&&Nc.debug("Loaded existing chat ID from storage:",this.chatId))}static getInstance(){return"undefined"==typeof window||"undefined"==typeof document?(e.instance||(e.instance=Object.create(e.prototype),e.instance.chatId=null,e.instance.initializationPromise=null),e.instance):(e.instance||(e.instance=new e),e.instance)}getChatId(){return this.chatId}async getOrCreateChatId(){if(this.chatId)return Nc.debug("Returning existing chat ID:",this.chatId),this.chatId;if(this.initializationPromise)return Nc.debug("Chat ID initialization in progress, waiting..."),this.initializationPromise;const e=this.getStoredChatId();if(e)return this.chatId=e,Nc.debug("Found chat ID in storage:",this.chatId),this.chatId;this.initializationPromise=this.createChatId();try{return await this.initializationPromise}finally{this.initializationPromise=null}}async createChatId(){try{Nc.info("Creating new chat ID...");const e=await rc.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return this.chatId=e,this.storeChatId(e),Nc.info("Created and stored new chat ID:",this.chatId),Ac.createInitialContext(e),e}catch(e){throw Nc.error("Failed to create chat ID:",e),this.initializationPromise=null,e}}clearChatId(){this.chatId=null,this.initializationPromise=null,Nc.debug("Cleared chat ID")}static resetInstance(){e.instance=null}getStoredChatId(){return Ec.getChatId()}storeChatId(e){Ec.setChatId(e)}}.getInstance(),Lc=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;isIntentionallyDisconnected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;config;connectionId=0;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}getStatus(){return this.status}isConnected(){return"registered"===this.status}async connect(e,t){if(this.isIntentionallyDisconnected&&(this.isIntentionallyDisconnected=!1),this.isConnected()&&this.chatId===e)return;this.abortController&&(this.abortController.abort(),this.abortController=null),this.chatId=e,t&&(this.config=t),this.setStatus("connecting");const n=++this.connectionId;this.abortController=new AbortController;const r=this.abortController.signal;try{const t={chat_id:e};this.config?.mtxId&&this.config?.mtxKey?(t.marketrix_id=this.config.mtxId,t.marketrix_key=this.config.mtxKey):this.config?.mtxAgent&&this.config?.mtxApp&&(t.agent_id=this.config.mtxAgent,t.application_id=this.config.mtxApp);const i=await rc.widgetStream(t,{signal:r});this.setStatus("connected"),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.consumeEvents(i,n)}catch(i){r.aborted||(this.setStatus("error"),this.notifyError(/* @__PURE__ */new Error("Stream connection failed")),this.scheduleReconnect())}}async consumeEvents(e,t){let n=!1;try{for await(const r of e){if(this.connectionId!==t){n=!0;break}this.handleMessage(r)}}catch(r){this.connectionId!==t?n=!0:this.isIntentionallyDisconnected||this.setStatus("error")}finally{n||this.connectionId!==t||this.isIntentionallyDisconnected||(this.setStatus("disconnected"),this.scheduleReconnect())}}disconnect(){this.isIntentionallyDisconnected=!0,this.clearReconnectTimer(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.setStatus("disconnected"),this.chatId=null}send(e){return this.chatId?rc.widgetMessage({chat_id:this.chatId,command:e}).then(()=>{}).catch(e=>{throw this.notifyError(/* @__PURE__ */new Error(`Failed to send message: ${String(e)}`)),e}):Promise.reject(/* @__PURE__ */new Error("No active chat"))}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(t=>t.onStatusChange?.(e)))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}handleMessage(e){this.isIntentionallyDisconnected||"heartbeat"!==e.type&&("registered"===e.type&&e.chat_id===this.chatId&&(this.setStatus("registered"),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.callbacks.forEach(t=>t.onRegistered?.(e.application_id))),"chat/error"===e.type&&"auth"===e.request_id&&(this.isIntentionallyDisconnected=!0),this.callbacks.forEach(t=>t.onMessage?.(e)))}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.notifyError(/* @__PURE__ */new Error("Max reconnect attempts reached"));this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.isIntentionallyDisconnected&&this.chatId&&this.connect(this.chatId,this.config).catch(console.error)},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},Dc=class{config;constructor(e){this.config=e}getChatId(){return Pc.getChatId()}async getOrCreateChatId(){return Pc.getOrCreateChatId()}getUserId(){if(this.config.userId&&"number"==typeof this.config.userId)return this.config.userId;try{const e=localStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}try{const e=sessionStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}return null}async logWidgetQuestion(e,t){try{const n=this.getUserId(),r={question:e,mode:t,chat_id:this.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString()};null!==n&&(r.user_id=n),this.config.mtxApp&&(r.application_id=this.config.mtxApp),this.config.mtxId&&this.config.mtxKey&&(r.marketrix_id=this.config.mtxId,r.marketrix_key=this.config.mtxKey),rc.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>{})}catch(n){}}async sendMessage(e){if(!(await Pc.getOrCreateChatId()))throw new Error("Failed to initialize chat session");const t=e.mode||"tell";if(e.message&&await this.logWidgetQuestion(e.message,t),!(this.config.mtxId&&this.config.mtxKey||this.config.mtxApp&&this.config.mtxAgent))throw new Error("Either mtxId + mtxKey or both mtxApp + mtxAgent are required");const n=e.requestId||`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r={type:`chat/${t}`,request_id:n,content:e.message||""};return Lc.getInstance().send(r),{messageId:n,response:"",mode:t,timestamp:/* @__PURE__ */new Date}}async checkAgentAvailability(){try{return null!==Pc.getChatId()}catch(e){return!1}}async getAgentInfo(){return{available:!0,status:"online"}}async stopTask(e){return Lc.getInstance().send({type:"chat/stop",...e&&{task_id:e}}),{status:"stopping",message:"Stop command sent"}}updateConfig(e){this.config={...this.config,...e}}},$c=class e{static instance;config=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadConfig(){const e=Ec.getConfig();return e?(this.config=e,e):(this.config={},this.config)}saveConfig(e){Ec.setConfig(e),this.config=e}updateConfig(e){this.config||(this.config={}),this.config={...this.config,...e},this.saveConfig(this.config)}getConfig(){return this.config}shouldShowWidget(){return!!this.config&&(this.config.widget_enabled??!1)}}.getInstance();function jc(e,t={}){return{...t,...e}}function Fc(e,t){return"object"==typeof e&&null!==e&&t in e}function Uc(e){return null!==e&&e instanceof HTMLElement}function Bc(e){return null!==e&&e instanceof HTMLScriptElement}function Wc(e){if(!(e&&e instanceof Element))return!1;try{const n=e.tagName.toLowerCase(),r="button"===n;if(!(r||"input"===n||"textarea"===n||"select"===n||"a"===n&&e.hasAttribute("href")||"button"===e.getAttribute("role")||"link"===e.getAttribute("role")||"textbox"===e.getAttribute("role")||"checkbox"===e.getAttribute("role")||"radio"===e.getAttribute("role")||"switch"===e.getAttribute("role")||"tab"===e.getAttribute("role")||"menuitem"===e.getAttribute("role")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||e.hasAttribute("tabindex")&&parseInt(e.getAttribute("tabindex")||"-1",10)>=0))return!1;const i=(t,n)=>{if(r){e.tagName,e.id,e.className}};if(!0===e.disabled)return i("disabled","button is disabled"),!1;if("true"===e.getAttribute("aria-disabled"))return i("aria-disabled","aria-disabled is true"),!1;try{let t=e;for(;t;){if(t instanceof HTMLElement&&t.inert)return i("inert","ancestor is inert"),!1;const e=t instanceof Element?t.getRootNode():null;t=t instanceof Element?t.parentElement||(e instanceof ShadowRoot?e.host:null):null}}catch(t){}const o=e.hasAttribute("onclick");if(r&&o)return!0;let s,a;try{s=window.getComputedStyle(e)}catch(t){return i("computed-style","failed to get computed style"),!1}if("none"===s.display)return i("display","display is none"),!1;if("none"===s.pointerEvents)return i("pointer-events","pointer-events is none"),!1;try{a=e.getBoundingClientRect()}catch(t){return i("bounding-rect","failed to get bounding rect"),!1}if(a.width<=0||a.height<=0)return i("dimensions",`width=${a.width}, height=${a.height}`),!1;try{let t=e;for(;t&&t!==document.body;){const e=t.getRootNode(),n=t.parentElement||(e instanceof ShadowRoot?e.host:null);if(!n)break;let o,s;try{o=window.getComputedStyle(n),s=n.getBoundingClientRect()}catch{t=n;continue}if("hidden"===o.overflow||"clip"===o.overflow){const e=a.right<s.left||a.left>s.right||a.bottom<s.top||a.top>s.bottom;if(r){if(e)return i("overflow-clipping","completely outside parent bounds"),!1}else if(e)return!1}t=n}}catch(t){}try{let t=e.getRootNode();for(;t instanceof ShadowRoot;){const e=t.host;let n;try{n=e.getBoundingClientRect()}catch{break}if(n.width<=0||n.height<=0)return!1;t=e.getRootNode()}}catch(t){}return!0}catch(t){return!1}}var Gc=class e{static instance;elementMap=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;selectorMap=/* @__PURE__ */new Map;fingerprintMap=/* @__PURE__ */new Map;isIndexed=!1;indexingInProgress=!1;indexVersion=0;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}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,i=Array.from(t.children).filter(e=>e.tagName===r);if(i.length>1){e+=`:nth-of-type(${i.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}generateFingerprint(e,t){return{tagName:e.tagName,id:e.id||null,textContent:((e,t=100)=>{if(!e)return null;const n=e.trim().replace(/\s+/g," ");return n.length>t?n.slice(0,t):n})(e.textContent),type:e.getAttribute("type"),role:e.getAttribute("role"),ariaLabel:e.getAttribute("aria-label"),name:e.getAttribute("name"),href:e.getAttribute("href"),selector:t,indexVersion:this.indexVersion}}matchesFingerprint(e,t){return e.tagName===t.tagName&&(!(!t.id||e.id!==t.id)||(!t.type||e.getAttribute("type")===t.type)&&((!t.ariaLabel||e.getAttribute("aria-label")===t.ariaLabel)&&((!t.role||e.getAttribute("role")===t.role)&&((!t.href||"A"!==t.tagName||e.getAttribute("href")===t.href)&&(!t.name||e.getAttribute("name")===t.name)))))}validateElementAtIndex(e){const t=this.fingerprintMap.get(e);if(!t)return{isValid:!0};const n=this.elementMap.get(e);return n&&document.contains(n)?n instanceof HTMLElement&&!this.matchesFingerprint(n,t)?{isValid:!1,mismatchReason:"element_changed"}:{isValid:!0}:{isValid:!1,mismatchReason:"element_removed"}}exportState(){return{selectors:Array.from(this.selectorMap.entries()),fingerprints:Array.from(this.fingerprintMap.entries())}}importState(e){if(e)try{e.selectors&&(this.selectorMap=new Map(e.selectors)),e.fingerprints&&(this.fingerprintMap=new Map(e.fingerprints)),(this.selectorMap.size>0||this.fingerprintMap.size>0)&&(this.isIndexed=!0)}catch(t){}}indexInteractableElements(){if(this.indexingInProgress)return[];try{this.indexingInProgress=!0,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;const r=[];for(;t;){if(t instanceof HTMLElement){const e=t.matches('a[href], button, input, textarea, select, [role="button"]'),i=t.classList.contains("cursor-pointer")||t.classList.contains("clickable"),o="onclick"in t&&"function"==typeof t.onclick;if(e||i||o||Wc(t)){this.elementMap.set(n,t),this.elementToSequence.set(t,n);const e=this.generateSelector(t);this.selectorMap.set(n,e);const i=this.generateFingerprint(t,e);this.fingerprintMap.set(n,i),r.push([n,t]),n++}}t=e.nextNode()}return this.isIndexed=!0,this.indexVersion++,r}finally{this.indexingInProgress=!1}}getElementCoordinates(e){const t=e.getBoundingClientRect(),n=this.calculateGlobalZOrder(e);return{x:Math.round(t.left),y:Math.round(t.top),w:Math.round(t.width),h:Math.round(t.height),z:n}}isStackingContext(e){const t=window.getComputedStyle(e),n=t.position;if(("fixed"===n||"absolute"===n||"relative"===n||"sticky"===n)&&"auto"!==t.zIndex)return!0;if("auto"!==t.zIndex&&e.parentElement){const t=window.getComputedStyle(e.parentElement).display;if("flex"===t||"inline-flex"===t||"grid"===t||"inline-grid"===t)return!0}const r=parseFloat(t.opacity);if(!isNaN(r)&&r<1)return!0;if(t.transform&&"none"!==t.transform)return!0;if(t.filter&&"none"!==t.filter)return!0;const i=t.willChange;if(i&&(i.includes("transform")||i.includes("opacity")))return!0;if("isolate"===t.isolation)return!0;const o=t.contain;return!(!o||!(o.includes("layout")||o.includes("style")||o.includes("paint")))}calculateGlobalZOrder(e){let t=e;const n=[];for(;t&&t!==document.body&&t.parentElement;){const e=window.getComputedStyle(t);if(this.isStackingContext(t)){let r=0;if("auto"!==e.zIndex){const t=parseInt(e.zIndex,10);isNaN(t)||(r=t)}let i=0;t.parentElement&&(i=Array.from(t.parentElement.children).indexOf(t)),n.push({element:t,zIndex:r,domOrder:i})}t=t.parentElement}let r=1e6;for(let i=n.length-1;i>=0;i--){const e=n[i];r+=1e4*e.zIndex+e.domOrder}if(e.parentElement){r+=Array.from(e.parentElement.children).indexOf(e)}return r}getSnapshotHtml(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,r]of this.elementMap.entries())if(r instanceof HTMLElement){const i=this.selectorMap.get(n);if(i)try{const t=(e.querySelector("body")||e).querySelector(i);if(t)if(t.setAttribute("data-id",n.toString()),"none"===window.getComputedStyle(r).display)t.setAttribute("data-x","0"),t.setAttribute("data-y","0"),t.setAttribute("data-w","0"),t.setAttribute("data-h","0"),t.setAttribute("data-z","0");else{const e=this.getElementCoordinates(r);t.setAttribute("data-x",e.x.toString()),t.setAttribute("data-y",e.y.toString()),t.setAttribute("data-w",e.w.toString()),t.setAttribute("data-h",e.h.toString()),t.setAttribute("data-z",e.z.toString())}}catch(t){}}return e.outerHTML}getInteractableElements(){this.indexInteractableElements();const e=[];for(const[t,n]of this.elementMap.entries())if(n instanceof HTMLElement){const r=this.fingerprintMap.get(t);r&&e.push({index:t,fingerprint:r,coords:this.getElementCoordinates(n),cssClasses:Array.from(n.classList)})}return e}getElementByDataId(e){return this.elementMap.get(e)}getSequenceForElement(e){return this.elementToSequence.get(e)}isIndexActive(){return this.isIndexed}clearIndex(){this.elementMap.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap,this.fingerprintMap.clear(),this.isIndexed=!1}checkInteractability(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 i=r.left+r.width/2,o=r.top+r.height/2,s=document.elementFromPoint(i,o);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}checkElementInteractable(e,t){return this.checkInteractability(e,t)}getElementByIndex(e){let t=null;if(this.elementMap.has(e)){const n=this.elementMap.get(e);n&&n instanceof HTMLElement&&(t=n)}if(!t&&this.selectorMap.has(e)){const n=this.selectorMap.get(e);if(n)try{const e=document.querySelector(n);e&&e instanceof HTMLElement&&(t=e)}catch(r){}}if(!t)return{element:null,error:`Element ${e} not found`};const n=this.checkInteractability(t,e);return n?{element:null,error:n}:{element:t}}getValidatedElement(e){const t=this.validateElementAtIndex(e);if(!t.isValid)return{element:null,validation:t,error:`DOM_CHANGED: Element at index ${e} ${"element_removed"===t.mismatchReason?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const n=this.elementMap.get(e);if(!n)return{element:null,validation:t,error:`Element ${e} not found`};const r=this.checkInteractability(n,e);return r?{element:null,validation:t,error:r}:{element:n,validation:t}}getFingerprint(e){return this.fingerprintMap.get(e)}getAllFingerprints(){return Array.from(this.fingerprintMap.entries())}getIndexVersion(){return this.indexVersion}}.getInstance(),Hc=null;async function Zc(){if(Hc?.active){const e=Hc.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Hc}const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!e||0===e.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return Hc=e,e.getVideoTracks()[0].addEventListener("ended",()=>{Hc=null}),e}function Vc(){return null!==function(){if(Hc?.active){const e=Hc.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Hc}return Hc=null,null}()}var qc=class e{static instance;currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;updateHighlightPosition=null;rafId=null;mutationObserver=null;visibilityCheckInterval=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,toolName:i}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.toolName===i&&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.setupElementMonitoring(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t}).finally(()=>{this.cleanup()})),this.currentPromise}cleanup(){this.rejectPromise&&(this.rejectPromise("Cancelled by cleanup"),this.rejectPromise=null),this.resolvePromise=null,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler&&(window.removeEventListener("scroll",this.scrollHandler,{capture:!0}),window.removeEventListener("resize",this.scrollHandler),window.removeEventListener("touchmove",this.scrollHandler),window.removeEventListener("wheel",this.scrollHandler),this.scrollHandler=null),null!==this.rafId&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.updateHighlightPosition=null,this.currentPopup&&(this.currentPopup.remove(),this.currentPopup=null),this.currentHighlight&&(this.currentHighlight.remove(),this.currentHighlight=null);const e=document.getElementById("marketrix-show-popup");e&&e.remove();const t=document.getElementById("marketrix-show-highlight");t&&t.remove(),this.currentElement=null,this.currentOptions=null,this.currentPromise=null,this.resolvePromise=null,this.rejectPromise=null}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>`,document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.updateHighlightPosition=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();this.currentHighlight.style.top=`${e.top}px`,this.currentHighlight.style.left=`${e.left}px`,this.currentHighlight.style.width=`${e.width}px`,this.currentHighlight.style.height=`${e.height}px`,this.updatePopupPosition()},this.scrollHandler=()=>{null!==this.rafId&&window.cancelAnimationFrame(this.rafId),this.updateHighlightPosition?.()},window.addEventListener("scroll",this.scrollHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.scrollHandler,{passive:!0}),window.addEventListener("touchmove",this.scrollHandler,{passive:!0}),window.addEventListener("wheel",this.scrollHandler,{passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=320,n=120,r=10,i=e.left+e.width/2,o=e.top+e.height/2,s=[{left:e.right+20,top:o-60},{left:e.left-t-20,top:o-60},{left:i-160,top:e.top-n-20},{left:i-160,top:e.bottom+20}];let a=s[0];for(const d of s)if(d.left>=r&&d.left+t<=window.innerWidth-r&&d.top>=r&&d.top+n<=window.innerHeight-r){a=d;break}const l=Math.max(r,Math.min(a.left,window.innerWidth-t-r)),c=Math.max(r,Math.min(a.top,window.innerHeight-n-r));this.currentPopup.style.cssText+=`\n position: fixed;\n top: ${c}px;\n left: ${l}px;\n width: 320px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n z-index: 2147483646;\n padding: 16px;\n `}setupClickHandler(){this.clickHandler=e=>{if(this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)){e.preventDefault(),e.stopPropagation();const t=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,t(!0)}},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{const t=e.querySelector("#marketrix-show-continue");t&&t.addEventListener("click",e=>{if(e.stopPropagation(),this.resolvePromise){const e=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,e(!0)}})})}setupElementMonitoring(){this.currentElement&&(this.mutationObserver=new MutationObserver(()=>{this.currentElement&&!document.body.contains(this.currentElement)&&this.failWithElementGone("Element was removed from DOM")}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{if(!this.currentElement)return;const e=Gc.getSequenceForElement(this.currentElement)??-1,t=Gc.checkElementInteractable(this.currentElement,e);t&&this.failWithElementGone(t)},200)}failWithElementGone(e){if(this.rejectPromise){const t=this.rejectPromise;this.rejectPromise=null,this.resolvePromise=null,t(/* @__PURE__ */new Error(`ELEMENT_GONE: ${e}`))}this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}.getInstance(),Jc=class e{static instance;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async executeTool(e,t,n="do",r=""){try{if("show"===n&&this.requiresHighlight(e)){const n=t.index;if(void 0!==n){const{element:t,error:i}=Gc.getElementByIndex(n);if(!t)return{success:!1,data:{text:""},error:i||`Element ${n} not found`};if(!(await qc.showToolAction({element:t,explanation:r||`Execute ${e}`,toolName:e,isClickAction:"click_element"===e})))return{success:!1,data:{text:""},error:"User cancelled action"}}}switch(e){case"navigate":return this.navigate(t);case"search":return this.search(t);case"click_element":return await this.clickElement(t);case"type_text":return this.typeText(t);case"scroll":return this.scroll(t);case"scroll_to_text":return this.scrollToText(t);case"extract":return this.extract(t);case"go_back":return this.goBack();case"wait":return await this.wait(t);case"select_dropdown_option":return this.selectDropdownOption(t);case"get_dropdown_options":return this.getDropdownOptions(t);case"send_keys":return this.sendKeys(t);case"upload_file":return this.uploadFile(t);case"close_tab":return this.closeTab();case"switch_tab":return this.switchTab(t);case"done":return this.done(t);case"get_html":return this.getHtml();case"get_interactable_elements":return this.getInteractableElements();case"get_screenshot":return await this.getScreenshot();default:return{success:!1,data:{text:""},error:`Unknown tool: ${e}`}}}catch(i){return qc.cleanup(),{success:!1,data:{text:""},error:i instanceof Error?i.message:String(i)}}}requiresHighlight(e){return["click_element","type_text","select_dropdown_option","send_keys","upload_file"].includes(e)}navigate(e){return e.url?e.new_tab?(window.open(e.url,"_blank"),{success:!0,data:{text:`Opened ${e.url} in new tab`}}):(window.location.href=e.url,{success:!0,data:{text:`Navigating to ${e.url}`}}):{success:!1,data:{text:""},error:"URL is required"}}search(e){if(!e.query)return{success:!1,data:{text:""},error:"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,{success:!0,data:{text:`Searching for "${e.query}" on ${t}`}}}async clickElement(e){if(void 0===e.index)return{success:!1,data:{text:""},error:"Index required"};const{element:t,error:n}=Gc.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),{success:!0,data:{text:`Clicked element ${e.index}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}typeText(e){if(void 0===e.index||void 0===e.text)return{success:!1,data:{text:""},error:"Index and text required"};const t=!1!==e.clear,{element:n,error:r}=Gc.getValidatedElement(e.index);if(!n)return{success:!1,data:{text:""},error:r||`Element ${e.index} not found`};if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n.isContentEditable){const r=n;try{r.focus()}catch(i){}const o=t?e.text:r.value+e.text;let s=!1,a=null;if(!s)try{const e="TEXTAREA"===r.tagName.toUpperCase()?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,t=Object.getOwnPropertyDescriptor(e,"value");t?.set&&(t.set.call(r,o),s=!0)}catch(i){a=i}if(!s)try{r.value=o,s=!0}catch(i){a=i}if(!s)try{r.focus(),t&&r.select(),document.execCommand("insertText",!1,e.text)&&(s=!0)}catch(i){a=i}if(!s)try{r.focus(),t&&(r.value="");for(const t of e.text)r.dispatchEvent(new KeyboardEvent("keydown",{key:t,bubbles:!0,cancelable:!0})),r.value+=t,r.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),r.dispatchEvent(new KeyboardEvent("keyup",{key:t,bubbles:!0,cancelable:!0}));s=!0}catch(i){a=i}if(!s)return{success:!1,data:{text:""},error:`Failed to set value: ${a instanceof Error?a.message:String(a)}`};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(i){}}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(i){return{success:!1,data:{text:""},error:`Failed to set value on element: ${i instanceof Error?i.message:String(i)}`}}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(i){return{success:!1,data:{text:""},error:`Failed to set textContent: ${i instanceof Error?i.message:String(i)}`}}return{success:!0,data:{text:`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{success:!1,data:{text:""},error:"Invalid direction"}}return{success:!0,data:{text:`Scrolled ${e.direction}`}}}scrollToText(e){if(!e.text)return{success:!1,data:{text:""},error:"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"}),{success:!0,data:{text:`Scrolled to "${e.text}"`}};return{success:!1,data:{text:""},error:`Text "${e.text}" not found`}}extract(e){const t=e.start_from_char??0,n=!1!==e.extract_links,r=document.body.innerText;return{success:!0,data:{title:document.title,url:window.location.href,text:r.slice(t,t+1e4),links:n?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]}}}goBack(){return window.history.length>1?(window.history.back(),{success:!0,data:{text:"Navigated back"}}):{success:!1,data:{text:""},error:"No history"}}async wait(e){return void 0===e.seconds?{success:!1,data:{text:""},error:"Seconds required"}:(await new Promise(t=>setTimeout(t,1e3*e.seconds)),{success:!0,data:{text:`Waited ${e.seconds}s`}})}selectDropdownOption(e){if(void 0===e.index||!e.option)return{success:!1,data:{text:""},error:"Index/Option required"};const{element:t,error:n}=Gc.getValidatedElement(e.index);if(!t)return{success:!1,data:{text:""},error:n||`Select ${e.index} not found`};if(!(t instanceof HTMLSelectElement))return{success:!1,data:{text:""},error:`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})),{success:!0,data:{text:`Selected ${e.option}`}}):{success:!1,data:{text:""},error:`Option ${e.option} not found`}}getDropdownOptions(e){const t=e.index,{element:n,error:r}=Gc.getValidatedElement(t);return n?n instanceof HTMLSelectElement?{success:!0,data:{options:Array.from(n.options).map(e=>({value:e.value,text:e.text}))}}:{success:!1,data:{options:[]},error:`Element ${t} is not a select element`}:{success:!1,data:{options:[]},error:r||`Select ${t} not found`}}sendKeys(e){if(void 0===e.index||!e.keys)return{success:!1,data:{text:""},error:"Index/Keys required"};const{element:t,error:n}=Gc.getValidatedElement(e.index);return t?(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})),{success:!0,data:{text:this.simulateKeyAction(t,e.keys)||`Sent keys ${e.keys}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}simulateKeyAction(e,t){switch(t){case"Tab":{const t=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),n=t.indexOf(e);if(-1!==n&&n<t.length-1){const e=t[n+1];return e.focus(),`Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Tab: no next focusable element"}case"Shift+Tab":{const t=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),n=t.indexOf(e);if(n>0){const e=t[n-1];return e.focus(),`Shift+Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Shift+Tab: no 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,i=e.selectionStart??t.length,o=e.selectionEnd??t.length;if(0===i&&0===o&&(i=t.length,o=t.length),i===o&&i>0)n=t.slice(0,i-1)+t.slice(o),r=i-1;else{if(i===o)return"Backspace: cursor at start, nothing to delete";n=t.slice(0,i)+t.slice(o),r=i}const s=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return s?s.call(e,n):e.value=n,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(r,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 i;if(t===n&&t<r.length)i=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";i=r.slice(0,t)+r.slice(n)}const o=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return o?o.call(e,i):e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(t,t),`Delete: deleted character, value is now "${i}"`}return"Delete: dispatched event";default:return null}}uploadFile(e){return{success:!1,data:{text:""},error:"File upload not supported via script"}}closeTab(){return window.close(),{success:!0,data:{text:"Attempted close"}}}switchTab(e){return e.tab_id?{success:!1,data:{text:""},error:"Tab switching not supported"}:{success:!1,data:{text:""},error:"tab_id is required"}}done(e){return void 0===e.success?{success:!1,data:{text:""},error:"success parameter is required"}:{success:!0,data:{text:e.message||(e.success?"Task completed":"Task failed")}}}getHtml(){try{return{success:!0,data:{text:Gc.getSnapshotHtml()}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}getInteractableElements(){try{return{success:!0,data:{elements:Gc.getInteractableElements()}}}catch(e){return{success:!1,data:{elements:[]},error:String(e)}}}async getScreenshot(){try{const e=await Zc();if(!e)return{success:!1,data:{text:""},error:"Failed to get stream"};const 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(),{success:!0,data:{text:r}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}}.getInstance(),Yc=n(void 0),Kc=({children:e,previewMode:t=!1})=>{const n=u(0),r=u(/* @__PURE__ */new Set),i=u(!1),s=o(e=>{if(r.current.add(e),r.current.size>1e3){const e=Array.from(r.current).slice(-500);r.current=new Set(e)}},[]),l=u({}),c=o(()=>{const e=l.current;if(e.apiTaskId&&e.agentStarted){const t=e.apiTaskId;l.current={},m(e=>(Ac.setTaskState(!0,t,[]),i.current=!0,{...e,isTaskRunning:!0,activeTaskId:t,taskProgress:[]}))}},[]),[h,m]=p({isOpen:!1,isMinimized:!1,isLoading:!1,messages:[],currentMode:"tell",agentAvailable:!1,activeTaskId:null,isTaskRunning:!1,taskProgress:[],activeView:"home"});a(()=>{if(t)return;(async()=>{const e=await Pc.getOrCreateChatId();Ac.createInitialContext(e),Ac.initialize(e);const t=Ac.getIsTaskRunning();if(i.current=t,m(e=>({...e,messages:Ac.getMessages(),isLoading:Ac.getIsLoading(),isTaskRunning:t,activeTaskId:Ac.getActiveTaskId(),taskProgress:Ac.getTaskProgress(),currentMode:Ac.getCurrentMode(),isOpen:Ac.getIsOpen(),isMinimized:Ac.getIsMinimized()})),e){const t=Lc.getInstance(),n=$c.getConfig();t.connect(e,n?{mtxId:n.mtxId,mtxKey:n.mtxKey,mtxAgent:n.mtxAgent,mtxApp:n.mtxApp}:void 0).catch(e=>{})}})()},[t]);const g=o((e,t,n,r)=>{m(i=>{const o=function(e){return Sc[e]?Sc[e]:e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}(e),s=bc({messages:i.messages,isTaskRunning:i.isTaskRunning,currentMode:i.currentMode,preferPlaceholder:!0,requireContent:"failed"===n});if(!s)return i;let a=s.message;const l=["click_element","type_text","select_dropdown_option","send_keys","upload_file"].includes(e),c=i.isTaskRunning&&"show"===i.currentMode&&l,d="done"===e;"running"===n?(d||(a=function(e,t,n){const r=vc(e),i=r.parts||[],o=[...i],s=i.findIndex(e=>"progress"===e.type&&e.toolName===t&&"running"===e.status),a=!xc.has(t),l="default",c=kc(n);return s>=0?o[s]={...o[s],content:c,hideIcon:a,textStyle:l}:o.push({type:"progress",content:c,status:"running",toolName:t,hideIcon:a,textStyle:l}),{...r,parts:o}}(a,o,t||o)),!i.isTaskRunning||"show"!==i.currentMode&&"do"!==i.currentMode||(a=_c(a,i.isTaskRunning,i.currentMode,c))):"completed"===n?(d||(a=function(e,t){const n=vc(e),r=n.parts||[],i=[...r];let o=-1;if(t)o=r.map(e=>"progress"===e.type?e.toolName:"").lastIndexOf(t);else for(let s=r.length-1;s>=0;s--)if("progress"===r[s].type&&"running"===r[s].status){o=s;break}return o>=0&&(i[o]={...i[o],status:"completed"}),{...n,parts:i}}(a)),!i.isTaskRunning||"show"!==i.currentMode&&"do"!==i.currentMode||(a=_c(a,i.isTaskRunning,i.currentMode,!1))):(a=function(e,t,n){const r=vc(e),i=r.parts||[],o=n.toLowerCase().includes("cancelled by cleanup"),s=[...i];let a=i.map(e=>"progress"===e.type?e.toolName:"").lastIndexOf(t);if(-1===a)for(let l=i.length-1;l>=0;l--)if("progress"===i[l].type&&"running"===i[l].status){a=l;break}if(a>=0)if(o){const e=kc(s[a].content);s[a]={...s[a],status:"completed",content:e}}else{const e=kc(n),t=kc(s[a].content);s[a]={...s[a],status:"failed",content:e?`${t} (${e})`:t}}return{...r,parts:s}}(a,o,r||""),!i.isTaskRunning||"show"!==i.currentMode&&"do"!==i.currentMode||(a=_c(a,i.isTaskRunning,i.currentMode,!1)));const u=[...i.messages];return u[s.index]=a,Ac.setMessages(u),{...i,messages:u}})},[]);a(()=>{if(t)return;const e=Lc.getInstance(),o={onStatusChange:e=>{m(t=>({...t,agentAvailable:"registered"===e}))},onMessage:async t=>{if("tool/call"===t.type){const a=t.call_id;if(r.current.has(a))return;if(s(a),!fc.map(e=>e.id).includes(t.tool))return void e.send({type:"tool/response",call_id:a,success:!1,error:`Unknown tool: ${t.tool}`,state_version:n.current}).catch(e=>{});i.current||(i.current=!0,m(e=>({...e,isTaskRunning:!0})));const c=t.tool,d=t.args,u=t.mode||h.currentMode||"do",p=t.explanation||"",f=t.state_version;void 0!==f&&f>n.current&&(n.current=f),g(c,p,"running");const y=await Jc.executeTool(c,d,u,p);if(y.success)try{n.current++,e.send({type:"tool/response",call_id:a,success:!0,data:"string"==typeof y.data?y.data:JSON.stringify(y.data),state_version:n.current}).catch(e=>{}),g(c,p,"completed"),"done"===c&&(l.current={},m(e=>{Ac.setTaskState(!1,null,[]),i.current=!1;const t=bc({messages:e.messages,isTaskRunning:e.isTaskRunning,currentMode:e.currentMode,preferPlaceholder:!0,requireContent:!1}),n=[...e.messages];if(t){const e=t.message.parts?.filter(e=>!("progress"===e.type&&"done"===e.toolName))||[];n[t.index]={...t.message,taskStatus:"done",parts:e},Ac.setMessages(n)}return{...e,messages:n,isTaskRunning:!1,activeTaskId:null,taskProgress:[]}}))}catch(o){g(c,p,"failed","Connection error")}else g(c,p,"failed",y.error||"Tool execution failed"),n.current++,e.send({type:"tool/response",call_id:a,success:!1,data:"string"==typeof y.data?y.data:JSON.stringify(y.data),error:y.error??void 0,state_version:n.current}).catch(e=>{})}else if("task/status"===t.type){const e=t.status,n=t.message||"";"started"===e?(l.current={...l.current,agentStarted:!0,apiTaskId:l.current.apiTaskId||t.task_id||void 0},c()):"completed"!==e&&"failed"!==e&&"stopped"!==e||(r.current.clear(),l.current={},m(t=>{Ac.setTaskState(!1,null,[]);const r=bc({messages:t.messages,isTaskRunning:t.isTaskRunning,currentMode:t.currentMode,preferPlaceholder:!0,requireContent:!1}),o=[...t.messages];if(r){let t="done";"failed"===e?t="failed":"stopped"===e&&(t="stopped"),o[r.index]={...r.message,taskStatus:t,...n&&{content:n}},Ac.setMessages(o)}return i.current=!1,{...t,messages:o,isTaskRunning:!1,activeTaskId:null,taskProgress:[]}}))}else"chat/response"===t.type?m(e=>{const n=e.messages.map(e=>{if(e.id===t.request_id){const n=[...e.parts||[],{type:"text",content:t.text}];return{...e,content:t.text,isPlaceholder:!1,placeholderState:void 0,parts:n,...t.task_id&&{taskId:t.task_id}}}return e});return Ac.setMessages(n),t.task_id&&(l.current={...l.current,apiTaskId:t.task_id},c()),{...e,messages:n,isLoading:!1}}):"chat/error"===t.type&&m(e=>{const n=e.messages.map(e=>{if(e.id===t.request_id){const n=`Error: ${t.error}`,r=[...e.parts||[],{type:"text",content:n}];return{...e,content:n,isPlaceholder:!1,placeholderState:void 0,parts:r}}return e});return Ac.setMessages(n),{...e,messages:n,isLoading:!1}})},onError:e=>{m(t=>({...t,error:e.message}))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[g,t]);const y=o(e=>{m(t=>(Ac.setTaskState(e.isTaskRunning,e.activeTaskId,e.taskProgress||[]),{...t,...e}))},[]),w=o(()=>{Ac.clearMessages(),l.current={},i.current=!1,m(e=>({...e,messages:[],isTaskRunning:!1,activeTaskId:null,taskProgress:[],error:void 0}))},[]),b=o(e=>{m(t=>(Ac.addMessage(e),{...t,messages:[...t.messages,e]}))},[]),v=o(async(e,n,r,i,o)=>{if(t)return o||b(Tc(e,n||h.currentMode)),void b(Mc("This is a preview. In production, I'll respond to your messages here."));let s=$c.getConfig();if(s||(s=$c.loadConfig()),!s||!s.mtxId&&!s.mtxKey&&!s.mtxAgent)return void b(Mc("Configuration error: Missing API credentials. Please check your widget settings."));o||b(Tc(e,n||h.currentMode));const a=`temp-${globalThis.crypto.randomUUID()}`,l={id:a,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:n||h.currentMode,isPlaceholder:!0,placeholderState:"thinking",parts:[]};l.content=yc(""),b(l),m(e=>({...e,isLoading:!0}));const c=new Dc(s);try{r&&c.updateConfig({mtxApp:r});const t=c.getChatId();if(t){const e=Lc.getInstance();if(!e.isConnected()){const n=$c.getConfig();try{await e.connect(t,n?{mtxId:n.mtxId,mtxKey:n.mtxKey,mtxAgent:n.mtxAgent,mtxApp:n.mtxApp}:void 0)}catch(d){}}}await c.sendMessage({message:e,mode:n||h.currentMode,question:i,requestId:a})}catch(u){m(e=>{const t=e.messages.map(e=>{if(e.id===a){const t="I'm sorry, I encountered an error processing your request. Please try again.",n=[...e.parts||[],{type:"text",content:t}];return{...e,isPlaceholder:!1,parts:n,content:t}}return e});return Ac.setMessages(t),{...e,messages:t}})}finally{m(e=>({...e,isLoading:!1}))}},[h.currentMode,b,y,h,t]),x=d(()=>({setState:e=>m(t=>({...t,...e})),setActiveView:e=>m(t=>({...t,activeView:e})),toggleWidget:()=>m(e=>{const t={...e,isOpen:!e.isOpen,isMinimized:!!e.isOpen};return Ac.setWidgetState(t.isOpen,t.isMinimized),t}),closeWidget:()=>m(e=>{const t={...e,isOpen:!1,isMinimized:!0};return Ac.setWidgetState(t.isOpen,t.isMinimized),t}),setMode:e=>m(t=>(Ac.setMode(e),{...t,currentMode:e})),setLoading:e=>{Ac.setIsLoading(e),m(t=>({...t,isLoading:e}))},setAgentAvailable:e=>m(t=>({...t,agentAvailable:e})),setError:e=>m(t=>({...t,error:e})),clearError:()=>m(e=>({...e,error:void 0})),setTaskState:y,addMessage:b,updateMessage:(e,t)=>m(n=>(Ac.updateMessage(e,t),{...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)})),removeMessage:e=>m(t=>(Ac.removeMessage(e),{...t,messages:t.messages.filter(t=>t.id!==e)})),setMessages:e=>m(t=>(Ac.setMessages(e),{...t,messages:e})),resetState:w,stopTask:async()=>{const e=h.activeTaskId||i.current?h.activeTaskId??void 0:void 0;m(e=>{const n=bc({messages:e.messages,isTaskRunning:e.isTaskRunning,currentMode:e.currentMode,preferPlaceholder:!0,requireContent:!1}),r=[...e.messages];return n&&(r[n.index]={...n.message,taskStatus:"stopped"},t||Ac.setMessages(r)),t||Ac.setTaskState(!1,null,[]),i.current=!1,{...e,messages:r,isTaskRunning:!1,activeTaskId:null,taskProgress:[]}}),t||Lc.getInstance().send({type:"chat/stop",...e&&{task_id:e}}).catch(e=>{})},clearChatHistory:w,sendMessage:v}),[h.currentMode,y,w,b,v,t]);/* @__PURE__ */
2
+ return Yr(t=>t.normalize(e))}(...t)),e.toLowerCase=()=>e.check(/* @__PURE__ */Yr(e=>e.toLowerCase())),e.toUpperCase=()=>e.check(/* @__PURE__ */Yr(e=>e.toUpperCase())),e.slugify=()=>e.check(/* @__PURE__ */Yr(e=>function(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}(e)))}),Mi=/* @__PURE__ */je("ZodString",(e,t)=>{In.init(e,t),Ti.init(e,t),e.email=t=>e.check(function(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...lt(t)})}(Ri,t)),e.url=t=>e.check(function(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...lt(t)})}(Li,t)),e.jwt=t=>e.check(function(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...lt(t)})}(Ki,t)),e.emoji=t=>e.check(function(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...lt(t)})}(Di,t)),e.guid=t=>e.check(Ur(Ni,t)),e.uuid=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...lt(t)})}(Pi,t)),e.uuidv4=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...lt(t)})}(Pi,t)),e.uuidv6=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...lt(t)})}(Pi,t)),e.uuidv7=t=>e.check(function(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...lt(t)})}(Pi,t)),e.nanoid=t=>e.check(function(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...lt(t)})}($i,t)),e.guid=t=>e.check(Ur(Ni,t)),e.cuid=t=>e.check(function(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...lt(t)})}(ji,t)),e.cuid2=t=>e.check(function(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...lt(t)})}(Fi,t)),e.ulid=t=>e.check(function(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...lt(t)})}(Ui,t)),e.base64=t=>e.check(function(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...lt(t)})}(qi,t)),e.base64url=t=>e.check(function(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...lt(t)})}(Ji,t)),e.xid=t=>e.check(function(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...lt(t)})}(Bi,t)),e.ksuid=t=>e.check(function(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...lt(t)})}(Wi,t)),e.ipv4=t=>e.check(function(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...lt(t)})}(Gi,t)),e.ipv6=t=>e.check(function(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...lt(t)})}(Hi,t)),e.cidrv4=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...lt(t)})}(Zi,t)),e.cidrv6=t=>e.check(function(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...lt(t)})}(Vi,t)),e.e164=t=>e.check(function(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...lt(t)})}(Yi,t)),e.datetime=t=>e.check(ai(t)),e.date=t=>e.check(ci(t)),e.time=t=>e.check(ui(t)),e.duration=t=>e.check(hi(t))});function zi(e){return function(e,t){return new e({type:"string",...lt(t)})}(Mi,e)}var Oi=/* @__PURE__ */je("ZodStringFormat",(e,t)=>{En.init(e,t),Ti.init(e,t)}),Ri=/* @__PURE__ */je("ZodEmail",(e,t)=>{Mn.init(e,t),Oi.init(e,t)}),Ni=/* @__PURE__ */je("ZodGUID",(e,t)=>{An.init(e,t),Oi.init(e,t)}),Pi=/* @__PURE__ */je("ZodUUID",(e,t)=>{Tn.init(e,t),Oi.init(e,t)}),Li=/* @__PURE__ */je("ZodURL",(e,t)=>{zn.init(e,t),Oi.init(e,t)}),Di=/* @__PURE__ */je("ZodEmoji",(e,t)=>{On.init(e,t),Oi.init(e,t)}),$i=/* @__PURE__ */je("ZodNanoID",(e,t)=>{Rn.init(e,t),Oi.init(e,t)}),ji=/* @__PURE__ */je("ZodCUID",(e,t)=>{Nn.init(e,t),Oi.init(e,t)}),Fi=/* @__PURE__ */je("ZodCUID2",(e,t)=>{Pn.init(e,t),Oi.init(e,t)}),Ui=/* @__PURE__ */je("ZodULID",(e,t)=>{Ln.init(e,t),Oi.init(e,t)}),Bi=/* @__PURE__ */je("ZodXID",(e,t)=>{Dn.init(e,t),Oi.init(e,t)}),Wi=/* @__PURE__ */je("ZodKSUID",(e,t)=>{$n.init(e,t),Oi.init(e,t)}),Gi=/* @__PURE__ */je("ZodIPv4",(e,t)=>{Wn.init(e,t),Oi.init(e,t)}),Hi=/* @__PURE__ */je("ZodIPv6",(e,t)=>{Gn.init(e,t),Oi.init(e,t)}),Zi=/* @__PURE__ */je("ZodCIDRv4",(e,t)=>{Hn.init(e,t),Oi.init(e,t)}),Vi=/* @__PURE__ */je("ZodCIDRv6",(e,t)=>{Zn.init(e,t),Oi.init(e,t)}),qi=/* @__PURE__ */je("ZodBase64",(e,t)=>{qn.init(e,t),Oi.init(e,t)}),Ji=/* @__PURE__ */je("ZodBase64URL",(e,t)=>{Jn.init(e,t),Oi.init(e,t)}),Yi=/* @__PURE__ */je("ZodE164",(e,t)=>{Yn.init(e,t),Oi.init(e,t)}),Ki=/* @__PURE__ */je("ZodJWT",(e,t)=>{Kn.init(e,t),Oi.init(e,t)}),Qi=/* @__PURE__ */je("ZodNumber",(e,t)=>{Qn.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=n,{minimum:i,maximum:o,format:s,multipleOf:a,exclusiveMaximum:l,exclusiveMinimum:c}=e._zod.bag;"string"==typeof s&&s.includes("int")?r.type="integer":r.type="number","number"==typeof c&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.minimum=c,r.exclusiveMinimum=!0):r.exclusiveMinimum=c),"number"==typeof i&&(r.minimum=i,"number"==typeof c&&"draft-04"!==t.target&&(c>=i?delete r.minimum:delete r.exclusiveMinimum)),"number"==typeof l&&("draft-04"===t.target||"openapi-3.0"===t.target?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),"number"==typeof o&&(r.maximum=o,"number"==typeof l&&"draft-04"!==t.target&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),"number"==typeof a&&(r.multipleOf=a)})(e,t,n),e.gt=(t,n)=>e.check(Gr(t,n)),e.gte=(t,n)=>e.check(Hr(t,n)),e.min=(t,n)=>e.check(Hr(t,n)),e.lt=(t,n)=>e.check(Br(t,n)),e.lte=(t,n)=>e.check(Wr(t,n)),e.max=(t,n)=>e.check(Wr(t,n)),e.int=t=>e.check(to(t)),e.safe=t=>e.check(to(t)),e.positive=t=>e.check(Gr(0,t)),e.nonnegative=t=>e.check(Hr(0,t)),e.negative=t=>e.check(Br(0,t)),e.nonpositive=t=>e.check(Wr(0,t)),e.multipleOf=(t,n)=>e.check(Zr(t,n)),e.step=(t,n)=>e.check(Zr(t,n)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Xi(e){return function(e,t){return new e({type:"number",checks:[],...lt(t)})}(Qi,e)}var eo=/* @__PURE__ */je("ZodNumberFormat",(e,t)=>{Xn.init(e,t),Qi.init(e,t)});function to(e){return function(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...lt(t)})}(eo,e)}var no=/* @__PURE__ */je("ZodBoolean",(e,t)=>{er.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.type="boolean"})(0,0,t)});function ro(e){return function(e,t){return new e({type:"boolean",...lt(t)})}(no,e)}var io=/* @__PURE__ */je("ZodNull",(e,t)=>{tr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{"openapi-3.0"===t.target?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"})(0,e,t)});var oo=/* @__PURE__ */je("ZodUnknown",(e,t)=>{nr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>{}});function so(){return new oo({type:"unknown"})}var ao=/* @__PURE__ */je("ZodNever",(e,t)=>{rr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t,n)=>{n.not={}})(0,0,t)});function lo(e){return function(e,t){return new e({type:"never",...lt(t)})}(ao,e)}var co=/* @__PURE__ */je("ZodDate",(e,t)=>{ir.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Date cannot be represented in JSON Schema")})(0,e),e.min=(t,n)=>e.check(Hr(t,n)),e.max=(t,n)=>e.check(Wr(t,n));const n=e._zod.bag;e.minDate=n.minimum?new Date(n.minimum):null,e.maxDate=n.maximum?new Date(n.maximum):null}),uo=/* @__PURE__ */je("ZodArray",(e,t)=>{sr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def,{minimum:s,maximum:a}=e._zod.bag;"number"==typeof s&&(i.minItems=s),"number"==typeof a&&(i.maxItems=a),i.type="array",i.items=Xr(o.element,t,{...r,path:[...r.path,"items"]})})(e,t,n,r),e.element=t.element,e.min=(t,n)=>e.check(qr(t,n)),e.nonempty=t=>e.check(qr(1,t)),e.max=(t,n)=>e.check(Vr(t,n)),e.length=(t,n)=>e.check(Jr(t,n)),e.unwrap=()=>e.element});function po(e,t){return function(e,t,n){return new e({type:"array",element:t,...lt(n)})}(uo,e,t)}var ho=/* @__PURE__ */je("ZodObject",(e,t)=>{ur.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object",i.properties={};const s=o.shape;for(const c in s)i.properties[c]=Xr(s[c],t,{...r,path:[...r.path,"properties",c]});const a=new Set(Object.keys(s)),l=new Set([...a].filter(e=>{const n=o.shape[e]._zod;return"input"===t.io?void 0===n.optin:void 0===n.optout}));l.size>0&&(i.required=Array.from(l)),"never"===o.catchall?._zod.def.type?i.additionalProperties=!1:o.catchall?o.catchall&&(i.additionalProperties=Xr(o.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):"output"===t.io&&(i.additionalProperties=!1)})(e,t,n,r),Ye(e,"shape",()=>t.shape),e.keyof=()=>_o(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:so()}),e.loose=()=>e.clone({...e._zod.def,catchall:so()}),e.strict=()=>e.clone({...e._zod.def,catchall:lo()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>function(e,t){if(!rt(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const n=e._zod.def.shape;for(const e in t)if(void 0!==Object.getOwnPropertyDescriptor(n,e))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return at(e,Qe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ke(this,"shape",n),n}}))}(e,t),e.safeExtend=t=>function(e,t){if(!rt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return at(e,Qe(e._zod.def,{get shape(){const n={...e._zod.def.shape,...t};return Ke(this,"shape",n),n}}))}(e,t),e.merge=t=>{return r=t,at(n=e,Qe(n._zod.def,{get shape(){const e={...n._zod.def.shape,...r._zod.def.shape};return Ke(this,"shape",e),e},get catchall(){return r._zod.def.catchall},checks:[]}));var n,r},e.pick=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return at(e,Qe(e._zod.def,{get shape(){const e={};for(const r in t){if(!(r in n.shape))throw new Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Ke(this,"shape",e),e},checks:[]}))}(e,t),e.omit=t=>function(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");return at(e,Qe(e._zod.def,{get shape(){const r={...e._zod.def.shape};for(const e in t){if(!(e in n.shape))throw new Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Ke(this,"shape",r),r},checks:[]}))}(e,t),e.partial=(...t)=>function(e,t,n){const r=t._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");return at(t,Qe(t._zod.def,{get shape(){const r=t._zod.def.shape,i={...r};if(n)for(const t in n){if(!(t in r))throw new Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:"optional",innerType:r[t]}):r[t])}else for(const t in r)i[t]=e?new e({type:"optional",innerType:r[t]}):r[t];return Ke(this,"shape",i),i},checks:[]}))}(Ao,e,t[0]),e.required=(...t)=>{return n=Po,r=e,i=t[0],at(r,Qe(r._zod.def,{get shape(){const e=r._zod.def.shape,t={...e};if(i)for(const r in i){if(!(r in t))throw new Error(`Unrecognized key: "${r}"`);i[r]&&(t[r]=new n({type:"nonoptional",innerType:e[r]}))}else for(const r in e)t[r]=new n({type:"nonoptional",innerType:e[r]});return Ke(this,"shape",t),t}}));var n,r,i}});function mo(e,t){return new ho({type:"object",shape:e??{},...lt(t)})}var fo=/* @__PURE__ */je("ZodUnion",(e,t)=>{hr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=!1===i.inclusive,s=i.options.map((e,n)=>Xr(e,t,{...r,path:[...r.path,o?"oneOf":"anyOf",n]}));o?n.oneOf=s:n.anyOf=s})(e,t,n,r),e.options=t.options});function go(e,t){return new fo({type:"union",options:e,...lt(t)})}var yo=/* @__PURE__ */je("ZodDiscriminatedUnion",(e,t)=>{fo.init(e,t),mr.init(e,t)});function wo(e,t,n){return new yo({type:"union",options:t,discriminator:e,...lt(n)})}var bo=/* @__PURE__ */je("ZodIntersection",(e,t)=>{fr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.left,t,{...r,path:[...r.path,"allOf",0]}),s=Xr(i.right,t,{...r,path:[...r.path,"allOf",1]}),a=e=>"allOf"in e&&1===Object.keys(e).length;n.allOf=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]]})(e,t,n,r)});var vo=/* @__PURE__ */je("ZodRecord",(e,t)=>{wr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=n,o=e._zod.def;i.type="object";const s=o.keyType,a=s._zod.bag?.patterns;if("loose"===o.mode&&a&&a.size>0){const e=Xr(o.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const t of a)i.patternProperties[t.source]=e}else"draft-07"!==t.target&&"draft-2020-12"!==t.target||(i.propertyNames=Xr(o.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Xr(o.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const l=s._zod.values;if(l){const e=[...l].filter(e=>"string"==typeof e||"number"==typeof e);e.length>0&&(i.required=e)}})(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function xo(e,t,n){return new vo({type:"record",keyType:e,valueType:t,...lt(n)})}var ko=/* @__PURE__ */je("ZodEnum",(e,t)=>{br.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=Ge(e._zod.def.entries);r.every(e=>"number"==typeof e)&&(n.type="number"),r.every(e=>"string"==typeof e)&&(n.type="string"),n.enum=r})(e,0,n),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const o of e){if(!n.has(o))throw new Error(`Key ${o} not found in enum`);i[o]=t.entries[o]}return new ko({...t,checks:[],...lt(r),entries:i})},e.exclude=(e,r)=>{const i={...t.entries};for(const t of e){if(!n.has(t))throw new Error(`Key ${t} not found in enum`);delete i[t]}return new ko({...t,checks:[],...lt(r),entries:i})}});function _o(e,t){return new ko({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...lt(t)})}var So=/* @__PURE__ */je("ZodLiteral",(e,t)=>{vr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(void 0===o){if("throw"===t.unrepresentable)throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if("bigint"==typeof o){if("throw"===t.unrepresentable)throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(0===i.length);else if(1===i.length){const e=i[0];n.type=null===e?"null":typeof e,"draft-04"===t.target||"openapi-3.0"===t.target?n.enum=[e]:n.const=e}else i.every(e=>"number"==typeof e)&&(n.type="number"),i.every(e=>"string"==typeof e)&&(n.type="string"),i.every(e=>"boolean"==typeof e)&&(n.type="boolean"),i.every(e=>null===e)&&(n.type="null"),n.enum=i})(e,t,n),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Co(e,t){return new So({type:"literal",values:Array.isArray(e)?e:[e],...lt(t)})}var Io=/* @__PURE__ */je("ZodTransform",(e,t)=>{xr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,e),e._zod.parse=(n,r)=>{if("backward"===r.direction)throw new Ue(e.constructor.name);n.addIssue=r=>{if("string"==typeof r)n.issues.push(ft(r,n.value,t));else{const t=r;t.fatal&&(t.continue=!1),t.code??(t.code="custom"),t.input??(t.input=n.value),t.inst??(t.inst=e),n.issues.push(ft(t))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Eo(e){return new Io({type:"transform",transform:e})}var Ao=/* @__PURE__ */je("ZodOptional",(e,t)=>{_r.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oi(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});function To(e){return new Ao({type:"optional",innerType:e})}var Mo=/* @__PURE__ */je("ZodExactOptional",(e,t)=>{Sr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oi(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var zo=/* @__PURE__ */je("ZodNullable",(e,t)=>{Cr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o=Xr(i.innerType,t,r),s=t.seen.get(e);"openapi-3.0"===t.target?(s.ref=i.innerType,n.nullable=!0):n.anyOf=[o,{type:"null"}]})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oo(e){return new zo({type:"nullable",innerType:e})}var Ro=/* @__PURE__ */je("ZodDefault",(e,t)=>{Ir.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});var No=/* @__PURE__ */je("ZodPrefault",(e,t)=>{Ar.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,"input"===t.io&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Po=/* @__PURE__ */je("ZodNonOptional",(e,t)=>{Tr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType})(e,t,0,r),e.unwrap=()=>e._zod.def.innerType});var Lo=/* @__PURE__ */je("ZodCatch",(e,t)=>{zr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;let o;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});var Do=/* @__PURE__ */je("ZodPipe",(e,t)=>{Or.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def,o="input"===t.io?"transform"===i.in._zod.def.type?i.out:i.in:i.out;Xr(o,t,r),t.seen.get(e).ref=o})(e,t,0,r),e.in=t.in,e.out=t.out});function $o(e,t){return new Do({type:"pipe",in:e,out:t})}var jo=/* @__PURE__ */je("ZodReadonly",(e,t)=>{Nr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(t,n,r)=>((e,t,n,r)=>{const i=e._zod.def;Xr(i.innerType,t,r),t.seen.get(e).ref=i.innerType,n.readOnly=!0})(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});var Fo=/* @__PURE__ */je("ZodCustom",(e,t)=>{Dr.init(e,t),Ai.init(e,t),e._zod.processJSONSchema=(e,t,n)=>((e,t)=>{if("throw"===t.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,e)});function Uo(e,t={}){const n=new Fo({type:"custom",check:"custom",fn:t=>t instanceof e,abort:!0,...lt(t)});return n._zod.bag.Class=e,n._zod.check=t=>{t.value instanceof e||t.issues.push({code:"invalid_type",expected:e.name,input:t.value,inst:n,path:[...n._zod.def.path??[]]})},n}function Bo(e,t){return $o(Eo(e),t)}function Wo(e){return function(e,t){return new e({type:"number",coerce:!0,checks:[],...lt(t)})}(Qi,e)}function Go(e){return function(e,t){return new e({type:"boolean",coerce:!0,...lt(t)})}(no,e)}function Ho(e){return function(e,t){return new e({type:"date",coerce:!0,...lt(t)})}(co,e)}_o(["free","starter","growth","enterprise"]);var Zo,Vo=_o(["created","active","suspended","pending_approval"]),qo=_o(["free","starter","growth","enterprise"]),Jo=_o(["human","ai"]),Yo=_o(["male","female"]),Ko=_o(["active","learning","error"]),Qo=mo({vector_index_created:ro().nullable(),graph_index_created:ro().nullable()}),Xo=_o(["document","video"]),es=_o(["pending","processing","waiting_review","completed","failed"]),ts=(_o(["pending","running","completed","failed"]),_o(["pending","running","completed","failed","cancelled"])),ns=_o(["user","agent"]),rs=_o(["widget","app"]),is=(_o(["tell","show","do"]),_o(["app","website"])),os=_o(["widget","slack"]),ss=_o(["timer","github","slack","teams","jira"]),as=_o(["user_login","url_visit","update_workspace","create_user","update_user","delete_user","create_agent","update_agent","delete_agent","create_application","update_application","delete_application","create_widget","update_widget","delete_widget","create_knowledge","update_knowledge","delete_knowledge","approve_user","deny_user","request_workspace","widget_question","qa_run_started","start_simulation","create_automation","update_automation","delete_automation","toggle_automation"]),ls=mo({id:Xi().optional(),created_at:Ho().optional(),updated_at:Ho().optional()}),cs=mo({file:Uo(File),application_id:Wo().optional()}),ds=mo({id:Wo()}),us=mo({slug:zi()}),ps=mo({agent_id:Wo()}),hs=mo({widget_id:Wo()}),ms=mo({simulation_id:Wo()}),fs=mo({application_id:Wo()}),gs=mo({user_id:Wo()}),ys=mo({success:Co(!0)}),ws=ys.extend({message:zi()}),bs=(mo({workspace_id:Wo().optional()}),mo({application_id:Wo().optional()}),mo({limit:Wo().optional().default(50),offset:Wo().optional().default(0)})),vs=e=>mo({items:po(e),total:Xi(),limit:Xi(),offset:Xi()}),xs=e=>mo({items:po(e),count:Xi()}),ks=mo({status:zi(),timestamp:zi(),service:zi(),version:zi(),build:zi()}),_s=mo({name:zi(),version:zi(),build:zi(),status:zi(),timestamp:zi()}),Ss=_o(["password","oauth"]),Cs=ls.extend({is_super:ro(),status:Vo,email:zi().email(),external_id:zi().nullish(),first_name:zi().nullish(),last_name:zi().nullish(),password:zi().nullish(),image_url:zi().nullish(),prompt_limit:Xi().nullish(),last_login_at:Ho().nullish(),auth_method:Ss.nullish()}),Is=Cs.partial().extend({email:zi().email(),password:zi()}),Es=Cs.partial(),As=mo({users:po(Is)}),Ts=mo({users:po(Cs.partial())}),Ms=(mo({token:zi()}),ls.extend({name:zi(),slug:zi(),status:Vo,package:qo,ending_date:Ho().nullish(),external_workspace_id:zi().nullish()})),zs=Ms.partial().extend({name:zi().min(1)}),Os=Ms.partial(),Rs=_o(["active","past_due","canceled","unpaid","trialing","incomplete","incomplete_expired","paused"]),Ns=ls.extend({workspace_id:Xi(),package:qo,ending_date:Ho(),stripe_subscription_id:zi().nullable(),stripe_price_id:zi().nullable(),status:Rs.default("active").optional()}),Ps=(Ns.partial().extend({workspace_id:Xi(),package:qo}),Ns.partial(),_o(["owner","member"])),Ls=ls.extend({workspace_id:Xi(),user_id:Xi(),role:Ps}),Ds=mo({id:Xi(),agent_name:zi(),image_url:zi().nullish()}),$s=ls.extend({workspace_id:Xi(),application_id:Xi().optional(),file_name:zi().min(1),file_size:Wo(),file_type:Xo,file_url:zi(),source_url:zi().nullish(),agents:po(Ds).optional()}),js=_o(["chromium","firefox","webkit"]),Fs=mo({browsers:po(js).default(["chromium"]),parallel:ro().default(!1),fail_fast:ro().default(!1),timeout_per_browser:Xi().int().min(60).max(3600).optional()}),Us=ls.extend({workspace_id:Xi(),user_id:Xi(),application_id:Xi(),file_name:zi().min(1),file_size:Wo(),file_type:zi(),file_url:zi(),file_path:zi().nullable(),text_content:zi().nullish(),additional_instructions:zi().max(1e3).nullish(),status:es,processing_step:zi().nullish(),ultimate_goal:zi().nullish(),browser_config:Fs.nullish()}),Bs=mo({application_id:Wo(),file:Uo(File).optional(),text_content:zi().optional(),file_name:zi().optional(),additional_instructions:zi().max(1e3).optional()}),Ws=ls.extend({qa_flow_id:Xi(),workspace_id:Xi(),triggered_by:Xi(),status:ts,browser_type:js,browser_config:Fs.nullish(),total_tests:Xi().int().nonnegative(),passed_tests:Xi().int().nonnegative(),failed_tests:Xi().int().nonnegative(),started_at:Ho().nullish(),completed_at:Ho().nullish()}),Gs=mo({step:Xi(),message:zi(),timestamp:zi(),status:_o(["success","error","info"])}),Hs=mo({run_id:Xi(),status:_o(["pending","running","passed","failed","skipped"]),browser_type:js.nullish(),progress_log:po(Gs).default([]),error_message:zi().nullish(),screenshot_url:zi().nullish(),simulation_id:Xi().nullish(),duration_ms:Xi().nullish(),started_at:zi().nullish(),completed_at:zi().nullish()}),Zs=mo({version:Xi().int().positive(),test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"]),change_type:_o(["created","modified","self_healed","refined","deleted"]),change_reason:zi().nullish(),changed_by:Xi().nullish(),created_at:zi(),accepted:ro().optional()}),Vs=mo({failure_type:_o(["locator","assertion","timeout","flow_change","environment"]),failure_message:zi().nullish(),failure_context:xo(zi(),so()).nullish(),repair_strategy:zi().nullish(),repair_details:xo(zi(),so()).nullish(),confidence_score:Xi().min(0).max(1).nullish(),validation_status:_o(["pending","validated","failed","rejected"]),simulation_id:Xi().nullish(),validation_simulation_id:Xi().nullish(),healed_version:Xi().nullish(),created_at:zi()}),qs=ls.extend({qa_flow_id:Xi(),workspace_id:Xi(),order_index:Xi().int().nonnegative(),test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"]),is_active:Bo(e=>"number"==typeof e?0!==e:e,ro()),current_version:Xi().int().positive(),version_history:po(Zs).nullable(),executions:po(Hs).nullable(),healing_attempts:po(Vs).nullable(),healing_metadata:xo(zi(),so()).nullish(),last_healed_at:Ho().nullish()}),Js=(mo({qa_flow_id:Xi(),test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"]).optional()}),mo({ultimateGoal:zi(),document:Us,testCases:po(mo({id:Xi(),title:zi(),prompt:zi(),objective:zi(),steps:po(zi()),expectedOutcome:zi(),priority:_o(["Low","Medium","High"])})),summary:mo({total:Xi(),estimatedTime:zi(),complexity:_o(["Low","Medium","High"])})})),Ys=mo({ultimate_goal:zi(),test_cases:po(mo({test_title:zi(),test_objective:zi(),test_steps:po(zi()),expected_outcome:zi(),priority:_o(["Low","Medium","High"])})),summary:mo({total_tests:Xi(),high_priority:Xi(),medium_priority:Xi(),low_priority:Xi(),estimated_time_minutes:Xi()})}),Ks=(wo("event",[mo({event:Co("response.created"),data:mo({message:zi()})}),mo({event:Co("response.progress"),data:mo({message:zi()})}),mo({event:Co("response.clear"),data:mo({}).optional()}),mo({event:Co("response.completed"),data:Ys}),mo({event:Co("error"),data:mo({detail:zi()})})]),go([zi(),Xi(),ro(),po(zi()),function(e,t){return new e({type:"null",...lt(t)})}(io,Zo)])),Qs=(_o(["created","modified","self_healed","refined","deleted"]),_o(["locator","assertion","timeout","flow_change","environment"])),Xs=(_o(["pending","validated","failed","rejected"]),mo({healing_enabled:ro().default(!0),auto_apply:ro().default(!1),min_confidence_threshold:Xi().min(0).max(1).default(.85),max_healing_attempts:Xi().int().min(1).max(5).default(2),last_healing_attempt:zi().datetime().nullable(),total_healing_attempts:Xi().int().default(0),successful_heals:Xi().int().default(0)}),mo({failure_type:Qs,is_healable:ro(),is_actual_bug:ro(),failure_message:zi(),failure_context:xo(zi(),so()),suggested_repair:mo({type:_o(["update_locator","update_assertion","update_steps","skip_test"]),confidence:Xi().min(0).max(1),details:xo(zi(),so())}).nullable()})),ea=(mo({go_to_url:mo({url:zi(),new_tab:ro()})}),mo({click_element_by_index:mo({index:Xi().int().min(1)})}),mo({input_text:mo({index:Xi(),text:zi(),clear_existing:ro()})}),mo({write_file:mo({file_name:zi(),content:zi(),append:ro(),trailing_newline:ro(),leading_newline:ro()})}),mo({get_otp:mo({question:zi()})}),mo({done:mo({success:ro(),message:zi().optional()})}),mo({wait:mo({seconds:Xi()})}),mo({reload_page:mo({})}),mo({open_new_tab:mo({url:zi()})}),mo({navigate_to_url:mo({url:zi()})}),xo(zi(),so())),ta=mo({evaluation_previous_goal:zi().optional().nullable(),memory:zi().optional().nullable(),next_goal:zi().optional().nullable(),action:po(ea).optional().nullable(),thinking:zi().optional().nullable()}).passthrough(),na=mo({is_done:ro(),success:ro().optional().nullable(),long_term_memory:zi().optional().nullable(),extracted_content:zi().optional().nullable(),include_extracted_content_only_once:ro().optional().nullable(),include_in_memory:ro().optional().nullable(),error:zi().optional().nullable(),metadata:mo({click_x:Xi().optional(),click_y:Xi().optional(),new_tab_opened:ro().optional(),input_x:Xi().optional(),input_y:Xi().optional()}).passthrough().optional().nullable()}).passthrough(),ra=mo({url:zi(),title:zi(),tab_id:zi().optional(),parent_tab_id:zi().optional().nullable()}).passthrough(),ia=mo({node_id:Xi().optional(),backend_node_id:Xi().optional(),frame_id:zi().optional().nullable(),node_type:Xi().optional(),node_value:zi().optional(),node_name:zi().optional(),attributes:xo(zi(),zi()).optional().nullable(),x_path:zi().optional(),element_hash:Xi().optional(),bounds:mo({x:Xi(),y:Xi(),width:Xi(),height:Xi()}).passthrough().optional().nullable(),stable_hash:Xi().optional(),ax_name:zi().optional().nullable()}).passthrough(),oa=mo({tabs:po(ra),screenshot_path:zi().nullable(),interacted_element:po(ia.nullable()),url:zi(),title:zi()}).passthrough(),sa=mo({step_start_time:Xi().optional().nullable(),step_end_time:Xi().optional().nullable(),step_number:Xi().optional().nullable(),step_interval:Xi().optional().nullable()}).passthrough(),aa=mo({model_output:ta.nullable(),result:po(na),state:oa,metadata:sa.nullable(),state_message:zi().optional().nullable()}).passthrough(),la=(mo({history:po(aa)}),mo({step_number:Xi().int().positive(),topic:zi(),screenshot_url:zi().nullable(),title:zi().optional().nullable(),url:zi().optional().nullable()})),ca=mo({status:zi(),status_message:zi().nullable(),num_steps:Xi().int().nonnegative().nullable(),created_at:Ho()}),da=ls.extend({application_id:Xi(),agent_id:Xi(),job_id:zi(),session_id:zi().nullish(),status:zi(),status_message:zi().nullish(),path:zi().nullish(),instructions:zi().nullish(),num_steps:Xi().int().nonnegative(),pinned:ro().optional(),source:_o(["direct","qa"]).optional(),agent_name:zi().nullish(),graph_index_id:zi().nullish(),progress_log:po(ca).optional(),agents:po(Ds).optional()}),ua=(mo({user_id:Xi(),email:zi(),first_name:zi().optional().nullable(),last_name:zi().optional().nullable(),last_simulation_at:zi().optional()}),da.partial().extend({application_id:Xi(),agent_id:Xi(),instructions:zi(),max_steps:Xi().int().positive().max(1e3).optional(),timeout:Xi().positive().max(360).optional()})),pa=mo({job_id:zi().optional(),status:zi().optional(),status_message:zi().optional(),num_steps:Xi().int().nonnegative().optional(),pinned:ro().optional(),graph_index_id:zi().optional()}),ha=mo({answer:zi().min(1)}),ma=ls.extend({session_id:zi(),chat_id:zi(),application_id:Wo().nullish(),blob_url:zi().nullable(),event_count:Wo().int().nonnegative(),started_at:Ho(),ended_at:Ho().nullable(),is_active:Bo(e=>"number"==typeof e?0!==e:e,ro()),metadata:mo({userAgent:zi().optional(),url:zi().optional()}).nullable(),last_batch_index:Wo().int().nullable(),last_event_timestamp:Wo().int().nullable(),last_upload_time:Ho().nullable()}),fa=mo({session_id:zi().min(1),chat_id:zi().min(1),application_id:Xi().int().nullish(),blob_url:zi().nullish(),event_count:Xi().int().nonnegative().optional(),started_at:Ho().optional(),ended_at:Ho().nullish(),is_active:Bo(e=>"number"==typeof e?0!==e:e,ro()).optional(),metadata:mo({userAgent:zi().optional(),url:zi().optional(),applicationId:Xi().optional()}).nullable().optional(),last_batch_index:Xi().int().nonnegative().nullish(),last_event_timestamp:Xi().int().nullish(),last_upload_time:Ho().nullish()}),ga=mo({id:Xi(),simulation_id:Xi(),status:zi(),status_message:zi().nullable(),num_steps:Xi().int().nonnegative().nullable(),created_at:Ho()}),ya=mo({start:zi(),end:zi(),action:zi()}),wa=mo({id:zi(),screenshots:po(zi()),title:zi(),url:zi(),state:po(zi()),mentions:po(zi())}),ba=mo({nodes:po(wa),edges:po(ya)}),va=ls.extend({workspace_id:Xi(),user_id:Xi().nullish(),application_id:Xi(),agent_name:zi(),agent_type:Jo,agent_voice:Yo,agent_description:zi().nullish(),instructions:zi().nullish(),image_url:zi().nullish(),graph_index_id:zi().nullish(),vector_store_id:zi().nullish(),status:Ko,status_message:zi().nullish(),learning_progress:Qo.nullish(),learning_started_at:Ho().nullish(),workspace:Ms.optional(),user:Cs.optional(),knowledge:po($s).optional(),simulations:po(da).optional(),simulation_count:Xi().int().nonnegative().optional(),knowledge_count:Xi().int().nonnegative().optional()}),xa=e=>{if(Array.isArray(e))return e.map(e=>Number(e));if("string"==typeof e){const t=JSON.parse(e);return Array.isArray(t)?t.map(e=>Number(e)):[]}return[]},ka=go([po(Xi()),zi()]).transform(xa),_a=go([po(Xi()),zi()]).transform(xa),Sa=va.partial().extend({application_id:Wo(),agent_name:zi(),agent_type:Jo,agent_voice:Yo,agent_description:zi(),instructions:zi(),file:Uo(File).optional(),image_url:zi().optional(),knowledge_ids:ka,simulation_ids:_a}),Ca=va.partial().extend({file:Uo(File).optional(),knowledge_ids:ka,simulation_ids:_a}),Ia=(mo({text:zi(),task_id:zi().optional()}),mo({status:zi(),message:zi().optional()}),mo({task_id:zi().optional(),status:zi().optional(),current_step:zi().optional(),error:zi().optional(),message:zi().optional()}),mo({workflow_id:zi(),workflow_type:zi(),status:zi(),current_step:zi(),error:zi().nullable(),created_at:zi(),updated_at:zi()}),mo({session_id:zi().optional(),live_view_url:zi().nullish(),status:zi().optional(),message:zi().nullish(),success:ro().optional()}),_o(["pending","running","completed","failed","cancelled","has_question","in_progress"]),mo({contentType:_o(["document","video","automation_log","screenshot","all"]).optional(),context:zi().optional(),previousActions:po(zi()).optional(),top:Wo().min(1).max(100).optional(),minConfidence:Wo().min(0).max(1).optional(),entities:po(zi()).optional(),useVectorSearch:ro().optional(),vectorThreshold:Wo().min(0).max(1).optional()}),mo({id:zi(),content:zi(),contentType:_o(["document","video","automation_log","screenshot"]),sourceFile:zi(),sourceType:zi(),metadata:zi(),confidence:Xi(),keyPhrases:po(zi()),entities:po(zi()),sentiment:zi(),vectorContent:po(Xi())})),Ea=(mo({document:Ia,score:Xi(),highlights:xo(zi(),po(zi())).optional()}),mo({simulation_id:Wo().positive("Simulation ID must be a positive number")})),Aa=mo({agent:va,simulation_id:Xi(),knowledge_id:Xi(),message:zi()}),Ta=ls.extend({workspace_id:Xi(),name:zi(),type:is,url:zi().nullish(),username:zi().nullish(),password:zi().nullish(),allowed_domains:po(zi()).nullish().default([])}),Ma=Ta.partial().extend({type:is,name:zi().min(1),url:zi(),allowed_domains:po(zi()).optional().default([])}),za=Ta.partial().omit({workspace_id:!0}),Oa=mo({chip_mode:_o(["show","tell","do"]),chip_text:zi()}),Ra=mo({widget_enabled:ro(),widget_appearance:_o(["default","compact","full"]),widget_position:_o(["bottom_left","bottom_right","top_left","top_right"]),widget_device:_o(["desktop","mobile","desktop_mobile"]),widget_header:zi(),widget_body:zi(),widget_greeting:zi(),widget_feature_tell:ro(),widget_feature_show:ro(),widget_feature_do:ro(),widget_feature_human:ro(),widget_background_color:zi(),widget_text_color:zi(),widget_border_color:zi(),widget_accent_color:zi(),widget_secondary_color:zi(),widget_border_radius:zi(),widget_font_size:zi(),widget_width:zi(),widget_height:zi(),widget_shadow:zi(),widget_animation_duration:zi(),widget_fade_duration:zi(),widget_bounce_effect:ro(),widget_chips:po(Oa)}),Na=mo({webhook_url:zi().url(),channel:zi(),bot_token:zi(),notifications_enabled:ro()}),Pa=ls.extend({application_id:Xi(),agent_id:Xi(),type:os,settings:go([Ra,Na]),status:Vo,marketrix_id:zi(),marketrix_key:zi(),snippet:zi().nullish()}),La=(Pa.extend({application:Ta.partial(),workspace:Ms.partial(),user:Cs.partial(),agent:va.partial()}),Pa.extend({agent:va.partial().optional()})),Da=(Ta.extend({widgets:po(Pa).optional(),agents:po(va).optional()}),Pa.partial().extend({application_id:Xi().positive(),agent_id:Xi().positive(),type:os,settings:go([Ra,Na]).optional()})),$a=Pa.partial(),ja=ls.extend({widget_id:Xi(),url_pattern:zi(),message:go([zi(),po(zi())]),description:zi().optional()}),Fa=ja.partial().extend({widget_id:Xi().positive(),url_pattern:zi().min(1),message:go([zi().min(1),po(zi().min(1)).min(1)])}),Ua=ja.partial(),Ba=po(mo({step_number:Xi(),action:zi(),element:zi(),text:zi(),description:zi(),selector:zi()})),Wa=ls.extend({application_id:Xi(),question:zi(),answer:Ba}),Ga=(mo({marketrix_id:zi().optional(),marketrix_key:zi().optional(),agent_id:Xi().positive().optional(),application_id:Xi().positive().optional(),chat_id:zi().optional(),content:zi()}).refine(e=>(e.marketrix_id&&e.marketrix_key)??(e.agent_id&&e.application_id),{message:"Either marketrix_id + marketrix_key or both agent_id + application_id must be provided"}),mo({text:zi(),task_id:zi().optional()}),wo("type",[mo({type:Co("registered"),chat_id:zi(),application_id:Xi().optional()}),mo({type:Co("pong")}),mo({type:Co("heartbeat")}),mo({type:Co("chat/response"),request_id:zi(),text:zi(),task_id:zi().optional()}),mo({type:Co("chat/error"),request_id:zi(),error:zi()}),mo({type:Co("task/status"),status:_o(["started","completed","failed","stopped","in_progress","has_question"]),message:zi().optional(),task_id:zi().optional(),timestamp:Xi().optional()}),mo({type:Co("tool/call"),call_id:zi(),tool:zi(),args:xo(zi(),so()),mode:_o(["show","do"]).optional(),explanation:zi().optional(),state_version:Xi().optional()})])),Ha=wo("type",[mo({type:Co("chat/tell"),request_id:zi(),content:zi()}),mo({type:Co("chat/show"),request_id:zi(),content:zi()}),mo({type:Co("chat/do"),request_id:zi(),content:zi()}),mo({type:Co("chat/stop"),task_id:zi().optional()}),mo({type:Co("tool/response"),call_id:zi(),success:ro(),data:zi().optional(),error:zi().optional(),state_version:Xi().optional()}),mo({type:Co("ping")}),mo({type:Co("rrweb/metadata"),session_id:zi(),chat_id:zi(),application_id:Xi(),url:zi().optional(),user_agent:zi().optional(),timestamp:Xi().optional()}),mo({type:Co("rrweb/events"),session_id:zi(),events:po(so())})]),Za=_o(["simulations","agents","qa","user","jobs"]),Va=wo("type",[mo({type:Co("simulation/updated"),simulation_id:Xi(),application_id:Xi(),status:zi(),step_label:zi().optional(),step_pending:ro().optional(),num_steps:Xi().optional()}),mo({type:Co("simulation/created"),simulation_id:Xi(),application_id:Xi()}),mo({type:Co("simulation/deleted"),simulation_id:Xi(),application_id:Xi()}),mo({type:Co("agent/updated"),agent_id:Xi(),application_id:Xi(),status:zi()}),mo({type:Co("agent/created"),agent_id:Xi(),application_id:Xi()}),mo({type:Co("agent/deleted"),agent_id:Xi(),application_id:Xi()}),mo({type:Co("qa-document/updated"),document_id:Xi(),application_id:Xi(),status:zi(),step_label:zi().optional()}),mo({type:Co("qa-run/updated"),run_id:Xi(),document_id:Xi(),application_id:Xi(),status:zi()}),mo({type:Co("qa-test/updated"),test_id:Xi(),run_id:Xi(),document_id:Xi(),application_id:Xi(),status:zi()}),mo({type:Co("user/updated"),user_id:Xi(),workspace_id:Xi(),status:zi()}),mo({type:Co("job/progress"),job_id:zi(),application_id:Xi(),status:zi(),message:zi().optional()}),mo({type:Co("job/completed"),job_id:zi(),application_id:Xi(),result:so().optional()}),mo({type:Co("job/failed"),job_id:zi(),application_id:Xi(),error:zi()})]),qa=mo({details:zi().optional(),id:Xi().optional(),type:zi().optional(),name:zi().optional(),target_user_id:Xi().optional(),target_user_email:zi().optional(),reason:zi().optional(),assigned_role:zi().optional(),new_role:zi().optional(),previous_role:zi().optional(),workspace_name:zi().optional(),workspace_slug:zi().optional(),ip_address:zi().optional(),user_agent:zi().optional(),widget_type:zi().optional(),created_by:Xi().optional()}).passthrough(),Ja=ls.extend({workspace_id:Xi(),user_id:Xi(),type:as,metadata:qa.optional()}),Ya=Ja.partial().extend({type:as}),Ka=(ls.extend({user_id:Xi(),application_id:Xi(),agent_id:Xi(),chat_id:zi(),role:ns,source:rs,message:zi()}),ls.extend({workspace_id:Xi(),provider:ss,name:zi().min(1).max(120),identifier:zi().max(120).nullish(),api_endpoint:zi().url().nullish(),api_token:zi().nullish(),metadata:xo(zi(),so()).nullish(),is_active:ro().default(!0),status:Vo.default("active")})),Qa=mo({id:Wo().optional(),provider:ss,name:zi().min(1).max(120),identifier:zi().max(120).nullish(),api_endpoint:zi().url().nullish(),api_token:zi().nullish(),metadata:xo(zi(),so()).nullish(),is_active:ro().optional(),status:Vo.optional()}),Xa=mo({provider:ss.optional(),status:Vo.optional(),is_active:Go().optional(),limit:Wo().int().positive().max(100).optional(),offset:Wo().int().nonnegative().optional()}),el=mo({id:Xi(),full_name:zi(),name:zi(),private:ro(),html_url:zi(),default_branch:zi().optional()}),tl=mo({id:Xi(),name:zi(),status:zi(),conclusion:zi().nullable(),created_at:zi(),updated_at:zi(),html_url:zi(),head_branch:zi(),run_attempt:Xi()}),nl=_o(["pending","running","completed","failed","stopped"]),rl=(_o(["connector","condition"]),wo("kind",[mo({kind:Co("connector"),connector_type:zi().min(1),connector_id:Xi().nullable().optional(),capability:zi().min(1),role:_o(["trigger","callback"]),config:xo(zi(),so()).default({})}),mo({kind:Co("condition"),config:mo({field:zi().min(1),operator:_o(["equals","not_equals","contains","gt","lt"]),value:so()})})])),il=mo({from:zi().min(1),to:zi().min(1),when:_o(["true","false"]).optional()}),ol=mo({nodes:xo(zi(),rl),edges:po(il)}),sl=_o(["skip","queue","replace"]).default("skip"),al=ls.extend({workspace_id:Xi(),name:zi(),graph:ol,concurrency:sl,enabled:ro(),last_run_at:Ho().nullable(),next_run_at:Ho().nullable()}),ll=mo({name:zi().min(1).max(255),graph:ol,concurrency:sl.optional(),enabled:ro().optional()}),cl=mo({id:Wo(),name:zi().min(1).max(255).optional(),graph:ol.optional(),enabled:ro().optional()}),dl=mo({enabled:Go().optional(),limit:Wo().int().positive().max(100).optional(),offset:Wo().int().nonnegative().optional()}),ul=mo({status:_o(["completed","failed","skipped","stopped"]),output:xo(zi(),so()).nullable().optional(),error:zi().nullable().optional(),duration_ms:Xi().optional()}),pl=mo({id:Xi().optional(),automation_id:Xi(),status:nl,trigger_node_id:zi(),trigger_data:xo(zi(),so()).nullable(),node_results:xo(zi(),ul),started_at:Ho(),completed_at:Ho().nullable()}),hl=mo({status:nl.optional(),limit:Wo().int().positive().max(100).optional(),offset:Wo().int().nonnegative().optional()}),ml=mo({connector_type:zi(),built_in:ro(),triggers:po(mo({capability:zi(),description:zi(),config_schema:xo(zi(),so())})),callbacks:po(mo({capability:zi(),description:zi(),config_schema:xo(zi(),so())}))}),fl=mo({migration_type:zi().optional(),dry_run:ro().default(!0)}),gl=mo({migration_type:zi().optional(),backup:ro().default(!0)}),yl=mo({url:zi()}),wl=(mo({user_id:Xi(),file:Uo(File)}),mo({user_id:Xi(),application_id:Xi(),source:rs,prompt:zi(),status:zi()}),mo({user_id:Xi(),limit:Xi(),used:Xi(),remaining:Xi()})),bl=(mo({user_id:Xi(),workspace_id:Xi(),chat_count:Xi(),prompt_text:zi(),metadata:xo(zi(),zi()).optional()}),mo({to:zi(),subject:zi(),template:zi(),context:xo(zi(),zi())}),mo({id:zi(),object:Co("event"),api_version:zi().nullish(),created:Xi(),data:mo({object:xo(zi(),so()),previous_attributes:xo(zi(),so()).optional()}),livemode:ro(),pending_webhooks:Xi(),request:mo({id:zi().nullable(),idempotency_key:zi().nullable()}).nullable().optional(),type:zi()}),mo({priceId:zi().min(1,"Price ID is required"),successUrl:zi().url("Success URL must be a valid URL"),cancelUrl:zi().url("Cancel URL must be a valid URL")})),vl=mo({returnUrl:zi().url("Return URL must be a valid URL")}),xl=mo({plan:_o(["starter","growth"]).default("starter"),interval:_o(["month","year"]).default("month")}),kl=mo({subscriptionId:zi().min(1,"Subscription ID is required"),priceId:zi().min(1,"Price ID is required")}),_l=mo({success:ro(),message:zi()}),Sl=mo({subscriptionId:zi().nullable(),customerId:zi().nullable(),status:_o(["active","past_due","canceled","unpaid","trialing","incomplete","incomplete_expired","paused"]).nullable(),planTier:_o(["free","starter","growth","enterprise"]).nullable(),billingInterval:_o(["month","year"]).nullable(),priceId:zi().nullable(),trialEndDate:Ho().nullable(),currentPeriodStart:Ho().nullable(),currentPeriodEnd:Ho().nullable(),cancelAtPeriodEnd:ro(),isTrialing:ro(),daysRemainingInTrial:Xi().nullable(),trialProvisioned:ro()}),Cl=mo({sessionId:zi(),url:zi().url()}),Il=mo({url:zi().url()}),El=mo({subscriptionId:zi(),customerId:zi(),status:Co("trialing"),trialStartDate:Ho(),trialEndDate:Ho(),planTier:_o(["starter","growth"]),daysRemainingInTrial:Xi()}),Al=mo({used:Xi().int().min(0),limit:Xi().int()}),Tl=mo({applications:Al,simulationsPerMonth:Al,userPrompts:Al}),Ml=mo({amount:Xi().int().min(0),currency:zi().default("usd"),formatted:zi()}),zl=mo({planId:_o(["free","starter","growth","enterprise"]),monthly:Ml.nullable(),annual:Ml.nullable(),priceIds:mo({monthly:zi().nullable(),annual:zi().nullable()})}),Ol=mo({plans:po(zl),lastUpdated:zi().datetime()}),Rl=mo({id:_o(["free","starter","growth","enterprise"]),name:zi(),description:zi(),features:po(zi()),cta:zi(),isPopular:ro(),customPriceDisplay:zi().optional(),priceSubtext:zi().optional(),borderColor:zi(),buttonColor:zi(),outlineColor:zi(),checkColor:zi()}),Nl=mo({plans:po(Rl)}),Pl=mo({publishableKey:zi(),priceIds:mo({starter:mo({monthly:zi().nullable(),annual:zi().nullable()}),growth:mo({monthly:zi().nullable(),annual:zi().nullable()})}),trialDays:Xi().int().min(0),calendlyUrl:zi()}),Ll=mo({widgetKey:zi(),widgetId:zi(),widgetUrl:zi()}),Dl=mo({date:zi().describe("YYYY-MM-DD"),sessions:Xi().int().nonnegative(),events:Xi().int().nonnegative()}),$l=mo({items:po(Dl)}),jl=mo({role:_o(["user","assistant","system"]),content:zi(),timestamp:zi().optional()}),Fl=ls.extend({workspace_id:Xi(),application_id:Xi().nullish(),agent_id:Xi().nullish(),simulation_id:Xi().nullish(),chat_id:zi(),chat_content:zi().nullish(),chat_history:po(jl).nullish(),chat_output:zi().nullish(),preview_video_url:zi().nullish(),metadata:xo(zi(),so()).nullish()}),Ul=mo({application_id:Xi().nullish(),agent_id:Xi().nullish(),simulation_id:Xi().nullish(),chat_id:zi(),chat_content:zi().nullish(),chat_history:po(jl).nullish(),chat_output:zi().nullish(),preview_video_url:zi().nullish(),metadata:xo(zi(),so()).nullish()}),Bl=mo({chat_id:zi().optional(),agent_id:Xi().optional(),simulation_id:Xi().optional(),limit:Xi().optional(),offset:Xi().optional()}),Wl=class extends Error{issues;data;constructor(e){super(e.message,e),this.issues=e.issues,this.data=e.data}};function Gl(e,t){return{...e,...t}}var Hl=class{"~orpc";constructor(e){if(e.route?.successStatus&&X(e.route.successStatus))throw new Error("[ContractProcedure] Invalid successStatus.");if(Object.values(e.errorMap).some(e=>e&&e.status&&!X(e.status)))throw new Error("[ContractProcedure] Invalid error status code.");this["~orpc"]=e}};function Zl(e,t){let n=e;return t.prefix&&(n=function(e,t){return e.path?{...e,path:`${t}${e.path}`}:e}(n,t.prefix)),t.tags?.length&&(n=function(e,t){return{...e,tags:[...t,...e.tags??[]]}}(n,t.tags)),n}function Vl(e,t){if((n=e)instanceof Hl||("object"==typeof n||"function"==typeof n)&&null!==n&&"~orpc"in n&&"object"==typeof n["~orpc"]&&null!==n["~orpc"]&&"errorMap"in n["~orpc"]&&"route"in n["~orpc"]&&"meta"in n["~orpc"])return new Hl({...e["~orpc"],errorMap:Gl(t.errorMap,e["~orpc"].errorMap),route:Zl(e["~orpc"].route,t)});var n;const r={};for(const i in e)r[i]=Vl(e[i],t);return r}var ql=new class e extends Hl{constructor(e){super(e),this["~orpc"].prefix=e.prefix,this["~orpc"].tags=e.tags}$meta(t){return new e({...this["~orpc"],meta:t})}$route(t){return new e({...this["~orpc"],route:t})}$input(t){return new e({...this["~orpc"],inputSchema:t})}errors(t){return new e({...this["~orpc"],errorMap:Gl(this["~orpc"].errorMap,t)})}meta(t){return new e({...this["~orpc"],meta:(n=this["~orpc"].meta,r=t,{...n,...r})});var n,r}route(t){return new e({...this["~orpc"],route:(n=this["~orpc"].route,r=t,{...n,...r})});var n,r}input(t){return new e({...this["~orpc"],inputSchema:t})}output(t){return new e({...this["~orpc"],outputSchema:t})}prefix(t){return new e({...this["~orpc"],prefix:(n=this["~orpc"].prefix,r=t,n?`${n}${r}`:r)});var n,r}tag(...t){return new e({...this["~orpc"],tags:(n=this["~orpc"].tags,r=t,n?[...n,...r]:r)});var n,r}router(e){return Vl(e,this["~orpc"])}}({errorMap:{},route:{},meta:{}}),Jl=Symbol("ORPC_EVENT_ITERATOR_DETAILS");function Yl(e,t){return{"~standard":{[Jl]:{yields:e,returns:t},vendor:"orpc",version:1,validate:n=>D(n)?{value:ge(n,{async value(n,r){const i=r?t:e;if(!i)return n;const o=await i["~standard"].validate(n);if(o.issues)throw new Q("EVENT_ITERATOR_VALIDATION_FAILED",{message:"Event iterator validation failed",cause:new Wl({issues:o.issues,message:"Event iterator validation failed",data:n})});return o.value},error:async e=>e})}:{issues:[{message:"Expect event iterator",path:[]}]}}}}ql.route({method:"GET",tags:["Root"],path:"/",summary:"Get API index information and basic system details",description:"Returns general API information, version, and available endpoints"}).output(_s),ql.route({method:"GET",tags:["Internal"],path:"/health",summary:"Health check endpoint for monitoring system status",description:"Returns current system health, database connectivity, and service status"}).output(ks),ql.route({method:"GET",tags:["Root"],path:"/validate-url",summary:"Validate URL accessibility and DNS resolution",description:"Validates a URL for format, DNS resolution, and HTTP accessibility"}).input(mo({url:zi().url(),skip_network:zi().optional()})).output(mo({valid:ro(),accessible:ro(),dnsResolves:ro(),error:zi().optional().describe("Error message if URL validation failed"),warnings:po(zi()).optional().describe("Non-fatal issues found during URL validation")})),ql.route({method:"GET",tags:["Root"],path:"/config/public",summary:"Get public client configuration",description:"Returns widget key and widget ID. No auth. Values are stored in backend env only."}).output(Ll),ql.route({method:"GET",tags:["Auth"],path:"/auth/me",summary:"Get current authenticated user and workspace information",description:"Returns user profile and workspace data based on session cookie"}).output(mo({user:Cs,workspace:Ms.nullable(),workspaces:po(mo({id:Xi(),name:zi(),slug:zi(),role:_o(["owner","member"])}))})),ql.route({method:"GET",tags:["Auth"],path:"/email-action/{token}",summary:"Process email approval/rejection action",description:"Handles approve/reject links from admin emails. Token-in-URL authentication (no session required). Returns an HTML page, not JSON."}).input(mo({token:zi().min(1)})).output(mo({result:zi().describe("HTML response page")})),ql.route({method:"POST",tags:["Onboarding"],path:"/onboard",summary:"Complete user onboarding in one atomic operation",description:"Creates workspace, updates user status, and invites team members"}).input(mo({name:zi().min(1).max(45),slug:zi().min(1).max(45).optional(),domain:zi().min(1).max(200),team_emails:po(zi().email()).optional().default([]),app_url:zi().optional(),app_username:zi().optional(),app_password:zi().optional()})).output(mo({workspace:Ms})),ql.route({method:"POST",tags:["Workspace"],path:"/workspaces",summary:"Create a new workspace",description:"Creates new workspace with specified settings and returns workspace entity"}).input(zs).output(Ms),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces",summary:"Search and filter workspaces by various criteria",description:"Returns list of workspaces matching search parameters (name, domain, email, etc.)"}).input(mo({name:zi().optional(),domain:zi().optional(),email:zi().email().optional(),app_id:Wo().optional(),workspace_id:Wo().optional(),user_id:Wo().optional()}).extend(bs.shape)).output(vs(Ms)),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces/lookup/{slug}",summary:"Look up workspace by slug for onboarding",description:"Returns workspace name and slug for join-workspace flow. Requires onboarding-level auth."}).input(us).output(mo({name:zi(),slug:zi()}).nullable()),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces/{slug}",summary:"Get specific workspace details by slug",description:"Returns complete workspace information including settings and configuration"}).input(us).output(Ms),ql.route({method:"PUT",tags:["Workspace"],path:"/workspaces/{slug}",summary:"Update workspace settings and configuration",description:"Modifies workspace properties like name, domain, or feature settings"}).input(Os.extend({slug:zi()})).output(Ms),ql.route({method:"DELETE",tags:["Workspace"],path:"/workspaces/{slug}",summary:"Delete workspace and all associated data",description:"Permanently deletes a workspace and cleans up all related resources. This action cannot be undone."}).input(us).output(ys),ql.route({method:"GET",tags:["Workspace"],path:"/workspaces/{slug}/members",summary:"List workspace members",description:"Returns all members of the workspace with their user profile details and roles."}).input(us).output(xs(Ls.extend({user:Cs.pick({id:!0,email:!0,first_name:!0,last_name:!0,image_url:!0})}))),ql.route({method:"POST",tags:["Workspace"],path:"/workspaces/{slug}/members",summary:"Add member to workspace",description:"Invites a user by email to join the workspace with the specified role. Defaults to member role."}).input(us.extend({email:zi().email(),role:Ps.default("member")})).output(Ls),ql.route({method:"DELETE",tags:["Workspace"],path:"/workspaces/{slug}/members/{user_id}",summary:"Remove member from workspace",description:"Removes a user from the workspace by user_id. The user loses access immediately."}).input(us.extend({user_id:Xi()})).output(ys),ql.route({method:"PATCH",tags:["Workspace"],path:"/workspaces/{slug}/members/{user_id}",summary:"Update member role",description:"Changes the role of a workspace member. Valid roles: owner, member."}).input(us.extend({user_id:Xi(),role:Ps})).output(Ls),ql.route({method:"GET",tags:["Workspace"],path:"/users/me/workspaces",summary:"List workspaces for current user",description:"Returns all workspaces the authenticated user belongs to, including their role in each."}).output(xs(Ms.extend({role:Ps}))),ql.route({method:"POST",path:"/admin/reconcile",tags:["Internal"],summary:"Reconcile Stripe customers and WorkOS users",description:"Backfills missing Stripe customer IDs for workspaces and real WorkOS user IDs for users. Idempotent and safe to run repeatedly. Requires super user role."}).output(mo({workspaces_stripe_created:Xi(),users_workos_created:Xi(),workspace_plans_synced:Xi(),trials_provisioned:Xi(),stripe_plans_refreshed:Xi(),workos_profiles_synced:Xi(),errors:po(mo({type:zi(),id:Xi(),error:zi()}))})),ql.route({method:"POST",path:"/admin/maintenance",tags:["Internal"],summary:"Run periodic maintenance cleanup tasks",description:"Cleans up orphaned CosmosDB containers, QA simulations not linked to existing runs, and orphaned blob storage files. Idempotent and safe to run repeatedly. Requires super user role."}).output(mo({cosmos_containers_deleted:Xi(),orphaned_qa_simulations_deleted:Xi(),orphaned_blob_dirs_deleted:Xi(),errors:po(mo({type:zi(),detail:zi()}))})),ql.route({method:"POST",path:"/admin/rebuild",tags:["Internal"],summary:"Rebuild all agent indexes after cleanup",description:"Removes stale knowledge (missing files), stale simulations (0 steps or missing blobs), then deletes and recreates vector stores and knowledge graphs for every agent. Index creation is async. Requires super user role."}).output(mo({knowledge_removed:Xi(),simulations_removed:Xi(),agents_rebuilt:Xi(),errors:po(mo({type:zi(),detail:zi()}))})),ql.route({method:"POST",tags:["Application"],path:"/applications",summary:"Create a new application",description:"Creates a new application for the authenticated workspace and returns the created entity."}).input(Ma).output(Ta),ql.route({method:"GET",tags:["Application"],path:"/applications",summary:"Search applications for workspace",description:"Returns applications for the authenticated workspace, optionally filtered by type, always includes widgets"}).input(mo({type:is.optional(),include:po(_o(["widgets"])).optional()}).extend(bs.shape)).output(vs(Ta.extend({widgets:po(Pa).optional()}))),ql.route({method:"GET",tags:["Application"],path:"/applications/{application_id}",summary:"Get application by ID",description:"Returns specific application details by ID, always includes widgets"}).input(fs).output(Ta.extend({widgets:po(Pa)})),ql.route({method:"PUT",tags:["Application"],path:"/applications/{application_id}",summary:"Update application",description:"Updates application details and configuration"}).input(za.extend({application_id:Wo()})).output(Ta),ql.route({method:"DELETE",tags:["Application"],path:"/applications/{application_id}",summary:"Delete application",description:"Permanently deletes an application and all associated widgets. This action cannot be undone."}).input(fs).output(ys),ql.route({method:"POST",tags:["Widget"],path:"/widgets",summary:"Create a new widget",description:"Creates a new widget for an application and returns the created entity. Requires an application_id."}).input(Da).output(Pa),ql.route({method:"GET",tags:["Widget"],path:"/widgets",summary:"Search widgets for workspace",description:"Search widgets by type, application, marketrix_id, or marketrix_key"}).input(mo({type:os.optional(),application_id:Wo().optional(),marketrix_id:zi().optional(),marketrix_key:zi().optional(),include:po(_o(["agent"])).optional()}).extend(bs.shape)).output(vs(La)),ql.route({method:"GET",tags:["Widget"],path:"/widgets/defaults/{type}",summary:"Get default settings for widget type",description:"Returns default settings for the specified widget type"}).input(mo({type:os})).output(go([Ra,Na])),ql.route({method:"GET",tags:["Widget"],path:"/widgets/{widget_id}",summary:"Get widget by ID",description:"Returns specific widget details by widget ID including snippet code"}).input(hs).output(Pa),ql.route({method:"PUT",tags:["Widget"],path:"/widgets/{widget_id}",summary:"Update widget",description:"Updates widget settings and configuration"}).input($a.extend({widget_id:Wo()})).output(Pa),ql.route({method:"DELETE",tags:["Widget"],path:"/widgets/{widget_id}",summary:"Delete widget",description:"Permanently deletes a widget from an application. This action cannot be undone."}).input(hs).output(ys),ql.route({method:"POST",tags:["Chat"],path:"/chat",summary:"Create a new chat thread",description:"Initializes new chat thread and returns session ID"}).output(zi()),ql.route({method:"GET",tags:["Chat"],path:"/chat",summary:"Search chats by user",description:"Returns chat list and quota for the specified user"}).input(mo({user_id:Wo().optional(),chat_id:Wo().optional()})).output(wl),ql.route({method:"POST",tags:["Chat"],path:"/preview-video-chat",summary:"Create or update preview video chat record",description:"Persists guide preview chat content, history, output, and related simulation metadata"}).input(Ul).output(Fl),ql.route({method:"GET",tags:["Chat"],path:"/preview-video-chat",summary:"Search preview video chat records",description:"Returns preview chat records filtered by chat_id, agent_id, or simulation_id for current workspace"}).input(Bl).output(xs(Fl)),ql.route({method:"GET",tags:["Chat"],path:"/preview-video-chat/{id}",summary:"Get preview video chat record by ID",description:"Returns a single preview chat record for current workspace"}).input(ds).output(Fl.nullable()),ql.route({method:"POST",tags:["Connector"],path:"/connector",summary:"Create or update connector",description:"Stores provider credentials and API endpoint details for workspace connectors"}).input(Qa).output(Ka),ql.route({method:"GET",tags:["Connector"],path:"/connector",summary:"Search connectors",description:"Returns workspace connectors filtered by provider/status"}).input(Xa).output(vs(Ka)),ql.route({method:"GET",tags:["Connector"],path:"/connector/{id}",summary:"Get connector by ID",description:"Returns a single workspace connector"}).input(ds).output(Ka.nullable()),ql.route({method:"DELETE",tags:["Connector"],path:"/connector/{id}",summary:"Delete connector",description:"Permanently deletes a connector for current workspace. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"GET",tags:["Connector"],path:"/connector/{id}/github/repos",summary:"List GitHub repositories for a GitHub connector",description:"Uses the stored GitHub PAT from the connector to call GitHub /user/repos."}).input(mo({id:Wo(),per_page:Wo().int().min(1).max(100).optional(),page:Wo().int().min(1).optional()})).output(po(el)),ql.route({method:"GET",tags:["Connector"],path:"/connector/{id}/github/repos/{owner}/{repo}/actions/runs",summary:"List GitHub Actions workflow runs",description:"Lists workflow runs for a repository (pass/fail status)."}).input(mo({id:Wo(),owner:zi().min(1),repo:zi().min(1),per_page:Wo().int().min(1).max(100).optional(),page:Wo().int().min(1).optional()})).output(po(tl)),ql.route({method:"POST",tags:["Automation"],path:"/automation",summary:"Create automation",description:"Creates a DAG-based automation workflow"}).input(ll).output(al),ql.route({method:"GET",tags:["Automation"],path:"/automation",summary:"List automations",description:"Returns automations for the current workspace"}).input(dl).output(vs(al)),ql.route({method:"GET",tags:["Automation"],path:"/automation/{id}",summary:"Get automation",description:"Returns a single automation with its graph"}).input(ds).output(al.nullable()),ql.route({method:"PUT",tags:["Automation"],path:"/automation/{id}",summary:"Update automation",description:"Updates automation graph and settings"}).input(cl).output(al),ql.route({method:"DELETE",tags:["Automation"],path:"/automation/{id}",summary:"Delete automation",description:"Permanently deletes an automation and deregisters its triggers"}).input(ds).output(ys),ql.route({method:"PATCH",tags:["Automation"],path:"/automation/{id}/toggle",summary:"Toggle automation",description:"Enable or disable an automation"}).input(mo({id:Wo(),enabled:ro()})).output(al),ql.route({method:"POST",tags:["Automation"],path:"/automation/{id}/run",summary:"Trigger automation run",description:"Manually triggers an automation run"}).input(ds).output(pl.nullable()),ql.route({method:"GET",tags:["Automation"],path:"/automation/{id}/runs",summary:"List automation runs",description:"Returns execution history for an automation"}).input(mo({id:Wo()}).extend(hl.shape)).output(vs(pl)),ql.route({method:"GET",tags:["Automation"],path:"/automation/{id}/runs/{run_id}",summary:"Get automation run",description:"Returns a single run with per-node results"}).input(mo({id:Wo(),run_id:Wo()})).output(pl.nullable()),ql.route({method:"GET",tags:["Connector"],path:"/connector-capabilities",summary:"List connector capabilities",description:"Returns available triggers and callbacks per connector type"}).input(mo({})).output(po(ml)),ql.route({method:"GET",tags:["User"],path:"/user",summary:"Search and filter users by workspace",description:"Returns list of users associated with specified workspace"}).input(mo({workspace_id:Wo().optional(),status:Vo.optional()}).extend(bs.shape)).output(vs(Cs)),ql.route({method:"POST",tags:["User"],path:"/user/batch",summary:"Create multiple users in batch operation",description:"Processes bulk user creation and returns results for each user"}).input(As).output(po(Ts)),ql.route({method:"GET",tags:["User"],path:"/user/{user_id}",summary:"Get specific user details by ID",description:"Returns complete user information including profile and settings"}).input(gs).output(Cs),ql.route({method:"PUT",tags:["User"],path:"/user/{user_id}",summary:"Update user profile and settings",description:"Modifies user properties like name, email, or preferences"}).input(Es.extend({user_id:Wo()})).output(Cs),ql.route({method:"PUT",tags:["User"],path:"/user/{user_id}/image",summary:"Upload and update user profile image",description:"Handles file upload for user avatar and returns upload response"}).input(cs.extend({user_id:Wo()})).output(yl),ql.route({method:"DELETE",tags:["User"],path:"/user/{user_id}",summary:"Delete user account and all associated data",description:"Permanently deletes a user account and cleans up all related resources. This action cannot be undone."}).input(gs).output(ys),ql.route({method:"POST",tags:["User"],path:"/user/{user_id}/deactivate",summary:"Deactivate user account without deletion",description:"Deactivates user access while preserving data for potential reactivation"}).input(gs.extend({reason:zi().optional()})).output(ys),ql.route({method:"POST",tags:["Agent"],path:"/agent",summary:"Create new AI agent with configuration",description:"Creates agent with specified settings, prompts, and returns agent entity"}).input(Sa).output(va),ql.route({method:"GET",tags:["Agent"],path:"/agent",summary:"Search and filter agents by workspace or user",description:"Returns list of agents matching search parameters. Supports filtering by workspace_id, user_id, and application_id."}).input(mo({workspace_id:Wo().optional(),user_id:Wo().optional(),application_id:Wo().optional(),include:po(_o(["knowledge","simulations"])).optional()}).extend(bs.shape)).output(vs(va)),ql.route({method:"GET",tags:["Agent"],path:"/agent/{agent_id}",summary:"Get specific agent details by ID",description:"Returns complete agent information including configuration and settings"}).input(ps.extend({include:po(_o(["knowledge","simulations"])).optional()})).output(va),ql.route({method:"GET",tags:["Agent"],path:"/agent/{agent_id}/mindmap",summary:"Get agent mindmap by ID",description:"Returns the mindmap knowledge graph for the specified agent"}).input(ps).output(ba),ql.route({method:"PUT",tags:["Agent"],path:"/agent/{agent_id}",summary:"Update agent configuration and settings",description:"Updates agent details. For JSON requests, handled by oRPC. Also accepts multipart/form-data for logo file uploads (handled by raw Express route)."}).input(Ca.extend({agent_id:Wo(),force_reset_learning:Go().optional()})).output(va),ql.route({method:"DELETE",tags:["Agent"],path:"/agent/{agent_id}",summary:"Delete agent and all associated data",description:"Permanently deletes an agent and cleans up all related resources. This action cannot be undone."}).input(ps).output(ys),ql.route({method:"POST",tags:["Agent"],path:"/agent/{agent_id}/index",summary:"Index simulation document into agent knowledge base",description:"Adds a simulation document to an agent's knowledge base and refreshes the search index"}).input(Ea.extend({agent_id:Wo()})).output(Aa),ql.route({method:"POST",tags:["Agent"],path:"/agent/{agent_id}/reset-learning",summary:"Force reset agent from stuck learning state",description:"Resets an agent that is stuck in learning state, setting it to error status with a message explaining the reset"}).input(ps).output(va),ql.route({method:"POST",tags:["Activity Log"],path:"/log",summary:"Create new activity log entry",description:"Records user or system action for auditing and tracking purposes"}).input(Ya).output(Ja),ql.route({method:"GET",tags:["Activity Log"],path:"/log",summary:"Search and filter activity logs",description:"Returns list of activity logs matching search parameters (workspace, type)"}).input(mo({workspace_id:Wo().optional(),type:as.optional(),application_id:Wo().optional()}).extend(bs.shape)).output(vs(Ja)),ql.route({method:"GET",tags:["Tour"],path:"/tour",summary:"Search and filter tours by workspace",description:"Returns list of available tours for specified workspace"}).input(mo({workspace_id:Wo().optional(),application_id:Wo().optional()}).extend(bs.shape)).output(vs(Wa)),ql.route({method:"POST",tags:["Tour"],path:"/tour",summary:"Create new interactive tour",description:"Creates tour with specified steps and configuration"}).input(Wa).output(Wa),ql.route({method:"GET",tags:["URL Guide"],path:"/url-guide",summary:"Search URL guides by widget",description:"Returns list of URL guides for specified widget"}).input(hs.extend(bs.shape)).output(vs(ja)),ql.route({method:"POST",tags:["URL Guide"],path:"/url-guide",summary:"Create new URL guide",description:"Creates URL guide with pattern and message"}).input(Fa).output(ja),ql.route({method:"GET",tags:["URL Guide"],path:"/url-guide/{id}",summary:"Get URL guide by ID",description:"Returns URL guide details"}).input(ds).output(ja),ql.route({method:"PUT",tags:["URL Guide"],path:"/url-guide/{id}",summary:"Update URL guide",description:"Updates URL guide properties"}).input(Ua.extend({id:Wo()})).output(ja),ql.route({method:"DELETE",tags:["URL Guide"],path:"/url-guide/{id}",summary:"Delete URL guide",description:"Permanently deletes a URL guide. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"GET",tags:["URL Guide"],path:"/url-guide/match",summary:"Find matching URL guide for current URL",description:"Returns matching URL guide for a given URL pattern"}).input(mo({widget_id:Wo(),url:zi()})).output(ja.nullable()),ql.route({method:"GET",tags:["Simulation"],path:"/simulation",summary:"Search and filter simulations by workspace",description:"Returns list of simulations associated with specified workspace. Use application_id, agent_id, or pinned to filter."}).input(mo({workspace_id:Wo().optional(),application_id:Wo().optional(),agent_id:Wo().optional(),pinned:go([ro(),zi()]).optional().transform(e=>void 0===e?void 0:"boolean"==typeof e?e:"true"===e||"false"!==e&&void 0),source:_o(["direct","qa"]).optional(),include:po(_o(["agent","application"])).optional()}).extend(bs.shape)).output(vs(da)),ql.route({method:"POST",tags:["Simulation"],path:"/simulation/start",summary:"Start new application simulation",description:"Creates and initializes simulation with specified parameters"}).input(ua).output(da),ql.route({method:"PUT",tags:["Simulation"],path:"/simulation/{simulation_id}",summary:"Update simulation configuration and status",description:"Modifies simulation parameters and updates execution state"}).input(pa.extend({simulation_id:Wo()})).output(da),ql.route({method:"PUT",tags:["Simulation"],path:"/simulation/{simulation_id}/agents",summary:"Assign agents to a simulation",description:"Sets which agents use this simulation for their knowledge. Triggers learning on affected agents."}).input(ms.extend({agent_ids:po(Xi())})).output(da),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/progress",summary:"Get simulation progress history as chat transcript",description:"Returns all progress updates for a simulation ordered chronologically"}).input(ms).output(xs(ga)),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/live-view",summary:"Get live view URL for simulation session",description:"Returns Browserbase live view URL for embedding in iframe"}).input(ms).output(mo({session_id:zi(),live_view_url:zi(),status:zi()})),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/history",summary:"Get simulation history by ID",description:"Returns the history array for the specified simulation"}).input(ms).output(xs(aa)),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/steps",summary:"Get all simulation steps with topic and screenshot link as JSON",description:"Returns each step with step_number, topic, screenshot_url, and optional title/url for the simulation"}).input(ms).output(xs(la)),ql.route({method:"GET",tags:["Simulation"],path:"/simulation/{simulation_id}/mindmap",summary:"Get simulation mindmap by ID",description:"Returns the mindmap knowledge graph for the specified simulation"}).input(ms).output(ba),ql.route({method:"POST",tags:["Simulation"],path:"/simulation/{simulation_id}/stop",summary:"Stop running simulation",description:"Terminates a running simulation and closes its browser session."}).input(ms).output(ws),ql.route({method:"POST",tags:["Simulation"],path:"/simulation/{simulation_id}/answer",summary:"Submit answer to simulation question",description:"Submits an answer to a pending question from the simulation agent"}).input(ha.extend({simulation_id:Wo()})).output(ws),ql.route({method:"DELETE",tags:["Simulation"],path:"/simulation/{simulation_id}",summary:"Delete simulation",description:"Permanently deletes a simulation and all associated data. Only works on simulations in terminal state."}).input(ms).output(ws),ql.route({method:"POST",tags:["Session"],path:"/sessions",summary:"Create or update session",description:"Creates a new session or updates an existing one"}).input(fa).output(ma),ql.route({method:"GET",tags:["Session"],path:"/sessions/{session_id}",summary:"Get session by session ID",description:"Retrieves a session by its session_id"}).input(mo({session_id:zi().min(1)})).output(ma.nullable()),ql.route({method:"GET",tags:["Session"],path:"/sessions/chat/{chat_id}",summary:"Get sessions by chat ID",description:"Retrieves all sessions for a given chat_id"}).input(mo({chat_id:zi().min(1)})).output(xs(ma)),ql.route({method:"GET",tags:["Session"],path:"/sessions",summary:"Get all sessions",description:"Retrieves all sessions ordered by creation date, optionally filtered by application and date range"}).input(mo({application_id:Wo().optional(),start_date:zi().optional(),end_date:zi().optional()}).extend(bs.shape)).output(vs(ma)),ql.route({method:"GET",tags:["Session"],path:"/sessions/stats",summary:"Get session activity stats",description:"Returns daily aggregated session metrics for charting. Each entry is one calendar day with session count and total event count."}).input(mo({application_id:Wo(),start_date:zi().describe("YYYY-MM-DD"),end_date:zi().describe("YYYY-MM-DD")})).output($l),ql.route({method:"GET",tags:["Session"],path:"/sessions/{session_id}/events",summary:"Get session events",description:"Fetches all batches from folder, combines them in correct order, and returns events array"}).input(mo({session_id:zi().min(1)})).output(xs(mo({type:Xi(),timestamp:Xi(),data:so().describe("rrweb event payload — shape defined by rrweb library")}))),ql.route({method:"POST",tags:["Browser Session"],path:"/browser-session/create",summary:"Create browser session for application",description:"Creates a browser session and navigates to the application URL"}).input(mo({application_id:Xi(),agent_id:Xi(),url:zi().nullish()})).output(mo({session_id:zi(),live_view_url:zi()})),ql.route({method:"POST",tags:["Browser Session"],path:"/browser-session/{session_id}/stop",summary:"Stop browser session",description:"Stops all running tasks and closes the browser session. Set stop_tasks=false to skip task cleanup."}).input(mo({session_id:zi(),stop_tasks:ro().optional().default(!0)})).output(ws),ql.route({method:"GET",tags:["Knowledge"],path:"/knowledge",summary:"Search and filter knowledge base documents",description:"Returns list of knowledge documents matching search parameters. Supports filtering by workspace_id, type, and application_id."}).input(mo({workspace_id:Wo().optional(),type:Xo.optional(),application_id:Wo().optional(),include:po(_o(["agents","application"])).optional()}).extend(bs.shape)).output(vs($s)),ql.route({method:"POST",tags:["Knowledge"],path:"/knowledge",summary:"Upload new knowledge base document",description:"Upload a file, document URL, or video URL to create a knowledge entry for AI training"}).input(mo({file:Uo(File).optional(),application_id:Wo(),document_url:zi().url().optional(),document_name:zi().optional(),video_url:zi().url().optional(),video_name:zi().optional()})).output($s),ql.route({method:"GET",tags:["Knowledge"],path:"/knowledge/{id}",summary:"Get specific knowledge document by ID",description:"Returns complete knowledge document information and content"}).input(ds).output($s),ql.route({method:"DELETE",tags:["Knowledge"],path:"/knowledge/{id}",summary:"Delete knowledge document",description:"Permanently deletes a knowledge document from the database. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"POST",tags:["Knowledge"],path:"/knowledge/{id}/refresh",summary:"Refresh knowledge document",description:"Re-fetches HTML content from source URL and updates the document"}).input(ds).output($s),ql.route({method:"PUT",tags:["Knowledge"],path:"/knowledge/{knowledge_id}/agents",summary:"Assign agents to a knowledge item",description:"Sets which agents use this knowledge item. Triggers learning on affected agents."}).input(mo({knowledge_id:Wo(),agent_ids:po(Xi())})).output($s),ql.route({method:"POST",tags:["QA"],path:"/qa/document",summary:"Upload QA flow (file or text)",description:"Uploads a PDF/text file or text content for QA test generation. Also accepts multipart/form-data for file uploads (handled by raw Express route)."}).input(Bs).output(Us),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/process",summary:"Process QA flow and generate test cases",description:"Starts async processing (returns 202). Poll GET /qa/document/:id for status and processing_step until completed/failed."}).input(ds).output(mo({document:Us})),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/refine",summary:"Refine existing QA test cases",description:"Refines existing test cases with a refinement prompt via AI agent API"}).input(ds.extend({refinementPrompt:zi().min(5).max(2e3)})).output(Js),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/process/stream",summary:"Process QA flow with SSE streaming",description:"Streams processing events as Server-Sent Events. Events: response.created, response.progress, response.clear, response.completed, error."}).input(ds).output(Yl(mo({event:zi().describe("SSE event type: response.created | response.progress | response.clear | response.completed | error"),data:so().describe("Event payload object — shape varies by event type")}))),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/refine/stream",summary:"Refine QA flow test cases with SSE streaming",description:"Streams refinement events as Server-Sent Events. Requires a refinement prompt (min 5 chars)."}).input(ds.extend({refinementPrompt:zi().min(5)})).output(Yl(mo({event:zi().describe("SSE event type: response.created | response.progress | response.clear | response.completed | error"),data:so().describe("Event payload object — shape varies by event type")}))),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}",summary:"Get QA flow by ID",description:"Retrieves a QA flow by its ID"}).input(ds).output(Us),ql.route({method:"GET",tags:["QA"],path:"/qa/document",summary:"List QA flows",description:"Returns all QA flows with aggregated metrics (run_count, pass_rate, total_failed) and the last run summary. Supports filtering by application_id."}).input(mo({application_id:Wo().optional()}).extend(bs.shape)).output(vs(Us.extend({run_count:Xi(),display_title:zi(),total_failed:Xi(),pass_rate:Xi().nullable(),last_run:mo({id:Xi(),status:zi(),total_tests:Xi(),passed_tests:Xi(),failed_tests:Xi(),created_at:Ho().nullable()}).nullable()})).extend({metrics:mo({total_flows:Xi(),total_runs:Xi(),avg_pass_rate:Xi().nullable(),total_failed:Xi(),total_passed:Xi()})})),ql.route({method:"DELETE",tags:["QA"],path:"/qa/document/{id}",summary:"Delete QA flow",description:"Permanently deletes a QA flow and all its runs and test cases. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"PUT",tags:["QA"],path:"/qa/document/{id}",summary:"Update QA flow status",description:"Updates the status of a QA flow"}).input(ds.extend({status:es})).output(Us),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}/runs",summary:"List runs for a QA flow",description:"Returns all runs for a document with total/passed/failed counts"}).input(ds.extend(bs.shape)).output(vs(Ws.extend({total_tests:Xi(),passed:Xi(),failed:Xi()}))),ql.route({method:"GET",tags:["QA"],path:"/qa/run/{id}",summary:"Get a QA run by ID",description:"Returns run details with test cases"}).input(ds).output(Ws.extend({test_cases:po(qs)})),ql.route({method:"DELETE",tags:["QA"],path:"/qa/run/{id}",summary:"Delete a QA run",description:"Permanently deletes a QA run and all its test case results. This action cannot be undone."}).input(ds).output(ys),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/run",summary:"Create and start a new QA run",description:"Creates a new run and starts execution. Returns 202; poll test-cases for execution status."}).input(ds).output(mo({run:Ws,simulations:po(da)})),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}/test-cases",summary:"Get test cases for a QA flow",description:"Retrieves test cases; optional run_id scopes to that run"}).input(ds.extend({run_id:Wo().optional()})).output(xs(qs)),ql.route({method:"PUT",tags:["QA"],path:"/qa/test-case/{id}",summary:"Update test case definition fields",description:"Updates a test case definition (title, objective, steps, etc.)"}).input(ds.extend({test_title:zi().optional(),test_objective:zi().optional(),test_steps:po(zi()).optional(),expected_outcome:zi().optional(),priority:_o(["Low","Medium","High"]).optional(),is_active:ro().optional()})).output(qs),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/execute",summary:"Create a run and execute all pending tests for a QA flow as simulations",description:"Creates a new QA run, then starts a simulation for every active test case. Returns the run and simulation entities."}).input(ds).output(mo({run:Ws,simulations:po(da)})),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/execute",summary:"Execute a single test case as a simulation",description:"Starts a simulation for the specified test case and returns the simulation entity."}).input(ds).output(mo({simulation:da})),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/simulation",summary:"Get the simulation linked to a test case",description:"Returns the simulation entity associated with the test case, or null if no simulation exists."}).input(ds).output(mo({simulation:da.nullable()})),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/versions",summary:"Get version history for a test case",description:"Returns all version entries from the test case version_history JSON"}).input(ds).output(xs(Zs)),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}",summary:"Get specific test case version",description:"Returns a specific version entry from the test case version_history JSON"}).input(ds.extend({version:Wo()})).output(Zs),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}/rollback",summary:"Rollback to specific version",description:"Restores test case to a previous version and appends new version entry"}).input(ds.extend({version:Wo()})).output(Zs),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/versions/compare",summary:"Compare two versions",description:"Returns differences between two test case versions"}).input(ds.extend({version1:Wo(),version2:Wo()})).output(mo({version1:Zs,version2:Zs,diff:po(mo({field:zi(),oldValue:Ks,newValue:Ks}))})),ql.route({method:"DELETE",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}",summary:"Delete a specific version",description:"Removes a version from history and reverts test case to previous version if it was the latest"}).input(ds.extend({version:Wo()})).output(ys.extend({current_version:Xi()})),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/versions/{version}/accept",summary:"Accept a specific version",description:"Marks a version as accepted by the user"}).input(ds.extend({version:Wo()})).output(ys),ql.route({method:"GET",tags:["QA"],path:"/qa/test-case/{id}/healing-attempts",summary:"Get healing attempts for a test case",description:"Returns all healing attempt entries from the test case healing_attempts JSON"}).input(ds).output(xs(Vs)),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/healing-attempts/{attemptIndex}/approve",summary:"Approve a healing attempt",description:"Applies the repair from a validated healing attempt by array index"}).input(ds.extend({attemptIndex:Wo()})).output(ys),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/healing-attempts/{attemptIndex}/reject",summary:"Reject a healing attempt",description:"Marks a healing attempt as rejected by array index"}).input(ds.extend({attemptIndex:Wo()})).output(ys),ql.route({method:"POST",tags:["QA"],path:"/qa/test-case/{id}/heal",summary:"Trigger self-healing for a failed test case",description:"Initiates the self-healing workflow for a test case"}).input(ds.extend({simulation_id:Xi(),config:mo({enabled:ro().optional(),autoApply:ro().optional(),minConfidenceThreshold:Xi().min(0).max(1).optional(),maxHealingAttempts:Xi().int().min(1).max(5).optional()}).optional()})).output(mo({healed:ro(),attemptIndex:Xi().nullable(),analysis:Xs.nullable(),confidence:Xi().nullable()})),ql.route({method:"POST",tags:["QA"],path:"/qa/document/{id}/run-cross-browser",summary:"Execute cross-browser tests",description:"Runs tests across multiple browsers (chromium, firefox, webkit)"}).input(Fs.extend({id:Wo()})).output(mo({runs:po(mo({browserType:js,runId:Xi(),status:_o(["completed","failed","skipped"]),passedTests:Xi(),failedTests:Xi(),totalTests:Xi()})),summary:mo({totalRuns:Xi(),completedRuns:Xi(),failedRuns:Xi(),overallPassed:Xi(),overallFailed:Xi()})})),ql.route({method:"GET",tags:["QA"],path:"/qa/document/{id}/cross-browser-comparison",summary:"Get cross-browser comparison",description:"Returns test cases comparison across different browsers"}).input(ds).output(mo({byTest:xo(zi(),xo(zi(),mo({status:zi(),runId:Xi()}))),byBrowser:xo(zi(),mo({passed:Xi(),failed:Xi(),total:Xi()}))})),ql.route({method:"PUT",tags:["QA"],path:"/qa/document/{id}/browser-config",summary:"Update browser configuration",description:"Updates the default browser configuration for a QA flow"}).input(Fs.extend({id:Wo()})).output(ys),ql.route({method:"POST",tags:["Internal"],path:"/migrate/prepare",summary:"Prepare database migration",description:"Validates migration requirements and prepares system for migration"}).input(fl).output(mo({message:zi(),status:zi(),data:fl})),ql.route({method:"POST",tags:["Internal"],path:"/migrate/run",summary:"Execute database migration",description:"Runs migration scripts and updates database schema"}).input(gl).output(mo({message:zi(),status:zi(),data:gl})),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/trial",summary:"Create a trial subscription",description:"Creates a trial subscription for the authenticated workspace. The trial period is 30 days by default."}).input(xl).output(El),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/checkout",summary:"Create a checkout session for subscription purchase",description:"Creates a Stripe checkout session for purchasing a subscription. Returns a session URL for redirect."}).input(bl).output(Cl),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/portal",summary:"Create a customer portal session",description:"Creates a Stripe billing portal session for managing subscription, payment methods, and invoices."}).input(vl).output(Il),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/downgrade",summary:"Confirm and process a subscription downgrade",description:"Processes a confirmed subscription downgrade to a lower tier plan. No payment required."}).input(kl).output(_l),ql.route({method:"POST",tags:["Stripe"],path:"/stripe/cancel",summary:"Cancel subscription at period end",description:"Cancels the subscription at the end of the current billing period."}).input(mo({subscriptionId:zi().min(1)})).output(mo({subscriptionId:zi(),cancelAtPeriodEnd:ro()})),ql.route({method:"GET",tags:["Stripe"],path:"/stripe/catalog",summary:"Get public Stripe catalog (pricing, plans, config)",description:"Returns pricing from Stripe, plan catalog metadata, and Stripe frontend configuration in a single call."}).output(mo({pricing:Ol,plans:Nl,config:Pl})),ql.route({method:"GET",tags:["Stripe"],path:"/stripe/subscription",summary:"Get current subscription plan and usage",description:"Returns current subscription plan information and actual usage statistics for the authenticated workspace."}).output(mo({plan:Sl,usage:Tl})),ql.route({method:"GET",tags:["Widget"],path:"/widget/stream",summary:"SSE stream for real-time widget events",description:"Typed event stream delivering tool calls, task status updates, chat responses, and registration confirmation."}).input(mo({chat_id:zi(),tab_id:zi().optional(),marketrix_id:zi().optional(),marketrix_key:zi().optional(),agent_id:Wo().optional(),application_id:Wo().optional()})).output(Yl(Ga)),ql.route({method:"POST",tags:["Widget"],path:"/widget/message",summary:"Send a typed command from widget to server",description:"Receives chat commands, tool responses, and keepalive pings from the widget."}).input(mo({chat_id:zi(),command:Ha})).output(mo({ok:ro()})),ql.route({method:"GET",tags:["App"],path:"/app/events",summary:"SSE stream for real-time app dashboard events",description:"Typed event stream delivering simulation, agent, QA, and user updates filtered by scope and application."}).input(mo({scopes:po(Za).min(1),application_id:Wo().optional()})).output(Yl(Va)),ql.route({method:"POST",tags:["Internal"],path:"/workos/webhook",summary:"WorkOS webhook receiver",description:"Receives webhook events from WorkOS (user management, SSO). Verified via workos-signature header. Not for external use."}).input(mo({event:zi(),data:xo(zi(),so())})).output(mo({received:ro()})),ql.route({method:"POST",tags:["Internal"],path:"/stripe/webhook",summary:"Stripe webhook receiver",description:"Receives webhook events from Stripe (payments, subscriptions). Verified via stripe-signature header. Not for external use."}).input(mo({id:zi(),object:zi(),type:zi(),data:xo(zi(),so())}).passthrough().describe("Stripe event payload")).output(mo({received:ro()}));var Kl,Ql=null,Xl="";function ec(e){return ye(new $e({url:e,headers:()=>{const e={};return Ql&&(e.Authorization=`Bearer ${Ql}`),e}}))}Kl=ec("");var tc=e=>{if(!e?.trim())throw new Error("API URL is required for SDK configuration");e!==Xl&&(Xl=e,Kl=ec(e))},nc={setAuthToken:e=>{Ql=e},clearAuthToken:()=>{Ql=null},getAuthToken:()=>Ql,configure:tc},rc=new Proxy({},{get:(e,t)=>t in nc?nc[t]:Kl[t]}),ic=e=>e?.mtxApiHost?e.mtxApiHost:"";function oc(e,t="Unknown error"){return e instanceof Error?e.message:"string"==typeof e?e:t}function sc(e,t="Operation",n){const r=oc(e);return function(e){const t=e instanceof Error?e.message:String(e);return t.includes("Failed to fetch")||t.includes("ERR_CONNECTION_REFUSED")||t.includes("NetworkError")||t.includes("Network request failed")}(e)?{isValid:!1,error:`Cannot connect to API server. Please ensure the API server is running at ${ic(n)||"configured API server"}. Error: ${r}`}:{isValid:!1,error:`${t} failed: ${r}`}}var ac="undefined"==typeof window||"localhost"!==window.location.hostname&&"127.0.0.1"!==window.location.hostname&&!window.location.hostname.includes("localhost")?"error":"debug",lc={debug:0,info:1,warn:2,error:3};function cc(e){return lc[e]>=lc[ac]}var dc=(e,t,...n)=>{cc("debug")},uc=(e,t,...n)=>{cc("info")},pc=(e,t,...n)=>{cc("warn")},hc=(e,t,...n)=>{cc("error")};function mc(e){return{debug:(t,...n)=>dc(e,t,...n),info:(t,...n)=>uc(e,t,...n),warn:(t,...n)=>pc(e,t,...n),error:(t,...n)=>hc(e,t,...n)}}mc("ErrorUtils");var fc=[{id:"navigate",name:"Navigate",description:"Navigate to a URL",displayAction:"Navigating",category:"navigation",actionType:"navigate"},{id:"search",name:"Search",description:"Search the web using a search engine",displayAction:"Searching",category:"navigation",actionType:"search"},{id:"click_element",name:"Click Element",description:"Click on an element by index or coordinates",displayAction:"Clicking element",category:"interaction",actionType:"click_element"},{id:"type_text",name:"Type Text",description:"Type text into an input field",displayAction:"Typing text",category:"interaction",actionType:"type_text"},{id:"scroll",name:"Scroll",description:"Scroll the page up or down",displayAction:"Scrolling",category:"interaction",actionType:"scroll"},{id:"scroll_to_text",name:"Scroll to Text",description:"Scroll until text is visible",displayAction:"Scrolling to text",category:"interaction",actionType:"scroll_to_text"},{id:"send_keys",name:"Send Keys",description:"Send keyboard keys or shortcuts",displayAction:"Pressing key",category:"interaction",actionType:"send_keys"},{id:"extract",name:"Extract",description:"Extract content from the page",displayAction:"Extracting content",category:"extraction",actionType:"extract"},{id:"get_dropdown_options",name:"Get Dropdown Options",description:"Get available options from a dropdown",displayAction:"Reading dropdown options",category:"extraction",actionType:"get_dropdown_options"},{id:"select_dropdown_option",name:"Select Dropdown Option",description:"Select an option from a dropdown",displayAction:"Selecting option",category:"interaction",actionType:"select_dropdown_option"},{id:"upload_file",name:"Upload File",description:"Upload a file to an input field",displayAction:"Uploading file",category:"interaction",actionType:"upload_file"},{id:"go_back",name:"Go Back",description:"Browser back button",displayAction:"Going back",category:"navigation",actionType:"go_back"},{id:"wait",name:"Wait",description:"Wait for a specified duration",displayAction:"Waiting",category:"utility",actionType:"wait"},{id:"switch_tab",name:"Switch Tab",description:"Switch to a different browser tab",displayAction:"Switching tab",category:"utility",actionType:"switch_tab"},{id:"close_tab",name:"Close Tab",description:"Close the current browser tab",displayAction:"Closing tab",category:"utility",actionType:"close_tab"},{id:"done",name:"Done",description:"Mark task as complete",displayAction:"Done",category:"utility",actionType:"done"},{id:"get_html",name:"Get HTML",description:"Get full page HTML with data-id attributes",displayAction:"Viewed your screen",category:"extraction",actionType:"get_html"},{id:"get_interactable_elements",name:"Get Interactable Elements",description:"Get list of interactable elements",displayAction:"Scanning elements",category:"extraction",actionType:"get_interactable_elements"},{id:"get_screenshot",name:"Get Screenshot",description:"Capture a screenshot of the page",displayAction:"Taking screenshot",category:"extraction",actionType:"get_screenshot"}];function gc(e){return e.includes("__THINKING__")}function yc(e){return gc(e)?e:`${e}\n\n__THINKING__`}function wc(e,t,n,r,i,o){if("agent"!==e.sender||e.isSystemMessage||e.isScreenAccessRequest)return!1;if(o&&t&&("show"===n||"do"===n))if(e.isPlaceholder){if(void 0!==e.mode&&e.mode!==n)return!1}else if(e.mode!==n)return!1;if(i){const t=e.content.trim().length>0,n=e.parts&&e.parts.length>0;if(!t&&!n)return!1}return!0}function bc(e){const{messages:t,isTaskRunning:n,currentMode:r,preferPlaceholder:i,requireContent:o}=e;let s=-1;if(n&&("show"===r||"do"===r)){const e=!0;for(let i=t.length-1;i>=0;i--){const a=t[i],l=wc(a,n,r,0,o,e),c=a.isPlaceholder,d=!o||a.content.trim().length>0||a.parts&&a.parts.length>0;if(l&&c&&d){s=i;break}}if(s<0&&!o)for(let i=t.length-1;i>=0;i--){const a=t[i],l=wc(a,n,r,0,o,e),c=a.isPlaceholder;if(l&&c){s=i;break}}if(s<0)for(let i=t.length-1;i>=0;i--){const a=t[i],l=wc(a,n,r,0,o,e),c=a.isPlaceholder;if(l&&!c){s=i;break}}}if(s<0){for(let e=t.length-1;e>=0;e--){const n=t[e],r="agent"===n.sender,i=n.isPlaceholder,a=!n.isSystemMessage,l=!n.isScreenAccessRequest,c=!o||n.content.trim().length>0||n.parts&&n.parts.length>0;if(r&&i&&a&&l&&c){s=e;break}}if(s<0&&!o)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&n.isPlaceholder&&!n.isSystemMessage&&!n.isScreenAccessRequest){s=e;break}}if(s<0&&(s=function(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest&&!n.isPlaceholder)return t}return-1}(t)),s<0)for(let e=t.length-1;e>=0;e--){const n=t[e];if("agent"===n.sender&&!n.isSystemMessage&&!n.isScreenAccessRequest){s=e;break}}}return s>=0?{index:s,message:t[s]}:null}function vc(e){const t={...e};if(!t.parts){t.parts=[];const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts.push({type:"text",content:e})}return t}var xc=new Set(["click_element","type_text","send_keys","select_dropdown_option","upload_file","scroll"]);function kc(e){return e?e.replace(/\(Cancelled by cleanup\)/gi,"").replace(/\(cancelled by cleanup\)/gi,"").replace(/Cancelled by cleanup/gi,"").replace(/\s+/g," ").trim():e}function _c(e,t,n,r=!1){const i=vc(e);if(!t||"show"!==n&&"do"!==n)return gc(i.content)?{...i,content:i.content.replace(/\n\n__THINKING__$/,"").replace(/__THINKING__/g,""),placeholderState:void 0}:i;const o=r?"waiting-for-user":"thinking";return gc(i.content)?i.placeholderState!==o?{...i,placeholderState:o}:i:{...i,content:yc(i.content),placeholderState:o}}var Sc=Object.fromEntries(fc.map(e=>[e.id,e.displayAction]));var Cc="marketrix_chat_context",Ic={chat_id:null,messages:[],isTaskRunning:!1,activeTaskId:null,taskProgress:[],currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1,config:null,timestamp:Date.now()},Ec=class e{static instance;context=null;constructor(){this.loadContext()}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadContext(){if("undefined"==typeof window)return this.context={...Ic},this.context;try{const e=localStorage.getItem(Cc);if(e){const t=JSON.parse(e);return Date.now()-t.timestamp>6048e5?(this.context={...Ic},this.saveContext(),this.context):(this.context=t,this.context)}}catch(e){}return this.context={...Ic},this.context}saveContext(){if("undefined"!=typeof window&&this.context)try{this.context.timestamp=Date.now(),localStorage.setItem(Cc,JSON.stringify(this.context))}catch(e){}}getContext(){return this.context?this.context:this.loadContext()}updateContext(e){this.context||this.loadContext(),this.context={...this.context,...e},this.saveContext()}isValidChatId(e){return"string"==typeof e&&""!==e.trim()}getChatId(){if("undefined"!=typeof window&&this.isValidChatId(window.name)){const e=window.name;return e!==this.getContext().chat_id&&this.updateContext({chat_id:e}),e}return this.getContext().chat_id}setChatId(e){this.updateContext({chat_id:e}),"undefined"!=typeof window&&e&&(window.name=e,window.dispatchEvent(new CustomEvent("marketrix:chatid",{detail:{chatId:e}})))}getMessages(){return this.getContext().messages}setMessages(e){this.updateContext({messages:e})}getChatState(){const e=this.getContext();return{isTaskRunning:e.isTaskRunning,activeTaskId:e.activeTaskId,taskProgress:e.taskProgress,currentMode:e.currentMode,isOpen:e.isOpen,isMinimized:e.isMinimized,isLoading:e.isLoading}}setChatState(e){this.updateContext(e)}getConfig(){return this.getContext().config}setConfig(e){this.updateContext({config:e})}clear(){this.context={...Ic},"undefined"!=typeof window&&localStorage.removeItem(Cc)}hasValidContext(){const e=this.getContext();return null!==e.chat_id&&e.chat_id.length>0}}.getInstance(),Ac=class e{static instance;messages=[];chatId=null;isTaskRunning=!1;activeTaskId=null;taskProgress=[];currentMode="tell";isOpen=!1;isMinimized=!1;isLoading=!1;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}initialize(e){this.chatId=e,this.restoreState()}createInitialContext(e){try{if(Ec.hasValidContext())return;Ec.updateContext({chat_id:e,messages:[],isTaskRunning:!1,activeTaskId:null,taskProgress:[],currentMode:"tell",isOpen:!1,isMinimized:!1,isLoading:!1})}catch(t){}}getMessages(){return this.messages}getIsLoading(){return this.isLoading}getIsTaskRunning(){return this.isTaskRunning}getActiveTaskId(){return this.activeTaskId}getTaskProgress(){return this.taskProgress}getCurrentMode(){return this.currentMode}getIsOpen(){return this.isOpen}getIsMinimized(){return this.isMinimized}addMessage(e){this.messages=[...this.messages,e],this.persistState()}updateMessage(e,t){this.messages=this.messages.map(n=>n.id===e?{...n,...t}:n),this.persistState()}removeMessage(e){this.messages=this.messages.filter(t=>t.id!==e),this.persistState()}setMessages(e){this.messages=e,this.persistState()}clearMessages(){this.messages=[],this.persistState()}setTaskState(e,t,n){this.isTaskRunning=e,this.activeTaskId=t,this.taskProgress=n,this.persistState()}setMode(e){this.currentMode=e,this.persistState()}setWidgetState(e,t){this.isOpen=e,this.isMinimized=t,this.persistState()}setIsLoading(e){this.isLoading=e,this.persistState()}restoreState(){try{const e=Ec.getContext();if(!e.chat_id)return;this.chatId&&(e.chat_id,this.chatId),this.messages=e.messages.map(e=>{if(e.id.startsWith("screenshare-"))return{...e,content:"Screenshare ended",videoStream:void 0,isSystemMessage:!0,timestamp:new Date(e.timestamp),parts:[{type:"text",content:"Screenshare ended"}]};const t={...e,timestamp:new Date(e.timestamp),videoStream:void 0,placeholderState:e.placeholderState,taskStatus:e.taskStatus,parts:e.parts||[]};if(0===t.parts?.length&&t.content){const e=t.content.replace(/\n\n__THINKING__$/,"").trim();e&&t.parts&&t.parts.push({type:"text",content:e})}return t}),this.isTaskRunning=e.isTaskRunning,this.activeTaskId=e.activeTaskId,this.taskProgress=e.taskProgress,this.currentMode=e.currentMode,this.isOpen=e.isOpen,this.isMinimized=e.isMinimized,this.isLoading=e.isLoading??!1}catch(e){}}persistState(){if(this.chatId)try{const e=this.messages.filter(e=>!e.isPlaceholder||("thinking"===e.placeholderState||"waiting-for-user"===e.placeholderState||(e.parts||[]).length>0)).filter(e=>!(e.isSystemMessage&&"Chat context changed"===e.content)).map(e=>{return{id:e.id,content:(t=e.content,t.replace(/__THINKING__/g,"")),sender:e.sender,timestamp:e.timestamp.toISOString(),mode:e.mode,isScreenAccessRequest:e.isScreenAccessRequest,screenShareStatus:e.screenShareStatus,isSystemMessage:e.isSystemMessage,isPlaceholder:e.isPlaceholder,placeholderState:e.placeholderState,taskStatus:e.taskStatus,parts:e.parts};var t});Ec.updateContext({chat_id:this.chatId,messages:e,isTaskRunning:this.isTaskRunning,activeTaskId:this.activeTaskId,taskProgress:this.taskProgress,currentMode:this.currentMode,isOpen:this.isOpen,isMinimized:this.isMinimized,isLoading:this.isLoading})}catch(e){}}}.getInstance();function Tc(e,t,n="user-message"){const r=[],i=e.trim();return i&&r.push({type:"text",content:i}),{id:`${n}-${Date.now()}`,content:i,sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,parts:r}}function Mc(e,t,n,r="agent-message"){const i=[],o=e.trim();return o&&i.push({type:"text",content:o}),{id:n||`${r}-${Date.now()}`,content:e,sender:"agent",timestamp:/* @__PURE__ */new Date,mode:t,parts:i}}function zc(e,t,n="agent",r="system-message"){const i=[];return e&&i.push({type:"text",content:e}),{id:`${r}-${Date.now()}`,content:e,sender:n,timestamp:/* @__PURE__ */new Date,mode:t,isSystemMessage:!0,parts:i}}function Oc(e="show"){const t="Started screenshare";return{id:`started-screenshare-${Date.now()}`,content:t,sender:"user",timestamp:/* @__PURE__ */new Date,mode:e,isSystemMessage:!0,parts:[{type:"text",content:t}]}}function Rc(e,t="show"){return{id:`screenshare-${Date.now()}`,content:"",sender:"user",timestamp:/* @__PURE__ */new Date,mode:t,videoStream:e,parts:[]}}var Nc=mc("ChatIdManager"),Pc=class e{static instance=null;chatId=null;initializationPromise=null;constructor(){"undefined"!=typeof window&&"undefined"!=typeof document&&(this.chatId=this.getStoredChatId(),this.chatId&&Nc.debug("Loaded existing chat ID from storage:",this.chatId))}static getInstance(){return"undefined"==typeof window||"undefined"==typeof document?(e.instance||(e.instance=Object.create(e.prototype),e.instance.chatId=null,e.instance.initializationPromise=null),e.instance):(e.instance||(e.instance=new e),e.instance)}getChatId(){return this.chatId}async getOrCreateChatId(){if(this.chatId)return Nc.debug("Returning existing chat ID:",this.chatId),this.chatId;if(this.initializationPromise)return Nc.debug("Chat ID initialization in progress, waiting..."),this.initializationPromise;const e=this.getStoredChatId();if(e)return this.chatId=e,Nc.debug("Found chat ID in storage:",this.chatId),this.chatId;this.initializationPromise=this.createChatId();try{return await this.initializationPromise}finally{this.initializationPromise=null}}async createChatId(){try{Nc.info("Creating new chat ID...");const e=await rc.chatCreate(void 0);if(!e)throw new Error("API returned empty chat ID");return this.chatId=e,this.storeChatId(e),Nc.info("Created and stored new chat ID:",this.chatId),Ac.createInitialContext(e),e}catch(e){throw Nc.error("Failed to create chat ID:",e),this.initializationPromise=null,e}}clearChatId(){this.chatId=null,this.initializationPromise=null,Nc.debug("Cleared chat ID")}static resetInstance(){e.instance=null}getStoredChatId(){return Ec.getChatId()}storeChatId(e){Ec.setChatId(e)}}.getInstance(),Lc=class e{static instance=null;abortController=null;chatId=null;status="disconnected";callbacks=/* @__PURE__ */new Set;isIntentionallyDisconnected=!1;reconnectAttempts=0;maxReconnectAttempts=10;reconnectDelay=1e3;maxReconnectDelay=3e4;reconnectTimer=null;config;connectionId=0;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}addCallbacks(e){this.callbacks.add(e)}removeCallbacks(e){this.callbacks.delete(e)}getStatus(){return this.status}isConnected(){return"registered"===this.status}async connect(e,t){if(this.isIntentionallyDisconnected&&(this.isIntentionallyDisconnected=!1),this.isConnected()&&this.chatId===e)return;this.abortController&&(this.abortController.abort(),this.abortController=null),this.chatId=e,t&&(this.config=t),this.setStatus("connecting");const n=++this.connectionId;this.abortController=new AbortController;const r=this.abortController.signal;try{const t={chat_id:e};this.config?.mtxId&&this.config?.mtxKey?(t.marketrix_id=this.config.mtxId,t.marketrix_key=this.config.mtxKey):this.config?.mtxAgent&&this.config?.mtxApp&&(t.agent_id=this.config.mtxAgent,t.application_id=this.config.mtxApp);const i=await rc.widgetStream(t,{signal:r});this.setStatus("connected"),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.consumeEvents(i,n)}catch(i){r.aborted||(this.setStatus("error"),this.notifyError(/* @__PURE__ */new Error("Stream connection failed")),this.scheduleReconnect())}}async consumeEvents(e,t){let n=!1;try{for await(const r of e){if(this.connectionId!==t){n=!0;break}this.handleMessage(r)}}catch(r){this.connectionId!==t?n=!0:this.isIntentionallyDisconnected||this.setStatus("error")}finally{n||this.connectionId!==t||this.isIntentionallyDisconnected||(this.setStatus("disconnected"),this.scheduleReconnect())}}disconnect(){this.isIntentionallyDisconnected=!0,this.clearReconnectTimer(),this.abortController&&(this.abortController.abort(),this.abortController=null),this.setStatus("disconnected"),this.chatId=null}send(e){return this.chatId?rc.widgetMessage({chat_id:this.chatId,command:e}).then(()=>{}).catch(e=>{throw this.notifyError(/* @__PURE__ */new Error(`Failed to send message: ${String(e)}`)),e}):Promise.reject(/* @__PURE__ */new Error("No active chat"))}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.forEach(t=>t.onStatusChange?.(e)))}notifyError(e){this.callbacks.forEach(t=>t.onError?.(e))}handleMessage(e){this.isIntentionallyDisconnected||"heartbeat"!==e.type&&("registered"===e.type&&e.chat_id===this.chatId&&(this.setStatus("registered"),this.reconnectAttempts=0,this.reconnectDelay=1e3,this.callbacks.forEach(t=>t.onRegistered?.(e.application_id))),"chat/error"===e.type&&"auth"===e.request_id&&(this.isIntentionallyDisconnected=!0),this.callbacks.forEach(t=>t.onMessage?.(e)))}scheduleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts)return void this.notifyError(/* @__PURE__ */new Error("Max reconnect attempts reached"));this.clearReconnectTimer(),this.reconnectAttempts++;const e=Math.min(this.reconnectDelay*Math.pow(2,this.reconnectAttempts-1),this.maxReconnectDelay);this.reconnectTimer=setTimeout(()=>{!this.isIntentionallyDisconnected&&this.chatId&&this.connect(this.chatId,this.config).catch(console.error)},e)}clearReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}},Dc=class{config;constructor(e){this.config=e}getChatId(){return Pc.getChatId()}async getOrCreateChatId(){return Pc.getOrCreateChatId()}getUserId(){if(this.config.userId&&"number"==typeof this.config.userId)return this.config.userId;try{const e=localStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}try{const e=sessionStorage.getItem("marketrix_user_id");if(e){const t=Number(e);if(!isNaN(t))return t}}catch(e){}return null}async logWidgetQuestion(e,t){try{const n=this.getUserId(),r={question:e,mode:t,chat_id:this.getChatId(),timestamp:/* @__PURE__ */(new Date).toISOString()};null!==n&&(r.user_id=n),this.config.mtxApp&&(r.application_id=this.config.mtxApp),this.config.mtxId&&this.config.mtxKey&&(r.marketrix_id=this.config.mtxId,r.marketrix_key=this.config.mtxKey),rc.activityLogCreate({type:"widget_question",metadata:r}).catch(e=>{})}catch(n){}}async sendMessage(e){if(!(await Pc.getOrCreateChatId()))throw new Error("Failed to initialize chat session");const t=e.mode||"tell";if(e.message&&await this.logWidgetQuestion(e.message,t),!(this.config.mtxId&&this.config.mtxKey||this.config.mtxApp&&this.config.mtxAgent))throw new Error("Either mtxId + mtxKey or both mtxApp + mtxAgent are required");const n=e.requestId||`req_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r={type:`chat/${t}`,request_id:n,content:e.message||""};return Lc.getInstance().send(r),{messageId:n,response:"",mode:t,timestamp:/* @__PURE__ */new Date}}async checkAgentAvailability(){try{return null!==Pc.getChatId()}catch(e){return!1}}async getAgentInfo(){return{available:!0,status:"online"}}async stopTask(e){return Lc.getInstance().send({type:"chat/stop",...e&&{task_id:e}}),{status:"stopping",message:"Stop command sent"}}updateConfig(e){this.config={...this.config,...e}}},$c=class e{static instance;config=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}loadConfig(){const e=Ec.getConfig();return e?(this.config=e,e):(this.config={},this.config)}saveConfig(e){Ec.setConfig(e),this.config=e}updateConfig(e){this.config||(this.config={}),this.config={...this.config,...e},this.saveConfig(this.config)}getConfig(){return this.config}shouldShowWidget(){return!!this.config&&(this.config.widget_enabled??!1)}}.getInstance();function jc(e,t={}){return{...t,...e}}function Fc(e,t){return"object"==typeof e&&null!==e&&t in e}function Uc(e){return null!==e&&e instanceof HTMLElement}function Bc(e){return null!==e&&e instanceof HTMLScriptElement}function Wc(e){if(!(e&&e instanceof Element))return!1;try{const n=e.tagName.toLowerCase(),r="button"===n;if(!(r||"input"===n||"textarea"===n||"select"===n||"a"===n&&e.hasAttribute("href")||"button"===e.getAttribute("role")||"link"===e.getAttribute("role")||"textbox"===e.getAttribute("role")||"checkbox"===e.getAttribute("role")||"radio"===e.getAttribute("role")||"switch"===e.getAttribute("role")||"tab"===e.getAttribute("role")||"menuitem"===e.getAttribute("role")||"true"===e.getAttribute("contenteditable")||e.hasAttribute("onclick")||e.hasAttribute("tabindex")&&parseInt(e.getAttribute("tabindex")||"-1",10)>=0))return!1;const i=(t,n)=>{if(r){e.tagName,e.id,e.className}};if(!0===e.disabled)return i("disabled","button is disabled"),!1;if("true"===e.getAttribute("aria-disabled"))return i("aria-disabled","aria-disabled is true"),!1;try{let t=e;for(;t;){if(t instanceof HTMLElement&&t.inert)return i("inert","ancestor is inert"),!1;const e=t instanceof Element?t.getRootNode():null;t=t instanceof Element?t.parentElement||(e instanceof ShadowRoot?e.host:null):null}}catch(t){}const o=e.hasAttribute("onclick");if(r&&o)return!0;let s,a;try{s=window.getComputedStyle(e)}catch(t){return i("computed-style","failed to get computed style"),!1}if("none"===s.display)return i("display","display is none"),!1;if("none"===s.pointerEvents)return i("pointer-events","pointer-events is none"),!1;try{a=e.getBoundingClientRect()}catch(t){return i("bounding-rect","failed to get bounding rect"),!1}if(a.width<=0||a.height<=0)return i("dimensions",`width=${a.width}, height=${a.height}`),!1;try{let t=e;for(;t&&t!==document.body;){const e=t.getRootNode(),n=t.parentElement||(e instanceof ShadowRoot?e.host:null);if(!n)break;let o,s;try{o=window.getComputedStyle(n),s=n.getBoundingClientRect()}catch{t=n;continue}if("hidden"===o.overflow||"clip"===o.overflow){const e=a.right<s.left||a.left>s.right||a.bottom<s.top||a.top>s.bottom;if(r){if(e)return i("overflow-clipping","completely outside parent bounds"),!1}else if(e)return!1}t=n}}catch(t){}try{let t=e.getRootNode();for(;t instanceof ShadowRoot;){const e=t.host;let n;try{n=e.getBoundingClientRect()}catch{break}if(n.width<=0||n.height<=0)return!1;t=e.getRootNode()}}catch(t){}return!0}catch(t){return!1}}var Gc=class e{static instance;elementMap=/* @__PURE__ */new Map;elementToSequence=/* @__PURE__ */new WeakMap;selectorMap=/* @__PURE__ */new Map;fingerprintMap=/* @__PURE__ */new Map;isIndexed=!1;indexingInProgress=!1;indexVersion=0;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}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,i=Array.from(t.children).filter(e=>e.tagName===r);if(i.length>1){e+=`:nth-of-type(${i.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}generateFingerprint(e,t){return{tagName:e.tagName,id:e.id||null,textContent:((e,t=100)=>{if(!e)return null;const n=e.trim().replace(/\s+/g," ");return n.length>t?n.slice(0,t):n})(e.textContent),type:e.getAttribute("type"),role:e.getAttribute("role"),ariaLabel:e.getAttribute("aria-label"),name:e.getAttribute("name"),href:e.getAttribute("href"),selector:t,indexVersion:this.indexVersion}}matchesFingerprint(e,t){return e.tagName===t.tagName&&(!(!t.id||e.id!==t.id)||(!t.type||e.getAttribute("type")===t.type)&&((!t.ariaLabel||e.getAttribute("aria-label")===t.ariaLabel)&&((!t.role||e.getAttribute("role")===t.role)&&((!t.href||"A"!==t.tagName||e.getAttribute("href")===t.href)&&(!t.name||e.getAttribute("name")===t.name)))))}validateElementAtIndex(e){const t=this.fingerprintMap.get(e);if(!t)return{isValid:!0};const n=this.elementMap.get(e);return n&&document.contains(n)?n instanceof HTMLElement&&!this.matchesFingerprint(n,t)?{isValid:!1,mismatchReason:"element_changed"}:{isValid:!0}:{isValid:!1,mismatchReason:"element_removed"}}exportState(){return{selectors:Array.from(this.selectorMap.entries()),fingerprints:Array.from(this.fingerprintMap.entries())}}importState(e){if(e)try{e.selectors&&(this.selectorMap=new Map(e.selectors)),e.fingerprints&&(this.fingerprintMap=new Map(e.fingerprints)),(this.selectorMap.size>0||this.fingerprintMap.size>0)&&(this.isIndexed=!0)}catch(t){}}indexInteractableElements(){if(this.indexingInProgress)return[];try{this.indexingInProgress=!0,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;const r=[];for(;t;){if(t instanceof HTMLElement){const e=t.matches('a[href], button, input, textarea, select, [role="button"]'),i=t.classList.contains("cursor-pointer")||t.classList.contains("clickable"),o="onclick"in t&&"function"==typeof t.onclick;if(e||i||o||Wc(t)){this.elementMap.set(n,t),this.elementToSequence.set(t,n);const e=this.generateSelector(t);this.selectorMap.set(n,e);const i=this.generateFingerprint(t,e);this.fingerprintMap.set(n,i),r.push([n,t]),n++}}t=e.nextNode()}return this.isIndexed=!0,this.indexVersion++,r}finally{this.indexingInProgress=!1}}getElementCoordinates(e){const t=e.getBoundingClientRect(),n=this.calculateGlobalZOrder(e);return{x:Math.round(t.left),y:Math.round(t.top),w:Math.round(t.width),h:Math.round(t.height),z:n}}isStackingContext(e){const t=window.getComputedStyle(e),n=t.position;if(("fixed"===n||"absolute"===n||"relative"===n||"sticky"===n)&&"auto"!==t.zIndex)return!0;if("auto"!==t.zIndex&&e.parentElement){const t=window.getComputedStyle(e.parentElement).display;if("flex"===t||"inline-flex"===t||"grid"===t||"inline-grid"===t)return!0}const r=parseFloat(t.opacity);if(!isNaN(r)&&r<1)return!0;if(t.transform&&"none"!==t.transform)return!0;if(t.filter&&"none"!==t.filter)return!0;const i=t.willChange;if(i&&(i.includes("transform")||i.includes("opacity")))return!0;if("isolate"===t.isolation)return!0;const o=t.contain;return!(!o||!(o.includes("layout")||o.includes("style")||o.includes("paint")))}calculateGlobalZOrder(e){let t=e;const n=[];for(;t&&t!==document.body&&t.parentElement;){const e=window.getComputedStyle(t);if(this.isStackingContext(t)){let r=0;if("auto"!==e.zIndex){const t=parseInt(e.zIndex,10);isNaN(t)||(r=t)}let i=0;t.parentElement&&(i=Array.from(t.parentElement.children).indexOf(t)),n.push({element:t,zIndex:r,domOrder:i})}t=t.parentElement}let r=1e6;for(let i=n.length-1;i>=0;i--){const e=n[i];r+=1e4*e.zIndex+e.domOrder}if(e.parentElement){r+=Array.from(e.parentElement.children).indexOf(e)}return r}getSnapshotHtml(){this.indexInteractableElements();const e=document.documentElement.cloneNode(!0);for(const[n,r]of this.elementMap.entries())if(r instanceof HTMLElement){const i=this.selectorMap.get(n);if(i)try{const t=(e.querySelector("body")||e).querySelector(i);if(t)if(t.setAttribute("data-id",n.toString()),"none"===window.getComputedStyle(r).display)t.setAttribute("data-x","0"),t.setAttribute("data-y","0"),t.setAttribute("data-w","0"),t.setAttribute("data-h","0"),t.setAttribute("data-z","0");else{const e=this.getElementCoordinates(r);t.setAttribute("data-x",e.x.toString()),t.setAttribute("data-y",e.y.toString()),t.setAttribute("data-w",e.w.toString()),t.setAttribute("data-h",e.h.toString()),t.setAttribute("data-z",e.z.toString())}}catch(t){}}return e.outerHTML}getInteractableElements(){this.indexInteractableElements();const e=[];for(const[t,n]of this.elementMap.entries())if(n instanceof HTMLElement){const r=this.fingerprintMap.get(t);r&&e.push({index:t,fingerprint:r,coords:this.getElementCoordinates(n),cssClasses:Array.from(n.classList)})}return e}getElementByDataId(e){return this.elementMap.get(e)}getSequenceForElement(e){return this.elementToSequence.get(e)}isIndexActive(){return this.isIndexed}clearIndex(){this.elementMap.clear(),this.elementToSequence=/* @__PURE__ */new WeakMap,this.fingerprintMap.clear(),this.isIndexed=!1}checkInteractability(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 i=r.left+r.width/2,o=r.top+r.height/2,s=document.elementFromPoint(i,o);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}checkElementInteractable(e,t){return this.checkInteractability(e,t)}getElementByIndex(e){let t=null;if(this.elementMap.has(e)){const n=this.elementMap.get(e);n&&n instanceof HTMLElement&&(t=n)}if(!t&&this.selectorMap.has(e)){const n=this.selectorMap.get(e);if(n)try{const e=document.querySelector(n);e&&e instanceof HTMLElement&&(t=e)}catch(r){}}if(!t)return{element:null,error:`Element ${e} not found`};const n=this.checkInteractability(t,e);return n?{element:null,error:n}:{element:t}}getValidatedElement(e){const t=this.validateElementAtIndex(e);if(!t.isValid)return{element:null,validation:t,error:`DOM_CHANGED: Element at index ${e} ${"element_removed"===t.mismatchReason?"no longer exists":"has changed"}. Call get_html to get updated indices.`};const n=this.elementMap.get(e);if(!n)return{element:null,validation:t,error:`Element ${e} not found`};const r=this.checkInteractability(n,e);return r?{element:null,validation:t,error:r}:{element:n,validation:t}}getFingerprint(e){return this.fingerprintMap.get(e)}getAllFingerprints(){return Array.from(this.fingerprintMap.entries())}getIndexVersion(){return this.indexVersion}}.getInstance(),Hc=null;async function Zc(){if(Hc?.active){const e=Hc.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Hc}const e=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0});if(!e||0===e.getVideoTracks().length)throw new Error("Screen sharing permission denied or no video track available");return Hc=e,e.getVideoTracks()[0].addEventListener("ended",()=>{Hc=null}),e}function Vc(){return null!==function(){if(Hc?.active){const e=Hc.getVideoTracks();if(e.length>0&&"live"===e[0].readyState)return Hc}return Hc=null,null}()}var qc=class e{static instance;currentPopup=null;currentHighlight=null;currentElement=null;currentOptions=null;currentPromise=null;resolvePromise=null;rejectPromise=null;clickHandler=null;scrollHandler=null;updateHighlightPosition=null;rafId=null;mutationObserver=null;visibilityCheckInterval=null;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async showToolAction(e){const{element:t,explanation:n,isClickAction:r=!1,toolName:i}=e;return this.currentOptions?.element===t&&this.currentOptions.explanation===n&&this.currentOptions.toolName===i&&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.setupElementMonitoring(),this.setupVisibilityMonitoring(),r&&this.setupClickHandler(),this.currentPromise=new Promise((e,t)=>{this.resolvePromise=e,this.rejectPromise=t}).finally(()=>{this.cleanup()})),this.currentPromise}cleanup(){this.rejectPromise&&(this.rejectPromise("Cancelled by cleanup"),this.rejectPromise=null),this.resolvePromise=null,this.clickHandler&&(document.removeEventListener("click",this.clickHandler,{capture:!0}),this.clickHandler=null),this.scrollHandler&&(window.removeEventListener("scroll",this.scrollHandler,{capture:!0}),window.removeEventListener("resize",this.scrollHandler),window.removeEventListener("touchmove",this.scrollHandler),window.removeEventListener("wheel",this.scrollHandler),this.scrollHandler=null),null!==this.rafId&&(window.cancelAnimationFrame(this.rafId),this.rafId=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.visibilityCheckInterval&&(clearInterval(this.visibilityCheckInterval),this.visibilityCheckInterval=null),this.updateHighlightPosition=null,this.currentPopup&&(this.currentPopup.remove(),this.currentPopup=null),this.currentHighlight&&(this.currentHighlight.remove(),this.currentHighlight=null);const e=document.getElementById("marketrix-show-popup");e&&e.remove();const t=document.getElementById("marketrix-show-highlight");t&&t.remove(),this.currentElement=null,this.currentOptions=null,this.currentPromise=null,this.resolvePromise=null,this.rejectPromise=null}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>`,document.body.appendChild(n),this.currentPopup=n,t||this.setupContinueButton(n),this.updatePopupPosition()}setupPositionUpdates(){this.updateHighlightPosition=()=>{if(!this.currentElement||!this.currentHighlight)return;const e=this.currentElement.getBoundingClientRect();this.currentHighlight.style.top=`${e.top}px`,this.currentHighlight.style.left=`${e.left}px`,this.currentHighlight.style.width=`${e.width}px`,this.currentHighlight.style.height=`${e.height}px`,this.updatePopupPosition()},this.scrollHandler=()=>{null!==this.rafId&&window.cancelAnimationFrame(this.rafId),this.updateHighlightPosition?.()},window.addEventListener("scroll",this.scrollHandler,{capture:!0,passive:!0}),window.addEventListener("resize",this.scrollHandler,{passive:!0}),window.addEventListener("touchmove",this.scrollHandler,{passive:!0}),window.addEventListener("wheel",this.scrollHandler,{passive:!0})}updatePopupPosition(){if(!this.currentPopup||!this.currentElement)return;const e=this.currentElement.getBoundingClientRect(),t=320,n=120,r=10,i=e.left+e.width/2,o=e.top+e.height/2,s=[{left:e.right+20,top:o-60},{left:e.left-t-20,top:o-60},{left:i-160,top:e.top-n-20},{left:i-160,top:e.bottom+20}];let a=s[0];for(const d of s)if(d.left>=r&&d.left+t<=window.innerWidth-r&&d.top>=r&&d.top+n<=window.innerHeight-r){a=d;break}const l=Math.max(r,Math.min(a.left,window.innerWidth-t-r)),c=Math.max(r,Math.min(a.top,window.innerHeight-n-r));this.currentPopup.style.cssText+=`\n position: fixed;\n top: ${c}px;\n left: ${l}px;\n width: 320px;\n background: white;\n border-radius: 8px;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);\n z-index: 2147483646;\n padding: 16px;\n `}setupClickHandler(){this.clickHandler=e=>{if(this.currentElement&&this.resolvePromise&&e.composedPath().includes(this.currentElement)){e.preventDefault(),e.stopPropagation();const t=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,t(!0)}},document.addEventListener("click",this.clickHandler,{capture:!0})}setupContinueButton(e){window.requestAnimationFrame(()=>{const t=e.querySelector("#marketrix-show-continue");t&&t.addEventListener("click",e=>{if(e.stopPropagation(),this.resolvePromise){const e=this.resolvePromise;this.resolvePromise=null,this.rejectPromise=null,e(!0)}})})}setupElementMonitoring(){this.currentElement&&(this.mutationObserver=new MutationObserver(()=>{this.currentElement&&!document.body.contains(this.currentElement)&&this.failWithElementGone("Element was removed from DOM")}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}))}setupVisibilityMonitoring(){this.visibilityCheckInterval=setInterval(()=>{if(!this.currentElement)return;const e=Gc.getSequenceForElement(this.currentElement)??-1,t=Gc.checkElementInteractable(this.currentElement,e);t&&this.failWithElementGone(t)},200)}failWithElementGone(e){if(this.rejectPromise){const t=this.rejectPromise;this.rejectPromise=null,this.resolvePromise=null,t(/* @__PURE__ */new Error(`ELEMENT_GONE: ${e}`))}this.cleanup()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}.getInstance(),Jc=class e{static instance;constructor(){}static getInstance(){return e.instance||(e.instance=new e),e.instance}async executeTool(e,t,n="do",r=""){try{if("show"===n&&this.requiresHighlight(e)){const n=t.index;if(void 0!==n){const{element:t,error:i}=Gc.getElementByIndex(n);if(!t)return{success:!1,data:{text:""},error:i||`Element ${n} not found`};if(!(await qc.showToolAction({element:t,explanation:r||`Execute ${e}`,toolName:e,isClickAction:"click_element"===e})))return{success:!1,data:{text:""},error:"User cancelled action"}}}switch(e){case"navigate":return this.navigate(t);case"search":return this.search(t);case"click_element":return await this.clickElement(t);case"type_text":return this.typeText(t);case"scroll":return this.scroll(t);case"scroll_to_text":return this.scrollToText(t);case"extract":return this.extract(t);case"go_back":return this.goBack();case"wait":return await this.wait(t);case"select_dropdown_option":return this.selectDropdownOption(t);case"get_dropdown_options":return this.getDropdownOptions(t);case"send_keys":return this.sendKeys(t);case"upload_file":return this.uploadFile(t);case"close_tab":return this.closeTab();case"switch_tab":return this.switchTab(t);case"done":return this.done(t);case"get_html":return this.getHtml();case"get_interactable_elements":return this.getInteractableElements();case"get_screenshot":return await this.getScreenshot();default:return{success:!1,data:{text:""},error:`Unknown tool: ${e}`}}}catch(i){return qc.cleanup(),{success:!1,data:{text:""},error:i instanceof Error?i.message:String(i)}}}requiresHighlight(e){return["click_element","type_text","select_dropdown_option","send_keys","upload_file"].includes(e)}navigate(e){return e.url?e.new_tab?(window.open(e.url,"_blank"),{success:!0,data:{text:`Opened ${e.url} in new tab`}}):(window.location.href=e.url,{success:!0,data:{text:`Navigating to ${e.url}`}}):{success:!1,data:{text:""},error:"URL is required"}}search(e){if(!e.query)return{success:!1,data:{text:""},error:"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,{success:!0,data:{text:`Searching for "${e.query}" on ${t}`}}}async clickElement(e){if(void 0===e.index)return{success:!1,data:{text:""},error:"Index required"};const{element:t,error:n}=Gc.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),{success:!0,data:{text:`Clicked element ${e.index}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}typeText(e){if(void 0===e.index||void 0===e.text)return{success:!1,data:{text:""},error:"Index and text required"};const t=!1!==e.clear,{element:n,error:r}=Gc.getValidatedElement(e.index);if(!n)return{success:!1,data:{text:""},error:r||`Element ${e.index} not found`};if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n.isContentEditable){const r=n;try{r.focus()}catch(i){}const o=t?e.text:r.value+e.text;let s=!1,a=null;if(!s)try{const e="TEXTAREA"===r.tagName.toUpperCase()?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,t=Object.getOwnPropertyDescriptor(e,"value");t?.set&&(t.set.call(r,o),s=!0)}catch(i){a=i}if(!s)try{r.value=o,s=!0}catch(i){a=i}if(!s)try{r.focus(),t&&r.select(),document.execCommand("insertText",!1,e.text)&&(s=!0)}catch(i){a=i}if(!s)try{r.focus(),t&&(r.value="");for(const t of e.text)r.dispatchEvent(new KeyboardEvent("keydown",{key:t,bubbles:!0,cancelable:!0})),r.value+=t,r.dispatchEvent(new InputEvent("input",{bubbles:!0,cancelable:!0,inputType:"insertText",data:t})),r.dispatchEvent(new KeyboardEvent("keyup",{key:t,bubbles:!0,cancelable:!0}));s=!0}catch(i){a=i}if(!s)return{success:!1,data:{text:""},error:`Failed to set value: ${a instanceof Error?a.message:String(a)}`};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(i){}}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(i){return{success:!1,data:{text:""},error:`Failed to set value on element: ${i instanceof Error?i.message:String(i)}`}}else try{n.textContent=e.text,n.dispatchEvent(new Event("input",{bubbles:!0}))}catch(i){return{success:!1,data:{text:""},error:`Failed to set textContent: ${i instanceof Error?i.message:String(i)}`}}return{success:!0,data:{text:`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{success:!1,data:{text:""},error:"Invalid direction"}}return{success:!0,data:{text:`Scrolled ${e.direction}`}}}scrollToText(e){if(!e.text)return{success:!1,data:{text:""},error:"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"}),{success:!0,data:{text:`Scrolled to "${e.text}"`}};return{success:!1,data:{text:""},error:`Text "${e.text}" not found`}}extract(e){const t=e.start_from_char??0,n=!1!==e.extract_links,r=document.body.innerText;return{success:!0,data:{title:document.title,url:window.location.href,text:r.slice(t,t+1e4),links:n?Array.from(document.querySelectorAll("a[href]")).slice(0,100).map(e=>({text:e.textContent?.trim()||"",href:e.getAttribute("href")})):[]}}}goBack(){return window.history.length>1?(window.history.back(),{success:!0,data:{text:"Navigated back"}}):{success:!1,data:{text:""},error:"No history"}}async wait(e){return void 0===e.seconds?{success:!1,data:{text:""},error:"Seconds required"}:(await new Promise(t=>setTimeout(t,1e3*e.seconds)),{success:!0,data:{text:`Waited ${e.seconds}s`}})}selectDropdownOption(e){if(void 0===e.index||!e.option)return{success:!1,data:{text:""},error:"Index/Option required"};const{element:t,error:n}=Gc.getValidatedElement(e.index);if(!t)return{success:!1,data:{text:""},error:n||`Select ${e.index} not found`};if(!(t instanceof HTMLSelectElement))return{success:!1,data:{text:""},error:`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})),{success:!0,data:{text:`Selected ${e.option}`}}):{success:!1,data:{text:""},error:`Option ${e.option} not found`}}getDropdownOptions(e){const t=e.index,{element:n,error:r}=Gc.getValidatedElement(t);return n?n instanceof HTMLSelectElement?{success:!0,data:{options:Array.from(n.options).map(e=>({value:e.value,text:e.text}))}}:{success:!1,data:{options:[]},error:`Element ${t} is not a select element`}:{success:!1,data:{options:[]},error:r||`Select ${t} not found`}}sendKeys(e){if(void 0===e.index||!e.keys)return{success:!1,data:{text:""},error:"Index/Keys required"};const{element:t,error:n}=Gc.getValidatedElement(e.index);return t?(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})),{success:!0,data:{text:this.simulateKeyAction(t,e.keys)||`Sent keys ${e.keys}`}}):{success:!1,data:{text:""},error:n||`Element ${e.index} not found`}}simulateKeyAction(e,t){switch(t){case"Tab":{const t=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),n=t.indexOf(e);if(-1!==n&&n<t.length-1){const e=t[n+1];return e.focus(),`Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Tab: no next focusable element"}case"Shift+Tab":{const t=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),n=t.indexOf(e);if(n>0){const e=t[n-1];return e.focus(),`Shift+Tab: moved focus to ${e.tagName.toLowerCase()}${e.id?`#${e.id}`:""}`}return"Shift+Tab: no 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,i=e.selectionStart??t.length,o=e.selectionEnd??t.length;if(0===i&&0===o&&(i=t.length,o=t.length),i===o&&i>0)n=t.slice(0,i-1)+t.slice(o),r=i-1;else{if(i===o)return"Backspace: cursor at start, nothing to delete";n=t.slice(0,i)+t.slice(o),r=i}const s=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return s?s.call(e,n):e.value=n,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(r,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 i;if(t===n&&t<r.length)i=r.slice(0,t)+r.slice(n+1);else{if(t===n)return"Delete: cursor at end, nothing to delete";i=r.slice(0,t)+r.slice(n)}const o=Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,"value")?.set;return o?o.call(e,i):e.value=i,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.setSelectionRange(t,t),`Delete: deleted character, value is now "${i}"`}return"Delete: dispatched event";default:return null}}uploadFile(e){return{success:!1,data:{text:""},error:"File upload not supported via script"}}closeTab(){return window.close(),{success:!0,data:{text:"Attempted close"}}}switchTab(e){return e.tab_id?{success:!1,data:{text:""},error:"Tab switching not supported"}:{success:!1,data:{text:""},error:"tab_id is required"}}done(e){return void 0===e.success?{success:!1,data:{text:""},error:"success parameter is required"}:{success:!0,data:{text:e.message||(e.success?"Task completed":"Task failed")}}}getHtml(){try{return{success:!0,data:{text:Gc.getSnapshotHtml()}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}getInteractableElements(){try{return{success:!0,data:{elements:Gc.getInteractableElements()}}}catch(e){return{success:!1,data:{elements:[]},error:String(e)}}}async getScreenshot(){try{const e=await Zc();if(!e)return{success:!1,data:{text:""},error:"Failed to get stream"};const 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(),{success:!0,data:{text:r}}}catch(e){return{success:!1,data:{text:""},error:String(e)}}}}.getInstance(),Yc=n(void 0),Kc=({children:e,previewMode:t=!1})=>{const n=u(0),r=u(/* @__PURE__ */new Set),i=u(!1),s=o(e=>{if(r.current.add(e),r.current.size>1e3){const e=Array.from(r.current).slice(-500);r.current=new Set(e)}},[]),l=u({}),c=o(()=>{const e=l.current;if(e.apiTaskId&&e.agentStarted){const t=e.apiTaskId;l.current={},m(e=>(Ac.setTaskState(!0,t,[]),i.current=!0,{...e,isTaskRunning:!0,activeTaskId:t,taskProgress:[]}))}},[]),[h,m]=p({isOpen:!1,isMinimized:!1,isLoading:!1,messages:[],currentMode:"tell",agentAvailable:!1,activeTaskId:null,isTaskRunning:!1,taskProgress:[],activeView:"home"});a(()=>{if(t)return;(async()=>{const e=await Pc.getOrCreateChatId();Ac.createInitialContext(e),Ac.initialize(e);const t=Ac.getIsTaskRunning();if(i.current=t,m(e=>({...e,messages:Ac.getMessages(),isLoading:Ac.getIsLoading(),isTaskRunning:t,activeTaskId:Ac.getActiveTaskId(),taskProgress:Ac.getTaskProgress(),currentMode:Ac.getCurrentMode(),isOpen:Ac.getIsOpen(),isMinimized:Ac.getIsMinimized()})),e){const t=Lc.getInstance(),n=$c.getConfig();t.connect(e,n?{mtxId:n.mtxId,mtxKey:n.mtxKey,mtxAgent:n.mtxAgent,mtxApp:n.mtxApp}:void 0).catch(e=>{})}})()},[t]);const g=o((e,t,n,r)=>{m(i=>{const o=function(e){return Sc[e]?Sc[e]:e.replace(/([A-Z])/g," $1").replace(/_/g," ").trim().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" ")}(e),s=bc({messages:i.messages,isTaskRunning:i.isTaskRunning,currentMode:i.currentMode,preferPlaceholder:!0,requireContent:"failed"===n});if(!s)return i;let a=s.message;const l=["click_element","type_text","select_dropdown_option","send_keys","upload_file"].includes(e),c=i.isTaskRunning&&"show"===i.currentMode&&l,d="done"===e;"running"===n?(d||(a=function(e,t,n){const r=vc(e),i=r.parts||[],o=[...i],s=i.findIndex(e=>"progress"===e.type&&e.toolName===t&&"running"===e.status),a=!xc.has(t),l="default",c=kc(n);return s>=0?o[s]={...o[s],content:c,hideIcon:a,textStyle:l}:o.push({type:"progress",content:c,status:"running",toolName:t,hideIcon:a,textStyle:l}),{...r,parts:o}}(a,o,t||o)),!i.isTaskRunning||"show"!==i.currentMode&&"do"!==i.currentMode||(a=_c(a,i.isTaskRunning,i.currentMode,c))):"completed"===n?(d||(a=function(e,t){const n=vc(e),r=n.parts||[],i=[...r];let o=-1;if(t)o=r.map(e=>"progress"===e.type?e.toolName:"").lastIndexOf(t);else for(let s=r.length-1;s>=0;s--)if("progress"===r[s].type&&"running"===r[s].status){o=s;break}return o>=0&&(i[o]={...i[o],status:"completed"}),{...n,parts:i}}(a)),!i.isTaskRunning||"show"!==i.currentMode&&"do"!==i.currentMode||(a=_c(a,i.isTaskRunning,i.currentMode,!1))):(a=function(e,t,n){const r=vc(e),i=r.parts||[],o=n.toLowerCase().includes("cancelled by cleanup"),s=[...i];let a=i.map(e=>"progress"===e.type?e.toolName:"").lastIndexOf(t);if(-1===a)for(let l=i.length-1;l>=0;l--)if("progress"===i[l].type&&"running"===i[l].status){a=l;break}if(a>=0)if(o){const e=kc(s[a].content);s[a]={...s[a],status:"completed",content:e}}else{const e=kc(n),t=kc(s[a].content);s[a]={...s[a],status:"failed",content:e?`${t} (${e})`:t}}return{...r,parts:s}}(a,o,r||""),!i.isTaskRunning||"show"!==i.currentMode&&"do"!==i.currentMode||(a=_c(a,i.isTaskRunning,i.currentMode,!1)));const u=[...i.messages];return u[s.index]=a,Ac.setMessages(u),{...i,messages:u}})},[]);a(()=>{if(t)return;const e=Lc.getInstance(),o={onStatusChange:e=>{m(t=>({...t,agentAvailable:"registered"===e}))},onMessage:async t=>{if("tool/call"===t.type){const a=t.call_id;if(r.current.has(a))return;if(s(a),!fc.map(e=>e.id).includes(t.tool))return void e.send({type:"tool/response",call_id:a,success:!1,error:`Unknown tool: ${t.tool}`,state_version:n.current}).catch(e=>{});i.current||(i.current=!0,m(e=>({...e,isTaskRunning:!0})));const c=t.tool,d=t.args,u=t.mode||h.currentMode||"do",p=t.explanation||"",f=t.state_version;void 0!==f&&f>n.current&&(n.current=f),g(c,p,"running");const y=await Jc.executeTool(c,d,u,p);if(y.success)try{n.current++,e.send({type:"tool/response",call_id:a,success:!0,data:"string"==typeof y.data?y.data:JSON.stringify(y.data),state_version:n.current}).catch(e=>{}),g(c,p,"completed"),"done"===c&&(l.current={},m(e=>{Ac.setTaskState(!1,null,[]),i.current=!1;const t=bc({messages:e.messages,isTaskRunning:e.isTaskRunning,currentMode:e.currentMode,preferPlaceholder:!0,requireContent:!1}),n=[...e.messages];if(t){const e=t.message.parts?.filter(e=>!("progress"===e.type&&"done"===e.toolName))||[];n[t.index]={...t.message,taskStatus:"done",parts:e},Ac.setMessages(n)}return{...e,messages:n,isTaskRunning:!1,activeTaskId:null,taskProgress:[]}}))}catch(o){g(c,p,"failed","Connection error")}else g(c,p,"failed",y.error||"Tool execution failed"),n.current++,e.send({type:"tool/response",call_id:a,success:!1,data:"string"==typeof y.data?y.data:JSON.stringify(y.data),error:y.error??void 0,state_version:n.current}).catch(e=>{})}else if("task/status"===t.type){const e=t.status,n=t.message||"";"started"===e?(l.current={...l.current,agentStarted:!0,apiTaskId:l.current.apiTaskId||t.task_id||void 0},c()):"completed"!==e&&"failed"!==e&&"stopped"!==e||(r.current.clear(),l.current={},m(t=>{Ac.setTaskState(!1,null,[]);const r=bc({messages:t.messages,isTaskRunning:t.isTaskRunning,currentMode:t.currentMode,preferPlaceholder:!0,requireContent:!1}),o=[...t.messages];if(r){let t="done";"failed"===e?t="failed":"stopped"===e&&(t="stopped"),o[r.index]={...r.message,taskStatus:t,...n&&{content:n}},Ac.setMessages(o)}return i.current=!1,{...t,messages:o,isTaskRunning:!1,activeTaskId:null,taskProgress:[]}}))}else"chat/response"===t.type?m(e=>{const n=e.messages.map(e=>{if(e.id===t.request_id){const n=[...e.parts||[],{type:"text",content:t.text}];return{...e,content:t.text,isPlaceholder:!1,placeholderState:void 0,parts:n,...t.task_id&&{taskId:t.task_id}}}return e});return Ac.setMessages(n),t.task_id&&(l.current={...l.current,apiTaskId:t.task_id},c()),{...e,messages:n,isLoading:!1}}):"chat/error"===t.type&&m(e=>{const n=e.messages.map(e=>{if(e.id===t.request_id){const n=`Error: ${t.error}`,r=[...e.parts||[],{type:"text",content:n}];return{...e,content:n,isPlaceholder:!1,placeholderState:void 0,parts:r}}return e});return Ac.setMessages(n),{...e,messages:n,isLoading:!1}})},onError:e=>{m(t=>({...t,error:e.message}))}};return e.addCallbacks(o),()=>{e.removeCallbacks(o)}},[g,t]);const y=o(e=>{m(t=>(Ac.setTaskState(e.isTaskRunning,e.activeTaskId,e.taskProgress||[]),{...t,...e}))},[]),w=o(()=>{Ac.clearMessages(),l.current={},i.current=!1,m(e=>({...e,messages:[],isTaskRunning:!1,activeTaskId:null,taskProgress:[],error:void 0}))},[]),b=o(e=>{m(t=>(Ac.addMessage(e),{...t,messages:[...t.messages,e]}))},[]),v=o(async(e,n,r,i,o)=>{if(t)return o||b(Tc(e,n||h.currentMode)),void b(Mc("This is a preview. In production, I'll respond to your messages here."));let s=$c.getConfig();if(s||(s=$c.loadConfig()),!s||!s.mtxId&&!s.mtxKey&&!s.mtxAgent)return void b(Mc("Configuration error: Missing API credentials. Please check your widget settings."));o||b(Tc(e,n||h.currentMode));const a=`temp-${globalThis.crypto.randomUUID()}`,l={id:a,content:"",sender:"agent",timestamp:/* @__PURE__ */new Date,mode:n||h.currentMode,isPlaceholder:!0,placeholderState:"thinking",parts:[]};l.content=yc(""),b(l),m(e=>({...e,isLoading:!0}));const c=new Dc(s);try{r&&c.updateConfig({mtxApp:r});const t=c.getChatId();if(t){const e=Lc.getInstance();if(!e.isConnected()){const n=$c.getConfig();try{await e.connect(t,n?{mtxId:n.mtxId,mtxKey:n.mtxKey,mtxAgent:n.mtxAgent,mtxApp:n.mtxApp}:void 0)}catch(d){}}}await c.sendMessage({message:e,mode:n||h.currentMode,question:i,requestId:a})}catch(u){m(e=>{const t=e.messages.map(e=>{if(e.id===a){const t="I'm sorry, I encountered an error processing your request. Please try again.",n=[...e.parts||[],{type:"text",content:t}];return{...e,isPlaceholder:!1,parts:n,content:t}}return e});return Ac.setMessages(t),{...e,messages:t}})}finally{m(e=>({...e,isLoading:!1}))}},[h.currentMode,b,y,h,t]),x=d(()=>({setState:e=>m(t=>({...t,...e})),setActiveView:e=>m(t=>({...t,activeView:e})),toggleWidget:()=>m(e=>{const t={...e,isOpen:!e.isOpen,isMinimized:!!e.isOpen};return Ac.setWidgetState(t.isOpen,t.isMinimized),t}),closeWidget:()=>m(e=>{const t={...e,isOpen:!1,isMinimized:!0};return Ac.setWidgetState(t.isOpen,t.isMinimized),t}),setMode:e=>m(t=>(Ac.setMode(e),{...t,currentMode:e})),setLoading:e=>{Ac.setIsLoading(e),m(t=>({...t,isLoading:e}))},setAgentAvailable:e=>m(t=>({...t,agentAvailable:e})),setError:e=>m(t=>({...t,error:e})),clearError:()=>m(e=>({...e,error:void 0})),setTaskState:y,addMessage:b,updateMessage:(e,t)=>m(n=>(Ac.updateMessage(e,t),{...n,messages:n.messages.map(n=>n.id===e?{...n,...t}:n)})),removeMessage:e=>m(t=>(Ac.removeMessage(e),{...t,messages:t.messages.filter(t=>t.id!==e)})),setMessages:e=>m(t=>(Ac.setMessages(e),{...t,messages:e})),resetState:w,stopTask:async()=>{const e=h.activeTaskId||i.current?h.activeTaskId??void 0:void 0;m(e=>{const n=bc({messages:e.messages,isTaskRunning:e.isTaskRunning,currentMode:e.currentMode,preferPlaceholder:!0,requireContent:!1}),r=[...e.messages];return n&&(r[n.index]={...n.message,taskStatus:"stopped"},t||Ac.setMessages(r)),t||Ac.setTaskState(!1,null,[]),i.current=!1,{...e,messages:r,isTaskRunning:!1,activeTaskId:null,taskProgress:[]}}),t||Lc.getInstance().send({type:"chat/stop",...e&&{task_id:e}}).catch(e=>{})},clearChatHistory:w,sendMessage:v}),[h.currentMode,y,w,b,v,t]);/* @__PURE__ */
3
3
  return f(Yc.Provider,{value:{state:h,actions:x},children:e})};var Qc=({config:e}={})=>{const{state:t,actions:n}=(()=>{const e=s(Yc);if(void 0===e)throw new Error("useWidgetContext must be used within a WidgetProvider");return e})(),r=d(()=>e||$c.getConfig()||{},[e]),i=function(e){return Object.keys(Ra.shape).every(t=>void 0!==e[t])}(r);a(()=>{i&&$c.saveConfig(r)},[r,i]);const l=o(()=>i&&!0===r.widget_enabled,[r,i]),c=r.isPreviewMode??!1;return{state:t,config:r,actions:n,shouldShow:l(),isPreviewMode:c,configValid:i}},Xc=(e=/* @__PURE__ */new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),ed="-",td=[],nd=e=>{const t=od(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith("[")&&e.endsWith("]"))return id(e);const n=e.split(ed);return rd(n,""===n[0]&&n.length>1?1:0,t)},getConflictingClassGroupIds:(e,t)=>{if(t){const t=r[e],i=n[e];return t?i?((e,t)=>{const n=new Array(e.length+t.length);for(let r=0;r<e.length;r++)n[r]=e[r];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n})(i,t):t:i||td}return n[e]||td}}},rd=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;const r=e[t],i=n.nextPart.get(r);if(i){const n=rd(e,t+1,i);if(n)return n}const o=n.validators;if(null===o)return;const s=0===t?e.join(ed):e.slice(t).join(ed),a=o.length;for(let l=0;l<a;l++){const e=o[l];if(e.validator(s))return e.classGroupId}},id=e=>-1===e.slice(1,-1).indexOf(":")?void 0:(()=>{const t=e.slice(1,-1),n=t.indexOf(":"),r=t.slice(0,n);return r?"arbitrary.."+r:void 0})(),od=e=>{const{theme:t,classGroups:n}=e;return sd(n,t)},sd=(e,t)=>{const n=Xc();for(const r in e){const i=e[r];ad(i,n,r,t)}return n},ad=(e,t,n,r)=>{const i=e.length;for(let o=0;o<i;o++){const i=e[o];ld(i,t,n,r)}},ld=(e,t,n,r)=>{"string"!=typeof e?"function"!=typeof e?ud(e,t,n,r):dd(e,t,n,r):cd(e,t,n)},cd=(e,t,n)=>{(""===e?t:pd(t,e)).classGroupId=n},dd=(e,t,n,r)=>{hd(e)?ad(e(r),t,n,r):(null===t.validators&&(t.validators=[]),t.validators.push(((e,t)=>({classGroupId:e,validator:t}))(n,e)))},ud=(e,t,n,r)=>{const i=Object.entries(e),o=i.length;for(let s=0;s<o;s++){const[e,o]=i[s];ad(o,pd(t,e),n,r)}},pd=(e,t)=>{let n=e;const r=t.split(ed),i=r.length;for(let o=0;o<i;o++){const e=r[o];let t=n.nextPart.get(e);t||(t=Xc(),n.nextPart.set(e,t)),n=t}return n},hd=e=>"isThemeGetter"in e&&!0===e.isThemeGetter,md=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null);const i=(i,o)=>{n[i]=o,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];return void 0!==t?t:void 0!==(t=r[e])?(i(e,t),t):void 0},set(e,t){e in n?n[e]=t:i(e,t)}}},fd=[],gd=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),yd=e=>{const{prefix:t,experimentalParseClassName:n}=e;let r=e=>{const t=[];let n,r=0,i=0,o=0;const s=e.length;for(let d=0;d<s;d++){const s=e[d];if(0===r&&0===i){if(":"===s){t.push(e.slice(o,d)),o=d+1;continue}if("/"===s){n=d;continue}}"["===s?r++:"]"===s?r--:"("===s?i++:")"===s&&i--}const a=0===t.length?e:e.slice(o);let l=a,c=!1;a.endsWith("!")?(l=a.slice(0,-1),c=!0):a.startsWith("!")&&(l=a.slice(1),c=!0);return gd(t,c,l,n&&n>o?n-o:void 0)};if(t){const e=t+":",n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):gd(fd,!1,t,void 0,!0)}if(n){const e=r;r=t=>n({className:t,parseClassName:e})}return r},wd=e=>{const t=/* @__PURE__ */new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{const n=[];let r=[];for(let i=0;i<e.length;i++){const o=e[i],s="["===o[0],a=t.has(o);s||a?(r.length>0&&(r.sort(),n.push(...r),r=[]),n.push(o)):r.push(o)}return r.length>0&&(r.sort(),n.push(...r)),n}},bd=/\s+/,vd=e=>{if("string"==typeof e)return e;let t,n="";for(let r=0;r<e.length;r++)e[r]&&(t=vd(e[r]))&&(n&&(n+=" "),n+=t);return n},xd=(e,...t)=>{let n,r,i,o;const s=e=>{const t=r(e);if(t)return t;const o=((e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:o}=t,s=[],a=e.trim().split(bd);let l="";for(let c=a.length-1;c>=0;c-=1){const e=a[c],{isExternal:t,modifiers:d,hasImportantModifier:u,baseClassName:p,maybePostfixModifierPosition:h}=n(e);if(t){l=e+(l.length>0?" "+l:l);continue}let m=!!h,f=r(m?p.substring(0,h):p);if(!f){if(!m){l=e+(l.length>0?" "+l:l);continue}if(f=r(p),!f){l=e+(l.length>0?" "+l:l);continue}m=!1}const g=0===d.length?"":1===d.length?d[0]:o(d).join(":"),y=u?g+"!":g,w=y+f;if(s.indexOf(w)>-1)continue;s.push(w);const b=i(f,m);for(let n=0;n<b.length;++n){const e=b[n];s.push(y+e)}l=e+(l.length>0?" "+l:l)}return l})(e,n);return i(e,o),o};return o=a=>(n=(e=>({cache:md(e.cacheSize),parseClassName:yd(e),sortModifiers:wd(e),...nd(e)}))(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,o=s,s(a)),(...e)=>o(((...e)=>{let t,n,r=0,i="";for(;r<e.length;)(t=e[r++])&&(n=vd(t))&&(i&&(i+=" "),i+=n);return i})(...e))},kd=[],_d=e=>{const t=t=>t[e]||kd;return t.isThemeGetter=!0,t},Sd=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Cd=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Id=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ed=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ad=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Td=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Md=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,zd=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Od=e=>Id.test(e),Rd=e=>!!e&&!Number.isNaN(Number(e)),Nd=e=>!!e&&Number.isInteger(Number(e)),Pd=e=>e.endsWith("%")&&Rd(e.slice(0,-1)),Ld=e=>Ed.test(e),Dd=()=>!0,$d=e=>Ad.test(e)&&!Td.test(e),jd=()=>!1,Fd=e=>Md.test(e),Ud=e=>zd.test(e),Bd=e=>!Gd(e)&&!Qd(e),Wd=e=>su(e,du,jd),Gd=e=>Sd.test(e),Hd=e=>su(e,uu,$d),Zd=e=>su(e,pu,Rd),Vd=e=>su(e,mu,Dd),qd=e=>su(e,hu,jd),Jd=e=>su(e,lu,jd),Yd=e=>su(e,cu,Ud),Kd=e=>su(e,fu,Fd),Qd=e=>Cd.test(e),Xd=e=>au(e,uu),eu=e=>au(e,hu),tu=e=>au(e,lu),nu=e=>au(e,du),ru=e=>au(e,cu),iu=e=>au(e,fu,!0),ou=e=>au(e,mu,!0),su=(e,t,n)=>{const r=Sd.exec(e);return!!r&&(r[1]?t(r[1]):n(r[2]))},au=(e,t,n=!1)=>{const r=Cd.exec(e);return!!r&&(r[1]?t(r[1]):n)},lu=e=>"position"===e||"percentage"===e,cu=e=>"image"===e||"url"===e,du=e=>"length"===e||"size"===e||"bg-size"===e,uu=e=>"length"===e,pu=e=>"number"===e,hu=e=>"family-name"===e,mu=e=>"number"===e||"weight"===e,fu=e=>"shadow"===e,gu=/* @__PURE__ */xd(()=>{const e=_d("color"),t=_d("font"),n=_d("text"),r=_d("font-weight"),i=_d("tracking"),o=_d("leading"),s=_d("breakpoint"),a=_d("container"),l=_d("spacing"),c=_d("radius"),d=_d("shadow"),u=_d("inset-shadow"),p=_d("text-shadow"),h=_d("drop-shadow"),m=_d("blur"),f=_d("perspective"),g=_d("aspect"),y=_d("ease"),w=_d("animate"),b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",Qd,Gd],v=()=>[Qd,Gd,l],x=()=>[Od,"full","auto",...v()],k=()=>[Nd,"none","subgrid",Qd,Gd],_=()=>["auto",{span:["full",Nd,Qd,Gd]},Nd,Qd,Gd],S=()=>[Nd,"auto",Qd,Gd],C=()=>["auto","min","max","fr",Qd,Gd],I=()=>["auto",...v()],E=()=>[Od,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...v()],A=()=>[Od,"screen","full","dvw","lvw","svw","min","max","fit",...v()],T=()=>[Od,"screen","full","lh","dvh","lvh","svh","min","max","fit",...v()],M=()=>[e,Qd,Gd],z=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom",tu,Jd,{position:[Qd,Gd]}],O=()=>["auto","cover","contain",nu,Wd,{size:[Qd,Gd]}],R=()=>[Pd,Xd,Hd],N=()=>["","none","full",c,Qd,Gd],P=()=>["",Rd,Xd,Hd],L=()=>[Rd,Pd,tu,Jd],D=()=>["","none",m,Qd,Gd],$=()=>["none",Rd,Qd,Gd],j=()=>["none",Rd,Qd,Gd],F=()=>[Rd,Qd,Gd],U=()=>[Od,"full",...v()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[Ld],breakpoint:[Ld],color:[Dd],container:[Ld],"drop-shadow":[Ld],ease:["in","out","in-out"],font:[Bd],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[Ld],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[Ld],shadow:[Ld],spacing:["px",Rd],text:[Ld],"text-shadow":[Ld],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",Od,Gd,Qd,g]}],container:["container"],columns:[{columns:[Rd,Gd,Qd,a]}],"break-after":[{"break-after":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-before":[{"break-before":["auto","avoid","all","avoid-page","page","left","right","column"]}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:b()}],overflow:[{overflow:["auto","hidden","clip","visible","scroll"]}],"overflow-x":[{"overflow-x":["auto","hidden","clip","visible","scroll"]}],"overflow-y":[{"overflow-y":["auto","hidden","clip","visible","scroll"]}],overscroll:[{overscroll:["auto","contain","none"]}],"overscroll-x":[{"overscroll-x":["auto","contain","none"]}],"overscroll-y":[{"overscroll-y":["auto","contain","none"]}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:x()}],"inset-x":[{"inset-x":x()}],"inset-y":[{"inset-y":x()}],start:[{"inset-s":x(),start:x()}],end:[{"inset-e":x(),end:x()}],"inset-bs":[{"inset-bs":x()}],"inset-be":[{"inset-be":x()}],top:[{top:x()}],right:[{right:x()}],bottom:[{bottom:x()}],left:[{left:x()}],visibility:["visible","invisible","collapse"],z:[{z:[Nd,"auto",Qd,Gd]}],basis:[{basis:[Od,"full","auto",a,...v()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Rd,Od,"auto","initial","none",Gd]}],grow:[{grow:["",Rd,Qd,Gd]}],shrink:[{shrink:["",Rd,Qd,Gd]}],order:[{order:[Nd,"first","last","none",Qd,Gd]}],"grid-cols":[{"grid-cols":k()}],"col-start-end":[{col:_()}],"col-start":[{"col-start":S()}],"col-end":[{"col-end":S()}],"grid-rows":[{"grid-rows":k()}],"row-start-end":[{row:_()}],"row-start":[{"row-start":S()}],"row-end":[{"row-end":S()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":C()}],"auto-rows":[{"auto-rows":C()}],gap:[{gap:v()}],"gap-x":[{"gap-x":v()}],"gap-y":[{"gap-y":v()}],"justify-content":[{justify:["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe","normal"]}],"justify-items":[{"justify-items":["start","end","center","stretch","center-safe","end-safe","normal"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],"align-content":[{content:["normal","start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"align-items":[{items:["start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"align-self":[{self:["auto","start","end","center","stretch","center-safe","end-safe",{baseline:["","last"]}]}],"place-content":[{"place-content":["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"]}],"place-items":[{"place-items":["start","end","center","stretch","center-safe","end-safe","baseline"]}],"place-self":[{"place-self":["auto","start","end","center","stretch","center-safe","end-safe"]}],p:[{p:v()}],px:[{px:v()}],py:[{py:v()}],ps:[{ps:v()}],pe:[{pe:v()}],pbs:[{pbs:v()}],pbe:[{pbe:v()}],pt:[{pt:v()}],pr:[{pr:v()}],pb:[{pb:v()}],pl:[{pl:v()}],m:[{m:I()}],mx:[{mx:I()}],my:[{my:I()}],ms:[{ms:I()}],me:[{me:I()}],mbs:[{mbs:I()}],mbe:[{mbe:I()}],mt:[{mt:I()}],mr:[{mr:I()}],mb:[{mb:I()}],ml:[{ml:I()}],"space-x":[{"space-x":v()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":v()}],"space-y-reverse":["space-y-reverse"],size:[{size:E()}],"inline-size":[{inline:["auto",...A()]}],"min-inline-size":[{"min-inline":["auto",...A()]}],"max-inline-size":[{"max-inline":["none",...A()]}],"block-size":[{block:["auto",...T()]}],"min-block-size":[{"min-block":["auto",...T()]}],"max-block-size":[{"max-block":["none",...T()]}],w:[{w:[a,"screen",...E()]}],"min-w":[{"min-w":[a,"screen","none",...E()]}],"max-w":[{"max-w":[a,"screen","none","prose",{screen:[s]},...E()]}],h:[{h:["screen","lh",...E()]}],"min-h":[{"min-h":["screen","lh","none",...E()]}],"max-h":[{"max-h":["screen","lh",...E()]}],"font-size":[{text:["base",n,Xd,Hd]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[r,ou,Vd]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Pd,Gd]}],"font-family":[{font:[eu,qd,t]}],"font-features":[{"font-features":[Gd]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[i,Qd,Gd]}],"line-clamp":[{"line-clamp":[Rd,"none",Qd,Zd]}],leading:[{leading:[o,...v()]}],"list-image":[{"list-image":["none",Qd,Gd]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Qd,Gd]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:M()}],"text-color":[{text:M()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:["solid","dashed","dotted","double","wavy"]}],"text-decoration-thickness":[{decoration:[Rd,"from-font","auto",Qd,Hd]}],"text-decoration-color":[{decoration:M()}],"underline-offset":[{"underline-offset":[Rd,"auto",Qd,Gd]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:v()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Qd,Gd]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Qd,Gd]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:z()}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","space","round"]}]}],"bg-size":[{bg:O()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Nd,Qd,Gd],radial:["",Qd,Gd],conic:[Nd,Qd,Gd]},ru,Yd]}],"bg-color":[{bg:M()}],"gradient-from-pos":[{from:R()}],"gradient-via-pos":[{via:R()}],"gradient-to-pos":[{to:R()}],"gradient-from":[{from:M()}],"gradient-via":[{via:M()}],"gradient-to":[{to:M()}],rounded:[{rounded:N()}],"rounded-s":[{"rounded-s":N()}],"rounded-e":[{"rounded-e":N()}],"rounded-t":[{"rounded-t":N()}],"rounded-r":[{"rounded-r":N()}],"rounded-b":[{"rounded-b":N()}],"rounded-l":[{"rounded-l":N()}],"rounded-ss":[{"rounded-ss":N()}],"rounded-se":[{"rounded-se":N()}],"rounded-ee":[{"rounded-ee":N()}],"rounded-es":[{"rounded-es":N()}],"rounded-tl":[{"rounded-tl":N()}],"rounded-tr":[{"rounded-tr":N()}],"rounded-br":[{"rounded-br":N()}],"rounded-bl":[{"rounded-bl":N()}],"border-w":[{border:P()}],"border-w-x":[{"border-x":P()}],"border-w-y":[{"border-y":P()}],"border-w-s":[{"border-s":P()}],"border-w-e":[{"border-e":P()}],"border-w-bs":[{"border-bs":P()}],"border-w-be":[{"border-be":P()}],"border-w-t":[{"border-t":P()}],"border-w-r":[{"border-r":P()}],"border-w-b":[{"border-b":P()}],"border-w-l":[{"border-l":P()}],"divide-x":[{"divide-x":P()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":P()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:["solid","dashed","dotted","double","hidden","none"]}],"divide-style":[{divide:["solid","dashed","dotted","double","hidden","none"]}],"border-color":[{border:M()}],"border-color-x":[{"border-x":M()}],"border-color-y":[{"border-y":M()}],"border-color-s":[{"border-s":M()}],"border-color-e":[{"border-e":M()}],"border-color-bs":[{"border-bs":M()}],"border-color-be":[{"border-be":M()}],"border-color-t":[{"border-t":M()}],"border-color-r":[{"border-r":M()}],"border-color-b":[{"border-b":M()}],"border-color-l":[{"border-l":M()}],"divide-color":[{divide:M()}],"outline-style":[{outline:["solid","dashed","dotted","double","none","hidden"]}],"outline-offset":[{"outline-offset":[Rd,Qd,Gd]}],"outline-w":[{outline:["",Rd,Xd,Hd]}],"outline-color":[{outline:M()}],shadow:[{shadow:["","none",d,iu,Kd]}],"shadow-color":[{shadow:M()}],"inset-shadow":[{"inset-shadow":["none",u,iu,Kd]}],"inset-shadow-color":[{"inset-shadow":M()}],"ring-w":[{ring:P()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:M()}],"ring-offset-w":[{"ring-offset":[Rd,Hd]}],"ring-offset-color":[{"ring-offset":M()}],"inset-ring-w":[{"inset-ring":P()}],"inset-ring-color":[{"inset-ring":M()}],"text-shadow":[{"text-shadow":["none",p,iu,Kd]}],"text-shadow-color":[{"text-shadow":M()}],opacity:[{opacity:[Rd,Qd,Gd]}],"mix-blend":[{"mix-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"]}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Rd]}],"mask-image-linear-from-pos":[{"mask-linear-from":L()}],"mask-image-linear-to-pos":[{"mask-linear-to":L()}],"mask-image-linear-from-color":[{"mask-linear-from":M()}],"mask-image-linear-to-color":[{"mask-linear-to":M()}],"mask-image-t-from-pos":[{"mask-t-from":L()}],"mask-image-t-to-pos":[{"mask-t-to":L()}],"mask-image-t-from-color":[{"mask-t-from":M()}],"mask-image-t-to-color":[{"mask-t-to":M()}],"mask-image-r-from-pos":[{"mask-r-from":L()}],"mask-image-r-to-pos":[{"mask-r-to":L()}],"mask-image-r-from-color":[{"mask-r-from":M()}],"mask-image-r-to-color":[{"mask-r-to":M()}],"mask-image-b-from-pos":[{"mask-b-from":L()}],"mask-image-b-to-pos":[{"mask-b-to":L()}],"mask-image-b-from-color":[{"mask-b-from":M()}],"mask-image-b-to-color":[{"mask-b-to":M()}],"mask-image-l-from-pos":[{"mask-l-from":L()}],"mask-image-l-to-pos":[{"mask-l-to":L()}],"mask-image-l-from-color":[{"mask-l-from":M()}],"mask-image-l-to-color":[{"mask-l-to":M()}],"mask-image-x-from-pos":[{"mask-x-from":L()}],"mask-image-x-to-pos":[{"mask-x-to":L()}],"mask-image-x-from-color":[{"mask-x-from":M()}],"mask-image-x-to-color":[{"mask-x-to":M()}],"mask-image-y-from-pos":[{"mask-y-from":L()}],"mask-image-y-to-pos":[{"mask-y-to":L()}],"mask-image-y-from-color":[{"mask-y-from":M()}],"mask-image-y-to-color":[{"mask-y-to":M()}],"mask-image-radial":[{"mask-radial":[Qd,Gd]}],"mask-image-radial-from-pos":[{"mask-radial-from":L()}],"mask-image-radial-to-pos":[{"mask-radial-to":L()}],"mask-image-radial-from-color":[{"mask-radial-from":M()}],"mask-image-radial-to-color":[{"mask-radial-to":M()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"]}],"mask-image-conic-pos":[{"mask-conic":[Rd]}],"mask-image-conic-from-pos":[{"mask-conic-from":L()}],"mask-image-conic-to-pos":[{"mask-conic-to":L()}],"mask-image-conic-from-color":[{"mask-conic-from":M()}],"mask-image-conic-to-color":[{"mask-conic-to":M()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:z()}],"mask-repeat":[{mask:["no-repeat",{repeat:["","x","y","space","round"]}]}],"mask-size":[{mask:O()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Qd,Gd]}],filter:[{filter:["","none",Qd,Gd]}],blur:[{blur:D()}],brightness:[{brightness:[Rd,Qd,Gd]}],contrast:[{contrast:[Rd,Qd,Gd]}],"drop-shadow":[{"drop-shadow":["","none",h,iu,Kd]}],"drop-shadow-color":[{"drop-shadow":M()}],grayscale:[{grayscale:["",Rd,Qd,Gd]}],"hue-rotate":[{"hue-rotate":[Rd,Qd,Gd]}],invert:[{invert:["",Rd,Qd,Gd]}],saturate:[{saturate:[Rd,Qd,Gd]}],sepia:[{sepia:["",Rd,Qd,Gd]}],"backdrop-filter":[{"backdrop-filter":["","none",Qd,Gd]}],"backdrop-blur":[{"backdrop-blur":D()}],"backdrop-brightness":[{"backdrop-brightness":[Rd,Qd,Gd]}],"backdrop-contrast":[{"backdrop-contrast":[Rd,Qd,Gd]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Rd,Qd,Gd]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Rd,Qd,Gd]}],"backdrop-invert":[{"backdrop-invert":["",Rd,Qd,Gd]}],"backdrop-opacity":[{"backdrop-opacity":[Rd,Qd,Gd]}],"backdrop-saturate":[{"backdrop-saturate":[Rd,Qd,Gd]}],"backdrop-sepia":[{"backdrop-sepia":["",Rd,Qd,Gd]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":v()}],"border-spacing-x":[{"border-spacing-x":v()}],"border-spacing-y":[{"border-spacing-y":v()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Qd,Gd]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Rd,"initial",Qd,Gd]}],ease:[{ease:["linear","initial",y,Qd,Gd]}],delay:[{delay:[Rd,Qd,Gd]}],animate:[{animate:["none",w,Qd,Gd]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[f,Qd,Gd]}],"perspective-origin":[{"perspective-origin":b()}],rotate:[{rotate:$()}],"rotate-x":[{"rotate-x":$()}],"rotate-y":[{"rotate-y":$()}],"rotate-z":[{"rotate-z":$()}],scale:[{scale:j()}],"scale-x":[{"scale-x":j()}],"scale-y":[{"scale-y":j()}],"scale-z":[{"scale-z":j()}],"scale-3d":["scale-3d"],skew:[{skew:F()}],"skew-x":[{"skew-x":F()}],"skew-y":[{"skew-y":F()}],transform:[{transform:[Qd,Gd,"","none","gpu","cpu"]}],"transform-origin":[{origin:b()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:U()}],"translate-x":[{"translate-x":U()}],"translate-y":[{"translate-y":U()}],"translate-z":[{"translate-z":U()}],"translate-none":["translate-none"],accent:[{accent:M()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:M()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Qd,Gd]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":v()}],"scroll-mx":[{"scroll-mx":v()}],"scroll-my":[{"scroll-my":v()}],"scroll-ms":[{"scroll-ms":v()}],"scroll-me":[{"scroll-me":v()}],"scroll-mbs":[{"scroll-mbs":v()}],"scroll-mbe":[{"scroll-mbe":v()}],"scroll-mt":[{"scroll-mt":v()}],"scroll-mr":[{"scroll-mr":v()}],"scroll-mb":[{"scroll-mb":v()}],"scroll-ml":[{"scroll-ml":v()}],"scroll-p":[{"scroll-p":v()}],"scroll-px":[{"scroll-px":v()}],"scroll-py":[{"scroll-py":v()}],"scroll-ps":[{"scroll-ps":v()}],"scroll-pe":[{"scroll-pe":v()}],"scroll-pbs":[{"scroll-pbs":v()}],"scroll-pbe":[{"scroll-pbe":v()}],"scroll-pt":[{"scroll-pt":v()}],"scroll-pr":[{"scroll-pr":v()}],"scroll-pb":[{"scroll-pb":v()}],"scroll-pl":[{"scroll-pl":v()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Qd,Gd]}],fill:[{fill:["none",...M()]}],"stroke-w":[{stroke:[Rd,Xd,Hd,Zd]}],stroke:[{stroke:["none",...M()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function yu(...e){return gu(e.filter(Boolean).join(" "))}var wu={none:"0",xs:"0.5",sm:"1.5",md:"2",lg:"3",xl:"4","2xl":"6"},bu=new Set(["padding","paddingX","paddingY","margin","marginTop","gap","align","justify","grow","shrink","position","inset","overflow","overflowY","width","height","border","rounded","shadow","animate","as","style"]);function vu(e){const t=[];if(void 0!==e.padding&&t.push(`p-${wu[e.padding]}`),void 0!==e.paddingX&&t.push(`px-${wu[e.paddingX]}`),void 0!==e.paddingY&&t.push(`py-${wu[e.paddingY]}`),void 0!==e.margin&&t.push(`m-${wu[e.margin]}`),void 0!==e.marginTop&&t.push(`mt-${wu[e.marginTop]}`),void 0!==e.gap&&t.push(`gap-${wu[e.gap]}`),void 0!==e.align&&t.push(`items-${e.align}`),void 0!==e.justify&&t.push(`justify-${e.justify}`),!0===e.grow&&t.push("flex-1"),!1===e.shrink&&t.push("flex-shrink-0"),void 0!==e.position&&t.push(e.position),"0"===e.inset&&t.push("inset-0"),void 0!==e.overflow&&t.push(`overflow-${e.overflow}`),void 0!==e.overflowY&&t.push(`overflow-y-${e.overflowY}`),void 0!==e.width&&t.push(`w-${e.width}`),void 0!==e.height&&t.push(`h-${e.height}`),void 0!==e.border&&!1!==e.border)if(!0===e.border)t.push("border","border-border");else{const n={top:"t",bottom:"b"}[e.border];t.push(`border-${n}`,"border-border")}return void 0!==e.rounded&&!1!==e.rounded&&(!0===e.rounded||"theme"===e.rounded?t.push("rounded-[var(--radius)]"):"full"===e.rounded?t.push("rounded-full"):"lg"===e.rounded&&t.push("rounded-lg")),!0===e.shadow&&t.push("shadow-[var(--shadow)]"),void 0!==e.animate&&t.push({spin:"animate-spin",ping:"animate-ping",fadeIn:"animate-fade-in"}[e.animate]),t.join(" ")}function xu(e){const t={};for(const n in e)bu.has(n)||(t[n]=e[n]);return t}var ku=i(function(e,t){const{as:n="div",className:r,style:i,...o}=e,s=vu(e);/* @__PURE__ */
4
4
  return f(n,{...xu(o),ref:t,className:yu(s,r),style:i})}),_u="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%3c!--%20Generator:%20Adobe%20Illustrator%2030.1.0,%20SVG%20Export%20Plug-In%20.%20SVG%20Version:%202.1.1%20Build%20136)%20--%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",Su={md:"w-8 h-8"},Cu=i(function({src:e,alt:t,size:n="md",rounded:r,className:i,style:o,...s},a){const l="string"==typeof n,c=l?Su[n]:void 0,d=l?o:{width:n,height:n,...o};/* @__PURE__ */
5
5
  return f("img",{...s,ref:a,alt:t,className:yu("flex-shrink-0 object-contain",c,(!0===r||"theme"===r)&&"rounded-[var(--radius)]","full"===r&&"rounded-full",i),src:e,style:d})});function Iu(e){return"undefined"!=typeof window&&(e instanceof HTMLElement||e instanceof function(e){var t;return(null==e||null==(t=e.ownerDocument)?void 0:t.defaultView)||window}(e).HTMLElement)}var Eu={};function Au(t,n){const r=e.useRef(Eu);return r.current===Eu&&(r.current=t(n)),r}var Tu=e[`useInsertionEffect${Math.random().toFixed(1)}`.slice(0,-3)],Mu=Tu&&Tu!==e.useLayoutEffect?Tu:e=>e();function zu(e){const t=Au(Ou).current;return t.next=e,Mu(t.effect),t.trampoline}function Ou(){const e={next:void 0,callback:Ru,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function Ru(){}var Nu="undefined"!=typeof document?e.useLayoutEffect:()=>{};function Pu(e,t){return e&&!t?e:!e&&t?t:e||t?{...e,...t}:void 0}var Lu={};function Du(e,t,n,r,i){let o={...Uu(e,Lu)};return t&&(o=$u(o,t)),n&&(o=$u(o,n)),r&&(o=$u(o,r)),i&&(o=$u(o,i)),o}function $u(e,t){return Fu(t)?t(e):function(e,t){if(!t)return e;for(const n in t){const r=t[n];switch(n){case"style":e[n]=Pu(e.style,r);break;case"className":e[n]=Gu(e.className,r);break;default:ju(n,r)?e[n]=Bu(e[n],r):e[n]=r}}return e}(e,t)}function ju(e,t){const n=e.charCodeAt(0),r=e.charCodeAt(1),i=e.charCodeAt(2);return 111===n&&110===r&&i>=65&&i<=90&&("function"==typeof t||void 0===t)}function Fu(e){return"function"==typeof e}function Uu(e,t){return Fu(e)?e(t):e??Lu}function Bu(e,t){return t?e?n=>{if(function(e){return null!=e&&"object"==typeof e&&"nativeEvent"in e}(n)){const r=n;Wu(r);const i=t(r);return r.baseUIHandlerPrevented||e?.(r),i}const r=t(n);return e?.(n),r}:t:e}function Wu(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function Gu(e,t){return t?e?t+" "+e:t:e}var Hu,Zu,Vu=(Hu="https://base-ui.com/production-error",Zu="Base UI",function(e,...t){const n=new URL(Hu);return n.searchParams.set("code",e.toString()),t.forEach(e=>n.searchParams.append("args[]",e)),`${Zu} error #${e}; visit ${n} for the full message.`}),qu=/* @__PURE__ */e.createContext(void 0);function Ju(t={}){const{disabled:n=!1,focusableWhenDisabled:r,tabIndex:i=0,native:o=!0,composite:s}=t,a=e.useRef(null),l=function(t=!1){const n=e.useContext(qu);if(void 0===n&&!t)throw new Error(Vu(16));return n}(!0),c=s??void 0!==l,{props:d}=function(t){const{focusableWhenDisabled:n,disabled:r,composite:i=!1,tabIndex:o=0,isNativeButton:s}=t,a=i&&!1!==n,l=i&&!1===n;return{props:e.useMemo(()=>{const e={onKeyDown(e){r&&n&&"Tab"!==e.key&&e.preventDefault()}};return i||(e.tabIndex=o,!s&&r&&(e.tabIndex=n?o:-1)),(s&&(n||a)||!s&&r)&&(e["aria-disabled"]=r),!s||n&&!l||(e.disabled=r),e},[i,r,n,a,l,s,o])}}({focusableWhenDisabled:r,disabled:n,composite:c,tabIndex:i,isNativeButton:o}),u=e.useCallback(()=>{const e=a.current;Yu(e)&&c&&n&&void 0===d.disabled&&e.disabled&&(e.disabled=!1)},[n,d.disabled,c]);return Nu(u,[u]),{getButtonProps:e.useCallback((e={})=>{const{onClick:t,onMouseDown:r,onKeyUp:i,onKeyDown:s,onPointerDown:a,...l}=e;return Du({type:o?"button":void 0,onClick(e){n?e.preventDefault():t?.(e)},onMouseDown(e){n||r?.(e)},onKeyDown(e){if(n)return;if(Wu(e),s?.(e),e.baseUIHandlerPrevented)return;const r=e.target===e.currentTarget,i=e.currentTarget,a=Yu(i),l=!o&&(d=i,Boolean("A"===d?.tagName&&d?.href));var d;const u=r&&(o?a:!l),p="Enter"===e.key,h=" "===e.key,m=i.getAttribute("role"),f=m?.startsWith("menuitem")||"option"===m||"gridcell"===m;if(r&&c&&h){if(e.defaultPrevented&&f)return;return e.preventDefault(),void(l||o&&a?(i.click(),e.preventBaseUIHandler()):u&&(t?.(e),e.preventBaseUIHandler()))}u&&(o||!h&&!p||e.preventDefault(),!o&&p&&t?.(e))},onKeyUp(e){n||(Wu(e),i?.(e),e.target===e.currentTarget&&o&&c&&Yu(e.currentTarget)&&" "===e.key?e.preventDefault():e.baseUIHandlerPrevented||e.target!==e.currentTarget||o||c||" "!==e.key||t?.(e))},onPointerDown(e){n?e.preventDefault():a?.(e)}},o?void 0:{role:"button"},d,l)},[n,d,c,o]),buttonRef:zu(e=>{a.current=e,u()})}}function Yu(e){return Iu(e)&&"BUTTON"===e.tagName}function Ku(e,t,n,r){const i=Au(Qu).current;return function(e,t,n,r,i){return e.refs[0]!==t||e.refs[1]!==n||e.refs[2]!==r||e.refs[3]!==i}(i,e,t,n,r)&&Xu(i,[e,t,n,r]),i.callback}function Qu(){return{callback:null,cleanup:null,refs:[]}}function Xu(e,t){e.refs=t,t.every(e=>null==e)?e.callback=null:e.callback=n=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),null!=n){const r=Array(t.length).fill(null);for(let e=0;e<t.length;e+=1){const i=t[e];if(null!=i)switch(typeof i){case"function":{const t=i(n);"function"==typeof t&&(r[e]=t);break}case"object":i.current=n}}e.cleanup=()=>{for(let e=0;e<t.length;e+=1){const n=t[e];if(null!=n)switch(typeof n){case"function":{const t=r[e];"function"==typeof t?t():n(null);break}case"object":n.current=null}}}}}}var ep=parseInt(e.version,10);function tp(t){if(!/* @__PURE__ */e.isValidElement(t))return null;const n=t,r=n.props;return(ep>=19?r?.ref:n.ref)??null}Object.freeze([]);var np=Object.freeze({});function rp(t,n,i={}){const o=n.render,s=function(e,t={}){const{className:n,style:r,render:i}=e,{state:o=np,ref:s,props:a,stateAttributesMapping:l,enabled:c=!0}=t,d=c?function(e,t){return"function"==typeof e?e(t):e}(n,o):void 0,u=c?function(e,t){return"function"==typeof e?e(t):e}(r,o):void 0,p=c?function(e,t){const n={};for(const r in e){const i=e[r];if(t?.hasOwnProperty(r)){const e=t[r](i);null!=e&&Object.assign(n,e);continue}!0===i?n[`data-${r.toLowerCase()}`]="":i&&(n[`data-${r.toLowerCase()}`]=i.toString())}return n}(o,l):np,h=c?Pu(p,Array.isArray(a)?function(e){if(0===e.length)return Lu;if(1===e.length)return Uu(e[0],Lu);let t={...Uu(e[0],Lu)};for(let n=1;n<e.length;n+=1)t=$u(t,e[n]);return t}(a):a)??np:np;"undefined"!=typeof document&&(c?Array.isArray(s)?h.ref=function(e){const t=Au(Qu).current;return function(e,t){return e.refs.length!==t.length||e.refs.some((e,n)=>e!==t[n])}(t,e)&&Xu(t,e),t.callback}([h.ref,tp(i),...s]):h.ref=Ku(h.ref,tp(i),s):Ku(null,null));if(!c)return np;void 0!==d&&(h.className=Gu(h.className,d));void 0!==u&&(h.style=Pu(h.style,u));return h}(n,i);return!1===i.enabled?null:function(t,n,i,o){if(n){if("function"==typeof n)return n(i,o);const t=Du(i,n.props);t.ref=i.ref;let r=n;return r?.$$typeof===ip&&(r=e.Children.toArray(n)[0]),/* @__PURE__ */e.cloneElement(r,t)}if(t&&"string"==typeof t)return function(t,n){return"button"===t?/* @__PURE__ */r("button",{type:"button",...n,key:n.key}):"img"===t?/* @__PURE__ */r("img",{alt:"",...n,key:n.key}):/* @__PURE__ */e.createElement(t,n)}(t,i);throw new Error(Vu(8))}(t,o,s,i.state??np)}var ip=Symbol.for("react.lazy");var op=/* @__PURE__ */e.forwardRef(function(e,t){const{render:n,className:r,disabled:i=!1,focusableWhenDisabled:o=!1,nativeButton:s=!0,...a}=e,{getButtonProps:l,buttonRef:c}=Ju({disabled:i,focusableWhenDisabled:o,native:s});return rp("button",e,{state:{disabled:i},ref:[t,c],props:[a,l]})}),sp={primary:"bg-primary text-primary-foreground border-transparent hover:bg-primary/90",secondary:"bg-secondary text-secondary-foreground border-transparent hover:bg-secondary/80",ghost:"bg-transparent text-foreground border-border hover:bg-muted",bare:"bg-transparent text-inherit border-transparent hover:bg-transparent p-0 min-h-0"},ap={sm:"px-2 py-1 text-xs min-h-7",md:"px-4 py-2 text-sm min-h-9"},lp=i(function({className:e,disabled:t,full:n,size:r="md",type:i="button",variant:o="primary",...s},a){/* @__PURE__ */
@@ -15,7 +15,7 @@ return f(ku,{className:"fixed",style:{zIndex:b,maxWidth:"420px",opacity:l?0:1,tr
15
15
  return g(ku,{ref:_,className:`${O} ${C?"":z} ${S?"":"transition-transform duration-300 ease-in-out"}`,style:{zIndex:p,pointerEvents:e?"none":"auto",...R,...C},children:[/* @__PURE__ */g(ku,{className:`\n group relative w-14 h-14 overflow-visible transition-all duration-300 ease-in-out\n ${e?"scale-0 opacity-0 pointer-events-none":"scale-100 opacity-100 hover:scale-110"}\n `,children:[w&&/* @__PURE__ */f(ku,{className:v,"aria-hidden":!0}),b&&!S&&/* @__PURE__ */f(lp,{type:"button",variant:"secondary",size:"sm",onClick:e=>{e.preventDefault(),e.stopPropagation(),o?.()},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 "+(h.includes("left")?"left-full ml-2":"right-full mr-2"),style:{border:"1px solid rgba(255,255,255,0.25)"},"aria-label":"Stop running task",children:"Stop"}),
16
16
  /* @__PURE__ */f(lp,{type:"button",variant:"bare",onClick:()=>{Date.now()<M.current||i()},onDragStart:e=>e.preventDefault(),onPointerDown:I,onPointerMove:E,onPointerUp:A,onPointerCancel:T,className:"relative z-10 w-14 h-14 min-w-14",style:{touchAction:"none",cursor:S?"grabbing":"grab",userSelect:"none",WebkitUserSelect:"none"},"aria-label":e?"Close":"Open","aria-live":"polite",children:/* @__PURE__ */f(cp,{className:"w-full h-full items-center justify-center relative",children:/* @__PURE__ */g(ku,{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:l,backgroundColor:e?a:s,boxShadow:Ep},children:[w&&/* @__PURE__ */f("svg",{className:x,viewBox:"0 0 54 54",fill:"none","aria-hidden":!0,children:/* @__PURE__ */f("rect",{x:"1.25",y:"1.25",width:"51.5",height:"51.5",rx:k+1,ry:k+1})}),
17
17
  /* @__PURE__ */f(cp,{className:"absolute inset-0 items-center justify-center transition-[transform,opacity] duration-[160ms] linear",style:{transform:e?"rotate(30deg) scale(0)":"rotate(0deg) scale(1)",opacity:e?0:1,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":e,children:/* @__PURE__ */f(Cu,{src:_u,alt:"",className:"relative z-10 w-full h-full object-contain",draggable:!1,onDragStart:e=>e.preventDefault(),style:{borderRadius:l,border:"none",outline:"none",backgroundColor:"transparent",pointerEvents:"none",userSelect:"none"}})}),
18
- /* @__PURE__ */f(cp,{className:"absolute inset-0 items-center justify-center transition-[transform,opacity] duration-[160ms] linear",style:{transform:e?"rotate(0deg) scale(1)":"rotate(-30deg) scale(0)",opacity:e?1:0,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":!e,children:/* @__PURE__ */f(up,{name:"chevronDown",size:24,className:"relative z-10 text-foreground pointer-events-none"})})]})})})]}),!e&&/* @__PURE__ */g(ku,{className:`absolute bottom-16 ${h.includes("left")?"left-0":"right-0"} mb-2 px-3 py-2 text-sm rounded-lg shadow-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity duration-200`,style:{backgroundColor:c,color:d},children:[/* @__PURE__ */f(vp,{as:"span",className:"text-inherit",children:"Support Agent"}),/* @__PURE__ */f(ku,{"aria-hidden":!0,className:`absolute top-full ${h.includes("left")?"left-4":"right-4"} w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent`,style:{borderTopColor:c}})]})]})},Pp="3.2.183";function Lp(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!e.hasAttribute("aria-hidden"))}function Dp(e){if(!e)return 360;const t=parseInt(e.replace(/px|rem|em/gi,""),10);return isNaN(t)?360:t}function $p(e,t,n){return Math.min(Math.max(e,t),n)}function jp(e,t,n,r,i){const o={"bottom-right":"nwse-resize","bottom-left":"nesw-resize","top-right":"nesw-resize","top-left":"nwse-resize"};switch(e){case"bottom-right":return{dx:r-t,dy:i-n,cursor:o[e]};case"bottom-left":return{dx:t-r,dy:i-n,cursor:o[e]};case"top-right":return{dx:r-t,dy:n-i,cursor:o[e]};case"top-left":return{dx:t-r,dy:n-i,cursor:o[e]}}}var Fp={live:"inline-flex items-center gap-1",status:"inline-flex items-center text-[9px] font-medium px-1.5 py-0.5 rounded"},Up=i(function({variant:e,className:t,style:n,children:r,...i},o){/* @__PURE__ */
18
+ /* @__PURE__ */f(cp,{className:"absolute inset-0 items-center justify-center transition-[transform,opacity] duration-[160ms] linear",style:{transform:e?"rotate(0deg) scale(1)":"rotate(-30deg) scale(0)",opacity:e?1:0,transitionProperty:"transform, opacity",transitionDuration:"0.16s, 0.08s",transitionTimingFunction:"linear"},"aria-hidden":!e,children:/* @__PURE__ */f(up,{name:"chevronDown",size:24,className:"relative z-10 text-foreground pointer-events-none"})})]})})})]}),!e&&/* @__PURE__ */g(ku,{className:`absolute bottom-16 ${h.includes("left")?"left-0":"right-0"} mb-2 px-3 py-2 text-sm rounded-lg shadow-lg whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity duration-200`,style:{backgroundColor:c,color:d},children:[/* @__PURE__ */f(vp,{as:"span",className:"text-inherit",children:"Support Agent"}),/* @__PURE__ */f(ku,{"aria-hidden":!0,className:`absolute top-full ${h.includes("left")?"left-4":"right-4"} w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent`,style:{borderTopColor:c}})]})]})},Pp="3.2.195";function Lp(e){return Array.from(e.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>null!==e.offsetParent&&!e.hasAttribute("aria-hidden"))}function Dp(e){if(!e)return 360;const t=parseInt(e.replace(/px|rem|em/gi,""),10);return isNaN(t)?360:t}function $p(e,t,n){return Math.min(Math.max(e,t),n)}function jp(e,t,n,r,i){const o={"bottom-right":"nwse-resize","bottom-left":"nesw-resize","top-right":"nesw-resize","top-left":"nwse-resize"};switch(e){case"bottom-right":return{dx:r-t,dy:i-n,cursor:o[e]};case"bottom-left":return{dx:t-r,dy:i-n,cursor:o[e]};case"top-right":return{dx:r-t,dy:n-i,cursor:o[e]};case"top-left":return{dx:t-r,dy:n-i,cursor:o[e]}}}var Fp={live:"inline-flex items-center gap-1",status:"inline-flex items-center text-[9px] font-medium px-1.5 py-0.5 rounded"},Up=i(function({variant:e,className:t,style:n,children:r,...i},o){/* @__PURE__ */
19
19
  return g("span",{...i,ref:o,className:yu(Fp[e],t),"data-variant":e,style:n,children:["live"===e&&/* @__PURE__ */g("span",{className:"relative flex h-1.5 w-1.5",children:[/* @__PURE__ */f("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-current opacity-75"}),/* @__PURE__ */f("span",{className:"relative inline-flex h-1.5 w-1.5 rounded-full bg-current"})]}),r]})}),Bp=i(function({className:e,style:t,children:n,...r},i){/* @__PURE__ */
20
20
  return f("div",{...r,ref:i,className:yu(e),style:{padding:"8px 12px",borderRadius:"var(--radius-xl, 12px)",border:"1px solid transparent",backgroundColor:"#ffffff",boxShadow:Sp,...t},children:n})});var Wp=n(null);function Gp(e){const t=s(Wp);if(!t)throw new Error(`${e} must be used within Dialog`);return t}function Hp({children:e,onOpenChange:t,open:n}){const{isOpen:r,setIsOpen:i}=function({defaultOpen:e=!1,onOpenChange:t,open:n}){const[r,i]=p(e),s=void 0!==n;return{isOpen:s?n:r,setIsOpen:o(e=>{s||i(e),t?.(e)},[s,t])}}({onOpenChange:t,open:n}),s=l(),a=l(),c=l(),u=d(()=>({contentId:s,descriptionId:c,open:r,setOpen:i,titleId:a}),[s,c,r,i,a]);/* @__PURE__ */
21
21
  return f(Wp.Provider,{value:u,children:e})}function Zp({children:e,className:t,onKeyDown:n,...r}){const i=Gp("DialogContent");return a(()=>{if(!i.open)return;const e=e=>{"Escape"===e.key&&i.setOpen(!1)};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[i]),i.open?/* @__PURE__ */f("div",{...r,"aria-describedby":i.descriptionId,"aria-labelledby":i.titleId,"aria-modal":"true",className:yu("fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 z-[calc(var(--layer-dialog)+1)] flex flex-col w-full max-w-[500px] max-h-[85vh] overflow-auto bg-card rounded-lg shadow-xl p-6 animate-dialog-content-in",t),"data-state":"open",id:i.contentId,onKeyDown:e=>{n?.(e),e.defaultPrevented||"Escape"!==e.key||i.setOpen(!1)},role:"dialog",tabIndex:-1,children:e}):null}function Vp({className:e,...t}){const n=Gp("DialogTitle");/* @__PURE__ */