orquesta-embed 0.2.0 → 0.2.1
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/core/version.d.ts +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/vanilla.js +1 -1
- package/dist/vanilla.min.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import o,{createContext as r,useState as i,useContext as s,useRef as a,useEffect as l,useCallback as c}from"react";const d="0.1.38",h=Object.create(null);h.open="0",h.close="1",h.ping="2",h.pong="3",h.message="4",h.upgrade="5",h.noop="6";const p=Object.create(null);Object.keys(h).forEach(e=>{p[h[e]]=e});const u={type:"error",data:"parser error"},m="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),g="function"==typeof ArrayBuffer,f=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,b=({type:e,data:t},n,o)=>m&&t instanceof Blob?n?o(t):x(t,o):g&&(t instanceof ArrayBuffer||f(t))?n?o(t):x(new Blob([t]),o):o(h[e]+(t||"")),x=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function y(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let w;const v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)k[v.charCodeAt(e)]=e;const C="function"==typeof ArrayBuffer,N=(e,t)=>{if("string"!=typeof e)return{type:"message",data:q(e,t)};const n=e.charAt(0);if("b"===n)return{type:"message",data:S(e.substring(1),t)};return p[n]?e.length>1?{type:p[n],data:e.substring(1)}:{type:p[n]}:u},S=(e,t)=>{if(C){const n=(e=>{let t,n,o,r,i,s=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const c=new ArrayBuffer(s),d=new Uint8Array(c);for(t=0;t<a;t+=4)n=k[e.charCodeAt(t)],o=k[e.charCodeAt(t+1)],r=k[e.charCodeAt(t+2)],i=k[e.charCodeAt(t+3)],d[l++]=n<<2|o>>4,d[l++]=(15&o)<<4|r>>2,d[l++]=(3&r)<<6|63&i;return c})(e);return q(n,t)}return{base64:!0,data:e}},q=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,E=String.fromCharCode(30);function _(){return new TransformStream({transform(e,t){!function(e,t){m&&e.data instanceof Blob?e.data.arrayBuffer().then(y).then(t):g&&(e.data instanceof ArrayBuffer||f(e.data))?t(y(e.data)):b(e,!1,e=>{w||(w=new TextEncoder),t(w.encode(e))})}(e,n=>{const o=n.length;let r;if(o<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,o);else if(o<65536){r=new Uint8Array(3);const e=new DataView(r.buffer);e.setUint8(0,126),e.setUint16(1,o)}else{r=new Uint8Array(9);const e=new DataView(r.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(o))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(n)})}})}let z;function L(e){return e.reduce((e,t)=>e+t.length,0)}function A(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let o=0;for(let r=0;r<t;r++)n[r]=e[0][o++],o===e[0].length&&(e.shift(),o=0);return e.length&&o<e[0].length&&(e[0]=e[0].slice(o)),n}function O(e){if(e)return function(e){for(var t in O.prototype)e[t]=O.prototype[t];return e}(e)}O.prototype.on=O.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},O.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},O.prototype.off=O.prototype.removeListener=O.prototype.removeAllListeners=O.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,o=this._callbacks["$"+e];if(!o)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<o.length;r++)if((n=o[r])===t||n.fn===t){o.splice(r,1);break}return 0===o.length&&delete this._callbacks["$"+e],this},O.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],o=1;o<arguments.length;o++)t[o-1]=arguments[o];if(n){o=0;for(var r=(n=n.slice(0)).length;o<r;++o)n[o].apply(this,t)}return this},O.prototype.emitReserved=O.prototype.emit,O.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},O.prototype.hasListeners=function(e){return!!this.listeners(e).length};const T="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function H(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const M=R.setTimeout,P=R.clearTimeout;function j(e,t){t.useNativeTimers?(e.setTimeoutFn=M.bind(R),e.clearTimeoutFn=P.bind(R)):(e.setTimeoutFn=R.setTimeout.bind(R),e.clearTimeoutFn=R.clearTimeout.bind(R))}function B(e){return"string"==typeof e?function(e){let t=0,n=0;for(let o=0,r=e.length;o<r;o++)t=e.charCodeAt(o),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(o++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function I(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class $ extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class D extends O{constructor(e){super(),this.writable=!1,j(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new $(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=N(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class W extends D{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(E),o=[];for(let e=0;e<n.length;e++){const r=N(n[e],t);if(o.push(r),"error"===r.type)break}return o})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,o=new Array(n);let r=0;e.forEach((e,i)=>{b(e,!1,e=>{o[i]=e,++r===n&&t(o.join(E))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=I()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let F=!1;try{F="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const U=F;function V(){}class Q extends W{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class K extends O{constructor(e,t,n){super(),this.createRequest=e,j(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=H(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=K.requestsCount++,K.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=V,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete K.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(K.requestsCount=0,K.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",X);else if("function"==typeof addEventListener){addEventListener("onpagehide"in R?"pagehide":"unload",X,!1)}function X(){for(let e in K.requests)K.requests.hasOwnProperty(e)&&K.requests[e].abort()}const Y=function(){const e=J({xdomain:!1});return e&&null!==e.responseType}();function J(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||U))return new XMLHttpRequest}catch(e){}if(!t)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const G="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Z extends D{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=G?{}:H(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],o=t===e.length-1;b(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}o&&T(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=I()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ee=R.WebSocket||R.MozWebSocket;const te={websocket:class extends Z{createSocket(e,t,n){return G?new ee(e,t,n):t?new ee(e,t):new ee(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends D{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){z||(z=new TextDecoder);const n=[];let o=0,r=-1,i=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===o){if(L(n)<1)break;const e=A(n,1);i=!(128&~e[0]),r=127&e[0],o=r<126?3:126===r?1:2}else if(1===o){if(L(n)<2)break;const e=A(n,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),o=3}else if(2===o){if(L(n)<8)break;const e=A(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(u);break}r=i*Math.pow(2,32)+t.getUint32(4),o=3}else{if(L(n)<r)break;const e=A(n,r);a.enqueue(N(i?e:z.decode(e),t)),o=0}if(0===r||r>e){a.enqueue(u);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),o=_();o.readable.pipeTo(e.writable),this._writer=o.writable.getWriter();const r=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),r())}).catch(e=>{})};r();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],o=t===e.length-1;this._writer.write(n).then(()=>{o&&T(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Q{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Y&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new K(J,this.uri(),e)}}},ne=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,oe=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function re(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),o=e.indexOf("]");-1!=n&&-1!=o&&(e=e.substring(0,n)+e.substring(n,o).replace(/:/g,";")+e.substring(o,e.length));let r=ne.exec(e||""),i={},s=14;for(;s--;)i[oe[s]]=r[s]||"";return-1!=n&&-1!=o&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=/\/{2,9}/g,o=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||o.splice(0,1);"/"==t.slice(-1)&&o.splice(o.length-1,1);return o}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,o){t&&(n[t]=o)}),n}(0,i.query),i}const ie="function"==typeof addEventListener&&"function"==typeof removeEventListener,se=[];ie&&addEventListener("offline",()=>{se.forEach(e=>e())},!1);class ae extends O{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=re(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=re(t.host).host);j(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,o=n.length;e<o;e++){let o=n[e].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}(this.opts.query)),ie&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},se.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&ae.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",ae.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=B(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,T(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,o){if("function"==typeof t&&(o=t,t=void 0),"function"==typeof n&&(o=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),o&&this.once("flush",o),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(ae.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ie&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=se.indexOf(this._offlineEventListener);-1!==e&&se.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}ae.protocol=4;class le extends ae{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;ae.priorWebsocketSuccess=!1;const o=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ae.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function r(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function s(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&r()}const c=()=>{t.removeListener("open",o),t.removeListener("error",i),t.removeListener("close",s),this.off("close",a),this.off("upgrading",l)};t.once("open",o),t.once("error",i),t.once("close",s),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let ce=class extends le{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>te[e]).filter(e=>!!e)),super(e,n)}};const de="function"==typeof ArrayBuffer,he=Object.prototype.toString,pe="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===he.call(Blob),ue="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===he.call(File);function me(e){return de&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||pe&&e instanceof Blob||ue&&e instanceof File}function ge(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ge(e[t]))return!0;return!1}if(me(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ge(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ge(e[t]))return!0;return!1}function fe(e){const t=[],n=e.data,o=e;return o.data=be(n,t),o.attachments=t.length,{packet:o,buffers:t}}function be(e,t){if(!e)return e;if(me(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let o=0;o<e.length;o++)n[o]=be(e[o],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=be(e[o],t));return n}return e}function xe(e,t){return e.data=ye(e.data,t),delete e.attachments,e}function ye(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ye(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ye(e[n],t));return e}const we=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ve;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(ve||(ve={}));class ke extends O{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===ve.BINARY_EVENT;n||t.type===ve.BINARY_ACK?(t.type=n?ve.EVENT:ve.ACK,this.reconstructor=new Ce(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!me(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===ve[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ve.BINARY_EVENT||n.type===ve.BINARY_ACK){const o=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const r=e.substring(o,t);if(r!=Number(r)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const i=Number(r);if(!Ne(i)||i<0)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===e.charAt(t+1)){const o=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(o,t)}else n.nsp="/";const o=e.charAt(t+1);if(""!==o&&Number(o)==o){const o=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(o,t+1))}if(e.charAt(++t)){const o=this.tryParse(e.substr(t));if(!ke.isPayloadValid(n.type,o))throw new Error("invalid payload");n.data=o}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case ve.CONNECT:return Se(t);case ve.DISCONNECT:return void 0===t;case ve.CONNECT_ERROR:return"string"==typeof t||Se(t);case ve.EVENT:case ve.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===we.indexOf(t[0]));case ve.ACK:case ve.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ce{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=xe(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Ne=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function Se(e){return"[object Object]"===Object.prototype.toString.call(e)}var qe=Object.freeze({__proto__:null,Decoder:ke,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==ve.EVENT&&e.type!==ve.ACK||!ge(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===ve.EVENT?ve.BINARY_EVENT:ve.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==ve.BINARY_EVENT&&e.type!==ve.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=fe(e),n=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(n),o}},get PacketType(){return ve},isPacketValid:function(e){return"string"==typeof e.nsp&&(void 0===(t=e.id)||Ne(t))&&function(e,t){switch(e){case ve.CONNECT:return void 0===t||Se(t);case ve.DISCONNECT:return void 0===t;case ve.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===we.indexOf(t[0]));case ve.ACK:return Array.isArray(t);case ve.CONNECT_ERROR:return"string"==typeof t||Se(t);default:return!1}}(e.type,e.data);var t},protocol:5});function Ee(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const _e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ze extends O{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Ee(e,"open",this.onopen.bind(this)),Ee(e,"packet",this.onpacket.bind(this)),Ee(e,"error",this.onerror.bind(this)),Ee(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,o,r;if(_e.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:ve.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const s=null===(o=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===o?void 0:o.writable,a=this.connected&&!(null===(r=this.io.engine)||void 0===r?void 0:r._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const o=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===o)return void(this.acks[e]=t);const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},o),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,o)=>{const r=(e,t)=>e?o(e):n(t);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...o)=>{this._queue[0];return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...o)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ve.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ve.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ve.EVENT:case ve.BINARY_EVENT:this.onevent(e);break;case ve.ACK:case ve.BINARY_ACK:this.onack(e);break;case ve.DISCONNECT:this.ondisconnect();break;case ve.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...o){n||(n=!0,t.packet({type:ve.ACK,id:e,data:o}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ve.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function Le(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Le.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},Le.prototype.reset=function(){this.attempts=0},Le.prototype.setMin=function(e){this.ms=e},Le.prototype.setMax=function(e){this.max=e},Le.prototype.setJitter=function(e){this.jitter=e};class Ae extends O{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,j(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Le({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const o=t.parser||qe;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ce(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const o=Ee(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=Ee(t,"error",r);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{o(),r(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(o),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Ee(e,"ping",this.onping.bind(this)),Ee(e,"data",this.ondata.bind(this)),Ee(e,"error",this.onerror.bind(this)),Ee(e,"close",this.onclose.bind(this)),Ee(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){T(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new ze(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Oe={};function Te(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let o=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),o=re(e)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";const r=-1!==o.host.indexOf(":")?"["+o.host+"]":o.host;return o.id=o.protocol+"://"+r+":"+o.port+t,o.href=o.protocol+"://"+r+(n&&n.port===o.port?"":":"+o.port),o}(e,(t=t||{}).path||"/socket.io"),o=n.source,r=n.id,i=n.path,s=Oe[r]&&i in Oe[r].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new Ae(o,t):(Oe[r]||(Oe[r]=new Ae(o,t)),a=Oe[r]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(Te,{Manager:Ae,Socket:ze,io:Te,connect:Te});const Re={mode:"widget",position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class He{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[],isSubmitting:!1,promptQueue:[],outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}setConnected(e,t,n){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:e,projectName:t,agentOnline:n})}setConnectionError(e){this.setState({isConnected:!1,isConnecting:!1,connectionError:e})}setOpen(e){this.setState({isOpen:e})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(e){this.setState({activeTab:e})}setCurrentPrompt(e){this.setState({currentPrompt:e}),e&&!this.state.promptHistory.find(t=>t.id===e.id)&&this.setState({promptHistory:[e,...this.state.promptHistory].slice(0,50)})}updatePrompt(e,t){this.state.currentPrompt?.id===e&&this.setState({currentPrompt:{...this.state.currentPrompt,...t}}),this.setState({promptHistory:this.state.promptHistory.map(n=>n.id===e?{...n,...t}:n)})}addOutputLine(e){const t={...e,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,t]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(e){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[e]:[...this.state.outputLines]}})}addToQueue(e){this.setState({promptQueue:[...this.state.promptQueue,e]})}getNextFromQueue(){if(0===this.state.promptQueue.length)return null;const[e,...t]=this.state.promptQueue;return this.setState({promptQueue:t}),e}clearQueue(){this.setState({promptQueue:[]})}getQueueLength(){return this.state.promptQueue.length}setSelectedElement(e){this.setState({selectedElement:e,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(e){this.setState({overlayMode:e}),"off"===e&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(e){this.setState({highlightedPromptId:e})}setElementMarkers(e){this.setState({elementMarkers:e})}setCommentsForPrompt(e,t){this.setState({comments:{...this.state.comments,[e]:t}})}addComment(e,t){const n=this.state.comments[e]||[];this.setState({comments:{...this.state.comments,[e]:[...n,t]}}),this.setState({promptHistory:this.state.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)})}setExpandedPromptId(e){this.setState({expandedPromptId:e})}setLoadingComments(e){this.setState({isLoadingComments:e})}addConsoleLogs(e){this.setState({consoleLogs:[...this.state.consoleLogs,...e].slice(-100)})}addNetworkLogs(e){this.setState({networkLogs:[...this.state.networkLogs,...e].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}toggleIncludeHistory(){this.setState({includeHistory:!this.state.includeHistory})}toggleIncludeContext(){this.setState({includeContext:!this.state.includeContext})}setAuth(e,t){this.setState({user:e,isAuthenticated:t,isAuthenticating:!1,authError:null})}setAuthenticating(e){this.setState({isAuthenticating:e})}setAuthError(e){this.setState({authError:e,isAuthenticating:!1})}setRequireAuth(e){this.setState({requireAuth:e})}reset(){this.state=this.getInitialState(),this.notify()}}class Me{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const e=e=>(...t)=>{const n=this.createEntry(e,t);this.addEntry(n),this.originalConsole?.[e](...t)};console.log=e("log"),console.info=e("info"),console.warn=e("warn"),console.error=e("error"),this.errorHandler=e=>{const t=this.createEntry("error",[e.message],e.error?.stack);this.addEntry(t)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{const t=e.reason instanceof Error?e.reason.message:String(e.reason),n=e.reason instanceof Error?e.reason.stack:void 0,o=this.createEntry("error",[`Unhandled Promise Rejection: ${t}`],n);this.addEntry(o)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}formatArg(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{const t=JSON.stringify(e,null,2);if("{}"===t||"[]"===t){const t=Object.prototype.toString.call(e);if("[object Object]"!==t&&"[object Array]"!==t)return t}return t}catch{return Object.prototype.toString.call(e)}return String(e)}createEntry(e,t,n){const o=t.map(e=>this.formatArg(e)).join(" ");return{timestamp:Date.now(),level:e,message:o||"(empty)",args:t,stack:n}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>"error"===e.level||"warn"===e.level)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getRecent(20);return 0===t.length?"":t.map(e=>`${`[${new Date(e.timestamp).toISOString()}] [${e.level.toUpperCase()}]`} ${e.message}${e.stack?`\n${e.stack}`:""}`).join("\n")}}class Pe{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{const n="string"==typeof e?e:e instanceof URL?e.href:e.url,o=t?.method||"GET",r=Date.now(),i={timestamp:r,method:o,url:n,requestBody:t?.body};try{const n=await this.originalFetch(e,t);if(i.status=n.status,i.duration=Date.now()-r,!n.ok)try{const e=n.clone();i.responseBody=await e.text()}catch{}return this.addEntry(i),n}catch(e){throw i.duration=Date.now()-r,i.error=e instanceof Error?e.message:String(e),this.addEntry(i),e}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const e=this,t=new WeakMap;XMLHttpRequest.prototype.open=function(n,o,...r){return t.set(this,{method:n,url:"string"==typeof o?o:o.href,startTime:0}),e.originalXHROpen.apply(this,[n,o,...r])},XMLHttpRequest.prototype.send=function(n){const o=t.get(this);return o&&(o.startTime=Date.now(),this.addEventListener("loadend",()=>{const t={timestamp:o.startTime,method:o.method,url:o.url,status:this.status,duration:Date.now()-o.startTime};if(this.status>=400||0===this.status){t.error=this.statusText||"Request failed";try{t.responseBody=this.responseText}catch{}}e.addEntry(t)})),e.originalXHRSend.call(this,n)}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>e.status&&e.status>=400||e.error)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getErrors();return 0===t.length?"":t.map(e=>{const t=new Date(e.timestamp).toISOString(),n=e.status?`[${e.status}]`:"[FAILED]";return`[${t}] ${e.method} ${e.url} ${n}${e.error?` - ${e.error}`:""}`}).join("\n")}}class je{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=e=>{if(!this.isActive||!this.highlight)return;const t=document.elementFromPoint(e.clientX,e.clientY);if(!t||t.id?.startsWith("orquesta-"))return;this.selectedElement=t;const n=t.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${n.top}px`,this.highlight.style.left=`${n.left}px`,this.highlight.style.width=`${n.width}px`,this.highlight.style.height=`${n.height}px`;const o=this.highlight.querySelector("#orquesta-element-label");if(o){const e=t.tagName.toLowerCase(),n=t.id?`#${t.id}`:"",r=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";o.textContent=`<${e}${n}${r}>`}},this.handleClick=e=>{if(!this.isActive)return;const t=e.target;if(!t.id?.startsWith("orquesta-")&&(e.preventDefault(),e.stopPropagation(),this.selectedElement)){const e=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(e)}},this.handleKeyDown=e=>{"Escape"===e.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(e){return this.globalRightClickCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const n=this.getElementContext(t);this.globalRightClickCallback?.(n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(e){return this.globalRightClickWithPositionCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const n=this.getElementContext(t),o={x:e.clientX,y:e.clientY};this.globalRightClickWithPositionCallback?.(n,o)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const n=document.createElement("div");n.id="orquesta-selected-element-label",n.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const o=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",i=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Selected: <${o}${r}${i}>`,this.selectedHighlight.appendChild(n);const s=()=>{if(!this.selectedHighlight)return;const e=t.getBoundingClientRect();this.selectedHighlight.style.top=e.top-3+"px",this.selectedHighlight.style.left=e.left-3+"px",this.selectedHighlight.style.width=`${e.width+6}px`,this.selectedHighlight.style.height=`${e.height+6}px`};return s(),this.selectedElementScrollHandler=s,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),t}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(e,t){this.isActive||(this.isActive=!0,this.onSelect=e,this.onCancel=t||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const e=document.createElement("div");e.id="orquesta-element-label",e.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(e)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let n=document.getElementById("orquesta-prompt-highlight");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight",n.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(n));let o=n.querySelector("#orquesta-prompt-highlight-label");o||(o=document.createElement("div"),o.id="orquesta-prompt-highlight-label",o.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',n.appendChild(o));const r=t.tagName.toLowerCase(),i=t.id?`#${t.id}`:"",s=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";o.textContent=`Highlighted: <${r}${i}${s}>`;const a=()=>{const e=t.getBoundingClientRect();n.style.display="block",n.style.top=e.top-3+"px",n.style.left=e.left-3+"px",n.style.width=`${e.width+6}px`,n.style.height=`${e.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=t.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&t.scrollIntoView({behavior:"smooth",block:"center"}),t}catch{return null}}removeHighlight(){const e=document.getElementById("orquesta-prompt-highlight");e&&(e.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}safeQuerySelector(e){try{return document.querySelector(e)}catch{return null}}findElement(e,t){try{let n=this.safeQuerySelector(e);if(n)return n;if(t&&(n=document.getElementById(t),n))return n;const o=e.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(o){const[,e,t]=o;if(n=this.safeQuerySelector(`${e}.${t}`),n)return n}return null}catch{return null}}getElementContext(e){const t=e.getBoundingClientRect(),n={};for(const t of e.attributes)t.name.startsWith("data-")||"class"===t.name||"id"===t.name||(n[t.name]=t.value);return{selector:this.generateSelector(e),tag:e.tagName.toLowerCase(),id:e.id||void 0,className:"string"==typeof e.className?e.className:void 0,textContent:e.textContent?.trim().slice(0,200)||void 0,boundingRect:t,attributes:Object.keys(n).length>0?n:void 0}}isValidCssClass(e){return!/[@:/\[\]()!#]/.test(e)&&!!/^[a-zA-Z_-]/.test(e)}generateSelector(e){if(e.id&&this.isValidCssClass(e.id))return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let e=n.tagName.toLowerCase();if(n.id&&this.isValidCssClass(n.id)){e=`#${n.id}`,t.unshift(e);break}if(n.className&&"string"==typeof n.className){const t=n.className.trim().split(/\s+/).filter(e=>this.isValidCssClass(e)).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}const o=n.parentElement;if(o){const t=Array.from(o.children).filter(e=>e.tagName===n.tagName);if(t.length>1){e+=`:nth-child(${t.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}}class Be{constructor(e,t){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.broadcastChannel=null,this.pollInterval=null,this.token=e,this.apiUrl=t,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(e){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(e))}catch{}}loadSession(){try{const e=localStorage.getItem(this.getStorageKey());if(!e)return null;const t=JSON.parse(e);return t.expiresAt&&new Date(t.expiresAt)<new Date?(this.clearSession(),null):t}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const e=this.loadSession();if(!e)return!1;try{const t=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})});if(!t.ok)return this.clearSession(),!1;const n=await t.json();return n.valid?(this.setState({isAuthenticated:!0,user:n.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0}}login(){return new Promise((e,t)=>{this.setState({isAuthenticating:!0,authError:null});const n=Math.random().toString(36).slice(2),o=`eas_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,r=new URL(`${this.apiUrl}/embed/auth`);r.searchParams.set("token",this.token),r.searchParams.set("origin",window.location.origin),r.searchParams.set("state",n),r.searchParams.set("authSession",o);const i=window.screenX+(window.innerWidth-500)/2,s=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(r.toString(),"orquesta_auth",`width=500,height=600,left=${i},top=${s},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void t(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=n=>{if(n.origin!==new URL(this.apiUrl).origin)return;const{type:o,payload:r}=n.data||{};"orquesta_auth_success"===o?(this.handleAuthSuccess(r),e(r),this.cleanup()):"orquesta_auth_error"===o?(this.handleAuthError(r),t(new Error(r.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===o&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=this.apiUrl.replace("://orquesta.live","://ws.orquesta.live").replace("://localhost:3113","://localhost:3200");this.pollInterval=setInterval(async()=>{try{const n=await fetch(`${a}/auth/result/${o}`);if(!n.ok)return;const r=await n.json();if(r.pending)return;const{type:i,payload:s}=r;"orquesta_auth_success"===i?(this.handleAuthSuccess(s),e(s),this.cleanup()):"orquesta_auth_error"===i&&(this.handleAuthError(s),t(new Error(s.message||"Authentication failed")),this.cleanup())}catch{}},1500);const l=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(l),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(e){const t={user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt};this.saveSession(t),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null})}handleAuthError(e){this.setState({isAuthenticating:!1,authError:e.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const e=this.loadSession();if(e?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const Ie=!1,$e="prompts",De="dark";const We=new class{constructor(){this.projectId=null}setProjectId(e){this.projectId=e}getKey(e){const t=`orquesta_embed_${e}`;return this.projectId?`${t}_${this.projectId}`:t}get(e){try{const t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):null}catch{return null}}set(e,t){try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch{}}remove(e){try{localStorage.removeItem(this.getKey(e))}catch{}}getState(){return{isOpen:this.get("isOpen")??Ie,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??$e,theme:this.get("theme")??De}}setState(e){Object.entries(e).forEach(([e,t])=>{void 0!==t&&this.set(e,t)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(e=>this.remove(e))}};class Fe{constructor(e){this.socket=null,this.channelName=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...Re,...e},this.state=new He,this.consoleCapture=new Me,this.networkCapture=new Pe,this.elementSelector=new je,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new Be(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const e=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!e.ok){const t=await e.json();throw new Error(t.error||"Failed to validate token")}const t=await e.json();if(!t.valid)throw new Error("Invalid embed token");this.projectId=t.projectId,We.setProjectId(t.projectId);const n=t.requireAuth||this.config.requireAuth;n&&!this.authManager?(this.state.setRequireAuth(!0),this.authManager=new Be(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}),await this.authManager.checkSession()):n&&this.state.setRequireAuth(!0),this.channelName=t.channelName;const o=Te("https://ws.orquesta.live",{auth:{embedToken:this.config.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,timeout:1e4});this.socket=o,o.on("output",e=>this.handleOutput(e)),o.on("complete",e=>this.handleComplete(e)),o.on("error",e=>this.handleError(e));let r=!1;o.on("connect",()=>{if(o.emit("subscribe",{channel:t.channelName}),this.state.setConnected(t.projectId,t.project?.name||"Project",t.project?.agent_online||!1),r)return;r=!0,this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(e=>{this.state.addConsoleLogs([e])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(e=>{this.state.addNetworkLogs([e])})),this.setupHotkey(),this.loadTimeline();const e=We.getState();this.state.setState({isOpen:this.config.defaultOpen??e.isOpen,activeTab:e.activeTab||"prompts"}),this.config.onReady?.()}),o.on("connect_error",e=>{const t=e?.message||"Failed to connect to WS server";this.state.setConnectionError(t)}),o.on("disconnect",()=>{this.state.setState({isConnecting:!1})})}catch(e){const t=e instanceof Error?e.message:"Connection failed";throw this.state.setConnectionError(t),this.config.onError?.(e instanceof Error?e:new Error(t)),e}}disconnect(){if(this.socket){if(this.channelName)try{this.socket.emit("unsubscribe",{channel:this.channelName})}catch{}this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null}this.channelName=null,this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const e=this.config.hotkey.toLowerCase().split("+"),t=e.pop(),n=new Set(e);this.hotkeyHandler=e=>{if(!e.key)return;const o=n.has("ctrl")===(e.ctrlKey||e.metaKey),r=n.has("shift")===e.shiftKey,i=n.has("alt")===e.altKey,s=e.key.toLowerCase()===t;o&&r&&i&&s&&(e.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(e){if(!this.state.getState().currentPrompt)return;let t,n,o,r="stdout",i=e.data;"stderr"===e.type?r="stderr":e.data.includes("Tool:")||e.data.includes("tool_call")?r="tool":(e.data.includes("thinking")||e.data.includes("Thinking"))&&(r="thinking");try{const s=JSON.parse(e.data);if(s.type){switch(s.type){case"thinking":r="thinking",i=s.thinking?.content||e.data;break;case"tool_call":r="tool_call",n=s.tool_call?.name,i=`Using ${n||"tool"}`;break;case"tool_result":r="tool_result",n=s.tool_result?.name,o=s.tool_result?.success,i=o?s.tool_result?.output||"Success":s.tool_result?.error||"Failed";break;case"output":r="output",i=s.output?.content||e.data;break;case"error":r="error",i=s.error?.message||e.data;break;case"system":r="system",i=s.system?.message||s.system?.event||e.data;break;case"progress":r="progress";const t=void 0!==s.progress?.percentage?` (${s.progress.percentage}%)`:"";i=(s.progress?.message||"Processing")+t;break;default:i=s.content||s.message||e.data}t=s}}catch{}this.state.addOutputLine({timestamp:e.timestamp||Date.now(),type:r,content:i,details:t,toolName:n,toolSuccess:o})}handleComplete(e){const t=this.state.getState(),n=0===e.exitCode?"completed":"failed",o=t.currentPrompt?.id;if(t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:n,completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),o&&this.config.onPromptComplete&&this.config.onPromptComplete(o,n),this.config.reloadOnComplete&&"completed"===n){const e=this.config.reloadDelay??1500;return console.log(`[Orquesta Embed] Prompt completed. Reloading page in ${e}ms...`),void setTimeout(()=>{window.location.reload()},e)}this.processQueue()}async processQueue(){const e=this.state.getNextFromQueue();if(e){console.log(`[Orquesta Embed] Processing queued prompt. Remaining in queue: ${this.state.getQueueLength()}`);try{await this.submitPrompt(e.content,e.options)}catch(e){console.error("[Orquesta Embed] Failed to process queued prompt:",e),this.processQueue()}}}handleError(e){const t=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${e.error}`}),t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),this.processQueue()}async submitPrompt(e,t){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const n=this.state.getState();if(n.isSubmitting)return this.state.addToQueue({id:`queue-${Date.now()}`,content:e,options:t,queuedAt:Date.now()}),console.log(`[Orquesta Embed] Prompt queued. Queue length: ${this.state.getQueueLength()}`),`queued-${Date.now()}`;this.state.setState({isSubmitting:!0}),this.state.clearOutput();let o=e;const r=t?.elementContext||n.selectedElement;if(r&&(o+=`\n\n--- Element Context ---\nSelector: ${r.selector}\nTag: <${r.tag}>\n${r.id?`ID: ${r.id}`:""}\n${r.className?`Classes: ${r.className}`:""}\n${r.textContent?`Text: ${r.textContent}`:""}\n${r.attributes?`Attributes: ${JSON.stringify(r.attributes)}`:""}`),t?.includeConsole??n.includeConsole){const e=this.consoleCapture.formatForPrompt();e&&(o+=`\n\n--- Console Logs ---\n${e}`)}if(t?.includeNetwork??n.includeNetwork){const e=this.networkCapture.formatForPrompt();e&&(o+=`\n\n--- Network Errors ---\n${e}`)}if(t?.includeHistory??n.includeHistory){const e=n.promptHistory.filter(e=>"completed"===e.status).slice(0,5).reverse();e.length>0&&(o+="\n\n--- Previous Prompts Context ---",e.forEach((e,t)=>{o+=`\n\n[Prompt ${t+1}]: ${e.content}`;const r=n.promptOutputs[e.id];if(r&&r.length>0){const e=r.slice(-10).map(e=>e.content).join("\n");o+=`\n[Output ${t+1}]:\n${e}`}}))}try{const e={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},t=this.authManager?.getSessionToken();t&&(e["X-Session-Token"]=t);const n=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:e,body:JSON.stringify({projectId:this.projectId,content:o,elementContext:r})});if(!n.ok){const e=await n.json();throw new Error(e.error||"Failed to submit prompt")}const i=(await n.json()).prompt;return this.state.setCurrentPrompt(i),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(i.id),i.id}catch(e){throw this.state.setState({isSubmitting:!1}),e}}async loadTimeline(){if(this.projectId)try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const t=await e.json();this.state.setState({promptHistory:t.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),We.set("isOpen",!0)}close(){this.state.setOpen(!1),We.set("isOpen",!1)}toggle(){const e=!this.state.getState().isOpen;this.state.setOpen(e),We.set("isOpen",e)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(e=>this.state.setSelectedElement(e),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(e){return this.state.subscribe(e)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}setActiveTab(e){this.state.setActiveTab(e)}async loadComments(e){if(this.projectId){this.state.setLoadingComments(!0);try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const n=await t.json();this.state.setCommentsForPrompt(e,n.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(e,t){if(this.projectId)try{const n=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:t})});if(n.ok){const t=await n.json();t.comment&&this.state.addComment(e,t.comment)}}catch(e){throw console.error("Failed to add comment:",e),e}}setOverlayMode(e){if(this.state.setOverlayMode(e),"off"===e)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===e){const e=this.state.getState().promptHistory.filter(e=>e.element_context?.selector).map(e=>({promptId:e.id,selector:e.element_context.selector,rect:null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}));this.state.setElementMarkers(e)}else this.state.setElementMarkers([])}highlightPromptElement(e){if(!e.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(e.element_context.selector)?(this.state.setHighlightedPromptId(e.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",e.id)}setupGlobalRightClick(e){return this.elementSelector.setupGlobalRightClick(e)}setupGlobalRightClickWithPosition(e){return this.elementSelector.setupGlobalRightClickWithPosition(e)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const e=await this.authManager.login();return this.config.onLogin?.(e.user),e.user}catch(e){throw e}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}let Ue=!1;function Ve({variant:n="primary",size:o="md",loading:r=!1,disabled:i,className:s="",children:a,...l}){return e("button",{className:`inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-zinc-900 disabled:opacity-50 disabled:cursor-not-allowed ${{primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-zinc-700 text-white hover:bg-zinc-600 focus:ring-zinc-500",ghost:"bg-transparent text-zinc-300 hover:bg-zinc-800 hover:text-white focus:ring-zinc-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500"}[n]} ${{sm:"px-2.5 py-1.5 text-xs",md:"px-3 py-2 text-sm",lg:"px-4 py-2.5 text-base"}[o]} ${s}`,disabled:i||r,...l,children:[r&&e("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),a]})}function Qe({label:n,error:o,className:r="",...i}){return e("div",{className:"w-full",children:[n&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:n}),t("input",{className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed ${o?"border-red-500":""} ${r}`,...i}),o&&t("p",{className:"mt-1.5 text-sm text-red-400",children:o})]})}const Ke=o.forwardRef(function({label:n,error:o,className:r="",...i},s){return e("div",{className:"w-full",children:[n&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:n}),t("textarea",{ref:s,className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed resize-none ${o?"border-red-500":""} ${r}`,...i}),o&&t("p",{className:"mt-1.5 text-sm text-red-400",children:o})]})});function Xe({variant:e="default",size:n="md",children:o,className:r=""}){return t("span",{className:`inline-flex items-center font-medium rounded-full ${{default:"bg-zinc-700 text-zinc-300",success:"bg-green-900/50 text-green-400",warning:"bg-yellow-900/50 text-yellow-400",error:"bg-red-900/50 text-red-400",info:"bg-blue-900/50 text-blue-400"}[e]} ${{sm:"px-1.5 py-0.5 text-xs",md:"px-2 py-1 text-xs"}[n]} ${r}`,children:o})}function Ye({status:e,className:n=""}){return t("span",{className:`inline-block w-2 h-2 rounded-full ${{online:"bg-green-500",offline:"bg-zinc-500",pending:"bg-yellow-500",running:"bg-blue-500 animate-pulse",completed:"bg-green-500",failed:"bg-red-500"}[e]} ${n}`})}const Je=r(null);function Ge(){const e=s(Je);if(!e)throw new Error("Tabs components must be used within a Tabs provider");return e}function Ze({defaultValue:e="",value:n,onChange:o,children:r,className:s=""}){const[a,l]=i(e),c=n??a??"";return t(Je.Provider,{value:{activeTab:c,setActiveTab:e=>{void 0===n&&l(e),o?.(e)}},children:t("div",{className:s,children:r})})}function et({children:e,className:n=""}){return t("div",{className:`flex items-center gap-1 p-1 bg-zinc-800 rounded-lg ${n}`,children:e})}function tt({value:e,children:n,className:o=""}){const{activeTab:r,setActiveTab:i}=Ge();return t("button",{onClick:()=>i(e),className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${r===e?"bg-zinc-700 text-white":"text-zinc-400 hover:text-zinc-300"} ${o}`,children:n})}function nt({value:e,children:n,className:o=""}){const{activeTab:r}=Ge();return r!==e?null:t("div",{className:o,children:n})}const ot=["Change the Shop Now button to green","Add a sale banner at the top","Show discounted prices on products","Make the headline bigger","Switch to dark mode"];function rt({onSubmit:n,isSubmitting:o,selectedElement:r,includeConsole:s,includeNetwork:d,includeContext:h,promptHistory:p,promptOutputs:u,queueLength:m=0,onToggleConsole:g,onToggleNetwork:f,onToggleContext:b,onSelectElement:x,onClearElement:y,agentOnline:w,replyContext:v,onClearReply:k,token:C,apiUrl:N="https://orquesta.live",demoMode:S=!1}){const[q,E]=i(""),[_,z]=i([]),[L,A]=i(!1),[O,T]=i(!1),R=a(null),H=a(null);l(()=>{R.current?.focus()},[]);const M=c(async e=>{if(!C)return null;const t=`temp-${Date.now()}-${Math.random().toString(36).slice(2)}`,n={id:t,name:e.name,type:e.type,size:e.size,url:"",isUploading:!0};z(e=>[...e,n]),A(!0);try{const n=new FormData;n.append("file",e);const o=await fetch(`${N}/api/embed/attachments`,{method:"POST",headers:{Authorization:`Bearer ${C}`},body:n});if(!o.ok){const e=await o.json();throw new Error(e.error||"Upload failed")}const{attachment:r}=await o.json();return z(e=>e.map(e=>e.id===t?{id:r.id,name:r.file_name,type:r.file_type,size:r.file_size,url:r.file_url,isUploading:!1}:e)),{id:r.id,name:r.file_name,type:r.file_type,size:r.file_size,url:r.file_url}}catch(e){return z(n=>n.map(n=>n.id===t?{...n,isUploading:!1,error:e instanceof Error?e.message:"Upload failed"}:n)),null}finally{A(!1)}},[C,N]),P=c(async e=>{if(!C)return;const t=Array.from(e);if(_.length+t.length>5)alert("Maximum 5 files allowed");else for(const e of t)e.size>20971520?alert(`${e.name} exceeds the 10MB limit`):await M(e)},[C,_.length,M]),j=e=>{if(e.preventDefault(),!q.trim()||!w||L)return;const t=_.filter(e=>!e.error&&!e.isUploading).map(e=>e.id);n(q.trim(),r,t.length>0?t:void 0),E(""),z([])};return e("form",{onSubmit:j,className:"orquesta-prompt-input",children:[t("input",{ref:H,type:"file",multiple:!0,onChange:e=>{e.target.files&&e.target.files.length>0&&(P(e.target.files),e.target.value="")},style:{display:"none"},accept:"*/*",disabled:!C}),v&&e("div",{className:"mb-3 p-2.5 bg-green-900/30 border border-green-500/40 rounded-lg",children:[e("div",{className:"flex items-center justify-between mb-1",children:[t("span",{className:"text-xs font-medium text-green-400",children:"↩ Replying to prompt:"}),k&&t("button",{type:"button",onClick:k,className:"text-green-400 hover:text-green-300 text-sm font-bold",children:"×"})]}),e("p",{className:"text-xs text-zinc-300 line-clamp-2",children:[v.prompt.content.slice(0,100),v.prompt.content.length>100&&"..."]}),v.output&&v.output.length>0&&e("p",{className:"text-xs text-zinc-500 mt-1",children:["+ ",v.output.length," output lines as context"]})]}),_.length>0&&t("div",{className:"mb-2 flex flex-wrap gap-1.5",children:_.map(n=>{return e("div",{className:"flex items-center gap-1.5 px-2 py-1 text-xs rounded-md "+(n.error?"bg-red-900/30 border border-red-500/40 text-red-400":"bg-zinc-800 border border-zinc-700 text-zinc-300"),children:[n.isUploading?e("svg",{className:"w-3 h-3 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):n.type.startsWith("image/")?t("span",{children:"🖼️"}):t("span",{children:"📎"}),t("span",{className:"truncate max-w-[80px]",title:n.name,children:n.name}),e("span",{className:"text-zinc-500",children:["(",(o=n.size,o<1024?`${o} B`:o<1048576?`${(o/1024).toFixed(1)} KB`:`${(o/1048576).toFixed(1)} MB`),")"]}),t("button",{type:"button",onClick:()=>(async e=>{const t=_.find(t=>t.id===e);if(z(t=>t.filter(t=>t.id!==e)),t&&!t.id.startsWith("temp-")&&!t.error&&C)try{await fetch(`${N}/api/embed/attachments?id=${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${C}`}})}catch{}})(n.id),className:"ml-0.5 hover:text-white",disabled:n.isUploading,children:"×"})]},n.id);var o})}),e("div",{onDragOver:e=>{e.preventDefault(),e.stopPropagation(),C&&T(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),T(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),T(!1),!C)return;const t=e.dataTransfer.files;t.length>0&&P(t)},className:"relative "+(O?"ring-2 ring-green-500/50 rounded-lg":""),children:[O&&t("div",{className:"absolute inset-0 bg-green-900/30 rounded-lg flex items-center justify-center z-10 pointer-events-none",children:t("span",{className:"text-green-400 text-sm font-medium",children:"Drop files here"})}),t(Ke,{ref:R,value:q,onChange:e=>E(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&j(e)},onPaste:e=>{if(!C)return;const t=e.clipboardData.items,n=[];for(let e=0;e<t.length;e++){const o=t[e];if(o.type.startsWith("image/")){const e=o.getAsFile();e&&n.push(e)}}n.length>0&&(e.preventDefault(),P(n))},placeholder:w?v?"Write your follow-up...":"What would you like to do?":"Agent is offline...",disabled:o||!w,rows:3,className:"min-h-[80px]"})]}),S&&!o&&!q.trim()&&e("div",{className:"mt-2",children:[t("p",{className:"text-[10px] text-zinc-500 mb-1.5",children:"Try these:"}),t("div",{className:"flex flex-wrap gap-1.5",children:ot.map(e=>t("button",{type:"button",onClick:()=>{E(e),setTimeout(()=>{n(e,r),E("")},150)},className:"px-2 py-1 rounded-md text-[10px] font-medium bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-green-900/40 hover:border-green-500/40 hover:text-green-400 transition-all cursor-pointer",children:e},e))})]}),e("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[r&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-blue-900/30 text-blue-400 text-xs rounded-md",children:[t("span",{children:"🎯"}),e("span",{className:"font-mono",children:["<",r.tag,">"]}),t("button",{type:"button",onClick:y,className:"ml-1 hover:text-blue-300",children:"×"})]}),s&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-yellow-900/30 text-yellow-400 text-xs rounded-md",children:[t("span",{children:"📋"}),t("span",{children:"Console logs"}),t("button",{type:"button",onClick:g,className:"ml-1 hover:text-yellow-300",children:"×"})]}),d&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-red-900/30 text-red-400 text-xs rounded-md",children:[t("span",{children:"🌐"}),t("span",{children:"Network errors"}),t("button",{type:"button",onClick:f,className:"ml-1 hover:text-red-300",children:"×"})]}),h&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-purple-900/30 text-purple-400 text-xs rounded-md",children:[t("span",{children:"🔗"}),t("span",{children:"Context (session outputs)"}),t("button",{type:"button",onClick:b,className:"ml-1 hover:text-purple-300",children:"×"})]})]}),e("div",{className:"mt-3 space-y-2.5",children:[e("div",{className:"grid grid-cols-5 gap-1.5",children:[e("button",{type:"button",onClick:x,disabled:o,title:"Select an element to include context",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border ${r?"bg-blue-500/20 text-blue-300 border-blue-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"🎯"}),t("span",{className:"text-[10px]",children:"Element"})]}),e("button",{type:"button",onClick:g,disabled:o,title:"Include recent console logs",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${s?"bg-yellow-500/20 text-yellow-300 border-yellow-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"📋"}),t("span",{className:"text-[10px]",children:"Logs"}),s&&t("span",{className:"absolute top-1 right-1 text-yellow-400 text-[8px]",children:"✓"})]}),e("button",{type:"button",onClick:f,disabled:o,title:"Include network errors",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${d?"bg-red-500/20 text-red-300 border-red-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"🌐"}),t("span",{className:"text-[10px]",children:"Network"}),d&&t("span",{className:"absolute top-1 right-1 text-red-400 text-[8px]",children:"✓"})]}),e("button",{type:"button",onClick:b,disabled:o,title:"Include session outputs as context",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${h?"bg-purple-500/20 text-purple-300 border-purple-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"🔗"}),t("span",{className:"text-[10px]",children:"Context"}),h&&t("span",{className:"absolute top-1 right-1 text-purple-400 text-[8px]",children:"✓"})]}),e("button",{type:"button",onClick:()=>H.current?.click(),disabled:o||!C||L,title:C?"Attach files (up to 10MB each)":"Login to attach files",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${_.length>0?"bg-green-500/20 text-green-300 border-green-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[L?e("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):t("span",{className:"text-base",children:"📎"}),t("span",{className:"text-[10px]",children:"Files"}),_.length>0&&t("span",{className:"absolute top-1 right-1 text-green-400 text-[8px]",children:_.length})]})]}),t(Ve,{type:"submit",variant:"primary",size:"sm",loading:o,disabled:!q.trim()||!w||L,className:"w-full justify-center",children:o?"Running...":"Submit Prompt"})]}),!w&&t("p",{className:"mt-2 text-xs text-yellow-400",children:"⚠️ Agent is offline. Start the agent to submit prompts."}),m>0&&e("div",{className:"mt-2 flex items-center gap-2 px-3 py-2 bg-blue-900/30 border border-blue-500/30 rounded-lg",children:[t("svg",{className:"w-4 h-4 text-blue-400 animate-pulse",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),e("span",{className:"text-xs text-blue-300",children:[m," prompt",m>1?"s":""," queued"]})]}),C&&t("p",{className:"mt-2 text-xs text-zinc-500",children:"💡 Drag & drop files or paste images to attach"}),o&&!C&&t("p",{className:"mt-2 text-xs text-zinc-400",children:"💡 Tip: You can queue more prompts while this one runs"})]})}function it({lines:n,isRunning:o}){const r=a(null);if(l(()=>{r.current&&(r.current.scrollTop=r.current.scrollHeight)},[n]),0===n.length&&!o)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"Output will appear here when running prompts"});const i=(e,t)=>{switch(e){case"stderr":case"error":return"text-red-400";case"tool":case"tool_call":return"text-blue-400";case"tool_result":return t?"text-green-400":"text-red-400";case"thinking":return"text-zinc-500 italic";case"system":return"text-yellow-400";case"progress":return"text-cyan-400";default:return"text-zinc-300"}},s=(e,t)=>{switch(e){case"stderr":case"error":return"✕";case"tool":case"tool_call":return"🔧";case"tool_result":return t?"✓":"✕";case"thinking":return"💭";case"system":return"ℹ";case"progress":return"⏳";default:return"›"}};return e("div",{ref:r,className:"orquesta-log-stream overflow-y-auto max-h-[200px] font-mono text-xs",children:[n.map(n=>e("div",{className:`flex items-start gap-2 py-0.5 ${i(n.type,n.toolSuccess)}`,children:[t("span",{className:"flex-shrink-0 w-4 text-center opacity-50",children:s(n.type,n.toolSuccess)}),e("span",{className:"flex-1 whitespace-pre-wrap break-all",children:[n.toolName&&("tool_call"===n.type||"tool_result"===n.type)&&e("span",{className:"font-medium mr-1",children:["[",n.toolName,"]"]}),n.content]})]},n.id)),o&&e("div",{className:"flex items-center gap-2 py-1 text-blue-400 animate-pulse",children:[t("span",{className:"w-4 text-center",children:"●"}),t("span",{children:"Running..."})]})]})}function st({author:n,size:o="sm",showName:r=!1,className:i=""}){const s={sm:"w-5 h-5 text-[10px]",md:"w-6 h-6 text-xs",lg:"w-8 h-8 text-sm"};return e("div",{className:`flex items-center gap-1.5 ${i}`,children:[n?.avatar_url?t("img",{src:n.avatar_url,alt:n.full_name||"User",className:`${s[o]} rounded-full object-cover ring-1 ring-zinc-700`}):t("div",{className:`${s[o]} ${(e=>{if(!e)return"bg-zinc-600";const t=["bg-blue-600","bg-green-600","bg-purple-600","bg-orange-600","bg-pink-600","bg-cyan-600","bg-indigo-600","bg-teal-600"];return t[e.split("").reduce((e,t)=>e+t.charCodeAt(0),0)%t.length]})(n?.id)} rounded-full flex items-center justify-center font-medium text-white ring-1 ring-zinc-700`,children:(e=>{if(!e)return"?";const t=e.trim().split(" ");return 1===t.length?t[0][0]?.toUpperCase()||"?":(t[0][0]+t[t.length-1][0]).toUpperCase()})(n?.full_name)}),r&&n?.full_name&&t("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:n.full_name})]})}function at({sha:n,url:o,branch:r,className:i=""}){if(!n)return null;const s=n.slice(0,7),a=e("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] font-mono text-zinc-400 hover:bg-zinc-700 hover:text-zinc-300 transition-colors ${i}`,children:[t("svg",{className:"w-3 h-3",fill:"currentColor",viewBox:"0 0 16 16",children:t("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})}),s,r&&e("span",{className:"text-zinc-500",children:["(",r,")"]})]});return o?t("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"inline-flex",onClick:e=>e.stopPropagation(),children:a}):a}function lt(e){const t=new Date(e),n=(new Date).getTime()-t.getTime(),o=Math.floor(n/6e4),r=Math.floor(o/60),i=Math.floor(r/24);return o<1?"just now":o<60?`${o}m`:r<24?`${r}h`:i<7?`${i}d`:t.toLocaleDateString()}function ct({comments:n,isLoading:o=!1,className:r=""}){return o?t("div",{className:`space-y-2 ${r}`,children:[1,2].map(n=>e("div",{className:"flex gap-2 animate-pulse",children:[t("div",{className:"w-5 h-5 bg-zinc-700 rounded-full"}),e("div",{className:"flex-1 space-y-1",children:[t("div",{className:"h-3 bg-zinc-700 rounded w-20"}),t("div",{className:"h-3 bg-zinc-700 rounded w-full"})]})]},n))}):0===n.length?t("div",{className:`text-center text-xs text-zinc-500 py-3 ${r}`,children:"No comments yet"}):t("div",{className:`space-y-3 ${r}`,children:n.map(n=>e("div",{className:"flex gap-2",children:[t(st,{author:n.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:n.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:lt(n.created_at)})]}),t("p",{className:"text-xs text-zinc-400 mt-0.5 break-words",children:n.content})]})]},n.id))})}function dt({onSubmit:n,placeholder:o="Add a comment...",disabled:r=!1,className:s=""}){const[a,l]=i(""),[c,d]=i(!1),h=async e=>{if(e.preventDefault(),a.trim()&&!c&&!r){d(!0);try{await n(a.trim()),l("")}finally{d(!1)}}};return e("form",{onSubmit:h,className:`flex gap-2 ${s}`,children:[t("input",{type:"text",value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),h(e))},placeholder:o,disabled:r||c,className:"flex-1 px-2 py-1.5 bg-zinc-800 border border-zinc-700 rounded text-xs text-white placeholder:text-zinc-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"}),t("button",{type:"submit",disabled:!a.trim()||c||r,className:"px-2 py-1.5 bg-blue-600 text-white text-xs rounded hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:c?e("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):"Post"})]})}function ht({prompts:n,currentPromptId:o,expandedPromptId:r,comments:s={},isLoadingComments:c=!1,promptOutputs:d={},onSelectPrompt:h,onExpandPrompt:p,onHighlightElement:u,onLoadComments:m,onAddComment:g,onReply:f}){const[b,x]=i(null),[y,w]=i(null),v=a(null),k=a(n.length);if(l(()=>{n.length>k.current&&v.current&&(v.current.scrollTop=0),k.current=n.length},[n.length]),0===n.length)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"No prompts yet. Right-click any element to start!"});const C=e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),o=Math.floor(n/6e4),r=Math.floor(n/36e5),i=Math.floor(n/864e5);return o<1?"Just now":o<60?`${o}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:t.toLocaleDateString()},N=e=>{switch(e){case"completed":return"success";case"failed":return"error";case"running":return"info";default:return"default"}};return t("div",{ref:v,className:"orquesta-timeline space-y-2 overflow-y-auto max-h-[400px]",children:n.map(n=>{const i=r===n.id,a=n.id===o,l=b===n.id,v=s[n.id]||[],k=d[n.id]||[],S=y===n.id;return e("div",{className:"rounded-lg border transition-all "+(a?"bg-zinc-800 border-blue-500":"bg-zinc-900 border-zinc-800 hover:border-zinc-700"),onMouseEnter:()=>x(n.id),onMouseLeave:()=>x(null),children:[t("button",{onClick:()=>(e=>{h?.(e),e.element_context&&u&&u(e)})(n),className:"w-full text-left p-3",children:e("div",{className:"flex items-start gap-2",children:[t(st,{author:n.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:n.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:C(n.created_at)})]}),e("p",{className:"text-sm text-zinc-200 line-clamp-2",children:[n.content.slice(0,100),n.content.length>100&&"..."]}),e("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[n.git_commit_sha&&t(at,{sha:n.git_commit_sha,url:n.git_commit_url,branch:n.git_branch}),n.element_context&&e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded-md text-[10px] text-blue-400 font-medium",children:[t("span",{children:"🎯"}),e("span",{children:["<",n.element_context.tag,">"]}),n.element_context.textContent&&e("span",{className:"text-blue-300/70 max-w-[60px] truncate",children:['"',n.element_context.textContent.slice(0,15),'..."']})]}),(n.comment_count||0)>0&&e("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] text-zinc-400",children:["💬 ",n.comment_count]})]})]}),e("div",{className:"flex-shrink-0 flex items-center gap-1.5",children:[t(Ye,{status:n.status}),t(Xe,{variant:N(n.status),size:"sm",children:n.status})]})]})}),e("div",{className:"flex items-center gap-2 px-3 pb-2 -mt-1 "+(l||n.element_context||i||"completed"===n.status||"failed"===n.status?"":"hidden"),children:[n.element_context&&e("button",{onClick:e=>{e.stopPropagation(),u?.(n)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-purple-600/20 border border-purple-500/40 rounded-md text-[11px] text-purple-300 font-medium hover:bg-purple-600/30 hover:border-purple-500/60 transition-all",children:[e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]}),t("span",{children:"Show on page"})]}),("completed"===n.status||"failed"===n.status)&&e("button",{onClick:e=>{e.stopPropagation(),w(S?null:n.id)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium transition-all "+(S?"bg-zinc-600 border border-zinc-500 text-zinc-100":"bg-zinc-700/50 border border-zinc-600/50 text-zinc-300 hover:bg-zinc-700 hover:border-zinc-500"),children:[t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),t("span",{children:S?"Hide output":"View output"})]}),f&&("completed"===n.status||"failed"===n.status)&&e("button",{onClick:e=>{e.stopPropagation(),f(n,k)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-green-600/20 border border-green-500/40 rounded-md text-[11px] text-green-300 font-medium hover:bg-green-600/30 hover:border-green-500/60 transition-all",children:[t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})}),t("span",{children:"Reply"})]}),t("button",{onClick:e=>{e.stopPropagation(),(async e=>{r===e?p?.(null):(p?.(e),m&&!s[e]&&await m(e))})(n.id)},className:"inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium transition-all ml-auto "+(i?"bg-zinc-700 text-zinc-200":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-300"),children:i?"Hide comments":(n.comment_count||0)>0?`💬 ${n.comment_count}`:"+ Comment"})]}),S&&t("div",{className:"px-3 pb-3 border-t border-zinc-800",children:t("div",{className:"mt-2 bg-zinc-950 rounded-md p-2 max-h-[150px] overflow-y-auto",children:k.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:k.slice(-20).map((e,n)=>t("div",{className:""+("stderr"===e.type?"text-red-400":"tool"===e.type?"text-blue-400":"thinking"===e.type?"text-zinc-500 italic":"system"===e.type?"text-yellow-400":"text-zinc-300"),children:e.content},n))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No output recorded for this prompt"})})}),i&&e("div",{className:"px-3 pb-3 pt-1 border-t border-zinc-800 space-y-3",children:[t(ct,{comments:v,isLoading:c}),g&&t(dt,{onSubmit:e=>g(n.id,e),placeholder:"Add a comment..."})]})]},n.id)})})}const pt=400,ut=500;function mt({state:o,position:r,onClose:s,onMinimize:h,onSubmitPrompt:p,onSelectElement:u,onClearElement:m,onToggleConsole:g,onToggleNetwork:f,onToggleHistory:b,onTabChange:x,onExpandPrompt:y,onHighlightElement:w,onLoadComments:v,onAddComment:k,onOverlayModeChange:C,onLogin:N,onLogout:S,onToggleRightClick:q,onExpandToBuilder:E,demoMode:_=!1}){const z=a(null),[L,A]=i(!1),[O,T]=i(!1),[R,H]=i(null),[M,P]=i(()=>We.get("position")||function(e){const t=20;switch(e){case"bottom-right":return{x:window.innerWidth-pt-t,y:window.innerHeight-ut-t};case"bottom-left":return{x:t,y:window.innerHeight-ut-t};case"top-right":return{x:window.innerWidth-pt-t,y:t};case"top-left":return{x:t,y:t}}}(r)),[j,B]=i(()=>We.get("size")||{width:pt,height:ut}),I=a({x:0,y:0}),$=a({width:0,height:0,x:0,y:0});const D=c((e,t)=>{H({prompt:e,output:t}),x("prompts")},[x]),W=c((e,t)=>{p(e,t),H(null)},[p]),F=c(e=>{e.target.closest("button")||(A(!0),I.current={x:e.clientX-M.x,y:e.clientY-M.y})},[M]),U=c(e=>{e.stopPropagation(),T(!0),$.current={width:j.width,height:j.height,x:e.clientX,y:e.clientY}},[j]);return l(()=>{const e=e=>{if(L){const t=Math.max(0,Math.min(window.innerWidth-j.width,e.clientX-I.current.x)),n=Math.max(0,Math.min(window.innerHeight-j.height,e.clientY-I.current.y));P({x:t,y:n})}else if(O){const t=e.clientX-$.current.x,n=e.clientY-$.current.y,o=Math.max(320,$.current.width+t),r=Math.max(400,$.current.height+n);B({width:o,height:r})}},t=()=>{L&&(A(!1),We.set("position",M)),O&&(T(!1),We.set("size",j))};return(L||O)&&(document.addEventListener("mousemove",e),document.addEventListener("mouseup",t)),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[L,O,M,j]),e("div",{ref:z,className:"orquesta-embed-panel fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl flex flex-col overflow-hidden",style:{left:M.x,top:M.y,width:j.width,height:j.height},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700 cursor-move select-none",onMouseDown:F,children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"}),e("span",{className:"text-[10px] text-zinc-500 font-mono",children:["v",d]}),o.projectName&&e("span",{className:"text-xs text-zinc-400",children:["• ",o.projectName]})]}),e("div",{className:"flex items-center gap-1",children:[o.requireAuth&&(o.isAuthenticated&&o.user?e("div",{className:"flex items-center gap-1.5 mr-2",children:[o.user.avatar_url?t("img",{src:o.user.avatar_url,alt:"",className:"w-5 h-5 rounded-full"}):t("div",{className:"w-5 h-5 rounded-full bg-zinc-600 flex items-center justify-center text-xs text-white",children:o.user.full_name?.[0]?.toUpperCase()||"?"}),t("span",{className:"text-xs text-zinc-300 max-w-20 truncate",children:o.user.full_name||"User"}),t("button",{onClick:S,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Sign out",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})})]}):t("button",{onClick:N,disabled:o.isAuthenticating,className:"flex items-center gap-1 px-2 py-1 mr-2 text-xs bg-blue-600 hover:bg-blue-500 disabled:bg-blue-800 text-white rounded transition-colors",children:o.isAuthenticating?e(n,{children:[e("svg",{className:"animate-spin w-3 h-3",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Signing in..."})]}):e(n,{children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"})}),t("span",{children:"Sign in"})]})})),t("div",{className:"flex items-center gap-1 mr-1",title:o.isConnected?o.agentOnline?"Agent online":"Agent offline":"Not connected to Orquesta",children:o.isConnected?t(Ye,{status:o.agentOnline?"online":"offline"}):t("span",{className:"w-2 h-2 rounded-full bg-red-500"})}),t("button",{onClick:q,className:"p-1 rounded text-xs "+(o.rightClickEnabled?"bg-green-600 text-white":"bg-zinc-700 text-zinc-400"),title:o.rightClickEnabled?"Right-click enabled":"Right-click disabled",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"})})}),e("div",{className:"flex items-center gap-0.5 mx-1 bg-zinc-800 rounded p-0.5",children:[t("button",{onClick:()=>C?.("off"),className:"p-1 rounded text-xs "+("off"===o.overlayMode?"bg-zinc-700 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Overlay off",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"})})}),t("button",{onClick:()=>C?.("single"),className:"p-1 rounded text-xs "+("single"===o.overlayMode?"bg-blue-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show selected prompt on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}),t("button",{onClick:()=>C?.("all"),className:"p-1 rounded text-xs "+("all"===o.overlayMode?"bg-purple-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show all prompts on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 11a3 3 0 11-6 0 3 3 0 016 0z"})]})})]}),E&&t("button",{onClick:E,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Expand to builder mode",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5v-4m0 4h-4m4 0l-5-5"})})}),t("button",{onClick:h,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Minimize",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:s,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Close",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),e(Ze,{value:o.activeTab,onChange:e=>x(e),className:"flex-1 flex flex-col overflow-hidden",children:[t("div",{className:"px-3 py-2 border-b border-zinc-800",children:e(et,{className:"w-full",children:[t(tt,{value:"prompts",children:"Prompts"}),t(tt,{value:"timeline",children:"Timeline"}),t(tt,{value:"logs",children:"Logs"})]})}),o.connectionError&&t("div",{className:"mx-3 mt-2 px-3 py-2 bg-red-900/30 border border-red-500/30 rounded-lg",children:e("div",{className:"flex items-center gap-2 text-red-400 text-xs",children:[t("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),t("span",{children:o.connectionError})]})}),!o.isConnected&&!o.connectionError&&t("div",{className:"mx-3 mt-2 px-3 py-2 bg-yellow-900/30 border border-yellow-500/30 rounded-lg",children:e("div",{className:"flex items-center gap-2 text-yellow-400 text-xs",children:[t("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),t("span",{children:"Reconnecting to Orquesta..."})]})}),e("div",{className:"flex-1 overflow-y-auto p-3",children:[o.requireAuth&&!o.isAuthenticated&&e("div",{className:"h-full flex flex-col items-center justify-center text-center p-4",children:[t("div",{className:"w-16 h-16 rounded-full bg-zinc-800 flex items-center justify-center mb-4",children:t("svg",{className:"w-8 h-8 text-zinc-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"})})}),t("h3",{className:"text-white font-semibold mb-2",children:"Sign in to continue"}),t("p",{className:"text-zinc-400 text-sm mb-4",children:"You need to sign in to submit prompts to this project."}),o.authError&&t("div",{className:"mb-4 px-3 py-2 bg-red-900/30 border border-red-800 rounded text-red-300 text-xs",children:o.authError}),t("button",{onClick:N,disabled:o.isAuthenticating,className:"flex items-center gap-2 px-4 py-2 bg-white text-gray-800 rounded-lg font-medium hover:bg-gray-100 disabled:bg-gray-300 transition-colors",children:o.isAuthenticating?e(n,{children:[e("svg",{className:"animate-spin w-4 h-4",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Signing in..."})]}):e(n,{children:[e("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",children:[t("path",{fill:"currentColor",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),t("path",{fill:"currentColor",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),t("path",{fill:"currentColor",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),t("path",{fill:"currentColor",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),t("span",{children:"Continue with Google"})]})}),t("p",{className:"text-zinc-500 text-xs mt-4",children:"You must be a member of this project's organization."})]}),(!o.requireAuth||o.isAuthenticated)&&e(n,{children:[e(nt,{value:"prompts",className:"h-full flex flex-col",children:[t(rt,{onSubmit:W,isSubmitting:o.isSubmitting,selectedElement:o.selectedElement,includeConsole:o.includeConsole,includeNetwork:o.includeNetwork,includeContext:o.includeHistory,promptHistory:o.promptHistory,promptOutputs:o.promptOutputs,queueLength:o.promptQueue?.length||0,onToggleConsole:g,onToggleNetwork:f,onToggleContext:b,onSelectElement:u,onClearElement:m,agentOnline:o.agentOnline,replyContext:R,onClearReply:()=>H(null),demoMode:_}),(o.currentPrompt||o.outputLines.length>0)&&e("div",{className:"mt-4 pt-4 border-t border-zinc-800",children:[o.currentPrompt&&e("div",{className:"flex items-center gap-2 mb-2",children:[t(Ye,{status:o.currentPrompt.status}),e("span",{className:"text-xs text-zinc-400 line-clamp-1",children:[o.currentPrompt.content.slice(0,50),"..."]})]}),t(it,{lines:o.outputLines,isRunning:o.isSubmitting})]})]}),t(nt,{value:"timeline",children:t(ht,{prompts:o.promptHistory,currentPromptId:o.currentPrompt?.id,expandedPromptId:o.expandedPromptId,comments:o.comments,isLoadingComments:o.isLoadingComments,promptOutputs:o.promptOutputs,onExpandPrompt:y,onHighlightElement:w,onLoadComments:v,onAddComment:k,onReply:D})}),e(nt,{value:"logs",className:"h-full flex flex-col",children:[e("div",{className:"mb-4",children:[e("div",{className:"flex items-center justify-between mb-2",children:[t("h3",{className:"text-sm font-medium text-zinc-300",children:"Agent Output"}),o.isSubmitting&&t("span",{className:"text-xs text-green-400 animate-pulse",children:"Running..."})]}),t("div",{className:"bg-zinc-950 rounded-md p-2 max-h-[150px] overflow-y-auto",children:o.outputLines.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:o.outputLines.slice(-30).map(e=>t("div",{className:""+("stderr"===e.type?"text-red-400":"tool"===e.type?"text-blue-400":"thinking"===e.type?"text-zinc-500 italic":"system"===e.type?"text-yellow-400":"text-zinc-300"),children:e.content},e.id))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No agent output yet"})})]}),e("div",{className:"mb-4",children:[e("div",{className:"flex items-center justify-between mb-2",children:[t("h3",{className:"text-sm font-medium text-zinc-300",children:"Console Logs"}),e("span",{className:"text-xs text-zinc-500",children:[o.consoleLogs.length," entries"]})]}),t("div",{className:"bg-zinc-950 rounded-md p-2 max-h-[120px] overflow-y-auto",children:o.consoleLogs.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:o.consoleLogs.slice(-20).map((t,n)=>e("div",{className:""+("error"===t.level?"text-red-400":"warn"===t.level?"text-yellow-400":"text-zinc-300"),children:[e("span",{className:"text-zinc-500",children:["[",t.level,"]"]})," ",t.message]},n))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No console logs captured"})})]}),e("div",{children:[e("div",{className:"flex items-center justify-between mb-2",children:[t("h3",{className:"text-sm font-medium text-zinc-300",children:"Network Requests"}),e("span",{className:"text-xs text-zinc-500",children:[o.networkLogs.length," requests"]})]}),t("div",{className:"bg-zinc-950 rounded-md p-2 max-h-[120px] overflow-y-auto",children:o.networkLogs.length>0?t("div",{className:"font-mono text-[11px] space-y-1",children:o.networkLogs.slice(-15).map((n,o)=>e("div",{className:"flex items-center gap-2",children:[t("span",{className:""+(n.status&&n.status>=400?"text-red-400":n.status&&n.status>=300?"text-yellow-400":"text-green-400"),children:n.status||"..."}),t("span",{className:"text-zinc-400",children:n.method}),t("span",{className:"text-zinc-300 truncate flex-1",children:n.url}),n.duration&&e("span",{className:"text-zinc-500",children:[n.duration,"ms"]})]},o))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No network requests captured"})})]})]})]})]})]}),t("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-se-resize",onMouseDown:U,children:t("svg",{className:"w-full h-full text-zinc-600",viewBox:"0 0 16 16",fill:"currentColor",children:t("path",{d:"M14 14H10V10H14V14ZM14 8H12V6H14V8ZM8 14H6V12H8V14Z"})})})]})}function gt({state:n,onSubmitPrompt:o,onSwitchToWidget:r,onSelectElement:s,onClearElement:h,onToggleConsole:p,onToggleNetwork:u,onToggleHistory:m,onTabChange:g,onExpandPrompt:f,onHighlightElement:b,onLoadComments:x,onAddComment:y,onOverlayModeChange:w,onLogin:v,onLogout:k,onToggleRightClick:C,demoMode:N=!1}){const[S,q]=i(()=>We.get("builderWidth")||380),E=a(!1);l(()=>(document.body.style.marginLeft=`${S+4}px`,document.body.style.transition="margin-left 0.2s ease-out",()=>{document.body.style.marginLeft="",document.body.style.transition=""}),[S]),l(()=>{We.set("builderWidth",S)},[S]);const _=c(e=>{E.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none",e.preventDefault()},[]);l(()=>{const e=e=>{E.current&&q(Math.max(320,Math.min(e.clientX,.5*window.innerWidth)))},t=()=>{E.current&&(E.current=!1,document.body.style.cursor="",document.body.style.userSelect="")};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[]);const z=n.activeTab||"prompts";return e("div",{className:"orquesta-embed-panel",style:{position:"fixed",top:0,left:0,bottom:0,width:`${S}px`,zIndex:2147483647,display:"flex",flexDirection:"column",background:"#09090b",borderRight:"1px solid #27272a",boxShadow:"4px 0 24px rgba(0,0,0,0.5)",overflow:"hidden"},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700",style:{flexShrink:0},children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-base",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"}),e("span",{className:"text-[10px] text-zinc-500 font-mono",children:["v",d]}),n.projectName&&e("span",{className:"text-xs text-zinc-500",children:["• ",n.projectName]})]}),e("div",{className:"flex items-center gap-1",children:[n.requireAuth&&n.isAuthenticated&&n.user&&e("div",{className:"flex items-center gap-1 mr-2",children:[t("span",{className:"text-xs text-zinc-400 max-w-[60px] truncate",children:n.user.full_name}),t("button",{onClick:()=>k?.(),className:"text-xs text-zinc-500 hover:text-white p-0.5",children:"↪"})]}),t(Ye,{status:n.isConnected?n.agentOnline?"online":"offline":"disconnected"}),C&&t("button",{onClick:C,className:"p-1 rounded text-xs "+(n.rightClickEnabled?"bg-green-600/20 text-green-400":"text-zinc-500 hover:text-white"),title:n.rightClickEnabled?"Right-click enabled":"Right-click disabled",children:"🎯"}),w&&t("div",{className:"flex gap-0.5 mx-1 p-0.5 bg-zinc-900 rounded",children:["off","single","all"].map(e=>t("button",{onClick:()=>w(e),className:"px-1 py-0.5 rounded text-[10px] "+(n.overlayMode===e?"off"===e?"bg-zinc-700 text-white":"single"===e?"bg-blue-600 text-white":"bg-purple-600 text-white":"text-zinc-500 hover:text-white"),title:"off"===e?"Overlay off":"single"===e?"Show selected":"Show all",children:"off"===e?"👁":"single"===e?"👀":"📍"},e))}),t("button",{onClick:r,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Collapse to widget",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.5 3.5M15 9h4.5M15 9V4.5M15 9l5.5-5.5M9 15v4.5M9 15H4.5M9 15l-5.5 5.5M15 15h4.5M15 15v4.5m0-4.5l5.5 5.5"})})})]})]}),n.connectionError&&e("div",{className:"mx-2 mt-2 p-2 bg-red-900/30 border border-red-800/30 rounded text-xs text-red-300 flex items-center gap-1",children:["⚠️ ",n.connectionError]}),!n.isConnected&&!n.connectionError&&t("div",{className:"mx-2 mt-2 p-2 bg-yellow-900/30 border border-yellow-800/30 rounded text-xs text-yellow-300 flex items-center gap-1",children:"ℹ️ Reconnecting..."}),n.requireAuth&&!n.isAuthenticated&&e("div",{className:"mx-2 mt-2 p-3 text-center",children:[t("p",{className:"text-sm text-white font-medium mb-2",children:"Sign in to continue"}),t("button",{onClick:()=>v?.(),className:"px-4 py-2 bg-white text-gray-700 rounded-lg text-sm font-medium",children:n.isAuthenticating?"Signing in...":"Continue with Google"})]}),e(Ze,{value:z,onValueChange:e=>g(e),children:[t("div",{className:"px-2 py-1.5 border-b border-zinc-800",style:{flexShrink:0},children:e(et,{children:[t(tt,{value:"prompts",children:"Prompts"}),t(tt,{value:"timeline",children:"Timeline"}),t(tt,{value:"logs",children:"Logs"})]})}),e("div",{style:{flex:1,overflowY:"auto"},children:[e(nt,{value:"prompts",children:[t("div",{className:"p-3",children:t(rt,{agentOnline:n.agentOnline,isSubmitting:n.isSubmitting,selectedElement:n.selectedElement,includeConsole:n.includeConsole,includeNetwork:n.includeNetwork,includeHistory:n.includeHistory,includeContext:n.includeContext,onSubmit:o,onSelectElement:s,onClearElement:h,onToggleConsole:p,onToggleNetwork:u,onToggleHistory:m})}),(n.outputLines.length>0||n.isSubmitting)&&t("div",{className:"px-3 pb-3 border-t border-zinc-800 pt-2",children:t(it,{lines:n.outputLines,isStreaming:n.isSubmitting,maxHeight:"250px"})})]}),t(nt,{value:"timeline",children:t("div",{className:"p-3",children:t(ht,{prompts:n.promptHistory,expandedPromptId:n.expandedPromptId||null,comments:n.comments,isLoadingComments:n.isLoadingComments,promptOutputs:n.promptOutputs,onExpand:e=>f?.(e),onHighlightElement:e=>b?.(e),onLoadComments:e=>x?.(e),onAddComment:(e,t)=>y?.(e,t),onReply:e=>{g("prompts")}})})}),t(nt,{value:"logs",children:t("div",{className:"p-3",children:t(it,{lines:n.outputLines,isStreaming:n.isSubmitting,maxHeight:"none"})})})]})]}),t("div",{onMouseDown:_,style:{position:"absolute",top:0,right:"-3px",bottom:0,width:"6px",cursor:"col-resize",zIndex:1}})]})}function ft({isActive:n,onCancel:o}){const r=a(null);return l(()=>{const e=e=>{"Escape"===e.key&&n&&o()};return n&&document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[n,o]),n?t("div",{ref:r,className:"orquesta-element-inspector fixed inset-0 z-[2147483645] pointer-events-none",children:t("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 pointer-events-auto",children:e("div",{className:"flex items-center gap-3 px-4 py-2 bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl",children:[t("span",{className:"text-sm text-zinc-300",children:"Click on any element to select it, or right-click for options"}),t(Ve,{variant:"ghost",size:"sm",onClick:o,children:"Cancel (Esc)"})]})})}):null}function bt({markers:n,onMarkerClick:o}){const[r,s]=i([]),[d,h]=i(null),p=a(null),u=c(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{const e=window.innerHeight,t=window.innerWidth,o=[];for(const r of n)try{const n=document.querySelector(r.selector);if(n){const i=n.getBoundingClientRect(),s=i.left+i.width/2,a=i.top+i.height/2,l=i.top<e&&i.bottom>0&&i.left<t&&i.right>0;o.push({promptId:r.promptId,x:s,y:a,visible:!0,inViewport:l})}else o.push({promptId:r.promptId,x:0,y:0,visible:!1,inViewport:!1})}catch{o.push({promptId:r.promptId,x:0,y:0,visible:!1,inViewport:!1})}s(o)})},[n]);l(()=>{u();let e=!1;const t=()=>{e||(e=!0,requestAnimationFrame(()=>{u(),e=!1}))};window.addEventListener("scroll",t,!0),window.addEventListener("resize",t);const n=new MutationObserver(t);return n.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),()=>{window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t),n.disconnect(),p.current&&cancelAnimationFrame(p.current)}},[u]);const m=d?n.find(e=>e.promptId===d):null,g=d?r.find(e=>e.promptId===d):null;return e("div",{className:"orquesta-markers-overlay fixed inset-0 pointer-events-none z-[2147483646]",children:[r.map((r,i)=>{if(!r.visible||!r.inViewport)return null;const s=n.find(e=>e.promptId===r.promptId);if(!s)return null;const a=d===r.promptId;return e("div",{className:"absolute pointer-events-auto",style:{left:r.x,top:r.y,transform:"translate(-50%, -50%)"},children:[e("button",{onClick:()=>o?.(r.promptId),onMouseEnter:()=>h(r.promptId),onMouseLeave:()=>h(null),className:"relative flex items-center gap-1.5 px-2 py-1 rounded-full border-2 shadow-lg transition-all "+(a?"bg-purple-500 border-white scale-110":"bg-purple-600 border-white/80 hover:scale-105"),children:[t("span",{className:"w-5 h-5 flex items-center justify-center bg-white/20 rounded-full text-white text-[10px] font-bold",children:i+1}),e("span",{className:"text-white text-[11px] font-medium max-w-[120px] truncate",children:[s.content.slice(0,25),s.content.length>25?"...":""]})]}),t("div",{className:"absolute inset-0 -z-10 animate-ping rounded-full bg-purple-500/30",style:{animationDuration:"2s"}})]},r.promptId)}),m&&g&&g.visible&&g.inViewport&&e("div",{className:"fixed pointer-events-none bg-zinc-900 border border-zinc-600 rounded-xl shadow-2xl p-4 z-20",style:{...(e=>{let t=e.x+20,n=e.y+20;return t+280>window.innerWidth-20&&(t=e.x-280-20),n+180>window.innerHeight-20&&(n=e.y-180-20),{left:t,top:n}})(g),width:280},children:[e("div",{className:"flex items-center justify-between mb-3",children:[e("div",{className:"flex items-center gap-2",children:[t(st,{author:m.author,size:"sm"}),t("span",{className:"text-xs font-medium text-zinc-200",children:m.author?.full_name||"Unknown"})]}),e("span",{className:"px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded text-[10px] text-blue-400 font-mono",children:["🎯 ",m.selector.split(" ").pop()?.split(".")[0]||"element"]})]}),e("p",{className:"text-sm text-zinc-200 mb-3 line-clamp-3",children:[m.content.slice(0,150),m.content.length>150&&"..."]}),e("div",{className:"flex items-center gap-3 text-[10px] text-zinc-500",children:[m.gitCommitSha&&e("span",{className:"inline-flex items-center gap-1 font-mono bg-zinc-800 px-1.5 py-0.5 rounded",children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),m.gitCommitSha.slice(0,7)]}),m.commentCount>0&&e("span",{className:"inline-flex items-center gap-1",children:["💬 ",m.commentCount," comments"]})]}),t("div",{className:"mt-3 pt-2 border-t border-zinc-800 text-[10px] text-zinc-500 text-center",children:"Click to view in timeline"})]})]})}function xt({isOpen:n,position:o,element:r,agentOnline:s,includeConsole:c,includeNetwork:d,onSubmit:h,onClose:p,onToggleConsole:u,onToggleNetwork:m,onOpenPanel:g}){const[f,b]=i(""),[x,y]=i(!1),w=a(null),v=a(null);if(l(()=>{n&&v.current&&setTimeout(()=>v.current?.focus(),50)},[n]),l(()=>{if(n&&w.current){const e=w.current,t=e.getBoundingClientRect(),n=window.innerWidth,o=window.innerHeight;t.right>n-20&&(e.style.left=`${Math.max(20,n-t.width-20)}px`),t.bottom>o-20&&(e.style.top=`${Math.max(20,o-t.height-20)}px`)}},[n,o]),l(()=>{if(!n)return;const e=e=>{w.current&&!w.current.contains(e.target)&&p()},t=e=>{"Escape"===e.key&&p()};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)}},[n,p]),l(()=>{n&&(b(""),y(!1))},[n]),!n||!r)return null;const k=async e=>{e.preventDefault(),f.trim()&&!x&&s&&(y(!0),h(f.trim()),b(""),setTimeout(()=>{p()},100))};return e("div",{ref:w,id:"orquesta-context-menu",style:{position:"fixed",zIndex:2147483647,backgroundColor:"#18181b",border:"1px solid #52525b",borderRadius:"12px",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.5)",overflow:"hidden",left:o.x,top:o.y,width:340,maxWidth:"calc(100vw - 40px)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',color:"#ffffff"},onClick:e=>e.stopPropagation(),children:[e("div",{style:{padding:"10px 12px",backgroundColor:"#27272a",borderBottom:"1px solid #3f3f46"},children:[e("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"6px"},children:[t("div",{style:{width:"24px",height:"24px",borderRadius:"6px",backgroundColor:"rgba(37, 99, 235, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",display:"flex",alignItems:"center",justifyContent:"center"},children:t("span",{style:{color:"#60a5fa",fontSize:"14px"},children:"🎯"})}),t("span",{style:{fontSize:"14px",fontWeight:500,color:"#ffffff"},children:"Selected Element"})]}),t("div",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",color:"#a1a1aa",backgroundColor:"rgba(24, 24, 27, 0.5)",padding:"6px 8px",borderRadius:"6px",wordBreak:"break-all"},children:(()=>{const e=[];if(e.push(`<${r.tag}`),r.id&&e.push(` id="${r.id}"`),r.className){const t=r.className.split(" ").slice(0,2).join(" ");e.push(` class="${t}${r.className.split(" ").length>2?"...":""}"`)}if(e.push(">"),r.textContent){const t=r.textContent.slice(0,30);e.push(t+(r.textContent.length>30?"...":""))}return e.push(`</${r.tag}>`),e.join("")})()})]}),e("form",{onSubmit:k,style:{padding:"12px"},children:[t("textarea",{ref:v,value:f,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&k(e)},placeholder:s?"What do you want to do with this element?":"Agent is offline...",disabled:x||!s,rows:3,style:{width:"100%",padding:"8px 10px",backgroundColor:"#09090b",border:"1px solid #3f3f46",borderRadius:"6px",color:"#ffffff",fontSize:"13px",fontFamily:"inherit",resize:"vertical",outline:"none",boxSizing:"border-box"}}),e("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:[e("button",{type:"button",onClick:u,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:c?"rgba(234, 179, 8, 0.2)":"#27272a",color:c?"#fde047":"#a1a1aa",border:c?"1px solid rgba(234, 179, 8, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"📋"}),t("span",{children:"Logs"}),c&&t("span",{style:{marginLeft:"2px",color:"#facc15"},children:"✓"})]}),e("button",{type:"button",onClick:m,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:d?"rgba(239, 68, 68, 0.2)":"#27272a",color:d?"#fca5a5":"#a1a1aa",border:d?"1px solid rgba(239, 68, 68, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"🌐"}),t("span",{children:"Network"}),d&&t("span",{style:{marginLeft:"2px",color:"#f87171"},children:"✓"})]})]}),e("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:"12px",paddingTop:"12px",borderTop:"1px solid #27272a"},children:[t("button",{type:"button",onClick:g,style:{fontSize:"12px",color:"#a1a1aa",background:"none",border:"none",cursor:"pointer",padding:0},children:"Open full panel →"}),e("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t("button",{type:"button",onClick:p,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:"pointer",backgroundColor:"transparent",color:"#d4d4d8",border:"none"},children:"Cancel"}),t("button",{type:"submit",disabled:!f.trim()||!s||x,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:f.trim()&&s&&!x?"pointer":"not-allowed",backgroundColor:f.trim()&&s&&!x?"#2563eb":"#3f3f46",color:"#ffffff",border:"none",opacity:f.trim()&&s&&!x?1:.5},children:x?"Submitting...":"Submit"})]})]}),e("div",{style:{marginTop:"8px",fontSize:"10px",color:"#71717a",textAlign:"center"},children:["Press ",t("kbd",{style:{padding:"2px 4px",backgroundColor:"#27272a",borderRadius:"4px"},children:"⌘/Ctrl + Enter"})," to submit"]})]})]})}function yt({isConnected:n,agentOnline:o,projectName:r,currentPrompt:s,isSubmitting:a,lastCompletedPrompt:c,onClose:d}){const[h,p]=i(!0),[u,m]=i(!1),g=n?o?a||"running"===s?.status?"running":"completed"===s?.status?"completed":"failed"===s?.status?"failed":"idle":"offline":"connecting";if(l(()=>{"running"!==g&&"completed"!==g&&"failed"!==g||(p(!0),m(!1))},[g]),l(()=>{if("completed"===g||"failed"===g){const e=setTimeout(()=>{m(!0)},5e3);return()=>clearTimeout(e)}},[g,s?.id]),!h)return null;const f=(()=>{switch(g){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${s?.content.slice(0,50)}${(s?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(s?.git_commit_sha?` • Commit ${s.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:r?`${r} • Ready`:"Orquesta Ready",pulse:!1}}})();return e("div",u?{id:"orquesta-status-bar-minimized",onClick:()=>m(!1),style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:f.bg,border:`1px solid ${f.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',transition:"all 0.2s ease"},children:[t("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===g?"#22c55e":"failed"===g?"#ef4444":"running"===g?"#3b82f6":"#71717a",animation:f.pulse?"pulse 2s infinite":"none"}}),t("span",{style:{fontSize:"11px",color:"#d4d4d8",fontWeight:500},children:"Orquesta"}),t("style",{children:"\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]}:{id:"orquesta-status-bar",style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:f.bg,border:`1px solid ${f.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)",transition:"all 0.3s ease"},children:[t("div",{style:{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:f.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t("span",{style:{fontSize:"14px",color:"#ffffff",animation:f.pulse?"spin 1s linear infinite":"none"},children:f.icon})}),e("div",{style:{flex:1,minWidth:0},children:[t("div",{style:{fontSize:"12px",fontWeight:500,color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"},children:f.text}),"running"===g&&t("div",{style:{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"},children:t("div",{style:{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",animation:"progress 2s ease-in-out infinite"}})})]}),"completed"===g&&s?.git_branch&&e("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"4px",flexShrink:0},children:[t("svg",{style:{width:"12px",height:"12px",color:"#a1a1aa"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),t("span",{style:{fontSize:"11px",color:"#a1a1aa",fontFamily:"ui-monospace, monospace"},children:s.git_branch})]}),t("button",{onClick:()=>m(!0),style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Minimize",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:()=>{p(!1),d()},style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Close",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),t("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]})}const wt=[{id:"demo-1",full_name:"Sarah Chen",avatar_url:null},{id:"demo-2",full_name:"Mike Johnson",avatar_url:null},{id:"demo-3",full_name:"Alex Rivera",avatar_url:null}],vt=[{id:"demo-prompt-1",content:'Change the "Shop Now" button color to green and add a hover animation',status:"completed",created_at:new Date(Date.now()-72e5).toISOString(),completed_at:new Date(Date.now()-72e5+45e3).toISOString(),user_id:"demo-1",source:"embed",element_context:{selector:"button.bg-blue-600",tag:"button",className:"px-6 py-3 bg-blue-600 text-white rounded-lg font-medium",textContent:"Shop Now"},author:wt[0],git_branch:"main",git_commit_sha:"a1b2c3d",comment_count:2},{id:"demo-prompt-2",content:'Add a discount badge showing "20% OFF" to the Premium Headphones card',status:"completed",created_at:new Date(Date.now()-36e5).toISOString(),completed_at:new Date(Date.now()-36e5+32e3).toISOString(),user_id:"demo-2",source:"embed",element_context:{selector:"div.bg-gradient-to-br.from-purple-400",tag:"div",className:"bg-gradient-to-br from-purple-400 to-purple-600 h-48 relative",textContent:"Best Seller"},author:wt[1],git_branch:"feature/product-badges",git_commit_sha:"e4f5g6h",comment_count:1},{id:"demo-prompt-3",content:"Make the contact form email field validate on blur and show error message",status:"completed",created_at:new Date(Date.now()-18e5).toISOString(),completed_at:new Date(Date.now()-18e5+28e3).toISOString(),user_id:"demo-3",source:"embed",element_context:{selector:'input[type="email"]',tag:"input",className:"w-full px-4 py-2 border border-gray-300 rounded-lg",textContent:""},author:wt[2],git_branch:"main",git_commit_sha:"i7j8k9l",comment_count:0}],kt={"demo-prompt-1":[{id:"comment-1",content:"Looks great! The animation is smooth.",created_at:new Date(Date.now()-54e5).toISOString(),author:wt[1]},{id:"comment-2",content:"Could we also add this to the Learn More button?",created_at:new Date(Date.now()-36e5).toISOString(),author:wt[2]}],"demo-prompt-2":[{id:"comment-3",content:"Perfect placement for the badge!",created_at:new Date(Date.now()-27e5).toISOString(),author:wt[0]}]};function Ct(o){const{children:r,enableGlobalRightClick:s=!0,demoMode:h=!1,...p}=o,[u,m]=i(null),[g,f]=i(h?{isConnected:!0,isConnecting:!1,connectionError:null,projectId:"demo-project",projectName:"Demo Store",agentOnline:!0,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[...vt],isSubmitting:!1,outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{...kt},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},promptQueue:[],consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1,requireAuth:p.requireAuth||!1}:null),[b,x]=i(!1),[y,w]=i(null),[v,k]=i({isOpen:!1,position:{x:0,y:0},element:null}),[C,N]=i(p.mode||"widget"),[S,q]=i(!0),[E,_]=i(null),z=a(null),L=a(null);a(null),l(()=>{console.log(`[Orquesta Embed] v${d}`),function(){if(Ue||"undefined"==typeof document)return;const e="orquesta-embed-styles";if(document.getElementById(e))return void(Ue=!0);const t=document.createElement("style");t.id=e,t.textContent="\n/* Orquesta Embed SDK Styles - Auto-injected */\n/* These styles are scoped to orquesta-* classes to avoid conflicts */\n\n/* Reset for Orquesta elements */\n[class^=\"orquesta-\"],\n[class*=\" orquesta-\"] {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Base colors */\n.orquesta-embed-panel {\n --orq-bg: #18181b;\n --orq-bg-secondary: #27272a;\n --orq-border: #3f3f46;\n --orq-text: #fafafa;\n --orq-text-muted: #a1a1aa;\n --orq-primary: #3b82f6;\n --orq-success: #22c55e;\n --orq-warning: #eab308;\n --orq-error: #ef4444;\n}\n\n/* Scrollbar styling */\n.orquesta-embed-panel ::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb {\n background: #3f3f46;\n border-radius: 3px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb:hover {\n background: #52525b;\n}\n\n/* Animations */\n@keyframes orquesta-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n@keyframes orquesta-pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.5;\n }\n}\n\n.orquesta-embed-panel .animate-spin {\n animation: orquesta-spin 1s linear infinite;\n}\n\n.orquesta-embed-panel .animate-pulse {\n animation: orquesta-pulse 2s ease-in-out infinite;\n}\n\n/* Utility classes */\n.orquesta-embed-panel .line-clamp-1 {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n.orquesta-embed-panel .line-clamp-2 {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n/* Focus visible */\n.orquesta-embed-panel button:focus-visible,\n.orquesta-embed-panel input:focus-visible,\n.orquesta-embed-panel textarea:focus-visible {\n outline: 2px solid var(--orq-primary);\n outline-offset: 2px;\n}\n\n/* Element selector highlight animation */\n#orquesta-element-highlight {\n animation: orquesta-highlight-pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes orquesta-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);\n }\n}\n\n/* Tooltip */\n.orquesta-tooltip {\n position: absolute;\n z-index: 2147483647;\n padding: 4px 8px;\n background: #18181b;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n font-size: 12px;\n color: #fafafa;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* Transitions */\n.orquesta-embed-panel * {\n transition-property: color, background-color, border-color, opacity, transform;\n transition-duration: 150ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n/* Panel entrance animation */\n.orquesta-embed-panel {\n animation: orquesta-panel-enter 0.2s ease-out;\n}\n\n@keyframes orquesta-panel-enter {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n}\n\n/* Trigger button */\n.orquesta-embed-trigger {\n animation: orquesta-trigger-enter 0.3s ease-out;\n}\n\n@keyframes orquesta-trigger-enter {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* Log stream */\n.orquesta-log-stream {\n background: #0a0a0a;\n border: 1px solid #27272a;\n border-radius: 6px;\n padding: 8px;\n}\n\n/* Timeline item hover */\n.orquesta-timeline button:hover {\n transform: translateX(2px);\n}\n\n/* ============================================ */\n/* Tailwind class overrides - CRITICAL STYLES */\n/* These ensure styles work even when purged */\n/* ============================================ */\n\n/* Explicit background colors */\n.orquesta-embed-panel {\n background-color: #18181b !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel .bg-zinc-950 { background-color: #09090b !important; }\n.orquesta-embed-panel .bg-zinc-900 { background-color: #18181b !important; }\n.orquesta-embed-panel .bg-zinc-800 { background-color: #27272a !important; }\n.orquesta-embed-panel .bg-zinc-700 { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .bg-zinc-600 { background-color: #52525b !important; }\n\n/* Text colors */\n.orquesta-embed-panel .text-white { color: #fafafa !important; }\n.orquesta-embed-panel .text-zinc-100 { color: #f4f4f5 !important; }\n.orquesta-embed-panel .text-zinc-200 { color: #e4e4e7 !important; }\n.orquesta-embed-panel .text-zinc-300 { color: #d4d4d8 !important; }\n.orquesta-embed-panel .text-zinc-400 { color: #a1a1aa !important; }\n.orquesta-embed-panel .text-zinc-500 { color: #71717a !important; }\n.orquesta-embed-panel .text-red-400 { color: #f87171 !important; }\n.orquesta-embed-panel .text-red-300 { color: #fca5a5 !important; }\n.orquesta-embed-panel .text-green-400 { color: #4ade80 !important; }\n.orquesta-embed-panel .text-green-500 { color: #22c55e !important; }\n.orquesta-embed-panel .text-blue-400 { color: #60a5fa !important; }\n.orquesta-embed-panel .text-blue-500 { color: #3b82f6 !important; }\n.orquesta-embed-panel .text-yellow-400 { color: #facc15 !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .text-orange-400 { color: #fb923c !important; }\n.orquesta-embed-panel .text-gray-800 { color: #1f2937 !important; }\n\n/* Border colors */\n.orquesta-embed-panel .border-zinc-700 { border-color: #3f3f46 !important; }\n.orquesta-embed-panel .border-zinc-800 { border-color: #27272a !important; }\n.orquesta-embed-panel .border-red-800 { border-color: #991b1b !important; }\n\n/* Background colors for buttons and UI */\n.orquesta-embed-panel .bg-blue-500 { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .bg-blue-600 { background-color: #2563eb !important; }\n.orquesta-embed-panel .bg-green-400 { background-color: #4ade80 !important; }\n.orquesta-embed-panel .bg-green-500 { background-color: #22c55e !important; }\n.orquesta-embed-panel .bg-green-600 { background-color: #16a34a !important; }\n.orquesta-embed-panel .bg-red-500 { background-color: #ef4444 !important; }\n.orquesta-embed-panel .bg-red-600 { background-color: #dc2626 !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-red-900\\/30 { background-color: rgba(127, 29, 29, 0.3) !important; }\n.orquesta-embed-panel .bg-white { background-color: #ffffff !important; }\n\n/* Hover states */\n.orquesta-embed-panel .hover\\:bg-zinc-700:hover { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .hover\\:bg-zinc-800:hover { background-color: #27272a !important; }\n.orquesta-embed-panel .hover\\:bg-blue-500:hover { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .hover\\:bg-blue-700:hover { background-color: #1d4ed8 !important; }\n.orquesta-embed-panel .hover\\:bg-gray-100:hover { background-color: #f3f4f6 !important; }\n.orquesta-embed-panel .hover\\:text-white:hover { color: #fafafa !important; }\n.orquesta-embed-panel .hover\\:text-zinc-300:hover { color: #d4d4d8 !important; }\n\n/* Form inputs */\n.orquesta-embed-panel input,\n.orquesta-embed-panel textarea {\n background-color: #27272a !important;\n border-color: #3f3f46 !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel input::placeholder,\n.orquesta-embed-panel textarea::placeholder {\n color: #71717a !important;\n}\n\n/* Buttons base */\n.orquesta-embed-panel button {\n background-color: transparent;\n}\n\n.orquesta-embed-panel button:hover {\n background-color: #3f3f46;\n}\n\n/* Rounded borders */\n.orquesta-embed-panel .rounded { border-radius: 0.25rem !important; }\n.orquesta-embed-panel .rounded-md { border-radius: 0.375rem !important; }\n.orquesta-embed-panel .rounded-lg { border-radius: 0.5rem !important; }\n.orquesta-embed-panel .rounded-xl { border-radius: 0.75rem !important; }\n.orquesta-embed-panel .rounded-full { border-radius: 9999px !important; }\n\n/* Border widths */\n.orquesta-embed-panel .border { border-width: 1px !important; }\n.orquesta-embed-panel .border-b { border-bottom-width: 1px !important; }\n.orquesta-embed-panel .border-t { border-top-width: 1px !important; }\n\n/* Padding */\n.orquesta-embed-panel .p-1 { padding: 0.25rem !important; }\n.orquesta-embed-panel .p-2 { padding: 0.5rem !important; }\n.orquesta-embed-panel .p-3 { padding: 0.75rem !important; }\n.orquesta-embed-panel .p-4 { padding: 1rem !important; }\n.orquesta-embed-panel .px-2 { padding-left: 0.5rem !important; padding-right: 0.5rem !important; }\n.orquesta-embed-panel .px-3 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }\n.orquesta-embed-panel .px-4 { padding-left: 1rem !important; padding-right: 1rem !important; }\n.orquesta-embed-panel .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }\n.orquesta-embed-panel .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .py-3 { padding-top: 0.75rem !important; padding-bottom: 0.75rem !important; }\n\n/* Margin */\n.orquesta-embed-panel .m-1 { margin: 0.25rem !important; }\n.orquesta-embed-panel .m-2 { margin: 0.5rem !important; }\n.orquesta-embed-panel .mb-1 { margin-bottom: 0.25rem !important; }\n.orquesta-embed-panel .mb-2 { margin-bottom: 0.5rem !important; }\n.orquesta-embed-panel .mb-4 { margin-bottom: 1rem !important; }\n.orquesta-embed-panel .mt-1 { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .mt-2 { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .mt-3 { margin-top: 0.75rem !important; }\n.orquesta-embed-panel .mt-4 { margin-top: 1rem !important; }\n.orquesta-embed-panel .mr-1 { margin-right: 0.25rem !important; }\n.orquesta-embed-panel .mr-2 { margin-right: 0.5rem !important; }\n.orquesta-embed-panel .mx-1 { margin-left: 0.25rem !important; margin-right: 0.25rem !important; }\n\n/* Gap */\n.orquesta-embed-panel .gap-0\\.5 { gap: 0.125rem !important; }\n.orquesta-embed-panel .gap-1 { gap: 0.25rem !important; }\n.orquesta-embed-panel .gap-1\\.5 { gap: 0.375rem !important; }\n.orquesta-embed-panel .gap-2 { gap: 0.5rem !important; }\n.orquesta-embed-panel .gap-3 { gap: 0.75rem !important; }\n.orquesta-embed-panel .gap-4 { gap: 1rem !important; }\n\n/* Flex */\n.orquesta-embed-panel .flex { display: flex !important; }\n.orquesta-embed-panel .flex-col { flex-direction: column !important; }\n.orquesta-embed-panel .flex-1 { flex: 1 1 0% !important; }\n.orquesta-embed-panel .flex-shrink-0 { flex-shrink: 0 !important; }\n.orquesta-embed-panel .items-center { align-items: center !important; }\n.orquesta-embed-panel .items-start { align-items: flex-start !important; }\n.orquesta-embed-panel .justify-center { justify-content: center !important; }\n.orquesta-embed-panel .justify-between { justify-content: space-between !important; }\n\n/* Width/Height */\n.orquesta-embed-panel .w-full { width: 100% !important; }\n.orquesta-embed-panel .w-2 { width: 0.5rem !important; }\n.orquesta-embed-panel .w-3 { width: 0.75rem !important; }\n.orquesta-embed-panel .w-3\\.5 { width: 0.875rem !important; }\n.orquesta-embed-panel .w-4 { width: 1rem !important; }\n.orquesta-embed-panel .w-5 { width: 1.25rem !important; }\n.orquesta-embed-panel .w-6 { width: 1.5rem !important; }\n.orquesta-embed-panel .w-8 { width: 2rem !important; }\n.orquesta-embed-panel .w-16 { width: 4rem !important; }\n.orquesta-embed-panel .h-2 { height: 0.5rem !important; }\n.orquesta-embed-panel .h-3 { height: 0.75rem !important; }\n.orquesta-embed-panel .h-3\\.5 { height: 0.875rem !important; }\n.orquesta-embed-panel .h-4 { height: 1rem !important; }\n.orquesta-embed-panel .h-5 { height: 1.25rem !important; }\n.orquesta-embed-panel .h-6 { height: 1.5rem !important; }\n.orquesta-embed-panel .h-8 { height: 2rem !important; }\n.orquesta-embed-panel .h-16 { height: 4rem !important; }\n.orquesta-embed-panel .h-full { height: 100% !important; }\n.orquesta-embed-panel .max-w-20 { max-width: 5rem !important; }\n\n/* Font */\n.orquesta-embed-panel .text-xs { font-size: 0.75rem !important; line-height: 1rem !important; }\n.orquesta-embed-panel .text-sm { font-size: 0.875rem !important; line-height: 1.25rem !important; }\n.orquesta-embed-panel .text-lg { font-size: 1.125rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-xl { font-size: 1.25rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-2xl { font-size: 1.5rem !important; line-height: 2rem !important; }\n.orquesta-embed-panel .text-4xl { font-size: 2.25rem !important; line-height: 2.5rem !important; }\n.orquesta-embed-panel .font-medium { font-weight: 500 !important; }\n.orquesta-embed-panel .font-semibold { font-weight: 600 !important; }\n.orquesta-embed-panel .font-bold { font-weight: 700 !important; }\n.orquesta-embed-panel .text-center { text-align: center !important; }\n.orquesta-embed-panel .truncate { overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; }\n\n/* Opacity */\n.orquesta-embed-panel .opacity-25 { opacity: 0.25 !important; }\n.orquesta-embed-panel .opacity-50 { opacity: 0.5 !important; }\n.orquesta-embed-panel .opacity-75 { opacity: 0.75 !important; }\n\n/* Overflow */\n.orquesta-embed-panel .overflow-hidden { overflow: hidden !important; }\n.orquesta-embed-panel .overflow-y-auto { overflow-y: auto !important; }\n\n/* Shadow */\n.orquesta-embed-panel .shadow-xl { box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important; }\n.orquesta-embed-panel .shadow-2xl { box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important; }\n.orquesta-embed-panel .shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important; }\n\n/* Position */\n.orquesta-embed-panel .fixed { position: fixed !important; }\n.orquesta-embed-panel .absolute { position: absolute !important; }\n.orquesta-embed-panel .relative { position: relative !important; }\n.orquesta-embed-panel .top-1 { top: 0.25rem !important; }\n.orquesta-embed-panel .right-1 { right: 0.25rem !important; }\n.orquesta-embed-panel .bottom-0 { bottom: 0 !important; }\n.orquesta-embed-panel .right-0 { right: 0 !important; }\n\n/* Z-index */\n.orquesta-embed-panel .z-\\[2147483647\\] { z-index: 2147483647 !important; }\n\n/* Cursor */\n.orquesta-embed-panel .cursor-move { cursor: move !important; }\n.orquesta-embed-panel .cursor-se-resize { cursor: se-resize !important; }\n.orquesta-embed-panel .cursor-not-allowed { cursor: not-allowed !important; }\n\n/* Select */\n.orquesta-embed-panel .select-none { user-select: none !important; }\n\n/* Disabled states */\n.orquesta-embed-panel .disabled\\:opacity-50:disabled { opacity: 0.5 !important; }\n.orquesta-embed-panel .disabled\\:cursor-not-allowed:disabled { cursor: not-allowed !important; }\n.orquesta-embed-panel .disabled\\:bg-blue-800:disabled { background-color: #1e40af !important; }\n.orquesta-embed-panel .disabled\\:bg-gray-300:disabled { background-color: #d1d5db !important; }\n\n/* Transition */\n.orquesta-embed-panel .transition-colors { transition-property: color, background-color, border-color !important; transition-duration: 150ms !important; }\n.orquesta-embed-panel .transition-all { transition-property: all !important; transition-duration: 150ms !important; }\n\n/* ============================================ */\n/* Action buttons & Comments - Timeline styles */\n/* ============================================ */\n\n/* Purple colors for \"Show on page\" button */\n.orquesta-embed-panel .text-purple-300 { color: #d8b4fe !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-purple-600\\/20 { background-color: rgba(147, 51, 234, 0.2) !important; }\n.orquesta-embed-panel .bg-purple-600\\/30 { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .border-purple-500\\/40 { border-color: rgba(168, 85, 247, 0.4) !important; }\n.orquesta-embed-panel .border-purple-500\\/60 { border-color: rgba(168, 85, 247, 0.6) !important; }\n.orquesta-embed-panel .hover\\:bg-purple-600\\/30:hover { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .hover\\:border-purple-500\\/60:hover { border-color: rgba(168, 85, 247, 0.6) !important; }\n\n/* Zinc with opacity for \"View output\" button */\n.orquesta-embed-panel .bg-zinc-700\\/50 { background-color: rgba(63, 63, 70, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600\\/50 { border-color: rgba(82, 82, 91, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600 { border-color: #52525b !important; }\n.orquesta-embed-panel .border-zinc-500 { border-color: #71717a !important; }\n.orquesta-embed-panel .hover\\:border-zinc-500:hover { border-color: #71717a !important; }\n\n/* Blue with opacity */\n.orquesta-embed-panel .bg-blue-500\\/20 { background-color: rgba(59, 130, 246, 0.2) !important; }\n.orquesta-embed-panel .border-blue-500\\/30 { border-color: rgba(59, 130, 246, 0.3) !important; }\n.orquesta-embed-panel .text-blue-300 { color: #93c5fd !important; }\n.orquesta-embed-panel .text-blue-300\\/70 { color: rgba(147, 197, 253, 0.7) !important; }\n\n/* Additional padding */\n.orquesta-embed-panel .py-1\\.5 { padding-top: 0.375rem !important; padding-bottom: 0.375rem !important; }\n.orquesta-embed-panel .py-0\\.5 { padding-top: 0.125rem !important; padding-bottom: 0.125rem !important; }\n.orquesta-embed-panel .px-1\\.5 { padding-left: 0.375rem !important; padding-right: 0.375rem !important; }\n.orquesta-embed-panel .px-2\\.5 { padding-left: 0.625rem !important; padding-right: 0.625rem !important; }\n.orquesta-embed-panel .pb-2 { padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .pb-3 { padding-bottom: 0.75rem !important; }\n.orquesta-embed-panel .pt-1 { padding-top: 0.25rem !important; }\n\n/* Space utilities */\n.orquesta-embed-panel .space-y-0\\.5 > * + * { margin-top: 0.125rem !important; }\n.orquesta-embed-panel .space-y-1 > * + * { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .space-y-2 > * + * { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .space-y-3 > * + * { margin-top: 0.75rem !important; }\n\n/* Focus states */\n.orquesta-embed-panel .focus\\:outline-none:focus { outline: none !important; }\n.orquesta-embed-panel .focus\\:ring-1:focus { box-shadow: 0 0 0 1px var(--orq-primary, #3b82f6) !important; }\n.orquesta-embed-panel .focus\\:ring-blue-500:focus { --tw-ring-color: #3b82f6 !important; }\n\n/* Placeholder colors */\n.orquesta-embed-panel .placeholder\\:text-zinc-500::placeholder { color: #71717a !important; }\n\n/* Text utilities */\n.orquesta-embed-panel .break-words { word-wrap: break-word !important; overflow-wrap: break-word !important; }\n.orquesta-embed-panel .italic { font-style: italic !important; }\n\n/* Negative margins */\n.orquesta-embed-panel .-mt-1 { margin-top: -0.25rem !important; }\n\n/* Max height */\n.orquesta-embed-panel .max-h-\\[400px\\] { max-height: 400px !important; }\n.orquesta-embed-panel .max-h-\\[150px\\] { max-height: 150px !important; }\n\n/* Font mono */\n.orquesta-embed-panel .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }\n\n/* Text sizes */\n.orquesta-embed-panel .text-\\[10px\\] { font-size: 10px !important; line-height: 1.4 !important; }\n.orquesta-embed-panel .text-\\[11px\\] { font-size: 11px !important; line-height: 1.4 !important; }\n\n/* Flex wrap */\n.orquesta-embed-panel .flex-wrap { flex-wrap: wrap !important; }\n\n/* Min width */\n.orquesta-embed-panel .min-w-0 { min-width: 0 !important; }\n\n/* ml-auto for comment button alignment */\n.orquesta-embed-panel .ml-auto { margin-left: auto !important; }\n\n/* Hidden utility */\n.orquesta-embed-panel .hidden { display: none !important; }\n\n/* SVG icon sizing */\n.orquesta-embed-panel svg { flex-shrink: 0; }\n\n/* Mobile responsive */\n@media (max-width: 480px) {\n .orquesta-embed-panel {\n position: fixed !important;\n left: 8px !important;\n right: 8px !important;\n bottom: 8px !important;\n top: auto !important;\n width: auto !important;\n max-height: 70vh !important;\n }\n}\n\n/* Builder Mode */\n.orquesta-builder{display:flex;flex-direction:column;width:100%;height:100vh;background:#0a0a0a;color:#fafafa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;overflow:hidden}\n.orquesta-builder-header{display:flex;align-items:center;justify-content:space-between;height:48px;padding:0 16px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-header-left{display:flex;align-items:center;gap:12px}\n.orquesta-builder-header-right{display:flex;align-items:center;gap:8px}\n.orquesta-builder-logo{font-weight:700;font-size:14px;color:#fafafa;letter-spacing:-0.02em}\n.orquesta-builder-project{font-size:13px;color:#a1a1aa}\n.orquesta-builder-status{display:flex;align-items:center;gap:6px;font-size:12px;color:#a1a1aa}\n.orquesta-builder-status-dot{width:8px;height:8px;border-radius:50%}\n.orquesta-builder-main{display:flex;flex:1;min-height:0}\n.orquesta-builder-chat{display:flex;flex-direction:column;width:380px;min-width:300px;max-width:50%;border-right:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}\n.orquesta-builder-chat-input{padding:12px 16px;border-top:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-input textarea{width:100%;min-height:60px;max-height:200px;padding:10px 12px;background:#27272a;border:1px solid #3f3f46;border-radius:8px;color:#fafafa;font-size:13px;resize:vertical;outline:none;font-family:inherit}\n.orquesta-builder-chat-input textarea:focus{border-color:#3b82f6}\n.orquesta-builder-chat-input-actions{display:flex;justify-content:space-between;align-items:center;margin-top:8px}\n.orquesta-builder-preview{flex:1;display:flex;flex-direction:column;min-width:0}\n.orquesta-builder-preview-bar{display:flex;align-items:center;height:36px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;gap:8px;flex-shrink:0}\n.orquesta-builder-preview-url{flex:1;padding:4px 10px;background:#27272a;border:1px solid #3f3f46;border-radius:6px;color:#a1a1aa;font-size:12px;font-family:'SF Mono','Fira Code',monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.orquesta-builder-preview-iframe{flex:1;width:100%;border:none;background:#fff}\n.orquesta-builder-terminal{height:200px;min-height:100px;max-height:50vh;border-top:1px solid #27272a;background:#0a0a0a;display:flex;flex-direction:column;flex-shrink:0}\n.orquesta-builder-terminal-header{display:flex;align-items:center;justify-content:space-between;height:32px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-terminal-title{font-size:12px;font-weight:600;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.05em}\n.orquesta-builder-terminal-output{flex:1;overflow-y:auto;padding:8px 12px;font-family:'SF Mono','Fira Code','Cascadia Code',monospace;font-size:12px;line-height:1.5}\n.orquesta-builder-terminal.collapsed{height:32px;min-height:32px}\n.orquesta-builder-terminal.collapsed .orquesta-builder-terminal-output{display:none}\n.orquesta-builder-msg{max-width:90%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}\n.orquesta-builder-msg-user{align-self:flex-end;background:#3b82f6;color:#fff;border-bottom-right-radius:4px}\n.orquesta-builder-msg-system{align-self:flex-start;background:#27272a;color:#fafafa;border-bottom-left-radius:4px}\n.orquesta-builder-msg-status{align-self:center;background:transparent;color:#71717a;font-size:12px;padding:4px 0}\n.orquesta-builder-resizer-h{width:4px;cursor:col-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-h:hover{background:#3b82f6}\n.orquesta-builder-resizer-v{height:4px;cursor:row-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-v:hover{background:#3b82f6}\n.orquesta-builder button{background:transparent;border:none;color:#a1a1aa;cursor:pointer;padding:4px 8px;border-radius:4px;font-size:12px}\n.orquesta-builder button:hover{background:#27272a;color:#fafafa}\n.orquesta-builder-btn-primary{background:#3b82f6!important;color:#fff!important;font-weight:500;padding:6px 16px!important;border-radius:6px!important}\n.orquesta-builder-btn-primary:hover{background:#2563eb!important}\n.orquesta-builder-btn-primary:disabled{opacity:0.5;cursor:not-allowed}\n@media(max-width:768px){.orquesta-builder-main{flex-direction:column}.orquesta-builder-chat{width:100%;max-width:100%;height:50%;border-right:none;border-bottom:1px solid #27272a}.orquesta-builder-resizer-h{display:none}}\n",document.head.appendChild(t),Ue=!0}()},[]),l(()=>{"completed"!==g?.currentPrompt?.status&&"failed"!==g?.currentPrompt?.status||_(g.currentPrompt)},[g?.currentPrompt?.status,g?.currentPrompt]);const A=a(void 0);l(()=>{if(h&&g&&!g.isSubmitting&&g.promptQueue&&g.promptQueue.length>0){const e=setTimeout(()=>{const[e,...t]=g.promptQueue;e&&(console.log("[Orquesta Embed Demo] Processing queued prompt"),f(e=>e?{...e,promptQueue:t}:null),A.current?.())},300);return()=>clearTimeout(e)}},[h,g?.isSubmitting,g?.promptQueue?.length]),l(()=>{if(h)return L.current=new je,s&&L.current&&(z.current=L.current.setupGlobalRightClickWithPosition((e,t)=>{L.current&&L.current.highlightSelectedElement(e.selector),k({isOpen:!0,position:t,element:e})})),()=>{z.current&&(z.current(),z.current=null)}},[h,s]),l(()=>{if(h)return;const e=new Fe(p);m(e);const t=e.subscribe(e=>{f(e)});return e.connect().catch(e=>{w(e.message)}),s&&(z.current=e.setupGlobalRightClickWithPosition((t,n)=>{e.getElementSelector().deactivate(),e.getElementSelector().highlightSelectedElement(t.selector),k({isOpen:!0,position:n,element:t})})),()=>{t(),z.current&&(z.current(),z.current=null),e.disconnect()}},[p.token,s,h]);const O=c(()=>{h?f(e=>e?{...e,isOpen:!1}:null):u?.close()},[u,h]),T=c(()=>{x(!0)},[]),R=c(()=>{x(!1),h?f(e=>e?{...e,isOpen:!0}:null):u?.open()},[u,h]),H=c(async(e,t)=>{if(h){const n=t||g?.selectedElement||void 0;if(g?.isSubmitting)return f(t=>t?{...t,promptQueue:[...t.promptQueue||[],{id:`queue-${Date.now()}`,content:e,options:{elementContext:n},queuedAt:Date.now()}]}:null),void console.log("[Orquesta Embed Demo] Prompt queued");const o={id:`demo-prompt-${Date.now()}`,content:e,status:"running",created_at:(new Date).toISOString(),user_id:"demo-user",source:"embed",element_context:n,author:{id:"demo-user",full_name:"Demo User",avatar_url:null},comment_count:0};f(e=>e?{...e,isSubmitting:!0,currentPrompt:o,outputLines:[],promptHistory:[o,...e.promptHistory]}:null);const r=e.toLowerCase();let i="Tool: Edit file",s="Changes applied successfully.";r.includes("button")||r.includes("color")||r.includes("green")?(i="Tool: Edit src/components/Button.tsx",s="Button styles updated."):r.includes("banner")||r.includes("sale")?(i="Tool: Create src/components/Banner.tsx",s="Banner component created and mounted."):r.includes("discount")||r.includes("price")?(i="Tool: Edit src/components/ProductCard.tsx",s="Discount pricing applied to products."):r.includes("headline")||r.includes("bigger")||r.includes("title")?(i="Tool: Edit src/app/page.tsx",s="Headline styles updated."):r.includes("dark")&&(i="Tool: Edit src/styles/globals.css",s="Dark mode theme applied.");return[{delay:200,type:"system",content:"Starting Claude CLI session..."},{delay:600,type:"thinking",content:"Analyzing the request..."},{delay:1e3,type:"stdout",content:`Processing: "${e.slice(0,50)}${e.length>50?"...":""}"`},{delay:1400,type:"tool",content:i},{delay:1800,type:"stdout",content:s}].forEach(({delay:e,type:t,content:n})=>{setTimeout(()=>{f(e=>e?{...e,outputLines:[...e.outputLines,{id:`output-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestamp:Date.now(),type:t,content:n}]}:null)},e)}),void setTimeout(()=>{f(e=>{if(!e)return null;const t={...o,status:"completed",completed_at:(new Date).toISOString(),git_branch:"main",git_commit_sha:Math.random().toString(36).slice(2,9)},n=[...e.outputLines,{id:`output-${Date.now()}-complete`,timestamp:Date.now(),type:"system",content:"Prompt completed successfully."}];return{...e,isSubmitting:!1,currentPrompt:t,selectedElement:null,outputLines:n,promptOutputs:{...e.promptOutputs,[o.id]:n},promptHistory:e.promptHistory.map(e=>e.id===o.id?t:e)}}),p.onDemoComplete&&p.onDemoComplete(e)},2200)}if(u)try{await u.submitPrompt(e,{elementContext:t||void 0})}catch(e){console.error("Failed to submit prompt:",e)}},[u,h,g?.selectedElement,g?.isSubmitting]);l(()=>{h&&g?.promptQueue&&g.promptQueue.length>0&&(A.current=()=>{const e=g.promptQueue[0];e&&H(e.content,e.options?.elementContext)})},[h,g?.promptQueue,H]);const M=c(()=>{h?(f(e=>e?{...e,isSelectingElement:!0}:null),L.current?.activate(e=>{f(t=>t?{...t,selectedElement:e,isSelectingElement:!1}:null)},()=>{f(e=>e?{...e,isSelectingElement:!1}:null)})):u?.startElementSelection()},[u,h]),P=c(()=>{h?(f(e=>e?{...e,selectedElement:null}:null),L.current?.deactivate(),L.current?.removeSelectedHighlight()):u&&(f(e=>e?{...e,selectedElement:null}:null),u.getElementSelector().deactivate(),u.getElementSelector().removeSelectedHighlight())},[u,h]),j=c(()=>{g&&f(e=>e?{...e,includeConsole:!e.includeConsole}:null)},[g]),B=c(()=>{g&&f(e=>e?{...e,includeNetwork:!e.includeNetwork}:null)},[g]),I=c(()=>{g&&f(e=>e?{...e,includeHistory:!e.includeHistory}:null)},[g]),$=c(e=>{g&&(f(t=>t?{...t,activeTab:e}:null),We.set("activeTab",e),u?.setActiveTab(e))},[g,u]),D=c(()=>{f(e=>{if(!e)return null;const t=!e.rightClickEnabled;return t?h&&L.current?z.current=L.current.setupGlobalRightClickWithPosition((e,t)=>{L.current?.highlightSelectedElement(e.selector),k({isOpen:!0,position:t,element:e})}):u&&(z.current=u.setupGlobalRightClickWithPosition((e,t)=>{u.getElementSelector().deactivate(),u.getElementSelector().highlightSelectedElement(e.selector),k({isOpen:!0,position:t,element:e})})):z.current&&(z.current(),z.current=null),{...e,rightClickEnabled:t}})},[h,u]),W=c(()=>{h?(L.current?.deactivate(),f(e=>e?{...e,isSelectingElement:!1}:null)):u?.getElementSelector().deactivate()},[u,h]),F=c(e=>{g&&f(t=>t?{...t,expandedPromptId:e}:null)},[g]),U=c(e=>{if(e.element_context?.selector)if(h){const t=L.current?.highlightElement(e.element_context.selector);t?f(t=>t?{...t,overlayMode:"single",highlightedPromptId:e.id}:null):(console.warn("[Orquesta Embed] Element not found for selector:",e.element_context.selector),f(e=>e?{...e,outputLines:[...e.outputLines,{id:`warn-${Date.now()}`,timestamp:Date.now(),type:"system",content:"⚠️ Element not found on page. The element may have been removed or changed since this prompt was created."}]}:null))}else{const t=e.element_context.selector;let n=null;try{n=document.querySelector(t)}catch{console.warn("[Orquesta Embed] Invalid selector syntax:",t)}n?u?.highlightPromptElement(e):(console.warn("[Orquesta Embed] Element not found for selector:",t),f(e=>e?{...e,outputLines:[...e.outputLines,{id:`warn-${Date.now()}`,timestamp:Date.now(),type:"system",content:"⚠️ Element not found on page. The element may have been removed or changed since this prompt was created."}]}:null))}else console.warn("[Orquesta Embed] Prompt has no element context")},[u,h]),V=c(async e=>{h||u&&await u.loadComments(e)},[u,h]),Q=c(async(e,t)=>{if(h){const n={id:`comment-${Date.now()}`,content:t,created_at:(new Date).toISOString(),author:{id:"demo-user",full_name:"Demo User",avatar_url:null}};return void f(t=>{if(!t)return null;const o=t.comments[e]||[];return{...t,comments:{...t.comments,[e]:[...o,n]},promptHistory:t.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)}})}u&&await u.addComment(e,t)},[u,h]),K=c(e=>{h?f(t=>{if(!t)return null;let n=t.elementMarkers;return"all"===e?n=t.promptHistory.filter(e=>e.element_context?.selector).map(e=>{let t=null;try{t=document.querySelector(e.element_context.selector)}catch{}return{promptId:e.id,selector:e.element_context.selector,rect:t?.getBoundingClientRect()||null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}}):"off"===e&&(L.current?.removeHighlight(),n=[]),{...t,overlayMode:e,highlightedPromptId:"off"===e?null:t.highlightedPromptId,elementMarkers:n}}):u?.setOverlayMode(e)},[u,h]),X=c(e=>{g&&f(t=>t?{...t,activeTab:"timeline",expandedPromptId:e}:null)},[g]),Y=c(()=>{k(e=>({...e,isOpen:!1})),h&&L.current?L.current.removeSelectedHighlight():u&&u.getElementSelector().removeSelectedHighlight()},[u,h]),J=c(async e=>{v.element&&(f(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),x(!1),await H(e,v.element||void 0),k(e=>({...e,isOpen:!1})))},[v.element,H]),G=c(()=>{v.element&&(f(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),x(!1),k(e=>({...e,isOpen:!1})))},[v.element]),Z=c(async()=>{if(h){const e={id:"demo-user-id",full_name:"Demo User",avatar_url:null};return f(t=>t?{...t,isAuthenticated:!0,user:e,authError:null}:null),void p.onLogin?.(e)}if(u)try{await u.login()}catch(e){console.error("Login failed:",e)}},[u,h,p]),ee=c(async()=>{if(h)return f(e=>e?{...e,isAuthenticated:!1,user:null}:null),void p.onLogout?.();if(u)try{await u.logout()}catch(e){console.error("Logout failed:",e)}},[u,h,p]);if(y){const{title:n,message:o,hint:r}=(te=y).includes("401")||te.includes("Invalid token")||te.includes("Unauthorized")?{title:"Authentication Failed",message:"The embed token is invalid or has expired.",hint:"Generate a new token from the Orquesta dashboard → Project Settings → Embed"}:te.includes("403")||te.includes("Domain not allowed")?{title:"Domain Not Allowed",message:"This domain is not authorized to use this embed token.",hint:"Add this domain to the allowed domains in Project Settings → Embed"}:te.includes("404")||te.includes("Project not found")?{title:"Project Not Found",message:"The project associated with this token no longer exists.",hint:"Check if the project was deleted or create a new embed token"}:te.includes("network")||te.includes("Failed to fetch")?{title:"Connection Failed",message:"Unable to connect to Orquesta servers.",hint:"Check your internet connection and try again"}:{title:"Connection Error",message:te,hint:"Please check your configuration and try again"};return e("div",{className:"orquesta-embed-error fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl overflow-hidden",style:{[p.position?.includes("right")?"right":"left"]:"20px",[p.position?.includes("top")?"top":"bottom"]:"20px",width:"360px"},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"})]}),t("div",{className:"flex items-center gap-1",children:t("span",{className:"w-2 h-2 rounded-full bg-red-500",title:"Disconnected"})})]}),e("div",{className:"p-4",children:[e("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0",children:t("svg",{className:"w-5 h-5 text-red-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),e("div",{className:"flex-1",children:[t("h3",{className:"text-white font-semibold text-sm",children:n}),t("p",{className:"text-zinc-400 text-xs mt-1",children:o}),e("p",{className:"text-zinc-500 text-xs mt-2 flex items-center gap-1",children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r]})]})]}),e("button",{onClick:()=>{w(null),u?.connect().catch(e=>w(e.message))},className:"mt-4 w-full px-3 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 text-xs font-medium rounded-lg transition-colors flex items-center justify-center gap-2",children:[t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry Connection"]})]})]})}var te;return!g||g.isConnecting?e("div",{className:"orquesta-embed-loading fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl overflow-hidden",style:{[p.position?.includes("right")?"right":"left"]:"20px",[p.position?.includes("top")?"top":"bottom"]:"20px",width:"320px"},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"})]}),t("div",{className:"flex items-center gap-1",children:t("span",{className:"w-2 h-2 rounded-full bg-yellow-500 animate-pulse",title:"Connecting..."})})]}),e("div",{className:"p-6 flex flex-col items-center",children:[e("svg",{className:"animate-spin h-8 w-8 text-zinc-400 mb-3",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{className:"text-zinc-300 text-sm",children:"Connecting to Orquesta..."}),t("span",{className:"text-zinc-500 text-xs mt-1",children:"Validating token and establishing connection"})]})]}):e(n,{children:[S&&t(yt,{isConnected:g.isConnected,agentOnline:g.agentOnline,projectName:g.projectName,currentPrompt:g.currentPrompt,isSubmitting:g.isSubmitting,lastCompletedPrompt:E,onClose:()=>q(!1)}),"widget"===C&&(b||!g.isOpen)&&e("button",{onClick:R,className:"orquesta-embed-trigger fixed z-[2147483647] p-3 bg-zinc-900 border border-zinc-700 rounded-full shadow-xl hover:bg-zinc-800 transition-colors",style:{[p.position?.includes("right")?"right":"left"]:"20px",[p.position?.includes("top")?"top":"bottom"]:"20px"},title:"Open Orquesta",children:[t("span",{className:"text-xl",children:"⬡"}),g.agentOnline&&t("span",{className:"absolute top-1 right-1 w-2 h-2 bg-green-500 rounded-full"})]}),"builder"===C&&t(gt,{state:g,onSubmitPrompt:H,onSwitchToWidget:()=>{N("widget"),x(!1),h?f(e=>e?{...e,isOpen:!0}:null):u?.open()},onSelectElement:M,onClearElement:P,onToggleConsole:j,onToggleNetwork:B,onToggleHistory:I,onTabChange:$,onExpandPrompt:F,onHighlightElement:U,onLoadComments:V,onAddComment:Q,onOverlayModeChange:K,onLogin:Z,onLogout:ee,onToggleRightClick:D,demoMode:h}),"widget"===C&&g.isOpen&&!b&&t(mt,{state:g,position:p.position||"bottom-right",onClose:O,onMinimize:T,onSubmitPrompt:H,onSelectElement:M,onClearElement:P,onToggleConsole:j,onToggleNetwork:B,onToggleHistory:I,onTabChange:$,onExpandPrompt:F,onHighlightElement:U,onLoadComments:V,onAddComment:Q,onOverlayModeChange:K,onLogin:Z,onLogout:ee,onToggleRightClick:D,onExpandToBuilder:()=>N("builder"),demoMode:h}),t(ft,{isActive:g.isSelectingElement,onCancel:W}),"all"===g.overlayMode&&g.elementMarkers.length>0&&t(bt,{markers:g.elementMarkers,onMarkerClick:X}),t(xt,{isOpen:v.isOpen,position:v.position,element:v.element,agentOnline:g.agentOnline,includeConsole:g.includeConsole,includeNetwork:g.includeNetwork,onSubmit:J,onClose:Y,onToggleConsole:j,onToggleNetwork:B,onOpenPanel:G}),r]})}export{Be as AuthManager,st as AuthorAvatar,Xe as Badge,gt as BuilderPanel,Ve as Button,dt as CommentInput,ct as CommentList,Me as ConsoleCapture,d as EMBED_VERSION,ft as ElementInspector,bt as ElementMarkers,je as ElementSelector,mt as EmbedPanel,at as GitCommitLink,Qe as Input,it as LogStream,Pe as NetworkCapture,Ct as OrquestaEmbed,Fe as OrquestaEmbedClient,rt as PromptInput,He as StateManager,Ye as StatusDot,Ze as Tabs,nt as TabsContent,et as TabsList,tt as TabsTrigger,Ke as Textarea,ht as Timeline,We as storage};
|
|
1
|
+
import{jsxs as e,jsx as t,Fragment as n}from"react/jsx-runtime";import o,{createContext as r,useState as i,useContext as s,useRef as a,useEffect as l,useCallback as c}from"react";const d="0.2.1",h=Object.create(null);h.open="0",h.close="1",h.ping="2",h.pong="3",h.message="4",h.upgrade="5",h.noop="6";const p=Object.create(null);Object.keys(h).forEach(e=>{p[h[e]]=e});const u={type:"error",data:"parser error"},m="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),g="function"==typeof ArrayBuffer,f=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,b=({type:e,data:t},n,o)=>m&&t instanceof Blob?n?o(t):x(t,o):g&&(t instanceof ArrayBuffer||f(t))?n?o(t):x(new Blob([t]),o):o(h[e]+(t||"")),x=(e,t)=>{const n=new FileReader;return n.onload=function(){const e=n.result.split(",")[1];t("b"+(e||""))},n.readAsDataURL(e)};function y(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let w;const v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",k="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let e=0;e<64;e++)k[v.charCodeAt(e)]=e;const C="function"==typeof ArrayBuffer,N=(e,t)=>{if("string"!=typeof e)return{type:"message",data:q(e,t)};const n=e.charAt(0);if("b"===n)return{type:"message",data:S(e.substring(1),t)};return p[n]?e.length>1?{type:p[n],data:e.substring(1)}:{type:p[n]}:u},S=(e,t)=>{if(C){const n=(e=>{let t,n,o,r,i,s=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const c=new ArrayBuffer(s),d=new Uint8Array(c);for(t=0;t<a;t+=4)n=k[e.charCodeAt(t)],o=k[e.charCodeAt(t+1)],r=k[e.charCodeAt(t+2)],i=k[e.charCodeAt(t+3)],d[l++]=n<<2|o>>4,d[l++]=(15&o)<<4|r>>2,d[l++]=(3&r)<<6|63&i;return c})(e);return q(n,t)}return{base64:!0,data:e}},q=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,E=String.fromCharCode(30);function _(){return new TransformStream({transform(e,t){!function(e,t){m&&e.data instanceof Blob?e.data.arrayBuffer().then(y).then(t):g&&(e.data instanceof ArrayBuffer||f(e.data))?t(y(e.data)):b(e,!1,e=>{w||(w=new TextEncoder),t(w.encode(e))})}(e,n=>{const o=n.length;let r;if(o<126)r=new Uint8Array(1),new DataView(r.buffer).setUint8(0,o);else if(o<65536){r=new Uint8Array(3);const e=new DataView(r.buffer);e.setUint8(0,126),e.setUint16(1,o)}else{r=new Uint8Array(9);const e=new DataView(r.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(o))}e.data&&"string"!=typeof e.data&&(r[0]|=128),t.enqueue(r),t.enqueue(n)})}})}let z;function L(e){return e.reduce((e,t)=>e+t.length,0)}function A(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let o=0;for(let r=0;r<t;r++)n[r]=e[0][o++],o===e[0].length&&(e.shift(),o=0);return e.length&&o<e[0].length&&(e[0]=e[0].slice(o)),n}function O(e){if(e)return function(e){for(var t in O.prototype)e[t]=O.prototype[t];return e}(e)}O.prototype.on=O.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},O.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this},O.prototype.off=O.prototype.removeListener=O.prototype.removeAllListeners=O.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,o=this._callbacks["$"+e];if(!o)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var r=0;r<o.length;r++)if((n=o[r])===t||n.fn===t){o.splice(r,1);break}return 0===o.length&&delete this._callbacks["$"+e],this},O.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),n=this._callbacks["$"+e],o=1;o<arguments.length;o++)t[o-1]=arguments[o];if(n){o=0;for(var r=(n=n.slice(0)).length;o<r;++o)n[o].apply(this,t)}return this},O.prototype.emitReserved=O.prototype.emit,O.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},O.prototype.hasListeners=function(e){return!!this.listeners(e).length};const T="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function H(e,...t){return t.reduce((t,n)=>(e.hasOwnProperty(n)&&(t[n]=e[n]),t),{})}const M=R.setTimeout,P=R.clearTimeout;function j(e,t){t.useNativeTimers?(e.setTimeoutFn=M.bind(R),e.clearTimeoutFn=P.bind(R)):(e.setTimeoutFn=R.setTimeout.bind(R),e.clearTimeoutFn=R.clearTimeout.bind(R))}function B(e){return"string"==typeof e?function(e){let t=0,n=0;for(let o=0,r=e.length;o<r;o++)t=e.charCodeAt(o),t<128?n+=1:t<2048?n+=2:t<55296||t>=57344?n+=3:(o++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))}function I(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class $ extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class D extends O{constructor(e){super(),this.writable=!1,j(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,n){return super.emitReserved("error",new $(e,t,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=N(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}(e);return t.length?"?"+t:""}}class W extends D{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const n=e.split(E),o=[];for(let e=0;e<n.length;e++){const r=N(n[e],t);if(o.push(r),"error"===r.type)break}return o})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const n=e.length,o=new Array(n);let r=0;e.forEach((e,i)=>{b(e,!1,e=>{o[i]=e,++r===n&&t(o.join(E))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=I()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let F=!1;try{F="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){}const U=F;function V(){}class Q extends W{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let n=location.port;n||(n=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||n!==e.port}}doWrite(e,t){const n=this.request({method:"POST",data:e});n.on("success",t),n.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}class K extends O{constructor(e,t,n){super(),this.createRequest=e,j(this,n),this._opts=n,this._method=n.method||"GET",this._uri=t,this._data=void 0!==n.data?n.data:null,this._create()}_create(){var e;const t=H(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(t);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(e){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this._opts.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(e){return void this.setTimeoutFn(()=>{this._onError(e)},0)}"undefined"!=typeof document&&(this._index=K.requestsCount++,K.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=V,e)try{this._xhr.abort()}catch(e){}"undefined"!=typeof document&&delete K.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}}if(K.requestsCount=0,K.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",X);else if("function"==typeof addEventListener){addEventListener("onpagehide"in R?"pagehide":"unload",X,!1)}function X(){for(let e in K.requests)K.requests.hasOwnProperty(e)&&K.requests[e].abort()}const Y=function(){const e=J({xdomain:!1});return e&&null!==e.responseType}();function J(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||U))return new XMLHttpRequest}catch(e){}if(!t)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}const G="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Z extends D{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=G?{}:H(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,n)}catch(e){return this.emitReserved("error",e)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],o=t===e.length-1;b(n,this.supportsBinary,e=>{try{this.doWrite(n,e)}catch(e){}o&&T(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=I()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ee=R.WebSocket||R.MozWebSocket;const te={websocket:class extends Z{createSocket(e,t,n){return G?new ee(e,t,n):t?new ee(e,t):new ee(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends D{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){z||(z=new TextDecoder);const n=[];let o=0,r=-1,i=!1;return new TransformStream({transform(s,a){for(n.push(s);;){if(0===o){if(L(n)<1)break;const e=A(n,1);i=!(128&~e[0]),r=127&e[0],o=r<126?3:126===r?1:2}else if(1===o){if(L(n)<2)break;const e=A(n,2);r=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),o=3}else if(2===o){if(L(n)<8)break;const e=A(n,8),t=new DataView(e.buffer,e.byteOffset,e.length),i=t.getUint32(0);if(i>Math.pow(2,21)-1){a.enqueue(u);break}r=i*Math.pow(2,32)+t.getUint32(4),o=3}else{if(L(n)<r)break;const e=A(n,r);a.enqueue(N(i?e:z.decode(e),t)),o=0}if(0===r||r>e){a.enqueue(u);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),o=_();o.readable.pipeTo(e.writable),this._writer=o.writable.getWriter();const r=()=>{n.read().then(({done:e,value:t})=>{e||(this.onPacket(t),r())}).catch(e=>{})};r();const i={type:"open"};this.query.sid&&(i.data=`{"sid":"${this.query.sid}"}`),this._writer.write(i).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const n=e[t],o=t===e.length-1;this._writer.write(n).then(()=>{o&&T(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends Q{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Y&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new K(J,this.uri(),e)}}},ne=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,oe=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function re(e){if(e.length>8e3)throw"URI too long";const t=e,n=e.indexOf("["),o=e.indexOf("]");-1!=n&&-1!=o&&(e=e.substring(0,n)+e.substring(n,o).replace(/:/g,";")+e.substring(o,e.length));let r=ne.exec(e||""),i={},s=14;for(;s--;)i[oe[s]]=r[s]||"";return-1!=n&&-1!=o&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=function(e,t){const n=/\/{2,9}/g,o=t.replace(n,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||o.splice(0,1);"/"==t.slice(-1)&&o.splice(o.length-1,1);return o}(0,i.path),i.queryKey=function(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,o){t&&(n[t]=o)}),n}(0,i.query),i}const ie="function"==typeof addEventListener&&"function"==typeof removeEventListener,se=[];ie&&addEventListener("offline",()=>{se.forEach(e=>e())},!1);class ae extends O{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const n=re(e);t.hostname=n.host,t.secure="https"===n.protocol||"wss"===n.protocol,t.port=n.port,n.query&&(t.query=n.query)}else t.host&&(t.hostname=re(t.host).host);j(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},n=e.split("&");for(let e=0,o=n.length;e<o;e++){let o=n[e].split("=");t[decodeURIComponent(o[0])]=decodeURIComponent(o[1])}return t}(this.opts.query)),ie&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},se.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const n=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](n)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&ae.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",ae.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const n=this.writeBuffer[t].data;if(n&&(e+=B(n)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,T(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,n){return this._sendPacket("message",e,t,n),this}send(e,t,n){return this._sendPacket("message",e,t,n),this}_sendPacket(e,t,n,o){if("function"==typeof t&&(o=t,t=void 0),"function"==typeof n&&(o=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const r={type:e,data:t,options:n};this.emitReserved("packetCreate",r),this.writeBuffer.push(r),o&&this.once("flush",o),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},n=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():e()}):this.upgrading?n():e()),this}_onError(e){if(ae.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ie&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=se.indexOf(this._offlineEventListener);-1!==e&&se.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}ae.protocol=4;class le extends ae{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),n=!1;ae.priorWebsocketSuccess=!1;const o=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!n)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ae.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(c(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function r(){n||(n=!0,c(),t.close(),t=null)}const i=e=>{const n=new Error("probe error: "+e);n.transport=t.name,r(),this.emitReserved("upgradeError",n)};function s(){i("transport closed")}function a(){i("socket closed")}function l(e){t&&e.name!==t.name&&r()}const c=()=>{t.removeListener("open",o),t.removeListener("error",i),t.removeListener("close",s),this.off("close",a),this.off("upgrading",l)};t.once("open",o),t.once("error",i),t.once("close",s),this.once("close",a),this.once("upgrading",l),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{n||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let n=0;n<e.length;n++)~this.transports.indexOf(e[n])&&t.push(e[n]);return t}}let ce=class extends le{constructor(e,t={}){const n="object"==typeof e?e:t;(!n.transports||n.transports&&"string"==typeof n.transports[0])&&(n.transports=(n.transports||["polling","websocket","webtransport"]).map(e=>te[e]).filter(e=>!!e)),super(e,n)}};const de="function"==typeof ArrayBuffer,he=Object.prototype.toString,pe="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===he.call(Blob),ue="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===he.call(File);function me(e){return de&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||pe&&e instanceof Blob||ue&&e instanceof File}function ge(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,n=e.length;t<n;t++)if(ge(e[t]))return!0;return!1}if(me(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return ge(e.toJSON(),!0);for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t)&&ge(e[t]))return!0;return!1}function fe(e){const t=[],n=e.data,o=e;return o.data=be(n,t),o.attachments=t.length,{packet:o,buffers:t}}function be(e,t){if(!e)return e;if(me(e)){const n={_placeholder:!0,num:t.length};return t.push(e),n}if(Array.isArray(e)){const n=new Array(e.length);for(let o=0;o<e.length;o++)n[o]=be(e[o],t);return n}if("object"==typeof e&&!(e instanceof Date)){const n={};for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=be(e[o],t));return n}return e}function xe(e,t){return e.data=ye(e.data,t),delete e.attachments,e}function ye(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let n=0;n<e.length;n++)e[n]=ye(e[n],t);else if("object"==typeof e)for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(e[n]=ye(e[n],t));return e}const we=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ve;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(ve||(ve={}));class ke extends O{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof e?{reviver:e}:e)}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const n=t.type===ve.BINARY_EVENT;n||t.type===ve.BINARY_ACK?(t.type=n?ve.EVENT:ve.ACK,this.reconstructor=new Ce(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!me(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const n={type:Number(e.charAt(0))};if(void 0===ve[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ve.BINARY_EVENT||n.type===ve.BINARY_ACK){const o=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const r=e.substring(o,t);if(r!=Number(r)||"-"!==e.charAt(t))throw new Error("Illegal attachments");const i=Number(r);if(!Ne(i)||i<0)throw new Error("Illegal attachments");if(i>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=i}if("/"===e.charAt(t+1)){const o=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}n.nsp=e.substring(o,t)}else n.nsp="/";const o=e.charAt(t+1);if(""!==o&&Number(o)==o){const o=t+1;for(;++t;){const n=e.charAt(t);if(null==n||Number(n)!=n){--t;break}if(t===e.length)break}n.id=Number(e.substring(o,t+1))}if(e.charAt(++t)){const o=this.tryParse(e.substr(t));if(!ke.isPayloadValid(n.type,o))throw new Error("invalid payload");n.data=o}return n}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch(e){return!1}}static isPayloadValid(e,t){switch(e){case ve.CONNECT:return Se(t);case ve.DISCONNECT:return void 0===t;case ve.CONNECT_ERROR:return"string"==typeof t||Se(t);case ve.EVENT:case ve.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===we.indexOf(t[0]));case ve.ACK:case ve.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Ce{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=xe(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Ne=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e};function Se(e){return"[object Object]"===Object.prototype.toString.call(e)}var qe=Object.freeze({__proto__:null,Decoder:ke,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==ve.EVENT&&e.type!==ve.ACK||!ge(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===ve.EVENT?ve.BINARY_EVENT:ve.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==ve.BINARY_EVENT&&e.type!==ve.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=fe(e),n=this.encodeAsString(t.packet),o=t.buffers;return o.unshift(n),o}},get PacketType(){return ve},isPacketValid:function(e){return"string"==typeof e.nsp&&(void 0===(t=e.id)||Ne(t))&&function(e,t){switch(e){case ve.CONNECT:return void 0===t||Se(t);case ve.DISCONNECT:return void 0===t;case ve.EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===we.indexOf(t[0]));case ve.ACK:return Array.isArray(t);case ve.CONNECT_ERROR:return"string"==typeof t||Se(t);default:return!1}}(e.type,e.data);var t},protocol:5});function Ee(e,t,n){return e.on(t,n),function(){e.off(t,n)}}const _e=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ze extends O{constructor(e,t,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,n&&n.auth&&(this.auth=n.auth),this._opts=Object.assign({},n),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Ee(e,"open",this.onopen.bind(this)),Ee(e,"packet",this.onpacket.bind(this)),Ee(e,"error",this.onerror.bind(this)),Ee(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var n,o,r;if(_e.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const i={type:ve.EVENT,data:t,options:{}};if(i.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,n=t.pop();this._registerAckCallback(e,n),i.id=e}const s=null===(o=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===o?void 0:o.writable,a=this.connected&&!(null===(r=this.io.engine)||void 0===r?void 0:r._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(i),this.packet(i)):this.sendBuffer.push(i)),this.flags={},this}_registerAckCallback(e,t){var n;const o=null!==(n=this.flags.timeout)&&void 0!==n?n:this._opts.ackTimeout;if(void 0===o)return void(this.acks[e]=t);const r=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},o),i=(...e)=>{this.io.clearTimeoutFn(r),t.apply(this,e)};i.withError=!0,this.acks[e]=i}emitWithAck(e,...t){return new Promise((n,o)=>{const r=(e,t)=>e?o(e):n(t);r.withError=!0,t.push(r),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const n={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...o)=>{this._queue[0];return null!==e?n.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...o)),n.pending=!1,this._drainQueue()}),this._queue.push(n),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:ve.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case ve.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case ve.EVENT:case ve.BINARY_EVENT:this.onevent(e);break;case ve.ACK:case ve.BINARY_ACK:this.onack(e);break;case ve.DISCONNECT:this.ondisconnect();break;case ve.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const n of t)n.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let n=!1;return function(...o){n||(n=!0,t.packet({type:ve.ACK,id:e,data:o}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:ve.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let n=0;n<t.length;n++)if(e===t[n])return t.splice(n,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const n of t)n.apply(this,e.data)}}}function Le(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Le.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+n:e-n}return 0|Math.min(e,this.max)},Le.prototype.reset=function(){this.attempts=0},Le.prototype.setMin=function(e){this.ms=e},Le.prototype.setMax=function(e){this.max=e},Le.prototype.setJitter=function(e){this.jitter=e};class Ae extends O{constructor(e,t){var n;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,j(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=t.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new Le({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const o=t.parser||qe;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new ce(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const o=Ee(t,"open",function(){n.onopen(),e&&e()}),r=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},i=Ee(t,"error",r);if(!1!==this._timeout){const e=this._timeout,n=this.setTimeoutFn(()=>{o(),r(new Error("timeout")),t.close()},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(o),this.subs.push(i),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Ee(e,"ping",this.onping.bind(this)),Ee(e,"data",this.ondata.bind(this)),Ee(e,"error",this.onerror.bind(this)),Ee(e,"close",this.onclose.bind(this)),Ee(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(e){this.onclose("parse error",e)}}ondecoded(e){T(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let n=this.nsps[e];return n?this._autoConnect&&!n.active&&n.connect():(n=new ze(this,e,t),this.nsps[e]=n),n}_destroy(e){const t=Object.keys(this.nsps);for(const e of t){if(this.nsps[e].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let n=0;n<t.length;n++)this.engine.write(t[n],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const n=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const Oe={};function Te(e,t){"object"==typeof e&&(t=e,e=void 0);const n=function(e,t="",n){let o=e;n=n||"undefined"!=typeof location&&location,null==e&&(e=n.protocol+"//"+n.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?n.protocol+e:n.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==n?n.protocol+"//"+e:"https://"+e),o=re(e)),o.port||(/^(http|ws)$/.test(o.protocol)?o.port="80":/^(http|ws)s$/.test(o.protocol)&&(o.port="443")),o.path=o.path||"/";const r=-1!==o.host.indexOf(":")?"["+o.host+"]":o.host;return o.id=o.protocol+"://"+r+":"+o.port+t,o.href=o.protocol+"://"+r+(n&&n.port===o.port?"":":"+o.port),o}(e,(t=t||{}).path||"/socket.io"),o=n.source,r=n.id,i=n.path,s=Oe[r]&&i in Oe[r].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new Ae(o,t):(Oe[r]||(Oe[r]=new Ae(o,t)),a=Oe[r]),n.query&&!t.query&&(t.query=n.queryKey),a.socket(n.path,t)}Object.assign(Te,{Manager:Ae,Socket:ze,io:Te,connect:Te});const Re={mode:"widget",position:"bottom-right",defaultOpen:!1,theme:"dark",features:["prompts","timeline","deployments","elements","captures"],captureConsole:!0,captureNetwork:!0,hotkey:"ctrl+shift+o",apiUrl:"https://orquesta.live"};class He{constructor(){this.listeners=new Set,this.state=this.getInitialState()}getInitialState(){return{isConnected:!1,isConnecting:!1,connectionError:null,projectId:null,projectName:null,agentOnline:!1,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[],isSubmitting:!1,promptQueue:[],outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}setConnected(e,t,n){this.setState({isConnected:!0,isConnecting:!1,connectionError:null,projectId:e,projectName:t,agentOnline:n})}setConnectionError(e){this.setState({isConnected:!1,isConnecting:!1,connectionError:e})}setOpen(e){this.setState({isOpen:e})}toggle(){this.setState({isOpen:!this.state.isOpen})}setActiveTab(e){this.setState({activeTab:e})}setCurrentPrompt(e){this.setState({currentPrompt:e}),e&&!this.state.promptHistory.find(t=>t.id===e.id)&&this.setState({promptHistory:[e,...this.state.promptHistory].slice(0,50)})}updatePrompt(e,t){this.state.currentPrompt?.id===e&&this.setState({currentPrompt:{...this.state.currentPrompt,...t}}),this.setState({promptHistory:this.state.promptHistory.map(n=>n.id===e?{...n,...t}:n)})}addOutputLine(e){const t={...e,id:`${Date.now()}-${Math.random().toString(36).slice(2,9)}`};this.setState({outputLines:[...this.state.outputLines,t]})}clearOutput(){this.setState({outputLines:[]})}storePromptOutput(e){this.state.outputLines.length>0&&this.setState({promptOutputs:{...this.state.promptOutputs,[e]:[...this.state.outputLines]}})}addToQueue(e){this.setState({promptQueue:[...this.state.promptQueue,e]})}getNextFromQueue(){if(0===this.state.promptQueue.length)return null;const[e,...t]=this.state.promptQueue;return this.setState({promptQueue:t}),e}clearQueue(){this.setState({promptQueue:[]})}getQueueLength(){return this.state.promptQueue.length}setSelectedElement(e){this.setState({selectedElement:e,isSelectingElement:!1})}startElementSelection(){this.setState({isSelectingElement:!0})}cancelElementSelection(){this.setState({isSelectingElement:!1,selectedElement:null})}setOverlayMode(e){this.setState({overlayMode:e}),"off"===e&&this.setState({highlightedPromptId:null})}setHighlightedPromptId(e){this.setState({highlightedPromptId:e})}setElementMarkers(e){this.setState({elementMarkers:e})}setCommentsForPrompt(e,t){this.setState({comments:{...this.state.comments,[e]:t}})}addComment(e,t){const n=this.state.comments[e]||[];this.setState({comments:{...this.state.comments,[e]:[...n,t]}}),this.setState({promptHistory:this.state.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)})}setExpandedPromptId(e){this.setState({expandedPromptId:e})}setLoadingComments(e){this.setState({isLoadingComments:e})}addConsoleLogs(e){this.setState({consoleLogs:[...this.state.consoleLogs,...e].slice(-100)})}addNetworkLogs(e){this.setState({networkLogs:[...this.state.networkLogs,...e].slice(-100)})}toggleIncludeConsole(){this.setState({includeConsole:!this.state.includeConsole})}toggleIncludeNetwork(){this.setState({includeNetwork:!this.state.includeNetwork})}toggleIncludeHistory(){this.setState({includeHistory:!this.state.includeHistory})}toggleIncludeContext(){this.setState({includeContext:!this.state.includeContext})}setAuth(e,t){this.setState({user:e,isAuthenticated:t,isAuthenticating:!1,authError:null})}setAuthenticating(e){this.setState({isAuthenticating:e})}setAuthError(e){this.setState({authError:e,isAuthenticating:!1})}setRequireAuth(e){this.setState({requireAuth:e})}reset(){this.state=this.getInitialState(),this.notify()}}class Me{constructor(){this.buffer=[],this.maxSize=100,this.originalConsole=null,this.errorHandler=null,this.rejectionHandler=null,this.listeners=new Set}start(){if(this.originalConsole)return;this.originalConsole={log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console)};const e=e=>(...t)=>{const n=this.createEntry(e,t);this.addEntry(n),this.originalConsole?.[e](...t)};console.log=e("log"),console.info=e("info"),console.warn=e("warn"),console.error=e("error"),this.errorHandler=e=>{const t=this.createEntry("error",[e.message],e.error?.stack);this.addEntry(t)},window.addEventListener("error",this.errorHandler),this.rejectionHandler=e=>{const t=e.reason instanceof Error?e.reason.message:String(e.reason),n=e.reason instanceof Error?e.reason.stack:void 0,o=this.createEntry("error",[`Unhandled Promise Rejection: ${t}`],n);this.addEntry(o)},window.addEventListener("unhandledrejection",this.rejectionHandler)}stop(){this.originalConsole&&(console.log=this.originalConsole.log,console.info=this.originalConsole.info,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error,this.originalConsole=null),this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null)}formatArg(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(null===e)return"null";if(void 0===e)return"undefined";if("object"==typeof e)try{const t=JSON.stringify(e,null,2);if("{}"===t||"[]"===t){const t=Object.prototype.toString.call(e);if("[object Object]"!==t&&"[object Array]"!==t)return t}return t}catch{return Object.prototype.toString.call(e)}return String(e)}createEntry(e,t,n){const o=t.map(e=>this.formatArg(e)).join(" ");return{timestamp:Date.now(),level:e,message:o||"(empty)",args:t,stack:n}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>"error"===e.level||"warn"===e.level)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getRecent(20);return 0===t.length?"":t.map(e=>`${`[${new Date(e.timestamp).toISOString()}] [${e.level.toUpperCase()}]`} ${e.message}${e.stack?`\n${e.stack}`:""}`).join("\n")}}class Pe{constructor(){this.buffer=[],this.maxSize=100,this.originalFetch=null,this.originalXHROpen=null,this.originalXHRSend=null,this.listeners=new Set}start(){this.originalFetch||(this.patchFetch(),this.patchXHR())}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXHROpen&&this.originalXHRSend&&(XMLHttpRequest.prototype.open=this.originalXHROpen,XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHROpen=null,this.originalXHRSend=null)}patchFetch(){this.originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{const n="string"==typeof e?e:e instanceof URL?e.href:e.url,o=t?.method||"GET",r=Date.now(),i={timestamp:r,method:o,url:n,requestBody:t?.body};try{const n=await this.originalFetch(e,t);if(i.status=n.status,i.duration=Date.now()-r,!n.ok)try{const e=n.clone();i.responseBody=await e.text()}catch{}return this.addEntry(i),n}catch(e){throw i.duration=Date.now()-r,i.error=e instanceof Error?e.message:String(e),this.addEntry(i),e}}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;const e=this,t=new WeakMap;XMLHttpRequest.prototype.open=function(n,o,...r){return t.set(this,{method:n,url:"string"==typeof o?o:o.href,startTime:0}),e.originalXHROpen.apply(this,[n,o,...r])},XMLHttpRequest.prototype.send=function(n){const o=t.get(this);return o&&(o.startTime=Date.now(),this.addEventListener("loadend",()=>{const t={timestamp:o.startTime,method:o.method,url:o.url,status:this.status,duration:Date.now()-o.startTime};if(this.status>=400||0===this.status){t.error=this.statusText||"Request failed";try{t.responseBody=this.responseText}catch{}}e.addEntry(t)})),e.originalXHRSend.call(this,n)}}addEntry(e){this.buffer.push(e),this.buffer.length>this.maxSize&&this.buffer.shift(),this.listeners.forEach(t=>t(e))}getAll(){return[...this.buffer]}getRecent(e=20){return this.buffer.slice(-e)}getErrors(){return this.buffer.filter(e=>e.status&&e.status>=400||e.error)}clear(){this.buffer=[]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}formatForPrompt(e){const t=e||this.getErrors();return 0===t.length?"":t.map(e=>{const t=new Date(e.timestamp).toISOString(),n=e.status?`[${e.status}]`:"[FAILED]";return`[${t}] ${e.method} ${e.url} ${n}${e.error?` - ${e.error}`:""}`}).join("\n")}}class je{constructor(){this.overlay=null,this.highlight=null,this.selectedHighlight=null,this.selectedElement=null,this.isActive=!1,this.onSelect=null,this.onCancel=null,this.globalRightClickHandler=null,this.globalRightClickCallback=null,this.globalRightClickWithPositionCallback=null,this.selectedElementScrollHandler=null,this.handleMouseMove=e=>{if(!this.isActive||!this.highlight)return;const t=document.elementFromPoint(e.clientX,e.clientY);if(!t||t.id?.startsWith("orquesta-"))return;this.selectedElement=t;const n=t.getBoundingClientRect();this.highlight.style.display="block",this.highlight.style.top=`${n.top}px`,this.highlight.style.left=`${n.left}px`,this.highlight.style.width=`${n.width}px`,this.highlight.style.height=`${n.height}px`;const o=this.highlight.querySelector("#orquesta-element-label");if(o){const e=t.tagName.toLowerCase(),n=t.id?`#${t.id}`:"",r=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";o.textContent=`<${e}${n}${r}>`}},this.handleClick=e=>{if(!this.isActive)return;const t=e.target;if(!t.id?.startsWith("orquesta-")&&(e.preventDefault(),e.stopPropagation(),this.selectedElement)){const e=this.getElementContext(this.selectedElement);this.deactivate(),this.onSelect?.(e)}},this.handleKeyDown=e=>{"Escape"===e.key&&this.isActive&&(this.deactivate(),this.onCancel?.())},this.promptHighlightScrollHandler=null}setupGlobalRightClick(e){return this.globalRightClickCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const n=this.getElementContext(t);this.globalRightClickCallback?.(n)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickCallback=null)}}setupGlobalRightClickWithPosition(e){return this.globalRightClickWithPositionCallback=e,this.globalRightClickHandler=e=>{const t=e.target;if(t.closest('[id^="orquesta-"]'))return;if(this.isActive)return;e.preventDefault(),e.stopPropagation();const n=this.getElementContext(t),o={x:e.clientX,y:e.clientY};this.globalRightClickWithPositionCallback?.(n,o)},document.addEventListener("contextmenu",this.globalRightClickHandler,!0),()=>{this.globalRightClickHandler&&(document.removeEventListener("contextmenu",this.globalRightClickHandler,!0),this.globalRightClickHandler=null,this.globalRightClickWithPositionCallback=null)}}highlightSelectedElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.removeSelectedHighlight(),this.selectedHighlight=document.createElement("div"),this.selectedHighlight.id="orquesta-selected-element-highlight",this.selectedHighlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #3b82f6;\n background: rgba(59, 130, 246, 0.15);\n z-index: 2147483640;\n transition: all 0.15s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.25), 0 0 20px rgba(59, 130, 246, 0.3);\n ",document.body.appendChild(this.selectedHighlight);const n=document.createElement("div");n.id="orquesta-selected-element-label",n.style.cssText='\n position: absolute;\n top: -28px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 8px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ';const o=t.tagName.toLowerCase(),r=t.id?`#${t.id}`:"",i=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";n.textContent=`Selected: <${o}${r}${i}>`,this.selectedHighlight.appendChild(n);const s=()=>{if(!this.selectedHighlight)return;const e=t.getBoundingClientRect();this.selectedHighlight.style.top=e.top-3+"px",this.selectedHighlight.style.left=e.left-3+"px",this.selectedHighlight.style.width=`${e.width+6}px`,this.selectedHighlight.style.height=`${e.height+6}px`};return s(),this.selectedElementScrollHandler=s,window.addEventListener("scroll",this.selectedElementScrollHandler,!0),window.addEventListener("resize",this.selectedElementScrollHandler),t}catch{return null}}removeSelectedHighlight(){this.selectedHighlight&&(this.selectedHighlight.remove(),this.selectedHighlight=null),this.selectedElementScrollHandler&&(window.removeEventListener("scroll",this.selectedElementScrollHandler,!0),window.removeEventListener("resize",this.selectedElementScrollHandler),this.selectedElementScrollHandler=null)}activate(e,t){this.isActive||(this.isActive=!0,this.onSelect=e,this.onCancel=t||null,this.createOverlay(),this.addListeners(),document.body.style.cursor="crosshair")}deactivate(){this.isActive&&(this.isActive=!1,this.removeListeners(),this.removeOverlay(),this.selectedElement=null,document.body.style.cursor="")}isSelecting(){return this.isActive}createOverlay(){this.overlay=document.createElement("div"),this.overlay.id="orquesta-element-selector-overlay",this.overlay.style.cssText="\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n bottom: 0;\n z-index: 2147483646;\n pointer-events: none;\n ",document.body.appendChild(this.overlay),this.highlight=document.createElement("div"),this.highlight.id="orquesta-element-highlight",this.highlight.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 2px solid #3b82f6;\n background: rgba(59, 130, 246, 0.1);\n z-index: 2147483646;\n transition: all 0.1s ease;\n display: none;\n ",document.body.appendChild(this.highlight);const e=document.createElement("div");e.id="orquesta-element-label",e.style.cssText="\n position: absolute;\n bottom: -24px;\n left: 0;\n background: #3b82f6;\n color: white;\n font-size: 11px;\n font-family: monospace;\n padding: 2px 6px;\n border-radius: 2px;\n white-space: nowrap;\n ",this.highlight.appendChild(e)}removeOverlay(){this.overlay?.remove(),this.highlight?.remove(),this.overlay=null,this.highlight=null}addListeners(){document.addEventListener("mousemove",this.handleMouseMove,!0),document.addEventListener("click",this.handleClick,!0),document.addEventListener("keydown",this.handleKeyDown,!0)}removeListeners(){document.removeEventListener("mousemove",this.handleMouseMove,!0),document.removeEventListener("click",this.handleClick,!0),document.removeEventListener("keydown",this.handleKeyDown,!0)}highlightElement(e){try{const t=this.safeQuerySelector(e);if(!t)return null;this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null);let n=document.getElementById("orquesta-prompt-highlight");n||(n=document.createElement("div"),n.id="orquesta-prompt-highlight",n.style.cssText="\n position: fixed;\n pointer-events: none;\n border: 3px solid #8b5cf6;\n background: rgba(139, 92, 246, 0.15);\n z-index: 2147483640;\n transition: top 0.1s ease, left 0.1s ease, width 0.1s ease, height 0.1s ease;\n border-radius: 4px;\n box-shadow: 0 0 0 4px rgba(139, 92, 246, 0.2), 0 0 20px rgba(139, 92, 246, 0.3);\n ",document.body.appendChild(n));let o=n.querySelector("#orquesta-prompt-highlight-label");o||(o=document.createElement("div"),o.id="orquesta-prompt-highlight-label",o.style.cssText='\n position: absolute;\n top: -30px;\n left: 0;\n background: #8b5cf6;\n color: white;\n font-size: 11px;\n font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;\n padding: 4px 10px;\n border-radius: 4px;\n white-space: nowrap;\n font-weight: 500;\n box-shadow: 0 2px 8px rgba(0,0,0,0.3);\n ',n.appendChild(o));const r=t.tagName.toLowerCase(),i=t.id?`#${t.id}`:"",s=t.className&&"string"==typeof t.className?`.${t.className.split(" ").slice(0,2).join(".")}`:"";o.textContent=`Highlighted: <${r}${i}${s}>`;const a=()=>{const e=t.getBoundingClientRect();n.style.display="block",n.style.top=e.top-3+"px",n.style.left=e.left-3+"px",n.style.width=`${e.width+6}px`,n.style.height=`${e.height+6}px`};a(),this.promptHighlightScrollHandler=a,window.addEventListener("scroll",this.promptHighlightScrollHandler,!0),window.addEventListener("resize",this.promptHighlightScrollHandler);const l=t.getBoundingClientRect();return(l.top<0||l.bottom>window.innerHeight)&&t.scrollIntoView({behavior:"smooth",block:"center"}),t}catch{return null}}removeHighlight(){const e=document.getElementById("orquesta-prompt-highlight");e&&(e.style.display="none"),this.promptHighlightScrollHandler&&(window.removeEventListener("scroll",this.promptHighlightScrollHandler,!0),window.removeEventListener("resize",this.promptHighlightScrollHandler),this.promptHighlightScrollHandler=null)}safeQuerySelector(e){try{return document.querySelector(e)}catch{return null}}findElement(e,t){try{let n=this.safeQuerySelector(e);if(n)return n;if(t&&(n=document.getElementById(t),n))return n;const o=e.match(/^([a-z]+)\.([a-z0-9_-]+)/i);if(o){const[,e,t]=o;if(n=this.safeQuerySelector(`${e}.${t}`),n)return n}return null}catch{return null}}getElementContext(e){const t=e.getBoundingClientRect(),n={};for(const t of e.attributes)t.name.startsWith("data-")||"class"===t.name||"id"===t.name||(n[t.name]=t.value);return{selector:this.generateSelector(e),tag:e.tagName.toLowerCase(),id:e.id||void 0,className:"string"==typeof e.className?e.className:void 0,textContent:e.textContent?.trim().slice(0,200)||void 0,boundingRect:t,attributes:Object.keys(n).length>0?n:void 0}}isValidCssClass(e){return!/[@:/\[\]()!#]/.test(e)&&!!/^[a-zA-Z_-]/.test(e)}generateSelector(e){if(e.id&&this.isValidCssClass(e.id))return`#${e.id}`;const t=[];let n=e;for(;n&&n!==document.body;){let e=n.tagName.toLowerCase();if(n.id&&this.isValidCssClass(n.id)){e=`#${n.id}`,t.unshift(e);break}if(n.className&&"string"==typeof n.className){const t=n.className.trim().split(/\s+/).filter(e=>this.isValidCssClass(e)).slice(0,2);t.length>0&&(e+=`.${t.join(".")}`)}const o=n.parentElement;if(o){const t=Array.from(o.children).filter(e=>e.tagName===n.tagName);if(t.length>1){e+=`:nth-child(${t.indexOf(n)+1})`}}t.unshift(e),n=n.parentElement}return t.join(" > ")}}class Be{constructor(e,t){this.listeners=new Set,this.popupWindow=null,this.messageHandler=null,this.broadcastChannel=null,this.pollInterval=null,this.token=e,this.apiUrl=t,this.state=this.getInitialState()}getInitialState(){return{isAuthenticated:!1,isAuthenticating:!1,user:null,sessionToken:null,expiresAt:null,authError:null}}getState(){return{...this.state}}setState(e){this.state={...this.state,...e},this.notify()}subscribe(e){return this.listeners.add(e),e(this.getState()),()=>this.listeners.delete(e)}notify(){const e=this.getState();this.listeners.forEach(t=>t(e))}getStorageKey(){return`orquesta_embed_session_${this.token.slice(-8)}`}saveSession(e){try{localStorage.setItem(this.getStorageKey(),JSON.stringify(e))}catch{}}loadSession(){try{const e=localStorage.getItem(this.getStorageKey());if(!e)return null;const t=JSON.parse(e);return t.expiresAt&&new Date(t.expiresAt)<new Date?(this.clearSession(),null):t}catch{return null}}clearSession(){try{localStorage.removeItem(this.getStorageKey())}catch{}}async checkSession(){const e=this.loadSession();if(!e)return!1;try{const t=await fetch(`${this.apiUrl}/api/embed/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})});if(!t.ok)return this.clearSession(),!1;const n=await t.json();return n.valid?(this.setState({isAuthenticated:!0,user:n.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0):(this.clearSession(),!1)}catch{return this.setState({isAuthenticated:!0,user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt,authError:null}),!0}}login(){return new Promise((e,t)=>{this.setState({isAuthenticating:!0,authError:null});const n=Math.random().toString(36).slice(2),o=`eas_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,r=new URL(`${this.apiUrl}/embed/auth`);r.searchParams.set("token",this.token),r.searchParams.set("origin",window.location.origin),r.searchParams.set("state",n),r.searchParams.set("authSession",o);const i=window.screenX+(window.innerWidth-500)/2,s=window.screenY+(window.innerHeight-600)/2;if(this.popupWindow=window.open(r.toString(),"orquesta_auth",`width=500,height=600,left=${i},top=${s},popup=yes`),!this.popupWindow)return this.setState({isAuthenticating:!1,authError:"Popup blocked"}),void t(new Error("Popup blocked. Please allow popups for this site."));this.messageHandler=n=>{if(n.origin!==new URL(this.apiUrl).origin)return;const{type:o,payload:r}=n.data||{};"orquesta_auth_success"===o?(this.handleAuthSuccess(r),e(r),this.cleanup()):"orquesta_auth_error"===o?(this.handleAuthError(r),t(new Error(r.message||"Authentication failed")),this.cleanup()):"orquesta_auth_closed"===o&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup())},window.addEventListener("message",this.messageHandler);const a=this.apiUrl.replace("://orquesta.live","://ws.orquesta.live").replace("://localhost:3113","://localhost:3200");this.pollInterval=setInterval(async()=>{try{const n=await fetch(`${a}/auth/result/${o}`);if(!n.ok)return;const r=await n.json();if(r.pending)return;const{type:i,payload:s}=r;"orquesta_auth_success"===i?(this.handleAuthSuccess(s),e(s),this.cleanup()):"orquesta_auth_error"===i&&(this.handleAuthError(s),t(new Error(s.message||"Authentication failed")),this.cleanup())}catch{}},1500);const l=setInterval(()=>{this.popupWindow?.closed&&(clearInterval(l),this.state.isAuthenticating&&(this.setState({isAuthenticating:!1}),t(new Error("Authentication cancelled")),this.cleanup()))},500)})}handleAuthSuccess(e){const t={user:e.user,sessionToken:e.sessionToken,expiresAt:e.expiresAt};this.saveSession(t),this.setState({isAuthenticated:!0,isAuthenticating:!1,user:t.user,sessionToken:t.sessionToken,expiresAt:t.expiresAt,authError:null})}handleAuthError(e){this.setState({isAuthenticating:!1,authError:e.message})}cleanup(){this.messageHandler&&(window.removeEventListener("message",this.messageHandler),this.messageHandler=null),this.broadcastChannel&&(this.broadcastChannel.close(),this.broadcastChannel=null),this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=null),this.popupWindow&&!this.popupWindow.closed&&this.popupWindow.close(),this.popupWindow=null}async logout(){const e=this.loadSession();if(e?.sessionToken)try{await fetch(`${this.apiUrl}/api/embed/session`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({embedToken:this.token,sessionToken:e.sessionToken})})}catch{}this.clearSession(),this.setState(this.getInitialState())}getUser(){return this.state.user}getSessionToken(){return this.state.sessionToken}destroy(){this.cleanup(),this.listeners.clear()}}const Ie=!1,$e="prompts",De="dark";const We=new class{constructor(){this.projectId=null}setProjectId(e){this.projectId=e}getKey(e){const t=`orquesta_embed_${e}`;return this.projectId?`${t}_${this.projectId}`:t}get(e){try{const t=localStorage.getItem(this.getKey(e));return t?JSON.parse(t):null}catch{return null}}set(e,t){try{localStorage.setItem(this.getKey(e),JSON.stringify(t))}catch{}}remove(e){try{localStorage.removeItem(this.getKey(e))}catch{}}getState(){return{isOpen:this.get("isOpen")??Ie,position:this.get("position"),size:this.get("size"),activeTab:this.get("activeTab")??$e,theme:this.get("theme")??De}}setState(e){Object.entries(e).forEach(([e,t])=>{void 0!==t&&this.set(e,t)})}clear(){["isOpen","position","size","activeTab","theme"].forEach(e=>this.remove(e))}};class Fe{constructor(e){this.socket=null,this.channelName=null,this.projectId=null,this.authManager=null,this.hotkeyHandler=null,this.config={...Re,...e},this.state=new He,this.consoleCapture=new Me,this.networkCapture=new Pe,this.elementSelector=new je,this.config.requireAuth&&(this.state.setRequireAuth(!0),this.authManager=new Be(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}))}async connect(){if(!this.config.token)throw new Error("Embed token is required");this.state.setState({isConnecting:!0});try{const e=await fetch(`${this.config.apiUrl}/api/embed/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:this.config.token})});if(!e.ok){const t=await e.json();throw new Error(t.error||"Failed to validate token")}const t=await e.json();if(!t.valid)throw new Error("Invalid embed token");this.projectId=t.projectId,We.setProjectId(t.projectId);const n=t.requireAuth||this.config.requireAuth;n&&!this.authManager?(this.state.setRequireAuth(!0),this.authManager=new Be(this.config.token,this.config.apiUrl||"https://orquesta.live"),this.authManager.subscribe(e=>{this.state.setState({isAuthenticated:e.isAuthenticated,isAuthenticating:e.isAuthenticating,user:e.user,authError:e.authError})}),await this.authManager.checkSession()):n&&this.state.setRequireAuth(!0),this.channelName=t.channelName;const o=Te("https://ws.orquesta.live",{auth:{embedToken:this.config.token},transports:["websocket"],reconnection:!0,reconnectionAttempts:1/0,reconnectionDelay:1e3,reconnectionDelayMax:1e4,timeout:1e4});this.socket=o,o.on("output",e=>this.handleOutput(e)),o.on("complete",e=>this.handleComplete(e)),o.on("error",e=>this.handleError(e));let r=!1;o.on("connect",()=>{if(o.emit("subscribe",{channel:t.channelName}),this.state.setConnected(t.projectId,t.project?.name||"Project",t.project?.agent_online||!1),r)return;r=!0,this.config.captureConsole&&(this.consoleCapture.start(),this.consoleCapture.subscribe(e=>{this.state.addConsoleLogs([e])})),this.config.captureNetwork&&(this.networkCapture.start(),this.networkCapture.subscribe(e=>{this.state.addNetworkLogs([e])})),this.setupHotkey(),this.loadTimeline();const e=We.getState();this.state.setState({isOpen:this.config.defaultOpen??e.isOpen,activeTab:e.activeTab||"prompts"}),this.config.onReady?.()}),o.on("connect_error",e=>{const t=e?.message||"Failed to connect to WS server";this.state.setConnectionError(t)}),o.on("disconnect",()=>{this.state.setState({isConnecting:!1})})}catch(e){const t=e instanceof Error?e.message:"Connection failed";throw this.state.setConnectionError(t),this.config.onError?.(e instanceof Error?e:new Error(t)),e}}disconnect(){if(this.socket){if(this.channelName)try{this.socket.emit("unsubscribe",{channel:this.channelName})}catch{}this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null}this.channelName=null,this.consoleCapture.stop(),this.networkCapture.stop(),this.elementSelector.deactivate(),this.removeHotkey(),this.authManager&&this.authManager.destroy(),this.state.reset(),this.projectId=null}setupHotkey(){if(!this.config.hotkey)return;const e=this.config.hotkey.toLowerCase().split("+"),t=e.pop(),n=new Set(e);this.hotkeyHandler=e=>{if(!e.key)return;const o=n.has("ctrl")===(e.ctrlKey||e.metaKey),r=n.has("shift")===e.shiftKey,i=n.has("alt")===e.altKey,s=e.key.toLowerCase()===t;o&&r&&i&&s&&(e.preventDefault(),this.toggle())},document.addEventListener("keydown",this.hotkeyHandler)}removeHotkey(){this.hotkeyHandler&&(document.removeEventListener("keydown",this.hotkeyHandler),this.hotkeyHandler=null)}handleOutput(e){if(!this.state.getState().currentPrompt)return;let t,n,o,r="stdout",i=e.data;"stderr"===e.type?r="stderr":e.data.includes("Tool:")||e.data.includes("tool_call")?r="tool":(e.data.includes("thinking")||e.data.includes("Thinking"))&&(r="thinking");try{const s=JSON.parse(e.data);if(s.type){switch(s.type){case"thinking":r="thinking",i=s.thinking?.content||e.data;break;case"tool_call":r="tool_call",n=s.tool_call?.name,i=`Using ${n||"tool"}`;break;case"tool_result":r="tool_result",n=s.tool_result?.name,o=s.tool_result?.success,i=o?s.tool_result?.output||"Success":s.tool_result?.error||"Failed";break;case"output":r="output",i=s.output?.content||e.data;break;case"error":r="error",i=s.error?.message||e.data;break;case"system":r="system",i=s.system?.message||s.system?.event||e.data;break;case"progress":r="progress";const t=void 0!==s.progress?.percentage?` (${s.progress.percentage}%)`:"";i=(s.progress?.message||"Processing")+t;break;default:i=s.content||s.message||e.data}t=s}}catch{}this.state.addOutputLine({timestamp:e.timestamp||Date.now(),type:r,content:i,details:t,toolName:n,toolSuccess:o})}handleComplete(e){const t=this.state.getState(),n=0===e.exitCode?"completed":"failed",o=t.currentPrompt?.id;if(t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:n,completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),o&&this.config.onPromptComplete&&this.config.onPromptComplete(o,n),this.config.reloadOnComplete&&"completed"===n){const e=this.config.reloadDelay??1500;return console.log(`[Orquesta Embed] Prompt completed. Reloading page in ${e}ms...`),void setTimeout(()=>{window.location.reload()},e)}this.processQueue()}async processQueue(){const e=this.state.getNextFromQueue();if(e){console.log(`[Orquesta Embed] Processing queued prompt. Remaining in queue: ${this.state.getQueueLength()}`);try{await this.submitPrompt(e.content,e.options)}catch(e){console.error("[Orquesta Embed] Failed to process queued prompt:",e),this.processQueue()}}}handleError(e){const t=this.state.getState();this.state.addOutputLine({timestamp:Date.now(),type:"stderr",content:`Error: ${e.error}`}),t.currentPrompt&&(this.state.storePromptOutput(t.currentPrompt.id),this.state.updatePrompt(t.currentPrompt.id,{status:"failed",completed_at:(new Date).toISOString()})),this.state.setState({isSubmitting:!1}),this.processQueue()}async submitPrompt(e,t){if(!this.projectId)throw new Error("Not connected");if(this.config.requireAuth&&!this.state.getState().isAuthenticated)throw new Error("Authentication required. Please log in first.");const n=this.state.getState();if(n.isSubmitting)return this.state.addToQueue({id:`queue-${Date.now()}`,content:e,options:t,queuedAt:Date.now()}),console.log(`[Orquesta Embed] Prompt queued. Queue length: ${this.state.getQueueLength()}`),`queued-${Date.now()}`;this.state.setState({isSubmitting:!0}),this.state.clearOutput();let o=e;const r=t?.elementContext||n.selectedElement;if(r&&(o+=`\n\n--- Element Context ---\nSelector: ${r.selector}\nTag: <${r.tag}>\n${r.id?`ID: ${r.id}`:""}\n${r.className?`Classes: ${r.className}`:""}\n${r.textContent?`Text: ${r.textContent}`:""}\n${r.attributes?`Attributes: ${JSON.stringify(r.attributes)}`:""}`),t?.includeConsole??n.includeConsole){const e=this.consoleCapture.formatForPrompt();e&&(o+=`\n\n--- Console Logs ---\n${e}`)}if(t?.includeNetwork??n.includeNetwork){const e=this.networkCapture.formatForPrompt();e&&(o+=`\n\n--- Network Errors ---\n${e}`)}if(t?.includeHistory??n.includeHistory){const e=n.promptHistory.filter(e=>"completed"===e.status).slice(0,5).reverse();e.length>0&&(o+="\n\n--- Previous Prompts Context ---",e.forEach((e,t)=>{o+=`\n\n[Prompt ${t+1}]: ${e.content}`;const r=n.promptOutputs[e.id];if(r&&r.length>0){const e=r.slice(-10).map(e=>e.content).join("\n");o+=`\n[Output ${t+1}]:\n${e}`}}))}try{const e={"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},t=this.authManager?.getSessionToken();t&&(e["X-Session-Token"]=t);const n=await fetch(`${this.config.apiUrl}/api/embed/prompts`,{method:"POST",headers:e,body:JSON.stringify({projectId:this.projectId,content:o,elementContext:r})});if(!n.ok){const e=await n.json();throw new Error(e.error||"Failed to submit prompt")}const i=(await n.json()).prompt;return this.state.setCurrentPrompt(i),this.state.setSelectedElement(null),this.config.onPromptSubmit?.(i.id),i.id}catch(e){throw this.state.setState({isSubmitting:!1}),e}}async loadTimeline(){if(this.projectId)try{const e=await fetch(`${this.config.apiUrl}/api/embed/prompts?projectId=${this.projectId}&limit=50`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(e.ok){const t=await e.json();this.state.setState({promptHistory:t.prompts||[]})}}catch{}}open(){this.state.setOpen(!0),We.set("isOpen",!0)}close(){this.state.setOpen(!1),We.set("isOpen",!1)}toggle(){const e=!this.state.getState().isOpen;this.state.setOpen(e),We.set("isOpen",e)}startElementSelection(){this.state.startElementSelection(),this.elementSelector.activate(e=>this.state.setSelectedElement(e),()=>this.state.cancelElementSelection())}getState(){return this.state.getState()}subscribe(e){return this.state.subscribe(e)}getConsoleCapture(){return this.consoleCapture}getNetworkCapture(){return this.networkCapture}getElementSelector(){return this.elementSelector}setActiveTab(e){this.state.setActiveTab(e)}async loadComments(e){if(this.projectId){this.state.setLoadingComments(!0);try{const t=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{headers:{Authorization:`Bearer ${this.config.token}`}});if(t.ok){const n=await t.json();this.state.setCommentsForPrompt(e,n.comments||[])}}catch{}finally{this.state.setLoadingComments(!1)}}}async addComment(e,t){if(this.projectId)try{const n=await fetch(`${this.config.apiUrl}/api/embed/prompts/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.token}`},body:JSON.stringify({content:t})});if(n.ok){const t=await n.json();t.comment&&this.state.addComment(e,t.comment)}}catch(e){throw console.error("Failed to add comment:",e),e}}setOverlayMode(e){if(this.state.setOverlayMode(e),"off"===e)this.elementSelector.removeHighlight(),this.state.setHighlightedPromptId(null);else if("all"===e){const e=this.state.getState().promptHistory.filter(e=>e.element_context?.selector).map(e=>({promptId:e.id,selector:e.element_context.selector,rect:null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}));this.state.setElementMarkers(e)}else this.state.setElementMarkers([])}highlightPromptElement(e){if(!e.element_context?.selector)return void console.warn("Prompt has no element context");this.elementSelector.highlightElement(e.element_context.selector)?(this.state.setHighlightedPromptId(e.id),this.state.setOverlayMode("single")):console.warn("Element not found for prompt:",e.id)}setupGlobalRightClick(e){return this.elementSelector.setupGlobalRightClick(e)}setupGlobalRightClickWithPosition(e){return this.elementSelector.setupGlobalRightClickWithPosition(e)}async login(){if(!this.authManager)throw new Error("Authentication is not enabled. Set requireAuth: true in config.");try{const e=await this.authManager.login();return this.config.onLogin?.(e.user),e.user}catch(e){throw e}}async logout(){if(!this.authManager)throw new Error("Authentication is not enabled.");await this.authManager.logout(),this.config.onLogout?.()}isAuthenticated(){return this.state.getState().isAuthenticated}getUser(){return this.state.getState().user}isAuthRequired(){return this.config.requireAuth||!1}}let Ue=!1;function Ve({variant:n="primary",size:o="md",loading:r=!1,disabled:i,className:s="",children:a,...l}){return e("button",{className:`inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-zinc-900 disabled:opacity-50 disabled:cursor-not-allowed ${{primary:"bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500",secondary:"bg-zinc-700 text-white hover:bg-zinc-600 focus:ring-zinc-500",ghost:"bg-transparent text-zinc-300 hover:bg-zinc-800 hover:text-white focus:ring-zinc-500",danger:"bg-red-600 text-white hover:bg-red-700 focus:ring-red-500"}[n]} ${{sm:"px-2.5 py-1.5 text-xs",md:"px-3 py-2 text-sm",lg:"px-4 py-2.5 text-base"}[o]} ${s}`,disabled:i||r,...l,children:[r&&e("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),a]})}function Qe({label:n,error:o,className:r="",...i}){return e("div",{className:"w-full",children:[n&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:n}),t("input",{className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed ${o?"border-red-500":""} ${r}`,...i}),o&&t("p",{className:"mt-1.5 text-sm text-red-400",children:o})]})}const Ke=o.forwardRef(function({label:n,error:o,className:r="",...i},s){return e("div",{className:"w-full",children:[n&&t("label",{className:"block text-sm font-medium text-zinc-300 mb-1.5",children:n}),t("textarea",{ref:s,className:`w-full px-3 py-2 bg-zinc-800 border border-zinc-700 rounded-md text-white placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed resize-none ${o?"border-red-500":""} ${r}`,...i}),o&&t("p",{className:"mt-1.5 text-sm text-red-400",children:o})]})});function Xe({variant:e="default",size:n="md",children:o,className:r=""}){return t("span",{className:`inline-flex items-center font-medium rounded-full ${{default:"bg-zinc-700 text-zinc-300",success:"bg-green-900/50 text-green-400",warning:"bg-yellow-900/50 text-yellow-400",error:"bg-red-900/50 text-red-400",info:"bg-blue-900/50 text-blue-400"}[e]} ${{sm:"px-1.5 py-0.5 text-xs",md:"px-2 py-1 text-xs"}[n]} ${r}`,children:o})}function Ye({status:e,className:n=""}){return t("span",{className:`inline-block w-2 h-2 rounded-full ${{online:"bg-green-500",offline:"bg-zinc-500",pending:"bg-yellow-500",running:"bg-blue-500 animate-pulse",completed:"bg-green-500",failed:"bg-red-500"}[e]} ${n}`})}const Je=r(null);function Ge(){const e=s(Je);if(!e)throw new Error("Tabs components must be used within a Tabs provider");return e}function Ze({defaultValue:e="",value:n,onChange:o,children:r,className:s=""}){const[a,l]=i(e),c=n??a??"";return t(Je.Provider,{value:{activeTab:c,setActiveTab:e=>{void 0===n&&l(e),o?.(e)}},children:t("div",{className:s,children:r})})}function et({children:e,className:n=""}){return t("div",{className:`flex items-center gap-1 p-1 bg-zinc-800 rounded-lg ${n}`,children:e})}function tt({value:e,children:n,className:o=""}){const{activeTab:r,setActiveTab:i}=Ge();return t("button",{onClick:()=>i(e),className:`flex-1 px-3 py-1.5 text-sm font-medium rounded-md transition-colors ${r===e?"bg-zinc-700 text-white":"text-zinc-400 hover:text-zinc-300"} ${o}`,children:n})}function nt({value:e,children:n,className:o=""}){const{activeTab:r}=Ge();return r!==e?null:t("div",{className:o,children:n})}const ot=["Change the Shop Now button to green","Add a sale banner at the top","Show discounted prices on products","Make the headline bigger","Switch to dark mode"];function rt({onSubmit:n,isSubmitting:o,selectedElement:r,includeConsole:s,includeNetwork:d,includeContext:h,promptHistory:p,promptOutputs:u,queueLength:m=0,onToggleConsole:g,onToggleNetwork:f,onToggleContext:b,onSelectElement:x,onClearElement:y,agentOnline:w,replyContext:v,onClearReply:k,token:C,apiUrl:N="https://orquesta.live",demoMode:S=!1}){const[q,E]=i(""),[_,z]=i([]),[L,A]=i(!1),[O,T]=i(!1),R=a(null),H=a(null);l(()=>{R.current?.focus()},[]);const M=c(async e=>{if(!C)return null;const t=`temp-${Date.now()}-${Math.random().toString(36).slice(2)}`,n={id:t,name:e.name,type:e.type,size:e.size,url:"",isUploading:!0};z(e=>[...e,n]),A(!0);try{const n=new FormData;n.append("file",e);const o=await fetch(`${N}/api/embed/attachments`,{method:"POST",headers:{Authorization:`Bearer ${C}`},body:n});if(!o.ok){const e=await o.json();throw new Error(e.error||"Upload failed")}const{attachment:r}=await o.json();return z(e=>e.map(e=>e.id===t?{id:r.id,name:r.file_name,type:r.file_type,size:r.file_size,url:r.file_url,isUploading:!1}:e)),{id:r.id,name:r.file_name,type:r.file_type,size:r.file_size,url:r.file_url}}catch(e){return z(n=>n.map(n=>n.id===t?{...n,isUploading:!1,error:e instanceof Error?e.message:"Upload failed"}:n)),null}finally{A(!1)}},[C,N]),P=c(async e=>{if(!C)return;const t=Array.from(e);if(_.length+t.length>5)alert("Maximum 5 files allowed");else for(const e of t)e.size>20971520?alert(`${e.name} exceeds the 10MB limit`):await M(e)},[C,_.length,M]),j=e=>{if(e.preventDefault(),!q.trim()||!w||L)return;const t=_.filter(e=>!e.error&&!e.isUploading).map(e=>e.id);n(q.trim(),r,t.length>0?t:void 0),E(""),z([])};return e("form",{onSubmit:j,className:"orquesta-prompt-input",children:[t("input",{ref:H,type:"file",multiple:!0,onChange:e=>{e.target.files&&e.target.files.length>0&&(P(e.target.files),e.target.value="")},style:{display:"none"},accept:"*/*",disabled:!C}),v&&e("div",{className:"mb-3 p-2.5 bg-green-900/30 border border-green-500/40 rounded-lg",children:[e("div",{className:"flex items-center justify-between mb-1",children:[t("span",{className:"text-xs font-medium text-green-400",children:"↩ Replying to prompt:"}),k&&t("button",{type:"button",onClick:k,className:"text-green-400 hover:text-green-300 text-sm font-bold",children:"×"})]}),e("p",{className:"text-xs text-zinc-300 line-clamp-2",children:[v.prompt.content.slice(0,100),v.prompt.content.length>100&&"..."]}),v.output&&v.output.length>0&&e("p",{className:"text-xs text-zinc-500 mt-1",children:["+ ",v.output.length," output lines as context"]})]}),_.length>0&&t("div",{className:"mb-2 flex flex-wrap gap-1.5",children:_.map(n=>{return e("div",{className:"flex items-center gap-1.5 px-2 py-1 text-xs rounded-md "+(n.error?"bg-red-900/30 border border-red-500/40 text-red-400":"bg-zinc-800 border border-zinc-700 text-zinc-300"),children:[n.isUploading?e("svg",{className:"w-3 h-3 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):n.type.startsWith("image/")?t("span",{children:"🖼️"}):t("span",{children:"📎"}),t("span",{className:"truncate max-w-[80px]",title:n.name,children:n.name}),e("span",{className:"text-zinc-500",children:["(",(o=n.size,o<1024?`${o} B`:o<1048576?`${(o/1024).toFixed(1)} KB`:`${(o/1048576).toFixed(1)} MB`),")"]}),t("button",{type:"button",onClick:()=>(async e=>{const t=_.find(t=>t.id===e);if(z(t=>t.filter(t=>t.id!==e)),t&&!t.id.startsWith("temp-")&&!t.error&&C)try{await fetch(`${N}/api/embed/attachments?id=${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${C}`}})}catch{}})(n.id),className:"ml-0.5 hover:text-white",disabled:n.isUploading,children:"×"})]},n.id);var o})}),e("div",{onDragOver:e=>{e.preventDefault(),e.stopPropagation(),C&&T(!0)},onDragLeave:e=>{e.preventDefault(),e.stopPropagation(),T(!1)},onDrop:e=>{if(e.preventDefault(),e.stopPropagation(),T(!1),!C)return;const t=e.dataTransfer.files;t.length>0&&P(t)},className:"relative "+(O?"ring-2 ring-green-500/50 rounded-lg":""),children:[O&&t("div",{className:"absolute inset-0 bg-green-900/30 rounded-lg flex items-center justify-center z-10 pointer-events-none",children:t("span",{className:"text-green-400 text-sm font-medium",children:"Drop files here"})}),t(Ke,{ref:R,value:q,onChange:e=>E(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&j(e)},onPaste:e=>{if(!C)return;const t=e.clipboardData.items,n=[];for(let e=0;e<t.length;e++){const o=t[e];if(o.type.startsWith("image/")){const e=o.getAsFile();e&&n.push(e)}}n.length>0&&(e.preventDefault(),P(n))},placeholder:w?v?"Write your follow-up...":"What would you like to do?":"Agent is offline...",disabled:o||!w,rows:3,className:"min-h-[80px]"})]}),S&&!o&&!q.trim()&&e("div",{className:"mt-2",children:[t("p",{className:"text-[10px] text-zinc-500 mb-1.5",children:"Try these:"}),t("div",{className:"flex flex-wrap gap-1.5",children:ot.map(e=>t("button",{type:"button",onClick:()=>{E(e),setTimeout(()=>{n(e,r),E("")},150)},className:"px-2 py-1 rounded-md text-[10px] font-medium bg-zinc-800 border border-zinc-700 text-zinc-300 hover:bg-green-900/40 hover:border-green-500/40 hover:text-green-400 transition-all cursor-pointer",children:e},e))})]}),e("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[r&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-blue-900/30 text-blue-400 text-xs rounded-md",children:[t("span",{children:"🎯"}),e("span",{className:"font-mono",children:["<",r.tag,">"]}),t("button",{type:"button",onClick:y,className:"ml-1 hover:text-blue-300",children:"×"})]}),s&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-yellow-900/30 text-yellow-400 text-xs rounded-md",children:[t("span",{children:"📋"}),t("span",{children:"Console logs"}),t("button",{type:"button",onClick:g,className:"ml-1 hover:text-yellow-300",children:"×"})]}),d&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-red-900/30 text-red-400 text-xs rounded-md",children:[t("span",{children:"🌐"}),t("span",{children:"Network errors"}),t("button",{type:"button",onClick:f,className:"ml-1 hover:text-red-300",children:"×"})]}),h&&e("div",{className:"flex items-center gap-1.5 px-2 py-1 bg-purple-900/30 text-purple-400 text-xs rounded-md",children:[t("span",{children:"🔗"}),t("span",{children:"Context (session outputs)"}),t("button",{type:"button",onClick:b,className:"ml-1 hover:text-purple-300",children:"×"})]})]}),e("div",{className:"mt-3 space-y-2.5",children:[e("div",{className:"grid grid-cols-5 gap-1.5",children:[e("button",{type:"button",onClick:x,disabled:o,title:"Select an element to include context",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border ${r?"bg-blue-500/20 text-blue-300 border-blue-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"🎯"}),t("span",{className:"text-[10px]",children:"Element"})]}),e("button",{type:"button",onClick:g,disabled:o,title:"Include recent console logs",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${s?"bg-yellow-500/20 text-yellow-300 border-yellow-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"📋"}),t("span",{className:"text-[10px]",children:"Logs"}),s&&t("span",{className:"absolute top-1 right-1 text-yellow-400 text-[8px]",children:"✓"})]}),e("button",{type:"button",onClick:f,disabled:o,title:"Include network errors",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${d?"bg-red-500/20 text-red-300 border-red-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"🌐"}),t("span",{className:"text-[10px]",children:"Network"}),d&&t("span",{className:"absolute top-1 right-1 text-red-400 text-[8px]",children:"✓"})]}),e("button",{type:"button",onClick:b,disabled:o,title:"Include session outputs as context",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${h?"bg-purple-500/20 text-purple-300 border-purple-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[t("span",{className:"text-base",children:"🔗"}),t("span",{className:"text-[10px]",children:"Context"}),h&&t("span",{className:"absolute top-1 right-1 text-purple-400 text-[8px]",children:"✓"})]}),e("button",{type:"button",onClick:()=>H.current?.click(),disabled:o||!C||L,title:C?"Attach files (up to 10MB each)":"Login to attach files",className:`flex flex-col items-center justify-center gap-0.5 px-2 py-2 rounded-lg text-xs font-medium transition-all border relative ${_.length>0?"bg-green-500/20 text-green-300 border-green-500/40":"bg-zinc-800 text-zinc-400 border-zinc-700 hover:bg-zinc-700 hover:text-zinc-200 hover:border-zinc-600"} disabled:opacity-50`,children:[L?e("svg",{className:"w-4 h-4 animate-spin",viewBox:"0 0 24 24",fill:"none",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):t("span",{className:"text-base",children:"📎"}),t("span",{className:"text-[10px]",children:"Files"}),_.length>0&&t("span",{className:"absolute top-1 right-1 text-green-400 text-[8px]",children:_.length})]})]}),t(Ve,{type:"submit",variant:"primary",size:"sm",loading:o,disabled:!q.trim()||!w||L,className:"w-full justify-center",children:o?"Running...":"Submit Prompt"})]}),!w&&t("p",{className:"mt-2 text-xs text-yellow-400",children:"⚠️ Agent is offline. Start the agent to submit prompts."}),m>0&&e("div",{className:"mt-2 flex items-center gap-2 px-3 py-2 bg-blue-900/30 border border-blue-500/30 rounded-lg",children:[t("svg",{className:"w-4 h-4 text-blue-400 animate-pulse",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),e("span",{className:"text-xs text-blue-300",children:[m," prompt",m>1?"s":""," queued"]})]}),C&&t("p",{className:"mt-2 text-xs text-zinc-500",children:"💡 Drag & drop files or paste images to attach"}),o&&!C&&t("p",{className:"mt-2 text-xs text-zinc-400",children:"💡 Tip: You can queue more prompts while this one runs"})]})}function it({lines:n,isRunning:o}){const r=a(null);if(l(()=>{r.current&&(r.current.scrollTop=r.current.scrollHeight)},[n]),0===n.length&&!o)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"Output will appear here when running prompts"});const i=(e,t)=>{switch(e){case"stderr":case"error":return"text-red-400";case"tool":case"tool_call":return"text-blue-400";case"tool_result":return t?"text-green-400":"text-red-400";case"thinking":return"text-zinc-500 italic";case"system":return"text-yellow-400";case"progress":return"text-cyan-400";default:return"text-zinc-300"}},s=(e,t)=>{switch(e){case"stderr":case"error":return"✕";case"tool":case"tool_call":return"🔧";case"tool_result":return t?"✓":"✕";case"thinking":return"💭";case"system":return"ℹ";case"progress":return"⏳";default:return"›"}};return e("div",{ref:r,className:"orquesta-log-stream overflow-y-auto max-h-[200px] font-mono text-xs",children:[n.map(n=>e("div",{className:`flex items-start gap-2 py-0.5 ${i(n.type,n.toolSuccess)}`,children:[t("span",{className:"flex-shrink-0 w-4 text-center opacity-50",children:s(n.type,n.toolSuccess)}),e("span",{className:"flex-1 whitespace-pre-wrap break-all",children:[n.toolName&&("tool_call"===n.type||"tool_result"===n.type)&&e("span",{className:"font-medium mr-1",children:["[",n.toolName,"]"]}),n.content]})]},n.id)),o&&e("div",{className:"flex items-center gap-2 py-1 text-blue-400 animate-pulse",children:[t("span",{className:"w-4 text-center",children:"●"}),t("span",{children:"Running..."})]})]})}function st({author:n,size:o="sm",showName:r=!1,className:i=""}){const s={sm:"w-5 h-5 text-[10px]",md:"w-6 h-6 text-xs",lg:"w-8 h-8 text-sm"};return e("div",{className:`flex items-center gap-1.5 ${i}`,children:[n?.avatar_url?t("img",{src:n.avatar_url,alt:n.full_name||"User",className:`${s[o]} rounded-full object-cover ring-1 ring-zinc-700`}):t("div",{className:`${s[o]} ${(e=>{if(!e)return"bg-zinc-600";const t=["bg-blue-600","bg-green-600","bg-purple-600","bg-orange-600","bg-pink-600","bg-cyan-600","bg-indigo-600","bg-teal-600"];return t[e.split("").reduce((e,t)=>e+t.charCodeAt(0),0)%t.length]})(n?.id)} rounded-full flex items-center justify-center font-medium text-white ring-1 ring-zinc-700`,children:(e=>{if(!e)return"?";const t=e.trim().split(" ");return 1===t.length?t[0][0]?.toUpperCase()||"?":(t[0][0]+t[t.length-1][0]).toUpperCase()})(n?.full_name)}),r&&n?.full_name&&t("span",{className:"text-xs text-zinc-400 truncate max-w-[100px]",children:n.full_name})]})}function at({sha:n,url:o,branch:r,className:i=""}){if(!n)return null;const s=n.slice(0,7),a=e("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] font-mono text-zinc-400 hover:bg-zinc-700 hover:text-zinc-300 transition-colors ${i}`,children:[t("svg",{className:"w-3 h-3",fill:"currentColor",viewBox:"0 0 16 16",children:t("path",{d:"M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"})}),s,r&&e("span",{className:"text-zinc-500",children:["(",r,")"]})]});return o?t("a",{href:o,target:"_blank",rel:"noopener noreferrer",className:"inline-flex",onClick:e=>e.stopPropagation(),children:a}):a}function lt(e){const t=new Date(e),n=(new Date).getTime()-t.getTime(),o=Math.floor(n/6e4),r=Math.floor(o/60),i=Math.floor(r/24);return o<1?"just now":o<60?`${o}m`:r<24?`${r}h`:i<7?`${i}d`:t.toLocaleDateString()}function ct({comments:n,isLoading:o=!1,className:r=""}){return o?t("div",{className:`space-y-2 ${r}`,children:[1,2].map(n=>e("div",{className:"flex gap-2 animate-pulse",children:[t("div",{className:"w-5 h-5 bg-zinc-700 rounded-full"}),e("div",{className:"flex-1 space-y-1",children:[t("div",{className:"h-3 bg-zinc-700 rounded w-20"}),t("div",{className:"h-3 bg-zinc-700 rounded w-full"})]})]},n))}):0===n.length?t("div",{className:`text-center text-xs text-zinc-500 py-3 ${r}`,children:"No comments yet"}):t("div",{className:`space-y-3 ${r}`,children:n.map(n=>e("div",{className:"flex gap-2",children:[t(st,{author:n.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:n.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:lt(n.created_at)})]}),t("p",{className:"text-xs text-zinc-400 mt-0.5 break-words",children:n.content})]})]},n.id))})}function dt({onSubmit:n,placeholder:o="Add a comment...",disabled:r=!1,className:s=""}){const[a,l]=i(""),[c,d]=i(!1),h=async e=>{if(e.preventDefault(),a.trim()&&!c&&!r){d(!0);try{await n(a.trim()),l("")}finally{d(!1)}}};return e("form",{onSubmit:h,className:`flex gap-2 ${s}`,children:[t("input",{type:"text",value:a,onChange:e=>l(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),h(e))},placeholder:o,disabled:r||c,className:"flex-1 px-2 py-1.5 bg-zinc-800 border border-zinc-700 rounded text-xs text-white placeholder:text-zinc-500 focus:outline-none focus:ring-1 focus:ring-blue-500 disabled:opacity-50"}),t("button",{type:"submit",disabled:!a.trim()||c||r,className:"px-2 py-1.5 bg-blue-600 text-white text-xs rounded hover:bg-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:c?e("svg",{className:"w-3 h-3 animate-spin",fill:"none",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}):"Post"})]})}function ht({prompts:n,currentPromptId:o,expandedPromptId:r,comments:s={},isLoadingComments:c=!1,promptOutputs:d={},onSelectPrompt:h,onExpandPrompt:p,onHighlightElement:u,onLoadComments:m,onAddComment:g,onReply:f}){const[b,x]=i(null),[y,w]=i(null),v=a(null),k=a(n.length);if(l(()=>{n.length>k.current&&v.current&&(v.current.scrollTop=0),k.current=n.length},[n.length]),0===n.length)return t("div",{className:"flex items-center justify-center h-32 text-zinc-500 text-sm",children:"No prompts yet. Right-click any element to start!"});const C=e=>{const t=new Date(e),n=(new Date).getTime()-t.getTime(),o=Math.floor(n/6e4),r=Math.floor(n/36e5),i=Math.floor(n/864e5);return o<1?"Just now":o<60?`${o}m ago`:r<24?`${r}h ago`:i<7?`${i}d ago`:t.toLocaleDateString()},N=e=>{switch(e){case"completed":return"success";case"failed":return"error";case"running":return"info";default:return"default"}};return t("div",{ref:v,className:"orquesta-timeline space-y-2 overflow-y-auto max-h-[400px]",children:n.map(n=>{const i=r===n.id,a=n.id===o,l=b===n.id,v=s[n.id]||[],k=d[n.id]||[],S=y===n.id;return e("div",{className:"rounded-lg border transition-all "+(a?"bg-zinc-800 border-blue-500":"bg-zinc-900 border-zinc-800 hover:border-zinc-700"),onMouseEnter:()=>x(n.id),onMouseLeave:()=>x(null),children:[t("button",{onClick:()=>(e=>{h?.(e),e.element_context&&u&&u(e)})(n),className:"w-full text-left p-3",children:e("div",{className:"flex items-start gap-2",children:[t(st,{author:n.author,size:"sm"}),e("div",{className:"flex-1 min-w-0",children:[e("div",{className:"flex items-center gap-2 mb-1",children:[t("span",{className:"text-xs font-medium text-zinc-300 truncate",children:n.author?.full_name||"Unknown"}),t("span",{className:"text-[10px] text-zinc-500",children:C(n.created_at)})]}),e("p",{className:"text-sm text-zinc-200 line-clamp-2",children:[n.content.slice(0,100),n.content.length>100&&"..."]}),e("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[n.git_commit_sha&&t(at,{sha:n.git_commit_sha,url:n.git_commit_url,branch:n.git_branch}),n.element_context&&e("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded-md text-[10px] text-blue-400 font-medium",children:[t("span",{children:"🎯"}),e("span",{children:["<",n.element_context.tag,">"]}),n.element_context.textContent&&e("span",{className:"text-blue-300/70 max-w-[60px] truncate",children:['"',n.element_context.textContent.slice(0,15),'..."']})]}),(n.comment_count||0)>0&&e("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 bg-zinc-800 rounded text-[10px] text-zinc-400",children:["💬 ",n.comment_count]})]})]}),e("div",{className:"flex-shrink-0 flex items-center gap-1.5",children:[t(Ye,{status:n.status}),t(Xe,{variant:N(n.status),size:"sm",children:n.status})]})]})}),e("div",{className:"flex items-center gap-2 px-3 pb-2 -mt-1 "+(l||n.element_context||i||"completed"===n.status||"failed"===n.status?"":"hidden"),children:[n.element_context&&e("button",{onClick:e=>{e.stopPropagation(),u?.(n)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-purple-600/20 border border-purple-500/40 rounded-md text-[11px] text-purple-300 font-medium hover:bg-purple-600/30 hover:border-purple-500/60 transition-all",children:[e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]}),t("span",{children:"Show on page"})]}),("completed"===n.status||"failed"===n.status)&&e("button",{onClick:e=>{e.stopPropagation(),w(S?null:n.id)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[11px] font-medium transition-all "+(S?"bg-zinc-600 border border-zinc-500 text-zinc-100":"bg-zinc-700/50 border border-zinc-600/50 text-zinc-300 hover:bg-zinc-700 hover:border-zinc-500"),children:[t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),t("span",{children:S?"Hide output":"View output"})]}),f&&("completed"===n.status||"failed"===n.status)&&e("button",{onClick:e=>{e.stopPropagation(),f(n,k)},className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-green-600/20 border border-green-500/40 rounded-md text-[11px] text-green-300 font-medium hover:bg-green-600/30 hover:border-green-500/60 transition-all",children:[t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6"})}),t("span",{children:"Reply"})]}),t("button",{onClick:e=>{e.stopPropagation(),(async e=>{r===e?p?.(null):(p?.(e),m&&!s[e]&&await m(e))})(n.id)},className:"inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-medium transition-all ml-auto "+(i?"bg-zinc-700 text-zinc-200":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-300"),children:i?"Hide comments":(n.comment_count||0)>0?`💬 ${n.comment_count}`:"+ Comment"})]}),S&&t("div",{className:"px-3 pb-3 border-t border-zinc-800",children:t("div",{className:"mt-2 bg-zinc-950 rounded-md p-2 max-h-[150px] overflow-y-auto",children:k.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:k.slice(-20).map((e,n)=>t("div",{className:""+("stderr"===e.type?"text-red-400":"tool"===e.type?"text-blue-400":"thinking"===e.type?"text-zinc-500 italic":"system"===e.type?"text-yellow-400":"text-zinc-300"),children:e.content},n))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No output recorded for this prompt"})})}),i&&e("div",{className:"px-3 pb-3 pt-1 border-t border-zinc-800 space-y-3",children:[t(ct,{comments:v,isLoading:c}),g&&t(dt,{onSubmit:e=>g(n.id,e),placeholder:"Add a comment..."})]})]},n.id)})})}const pt=400,ut=500;function mt({state:o,position:r,onClose:s,onMinimize:h,onSubmitPrompt:p,onSelectElement:u,onClearElement:m,onToggleConsole:g,onToggleNetwork:f,onToggleHistory:b,onTabChange:x,onExpandPrompt:y,onHighlightElement:w,onLoadComments:v,onAddComment:k,onOverlayModeChange:C,onLogin:N,onLogout:S,onToggleRightClick:q,onExpandToBuilder:E,demoMode:_=!1}){const z=a(null),[L,A]=i(!1),[O,T]=i(!1),[R,H]=i(null),[M,P]=i(()=>We.get("position")||function(e){const t=20;switch(e){case"bottom-right":return{x:window.innerWidth-pt-t,y:window.innerHeight-ut-t};case"bottom-left":return{x:t,y:window.innerHeight-ut-t};case"top-right":return{x:window.innerWidth-pt-t,y:t};case"top-left":return{x:t,y:t}}}(r)),[j,B]=i(()=>We.get("size")||{width:pt,height:ut}),I=a({x:0,y:0}),$=a({width:0,height:0,x:0,y:0});const D=c((e,t)=>{H({prompt:e,output:t}),x("prompts")},[x]),W=c((e,t)=>{p(e,t),H(null)},[p]),F=c(e=>{e.target.closest("button")||(A(!0),I.current={x:e.clientX-M.x,y:e.clientY-M.y})},[M]),U=c(e=>{e.stopPropagation(),T(!0),$.current={width:j.width,height:j.height,x:e.clientX,y:e.clientY}},[j]);return l(()=>{const e=e=>{if(L){const t=Math.max(0,Math.min(window.innerWidth-j.width,e.clientX-I.current.x)),n=Math.max(0,Math.min(window.innerHeight-j.height,e.clientY-I.current.y));P({x:t,y:n})}else if(O){const t=e.clientX-$.current.x,n=e.clientY-$.current.y,o=Math.max(320,$.current.width+t),r=Math.max(400,$.current.height+n);B({width:o,height:r})}},t=()=>{L&&(A(!1),We.set("position",M)),O&&(T(!1),We.set("size",j))};return(L||O)&&(document.addEventListener("mousemove",e),document.addEventListener("mouseup",t)),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[L,O,M,j]),e("div",{ref:z,className:"orquesta-embed-panel fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl flex flex-col overflow-hidden",style:{left:M.x,top:M.y,width:j.width,height:j.height},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700 cursor-move select-none",onMouseDown:F,children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"}),e("span",{className:"text-[10px] text-zinc-500 font-mono",children:["v",d]}),o.projectName&&e("span",{className:"text-xs text-zinc-400",children:["• ",o.projectName]})]}),e("div",{className:"flex items-center gap-1",children:[o.requireAuth&&(o.isAuthenticated&&o.user?e("div",{className:"flex items-center gap-1.5 mr-2",children:[o.user.avatar_url?t("img",{src:o.user.avatar_url,alt:"",className:"w-5 h-5 rounded-full"}):t("div",{className:"w-5 h-5 rounded-full bg-zinc-600 flex items-center justify-center text-xs text-white",children:o.user.full_name?.[0]?.toUpperCase()||"?"}),t("span",{className:"text-xs text-zinc-300 max-w-20 truncate",children:o.user.full_name||"User"}),t("button",{onClick:S,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Sign out",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})})]}):t("button",{onClick:N,disabled:o.isAuthenticating,className:"flex items-center gap-1 px-2 py-1 mr-2 text-xs bg-blue-600 hover:bg-blue-500 disabled:bg-blue-800 text-white rounded transition-colors",children:o.isAuthenticating?e(n,{children:[e("svg",{className:"animate-spin w-3 h-3",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Signing in..."})]}):e(n,{children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1"})}),t("span",{children:"Sign in"})]})})),t("div",{className:"flex items-center gap-1 mr-1",title:o.isConnected?o.agentOnline?"Agent online":"Agent offline":"Not connected to Orquesta",children:o.isConnected?t(Ye,{status:o.agentOnline?"online":"offline"}):t("span",{className:"w-2 h-2 rounded-full bg-red-500"})}),t("button",{onClick:q,className:"p-1 rounded text-xs "+(o.rightClickEnabled?"bg-green-600 text-white":"bg-zinc-700 text-zinc-400"),title:o.rightClickEnabled?"Right-click enabled":"Right-click disabled",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"})})}),e("div",{className:"flex items-center gap-0.5 mx-1 bg-zinc-800 rounded p-0.5",children:[t("button",{onClick:()=>C?.("off"),className:"p-1 rounded text-xs "+("off"===o.overlayMode?"bg-zinc-700 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Overlay off",children:t("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"})})}),t("button",{onClick:()=>C?.("single"),className:"p-1 rounded text-xs "+("single"===o.overlayMode?"bg-blue-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show selected prompt on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}),t("button",{onClick:()=>C?.("all"),className:"p-1 rounded text-xs "+("all"===o.overlayMode?"bg-purple-600 text-white":"text-zinc-500 hover:text-zinc-300"),title:"Show all prompts on page",children:e("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"}),t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 11a3 3 0 11-6 0 3 3 0 016 0z"})]})})]}),E&&t("button",{onClick:E,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Expand to builder mode",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5v-4m0 4h-4m4 0l-5-5"})})}),t("button",{onClick:h,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Minimize",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:s,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Close",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})]}),e(Ze,{value:o.activeTab,onChange:e=>x(e),className:"flex-1 flex flex-col overflow-hidden",children:[t("div",{className:"px-3 py-2 border-b border-zinc-800",children:e(et,{className:"w-full",children:[t(tt,{value:"prompts",children:"Prompts"}),t(tt,{value:"timeline",children:"Timeline"}),t(tt,{value:"logs",children:"Logs"})]})}),o.connectionError&&t("div",{className:"mx-3 mt-2 px-3 py-2 bg-red-900/30 border border-red-500/30 rounded-lg",children:e("div",{className:"flex items-center gap-2 text-red-400 text-xs",children:[t("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),t("span",{children:o.connectionError})]})}),!o.isConnected&&!o.connectionError&&t("div",{className:"mx-3 mt-2 px-3 py-2 bg-yellow-900/30 border border-yellow-500/30 rounded-lg",children:e("div",{className:"flex items-center gap-2 text-yellow-400 text-xs",children:[t("svg",{className:"w-4 h-4 flex-shrink-0",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),t("span",{children:"Reconnecting to Orquesta..."})]})}),e("div",{className:"flex-1 overflow-y-auto p-3",children:[o.requireAuth&&!o.isAuthenticated&&e("div",{className:"h-full flex flex-col items-center justify-center text-center p-4",children:[t("div",{className:"w-16 h-16 rounded-full bg-zinc-800 flex items-center justify-center mb-4",children:t("svg",{className:"w-8 h-8 text-zinc-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"})})}),t("h3",{className:"text-white font-semibold mb-2",children:"Sign in to continue"}),t("p",{className:"text-zinc-400 text-sm mb-4",children:"You need to sign in to submit prompts to this project."}),o.authError&&t("div",{className:"mb-4 px-3 py-2 bg-red-900/30 border border-red-800 rounded text-red-300 text-xs",children:o.authError}),t("button",{onClick:N,disabled:o.isAuthenticating,className:"flex items-center gap-2 px-4 py-2 bg-white text-gray-800 rounded-lg font-medium hover:bg-gray-100 disabled:bg-gray-300 transition-colors",children:o.isAuthenticating?e(n,{children:[e("svg",{className:"animate-spin w-4 h-4",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{children:"Signing in..."})]}):e(n,{children:[e("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",children:[t("path",{fill:"currentColor",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),t("path",{fill:"currentColor",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),t("path",{fill:"currentColor",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),t("path",{fill:"currentColor",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),t("span",{children:"Continue with Google"})]})}),t("p",{className:"text-zinc-500 text-xs mt-4",children:"You must be a member of this project's organization."})]}),(!o.requireAuth||o.isAuthenticated)&&e(n,{children:[e(nt,{value:"prompts",className:"h-full flex flex-col",children:[t(rt,{onSubmit:W,isSubmitting:o.isSubmitting,selectedElement:o.selectedElement,includeConsole:o.includeConsole,includeNetwork:o.includeNetwork,includeContext:o.includeHistory,promptHistory:o.promptHistory,promptOutputs:o.promptOutputs,queueLength:o.promptQueue?.length||0,onToggleConsole:g,onToggleNetwork:f,onToggleContext:b,onSelectElement:u,onClearElement:m,agentOnline:o.agentOnline,replyContext:R,onClearReply:()=>H(null),demoMode:_}),(o.currentPrompt||o.outputLines.length>0)&&e("div",{className:"mt-4 pt-4 border-t border-zinc-800",children:[o.currentPrompt&&e("div",{className:"flex items-center gap-2 mb-2",children:[t(Ye,{status:o.currentPrompt.status}),e("span",{className:"text-xs text-zinc-400 line-clamp-1",children:[o.currentPrompt.content.slice(0,50),"..."]})]}),t(it,{lines:o.outputLines,isRunning:o.isSubmitting})]})]}),t(nt,{value:"timeline",children:t(ht,{prompts:o.promptHistory,currentPromptId:o.currentPrompt?.id,expandedPromptId:o.expandedPromptId,comments:o.comments,isLoadingComments:o.isLoadingComments,promptOutputs:o.promptOutputs,onExpandPrompt:y,onHighlightElement:w,onLoadComments:v,onAddComment:k,onReply:D})}),e(nt,{value:"logs",className:"h-full flex flex-col",children:[e("div",{className:"mb-4",children:[e("div",{className:"flex items-center justify-between mb-2",children:[t("h3",{className:"text-sm font-medium text-zinc-300",children:"Agent Output"}),o.isSubmitting&&t("span",{className:"text-xs text-green-400 animate-pulse",children:"Running..."})]}),t("div",{className:"bg-zinc-950 rounded-md p-2 max-h-[150px] overflow-y-auto",children:o.outputLines.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:o.outputLines.slice(-30).map(e=>t("div",{className:""+("stderr"===e.type?"text-red-400":"tool"===e.type?"text-blue-400":"thinking"===e.type?"text-zinc-500 italic":"system"===e.type?"text-yellow-400":"text-zinc-300"),children:e.content},e.id))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No agent output yet"})})]}),e("div",{className:"mb-4",children:[e("div",{className:"flex items-center justify-between mb-2",children:[t("h3",{className:"text-sm font-medium text-zinc-300",children:"Console Logs"}),e("span",{className:"text-xs text-zinc-500",children:[o.consoleLogs.length," entries"]})]}),t("div",{className:"bg-zinc-950 rounded-md p-2 max-h-[120px] overflow-y-auto",children:o.consoleLogs.length>0?t("div",{className:"font-mono text-[11px] space-y-0.5",children:o.consoleLogs.slice(-20).map((t,n)=>e("div",{className:""+("error"===t.level?"text-red-400":"warn"===t.level?"text-yellow-400":"text-zinc-300"),children:[e("span",{className:"text-zinc-500",children:["[",t.level,"]"]})," ",t.message]},n))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No console logs captured"})})]}),e("div",{children:[e("div",{className:"flex items-center justify-between mb-2",children:[t("h3",{className:"text-sm font-medium text-zinc-300",children:"Network Requests"}),e("span",{className:"text-xs text-zinc-500",children:[o.networkLogs.length," requests"]})]}),t("div",{className:"bg-zinc-950 rounded-md p-2 max-h-[120px] overflow-y-auto",children:o.networkLogs.length>0?t("div",{className:"font-mono text-[11px] space-y-1",children:o.networkLogs.slice(-15).map((n,o)=>e("div",{className:"flex items-center gap-2",children:[t("span",{className:""+(n.status&&n.status>=400?"text-red-400":n.status&&n.status>=300?"text-yellow-400":"text-green-400"),children:n.status||"..."}),t("span",{className:"text-zinc-400",children:n.method}),t("span",{className:"text-zinc-300 truncate flex-1",children:n.url}),n.duration&&e("span",{className:"text-zinc-500",children:[n.duration,"ms"]})]},o))}):t("div",{className:"text-zinc-500 text-xs text-center py-2",children:"No network requests captured"})})]})]})]})]})]}),t("div",{className:"absolute bottom-0 right-0 w-4 h-4 cursor-se-resize",onMouseDown:U,children:t("svg",{className:"w-full h-full text-zinc-600",viewBox:"0 0 16 16",fill:"currentColor",children:t("path",{d:"M14 14H10V10H14V14ZM14 8H12V6H14V8ZM8 14H6V12H8V14Z"})})})]})}function gt({state:n,onSubmitPrompt:o,onSwitchToWidget:r,onSelectElement:s,onClearElement:h,onToggleConsole:p,onToggleNetwork:u,onToggleHistory:m,onTabChange:g,onExpandPrompt:f,onHighlightElement:b,onLoadComments:x,onAddComment:y,onOverlayModeChange:w,onLogin:v,onLogout:k,onToggleRightClick:C,demoMode:N=!1}){const[S,q]=i(()=>We.get("builderWidth")||380),E=a(!1);l(()=>(document.body.style.marginLeft=`${S+4}px`,document.body.style.transition="margin-left 0.2s ease-out",()=>{document.body.style.marginLeft="",document.body.style.transition=""}),[S]),l(()=>{We.set("builderWidth",S)},[S]);const _=c(e=>{E.current=!0,document.body.style.cursor="col-resize",document.body.style.userSelect="none",e.preventDefault()},[]);l(()=>{const e=e=>{E.current&&q(Math.max(320,Math.min(e.clientX,.5*window.innerWidth)))},t=()=>{E.current&&(E.current=!1,document.body.style.cursor="",document.body.style.userSelect="")};return document.addEventListener("mousemove",e),document.addEventListener("mouseup",t),()=>{document.removeEventListener("mousemove",e),document.removeEventListener("mouseup",t)}},[]);const z=n.activeTab||"prompts";return e("div",{className:"orquesta-embed-panel",style:{position:"fixed",top:0,left:0,bottom:0,width:`${S}px`,zIndex:2147483647,display:"flex",flexDirection:"column",background:"#09090b",borderRight:"1px solid #27272a",boxShadow:"4px 0 24px rgba(0,0,0,0.5)",overflow:"hidden"},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700",style:{flexShrink:0},children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-base",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"}),e("span",{className:"text-[10px] text-zinc-500 font-mono",children:["v",d]}),n.projectName&&e("span",{className:"text-xs text-zinc-500",children:["• ",n.projectName]})]}),e("div",{className:"flex items-center gap-1",children:[n.requireAuth&&n.isAuthenticated&&n.user&&e("div",{className:"flex items-center gap-1 mr-2",children:[t("span",{className:"text-xs text-zinc-400 max-w-[60px] truncate",children:n.user.full_name}),t("button",{onClick:()=>k?.(),className:"text-xs text-zinc-500 hover:text-white p-0.5",children:"↪"})]}),t(Ye,{status:n.isConnected?n.agentOnline?"online":"offline":"disconnected"}),C&&t("button",{onClick:C,className:"p-1 rounded text-xs "+(n.rightClickEnabled?"bg-green-600/20 text-green-400":"text-zinc-500 hover:text-white"),title:n.rightClickEnabled?"Right-click enabled":"Right-click disabled",children:"🎯"}),w&&t("div",{className:"flex gap-0.5 mx-1 p-0.5 bg-zinc-900 rounded",children:["off","single","all"].map(e=>t("button",{onClick:()=>w(e),className:"px-1 py-0.5 rounded text-[10px] "+(n.overlayMode===e?"off"===e?"bg-zinc-700 text-white":"single"===e?"bg-blue-600 text-white":"bg-purple-600 text-white":"text-zinc-500 hover:text-white"),title:"off"===e?"Overlay off":"single"===e?"Show selected":"Show all",children:"off"===e?"👁":"single"===e?"👀":"📍"},e))}),t("button",{onClick:r,className:"p-1 text-zinc-400 hover:text-white hover:bg-zinc-700 rounded",title:"Collapse to widget",children:t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.5 3.5M15 9h4.5M15 9V4.5M15 9l5.5-5.5M9 15v4.5M9 15H4.5M9 15l-5.5 5.5M15 15h4.5M15 15v4.5m0-4.5l5.5 5.5"})})})]})]}),n.connectionError&&e("div",{className:"mx-2 mt-2 p-2 bg-red-900/30 border border-red-800/30 rounded text-xs text-red-300 flex items-center gap-1",children:["⚠️ ",n.connectionError]}),!n.isConnected&&!n.connectionError&&t("div",{className:"mx-2 mt-2 p-2 bg-yellow-900/30 border border-yellow-800/30 rounded text-xs text-yellow-300 flex items-center gap-1",children:"ℹ️ Reconnecting..."}),n.requireAuth&&!n.isAuthenticated&&e("div",{className:"mx-2 mt-2 p-3 text-center",children:[t("p",{className:"text-sm text-white font-medium mb-2",children:"Sign in to continue"}),t("button",{onClick:()=>v?.(),className:"px-4 py-2 bg-white text-gray-700 rounded-lg text-sm font-medium",children:n.isAuthenticating?"Signing in...":"Continue with Google"})]}),e(Ze,{value:z,onValueChange:e=>g(e),children:[t("div",{className:"px-2 py-1.5 border-b border-zinc-800",style:{flexShrink:0},children:e(et,{children:[t(tt,{value:"prompts",children:"Prompts"}),t(tt,{value:"timeline",children:"Timeline"}),t(tt,{value:"logs",children:"Logs"})]})}),e("div",{style:{flex:1,overflowY:"auto"},children:[e(nt,{value:"prompts",children:[t("div",{className:"p-3",children:t(rt,{agentOnline:n.agentOnline,isSubmitting:n.isSubmitting,selectedElement:n.selectedElement,includeConsole:n.includeConsole,includeNetwork:n.includeNetwork,includeHistory:n.includeHistory,includeContext:n.includeContext,onSubmit:o,onSelectElement:s,onClearElement:h,onToggleConsole:p,onToggleNetwork:u,onToggleHistory:m})}),(n.outputLines.length>0||n.isSubmitting)&&t("div",{className:"px-3 pb-3 border-t border-zinc-800 pt-2",children:t(it,{lines:n.outputLines,isStreaming:n.isSubmitting,maxHeight:"250px"})})]}),t(nt,{value:"timeline",children:t("div",{className:"p-3",children:t(ht,{prompts:n.promptHistory,expandedPromptId:n.expandedPromptId||null,comments:n.comments,isLoadingComments:n.isLoadingComments,promptOutputs:n.promptOutputs,onExpand:e=>f?.(e),onHighlightElement:e=>b?.(e),onLoadComments:e=>x?.(e),onAddComment:(e,t)=>y?.(e,t),onReply:e=>{g("prompts")}})})}),t(nt,{value:"logs",children:t("div",{className:"p-3",children:t(it,{lines:n.outputLines,isStreaming:n.isSubmitting,maxHeight:"none"})})})]})]}),t("div",{onMouseDown:_,style:{position:"absolute",top:0,right:"-3px",bottom:0,width:"6px",cursor:"col-resize",zIndex:1}})]})}function ft({isActive:n,onCancel:o}){const r=a(null);return l(()=>{const e=e=>{"Escape"===e.key&&n&&o()};return n&&document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[n,o]),n?t("div",{ref:r,className:"orquesta-element-inspector fixed inset-0 z-[2147483645] pointer-events-none",children:t("div",{className:"absolute top-4 left-1/2 -translate-x-1/2 pointer-events-auto",children:e("div",{className:"flex items-center gap-3 px-4 py-2 bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl",children:[t("span",{className:"text-sm text-zinc-300",children:"Click on any element to select it, or right-click for options"}),t(Ve,{variant:"ghost",size:"sm",onClick:o,children:"Cancel (Esc)"})]})})}):null}function bt({markers:n,onMarkerClick:o}){const[r,s]=i([]),[d,h]=i(null),p=a(null),u=c(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{const e=window.innerHeight,t=window.innerWidth,o=[];for(const r of n)try{const n=document.querySelector(r.selector);if(n){const i=n.getBoundingClientRect(),s=i.left+i.width/2,a=i.top+i.height/2,l=i.top<e&&i.bottom>0&&i.left<t&&i.right>0;o.push({promptId:r.promptId,x:s,y:a,visible:!0,inViewport:l})}else o.push({promptId:r.promptId,x:0,y:0,visible:!1,inViewport:!1})}catch{o.push({promptId:r.promptId,x:0,y:0,visible:!1,inViewport:!1})}s(o)})},[n]);l(()=>{u();let e=!1;const t=()=>{e||(e=!0,requestAnimationFrame(()=>{u(),e=!1}))};window.addEventListener("scroll",t,!0),window.addEventListener("resize",t);const n=new MutationObserver(t);return n.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),()=>{window.removeEventListener("scroll",t,!0),window.removeEventListener("resize",t),n.disconnect(),p.current&&cancelAnimationFrame(p.current)}},[u]);const m=d?n.find(e=>e.promptId===d):null,g=d?r.find(e=>e.promptId===d):null;return e("div",{className:"orquesta-markers-overlay fixed inset-0 pointer-events-none z-[2147483646]",children:[r.map((r,i)=>{if(!r.visible||!r.inViewport)return null;const s=n.find(e=>e.promptId===r.promptId);if(!s)return null;const a=d===r.promptId;return e("div",{className:"absolute pointer-events-auto",style:{left:r.x,top:r.y,transform:"translate(-50%, -50%)"},children:[e("button",{onClick:()=>o?.(r.promptId),onMouseEnter:()=>h(r.promptId),onMouseLeave:()=>h(null),className:"relative flex items-center gap-1.5 px-2 py-1 rounded-full border-2 shadow-lg transition-all "+(a?"bg-purple-500 border-white scale-110":"bg-purple-600 border-white/80 hover:scale-105"),children:[t("span",{className:"w-5 h-5 flex items-center justify-center bg-white/20 rounded-full text-white text-[10px] font-bold",children:i+1}),e("span",{className:"text-white text-[11px] font-medium max-w-[120px] truncate",children:[s.content.slice(0,25),s.content.length>25?"...":""]})]}),t("div",{className:"absolute inset-0 -z-10 animate-ping rounded-full bg-purple-500/30",style:{animationDuration:"2s"}})]},r.promptId)}),m&&g&&g.visible&&g.inViewport&&e("div",{className:"fixed pointer-events-none bg-zinc-900 border border-zinc-600 rounded-xl shadow-2xl p-4 z-20",style:{...(e=>{let t=e.x+20,n=e.y+20;return t+280>window.innerWidth-20&&(t=e.x-280-20),n+180>window.innerHeight-20&&(n=e.y-180-20),{left:t,top:n}})(g),width:280},children:[e("div",{className:"flex items-center justify-between mb-3",children:[e("div",{className:"flex items-center gap-2",children:[t(st,{author:m.author,size:"sm"}),t("span",{className:"text-xs font-medium text-zinc-200",children:m.author?.full_name||"Unknown"})]}),e("span",{className:"px-2 py-0.5 bg-blue-500/20 border border-blue-500/30 rounded text-[10px] text-blue-400 font-mono",children:["🎯 ",m.selector.split(" ").pop()?.split(".")[0]||"element"]})]}),e("p",{className:"text-sm text-zinc-200 mb-3 line-clamp-3",children:[m.content.slice(0,150),m.content.length>150&&"..."]}),e("div",{className:"flex items-center gap-3 text-[10px] text-zinc-500",children:[m.gitCommitSha&&e("span",{className:"inline-flex items-center gap-1 font-mono bg-zinc-800 px-1.5 py-0.5 rounded",children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),m.gitCommitSha.slice(0,7)]}),m.commentCount>0&&e("span",{className:"inline-flex items-center gap-1",children:["💬 ",m.commentCount," comments"]})]}),t("div",{className:"mt-3 pt-2 border-t border-zinc-800 text-[10px] text-zinc-500 text-center",children:"Click to view in timeline"})]})]})}function xt({isOpen:n,position:o,element:r,agentOnline:s,includeConsole:c,includeNetwork:d,onSubmit:h,onClose:p,onToggleConsole:u,onToggleNetwork:m,onOpenPanel:g}){const[f,b]=i(""),[x,y]=i(!1),w=a(null),v=a(null);if(l(()=>{n&&v.current&&setTimeout(()=>v.current?.focus(),50)},[n]),l(()=>{if(n&&w.current){const e=w.current,t=e.getBoundingClientRect(),n=window.innerWidth,o=window.innerHeight;t.right>n-20&&(e.style.left=`${Math.max(20,n-t.width-20)}px`),t.bottom>o-20&&(e.style.top=`${Math.max(20,o-t.height-20)}px`)}},[n,o]),l(()=>{if(!n)return;const e=e=>{w.current&&!w.current.contains(e.target)&&p()},t=e=>{"Escape"===e.key&&p()};return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)}},[n,p]),l(()=>{n&&(b(""),y(!1))},[n]),!n||!r)return null;const k=async e=>{e.preventDefault(),f.trim()&&!x&&s&&(y(!0),h(f.trim()),b(""),setTimeout(()=>{p()},100))};return e("div",{ref:w,id:"orquesta-context-menu",style:{position:"fixed",zIndex:2147483647,backgroundColor:"#18181b",border:"1px solid #52525b",borderRadius:"12px",boxShadow:"0 25px 50px -12px rgba(0, 0, 0, 0.5)",overflow:"hidden",left:o.x,top:o.y,width:340,maxWidth:"calc(100vw - 40px)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',color:"#ffffff"},onClick:e=>e.stopPropagation(),children:[e("div",{style:{padding:"10px 12px",backgroundColor:"#27272a",borderBottom:"1px solid #3f3f46"},children:[e("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"6px"},children:[t("div",{style:{width:"24px",height:"24px",borderRadius:"6px",backgroundColor:"rgba(37, 99, 235, 0.2)",border:"1px solid rgba(59, 130, 246, 0.3)",display:"flex",alignItems:"center",justifyContent:"center"},children:t("span",{style:{color:"#60a5fa",fontSize:"14px"},children:"🎯"})}),t("span",{style:{fontSize:"14px",fontWeight:500,color:"#ffffff"},children:"Selected Element"})]}),t("div",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"11px",color:"#a1a1aa",backgroundColor:"rgba(24, 24, 27, 0.5)",padding:"6px 8px",borderRadius:"6px",wordBreak:"break-all"},children:(()=>{const e=[];if(e.push(`<${r.tag}`),r.id&&e.push(` id="${r.id}"`),r.className){const t=r.className.split(" ").slice(0,2).join(" ");e.push(` class="${t}${r.className.split(" ").length>2?"...":""}"`)}if(e.push(">"),r.textContent){const t=r.textContent.slice(0,30);e.push(t+(r.textContent.length>30?"...":""))}return e.push(`</${r.tag}>`),e.join("")})()})]}),e("form",{onSubmit:k,style:{padding:"12px"},children:[t("textarea",{ref:v,value:f,onChange:e=>b(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&k(e)},placeholder:s?"What do you want to do with this element?":"Agent is offline...",disabled:x||!s,rows:3,style:{width:"100%",padding:"8px 10px",backgroundColor:"#09090b",border:"1px solid #3f3f46",borderRadius:"6px",color:"#ffffff",fontSize:"13px",fontFamily:"inherit",resize:"vertical",outline:"none",boxSizing:"border-box"}}),e("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px",marginTop:"12px"},children:[e("button",{type:"button",onClick:u,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:c?"rgba(234, 179, 8, 0.2)":"#27272a",color:c?"#fde047":"#a1a1aa",border:c?"1px solid rgba(234, 179, 8, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"📋"}),t("span",{children:"Logs"}),c&&t("span",{style:{marginLeft:"2px",color:"#facc15"},children:"✓"})]}),e("button",{type:"button",onClick:m,style:{display:"inline-flex",alignItems:"center",gap:"6px",padding:"6px 10px",borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"all 0.15s ease",backgroundColor:d?"rgba(239, 68, 68, 0.2)":"#27272a",color:d?"#fca5a5":"#a1a1aa",border:d?"1px solid rgba(239, 68, 68, 0.3)":"1px solid #3f3f46"},children:[t("span",{children:"🌐"}),t("span",{children:"Network"}),d&&t("span",{style:{marginLeft:"2px",color:"#f87171"},children:"✓"})]})]}),e("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:"12px",paddingTop:"12px",borderTop:"1px solid #27272a"},children:[t("button",{type:"button",onClick:g,style:{fontSize:"12px",color:"#a1a1aa",background:"none",border:"none",cursor:"pointer",padding:0},children:"Open full panel →"}),e("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[t("button",{type:"button",onClick:p,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:"pointer",backgroundColor:"transparent",color:"#d4d4d8",border:"none"},children:"Cancel"}),t("button",{type:"submit",disabled:!f.trim()||!s||x,style:{padding:"6px 12px",borderRadius:"6px",fontSize:"12px",fontWeight:500,cursor:f.trim()&&s&&!x?"pointer":"not-allowed",backgroundColor:f.trim()&&s&&!x?"#2563eb":"#3f3f46",color:"#ffffff",border:"none",opacity:f.trim()&&s&&!x?1:.5},children:x?"Submitting...":"Submit"})]})]}),e("div",{style:{marginTop:"8px",fontSize:"10px",color:"#71717a",textAlign:"center"},children:["Press ",t("kbd",{style:{padding:"2px 4px",backgroundColor:"#27272a",borderRadius:"4px"},children:"⌘/Ctrl + Enter"})," to submit"]})]})]})}function yt({isConnected:n,agentOnline:o,projectName:r,currentPrompt:s,isSubmitting:a,lastCompletedPrompt:c,onClose:d}){const[h,p]=i(!0),[u,m]=i(!1),g=n?o?a||"running"===s?.status?"running":"completed"===s?.status?"completed":"failed"===s?.status?"failed":"idle":"offline":"connecting";if(l(()=>{"running"!==g&&"completed"!==g&&"failed"!==g||(p(!0),m(!1))},[g]),l(()=>{if("completed"===g||"failed"===g){const e=setTimeout(()=>{m(!0)},5e3);return()=>clearTimeout(e)}},[g,s?.id]),!h)return null;const f=(()=>{switch(g){case"connecting":return{bg:"#27272a",border:"#3f3f46",icon:"⟳",iconBg:"#3f3f46",text:"Connecting to Orquesta...",pulse:!0};case"offline":return{bg:"#27272a",border:"#ef4444",icon:"○",iconBg:"#7f1d1d",text:"Agent offline",pulse:!1};case"running":return{bg:"#172554",border:"#3b82f6",icon:"⟳",iconBg:"#1d4ed8",text:`Running: ${s?.content.slice(0,50)}${(s?.content.length||0)>50?"...":""}`,pulse:!0};case"completed":return{bg:"#14532d",border:"#22c55e",icon:"✓",iconBg:"#15803d",text:"Completed"+(s?.git_commit_sha?` • Commit ${s.git_commit_sha.slice(0,7)}`:""),pulse:!1};case"failed":return{bg:"#450a0a",border:"#ef4444",icon:"✕",iconBg:"#b91c1c",text:"Prompt failed",pulse:!1};default:return{bg:"#18181b",border:"#3f3f46",icon:"⬡",iconBg:"#27272a",text:r?`${r} • Ready`:"Orquesta Ready",pulse:!1}}})();return e("div",u?{id:"orquesta-status-bar-minimized",onClick:()=>m(!1),style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"6px",padding:"6px 12px",backgroundColor:f.bg,border:`1px solid ${f.border}`,borderRadius:"20px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.3)",cursor:"pointer",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',transition:"all 0.2s ease"},children:[t("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"completed"===g?"#22c55e":"failed"===g?"#ef4444":"running"===g?"#3b82f6":"#71717a",animation:f.pulse?"pulse 2s infinite":"none"}}),t("span",{style:{fontSize:"11px",color:"#d4d4d8",fontWeight:500},children:"Orquesta"}),t("style",{children:"\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]}:{id:"orquesta-status-bar",style:{position:"fixed",top:"12px",left:"50%",transform:"translateX(-50%)",zIndex:2147483646,display:"flex",alignItems:"center",gap:"10px",padding:"8px 12px 8px 10px",backgroundColor:f.bg,border:`1px solid ${f.border}`,borderRadius:"10px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.4)",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',maxWidth:"calc(100vw - 40px)",transition:"all 0.3s ease"},children:[t("div",{style:{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:f.iconBg,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t("span",{style:{fontSize:"14px",color:"#ffffff",animation:f.pulse?"spin 1s linear infinite":"none"},children:f.icon})}),e("div",{style:{flex:1,minWidth:0},children:[t("div",{style:{fontSize:"12px",fontWeight:500,color:"#ffffff",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"400px"},children:f.text}),"running"===g&&t("div",{style:{marginTop:"4px",height:"3px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"2px",overflow:"hidden"},children:t("div",{style:{height:"100%",backgroundColor:"#3b82f6",borderRadius:"2px",animation:"progress 2s ease-in-out infinite"}})})]}),"completed"===g&&s?.git_branch&&e("div",{style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"rgba(255, 255, 255, 0.1)",borderRadius:"4px",flexShrink:0},children:[t("svg",{style:{width:"12px",height:"12px",color:"#a1a1aa"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})}),t("span",{style:{fontSize:"11px",color:"#a1a1aa",fontFamily:"ui-monospace, monospace"},children:s.git_branch})]}),t("button",{onClick:()=>m(!0),style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Minimize",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20 12H4"})})}),t("button",{onClick:()=>{p(!1),d()},style:{width:"20px",height:"20px",borderRadius:"4px",backgroundColor:"transparent",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:"#71717a",flexShrink:0},title:"Close",children:t("svg",{style:{width:"14px",height:"14px"},fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})}),t("style",{children:"\n @keyframes spin {\n from { transform: rotate(0deg); }\n to { transform: rotate(360deg); }\n }\n @keyframes progress {\n 0% { width: 0%; margin-left: 0%; }\n 50% { width: 40%; margin-left: 30%; }\n 100% { width: 0%; margin-left: 100%; }\n }\n @keyframes pulse {\n 0%, 100% { opacity: 1; }\n 50% { opacity: 0.5; }\n }\n "})]})}const wt=[{id:"demo-1",full_name:"Sarah Chen",avatar_url:null},{id:"demo-2",full_name:"Mike Johnson",avatar_url:null},{id:"demo-3",full_name:"Alex Rivera",avatar_url:null}],vt=[{id:"demo-prompt-1",content:'Change the "Shop Now" button color to green and add a hover animation',status:"completed",created_at:new Date(Date.now()-72e5).toISOString(),completed_at:new Date(Date.now()-72e5+45e3).toISOString(),user_id:"demo-1",source:"embed",element_context:{selector:"button.bg-blue-600",tag:"button",className:"px-6 py-3 bg-blue-600 text-white rounded-lg font-medium",textContent:"Shop Now"},author:wt[0],git_branch:"main",git_commit_sha:"a1b2c3d",comment_count:2},{id:"demo-prompt-2",content:'Add a discount badge showing "20% OFF" to the Premium Headphones card',status:"completed",created_at:new Date(Date.now()-36e5).toISOString(),completed_at:new Date(Date.now()-36e5+32e3).toISOString(),user_id:"demo-2",source:"embed",element_context:{selector:"div.bg-gradient-to-br.from-purple-400",tag:"div",className:"bg-gradient-to-br from-purple-400 to-purple-600 h-48 relative",textContent:"Best Seller"},author:wt[1],git_branch:"feature/product-badges",git_commit_sha:"e4f5g6h",comment_count:1},{id:"demo-prompt-3",content:"Make the contact form email field validate on blur and show error message",status:"completed",created_at:new Date(Date.now()-18e5).toISOString(),completed_at:new Date(Date.now()-18e5+28e3).toISOString(),user_id:"demo-3",source:"embed",element_context:{selector:'input[type="email"]',tag:"input",className:"w-full px-4 py-2 border border-gray-300 rounded-lg",textContent:""},author:wt[2],git_branch:"main",git_commit_sha:"i7j8k9l",comment_count:0}],kt={"demo-prompt-1":[{id:"comment-1",content:"Looks great! The animation is smooth.",created_at:new Date(Date.now()-54e5).toISOString(),author:wt[1]},{id:"comment-2",content:"Could we also add this to the Learn More button?",created_at:new Date(Date.now()-36e5).toISOString(),author:wt[2]}],"demo-prompt-2":[{id:"comment-3",content:"Perfect placement for the badge!",created_at:new Date(Date.now()-27e5).toISOString(),author:wt[0]}]};function Ct(o){const{children:r,enableGlobalRightClick:s=!0,demoMode:h=!1,...p}=o,[u,m]=i(null),[g,f]=i(h?{isConnected:!0,isConnecting:!1,connectionError:null,projectId:"demo-project",projectName:"Demo Store",agentOnline:!0,isAuthenticated:!1,isAuthenticating:!1,user:null,authError:null,requireAuth:!1,isOpen:!1,activeTab:"prompts",isSelectingElement:!1,selectedElement:null,rightClickEnabled:!0,currentPrompt:null,promptHistory:[...vt],isSubmitting:!1,outputLines:[],overlayMode:"off",highlightedPromptId:null,elementMarkers:[],comments:{...kt},isLoadingComments:!1,expandedPromptId:null,promptOutputs:{},promptQueue:[],consoleLogs:[],networkLogs:[],includeConsole:!1,includeNetwork:!1,includeHistory:!1,includeContext:!1,requireAuth:p.requireAuth||!1}:null),[b,x]=i(!1),[y,w]=i(null),[v,k]=i({isOpen:!1,position:{x:0,y:0},element:null}),[C,N]=i(p.mode||"widget"),[S,q]=i(!0),[E,_]=i(null),z=a(null),L=a(null);a(null),l(()=>{console.log(`[Orquesta Embed] v${d}`),function(){if(Ue||"undefined"==typeof document)return;const e="orquesta-embed-styles";if(document.getElementById(e))return void(Ue=!0);const t=document.createElement("style");t.id=e,t.textContent="\n/* Orquesta Embed SDK Styles - Auto-injected */\n/* These styles are scoped to orquesta-* classes to avoid conflicts */\n\n/* Reset for Orquesta elements */\n[class^=\"orquesta-\"],\n[class*=\" orquesta-\"] {\n box-sizing: border-box;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n}\n\n/* Base colors */\n.orquesta-embed-panel {\n --orq-bg: #18181b;\n --orq-bg-secondary: #27272a;\n --orq-border: #3f3f46;\n --orq-text: #fafafa;\n --orq-text-muted: #a1a1aa;\n --orq-primary: #3b82f6;\n --orq-success: #22c55e;\n --orq-warning: #eab308;\n --orq-error: #ef4444;\n}\n\n/* Scrollbar styling */\n.orquesta-embed-panel ::-webkit-scrollbar {\n width: 6px;\n height: 6px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-track {\n background: transparent;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb {\n background: #3f3f46;\n border-radius: 3px;\n}\n\n.orquesta-embed-panel ::-webkit-scrollbar-thumb:hover {\n background: #52525b;\n}\n\n/* Animations */\n@keyframes orquesta-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n@keyframes orquesta-pulse {\n 0%, 100% {\n opacity: 1;\n }\n 50% {\n opacity: 0.5;\n }\n}\n\n.orquesta-embed-panel .animate-spin {\n animation: orquesta-spin 1s linear infinite;\n}\n\n.orquesta-embed-panel .animate-pulse {\n animation: orquesta-pulse 2s ease-in-out infinite;\n}\n\n/* Utility classes */\n.orquesta-embed-panel .line-clamp-1 {\n display: -webkit-box;\n -webkit-line-clamp: 1;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n.orquesta-embed-panel .line-clamp-2 {\n display: -webkit-box;\n -webkit-line-clamp: 2;\n -webkit-box-orient: vertical;\n overflow: hidden;\n}\n\n/* Focus visible */\n.orquesta-embed-panel button:focus-visible,\n.orquesta-embed-panel input:focus-visible,\n.orquesta-embed-panel textarea:focus-visible {\n outline: 2px solid var(--orq-primary);\n outline-offset: 2px;\n}\n\n/* Element selector highlight animation */\n#orquesta-element-highlight {\n animation: orquesta-highlight-pulse 1.5s ease-in-out infinite;\n}\n\n@keyframes orquesta-highlight-pulse {\n 0%, 100% {\n box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);\n }\n 50% {\n box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2);\n }\n}\n\n/* Tooltip */\n.orquesta-tooltip {\n position: absolute;\n z-index: 2147483647;\n padding: 4px 8px;\n background: #18181b;\n border: 1px solid #3f3f46;\n border-radius: 4px;\n font-size: 12px;\n color: #fafafa;\n pointer-events: none;\n white-space: nowrap;\n}\n\n/* Transitions */\n.orquesta-embed-panel * {\n transition-property: color, background-color, border-color, opacity, transform;\n transition-duration: 150ms;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n/* Panel entrance animation */\n.orquesta-embed-panel {\n animation: orquesta-panel-enter 0.2s ease-out;\n}\n\n@keyframes orquesta-panel-enter {\n from {\n opacity: 0;\n transform: scale(0.95) translateY(10px);\n }\n to {\n opacity: 1;\n transform: scale(1) translateY(0);\n }\n}\n\n/* Trigger button */\n.orquesta-embed-trigger {\n animation: orquesta-trigger-enter 0.3s ease-out;\n}\n\n@keyframes orquesta-trigger-enter {\n from {\n opacity: 0;\n transform: scale(0.8);\n }\n to {\n opacity: 1;\n transform: scale(1);\n }\n}\n\n/* Log stream */\n.orquesta-log-stream {\n background: #0a0a0a;\n border: 1px solid #27272a;\n border-radius: 6px;\n padding: 8px;\n}\n\n/* Timeline item hover */\n.orquesta-timeline button:hover {\n transform: translateX(2px);\n}\n\n/* ============================================ */\n/* Tailwind class overrides - CRITICAL STYLES */\n/* These ensure styles work even when purged */\n/* ============================================ */\n\n/* Explicit background colors */\n.orquesta-embed-panel {\n background-color: #18181b !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel .bg-zinc-950 { background-color: #09090b !important; }\n.orquesta-embed-panel .bg-zinc-900 { background-color: #18181b !important; }\n.orquesta-embed-panel .bg-zinc-800 { background-color: #27272a !important; }\n.orquesta-embed-panel .bg-zinc-700 { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .bg-zinc-600 { background-color: #52525b !important; }\n\n/* Text colors */\n.orquesta-embed-panel .text-white { color: #fafafa !important; }\n.orquesta-embed-panel .text-zinc-100 { color: #f4f4f5 !important; }\n.orquesta-embed-panel .text-zinc-200 { color: #e4e4e7 !important; }\n.orquesta-embed-panel .text-zinc-300 { color: #d4d4d8 !important; }\n.orquesta-embed-panel .text-zinc-400 { color: #a1a1aa !important; }\n.orquesta-embed-panel .text-zinc-500 { color: #71717a !important; }\n.orquesta-embed-panel .text-red-400 { color: #f87171 !important; }\n.orquesta-embed-panel .text-red-300 { color: #fca5a5 !important; }\n.orquesta-embed-panel .text-green-400 { color: #4ade80 !important; }\n.orquesta-embed-panel .text-green-500 { color: #22c55e !important; }\n.orquesta-embed-panel .text-blue-400 { color: #60a5fa !important; }\n.orquesta-embed-panel .text-blue-500 { color: #3b82f6 !important; }\n.orquesta-embed-panel .text-yellow-400 { color: #facc15 !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .text-orange-400 { color: #fb923c !important; }\n.orquesta-embed-panel .text-gray-800 { color: #1f2937 !important; }\n\n/* Border colors */\n.orquesta-embed-panel .border-zinc-700 { border-color: #3f3f46 !important; }\n.orquesta-embed-panel .border-zinc-800 { border-color: #27272a !important; }\n.orquesta-embed-panel .border-red-800 { border-color: #991b1b !important; }\n\n/* Background colors for buttons and UI */\n.orquesta-embed-panel .bg-blue-500 { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .bg-blue-600 { background-color: #2563eb !important; }\n.orquesta-embed-panel .bg-green-400 { background-color: #4ade80 !important; }\n.orquesta-embed-panel .bg-green-500 { background-color: #22c55e !important; }\n.orquesta-embed-panel .bg-green-600 { background-color: #16a34a !important; }\n.orquesta-embed-panel .bg-red-500 { background-color: #ef4444 !important; }\n.orquesta-embed-panel .bg-red-600 { background-color: #dc2626 !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-red-900\\/30 { background-color: rgba(127, 29, 29, 0.3) !important; }\n.orquesta-embed-panel .bg-white { background-color: #ffffff !important; }\n\n/* Hover states */\n.orquesta-embed-panel .hover\\:bg-zinc-700:hover { background-color: #3f3f46 !important; }\n.orquesta-embed-panel .hover\\:bg-zinc-800:hover { background-color: #27272a !important; }\n.orquesta-embed-panel .hover\\:bg-blue-500:hover { background-color: #3b82f6 !important; }\n.orquesta-embed-panel .hover\\:bg-blue-700:hover { background-color: #1d4ed8 !important; }\n.orquesta-embed-panel .hover\\:bg-gray-100:hover { background-color: #f3f4f6 !important; }\n.orquesta-embed-panel .hover\\:text-white:hover { color: #fafafa !important; }\n.orquesta-embed-panel .hover\\:text-zinc-300:hover { color: #d4d4d8 !important; }\n\n/* Form inputs */\n.orquesta-embed-panel input,\n.orquesta-embed-panel textarea {\n background-color: #27272a !important;\n border-color: #3f3f46 !important;\n color: #fafafa !important;\n}\n\n.orquesta-embed-panel input::placeholder,\n.orquesta-embed-panel textarea::placeholder {\n color: #71717a !important;\n}\n\n/* Buttons base */\n.orquesta-embed-panel button {\n background-color: transparent;\n}\n\n.orquesta-embed-panel button:hover {\n background-color: #3f3f46;\n}\n\n/* Rounded borders */\n.orquesta-embed-panel .rounded { border-radius: 0.25rem !important; }\n.orquesta-embed-panel .rounded-md { border-radius: 0.375rem !important; }\n.orquesta-embed-panel .rounded-lg { border-radius: 0.5rem !important; }\n.orquesta-embed-panel .rounded-xl { border-radius: 0.75rem !important; }\n.orquesta-embed-panel .rounded-full { border-radius: 9999px !important; }\n\n/* Border widths */\n.orquesta-embed-panel .border { border-width: 1px !important; }\n.orquesta-embed-panel .border-b { border-bottom-width: 1px !important; }\n.orquesta-embed-panel .border-t { border-top-width: 1px !important; }\n\n/* Padding */\n.orquesta-embed-panel .p-1 { padding: 0.25rem !important; }\n.orquesta-embed-panel .p-2 { padding: 0.5rem !important; }\n.orquesta-embed-panel .p-3 { padding: 0.75rem !important; }\n.orquesta-embed-panel .p-4 { padding: 1rem !important; }\n.orquesta-embed-panel .px-2 { padding-left: 0.5rem !important; padding-right: 0.5rem !important; }\n.orquesta-embed-panel .px-3 { padding-left: 0.75rem !important; padding-right: 0.75rem !important; }\n.orquesta-embed-panel .px-4 { padding-left: 1rem !important; padding-right: 1rem !important; }\n.orquesta-embed-panel .py-1 { padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; }\n.orquesta-embed-panel .py-2 { padding-top: 0.5rem !important; padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .py-3 { padding-top: 0.75rem !important; padding-bottom: 0.75rem !important; }\n\n/* Margin */\n.orquesta-embed-panel .m-1 { margin: 0.25rem !important; }\n.orquesta-embed-panel .m-2 { margin: 0.5rem !important; }\n.orquesta-embed-panel .mb-1 { margin-bottom: 0.25rem !important; }\n.orquesta-embed-panel .mb-2 { margin-bottom: 0.5rem !important; }\n.orquesta-embed-panel .mb-4 { margin-bottom: 1rem !important; }\n.orquesta-embed-panel .mt-1 { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .mt-2 { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .mt-3 { margin-top: 0.75rem !important; }\n.orquesta-embed-panel .mt-4 { margin-top: 1rem !important; }\n.orquesta-embed-panel .mr-1 { margin-right: 0.25rem !important; }\n.orquesta-embed-panel .mr-2 { margin-right: 0.5rem !important; }\n.orquesta-embed-panel .mx-1 { margin-left: 0.25rem !important; margin-right: 0.25rem !important; }\n\n/* Gap */\n.orquesta-embed-panel .gap-0\\.5 { gap: 0.125rem !important; }\n.orquesta-embed-panel .gap-1 { gap: 0.25rem !important; }\n.orquesta-embed-panel .gap-1\\.5 { gap: 0.375rem !important; }\n.orquesta-embed-panel .gap-2 { gap: 0.5rem !important; }\n.orquesta-embed-panel .gap-3 { gap: 0.75rem !important; }\n.orquesta-embed-panel .gap-4 { gap: 1rem !important; }\n\n/* Flex */\n.orquesta-embed-panel .flex { display: flex !important; }\n.orquesta-embed-panel .flex-col { flex-direction: column !important; }\n.orquesta-embed-panel .flex-1 { flex: 1 1 0% !important; }\n.orquesta-embed-panel .flex-shrink-0 { flex-shrink: 0 !important; }\n.orquesta-embed-panel .items-center { align-items: center !important; }\n.orquesta-embed-panel .items-start { align-items: flex-start !important; }\n.orquesta-embed-panel .justify-center { justify-content: center !important; }\n.orquesta-embed-panel .justify-between { justify-content: space-between !important; }\n\n/* Width/Height */\n.orquesta-embed-panel .w-full { width: 100% !important; }\n.orquesta-embed-panel .w-2 { width: 0.5rem !important; }\n.orquesta-embed-panel .w-3 { width: 0.75rem !important; }\n.orquesta-embed-panel .w-3\\.5 { width: 0.875rem !important; }\n.orquesta-embed-panel .w-4 { width: 1rem !important; }\n.orquesta-embed-panel .w-5 { width: 1.25rem !important; }\n.orquesta-embed-panel .w-6 { width: 1.5rem !important; }\n.orquesta-embed-panel .w-8 { width: 2rem !important; }\n.orquesta-embed-panel .w-16 { width: 4rem !important; }\n.orquesta-embed-panel .h-2 { height: 0.5rem !important; }\n.orquesta-embed-panel .h-3 { height: 0.75rem !important; }\n.orquesta-embed-panel .h-3\\.5 { height: 0.875rem !important; }\n.orquesta-embed-panel .h-4 { height: 1rem !important; }\n.orquesta-embed-panel .h-5 { height: 1.25rem !important; }\n.orquesta-embed-panel .h-6 { height: 1.5rem !important; }\n.orquesta-embed-panel .h-8 { height: 2rem !important; }\n.orquesta-embed-panel .h-16 { height: 4rem !important; }\n.orquesta-embed-panel .h-full { height: 100% !important; }\n.orquesta-embed-panel .max-w-20 { max-width: 5rem !important; }\n\n/* Font */\n.orquesta-embed-panel .text-xs { font-size: 0.75rem !important; line-height: 1rem !important; }\n.orquesta-embed-panel .text-sm { font-size: 0.875rem !important; line-height: 1.25rem !important; }\n.orquesta-embed-panel .text-lg { font-size: 1.125rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-xl { font-size: 1.25rem !important; line-height: 1.75rem !important; }\n.orquesta-embed-panel .text-2xl { font-size: 1.5rem !important; line-height: 2rem !important; }\n.orquesta-embed-panel .text-4xl { font-size: 2.25rem !important; line-height: 2.5rem !important; }\n.orquesta-embed-panel .font-medium { font-weight: 500 !important; }\n.orquesta-embed-panel .font-semibold { font-weight: 600 !important; }\n.orquesta-embed-panel .font-bold { font-weight: 700 !important; }\n.orquesta-embed-panel .text-center { text-align: center !important; }\n.orquesta-embed-panel .truncate { overflow: hidden !important; text-overflow: ellipsis !important; white-space: nowrap !important; }\n\n/* Opacity */\n.orquesta-embed-panel .opacity-25 { opacity: 0.25 !important; }\n.orquesta-embed-panel .opacity-50 { opacity: 0.5 !important; }\n.orquesta-embed-panel .opacity-75 { opacity: 0.75 !important; }\n\n/* Overflow */\n.orquesta-embed-panel .overflow-hidden { overflow: hidden !important; }\n.orquesta-embed-panel .overflow-y-auto { overflow-y: auto !important; }\n\n/* Shadow */\n.orquesta-embed-panel .shadow-xl { box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important; }\n.orquesta-embed-panel .shadow-2xl { box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important; }\n.orquesta-embed-panel .shadow-lg { box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05) !important; }\n\n/* Position */\n.orquesta-embed-panel .fixed { position: fixed !important; }\n.orquesta-embed-panel .absolute { position: absolute !important; }\n.orquesta-embed-panel .relative { position: relative !important; }\n.orquesta-embed-panel .top-1 { top: 0.25rem !important; }\n.orquesta-embed-panel .right-1 { right: 0.25rem !important; }\n.orquesta-embed-panel .bottom-0 { bottom: 0 !important; }\n.orquesta-embed-panel .right-0 { right: 0 !important; }\n\n/* Z-index */\n.orquesta-embed-panel .z-\\[2147483647\\] { z-index: 2147483647 !important; }\n\n/* Cursor */\n.orquesta-embed-panel .cursor-move { cursor: move !important; }\n.orquesta-embed-panel .cursor-se-resize { cursor: se-resize !important; }\n.orquesta-embed-panel .cursor-not-allowed { cursor: not-allowed !important; }\n\n/* Select */\n.orquesta-embed-panel .select-none { user-select: none !important; }\n\n/* Disabled states */\n.orquesta-embed-panel .disabled\\:opacity-50:disabled { opacity: 0.5 !important; }\n.orquesta-embed-panel .disabled\\:cursor-not-allowed:disabled { cursor: not-allowed !important; }\n.orquesta-embed-panel .disabled\\:bg-blue-800:disabled { background-color: #1e40af !important; }\n.orquesta-embed-panel .disabled\\:bg-gray-300:disabled { background-color: #d1d5db !important; }\n\n/* Transition */\n.orquesta-embed-panel .transition-colors { transition-property: color, background-color, border-color !important; transition-duration: 150ms !important; }\n.orquesta-embed-panel .transition-all { transition-property: all !important; transition-duration: 150ms !important; }\n\n/* ============================================ */\n/* Action buttons & Comments - Timeline styles */\n/* ============================================ */\n\n/* Purple colors for \"Show on page\" button */\n.orquesta-embed-panel .text-purple-300 { color: #d8b4fe !important; }\n.orquesta-embed-panel .text-purple-400 { color: #c084fc !important; }\n.orquesta-embed-panel .bg-purple-600 { background-color: #9333ea !important; }\n.orquesta-embed-panel .bg-purple-600\\/20 { background-color: rgba(147, 51, 234, 0.2) !important; }\n.orquesta-embed-panel .bg-purple-600\\/30 { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .border-purple-500\\/40 { border-color: rgba(168, 85, 247, 0.4) !important; }\n.orquesta-embed-panel .border-purple-500\\/60 { border-color: rgba(168, 85, 247, 0.6) !important; }\n.orquesta-embed-panel .hover\\:bg-purple-600\\/30:hover { background-color: rgba(147, 51, 234, 0.3) !important; }\n.orquesta-embed-panel .hover\\:border-purple-500\\/60:hover { border-color: rgba(168, 85, 247, 0.6) !important; }\n\n/* Zinc with opacity for \"View output\" button */\n.orquesta-embed-panel .bg-zinc-700\\/50 { background-color: rgba(63, 63, 70, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600\\/50 { border-color: rgba(82, 82, 91, 0.5) !important; }\n.orquesta-embed-panel .border-zinc-600 { border-color: #52525b !important; }\n.orquesta-embed-panel .border-zinc-500 { border-color: #71717a !important; }\n.orquesta-embed-panel .hover\\:border-zinc-500:hover { border-color: #71717a !important; }\n\n/* Blue with opacity */\n.orquesta-embed-panel .bg-blue-500\\/20 { background-color: rgba(59, 130, 246, 0.2) !important; }\n.orquesta-embed-panel .border-blue-500\\/30 { border-color: rgba(59, 130, 246, 0.3) !important; }\n.orquesta-embed-panel .text-blue-300 { color: #93c5fd !important; }\n.orquesta-embed-panel .text-blue-300\\/70 { color: rgba(147, 197, 253, 0.7) !important; }\n\n/* Additional padding */\n.orquesta-embed-panel .py-1\\.5 { padding-top: 0.375rem !important; padding-bottom: 0.375rem !important; }\n.orquesta-embed-panel .py-0\\.5 { padding-top: 0.125rem !important; padding-bottom: 0.125rem !important; }\n.orquesta-embed-panel .px-1\\.5 { padding-left: 0.375rem !important; padding-right: 0.375rem !important; }\n.orquesta-embed-panel .px-2\\.5 { padding-left: 0.625rem !important; padding-right: 0.625rem !important; }\n.orquesta-embed-panel .pb-2 { padding-bottom: 0.5rem !important; }\n.orquesta-embed-panel .pb-3 { padding-bottom: 0.75rem !important; }\n.orquesta-embed-panel .pt-1 { padding-top: 0.25rem !important; }\n\n/* Space utilities */\n.orquesta-embed-panel .space-y-0\\.5 > * + * { margin-top: 0.125rem !important; }\n.orquesta-embed-panel .space-y-1 > * + * { margin-top: 0.25rem !important; }\n.orquesta-embed-panel .space-y-2 > * + * { margin-top: 0.5rem !important; }\n.orquesta-embed-panel .space-y-3 > * + * { margin-top: 0.75rem !important; }\n\n/* Focus states */\n.orquesta-embed-panel .focus\\:outline-none:focus { outline: none !important; }\n.orquesta-embed-panel .focus\\:ring-1:focus { box-shadow: 0 0 0 1px var(--orq-primary, #3b82f6) !important; }\n.orquesta-embed-panel .focus\\:ring-blue-500:focus { --tw-ring-color: #3b82f6 !important; }\n\n/* Placeholder colors */\n.orquesta-embed-panel .placeholder\\:text-zinc-500::placeholder { color: #71717a !important; }\n\n/* Text utilities */\n.orquesta-embed-panel .break-words { word-wrap: break-word !important; overflow-wrap: break-word !important; }\n.orquesta-embed-panel .italic { font-style: italic !important; }\n\n/* Negative margins */\n.orquesta-embed-panel .-mt-1 { margin-top: -0.25rem !important; }\n\n/* Max height */\n.orquesta-embed-panel .max-h-\\[400px\\] { max-height: 400px !important; }\n.orquesta-embed-panel .max-h-\\[150px\\] { max-height: 150px !important; }\n\n/* Font mono */\n.orquesta-embed-panel .font-mono { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }\n\n/* Text sizes */\n.orquesta-embed-panel .text-\\[10px\\] { font-size: 10px !important; line-height: 1.4 !important; }\n.orquesta-embed-panel .text-\\[11px\\] { font-size: 11px !important; line-height: 1.4 !important; }\n\n/* Flex wrap */\n.orquesta-embed-panel .flex-wrap { flex-wrap: wrap !important; }\n\n/* Min width */\n.orquesta-embed-panel .min-w-0 { min-width: 0 !important; }\n\n/* ml-auto for comment button alignment */\n.orquesta-embed-panel .ml-auto { margin-left: auto !important; }\n\n/* Hidden utility */\n.orquesta-embed-panel .hidden { display: none !important; }\n\n/* SVG icon sizing */\n.orquesta-embed-panel svg { flex-shrink: 0; }\n\n/* Mobile responsive */\n@media (max-width: 480px) {\n .orquesta-embed-panel {\n position: fixed !important;\n left: 8px !important;\n right: 8px !important;\n bottom: 8px !important;\n top: auto !important;\n width: auto !important;\n max-height: 70vh !important;\n }\n}\n\n/* Builder Mode */\n.orquesta-builder{display:flex;flex-direction:column;width:100%;height:100vh;background:#0a0a0a;color:#fafafa;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;overflow:hidden}\n.orquesta-builder-header{display:flex;align-items:center;justify-content:space-between;height:48px;padding:0 16px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-header-left{display:flex;align-items:center;gap:12px}\n.orquesta-builder-header-right{display:flex;align-items:center;gap:8px}\n.orquesta-builder-logo{font-weight:700;font-size:14px;color:#fafafa;letter-spacing:-0.02em}\n.orquesta-builder-project{font-size:13px;color:#a1a1aa}\n.orquesta-builder-status{display:flex;align-items:center;gap:6px;font-size:12px;color:#a1a1aa}\n.orquesta-builder-status-dot{width:8px;height:8px;border-radius:50%}\n.orquesta-builder-main{display:flex;flex:1;min-height:0}\n.orquesta-builder-chat{display:flex;flex-direction:column;width:380px;min-width:300px;max-width:50%;border-right:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px}\n.orquesta-builder-chat-input{padding:12px 16px;border-top:1px solid #27272a;background:#18181b}\n.orquesta-builder-chat-input textarea{width:100%;min-height:60px;max-height:200px;padding:10px 12px;background:#27272a;border:1px solid #3f3f46;border-radius:8px;color:#fafafa;font-size:13px;resize:vertical;outline:none;font-family:inherit}\n.orquesta-builder-chat-input textarea:focus{border-color:#3b82f6}\n.orquesta-builder-chat-input-actions{display:flex;justify-content:space-between;align-items:center;margin-top:8px}\n.orquesta-builder-preview{flex:1;display:flex;flex-direction:column;min-width:0}\n.orquesta-builder-preview-bar{display:flex;align-items:center;height:36px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;gap:8px;flex-shrink:0}\n.orquesta-builder-preview-url{flex:1;padding:4px 10px;background:#27272a;border:1px solid #3f3f46;border-radius:6px;color:#a1a1aa;font-size:12px;font-family:'SF Mono','Fira Code',monospace;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}\n.orquesta-builder-preview-iframe{flex:1;width:100%;border:none;background:#fff}\n.orquesta-builder-terminal{height:200px;min-height:100px;max-height:50vh;border-top:1px solid #27272a;background:#0a0a0a;display:flex;flex-direction:column;flex-shrink:0}\n.orquesta-builder-terminal-header{display:flex;align-items:center;justify-content:space-between;height:32px;padding:0 12px;background:#18181b;border-bottom:1px solid #27272a;flex-shrink:0}\n.orquesta-builder-terminal-title{font-size:12px;font-weight:600;color:#a1a1aa;text-transform:uppercase;letter-spacing:0.05em}\n.orquesta-builder-terminal-output{flex:1;overflow-y:auto;padding:8px 12px;font-family:'SF Mono','Fira Code','Cascadia Code',monospace;font-size:12px;line-height:1.5}\n.orquesta-builder-terminal.collapsed{height:32px;min-height:32px}\n.orquesta-builder-terminal.collapsed .orquesta-builder-terminal-output{display:none}\n.orquesta-builder-msg{max-width:90%;padding:10px 14px;border-radius:12px;font-size:13px;line-height:1.5;word-break:break-word}\n.orquesta-builder-msg-user{align-self:flex-end;background:#3b82f6;color:#fff;border-bottom-right-radius:4px}\n.orquesta-builder-msg-system{align-self:flex-start;background:#27272a;color:#fafafa;border-bottom-left-radius:4px}\n.orquesta-builder-msg-status{align-self:center;background:transparent;color:#71717a;font-size:12px;padding:4px 0}\n.orquesta-builder-resizer-h{width:4px;cursor:col-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-h:hover{background:#3b82f6}\n.orquesta-builder-resizer-v{height:4px;cursor:row-resize;background:transparent;flex-shrink:0}\n.orquesta-builder-resizer-v:hover{background:#3b82f6}\n.orquesta-builder button{background:transparent;border:none;color:#a1a1aa;cursor:pointer;padding:4px 8px;border-radius:4px;font-size:12px}\n.orquesta-builder button:hover{background:#27272a;color:#fafafa}\n.orquesta-builder-btn-primary{background:#3b82f6!important;color:#fff!important;font-weight:500;padding:6px 16px!important;border-radius:6px!important}\n.orquesta-builder-btn-primary:hover{background:#2563eb!important}\n.orquesta-builder-btn-primary:disabled{opacity:0.5;cursor:not-allowed}\n@media(max-width:768px){.orquesta-builder-main{flex-direction:column}.orquesta-builder-chat{width:100%;max-width:100%;height:50%;border-right:none;border-bottom:1px solid #27272a}.orquesta-builder-resizer-h{display:none}}\n",document.head.appendChild(t),Ue=!0}()},[]),l(()=>{"completed"!==g?.currentPrompt?.status&&"failed"!==g?.currentPrompt?.status||_(g.currentPrompt)},[g?.currentPrompt?.status,g?.currentPrompt]);const A=a(void 0);l(()=>{if(h&&g&&!g.isSubmitting&&g.promptQueue&&g.promptQueue.length>0){const e=setTimeout(()=>{const[e,...t]=g.promptQueue;e&&(console.log("[Orquesta Embed Demo] Processing queued prompt"),f(e=>e?{...e,promptQueue:t}:null),A.current?.())},300);return()=>clearTimeout(e)}},[h,g?.isSubmitting,g?.promptQueue?.length]),l(()=>{if(h)return L.current=new je,s&&L.current&&(z.current=L.current.setupGlobalRightClickWithPosition((e,t)=>{L.current&&L.current.highlightSelectedElement(e.selector),k({isOpen:!0,position:t,element:e})})),()=>{z.current&&(z.current(),z.current=null)}},[h,s]),l(()=>{if(h)return;const e=new Fe(p);m(e);const t=e.subscribe(e=>{f(e)});return e.connect().catch(e=>{w(e.message)}),s&&(z.current=e.setupGlobalRightClickWithPosition((t,n)=>{e.getElementSelector().deactivate(),e.getElementSelector().highlightSelectedElement(t.selector),k({isOpen:!0,position:n,element:t})})),()=>{t(),z.current&&(z.current(),z.current=null),e.disconnect()}},[p.token,s,h]);const O=c(()=>{h?f(e=>e?{...e,isOpen:!1}:null):u?.close()},[u,h]),T=c(()=>{x(!0)},[]),R=c(()=>{x(!1),h?f(e=>e?{...e,isOpen:!0}:null):u?.open()},[u,h]),H=c(async(e,t)=>{if(h){const n=t||g?.selectedElement||void 0;if(g?.isSubmitting)return f(t=>t?{...t,promptQueue:[...t.promptQueue||[],{id:`queue-${Date.now()}`,content:e,options:{elementContext:n},queuedAt:Date.now()}]}:null),void console.log("[Orquesta Embed Demo] Prompt queued");const o={id:`demo-prompt-${Date.now()}`,content:e,status:"running",created_at:(new Date).toISOString(),user_id:"demo-user",source:"embed",element_context:n,author:{id:"demo-user",full_name:"Demo User",avatar_url:null},comment_count:0};f(e=>e?{...e,isSubmitting:!0,currentPrompt:o,outputLines:[],promptHistory:[o,...e.promptHistory]}:null);const r=e.toLowerCase();let i="Tool: Edit file",s="Changes applied successfully.";r.includes("button")||r.includes("color")||r.includes("green")?(i="Tool: Edit src/components/Button.tsx",s="Button styles updated."):r.includes("banner")||r.includes("sale")?(i="Tool: Create src/components/Banner.tsx",s="Banner component created and mounted."):r.includes("discount")||r.includes("price")?(i="Tool: Edit src/components/ProductCard.tsx",s="Discount pricing applied to products."):r.includes("headline")||r.includes("bigger")||r.includes("title")?(i="Tool: Edit src/app/page.tsx",s="Headline styles updated."):r.includes("dark")&&(i="Tool: Edit src/styles/globals.css",s="Dark mode theme applied.");return[{delay:200,type:"system",content:"Starting Claude CLI session..."},{delay:600,type:"thinking",content:"Analyzing the request..."},{delay:1e3,type:"stdout",content:`Processing: "${e.slice(0,50)}${e.length>50?"...":""}"`},{delay:1400,type:"tool",content:i},{delay:1800,type:"stdout",content:s}].forEach(({delay:e,type:t,content:n})=>{setTimeout(()=>{f(e=>e?{...e,outputLines:[...e.outputLines,{id:`output-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,timestamp:Date.now(),type:t,content:n}]}:null)},e)}),void setTimeout(()=>{f(e=>{if(!e)return null;const t={...o,status:"completed",completed_at:(new Date).toISOString(),git_branch:"main",git_commit_sha:Math.random().toString(36).slice(2,9)},n=[...e.outputLines,{id:`output-${Date.now()}-complete`,timestamp:Date.now(),type:"system",content:"Prompt completed successfully."}];return{...e,isSubmitting:!1,currentPrompt:t,selectedElement:null,outputLines:n,promptOutputs:{...e.promptOutputs,[o.id]:n},promptHistory:e.promptHistory.map(e=>e.id===o.id?t:e)}}),p.onDemoComplete&&p.onDemoComplete(e)},2200)}if(u)try{await u.submitPrompt(e,{elementContext:t||void 0})}catch(e){console.error("Failed to submit prompt:",e)}},[u,h,g?.selectedElement,g?.isSubmitting]);l(()=>{h&&g?.promptQueue&&g.promptQueue.length>0&&(A.current=()=>{const e=g.promptQueue[0];e&&H(e.content,e.options?.elementContext)})},[h,g?.promptQueue,H]);const M=c(()=>{h?(f(e=>e?{...e,isSelectingElement:!0}:null),L.current?.activate(e=>{f(t=>t?{...t,selectedElement:e,isSelectingElement:!1}:null)},()=>{f(e=>e?{...e,isSelectingElement:!1}:null)})):u?.startElementSelection()},[u,h]),P=c(()=>{h?(f(e=>e?{...e,selectedElement:null}:null),L.current?.deactivate(),L.current?.removeSelectedHighlight()):u&&(f(e=>e?{...e,selectedElement:null}:null),u.getElementSelector().deactivate(),u.getElementSelector().removeSelectedHighlight())},[u,h]),j=c(()=>{g&&f(e=>e?{...e,includeConsole:!e.includeConsole}:null)},[g]),B=c(()=>{g&&f(e=>e?{...e,includeNetwork:!e.includeNetwork}:null)},[g]),I=c(()=>{g&&f(e=>e?{...e,includeHistory:!e.includeHistory}:null)},[g]),$=c(e=>{g&&(f(t=>t?{...t,activeTab:e}:null),We.set("activeTab",e),u?.setActiveTab(e))},[g,u]),D=c(()=>{f(e=>{if(!e)return null;const t=!e.rightClickEnabled;return t?h&&L.current?z.current=L.current.setupGlobalRightClickWithPosition((e,t)=>{L.current?.highlightSelectedElement(e.selector),k({isOpen:!0,position:t,element:e})}):u&&(z.current=u.setupGlobalRightClickWithPosition((e,t)=>{u.getElementSelector().deactivate(),u.getElementSelector().highlightSelectedElement(e.selector),k({isOpen:!0,position:t,element:e})})):z.current&&(z.current(),z.current=null),{...e,rightClickEnabled:t}})},[h,u]),W=c(()=>{h?(L.current?.deactivate(),f(e=>e?{...e,isSelectingElement:!1}:null)):u?.getElementSelector().deactivate()},[u,h]),F=c(e=>{g&&f(t=>t?{...t,expandedPromptId:e}:null)},[g]),U=c(e=>{if(e.element_context?.selector)if(h){const t=L.current?.highlightElement(e.element_context.selector);t?f(t=>t?{...t,overlayMode:"single",highlightedPromptId:e.id}:null):(console.warn("[Orquesta Embed] Element not found for selector:",e.element_context.selector),f(e=>e?{...e,outputLines:[...e.outputLines,{id:`warn-${Date.now()}`,timestamp:Date.now(),type:"system",content:"⚠️ Element not found on page. The element may have been removed or changed since this prompt was created."}]}:null))}else{const t=e.element_context.selector;let n=null;try{n=document.querySelector(t)}catch{console.warn("[Orquesta Embed] Invalid selector syntax:",t)}n?u?.highlightPromptElement(e):(console.warn("[Orquesta Embed] Element not found for selector:",t),f(e=>e?{...e,outputLines:[...e.outputLines,{id:`warn-${Date.now()}`,timestamp:Date.now(),type:"system",content:"⚠️ Element not found on page. The element may have been removed or changed since this prompt was created."}]}:null))}else console.warn("[Orquesta Embed] Prompt has no element context")},[u,h]),V=c(async e=>{h||u&&await u.loadComments(e)},[u,h]),Q=c(async(e,t)=>{if(h){const n={id:`comment-${Date.now()}`,content:t,created_at:(new Date).toISOString(),author:{id:"demo-user",full_name:"Demo User",avatar_url:null}};return void f(t=>{if(!t)return null;const o=t.comments[e]||[];return{...t,comments:{...t.comments,[e]:[...o,n]},promptHistory:t.promptHistory.map(t=>t.id===e?{...t,comment_count:(t.comment_count||0)+1}:t)}})}u&&await u.addComment(e,t)},[u,h]),K=c(e=>{h?f(t=>{if(!t)return null;let n=t.elementMarkers;return"all"===e?n=t.promptHistory.filter(e=>e.element_context?.selector).map(e=>{let t=null;try{t=document.querySelector(e.element_context.selector)}catch{}return{promptId:e.id,selector:e.element_context.selector,rect:t?.getBoundingClientRect()||null,content:e.content,author:e.author||null,gitCommitSha:e.git_commit_sha||null,commentCount:e.comment_count||0}}):"off"===e&&(L.current?.removeHighlight(),n=[]),{...t,overlayMode:e,highlightedPromptId:"off"===e?null:t.highlightedPromptId,elementMarkers:n}}):u?.setOverlayMode(e)},[u,h]),X=c(e=>{g&&f(t=>t?{...t,activeTab:"timeline",expandedPromptId:e}:null)},[g]),Y=c(()=>{k(e=>({...e,isOpen:!1})),h&&L.current?L.current.removeSelectedHighlight():u&&u.getElementSelector().removeSelectedHighlight()},[u,h]),J=c(async e=>{v.element&&(f(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),x(!1),await H(e,v.element||void 0),k(e=>({...e,isOpen:!1})))},[v.element,H]),G=c(()=>{v.element&&(f(e=>e?{...e,selectedElement:v.element,isOpen:!0,activeTab:"prompts"}:null),x(!1),k(e=>({...e,isOpen:!1})))},[v.element]),Z=c(async()=>{if(h){const e={id:"demo-user-id",full_name:"Demo User",avatar_url:null};return f(t=>t?{...t,isAuthenticated:!0,user:e,authError:null}:null),void p.onLogin?.(e)}if(u)try{await u.login()}catch(e){console.error("Login failed:",e)}},[u,h,p]),ee=c(async()=>{if(h)return f(e=>e?{...e,isAuthenticated:!1,user:null}:null),void p.onLogout?.();if(u)try{await u.logout()}catch(e){console.error("Logout failed:",e)}},[u,h,p]);if(y){const{title:n,message:o,hint:r}=(te=y).includes("401")||te.includes("Invalid token")||te.includes("Unauthorized")?{title:"Authentication Failed",message:"The embed token is invalid or has expired.",hint:"Generate a new token from the Orquesta dashboard → Project Settings → Embed"}:te.includes("403")||te.includes("Domain not allowed")?{title:"Domain Not Allowed",message:"This domain is not authorized to use this embed token.",hint:"Add this domain to the allowed domains in Project Settings → Embed"}:te.includes("404")||te.includes("Project not found")?{title:"Project Not Found",message:"The project associated with this token no longer exists.",hint:"Check if the project was deleted or create a new embed token"}:te.includes("network")||te.includes("Failed to fetch")?{title:"Connection Failed",message:"Unable to connect to Orquesta servers.",hint:"Check your internet connection and try again"}:{title:"Connection Error",message:te,hint:"Please check your configuration and try again"};return e("div",{className:"orquesta-embed-error fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl overflow-hidden",style:{[p.position?.includes("right")?"right":"left"]:"20px",[p.position?.includes("top")?"top":"bottom"]:"20px",width:"360px"},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"})]}),t("div",{className:"flex items-center gap-1",children:t("span",{className:"w-2 h-2 rounded-full bg-red-500",title:"Disconnected"})})]}),e("div",{className:"p-4",children:[e("div",{className:"flex items-start gap-3",children:[t("div",{className:"w-10 h-10 rounded-full bg-red-500/20 flex items-center justify-center flex-shrink-0",children:t("svg",{className:"w-5 h-5 text-red-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}),e("div",{className:"flex-1",children:[t("h3",{className:"text-white font-semibold text-sm",children:n}),t("p",{className:"text-zinc-400 text-xs mt-1",children:o}),e("p",{className:"text-zinc-500 text-xs mt-2 flex items-center gap-1",children:[t("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),r]})]})]}),e("button",{onClick:()=>{w(null),u?.connect().catch(e=>w(e.message))},className:"mt-4 w-full px-3 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-300 text-xs font-medium rounded-lg transition-colors flex items-center justify-center gap-2",children:[t("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:t("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Retry Connection"]})]})]})}var te;return!g||g.isConnecting?e("div",{className:"orquesta-embed-loading fixed z-[2147483647] bg-zinc-900 border border-zinc-700 rounded-lg shadow-2xl overflow-hidden",style:{[p.position?.includes("right")?"right":"left"]:"20px",[p.position?.includes("top")?"top":"bottom"]:"20px",width:"320px"},children:[e("div",{className:"flex items-center justify-between px-3 py-2 bg-zinc-800 border-b border-zinc-700",children:[e("div",{className:"flex items-center gap-2",children:[t("span",{className:"text-lg",children:"⬡"}),t("span",{className:"font-semibold text-white text-sm",children:"Orquesta"})]}),t("div",{className:"flex items-center gap-1",children:t("span",{className:"w-2 h-2 rounded-full bg-yellow-500 animate-pulse",title:"Connecting..."})})]}),e("div",{className:"p-6 flex flex-col items-center",children:[e("svg",{className:"animate-spin h-8 w-8 text-zinc-400 mb-3",viewBox:"0 0 24 24",children:[t("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),t("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),t("span",{className:"text-zinc-300 text-sm",children:"Connecting to Orquesta..."}),t("span",{className:"text-zinc-500 text-xs mt-1",children:"Validating token and establishing connection"})]})]}):e(n,{children:[S&&t(yt,{isConnected:g.isConnected,agentOnline:g.agentOnline,projectName:g.projectName,currentPrompt:g.currentPrompt,isSubmitting:g.isSubmitting,lastCompletedPrompt:E,onClose:()=>q(!1)}),"widget"===C&&(b||!g.isOpen)&&e("button",{onClick:R,className:"orquesta-embed-trigger fixed z-[2147483647] p-3 bg-zinc-900 border border-zinc-700 rounded-full shadow-xl hover:bg-zinc-800 transition-colors",style:{[p.position?.includes("right")?"right":"left"]:"20px",[p.position?.includes("top")?"top":"bottom"]:"20px"},title:"Open Orquesta",children:[t("span",{className:"text-xl",children:"⬡"}),g.agentOnline&&t("span",{className:"absolute top-1 right-1 w-2 h-2 bg-green-500 rounded-full"})]}),"builder"===C&&t(gt,{state:g,onSubmitPrompt:H,onSwitchToWidget:()=>{N("widget"),x(!1),h?f(e=>e?{...e,isOpen:!0}:null):u?.open()},onSelectElement:M,onClearElement:P,onToggleConsole:j,onToggleNetwork:B,onToggleHistory:I,onTabChange:$,onExpandPrompt:F,onHighlightElement:U,onLoadComments:V,onAddComment:Q,onOverlayModeChange:K,onLogin:Z,onLogout:ee,onToggleRightClick:D,demoMode:h}),"widget"===C&&g.isOpen&&!b&&t(mt,{state:g,position:p.position||"bottom-right",onClose:O,onMinimize:T,onSubmitPrompt:H,onSelectElement:M,onClearElement:P,onToggleConsole:j,onToggleNetwork:B,onToggleHistory:I,onTabChange:$,onExpandPrompt:F,onHighlightElement:U,onLoadComments:V,onAddComment:Q,onOverlayModeChange:K,onLogin:Z,onLogout:ee,onToggleRightClick:D,onExpandToBuilder:()=>N("builder"),demoMode:h}),t(ft,{isActive:g.isSelectingElement,onCancel:W}),"all"===g.overlayMode&&g.elementMarkers.length>0&&t(bt,{markers:g.elementMarkers,onMarkerClick:X}),t(xt,{isOpen:v.isOpen,position:v.position,element:v.element,agentOnline:g.agentOnline,includeConsole:g.includeConsole,includeNetwork:g.includeNetwork,onSubmit:J,onClose:Y,onToggleConsole:j,onToggleNetwork:B,onOpenPanel:G}),r]})}export{Be as AuthManager,st as AuthorAvatar,Xe as Badge,gt as BuilderPanel,Ve as Button,dt as CommentInput,ct as CommentList,Me as ConsoleCapture,d as EMBED_VERSION,ft as ElementInspector,bt as ElementMarkers,je as ElementSelector,mt as EmbedPanel,at as GitCommitLink,Qe as Input,it as LogStream,Pe as NetworkCapture,Ct as OrquestaEmbed,Fe as OrquestaEmbedClient,rt as PromptInput,He as StateManager,Ye as StatusDot,Ze as Tabs,nt as TabsContent,et as TabsList,tt as TabsTrigger,Ke as Textarea,ht as Timeline,We as storage};
|