palmier 0.9.3 → 0.9.4
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/commands/run.js +6 -0
- package/dist/commands/serve.js +61 -36
- package/dist/pwa/assets/{index-CknFGshO.js → index-DX5qJgHZ.js} +4 -4
- package/dist/pwa/assets/{web-DdzXb-jW.js → web-Dcldtodb.js} +1 -1
- package/dist/pwa/assets/{web-Dl9aC-Qr.js → web-DdVpqhvX.js} +1 -1
- package/dist/pwa/assets/{web-a9jK1xeo.js → web-Eg0A6HEi.js} +1 -1
- package/dist/pwa/index.html +2 -2
- package/dist/pwa/manifest.webmanifest +1 -1
- package/dist/pwa/service-worker.js +1 -1
- package/dist/rpc-handler.js +41 -19
- package/dist/task.d.ts +7 -0
- package/dist/task.js +17 -0
- package/dist/types.d.ts +4 -0
- package/package.json +1 -1
- package/palmier-server/pwa/index.html +1 -1
- package/palmier-server/pwa/src/components/RunDetailView.tsx +1 -1
- package/palmier-server/pwa/src/components/TaskForm.tsx +5 -3
- package/palmier-server/pwa/vite.config.ts +1 -1
- package/src/commands/run.ts +3 -0
- package/src/commands/serve.ts +62 -37
- package/src/rpc-handler.ts +34 -18
- package/src/task.ts +21 -0
- package/src/types.ts +4 -0
|
@@ -84,10 +84,10 @@ ${d}`),g(S);return}f(null,T),s.strategy===yr.Count&&(m--,m===0&&g()),s.strategy=
|
|
|
84
84
|
|
|
85
85
|
${f.stack}`),d.unsubscribe(),c.reject(m)):(m=hx(y),m?(f&&(m.stack+=`
|
|
86
86
|
|
|
87
|
-
${f.stack}`),c.reject(m)):c.resolve(y))}});return d.requestSubject=t,this.protocol.publish(t,r,{reply:u,headers:s.headers}),c}else{const u=new px(this.protocol.muxSubscriptions,t,s,l);this.protocol.request(u);try{this.publish(t,r,{reply:`${this.protocol.muxSubscriptions.baseInbox}${u.token}`,headers:s.headers})}catch(f){u.cancel(f)}const c=Promise.race([u.timer,u.deferred]);return c.catch(()=>{u.cancel()}),c}}flush(){return this.isClosed()?Promise.reject(Oe.errorForCode(Se.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Oe.errorForCode(Se.ConnectionClosed)):this.isDraining()?Promise.reject(Oe.errorForCode(Se.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const t=this.protocol.getServer();return t?t.listen:""}status(){const t=new an;return t.iterClosed.then(()=>{const r=this.listeners.indexOf(t);this.listeners.splice(r,1)}),this.listeners.push(t),t}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((r,s)=>r==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(t={}){const r=new Dk(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===Se.NoResponders&&(l.code=Se.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Pd(this,t)}getServerVersion(){const t=this.info;return t?ms(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Oe.errorForCode(Se.Disconnect);const t=Date.now();return await this.flush(),Date.now()-t}get features(){return this.protocol.features}get services(){return this._services||(this._services=new Bk(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Oe.errorForCode(Se.ConnectionClosed)):this.isDraining()?Promise.reject(Oe.errorForCode(Se.ConnectionDraining)):this.protocol.reconnect()}}class Bk{constructor(t){C(this,"nc");this.nc=t}add(t){try{return new Yl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new yk(this.nc,t,r)}}class Pk{constructor(t,r,s){C(this,"bucket");C(this,"sm");C(this,"prefixLen");this.bucket=t,this.prefixLen=r,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(zu)||"PUT"}get length(){const t=this.sm.header.get(Sn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class qk{constructor(t,r,s){C(this,"bucket");C(this,"key");C(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Dd(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(zu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(Sn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class jx extends y2{constructor(r,s,l){super(r.nc,s,l);C(this,"js");C(this,"monitor");this.js=r,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(r){this.sub.info=r}get info(){return this.sub.info}_resetOrderedConsumer(r){if(this.info===null||this.sub.isClosed())return;const s=ei(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const u=this.info;u.config.name=Ui.next(),u.ordered_consumer_sequence.delivery_seq=0,u.flow_control.heartbeat_count=0,u.flow_control.fc_count=0,u.flow_control.consumer_restarts++,u.deliver=s,u.config.deliver_subject=s,u.config.deliver_policy=Vt.StartSequence,u.config.opt_start_seq=r;const c={};c.stream_name=this.info.stream,c.config=u.config;const f=`${u.api.prefix}.CONSUMER.CREATE.${u.stream}`;this.js._request(f,c,{retries:-1}).then(d=>{const m=d,y=this.sub.info;y.last=m,this.info.config=m.config,this.info.name=m.name}).catch(d=>{const m=new Oe(`unable to recreate ordered consumer ${u.stream} at seq ${r}`,Se.RequestError,d);this.sub.callback(m,{})})}_maybeSetupHbMonitoring(){var s,l;const r=((l=(s=this.info)==null?void 0:s.config)==null?void 0:l.idle_heartbeat)||0;r&&this._setupHbMonitoring(Dd(r))}_setupHbMonitoring(r,s=0){const l={cancelAfter:0,maxOut:2};s&&(l.cancelAfter=s);const u=this.sub,c=f=>{var y,g,x,w;const d=Q_(409,`${ar.IdleHeartbeatMissed}: ${f}`,this.sub.subject);if(!((y=this.info)==null?void 0:y.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const S=((x=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(S+1),(w=this.monitor)==null||w.restart(),!1}return!u.noIterator};this.monitor=new zd(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(Sn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(Sn.LastConsumerSeqHdr),10),u=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,l!==u.delivery_seq&&this._resetOrderedConsumer(u.stream_seq+1),!1}_checkOrderedConsumer(r){const s=this.info.ordered_consumer_sequence,l=r.info.streamSequence,u=r.info.deliverySequence;return u!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=u,s.stream_seq=l,!0)}async destroy(){this.isClosed()||await this.drain();const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.DELETE.${r.stream}.${s}`;await r.api._request(l)}async consumerInfo(){const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.INFO.${r.stream}.${s}`,u=await r.api._request(l);return r.last=u,u}}class Hk extends jx{constructor(t,r,s){super(t,r,s)}pull(t={batch:1}){const{stream:r,config:s,name:l}=this.sub.info,u=s.durable_name??l,c={};if(c.batch=t.batch||1,c.no_wait=t.no_wait||!1,(t.max_bytes??0)>0){const m=this.js.nc.features.get(ut.JS_PULL_MAX_BYTES);if(!m.ok)throw new Error(`max_bytes is only supported on servers ${m.min} or better`);c.max_bytes=t.max_bytes}let f=0;t.expires&&t.expires>0&&(f=t.expires,c.expires=zt(f));let d=0;if(t.idle_heartbeat&&t.idle_heartbeat>0&&(d=t.idle_heartbeat,c.idle_heartbeat=zt(d)),d&&f===0)throw new Error("idle_heartbeat requires expires");if(d>f)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),f&&d&&(this.monitor?this.monitor._change(d,f):this._setupHbMonitoring(d,f));const m=this.info.api,y=`${m.prefix}.CONSUMER.MSG.NEXT.${r}.${u}`,g=this.sub.subject;m.nc.publish(y,m.jc.encode(c),{reply:g})}}}function Ik(e,t){return e?$k(t):Fk(t)}function Fk(e){return(t,r)=>t?[t,null]:(t=ua(r),t?[t,null]:[null,Pl(r,e)])}function $k(e){return(t,r)=>{if(t)return[t,null];const s=ua(r);return s!==null?[Tx(s),null]:[null,Pl(r,e)]}}function Tx(e){if(e!==null)switch(e.code){case Se.JetStream404NoMessages:case Se.JetStream408RequestTimeout:return null;case Se.JetStream409:return Z_(e)?e:null;default:return e}return null}function Yk(e){e&&e.ack()}function Gk(e){const t=e.split(".");if(t.length===9&&t.splice(2,0,"_",""),t.length<11||t[0]!=="$JS"||t[1]!=="ACK")throw new Error("not js message");const r={};return r.domain=t[2]==="_"?"":t[2],r.account_hash=t[3],r.stream=t[4],r.consumer=t[5],r.deliveryCount=parseInt(t[6],10),r.redeliveryCount=r.deliveryCount,r.redelivered=r.deliveryCount>1,r.streamSequence=parseInt(t[7],10),r.deliverySequence=parseInt(t[8],10),r.timestampNanos=parseInt(t[9],10),r.pending=parseInt(t[10],10),r}class Vk{constructor(t,r){C(this,"msg");C(this,"di");C(this,"didAck");C(this,"timeout");this.msg=t,this.didAck=!1,this.timeout=r}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=Gk(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(t){this.didAck||(this.didAck=!this.isWIP(t),this.msg.respond(t))}isWIP(t){return t.length===4&&t[0]===xl[0]&&t[1]===xl[1]&&t[2]===xl[2]&&t[3]===xl[3]}async ackAck(t){var s;t=t||{},t.timeout=t.timeout||this.timeout;const r=Ut();if(this.didAck)r.resolve(!1);else if(this.didAck=!0,this.msg.reply){const u=this.msg.publisher,c=!((s=u.options)!=null&&s.noAsyncTraces),f=new px(u.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);u.request(f);try{u.publish(this.msg.reply,M0,{reply:`${u.muxSubscriptions.baseInbox}${f.token}`})}catch(d){f.cancel(d)}try{await Promise.race([f.timer,f.deferred]),r.resolve(!0)}catch(d){f.cancel(d),r.reject(d)}}else r.resolve(!1);return r}ack(){this.doAck(M0)}nak(t){let r=Ak;t&&(r=Nu().encode(`-NAK ${JSON.stringify({delay:zt(t)})}`)),this.doAck(r)}working(){this.doAck(xl)}next(t,r={batch:1}){const s={};s.batch=r.batch||1,s.no_wait=r.no_wait||!1,r.expires&&r.expires>0&&(s.expires=zt(r.expires));const l=br().encode(s),u=ga.concat(jk,Nk,l),c=t?{reply:t}:void 0;this.msg.respond(u,c)}term(t=""){let r=Tk;(t==null?void 0:t.length)>0&&(r=Nu().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const Jk="1.30.3",Xk="nats.ws";class Kk{constructor(){C(this,"version");C(this,"lang");C(this,"closeError");C(this,"connected");C(this,"done");C(this,"socket");C(this,"options");C(this,"socketClosed");C(this,"encrypted");C(this,"peeked");C(this,"yields");C(this,"signal");C(this,"closedNotification");this.version=Jk,this.lang=Xk,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=Ut(),this.closedNotification=Ut()}async connect(t,r){const s=Ut();if(r.tls)return s.reject(new Oe("tls",Se.InvalidOption)),s;this.options=r;const l=t.src;if(r.wsFactory){const{socket:u,encrypted:c}=await r.wsFactory(t.src,r);this.socket=u,this.encrypted=c}else this.encrypted=l.indexOf("wss://")===0,this.socket=new WebSocket(l);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=u=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(u.data)),this.peeked){this.signal.resolve();return}const c=ga.concat(...this.yields),f=_2(c);if(f!==""){const d=uk.exec(f);if(!d){r.debug&&console.error("!!!",cu(c)),s.reject(new Error("unexpected response from server"));return}try{const m=JSON.parse(d[1]);lk(m,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(m){s.reject(m);return}}},this.socket.onclose=u=>{if(this.isDiscarded())return;this.socketClosed=!0;let c;this.done||(u.wasClean||(c=new Error(u.reason)),this._closed(c))},this.socket.onerror=u=>{if(this.isDiscarded())return;const c=u,f=new Oe(c.message,Se.Unknown,new Error(c.error));s.reject(f)},s}disconnect(){this._closed(void 0,!0)}async _closed(t,r=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=t,!t)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await Sa(100);this.done=!0;try{this.socket.close(t?1002:1e3,t?t.message:void 0)}catch{}r&&this.closedNotification.resolve(t)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const t=this.yields;this.yields=[];for(let r=0;r<t.length;r++)this.options.debug&&console.info(`> ${cu(t[r])}`),yield t[r];if(this.done)break;this.yields.length===0&&(t.length=0,this.yields=t,this.signal=Ut())}}isEncrypted(){return this.connected&&this.encrypted}send(t){if(!this.isDiscarded())try{this.socket.send(t.buffer),this.options.debug&&console.info(`< ${cu(t)}`);return}catch(r){this.options.debug&&console.error(`!!! ${cu(t)}: ${r}`)}}close(t){return this._closed(t,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var t;this.done=!0;try{(t=this.socket)==null||t.close()}catch{}}}function Qk(e,t){/^(.*:\/\/)(.*)/.test(e)||(typeof t=="boolean"?e=`${t===!0?"https":"http"}://${e}`:e=`https://${e}`);let s=new URL(e);const l=s.protocol.toLowerCase();l==="ws:"&&(t=!1),l==="wss:"&&(t=!0),l!=="https:"&&l!=="http"&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${e}`));let u,c;const f=s.hostname,d=s.pathname,m=s.search||"";switch(l){case"http:":case"ws:":case"nats:":c=s.port||"80",u="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",u="wss:";break;default:c=s.port||t===!0?"443":"80",u=t===!0?"wss:":"ws:";break}return`${u}//${f}:${c}${d}${m}`}function Nx(e={}){return b2({defaultPort:443,urlParseFn:Qk,factory:()=>new Kk}),qd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var ya;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(ya||(ya={}));class jh extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const Zk=e=>{var t,r;return e!=null&&e.androidBridge?"android":!((r=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||r===void 0)&&r.bridge?"ios":"web"},Wk=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:Zk(e),u=()=>l()!=="web",c=g=>{const x=m.get(g);return!!(x!=null&&x.platforms.has(l())||f(g))},f=g=>{var x;return(x=r.PluginHeaders)===null||x===void 0?void 0:x.find(w=>w.name===g)},d=g=>e.console.error(g),m=new Map,y=(g,x={})=>{const w=m.get(g);if(w)return console.warn(`Capacitor plugin "${g}" already registered. Cannot register plugins twice.`),w.proxy;const S=l(),T=f(g);let L;const M=async()=>(!L&&S in x?L=typeof x[S]=="function"?L=await x[S]():L=x[S]:t!==null&&!L&&"web"in x&&(L=typeof x.web=="function"?L=await x.web():L=x.web),L),P=($,q)=>{var R,V;if(T){const X=T==null?void 0:T.methods.find(le=>q===le.name);if(X)return X.rtype==="promise"?le=>r.nativePromise(g,q.toString(),le):(le,ee)=>r.nativeCallback(g,q.toString(),le,ee);if($)return(R=$[q])===null||R===void 0?void 0:R.bind($)}else{if($)return(V=$[q])===null||V===void 0?void 0:V.bind($);throw new jh(`"${g}" plugin is not implemented on ${S}`,ya.Unimplemented)}},F=$=>{let q;const R=(...V)=>{const X=M().then(le=>{const ee=P(le,$);if(ee){const Y=ee(...V);return q=Y==null?void 0:Y.remove,Y}else throw new jh(`"${g}.${$}()" is not implemented on ${S}`,ya.Unimplemented)});return $==="addListener"&&(X.remove=async()=>q()),X};return R.toString=()=>`${$.toString()}() { [capacitor code] }`,Object.defineProperty(R,"name",{value:$,writable:!1,configurable:!1}),R},ce=F("addListener"),U=F("removeListener"),D=($,q)=>{const R=ce({eventName:$},q),V=async()=>{const le=await R;U({eventName:$,callbackId:le},q)},X=new Promise(le=>R.then(()=>le({remove:V})));return X.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await V()},X},te=new Proxy({},{get($,q){switch(q){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return T?D:ce;case"removeListener":return U;default:return F(q)}}});return s[g]=te,m.set(g,{name:g,proxy:te,platforms:new Set([...Object.keys(x),...T?[S]:[]])}),te};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=u,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=jh,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},eE=e=>e.Capacitor=Wk(e),Vn=eE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ys=Vn.registerPlugin;class Hd{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,r){let s=!1;this.listeners[t]||(this.listeners[t]=[],s=!0),this.listeners[t].push(r);const u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),s&&this.sendRetainedArgumentsForEvent(t);const c=async()=>this.removeListener(t,r);return Promise.resolve({remove:c})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,r,s){const l=this.listeners[t];if(!l){if(s){let u=this.retainedEventArguments[t];u||(u=[]),u.push(r),this.retainedEventArguments[t]=u}return}l.forEach(u=>u(r))}hasListeners(t){var r;return!!(!((r=this.listeners[t])===null||r===void 0)&&r.length)}registerWindowListener(t,r){this.windowListeners[r]={registered:!1,windowEventName:t,pluginEventName:r,handler:s=>{this.notifyListeners(r,s)}}}unimplemented(t="not implemented"){return new Vn.Exception(t,ya.Unimplemented)}unavailable(t="not available"){return new Vn.Exception(t,ya.Unavailable)}async removeListener(t,r){const s=this.listeners[t];if(!s)return;const l=s.indexOf(r);this.listeners[t].splice(l,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const r=this.retainedEventArguments[t];r&&(delete this.retainedEventArguments[t],r.forEach(s=>{this.notifyListeners(t,s)}))}}const L0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),z0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class tE extends Hd{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[l,u]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");l=z0(l).trim(),u=z0(u).trim(),r[l]=u}),r}async setCookie(t){try{const r=L0(t.key),s=L0(t.value),l=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${s||""}${l}; path=${u}; ${c};`}catch(r){return Promise.reject(r)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(r){return Promise.reject(r)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const r of t)document.cookie=r.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}ys("CapacitorCookies",{web:()=>new tE});const nE=async e=>new Promise((t,r)=>{const s=new FileReader;s.onload=()=>{const l=s.result;t(l.indexOf(",")>=0?l.split(",")[1]:l)},s.onerror=l=>r(l),s.readAsDataURL(e)}),rE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,u,c)=>(l[u]=e[t[c]],l),{})},iE=(e,t=!0)=>e?Object.entries(e).reduce((s,l)=>{const[u,c]=l;let f,d;return Array.isArray(c)?(d="",c.forEach(m=>{f=t?encodeURIComponent(m):m,d+=`${u}=${f}&`}),d.slice(0,-1)):(f=t?encodeURIComponent(c):c,d=`${u}=${f}`),`${s}&${d}`},"").substr(1):null,sE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=rE(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(l.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[c,f]of Object.entries(e.data||{}))u.set(c,f);r.body=u.toString()}else if(l.includes("multipart/form-data")||e.data instanceof FormData){const u=new FormData;if(e.data instanceof FormData)e.data.forEach((f,d)=>{u.append(d,f)});else for(const f of Object.keys(e.data))u.append(f,e.data[f]);r.body=u;const c=new Headers(r.headers);c.delete("content-type"),r.headers=c}else(l.includes("application/json")||typeof e.data=="object")&&(r.body=JSON.stringify(e.data));return r};class aE extends Hd{async request(t){const r=sE(t,t.webFetchExtra),s=iE(t.params,t.shouldEncodeUrlParams),l=s?`${t.url}?${s}`:t.url,u=await fetch(l,r),c=u.headers.get("content-type")||"";let{responseType:f="text"}=u.ok?t:{};c.includes("application/json")&&(f="json");let d,m;switch(f){case"arraybuffer":case"blob":m=await u.blob(),d=await nE(m);break;case"json":d=await u.json();break;case"document":case"text":default:d=await u.text()}const y={};return u.headers.forEach((g,x)=>{y[x]=g}),{data:d,headers:y,status:u.status,url:u.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}ys("CapacitorHttp",{web:()=>new aE});var U0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(U0||(U0={}));var B0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(B0||(B0={}));class lE extends Hd{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}ys("SystemBars",{web:()=>new lE});const oE="modulepreload",uE=function(e){return"/"+e},P0={},Id=function(t,r,s){let l=Promise.resolve();if(r&&r.length>0){let c=function(m){return Promise.all(m.map(y=>Promise.resolve(y).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),d=(f==null?void 0:f.nonce)||(f==null?void 0:f.getAttribute("nonce"));l=c(r.map(m=>{if(m=uE(m),m in P0)return;P0[m]=!0;const y=m.endsWith(".css"),g=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${g}`))return;const x=document.createElement("link");if(x.rel=y?"stylesheet":oE,y||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),y)return new Promise((w,S)=>{x.addEventListener("load",w),x.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${m}`)))})}))}function u(c){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=c,window.dispatchEvent(f),!f.defaultPrevented)throw c}return l.then(c=>{for(const f of c||[])f.status==="rejected"&&u(f.reason);return t().catch(u)})},hd=ys("App",{web:()=>Id(()=>import("./web-a9jK1xeo.js"),[]).then(e=>new e.AppWeb)}),cE=ys("Network",{web:()=>Id(()=>import("./web-Dl9aC-Qr.js"),[]).then(e=>new e.NetworkWeb)}),Uu=Vn.isNativePlatform()?"https://app.palmier.me":"";async function Ox(e,t,r,s){const l=`${Uu}${t}`;console.log(`[API] ${e} ${l}`);const c=await fetch(l,{method:e,headers:{"Content-Type":"application/json"},body:r!=null?JSON.stringify(r):void 0});if(!c.ok){const f=await c.text();let d;try{const m=JSON.parse(f);d=m.error??m.message??f}catch{d=f}throw console.error(`[API] ${e} ${t} failed:`,c.status,d),new Error(d||`Request failed with status ${c.status}`)}return console.log(`[API] ${e} ${t} ->`,c.status),c.json()}function fE(e,t,r){return Ox("POST",e,t)}function hE(e,t){return Ox("GET",e,void 0)}const q0=Vn.isNativePlatform(),Rx=j.createContext(null),dE=2e3,Th=6e3,mE=1500,pE=6e4;function gE({children:e,activeHost:t}){const[r,s]=j.useState(null),[l,u]=j.useState(!1),c=j.useRef(null),[f,d]=j.useState(!1),[m,y]=j.useState(!1),[g,x]=j.useState(!1),[w,S]=j.useState(!1),T=j.useRef(Nu()),L=j.useRef(new Set),M=j.useRef(0),P=!!t.directUrl,F=q0&&!P&&!!t.lanUrl&&w,ce=m||g?"disconnected":P?f?"direct":"connecting":l?F?"lan":"nats":"connecting",U=ce!=="connecting"&&ce!=="disconnected";j.useEffect(()=>{y(!1),x(!1)},[t.hostId,t.clientToken]),j.useEffect(()=>{if(!q0||P||!t.lanUrl){S(!1);return}let $=!1;const q=t.lanUrl,R=t.hostId;async function V(){console.log("[HOST/LAN] probing",q);try{const Y=await fetch(`${q}/health`,{signal:AbortSignal.timeout(mE)});if($)return;if(!Y.ok){console.log("[HOST/LAN] probe got non-ok:",Y.status),S(!1);return}const H=await Y.json(),W=H.hostId===R;W?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",H.hostId,"expected:",R),S(W)}catch(Y){$||(console.log("[HOST/LAN] probe failed:",Y instanceof Error?Y.message:Y),S(!1))}}V();const X=window.setInterval(V,pE),le=hd.addListener("appStateChange",Y=>{Y.isActive&&V()}),ee=cE.addListener("networkStatusChange",()=>V());return()=>{$=!0,clearInterval(X),le.then(Y=>Y.remove()),ee.then(Y=>Y.remove())}},[t.hostId,t.lanUrl,P]),j.useEffect(()=>{if(P){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1));return}let $=!1,q=1e3;const R=3e4;async function V(){for(;!$;)try{const X=await fetch(`${Uu}/api/nats-credentials/${t.hostId}`);if($)return;if(X.status===401||X.status===403||X.status===404){console.error("[NATS] Host not found or rejected by relay:",X.status),x(!0);return}if(!X.ok)throw new Error(`credentials fetch ${X.status}`);const le=await X.json();if(!le.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if($)return;console.log("[NATS] Connecting to",le.natsWsUrl);const ee=await Nx({servers:le.natsWsUrl,authenticator:wx(le.natsJwt,new TextEncoder().encode(le.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if($){ee.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=ee,s(ee),u(!0),q=1e3,await ee.closed(),$)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),u(!1)}catch(X){if($)return;console.warn(`[NATS] Connect failed, retrying in ${q}ms:`,X),u(!1),await new Promise(le=>setTimeout(le,q)),q=Math.min(q*2,R)}}return V(),()=>{$=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1))}},[P,t]),j.useEffect(()=>{if(P)return;const $=hd.addListener("appStateChange",q=>{if(!q.isActive||!c.current)return;const R=c.current;Promise.race([R.flush(),new Promise((V,X)=>setTimeout(()=>X(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),R.close().catch(()=>{})})});return()=>{$.then(q=>q.remove())}},[P]),j.useEffect(()=>{if(!P){d(!1);return}const $=new AbortController;async function q(){var le;const V=new AbortController,X=setTimeout(()=>V.abort(),dE);$.signal.addEventListener("abort",()=>V.abort());try{const ee=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:V.signal});return clearTimeout(X),ee.ok?((le=ee.body)==null?void 0:le.getReader())??null:null}catch{return clearTimeout(X),null}}async function R(V){d(!0),console.log("[HOST] SSE connected to",t.directUrl),M.current=Date.now();function X(){setTimeout(()=>{$.signal.aborted||Date.now()-M.current<Th||(console.log("[HOST] Heartbeat timeout — no data for",Th/1e3,"s"),$.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},Th)}X();const le=new TextDecoder;let ee="";try{for(;;){const{done:Y,value:H}=await V.read();if(Y)break;ee+=le.decode(H,{stream:!0}),M.current=Date.now(),X();const W=ee.split(`
|
|
88
|
-
`);ee=W.pop()??"";for(const oe of W)if(oe.startsWith("data: ")){const be=oe.slice(6);try{const k=JSON.parse(be);if(k.task_id&&k.event_type){const z=`host-event.${t.hostId}.${k.task_id}`;for(const K of L.current)K({subject:z,data:T.current.encode(be)})}}catch{}}}}catch{}}return(async()=>{const V=await q();V&&await R(V)})(),()=>{$.abort(),d(!1)}},[t,P]);const D=j.useCallback(async($,q,R)=>{function V(ee){ee&&typeof ee=="object"&&ee.error==="Unauthorized"&&y(!0)}async function X(ee,Y){console.log(`[HOST/${Y}] → ${$}`,q??"");const H=await fetch(`${ee}/rpc/${$}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.clientToken}`},body:q!=null?JSON.stringify(q):void 0,signal:R!=null&&R.timeout?AbortSignal.timeout(R.timeout):void 0});if(H.status===401)throw y(!0),new Error("Unauthorized");const W=await H.json();return V(W),console.log(`[HOST/${Y}] ← ${$}`,W),W}async function le(){if(!c.current)throw new Error("Not connected");const ee=`host.${t.hostId}.rpc.${$}`,Y={...q??{},clientToken:t.clientToken},H=T.current.encode(JSON.stringify(Y));console.log(`[HOST/NATS] → ${$}`,q??"");const W=await c.current.request(ee,H,{timeout:(R==null?void 0:R.timeout)??1e4}),oe=JSON.parse(T.current.decode(W.data));return V(oe),console.log(`[HOST/NATS] ← ${$}`,oe),oe}if(P)return X(t.directUrl,"HTTP");if(F&&t.lanUrl)try{return await X(t.lanUrl,"LAN")}catch(ee){if(ee instanceof Error&&ee.message==="Unauthorized")throw ee;console.log("[HOST/LAN] failed, falling back to NATS:",ee),S(!1)}return le()},[t,P,F]),te=j.useCallback(($,q)=>{if(P)return L.current.add(q),()=>{L.current.delete(q)};if(c.current){const R=c.current.subscribe(`host-event.${$}.>`);let V=!1;return(async()=>{try{for await(const X of R){if(V)break;q({subject:X.subject,data:X.data})}}catch{}})(),()=>{V=!0,R.unsubscribe()}}return()=>{}},[t,P]);return b.jsx(Rx.Provider,{value:{connected:U,mode:ce,nc:r,request:D,subscribeEvents:te,activeHost:t,unauthorized:m},children:e})}function Hi(){const e=j.useContext(Rx);if(!e)throw new Error("useHostConnection must be used within HostConnectionProvider");return e}const mn=Vn.isNativePlatform()?ys("Device"):null;function Bu(e){const t=new Date(e),r=new Date,s=t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return t.toDateString()===r.toDateString()?s:`${t.toLocaleDateString(void 0,{month:"short",day:"numeric"})} ${s}`}const Mx={};function yE(e){for(const t of e)Mx[t.key]=t.label}function dd(e){return Mx[e]??e}const bE=()=>window.matchMedia("(max-width: 600px)").matches;function xE({task:e,lastEvent:t,onEdit:r,onDelete:s,onViewRun:l}){var le;const{request:u}=Hi(),[c,f]=j.useState(!1),[d,m]=j.useState(!1),[y,g]=j.useState(!1),x=j.useRef(null),w=(t==null?void 0:t.running_state)==="started",S=(((le=e.schedule_values)==null?void 0:le.length)??0)>0,T=e.schedule_type==="on_new_notification"||e.schedule_type==="on_new_sms",M=!!e.schedule_enabled&&!!e.schedule_type&&(S||T)?w?"var(--color-success)":(t==null?void 0:t.running_state)==="failed"?"var(--color-error)":"var(--color-success)":"var(--color-text-secondary)";j.useEffect(()=>{if(!d)return;function ee(Y){x.current&&!x.current.contains(Y.target)&&m(!1)}return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[d]);function P(){bE()?g(!0):m(ee=>!ee)}function F(){m(!1),g(!1)}async function ce(){if(F(),!!confirm("Abort this task?")){f(!0);try{await u("task.abort",{id:e.id})}catch(ee){console.error("Abort failed:",ee)}finally{f(!1)}}}async function U(){F();try{const ee=await u("task.run",{id:e.id});l(e.id,ee.run_id)}catch(ee){console.error("Run failed:",ee)}}async function D(){if(F(),!!confirm("Delete this task? Results and reports will be kept."))try{await u("task.delete",{id:e.id}),s(e.id)}catch(ee){console.error("Delete failed:",ee)}}const te={started:"Started",finished:"Finished",aborted:"Aborted",failed:"Failed"};function $(ee,Y){if(ee==="specific_times"){const xe=new Date(Y);return{kind:"specific_times",detail:isNaN(xe.getTime())?Y:`${xe.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} at ${xe.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}`}}const H=Y.split(" ");if(H.length!==5)return{kind:"unknown",detail:Y};const[W,oe,be,,k]=H,z=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(oe==="*")return{kind:"hourly",detail:""};const K=new Date;K.setHours(Number(oe),Number(W),0,0);const A=K.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return k!=="*"?{kind:"weekly",detail:`${z[Number(k)]??k} at ${A}`}:be!=="*"?{kind:"monthly",detail:`day ${be} at ${A}`}:{kind:"daily",detail:A}}function q(ee,Y){const H=$(ee,Y);return H.kind==="hourly"?"Every hour":H.kind==="specific_times"?`Once on ${H.detail}`:`${H.kind.charAt(0).toUpperCase()+H.kind.slice(1)}: ${H.detail}`}function R(ee,Y){if(!ee)return"";if(ee==="on_new_notification")return"On new notification";if(ee==="on_new_sms")return"On new SMS";if(!Y||Y.length===0)return"";if(Y.length===1)return q(ee,Y[0]);const H=Y.map(oe=>$(ee,oe));if(new Set(H.map(oe=>oe.kind)).size===1){const oe=H[0].kind;if(oe==="hourly")return"Every hour";const be=H.map(k=>k.detail);return`${oe.charAt(0).toUpperCase()+oe.slice(1)}: ${be.join(", ")}`}return Y.map(oe=>q(ee,oe)).join(", ")}const V=R(e.schedule_type,e.schedule_values),X=b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:()=>{F(),r(e)},children:[b.jsx("span",{className:"menu-icon",children:"✎"}),"Edit"]}),b.jsxs("button",{onClick:()=>{F(),l(e.id)},children:[b.jsx("span",{className:"menu-icon",children:"📄"}),"View All Runs"]}),w?b.jsxs("button",{className:"menu-item-danger",onClick:ce,disabled:c,children:[b.jsx("span",{className:"menu-icon",children:"◼"}),"Abort"]}):b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:U,children:[b.jsx("span",{className:"menu-icon",children:"▶"}),"Run Now"]}),b.jsxs("button",{className:"menu-item-danger",onClick:D,children:[b.jsx("span",{className:"menu-icon",children:"🗑"}),"Delete"]})]})]});return b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"task-card",onClick:()=>l(e.id,"latest"),children:[b.jsxs("div",{className:"task-card-header",children:[b.jsxs("div",{className:"task-card-title-row",children:[w?b.jsx("span",{className:"status-spinner",children:b.jsx("span",{})}):b.jsx("span",{className:"status-dot",style:{backgroundColor:M}}),b.jsx("h3",{className:"task-card-name",children:e.name||e.user_prompt})]}),b.jsx("div",{className:"task-card-actions",onClick:ee=>ee.stopPropagation(),children:b.jsxs("div",{className:"task-card-menu",ref:x,children:[b.jsx("button",{className:"task-card-menu-btn",onClick:P,"aria-label":"Task actions",children:"⋮"}),d&&b.jsx("div",{className:"task-card-menu-dropdown",children:X})]})})]}),b.jsxs("div",{className:"task-card-meta",children:[e.agent&&b.jsx("span",{className:"task-card-agent",children:dd(e.agent)}),t&&te[t.running_state]&&b.jsxs("span",{className:"task-card-last-event",children:[te[t.running_state]," ",Bu(t.time_stamp)]}),e.schedule_type&&(S||T)&&b.jsx("span",{className:"task-card-triggers",children:e.schedule_enabled?V:"Schedule disabled"})]})]}),y&&ds.createPortal(b.jsx("div",{className:"bottom-sheet-overlay",onClick:()=>g(!1),children:b.jsxs("div",{className:"bottom-sheet",onClick:ee=>ee.stopPropagation(),children:[b.jsx("div",{className:"bottom-sheet-handle"}),b.jsx("div",{className:"bottom-sheet-title",children:e.name||e.user_prompt}),b.jsx("div",{className:"bottom-sheet-actions",children:X})]})}),document.body)]})}function vE({permissions:e}){return b.jsxs("div",{className:"permissions-dialog",children:[b.jsx("h2",{children:"Granted Permissions"}),b.jsx("div",{className:"permissions-dialog-scroll",children:e&&e.length>0?b.jsx("div",{className:"permissions-section",children:b.jsx("ul",{className:"permissions-list",children:e.map((t,r)=>b.jsxs("li",{className:"permission-item",children:[b.jsx("span",{className:"permission-tool",children:t.name}),b.jsx("span",{className:"permission-desc",children:t.description})]},r))})}):b.jsx("p",{className:"permissions-empty",children:"No permissions have been granted for this task."})}),b.jsx("div",{className:"permissions-dialog-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>history.back(),children:"Back"})})]})}const ra=[];function wE(){const e=ra.pop();e&&(e.pushed.current=!1,e.close())}let H0=!1;function SE(){H0||(H0=!0,window.addEventListener("popstate",wE))}function md(e,t){const r=j.useRef(!1),s=j.useRef(t);s.current=t;const l=j.useCallback(()=>s.current(),[]),u=j.useRef({close:l,pushed:r});u.current.close=l,j.useEffect(()=>{if(e&&!r.current)SE(),history.pushState({modal:!0},""),ra.push(u.current),r.current=!0;else if(!e&&r.current){r.current=!1;const c=ra.indexOf(u.current);c!==-1&&ra.splice(c,1),history.back()}},[e,l]),j.useEffect(()=>{const c=u.current;return()=>{if(r.current){r.current=!1;const f=ra.indexOf(c);f!==-1&&ra.splice(f,1),history.back()}}},[])}const _E=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],kE=["specific_times","hourly","daily","weekly","monthly"];function mu(e){return kE.includes(e)}function EE(e){return e==="on_new_notification"||e==="on_new_sms"}function Wr(e="daily"){return{schedule:e,time:"00:00",dayOfWeek:"1",dayOfMonth:"1",onceDate:"",onceTime:"00:00"}}function CE(e){const t=e.split(" ");if(t.length!==5)return Wr();const[r,s,l,,u]=t;if(s==="*")return Wr("hourly");const c=`${s.padStart(2,"0")}:${r.padStart(2,"0")}`;return u!=="*"?{...Wr("weekly"),time:c,dayOfWeek:u}:l!=="*"?{...Wr("monthly"),time:c,dayOfMonth:l}:{...Wr("daily"),time:c}}function Dx(e,t){if(e==="specific_times"){const[r,s]=t.split("T");return{...Wr("specific_times"),onceDate:r??"",onceTime:(s??"09:00").slice(0,5)}}return CE(t)}function AE(e){const[t,r]=e.time.split(":").map(Number);switch(e.schedule){case"hourly":return"0 * * * *";case"daily":return`${r} ${t} * * *`;case"weekly":return`${r} ${t} * * ${e.dayOfWeek}`;case"monthly":return`${r} ${t} ${e.dayOfMonth} * *`;default:return"0 * * * *"}}function jE(e){return e.schedule==="specific_times"?e.onceDate?`${e.onceDate}T${e.onceTime}`:null:AE(e)}function Nh(e){return e==="specific_times"?"specific_times":e==="on_new_notification"?"on_new_notification":e==="on_new_sms"?"on_new_sms":"crons"}function Oh(e){var s;if(!e)return"daily";if(e.command)return"command";const t=e.schedule_type;if(t==="on_new_notification"||t==="on_new_sms")return t;if(t!=="crons"&&t!=="specific_times")return"ondemand";const r=(s=e.schedule_values)==null?void 0:s[0];return r?Dx(t,r).schedule:"ondemand"}function TE({initial:e,agents:t,hostPlatform:r,isNotificationListener:s,onSaved:l,onRun:u,onCancel:c}){var Ht;const{request:f,activeHost:d}=Hi(),{setHostLastAgent:m}=Pi(),y=()=>{var Ae;const de=d.lastAgent,Ie=t.map(Ot=>Ot.key);return de&&Ie.includes(de)?de:((Ae=t[0])==null?void 0:Ae.key)??""},[g,x]=j.useState((e==null?void 0:e.user_prompt)??""),[w,S]=j.useState((e==null?void 0:e.agent)??y()),T=!!((Ht=e==null?void 0:e.permissions)!=null&&Ht.length),[L,M]=j.useState(!1),P=j.useCallback(()=>M(!1),[]);md(L,P);const[F,ce]=j.useState(null),[U,D]=j.useState(()=>Oh(e)),[te,$]=j.useState(()=>{const de=e==null?void 0:e.schedule_type,Ie=e==null?void 0:e.schedule_values;if(Ie&&(de==="crons"||de==="specific_times"))return Ie.map(Ot=>Dx(de,Ot));const Ae=Oh(e);return mu(Ae)?[Wr(Ae)]:[]}),[q,R]=j.useState((e==null?void 0:e.requires_confirmation)??!1),[V,X]=j.useState((e==null?void 0:e.schedule_enabled)??!0),[le,ee]=j.useState((e==null?void 0:e.yolo_mode)??!1),[Y,H]=j.useState((e==null?void 0:e.foreground_mode)??!1),[W,oe]=j.useState((e==null?void 0:e.command)??""),[be,k]=j.useState(!1),z=(e==null?void 0:e.schedule_type)==="on_new_notification"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[K,A]=j.useState(z),[xe,_e]=j.useState([]),[je,Le]=j.useState(!1),[$e,Ce]=j.useState(!1),[Ne,Te]=j.useState(""),Fe=j.useCallback(()=>Ce(!1),[]);md($e,Fe),j.useEffect(()=>{if(U!=="on_new_notification"||!s||!Vn.isNativePlatform()||!mn)return;let de=!1;return Le(!0),mn.getInstalledApps().then(({apps:Ie})=>{if(de)return;const Ae="com.palmier.app",Ot=Ie.filter(Pt=>Pt.packageName!==Ae).sort((Pt,fn)=>(Pt.appName||Pt.packageName).localeCompare(fn.appName||fn.packageName));_e(Ot)}).catch(()=>{}).finally(()=>{de||Le(!1)}),()=>{de=!0}},[U,s]);const Qe=(e==null?void 0:e.schedule_type)==="on_new_sms"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[qe,ct]=j.useState(Qe),vt=j.useRef(null),Ve=mu(U),He=U==="command",nt=EE(U),ft=t.find(de=>de.key===w),rt=!!(ft!=null&&ft.supportsYolo);j.useEffect(()=>{!rt&&le&&ee(!1)},[rt,le]);const qt=!!e,Tt=Oh(e),ht=!qt||g!==((e==null?void 0:e.user_prompt)??"")||w!==((e==null?void 0:e.agent)??"")||U!==Tt||q!==((e==null?void 0:e.requires_confirmation)??!1)||V!==((e==null?void 0:e.schedule_enabled)??!0)||le!==((e==null?void 0:e.yolo_mode)??!1)||Y!==((e==null?void 0:e.foreground_mode)??!1)||He&&W!==((e==null?void 0:e.command)??"")||Ve&&(JSON.stringify(nn())!==JSON.stringify((e==null?void 0:e.schedule_values)??[])||Nh(U)!==((e==null?void 0:e.schedule_type)??void 0))||nt&&U!==(e==null?void 0:e.schedule_type)||U==="on_new_notification"&&K.trim()!==z.trim()||U==="on_new_sms"&&qe.trim()!==Qe.trim(),Fi=Ve&&te.some(de=>de.schedule==="specific_times"&&(!de.onceDate||new Date(`${de.onceDate}T${de.onceTime}`)<=new Date)),fe=ht&&!!g.trim()&&!Fi&&(!He||!!W.trim())&&(!Ve||te.length>0);function ve(de,Ie){$(Ae=>Ae.map((Ot,Pt)=>Pt===de?{...Ot,...Ie}:Ot))}function Ue(de){$(Ie=>Ie.filter((Ae,Ot)=>Ot!==de))}function Je(){mu(U)&&$(de=>[...de,de.length>0?{...de[de.length-1]}:Wr(U)])}function lt(de){D(de),mu(de)?$([Wr(de)]):($([]),R(!1)),de==="command"?setTimeout(()=>{var Ie;return(Ie=vt.current)==null?void 0:Ie.focus()},0):oe(""),de!=="on_new_notification"&&A(z),de!=="on_new_sms"&&ct(Qe)}function nn(){return te.flatMap(de=>{const Ie=jE(de);return Ie?[Ie]:[]})}function _n(){return le?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
|
|
87
|
+
${f.stack}`),c.reject(m)):c.resolve(y))}});return d.requestSubject=t,this.protocol.publish(t,r,{reply:u,headers:s.headers}),c}else{const u=new px(this.protocol.muxSubscriptions,t,s,l);this.protocol.request(u);try{this.publish(t,r,{reply:`${this.protocol.muxSubscriptions.baseInbox}${u.token}`,headers:s.headers})}catch(f){u.cancel(f)}const c=Promise.race([u.timer,u.deferred]);return c.catch(()=>{u.cancel()}),c}}flush(){return this.isClosed()?Promise.reject(Oe.errorForCode(Se.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(Oe.errorForCode(Se.ConnectionClosed)):this.isDraining()?Promise.reject(Oe.errorForCode(Se.ConnectionDraining)):(this.draining=!0,this.protocol.drain())}isClosed(){return this.protocol.isClosed()}isDraining(){return this.draining}getServer(){const t=this.protocol.getServer();return t?t.listen:""}status(){const t=new an;return t.iterClosed.then(()=>{const r=this.listeners.indexOf(t);this.listeners.splice(r,1)}),this.listeners.push(t),t}get info(){return this.protocol.isClosed()?void 0:this.protocol.info}async context(){return(await this.request("$SYS.REQ.USER.INFO")).json((r,s)=>r==="time"?new Date(Date.parse(s)):s)}stats(){return{inBytes:this.protocol.inBytes,outBytes:this.protocol.outBytes,inMsgs:this.protocol.inMsgs,outMsgs:this.protocol.outMsgs}}async jetstreamManager(t={}){const r=new Dk(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===Se.NoResponders&&(l.code=Se.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Pd(this,t)}getServerVersion(){const t=this.info;return t?ms(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw Oe.errorForCode(Se.Disconnect);const t=Date.now();return await this.flush(),Date.now()-t}get features(){return this.protocol.features}get services(){return this._services||(this._services=new Bk(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(Oe.errorForCode(Se.ConnectionClosed)):this.isDraining()?Promise.reject(Oe.errorForCode(Se.ConnectionDraining)):this.protocol.reconnect()}}class Bk{constructor(t){C(this,"nc");this.nc=t}add(t){try{return new Yl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new yk(this.nc,t,r)}}class Pk{constructor(t,r,s){C(this,"bucket");C(this,"sm");C(this,"prefixLen");this.bucket=t,this.prefixLen=r,this.sm=s}get key(){return this.sm.subject.substring(this.prefixLen)}get value(){return this.sm.data}get delta(){return 0}get created(){return this.sm.time}get revision(){return this.sm.seq}get operation(){return this.sm.header.get(zu)||"PUT"}get length(){const t=this.sm.header.get(Sn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class qk{constructor(t,r,s){C(this,"bucket");C(this,"key");C(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Dd(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(zu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(Sn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class jx extends y2{constructor(r,s,l){super(r.nc,s,l);C(this,"js");C(this,"monitor");this.js=r,this.monitor=null,this.sub.closed.then(()=>{this.monitor&&this.monitor.cancel()})}set info(r){this.sub.info=r}get info(){return this.sub.info}_resetOrderedConsumer(r){if(this.info===null||this.sub.isClosed())return;const s=ei(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const u=this.info;u.config.name=Ui.next(),u.ordered_consumer_sequence.delivery_seq=0,u.flow_control.heartbeat_count=0,u.flow_control.fc_count=0,u.flow_control.consumer_restarts++,u.deliver=s,u.config.deliver_subject=s,u.config.deliver_policy=Vt.StartSequence,u.config.opt_start_seq=r;const c={};c.stream_name=this.info.stream,c.config=u.config;const f=`${u.api.prefix}.CONSUMER.CREATE.${u.stream}`;this.js._request(f,c,{retries:-1}).then(d=>{const m=d,y=this.sub.info;y.last=m,this.info.config=m.config,this.info.name=m.name}).catch(d=>{const m=new Oe(`unable to recreate ordered consumer ${u.stream} at seq ${r}`,Se.RequestError,d);this.sub.callback(m,{})})}_maybeSetupHbMonitoring(){var s,l;const r=((l=(s=this.info)==null?void 0:s.config)==null?void 0:l.idle_heartbeat)||0;r&&this._setupHbMonitoring(Dd(r))}_setupHbMonitoring(r,s=0){const l={cancelAfter:0,maxOut:2};s&&(l.cancelAfter=s);const u=this.sub,c=f=>{var y,g,x,w;const d=Q_(409,`${ar.IdleHeartbeatMissed}: ${f}`,this.sub.subject);if(!((y=this.info)==null?void 0:y.ordered))this.sub.callback(null,d);else{if(!this.js.nc.protocol.connected)return!1;const S=((x=(g=this.info)==null?void 0:g.ordered_consumer_sequence)==null?void 0:x.stream_seq)||0;return this._resetOrderedConsumer(S+1),(w=this.monitor)==null||w.restart(),!1}return!u.noIterator};this.monitor=new zd(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(Sn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(Sn.LastConsumerSeqHdr),10),u=this.info.ordered_consumer_sequence;return this.info.flow_control.heartbeat_count++,l!==u.delivery_seq&&this._resetOrderedConsumer(u.stream_seq+1),!1}_checkOrderedConsumer(r){const s=this.info.ordered_consumer_sequence,l=r.info.streamSequence,u=r.info.deliverySequence;return u!=s.delivery_seq+1?(this._resetOrderedConsumer(s.stream_seq+1),!1):(s.delivery_seq=u,s.stream_seq=l,!0)}async destroy(){this.isClosed()||await this.drain();const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.DELETE.${r.stream}.${s}`;await r.api._request(l)}async consumerInfo(){const r=this.sub.info,s=r.config.durable_name||r.name,l=`${r.api.prefix}.CONSUMER.INFO.${r.stream}.${s}`,u=await r.api._request(l);return r.last=u,u}}class Hk extends jx{constructor(t,r,s){super(t,r,s)}pull(t={batch:1}){const{stream:r,config:s,name:l}=this.sub.info,u=s.durable_name??l,c={};if(c.batch=t.batch||1,c.no_wait=t.no_wait||!1,(t.max_bytes??0)>0){const m=this.js.nc.features.get(ut.JS_PULL_MAX_BYTES);if(!m.ok)throw new Error(`max_bytes is only supported on servers ${m.min} or better`);c.max_bytes=t.max_bytes}let f=0;t.expires&&t.expires>0&&(f=t.expires,c.expires=zt(f));let d=0;if(t.idle_heartbeat&&t.idle_heartbeat>0&&(d=t.idle_heartbeat,c.idle_heartbeat=zt(d)),d&&f===0)throw new Error("idle_heartbeat requires expires");if(d>f)throw new Error("expires must be greater than idle_heartbeat");if(this.info){this.monitor&&this.monitor.cancel(),f&&d&&(this.monitor?this.monitor._change(d,f):this._setupHbMonitoring(d,f));const m=this.info.api,y=`${m.prefix}.CONSUMER.MSG.NEXT.${r}.${u}`,g=this.sub.subject;m.nc.publish(y,m.jc.encode(c),{reply:g})}}}function Ik(e,t){return e?$k(t):Fk(t)}function Fk(e){return(t,r)=>t?[t,null]:(t=ua(r),t?[t,null]:[null,Pl(r,e)])}function $k(e){return(t,r)=>{if(t)return[t,null];const s=ua(r);return s!==null?[Tx(s),null]:[null,Pl(r,e)]}}function Tx(e){if(e!==null)switch(e.code){case Se.JetStream404NoMessages:case Se.JetStream408RequestTimeout:return null;case Se.JetStream409:return Z_(e)?e:null;default:return e}return null}function Yk(e){e&&e.ack()}function Gk(e){const t=e.split(".");if(t.length===9&&t.splice(2,0,"_",""),t.length<11||t[0]!=="$JS"||t[1]!=="ACK")throw new Error("not js message");const r={};return r.domain=t[2]==="_"?"":t[2],r.account_hash=t[3],r.stream=t[4],r.consumer=t[5],r.deliveryCount=parseInt(t[6],10),r.redeliveryCount=r.deliveryCount,r.redelivered=r.deliveryCount>1,r.streamSequence=parseInt(t[7],10),r.deliverySequence=parseInt(t[8],10),r.timestampNanos=parseInt(t[9],10),r.pending=parseInt(t[10],10),r}class Vk{constructor(t,r){C(this,"msg");C(this,"di");C(this,"didAck");C(this,"timeout");this.msg=t,this.didAck=!1,this.timeout=r}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){return this.di||(this.di=Gk(this.reply)),this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}doAck(t){this.didAck||(this.didAck=!this.isWIP(t),this.msg.respond(t))}isWIP(t){return t.length===4&&t[0]===xl[0]&&t[1]===xl[1]&&t[2]===xl[2]&&t[3]===xl[3]}async ackAck(t){var s;t=t||{},t.timeout=t.timeout||this.timeout;const r=Ut();if(this.didAck)r.resolve(!1);else if(this.didAck=!0,this.msg.reply){const u=this.msg.publisher,c=!((s=u.options)!=null&&s.noAsyncTraces),f=new px(u.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);u.request(f);try{u.publish(this.msg.reply,M0,{reply:`${u.muxSubscriptions.baseInbox}${f.token}`})}catch(d){f.cancel(d)}try{await Promise.race([f.timer,f.deferred]),r.resolve(!0)}catch(d){f.cancel(d),r.reject(d)}}else r.resolve(!1);return r}ack(){this.doAck(M0)}nak(t){let r=Ak;t&&(r=Nu().encode(`-NAK ${JSON.stringify({delay:zt(t)})}`)),this.doAck(r)}working(){this.doAck(xl)}next(t,r={batch:1}){const s={};s.batch=r.batch||1,s.no_wait=r.no_wait||!1,r.expires&&r.expires>0&&(s.expires=zt(r.expires));const l=br().encode(s),u=ga.concat(jk,Nk,l),c=t?{reply:t}:void 0;this.msg.respond(u,c)}term(t=""){let r=Tk;(t==null?void 0:t.length)>0&&(r=Nu().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const Jk="1.30.3",Xk="nats.ws";class Kk{constructor(){C(this,"version");C(this,"lang");C(this,"closeError");C(this,"connected");C(this,"done");C(this,"socket");C(this,"options");C(this,"socketClosed");C(this,"encrypted");C(this,"peeked");C(this,"yields");C(this,"signal");C(this,"closedNotification");this.version=Jk,this.lang=Xk,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=Ut(),this.closedNotification=Ut()}async connect(t,r){const s=Ut();if(r.tls)return s.reject(new Oe("tls",Se.InvalidOption)),s;this.options=r;const l=t.src;if(r.wsFactory){const{socket:u,encrypted:c}=await r.wsFactory(t.src,r);this.socket=u,this.encrypted=c}else this.encrypted=l.indexOf("wss://")===0,this.socket=new WebSocket(l);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{this.isDiscarded()},this.socket.onmessage=u=>{if(this.isDiscarded())return;if(this.yields.push(new Uint8Array(u.data)),this.peeked){this.signal.resolve();return}const c=ga.concat(...this.yields),f=_2(c);if(f!==""){const d=uk.exec(f);if(!d){r.debug&&console.error("!!!",cu(c)),s.reject(new Error("unexpected response from server"));return}try{const m=JSON.parse(d[1]);lk(m,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),s.resolve()}catch(m){s.reject(m);return}}},this.socket.onclose=u=>{if(this.isDiscarded())return;this.socketClosed=!0;let c;this.done||(u.wasClean||(c=new Error(u.reason)),this._closed(c))},this.socket.onerror=u=>{if(this.isDiscarded())return;const c=u,f=new Oe(c.message,Se.Unknown,new Error(c.error));s.reject(f)},s}disconnect(){this._closed(void 0,!0)}async _closed(t,r=!0){if(!this.isDiscarded()&&this.connected&&!this.done){if(this.closeError=t,!t)for(;!this.socketClosed&&this.socket.bufferedAmount>0;)await Sa(100);this.done=!0;try{this.socket.close(t?1002:1e3,t?t.message:void 0)}catch{}r&&this.closedNotification.resolve(t)}}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){for(;;){if(this.isDiscarded())return;this.yields.length===0&&await this.signal;const t=this.yields;this.yields=[];for(let r=0;r<t.length;r++)this.options.debug&&console.info(`> ${cu(t[r])}`),yield t[r];if(this.done)break;this.yields.length===0&&(t.length=0,this.yields=t,this.signal=Ut())}}isEncrypted(){return this.connected&&this.encrypted}send(t){if(!this.isDiscarded())try{this.socket.send(t.buffer),this.options.debug&&console.info(`< ${cu(t)}`);return}catch(r){this.options.debug&&console.error(`!!! ${cu(t)}: ${r}`)}}close(t){return this._closed(t,!1)}closed(){return this.closedNotification}isDiscarded(){return this.done?(this.discard(),!0):!1}discard(){var t;this.done=!0;try{(t=this.socket)==null||t.close()}catch{}}}function Qk(e,t){/^(.*:\/\/)(.*)/.test(e)||(typeof t=="boolean"?e=`${t===!0?"https":"http"}://${e}`:e=`https://${e}`);let s=new URL(e);const l=s.protocol.toLowerCase();l==="ws:"&&(t=!1),l==="wss:"&&(t=!0),l!=="https:"&&l!=="http"&&(e=e.replace(/^(.*:\/\/)(.*)/gm,"$2"),s=new URL(`http://${e}`));let u,c;const f=s.hostname,d=s.pathname,m=s.search||"";switch(l){case"http:":case"ws:":case"nats:":c=s.port||"80",u="ws:";break;case"https:":case"wss:":case"tls:":c=s.port||"443",u="wss:";break;default:c=s.port||t===!0?"443":"80",u=t===!0?"wss:":"ws:";break}return`${u}//${f}:${c}${d}${m}`}function Nx(e={}){return b2({defaultPort:443,urlParseFn:Qk,factory:()=>new Kk}),qd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var ya;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(ya||(ya={}));class jh extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const Zk=e=>{var t,r;return e!=null&&e.androidBridge?"android":!((r=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||r===void 0)&&r.bridge?"ios":"web"},Wk=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:Zk(e),u=()=>l()!=="web",c=g=>{const x=m.get(g);return!!(x!=null&&x.platforms.has(l())||f(g))},f=g=>{var x;return(x=r.PluginHeaders)===null||x===void 0?void 0:x.find(w=>w.name===g)},d=g=>e.console.error(g),m=new Map,y=(g,x={})=>{const w=m.get(g);if(w)return console.warn(`Capacitor plugin "${g}" already registered. Cannot register plugins twice.`),w.proxy;const S=l(),T=f(g);let L;const M=async()=>(!L&&S in x?L=typeof x[S]=="function"?L=await x[S]():L=x[S]:t!==null&&!L&&"web"in x&&(L=typeof x.web=="function"?L=await x.web():L=x.web),L),P=($,q)=>{var R,V;if(T){const X=T==null?void 0:T.methods.find(le=>q===le.name);if(X)return X.rtype==="promise"?le=>r.nativePromise(g,q.toString(),le):(le,ee)=>r.nativeCallback(g,q.toString(),le,ee);if($)return(R=$[q])===null||R===void 0?void 0:R.bind($)}else{if($)return(V=$[q])===null||V===void 0?void 0:V.bind($);throw new jh(`"${g}" plugin is not implemented on ${S}`,ya.Unimplemented)}},F=$=>{let q;const R=(...V)=>{const X=M().then(le=>{const ee=P(le,$);if(ee){const Y=ee(...V);return q=Y==null?void 0:Y.remove,Y}else throw new jh(`"${g}.${$}()" is not implemented on ${S}`,ya.Unimplemented)});return $==="addListener"&&(X.remove=async()=>q()),X};return R.toString=()=>`${$.toString()}() { [capacitor code] }`,Object.defineProperty(R,"name",{value:$,writable:!1,configurable:!1}),R},ce=F("addListener"),U=F("removeListener"),D=($,q)=>{const R=ce({eventName:$},q),V=async()=>{const le=await R;U({eventName:$,callbackId:le},q)},X=new Promise(le=>R.then(()=>le({remove:V})));return X.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await V()},X},te=new Proxy({},{get($,q){switch(q){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return T?D:ce;case"removeListener":return U;default:return F(q)}}});return s[g]=te,m.set(g,{name:g,proxy:te,platforms:new Set([...Object.keys(x),...T?[S]:[]])}),te};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=u,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=jh,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},eE=e=>e.Capacitor=Wk(e),Vn=eE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ys=Vn.registerPlugin;class Hd{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,r){let s=!1;this.listeners[t]||(this.listeners[t]=[],s=!0),this.listeners[t].push(r);const u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),s&&this.sendRetainedArgumentsForEvent(t);const c=async()=>this.removeListener(t,r);return Promise.resolve({remove:c})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,r,s){const l=this.listeners[t];if(!l){if(s){let u=this.retainedEventArguments[t];u||(u=[]),u.push(r),this.retainedEventArguments[t]=u}return}l.forEach(u=>u(r))}hasListeners(t){var r;return!!(!((r=this.listeners[t])===null||r===void 0)&&r.length)}registerWindowListener(t,r){this.windowListeners[r]={registered:!1,windowEventName:t,pluginEventName:r,handler:s=>{this.notifyListeners(r,s)}}}unimplemented(t="not implemented"){return new Vn.Exception(t,ya.Unimplemented)}unavailable(t="not available"){return new Vn.Exception(t,ya.Unavailable)}async removeListener(t,r){const s=this.listeners[t];if(!s)return;const l=s.indexOf(r);this.listeners[t].splice(l,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const r=this.retainedEventArguments[t];r&&(delete this.retainedEventArguments[t],r.forEach(s=>{this.notifyListeners(t,s)}))}}const L0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),z0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class tE extends Hd{async getCookies(){const t=document.cookie,r={};return t.split(";").forEach(s=>{if(s.length<=0)return;let[l,u]=s.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");l=z0(l).trim(),u=z0(u).trim(),r[l]=u}),r}async setCookie(t){try{const r=L0(t.key),s=L0(t.value),l=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),c=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${r}=${s||""}${l}; path=${u}; ${c};`}catch(r){return Promise.reject(r)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(r){return Promise.reject(r)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const r of t)document.cookie=r.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}ys("CapacitorCookies",{web:()=>new tE});const nE=async e=>new Promise((t,r)=>{const s=new FileReader;s.onload=()=>{const l=s.result;t(l.indexOf(",")>=0?l.split(",")[1]:l)},s.onerror=l=>r(l),s.readAsDataURL(e)}),rE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,u,c)=>(l[u]=e[t[c]],l),{})},iE=(e,t=!0)=>e?Object.entries(e).reduce((s,l)=>{const[u,c]=l;let f,d;return Array.isArray(c)?(d="",c.forEach(m=>{f=t?encodeURIComponent(m):m,d+=`${u}=${f}&`}),d.slice(0,-1)):(f=t?encodeURIComponent(c):c,d=`${u}=${f}`),`${s}&${d}`},"").substr(1):null,sE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=rE(e.headers)["content-type"]||"";if(typeof e.data=="string")r.body=e.data;else if(l.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[c,f]of Object.entries(e.data||{}))u.set(c,f);r.body=u.toString()}else if(l.includes("multipart/form-data")||e.data instanceof FormData){const u=new FormData;if(e.data instanceof FormData)e.data.forEach((f,d)=>{u.append(d,f)});else for(const f of Object.keys(e.data))u.append(f,e.data[f]);r.body=u;const c=new Headers(r.headers);c.delete("content-type"),r.headers=c}else(l.includes("application/json")||typeof e.data=="object")&&(r.body=JSON.stringify(e.data));return r};class aE extends Hd{async request(t){const r=sE(t,t.webFetchExtra),s=iE(t.params,t.shouldEncodeUrlParams),l=s?`${t.url}?${s}`:t.url,u=await fetch(l,r),c=u.headers.get("content-type")||"";let{responseType:f="text"}=u.ok?t:{};c.includes("application/json")&&(f="json");let d,m;switch(f){case"arraybuffer":case"blob":m=await u.blob(),d=await nE(m);break;case"json":d=await u.json();break;case"document":case"text":default:d=await u.text()}const y={};return u.headers.forEach((g,x)=>{y[x]=g}),{data:d,headers:y,status:u.status,url:u.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}ys("CapacitorHttp",{web:()=>new aE});var U0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(U0||(U0={}));var B0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(B0||(B0={}));class lE extends Hd{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}ys("SystemBars",{web:()=>new lE});const oE="modulepreload",uE=function(e){return"/"+e},P0={},Id=function(t,r,s){let l=Promise.resolve();if(r&&r.length>0){let c=function(m){return Promise.all(m.map(y=>Promise.resolve(y).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const f=document.querySelector("meta[property=csp-nonce]"),d=(f==null?void 0:f.nonce)||(f==null?void 0:f.getAttribute("nonce"));l=c(r.map(m=>{if(m=uE(m),m in P0)return;P0[m]=!0;const y=m.endsWith(".css"),g=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${g}`))return;const x=document.createElement("link");if(x.rel=y?"stylesheet":oE,y||(x.as="script"),x.crossOrigin="",x.href=m,d&&x.setAttribute("nonce",d),document.head.appendChild(x),y)return new Promise((w,S)=>{x.addEventListener("load",w),x.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${m}`)))})}))}function u(c){const f=new Event("vite:preloadError",{cancelable:!0});if(f.payload=c,window.dispatchEvent(f),!f.defaultPrevented)throw c}return l.then(c=>{for(const f of c||[])f.status==="rejected"&&u(f.reason);return t().catch(u)})},hd=ys("App",{web:()=>Id(()=>import("./web-Eg0A6HEi.js"),[]).then(e=>new e.AppWeb)}),cE=ys("Network",{web:()=>Id(()=>import("./web-DdVpqhvX.js"),[]).then(e=>new e.NetworkWeb)}),Uu=Vn.isNativePlatform()?"https://app.palmier.me":"";async function Ox(e,t,r,s){const l=`${Uu}${t}`;console.log(`[API] ${e} ${l}`);const c=await fetch(l,{method:e,headers:{"Content-Type":"application/json"},body:r!=null?JSON.stringify(r):void 0});if(!c.ok){const f=await c.text();let d;try{const m=JSON.parse(f);d=m.error??m.message??f}catch{d=f}throw console.error(`[API] ${e} ${t} failed:`,c.status,d),new Error(d||`Request failed with status ${c.status}`)}return console.log(`[API] ${e} ${t} ->`,c.status),c.json()}function fE(e,t,r){return Ox("POST",e,t)}function hE(e,t){return Ox("GET",e,void 0)}const q0=Vn.isNativePlatform(),Rx=j.createContext(null),dE=2e3,Th=6e3,mE=1500,pE=6e4;function gE({children:e,activeHost:t}){const[r,s]=j.useState(null),[l,u]=j.useState(!1),c=j.useRef(null),[f,d]=j.useState(!1),[m,y]=j.useState(!1),[g,x]=j.useState(!1),[w,S]=j.useState(!1),T=j.useRef(Nu()),L=j.useRef(new Set),M=j.useRef(0),P=!!t.directUrl,F=q0&&!P&&!!t.lanUrl&&w,ce=m||g?"disconnected":P?f?"direct":"connecting":l?F?"lan":"nats":"connecting",U=ce!=="connecting"&&ce!=="disconnected";j.useEffect(()=>{y(!1),x(!1)},[t.hostId,t.clientToken]),j.useEffect(()=>{if(!q0||P||!t.lanUrl){S(!1);return}let $=!1;const q=t.lanUrl,R=t.hostId;async function V(){console.log("[HOST/LAN] probing",q);try{const Y=await fetch(`${q}/health`,{signal:AbortSignal.timeout(mE)});if($)return;if(!Y.ok){console.log("[HOST/LAN] probe got non-ok:",Y.status),S(!1);return}const H=await Y.json(),W=H.hostId===R;W?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",H.hostId,"expected:",R),S(W)}catch(Y){$||(console.log("[HOST/LAN] probe failed:",Y instanceof Error?Y.message:Y),S(!1))}}V();const X=window.setInterval(V,pE),le=hd.addListener("appStateChange",Y=>{Y.isActive&&V()}),ee=cE.addListener("networkStatusChange",()=>V());return()=>{$=!0,clearInterval(X),le.then(Y=>Y.remove()),ee.then(Y=>Y.remove())}},[t.hostId,t.lanUrl,P]),j.useEffect(()=>{if(P){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1));return}let $=!1,q=1e3;const R=3e4;async function V(){for(;!$;)try{const X=await fetch(`${Uu}/api/nats-credentials/${t.hostId}`);if($)return;if(X.status===401||X.status===403||X.status===404){console.error("[NATS] Host not found or rejected by relay:",X.status),x(!0);return}if(!X.ok)throw new Error(`credentials fetch ${X.status}`);const le=await X.json();if(!le.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if($)return;console.log("[NATS] Connecting to",le.natsWsUrl);const ee=await Nx({servers:le.natsWsUrl,authenticator:wx(le.natsJwt,new TextEncoder().encode(le.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if($){ee.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=ee,s(ee),u(!0),q=1e3,await ee.closed(),$)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),u(!1)}catch(X){if($)return;console.warn(`[NATS] Connect failed, retrying in ${q}ms:`,X),u(!1),await new Promise(le=>setTimeout(le,q)),q=Math.min(q*2,R)}}return V(),()=>{$=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1))}},[P,t]),j.useEffect(()=>{if(P)return;const $=hd.addListener("appStateChange",q=>{if(!q.isActive||!c.current)return;const R=c.current;Promise.race([R.flush(),new Promise((V,X)=>setTimeout(()=>X(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),R.close().catch(()=>{})})});return()=>{$.then(q=>q.remove())}},[P]),j.useEffect(()=>{if(!P){d(!1);return}const $=new AbortController;async function q(){var le;const V=new AbortController,X=setTimeout(()=>V.abort(),dE);$.signal.addEventListener("abort",()=>V.abort());try{const ee=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:V.signal});return clearTimeout(X),ee.ok?((le=ee.body)==null?void 0:le.getReader())??null:null}catch{return clearTimeout(X),null}}async function R(V){d(!0),console.log("[HOST] SSE connected to",t.directUrl),M.current=Date.now();function X(){setTimeout(()=>{$.signal.aborted||Date.now()-M.current<Th||(console.log("[HOST] Heartbeat timeout — no data for",Th/1e3,"s"),$.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},Th)}X();const le=new TextDecoder;let ee="";try{for(;;){const{done:Y,value:H}=await V.read();if(Y)break;ee+=le.decode(H,{stream:!0}),M.current=Date.now(),X();const W=ee.split(`
|
|
88
|
+
`);ee=W.pop()??"";for(const oe of W)if(oe.startsWith("data: ")){const be=oe.slice(6);try{const k=JSON.parse(be);if(k.task_id&&k.event_type){const z=`host-event.${t.hostId}.${k.task_id}`;for(const K of L.current)K({subject:z,data:T.current.encode(be)})}}catch{}}}}catch{}}return(async()=>{const V=await q();V&&await R(V)})(),()=>{$.abort(),d(!1)}},[t,P]);const D=j.useCallback(async($,q,R)=>{function V(ee){ee&&typeof ee=="object"&&ee.error==="Unauthorized"&&y(!0)}async function X(ee,Y){console.log(`[HOST/${Y}] → ${$}`,q??"");const H=await fetch(`${ee}/rpc/${$}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.clientToken}`},body:q!=null?JSON.stringify(q):void 0,signal:R!=null&&R.timeout?AbortSignal.timeout(R.timeout):void 0});if(H.status===401)throw y(!0),new Error("Unauthorized");const W=await H.json();return V(W),console.log(`[HOST/${Y}] ← ${$}`,W),W}async function le(){if(!c.current)throw new Error("Not connected");const ee=`host.${t.hostId}.rpc.${$}`,Y={...q??{},clientToken:t.clientToken},H=T.current.encode(JSON.stringify(Y));console.log(`[HOST/NATS] → ${$}`,q??"");const W=await c.current.request(ee,H,{timeout:(R==null?void 0:R.timeout)??1e4}),oe=JSON.parse(T.current.decode(W.data));return V(oe),console.log(`[HOST/NATS] ← ${$}`,oe),oe}if(P)return X(t.directUrl,"HTTP");if(F&&t.lanUrl)try{return await X(t.lanUrl,"LAN")}catch(ee){if(ee instanceof Error&&ee.message==="Unauthorized")throw ee;console.log("[HOST/LAN] failed, falling back to NATS:",ee),S(!1)}return le()},[t,P,F]),te=j.useCallback(($,q)=>{if(P)return L.current.add(q),()=>{L.current.delete(q)};if(c.current){const R=c.current.subscribe(`host-event.${$}.>`);let V=!1;return(async()=>{try{for await(const X of R){if(V)break;q({subject:X.subject,data:X.data})}}catch{}})(),()=>{V=!0,R.unsubscribe()}}return()=>{}},[t,P]);return b.jsx(Rx.Provider,{value:{connected:U,mode:ce,nc:r,request:D,subscribeEvents:te,activeHost:t,unauthorized:m},children:e})}function Hi(){const e=j.useContext(Rx);if(!e)throw new Error("useHostConnection must be used within HostConnectionProvider");return e}const mn=Vn.isNativePlatform()?ys("Device"):null;function Bu(e){const t=new Date(e),r=new Date,s=t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return t.toDateString()===r.toDateString()?s:`${t.toLocaleDateString(void 0,{month:"short",day:"numeric"})} ${s}`}const Mx={};function yE(e){for(const t of e)Mx[t.key]=t.label}function dd(e){return Mx[e]??e}const bE=()=>window.matchMedia("(max-width: 600px)").matches;function xE({task:e,lastEvent:t,onEdit:r,onDelete:s,onViewRun:l}){var le;const{request:u}=Hi(),[c,f]=j.useState(!1),[d,m]=j.useState(!1),[y,g]=j.useState(!1),x=j.useRef(null),w=(t==null?void 0:t.running_state)==="started",S=(((le=e.schedule_values)==null?void 0:le.length)??0)>0,T=e.schedule_type==="on_new_notification"||e.schedule_type==="on_new_sms",M=!!e.schedule_enabled&&!!e.schedule_type&&(S||T)?w?"var(--color-success)":(t==null?void 0:t.running_state)==="failed"?"var(--color-error)":"var(--color-success)":"var(--color-text-secondary)";j.useEffect(()=>{if(!d)return;function ee(Y){x.current&&!x.current.contains(Y.target)&&m(!1)}return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[d]);function P(){bE()?g(!0):m(ee=>!ee)}function F(){m(!1),g(!1)}async function ce(){if(F(),!!confirm("Abort this task?")){f(!0);try{await u("task.abort",{id:e.id})}catch(ee){console.error("Abort failed:",ee)}finally{f(!1)}}}async function U(){F();try{const ee=await u("task.run",{id:e.id});l(e.id,ee.run_id)}catch(ee){console.error("Run failed:",ee)}}async function D(){if(F(),!!confirm("Delete this task? Results and reports will be kept."))try{await u("task.delete",{id:e.id}),s(e.id)}catch(ee){console.error("Delete failed:",ee)}}const te={started:"Started",finished:"Finished",aborted:"Aborted",failed:"Failed"};function $(ee,Y){if(ee==="specific_times"){const xe=new Date(Y);return{kind:"specific_times",detail:isNaN(xe.getTime())?Y:`${xe.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} at ${xe.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"})}`}}const H=Y.split(" ");if(H.length!==5)return{kind:"unknown",detail:Y};const[W,oe,be,,k]=H,z=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];if(oe==="*")return{kind:"hourly",detail:""};const K=new Date;K.setHours(Number(oe),Number(W),0,0);const A=K.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"});return k!=="*"?{kind:"weekly",detail:`${z[Number(k)]??k} at ${A}`}:be!=="*"?{kind:"monthly",detail:`day ${be} at ${A}`}:{kind:"daily",detail:A}}function q(ee,Y){const H=$(ee,Y);return H.kind==="hourly"?"Every hour":H.kind==="specific_times"?`Once on ${H.detail}`:`${H.kind.charAt(0).toUpperCase()+H.kind.slice(1)}: ${H.detail}`}function R(ee,Y){if(!ee)return"";if(ee==="on_new_notification")return"On new notification";if(ee==="on_new_sms")return"On new SMS";if(!Y||Y.length===0)return"";if(Y.length===1)return q(ee,Y[0]);const H=Y.map(oe=>$(ee,oe));if(new Set(H.map(oe=>oe.kind)).size===1){const oe=H[0].kind;if(oe==="hourly")return"Every hour";const be=H.map(k=>k.detail);return`${oe.charAt(0).toUpperCase()+oe.slice(1)}: ${be.join(", ")}`}return Y.map(oe=>q(ee,oe)).join(", ")}const V=R(e.schedule_type,e.schedule_values),X=b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:()=>{F(),r(e)},children:[b.jsx("span",{className:"menu-icon",children:"✎"}),"Edit"]}),b.jsxs("button",{onClick:()=>{F(),l(e.id)},children:[b.jsx("span",{className:"menu-icon",children:"📄"}),"View All Runs"]}),w?b.jsxs("button",{className:"menu-item-danger",onClick:ce,disabled:c,children:[b.jsx("span",{className:"menu-icon",children:"◼"}),"Abort"]}):b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:U,children:[b.jsx("span",{className:"menu-icon",children:"▶"}),"Run Now"]}),b.jsxs("button",{className:"menu-item-danger",onClick:D,children:[b.jsx("span",{className:"menu-icon",children:"🗑"}),"Delete"]})]})]});return b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"task-card",onClick:()=>l(e.id,"latest"),children:[b.jsxs("div",{className:"task-card-header",children:[b.jsxs("div",{className:"task-card-title-row",children:[w?b.jsx("span",{className:"status-spinner",children:b.jsx("span",{})}):b.jsx("span",{className:"status-dot",style:{backgroundColor:M}}),b.jsx("h3",{className:"task-card-name",children:e.name||e.user_prompt})]}),b.jsx("div",{className:"task-card-actions",onClick:ee=>ee.stopPropagation(),children:b.jsxs("div",{className:"task-card-menu",ref:x,children:[b.jsx("button",{className:"task-card-menu-btn",onClick:P,"aria-label":"Task actions",children:"⋮"}),d&&b.jsx("div",{className:"task-card-menu-dropdown",children:X})]})})]}),b.jsxs("div",{className:"task-card-meta",children:[e.agent&&b.jsx("span",{className:"task-card-agent",children:dd(e.agent)}),t&&te[t.running_state]&&b.jsxs("span",{className:"task-card-last-event",children:[te[t.running_state]," ",Bu(t.time_stamp)]}),e.schedule_type&&(S||T)&&b.jsx("span",{className:"task-card-triggers",children:e.schedule_enabled?V:"Schedule disabled"})]})]}),y&&ds.createPortal(b.jsx("div",{className:"bottom-sheet-overlay",onClick:()=>g(!1),children:b.jsxs("div",{className:"bottom-sheet",onClick:ee=>ee.stopPropagation(),children:[b.jsx("div",{className:"bottom-sheet-handle"}),b.jsx("div",{className:"bottom-sheet-title",children:e.name||e.user_prompt}),b.jsx("div",{className:"bottom-sheet-actions",children:X})]})}),document.body)]})}function vE({permissions:e}){return b.jsxs("div",{className:"permissions-dialog",children:[b.jsx("h2",{children:"Granted Permissions"}),b.jsx("div",{className:"permissions-dialog-scroll",children:e&&e.length>0?b.jsx("div",{className:"permissions-section",children:b.jsx("ul",{className:"permissions-list",children:e.map((t,r)=>b.jsxs("li",{className:"permission-item",children:[b.jsx("span",{className:"permission-tool",children:t.name}),b.jsx("span",{className:"permission-desc",children:t.description})]},r))})}):b.jsx("p",{className:"permissions-empty",children:"No permissions have been granted for this task."})}),b.jsx("div",{className:"permissions-dialog-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>history.back(),children:"Back"})})]})}const ra=[];function wE(){const e=ra.pop();e&&(e.pushed.current=!1,e.close())}let H0=!1;function SE(){H0||(H0=!0,window.addEventListener("popstate",wE))}function md(e,t){const r=j.useRef(!1),s=j.useRef(t);s.current=t;const l=j.useCallback(()=>s.current(),[]),u=j.useRef({close:l,pushed:r});u.current.close=l,j.useEffect(()=>{if(e&&!r.current)SE(),history.pushState({modal:!0},""),ra.push(u.current),r.current=!0;else if(!e&&r.current){r.current=!1;const c=ra.indexOf(u.current);c!==-1&&ra.splice(c,1),history.back()}},[e,l]),j.useEffect(()=>{const c=u.current;return()=>{if(r.current){r.current=!1;const f=ra.indexOf(c);f!==-1&&ra.splice(f,1),history.back()}}},[])}const _E=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],kE=["specific_times","hourly","daily","weekly","monthly"];function mu(e){return kE.includes(e)}function EE(e){return e==="on_new_notification"||e==="on_new_sms"}function Wr(e="daily"){return{schedule:e,time:"00:00",dayOfWeek:"1",dayOfMonth:"1",onceDate:"",onceTime:"00:00"}}function CE(e){const t=e.split(" ");if(t.length!==5)return Wr();const[r,s,l,,u]=t;if(s==="*")return Wr("hourly");const c=`${s.padStart(2,"0")}:${r.padStart(2,"0")}`;return u!=="*"?{...Wr("weekly"),time:c,dayOfWeek:u}:l!=="*"?{...Wr("monthly"),time:c,dayOfMonth:l}:{...Wr("daily"),time:c}}function Dx(e,t){if(e==="specific_times"){const[r,s]=t.split("T");return{...Wr("specific_times"),onceDate:r??"",onceTime:(s??"09:00").slice(0,5)}}return CE(t)}function AE(e){const[t,r]=e.time.split(":").map(Number);switch(e.schedule){case"hourly":return"0 * * * *";case"daily":return`${r} ${t} * * *`;case"weekly":return`${r} ${t} * * ${e.dayOfWeek}`;case"monthly":return`${r} ${t} ${e.dayOfMonth} * *`;default:return"0 * * * *"}}function jE(e){return e.schedule==="specific_times"?e.onceDate?`${e.onceDate}T${e.onceTime}`:null:AE(e)}function Nh(e){return e==="specific_times"?"specific_times":e==="on_new_notification"?"on_new_notification":e==="on_new_sms"?"on_new_sms":"crons"}function Oh(e){var s;if(!e)return"daily";if(e.command)return"command";const t=e.schedule_type;if(t==="on_new_notification"||t==="on_new_sms")return t;if(t!=="crons"&&t!=="specific_times")return"ondemand";const r=(s=e.schedule_values)==null?void 0:s[0];return r?Dx(t,r).schedule:"ondemand"}function TE({initial:e,agents:t,hostPlatform:r,isNotificationListener:s,onSaved:l,onRun:u,onCancel:c}){var Ht;const{request:f,activeHost:d}=Hi(),{setHostLastAgent:m}=Pi(),y=()=>{var Ae;const de=d.lastAgent,Ie=t.map(Ot=>Ot.key);return de&&Ie.includes(de)?de:((Ae=t[0])==null?void 0:Ae.key)??""},[g,x]=j.useState((e==null?void 0:e.user_prompt)??""),[w,S]=j.useState((e==null?void 0:e.agent)??y()),T=!!((Ht=e==null?void 0:e.permissions)!=null&&Ht.length),[L,M]=j.useState(!1),P=j.useCallback(()=>M(!1),[]);md(L,P);const[F,ce]=j.useState(null),[U,D]=j.useState(()=>Oh(e)),[te,$]=j.useState(()=>{const de=e==null?void 0:e.schedule_type,Ie=e==null?void 0:e.schedule_values;if(Ie&&(de==="crons"||de==="specific_times"))return Ie.map(Ot=>Dx(de,Ot));const Ae=Oh(e);return mu(Ae)?[Wr(Ae)]:[]}),[q,R]=j.useState((e==null?void 0:e.requires_confirmation)??!1),[V,X]=j.useState(e!=null&&e.schedule_type?e.schedule_enabled??!0:!0),[le,ee]=j.useState((e==null?void 0:e.yolo_mode)??!1),[Y,H]=j.useState((e==null?void 0:e.foreground_mode)??!1),[W,oe]=j.useState((e==null?void 0:e.command)??""),[be,k]=j.useState(!1),z=(e==null?void 0:e.schedule_type)==="on_new_notification"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[K,A]=j.useState(z),[xe,_e]=j.useState([]),[je,Le]=j.useState(!1),[$e,Ce]=j.useState(!1),[Ne,Te]=j.useState(""),Fe=j.useCallback(()=>Ce(!1),[]);md($e,Fe),j.useEffect(()=>{if(U!=="on_new_notification"||!s||!Vn.isNativePlatform()||!mn)return;let de=!1;return Le(!0),mn.getInstalledApps().then(({apps:Ie})=>{if(de)return;const Ae="com.palmier.app",Ot=Ie.filter(Pt=>Pt.packageName!==Ae).sort((Pt,fn)=>(Pt.appName||Pt.packageName).localeCompare(fn.appName||fn.packageName));_e(Ot)}).catch(()=>{}).finally(()=>{de||Le(!1)}),()=>{de=!0}},[U,s]);const Qe=(e==null?void 0:e.schedule_type)==="on_new_sms"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[qe,ct]=j.useState(Qe),vt=j.useRef(null),Ve=mu(U),He=U==="command",nt=EE(U),ft=t.find(de=>de.key===w),rt=!!(ft!=null&&ft.supportsYolo);j.useEffect(()=>{!rt&&le&&ee(!1)},[rt,le]);const qt=!!e,Tt=Oh(e),ht=!qt||g!==((e==null?void 0:e.user_prompt)??"")||w!==((e==null?void 0:e.agent)??"")||U!==Tt||q!==((e==null?void 0:e.requires_confirmation)??!1)||V!==(e!=null&&e.schedule_type?e.schedule_enabled??!0:!0)||le!==((e==null?void 0:e.yolo_mode)??!1)||Y!==((e==null?void 0:e.foreground_mode)??!1)||He&&W!==((e==null?void 0:e.command)??"")||Ve&&(JSON.stringify(nn())!==JSON.stringify((e==null?void 0:e.schedule_values)??[])||Nh(U)!==((e==null?void 0:e.schedule_type)??void 0))||nt&&U!==(e==null?void 0:e.schedule_type)||U==="on_new_notification"&&K.trim()!==z.trim()||U==="on_new_sms"&&qe.trim()!==Qe.trim(),Fi=Ve&&te.some(de=>de.schedule==="specific_times"&&(!de.onceDate||new Date(`${de.onceDate}T${de.onceTime}`)<=new Date)),fe=ht&&!!g.trim()&&!Fi&&(!He||!!W.trim())&&(!Ve||te.length>0);function ve(de,Ie){$(Ae=>Ae.map((Ot,Pt)=>Pt===de?{...Ot,...Ie}:Ot))}function Ue(de){$(Ie=>Ie.filter((Ae,Ot)=>Ot!==de))}function Je(){mu(U)&&$(de=>[...de,de.length>0?{...de[de.length-1]}:Wr(U)])}function lt(de){D(de),mu(de)?$([Wr(de)]):($([]),R(!1)),de==="command"?setTimeout(()=>{var Ie;return(Ie=vt.current)==null?void 0:Ie.focus()},0):oe(""),de!=="on_new_notification"&&A(z),de!=="on_new_sms"&&ct(Qe)}function nn(){return te.flatMap(de=>{const Ie=jE(de);return Ie?[Ie]:[]})}function _n(){return le?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
|
|
89
89
|
|
|
90
|
-
Are you sure you want to continue?`):!0}async function Wt(){k(!0),ce(null);try{const de=Ve?nn():U==="on_new_notification"&&K.trim()?[K.trim()]:U==="on_new_sms"&&qe.trim()?[qe.trim()]:[],Ie=Ve||nt?Nh(U):null,Ae={user_prompt:g,agent:w,schedule_type:Ie,schedule_values:de.length>0?de:null,schedule_enabled:U!=="ondemand"&&V,requires_confirmation:Ve?q:!1,yolo_mode:le,foreground_mode:Y,command:He?W:""};qt&&(Ae.id=e.id);const Pt=await f(qt?"task.update":"task.create",Ae,{timeout:45e3});if(Pt.error){ce(Pt.error);return}if(qt||m(d.hostId,w),He&&!qt){l(Pt);try{const fn=await f("task.run",{id:Pt.id});fn.run_id?u(Pt.id,fn.run_id):fn.error||u(Pt.id)}catch{}return}l(Pt)}catch(de){ce(de instanceof Error?de.message:String(de))}finally{k(!1)}}const yt=qt?"Save":He?"Run":(Ve||nt)&&V?"Schedule":"Save";return b.jsxs("div",{className:"task-form-overlay",children:[b.jsx("div",{className:"task-form",children:L?b.jsx(vE,{permissions:e==null?void 0:e.permissions}):b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"task-form-header",children:b.jsx("h2",{children:e?"Edit Task":"New Task"})}),F&&b.jsx("div",{className:"form-error",children:F}),b.jsx("textarea",{autoFocus:!e,className:"form-textarea",value:g,onChange:de=>x(de.target.value),placeholder:He?"If the input email contains an event, create a calendar entry for it.":"Research today's top AI news and write a summary.",rows:4,disabled:be}),b.jsxs("div",{className:"plan-actions",children:[b.jsxs("div",{className:"agent-picker-section-inline",children:[b.jsx("span",{className:"agent-picker-label",children:"Run with"}),b.jsx("select",{className:"form-select form-select-sm",value:w,onChange:de=>S(de.target.value),disabled:be,children:t.map(de=>b.jsx("option",{value:de.key,children:de.label},de.key))})]}),rt&&b.jsxs("label",{className:"yolo-inline",style:{marginLeft:"auto"},children:[b.jsx("input",{type:"checkbox",checked:le,onChange:de=>ee(de.target.checked),disabled:be}),"Yolo"]}),rt&&le&&b.jsx("p",{className:"yolo-warning",children:"The agent will auto-approve all tool calls without asking for permission."}),T&&b.jsx("div",{className:"granted-permissions-row",children:b.jsx("button",{className:"btn btn-link",onClick:()=>M(!0),children:"Granted Permissions"})})]}),b.jsx("div",{className:"toggles-group",children:b.jsxs("div",{className:"schedule-section",children:[b.jsx("h3",{className:"schedule-section-title",children:"Schedule"}),b.jsxs("select",{className:"form-select",value:U,onChange:de=>lt(de.target.value),disabled:be,children:[b.jsx("option",{value:"ondemand",children:"On Demand"}),b.jsx("option",{value:"specific_times",children:"Specific Times"}),b.jsx("option",{value:"hourly",children:"Hourly"}),b.jsx("option",{value:"daily",children:"Daily"}),b.jsx("option",{value:"weekly",children:"Weekly"}),b.jsx("option",{value:"monthly",children:"Monthly"}),b.jsx("option",{value:"on_new_notification",children:"On New Notification"}),b.jsx("option",{value:"on_new_sms",children:"On New SMS"}),b.jsx("option",{value:"command",children:"Command-triggered"})]}),nt&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsxs("p",{className:"command-help-text",children:[U==="on_new_notification"?"Runs each time a new push notification arrives on the paired Android device.":"Runs each time a new SMS arrives on the paired Android device."," ","The triggering payload is spliced into your task prompt — reference it as “the new ",U==="on_new_notification"?"notification":"SMS","”."]}),U==="on_new_notification"&&(()=>{const de=xe.find(Ae=>Ae.packageName===K),Ie=(de==null?void 0:de.appName)||K;return b.jsxs(b.Fragment,{children:[s?K.trim()?b.jsxs("div",{className:"app-filter-selected",children:[b.jsx("span",{className:"app-filter-selected-name",children:Ie}),(de==null?void 0:de.appName)&&b.jsx("span",{className:"app-filter-selected-pkg",children:de.packageName}),b.jsx("button",{type:"button",className:"app-filter-selected-clear",onClick:()=>A(""),"aria-label":"Clear app filter",disabled:be,children:"✕"})]}):b.jsx("button",{type:"button",className:"btn btn-link app-filter-trigger",onClick:()=>{Te(""),Ce(!0)},disabled:be,children:"Select app"}):b.jsx("input",{className:"form-input",type:"text",value:K,onChange:Ae=>A(Ae.target.value),placeholder:"App (optional), e.g. com.google.android.gm",disabled:be}),b.jsx("p",{className:"command-help-text app-filter-help",children:K.trim()?`Only notifications from ${Ie} will trigger this task.`:"Every notification from your device triggers this task."})]})})(),U==="on_new_sms"&&b.jsxs(b.Fragment,{children:[b.jsx("input",{className:"form-input",type:"text",value:qe,onChange:de=>ct(de.target.value),placeholder:"From (optional), e.g. +1 555-1234)",disabled:be}),b.jsx("p",{className:"command-help-text app-filter-help",children:qe.trim()?`Only SMS from ${qe.trim()} will trigger this task. Formatting (spaces, dashes, parens) is ignored.`:"Every SMS that arrives on your device triggers this task."})]})]}),He&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsx("p",{className:"command-help-text",children:"Runs a command and invokes the task for each line of output. Use “the input” in your task description to reference each line."}),b.jsx("input",{ref:vt,className:"form-input form-input-mono",type:"text",value:W,onChange:de=>oe(de.target.value),placeholder:"gws gmail +watch --project my-project",disabled:be})]}),Ve&&U!=="hourly"&&b.jsxs(b.Fragment,{children:[te.map((de,Ie)=>b.jsxs("div",{className:"trigger-row-card",children:[b.jsxs("div",{className:"trigger-row-content",children:[U==="daily"&&b.jsx("input",{className:"form-input",type:"time",value:de.time,onChange:Ae=>ve(Ie,{time:Ae.target.value})}),U==="weekly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:de.dayOfWeek,onChange:Ae=>ve(Ie,{dayOfWeek:Ae.target.value}),children:_E.map((Ae,Ot)=>b.jsx("option",{value:String(Ot),children:Ae},Ot))}),b.jsx("input",{className:"form-input",type:"time",value:de.time,onChange:Ae=>ve(Ie,{time:Ae.target.value})})]}),U==="monthly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:de.dayOfMonth,onChange:Ae=>ve(Ie,{dayOfMonth:Ae.target.value}),children:Array.from({length:28},(Ae,Ot)=>Ot+1).map(Ae=>b.jsxs("option",{value:String(Ae),children:["Day ",Ae]},Ae))}),b.jsx("input",{className:"form-input",type:"time",value:de.time,onChange:Ae=>ve(Ie,{time:Ae.target.value})})]}),U==="specific_times"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("input",{className:"form-input",type:"date",value:de.onceDate,min:new Date().toISOString().split("T")[0],onChange:Ae=>ve(Ie,{onceDate:Ae.target.value})}),b.jsx("input",{className:"form-input",type:"time",value:de.onceTime,min:de.onceDate===new Date().toISOString().split("T")[0]?new Date().toTimeString().slice(0,5):void 0,onChange:Ae=>ve(Ie,{onceTime:Ae.target.value})})]})]}),te.length>1&&b.jsx("button",{className:"trigger-remove-btn",onClick:()=>Ue(Ie),title:"Remove trigger",children:"×"})]},Ie)),b.jsx("button",{className:"trigger-add-btn",onClick:Je,children:"+ Add"})]}),r==="win32"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:Y,onChange:de=>H(de.target.checked),disabled:be}),"Run in the foreground (host must login to Windows)"]}),Ve&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:q,onChange:de=>R(de.target.checked),disabled:be}),"Confirm before each run"]}),U!=="ondemand"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:V,onChange:de=>X(de.target.checked),disabled:be}),"Enabled"]})]})}),!le&&ft&&!ft.supportsPermissions&&b.jsxs("div",{className:"form-warning",children:["Palmier does not support runtime permission granting for ",ft.label,". The task may fail if required permissions are not pre-configured."]}),b.jsxs("div",{className:"form-actions",children:[b.jsxs("button",{className:"btn btn-primary",onClick:()=>_n()&&Wt(),disabled:!fe||be,children:[be&&b.jsx("span",{className:"btn-spinner"}),yt]}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{ht&&g.trim()&&!confirm("You have unsaved changes. Discard?")||c()},style:{marginLeft:"auto"},children:"Cancel"})]})]})}),$e&&(()=>{const de=Ne.trim().toLowerCase(),Ie=de?xe.filter(Ae=>Ae.packageName.toLowerCase().includes(de)||Ae.appName.toLowerCase().includes(de)):xe;return b.jsx("div",{className:"app-filter-overlay",onClick:Fe,children:b.jsxs("div",{className:"app-filter-dialog",onClick:Ae=>Ae.stopPropagation(),children:[b.jsxs("div",{className:"app-filter-header",children:[b.jsx("h2",{children:"Select app"}),b.jsx("button",{className:"app-filter-close",onClick:Fe,"aria-label":"Close",children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:b.jsx("path",{d:"M4 4L12 12M12 4L4 12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]}),b.jsx("input",{className:"form-input app-filter-search",type:"text",value:Ne,onChange:Ae=>Te(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&Ne.trim()&&(A(Ne.trim()),Fe())},placeholder:"Search or type a package name",autoFocus:!0}),b.jsxs("ul",{className:"app-filter-list",children:[je&&xe.length===0?Array.from({length:6}).map((Ae,Ot)=>b.jsx("li",{className:"app-filter-row app-filter-skeleton",children:b.jsx("div",{className:"app-filter-skeleton-bar"})},`sk-${Ot}`)):Ie.length===0&&!Ne.trim()?b.jsx("li",{className:"app-filter-empty",children:"No apps"}):Ie.map(Ae=>b.jsx("li",{className:"app-filter-row",onClick:()=>{A(Ae.packageName),Fe()},children:b.jsxs("div",{className:"app-filter-row-labels",children:[b.jsx("div",{className:"app-filter-row-name",children:Ae.appName||Ae.packageName}),Ae.appName&&b.jsx("div",{className:"app-filter-row-pkg",children:Ae.packageName})]})},Ae.packageName)),Ne.trim()&&b.jsx("li",{className:"app-filter-row",onClick:()=>{A(Ne.trim()),Fe()},children:b.jsx("div",{className:"app-filter-row-labels",children:b.jsx("div",{className:"app-filter-row-name",children:Ne.trim()})})})]})]})})})()]})}function Lx({pullDistance:e,refreshing:t,threshold:r}){const s=e>0||t,l=e>=r;return b.jsx("div",{className:"pull-to-refresh",style:{transform:`translateY(${e}px)`,opacity:s?Math.min(1,e/30):0},"aria-hidden":!s,children:b.jsx("div",{className:"pull-to-refresh-badge",children:t?b.jsx("div",{className:"spinner"}):b.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.25",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"},children:[b.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b.jsx("polyline",{points:"19 12 12 19 5 12"})]})})})}function zx({onRefresh:e,threshold:t=70,maxPull:r=110,enabled:s=!0}){const[l,u]=j.useState(0),[c,f]=j.useState(!1),d=j.useRef(null),m=j.useRef(!1),y=j.useRef(0),g=j.useRef(!1),x=j.useRef(e);return j.useEffect(()=>{x.current=e}),j.useEffect(()=>{if(!s)return;const w=L=>{if(g.current||window.scrollY>0){d.current=null;return}d.current=L.touches[0].clientY,m.current=!1,y.current=0},S=L=>{if(g.current||d.current==null)return;const M=L.touches[0].clientY-d.current;if(M<=0){m.current=!1,y.current=0,u(0);return}m.current=!0;const P=Math.min(r,M*.5);y.current=P,u(P),L.cancelable&&L.preventDefault()},T=()=>{if(!m.current){d.current=null,u(0);return}const L=y.current;d.current=null,m.current=!1,y.current=0,L>=t?(g.current=!0,f(!0),u(t),Promise.resolve(x.current()).catch(()=>{}).finally(()=>{g.current=!1,f(!1),u(0)})):u(0)};return window.addEventListener("touchstart",w,{passive:!0}),window.addEventListener("touchmove",S,{passive:!1}),window.addEventListener("touchend",T,{passive:!0}),window.addEventListener("touchcancel",T,{passive:!0}),()=>{window.removeEventListener("touchstart",w),window.removeEventListener("touchmove",S),window.removeEventListener("touchend",T),window.removeEventListener("touchcancel",T)}},[s,t,r]),{pullDistance:l,refreshing:c,threshold:t}}function NE({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,isNotificationListener:c,onViewRun:f}){const[d,m]=j.useState([]),[y,g]=j.useState(!1),[x,w]=j.useState(null),[S,T]=j.useState(new Map),[L,M]=j.useState(!1),[P,F]=j.useState(void 0),ce=j.useCallback(()=>{M(!1),F(void 0)},[]),U=j.useCallback(async()=>{if(e){g(!0),w(null);try{const R=(await r("task.list")).tasks??[],V=new Map;for(const X of R)X.status&&V.set(X.id,X.status);T(V),m(R)}catch(q){const R=q instanceof Error?q.message:String(q);R==="Not connected"||R.includes("503")||R.toLowerCase().includes("no responders")?w(null):w(R),m([])}finally{g(!1)}}},[e,t,r]);j.useEffect(()=>{e?U():(m([]),g(!1))},[e,t,U]);const D=zx({onRefresh:U,enabled:e});j.useEffect(()=>!e||!t?void 0:s(t,async R=>{const V=R.subject.split(".");if(V.length<3)return;const X=V.slice(2).join(".");let le={};try{le=JSON.parse(new TextDecoder().decode(R.data))}catch{return}const ee=le.event_type;if(!(ee!=="running-state"&&ee!=="permission-resolved"))try{const Y=await r("task.status",{id:X},{timeout:5e3});if(Y.error)return;T(H=>{const W=new Map(H);return W.set(X,Y),W})}catch{}}),[e,t,s,r]);function te(q){m(R=>{const V=R.findIndex(X=>X.id===q.id);if(V>=0){const X=[...R];return X[V]=q,X}return[q,...R]}),M(!1),F(void 0)}function $(q){m(R=>R.filter(V=>V.id!==q)),T(R=>{const V=new Map(R);return V.delete(q),V})}return b.jsxs(b.Fragment,{children:[b.jsx(Lx,{pullDistance:D.pullDistance,refreshing:D.refreshing,threshold:D.threshold}),x&&b.jsxs("div",{className:"form-error",children:[x,x.toLowerCase().includes("failed to fetch")&&b.jsxs(b.Fragment,{children:[" ",b.jsx("a",{href:"#",onClick:q=>{q.preventDefault(),window.location.reload()},children:"Reload"})]})]}),y&&!d.length?b.jsx("div",{className:"task-list",children:[0,1,2].map(q=>b.jsxs("div",{className:"task-card",style:{pointerEvents:"none"},children:[b.jsx("div",{className:"task-card-header",children:b.jsxs("div",{className:"task-card-title-row",children:[b.jsx("div",{className:"skeleton-line",style:{width:10,height:10,borderRadius:"50%"}}),b.jsx("div",{className:"skeleton-line",style:{width:`${60+q*12}%`}})]})}),b.jsxs("div",{className:"task-card-meta",children:[b.jsx("div",{className:"skeleton-line",style:{width:"30%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"25%"}})]})]},q))}):d.length===0?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No tasks yet"}),b.jsx("p",{className:"empty-state-hint",children:"Tap the + button to create your first task."})]}):b.jsx("div",{className:"task-list",children:d.map(q=>b.jsx(xE,{task:q,lastEvent:S.get(q.id),onEdit:async R=>{try{const V=await r("task.get",{id:R.id});F(V.error?R:V)}catch{F(R)}M(!0)},onDelete:$,onViewRun:f},q.id))}),b.jsx("button",{className:"fab",onClick:()=>{F(void 0),M(!0)},"aria-label":"New task",title:"New task",children:b.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),L&&b.jsx(TE,{initial:P,agents:l,hostPlatform:u,isNotificationListener:c,onSaved:te,onRun:f,onCancel:ce})]})}let ha=null;function I0(e){ha&&(e.preventDefault(),e.returnValue="")}function Rh(e){const t=!!ha;ha=e;const r=!!ha;r&&!t?window.addEventListener("beforeunload",I0):!r&&t&&window.removeEventListener("beforeunload",I0)}function ps(){return ha?window.confirm(ha):!0}function OE(){const e=Or(),t=or(),{hostId:r}=Yu(),s=t.pathname.endsWith("/tasks"),l=!s;function u(c){ps()&&r&&e(`/hosts/${encodeURIComponent(r)}${c}`)}return b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:`tab-btn ${l?"tab-btn-active":""}`,onClick:()=>u(""),children:[b.jsx("svg",{className:"tab-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M2 8H4.5L6 4L8 12L10 6L11.5 8H14"})}),"Sessions"]}),b.jsxs("button",{className:`tab-btn ${s?"tab-btn-active":""}`,onClick:()=>u("/tasks"),children:[b.jsxs("svg",{className:"tab-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),b.jsx("path",{d:"M5.5 8L7 9.5L10.5 6"})]}),"Tasks"]})]})}function Ux(e){const[t,r]=j.useState(()=>window.matchMedia(e).matches);return j.useEffect(()=>{const s=window.matchMedia(e),l=u=>r(u.matches);return s.addEventListener("change",l),r(s.matches),()=>s.removeEventListener("change",l)},[e]),t}const ku=Vn.isNativePlatform(),RE=["Device","Data","Messaging"],ME=[{capability:"sms-read",label:"Read SMS",group:"Messaging"},{capability:"sms-send",label:"Send SMS",group:"Messaging"},{capability:"send-email",label:"Send Email",group:"Messaging"},{capability:"notifications",label:"Notifications from Other Apps",group:"Data"},{capability:"contacts",label:"Manage Contacts",group:"Data"},{capability:"calendar",label:"Manage Calendar",group:"Data"},{capability:"location",label:"Get Location",group:"Device"},{capability:"dnd",label:"Set Ringer Mode",group:"Device"},{capability:"alarm",label:"Trigger Alarms",group:"Device"}];async function DE(){if(!ku||!mn)return new Set;try{const{capabilities:e}=await mn.getCapabilityStatus();return new Set(e.filter(t=>t.enabled).map(t=>t.name))}catch{return new Set}}function Bx({onChange:e,confirmDisable:t=!1}){const[r,s]=j.useState(new Map),[l,u]=j.useState(null),[c,f]=j.useState(null),d=j.useCallback(async()=>{if(!(!ku||!mn))try{const{capabilities:S}=await mn.getCapabilityStatus(),T=new Map;for(const L of S)T.set(L.name,L);s(T),e==null||e(new Set(S.filter(L=>L.enabled).map(L=>L.name)))}catch(S){console.error("Failed to read capability status:",S)}},[e]);j.useEffect(()=>{d()},[d]),j.useEffect(()=>{if(!ku)return;const S=hd.addListener("resume",d);return()=>{S.then(T=>T.remove())}},[d]);async function m(S,T){if(mn){u(S.capability);try{const L=await mn.setCapabilityEnabled({capability:S.capability,enabled:T});!L.enabled&&L.reason==="no-email-client"&&alert("No email app is installed on this device. Install one (e.g. Gmail) before enabling Send Email."),await d()}catch(L){console.error(`Failed to toggle ${S.capability}:`,L)}finally{u(null)}}}function y(S){const T=r.get(S.capability);if(T){if(T.enabled&&t){f(S);return}m(S,!T.enabled)}}function g(){const S=c;S&&(f(null),m(S,!1))}if(!ku)return null;const x=RE.map(S=>({group:S,items:ME.filter(T=>{const L=r.get(T.capability);return T.group===S&&(L==null?void 0:L.supported)})})).filter(S=>S.items.length>0);if(x.length===0)return b.jsx("div",{className:"capability-toggles-loading",children:b.jsx("span",{className:"spinner"})});const w=c&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>f(null),children:b.jsxs("div",{className:"confirm-modal",onClick:S=>S.stopPropagation(),children:[b.jsxs("h2",{className:"confirm-modal-title",children:["Disable ",c.label,"?"]}),b.jsxs("p",{className:"confirm-modal-message",children:["All hosts linked to this device will no longer be able to use ",c.label,"."]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>f(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:g,children:"Disable"})]})]})}),document.body);return b.jsxs(b.Fragment,{children:[x.map(({group:S,items:T},L)=>b.jsx("div",{className:L>0?"drawer-toggle-group drawer-toggle-group-divided":"drawer-toggle-group",children:T.map(M=>{const P=r.get(M.capability),F=!!(P!=null&&P.enabled);return b.jsxs("label",{className:"drawer-toggle",children:[b.jsx("span",{className:"drawer-toggle-label",children:M.label}),b.jsx("button",{className:`toggle-switch ${F?"toggle-switch-on":""}`,onClick:()=>y(M),disabled:l===M.capability,role:"switch","aria-checked":F,children:b.jsx("span",{className:"toggle-switch-thumb"})})]},M.capability)})},S)),w]})}const F0=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),LE=Vn.isNativePlatform();function $0({daemonVersion:e,linkedClientToken:t,request:r,onEnabledCapabilitiesChange:s,onLinkedClientTokenChange:l}){var Ce;const{pairedHosts:u,removePairedHost:c,renamePairedHost:f}=Pi(),{activeHost:d}=Hi(),m=Or(),y=or(),x=Yu().hostId??null,w=d.clientToken||null,S=!!w&&t===w,T=Ux("(min-width: 768px)"),[L,M]=j.useState(!1);async function P(){if(!(!mn||!r||!w)){M(!0);try{const{token:Ne}=await mn.getFcmToken();if(!Ne)return;await r("device.link",{fcmToken:Ne}),l==null||l(w)}catch(Ne){console.error("Failed to make this the linked device:",Ne)}finally{M(!1)}}}async function F(Ne){const Te=Ne===x;if(Te&&r)try{await r("clients.revoke_self")}catch{}c(Ne),ee(null),Te&&m("/",{replace:!0})}function ce(Ne){const Fe=y.pathname.endsWith("/tasks")?"/tasks":"";m(`/hosts/${encodeURIComponent(Ne)}${Fe}`)}const[U,D]=j.useState(!1),[te,$]=j.useState(!1),[q,R]=j.useState(null),[V,X]=j.useState(""),[le,ee]=j.useState(null),[Y,H]=j.useState(!1),W=j.useRef(null),oe=j.useRef(null),be=j.useCallback(()=>{$(!0)},[]);function k(){te&&(D(!1),$(!1))}function z(){$(!1),D(!0)}function K(Ne,Te){R(Ne),X(Te)}function A(){q&&V.trim()&&f(q,V.trim()),R(null),X("")}function xe(){R(null),X("")}j.useEffect(()=>{q&&oe.current&&(oe.current.focus(),oe.current.select())},[q]),j.useEffect(()=>{if(!U||te)return;function Ne(Te){Te.key==="Escape"&&be()}return document.addEventListener("keydown",Ne),()=>{document.removeEventListener("keydown",Ne)}},[U,te,be]);const _e=b.jsxs(b.Fragment,{children:[!T&&b.jsx("button",{className:"drawer-close-btn",onClick:be,"aria-label":"Close menu",children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:b.jsx("path",{d:"M4 4L12 12M12 4L4 12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),!F0&&u.length>0&&b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Hosts"}),b.jsx("div",{className:"host-picker-inline",children:b.jsx("div",{className:"host-picker-list",role:"listbox",children:u.map(Ne=>{const Te=Ne.hostId===x,Fe=q===Ne.hostId,Qe=Ne.name||Ne.hostId.slice(0,8);return b.jsx("div",{className:"host-picker-item-wrapper",children:b.jsxs("div",{className:`host-picker-item ${Te?"host-picker-item-active":""}`,onClick:()=>{if(!Fe&&!Te){if(!ps())return;ce(Ne.hostId),T||be()}},role:"option","aria-selected":Te,children:[Fe?b.jsx("input",{ref:oe,className:"form-input host-picker-rename-input",type:"text",value:V,onChange:qe=>X(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&A(),qe.key==="Escape"&&xe()},onBlur:A,onClick:qe=>qe.stopPropagation()}):b.jsx("span",{className:"host-picker-item-name",children:Qe}),b.jsxs("div",{className:"host-picker-item-actions",children:[Te&&!Fe&&b.jsx("button",{className:"host-picker-edit-btn",onClick:qe=>{qe.stopPropagation(),K(Ne.hostId,Qe)},"aria-label":"Rename host",children:b.jsx("svg",{width:"13",height:"13",viewBox:"0 0 13 13",fill:"none",children:b.jsx("path",{d:"M9.5 1.5L11.5 3.5M1.5 11.5L2 9L9 2L11 4L4 11L1.5 11.5Z",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}),!Te&&b.jsx("button",{className:"host-picker-delete-btn",onClick:qe=>{qe.stopPropagation(),ee(Ne.hostId)},"aria-label":`Unpair ${Qe}`,children:b.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:b.jsx("path",{d:"M4 5.5V11C4 11.2761 4.22386 11.5 4.5 11.5H9.5C9.77614 11.5 10 11.2761 10 11V5.5M3 4H11M5.5 4V3C5.5 2.72386 5.72386 2.5 6 2.5H8C8.27614 2.5 8.5 2.72386 8.5 3V4M6.5 6.5V9.5M7.5 6.5V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})},Ne.hostId)})})})]}),!F0&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsx("div",{className:"drawer-section",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:()=>{ps()&&(m("/pair"),T||be())},children:"Add New Host"})})]}),LE&&r&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Device Capabilities"}),S?b.jsx(Bx,{onChange:s,confirmDisable:!0}):b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"drawer-section-hint",children:"This device isn't the linked device for the host, so it can't provide capabilities (SMS, contacts, location, etc.)."}),b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>{t&&t!==w?H(!0):P()},disabled:L,children:L?"Linking…":"Link the host to this device"})]})]})]}),b.jsxs("div",{className:"drawer-footer",children:[e&&b.jsxs("div",{className:"drawer-version",children:["Palmier v",e]}),b.jsxs("div",{className:"drawer-legal",children:[b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms"}),b.jsx("span",{className:"drawer-legal-sep",children:"·"}),b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy"})]})]})]}),je=!!le&&le===x&&S,Le=le&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>ee(null),children:b.jsxs("div",{className:"confirm-modal",onClick:Ne=>Ne.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove host?"}),b.jsxs("p",{className:"confirm-modal-message",children:['"',((Ce=u.find(Ne=>Ne.hostId===le))==null?void 0:Ce.name)||le.slice(0,8),'" will be ',je?"removed and unlinked":"removed",".",je&&b.jsx(b.Fragment,{children:" This device is currently linked to the host — unlinking will revoke its access to all device capabilities (SMS, contacts, location, etc.) until another device is linked."})]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>ee(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:()=>F(le),children:"Remove"})]})]})}),document.body),$e=Y&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>H(!1),children:b.jsxs("div",{className:"confirm-modal",onClick:Ne=>Ne.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>H(!1),children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:()=>{H(!1),P()},children:"Link"})]})]})}),document.body);return T?b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-panel drawer-panel-desktop",ref:W,children:_e}),Le,$e]}):b.jsxs(b.Fragment,{children:[b.jsx("button",{className:"hamburger-btn",onClick:z,"aria-label":"Open menu",children:b.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:b.jsx("path",{d:"M3 5H17M3 10H17M3 15H17",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),U&&ds.createPortal(b.jsx("div",{className:`drawer-overlay ${te?"drawer-overlay-closing":""}`,onClick:be,onAnimationEnd:k,children:b.jsx("div",{className:`drawer-panel ${te?"drawer-panel-closing":""}`,ref:W,onClick:Ne=>Ne.stopPropagation(),children:_e})}),document.body),Le,$e]})}const zE=Vn.isNativePlatform(),Fd={width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function UE(){return b.jsxs("svg",{...Fd,"aria-hidden":"true",children:[b.jsx("path",{d:"M5 12.55a11 11 0 0 1 14.08 0"}),b.jsx("path",{d:"M1.42 9a16 16 0 0 1 21.16 0"}),b.jsx("path",{d:"M8.53 16.11a6 6 0 0 1 6.95 0"}),b.jsx("line",{x1:"12",y1:"20",x2:"12.01",y2:"20"})]})}function Y0(){return b.jsxs("svg",{...Fd,"aria-hidden":"true",children:[b.jsx("circle",{cx:"12",cy:"12",r:"10"}),b.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),b.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}function BE(){return b.jsxs("svg",{...Fd,"aria-hidden":"true",children:[b.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),b.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),b.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function PE(){const{mode:e}=Hi(),[t,r]=j.useState(!1),s=j.useRef(null);if(j.useEffect(()=>{if(!t)return;function f(m){var y;(y=s.current)!=null&&y.contains(m.target)||r(!1)}document.addEventListener("pointerdown",f);const d=window.setTimeout(()=>r(!1),3e3);return()=>{document.removeEventListener("pointerdown",f),clearTimeout(d)}},[t]),e==="direct")return null;let l,u,c;switch(e){case"lan":l=b.jsx(UE,{}),u="Connected via LAN",c="lan";break;case"nats":l=b.jsx(Y0,{}),u=zE?"Connected via relay":"Connected",c="relay";break;case"disconnected":l=b.jsx(BE,{}),u="Disconnected",c="disconnected";break;case"connecting":default:l=b.jsx(Y0,{}),u="Connecting…",c="connecting";break}return b.jsxs("div",{ref:s,className:`conn-status conn-status--${c}`,children:[b.jsx("button",{type:"button",className:"conn-status-btn","aria-label":u,onClick:()=>r(f=>!f),children:l}),b.jsx("div",{className:`conn-status-popover ${t?"conn-status-popover--open":""}`,role:"tooltip",children:u})]})}function G0(e,t){var s;const r=e.map(l=>l.key);return t&&r.includes(t)?t:((s=e[0])==null?void 0:s.key)??""}function qE({agents:e,hostPlatform:t,onStarted:r}){const{request:s,activeHost:l}=Hi(),{setHostLastAgent:u}=Pi(),[c,f]=j.useState(""),[d,m]=j.useState(()=>G0(e,l.lastAgent)),[y,g]=j.useState(!1),[x,w]=j.useState(!1),[S,T]=j.useState(null);j.useEffect(()=>{e.length&&(e.find(D=>D.key===d)||m(G0(e,l.lastAgent)))},[e,d,l.lastAgent]),j.useEffect(()=>{const D=c.trim().length>0;return Rh(D?"Your session draft will be lost. Continue?":null),()=>Rh(null)},[c]);const L=e.find(D=>D.key===d),M=!!(L!=null&&L.supportsYolo);j.useEffect(()=>{!M&&y&&g(!1)},[M,y]);const P=!!c.trim()&&!!d&&!x;function F(){return y?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
|
|
90
|
+
Are you sure you want to continue?`):!0}async function Wt(){k(!0),ce(null);try{const de=Ve?nn():U==="on_new_notification"&&K.trim()?[K.trim()]:U==="on_new_sms"&&qe.trim()?[qe.trim()]:[],Ie=Ve||nt?Nh(U):null,Ae={user_prompt:g,agent:w,schedule_type:Ie,schedule_values:de.length>0?de:null,schedule_enabled:U==="ondemand"?!0:V,requires_confirmation:Ve?q:!1,yolo_mode:le,foreground_mode:Y,command:He?W:""};qt&&(Ae.id=e.id);const Pt=await f(qt?"task.update":"task.create",Ae,{timeout:45e3});if(Pt.error){ce(Pt.error);return}if(qt||m(d.hostId,w),He&&!qt){l(Pt);try{const fn=await f("task.run",{id:Pt.id});fn.run_id?u(Pt.id,fn.run_id):fn.error||u(Pt.id)}catch{}return}l(Pt)}catch(de){ce(de instanceof Error?de.message:String(de))}finally{k(!1)}}const yt=qt?"Save":He?"Run":(Ve||nt)&&V?"Schedule":"Save";return b.jsxs("div",{className:"task-form-overlay",children:[b.jsx("div",{className:"task-form",children:L?b.jsx(vE,{permissions:e==null?void 0:e.permissions}):b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"task-form-header",children:b.jsx("h2",{children:e?"Edit Task":"New Task"})}),F&&b.jsx("div",{className:"form-error",children:F}),b.jsx("textarea",{autoFocus:!e,className:"form-textarea",value:g,onChange:de=>x(de.target.value),placeholder:He?"If the input email contains an event, create a calendar entry for it.":"Research today's top AI news and write a summary.",rows:4,disabled:be}),b.jsxs("div",{className:"plan-actions",children:[b.jsxs("div",{className:"agent-picker-section-inline",children:[b.jsx("span",{className:"agent-picker-label",children:"Run with"}),b.jsx("select",{className:"form-select form-select-sm",value:w,onChange:de=>S(de.target.value),disabled:be,children:t.map(de=>b.jsx("option",{value:de.key,children:de.label},de.key))})]}),rt&&b.jsxs("label",{className:"yolo-inline",style:{marginLeft:"auto"},children:[b.jsx("input",{type:"checkbox",checked:le,onChange:de=>ee(de.target.checked),disabled:be}),"Yolo"]}),rt&&le&&b.jsx("p",{className:"yolo-warning",children:"The agent will auto-approve all tool calls without asking for permission."}),T&&b.jsx("div",{className:"granted-permissions-row",children:b.jsx("button",{className:"btn btn-link",onClick:()=>M(!0),children:"Granted Permissions"})})]}),b.jsx("div",{className:"toggles-group",children:b.jsxs("div",{className:"schedule-section",children:[b.jsx("h3",{className:"schedule-section-title",children:"Schedule"}),b.jsxs("select",{className:"form-select",value:U,onChange:de=>lt(de.target.value),disabled:be,children:[b.jsx("option",{value:"ondemand",children:"On Demand"}),b.jsx("option",{value:"specific_times",children:"Specific Times"}),b.jsx("option",{value:"hourly",children:"Hourly"}),b.jsx("option",{value:"daily",children:"Daily"}),b.jsx("option",{value:"weekly",children:"Weekly"}),b.jsx("option",{value:"monthly",children:"Monthly"}),b.jsx("option",{value:"on_new_notification",children:"On New Notification"}),b.jsx("option",{value:"on_new_sms",children:"On New SMS"}),b.jsx("option",{value:"command",children:"Command-triggered"})]}),nt&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsxs("p",{className:"command-help-text",children:[U==="on_new_notification"?"Runs each time a new push notification arrives on the paired Android device.":"Runs each time a new SMS arrives on the paired Android device."," ","The triggering payload is spliced into your task prompt — reference it as “the new ",U==="on_new_notification"?"notification":"SMS","”."]}),U==="on_new_notification"&&(()=>{const de=xe.find(Ae=>Ae.packageName===K),Ie=(de==null?void 0:de.appName)||K;return b.jsxs(b.Fragment,{children:[s?K.trim()?b.jsxs("div",{className:"app-filter-selected",children:[b.jsx("span",{className:"app-filter-selected-name",children:Ie}),(de==null?void 0:de.appName)&&b.jsx("span",{className:"app-filter-selected-pkg",children:de.packageName}),b.jsx("button",{type:"button",className:"app-filter-selected-clear",onClick:()=>A(""),"aria-label":"Clear app filter",disabled:be,children:"✕"})]}):b.jsx("button",{type:"button",className:"btn btn-link app-filter-trigger",onClick:()=>{Te(""),Ce(!0)},disabled:be,children:"Select app"}):b.jsx("input",{className:"form-input",type:"text",value:K,onChange:Ae=>A(Ae.target.value),placeholder:"App (optional), e.g. com.google.android.gm",disabled:be}),b.jsx("p",{className:"command-help-text app-filter-help",children:K.trim()?`Only notifications from ${Ie} will trigger this task.`:"Every notification from your device triggers this task."})]})})(),U==="on_new_sms"&&b.jsxs(b.Fragment,{children:[b.jsx("input",{className:"form-input",type:"text",value:qe,onChange:de=>ct(de.target.value),placeholder:"From (optional), e.g. +1 555-1234)",disabled:be}),b.jsx("p",{className:"command-help-text app-filter-help",children:qe.trim()?`Only SMS from ${qe.trim()} will trigger this task. Formatting (spaces, dashes, parens) is ignored.`:"Every SMS that arrives on your device triggers this task."})]})]}),He&&b.jsxs("div",{className:"schedule-reactive",children:[b.jsx("p",{className:"command-help-text",children:"Runs a command and invokes the task for each line of output. Use “the input” in your task description to reference each line."}),b.jsx("input",{ref:vt,className:"form-input form-input-mono",type:"text",value:W,onChange:de=>oe(de.target.value),placeholder:"gws gmail +watch --project my-project",disabled:be})]}),Ve&&U!=="hourly"&&b.jsxs(b.Fragment,{children:[te.map((de,Ie)=>b.jsxs("div",{className:"trigger-row-card",children:[b.jsxs("div",{className:"trigger-row-content",children:[U==="daily"&&b.jsx("input",{className:"form-input",type:"time",value:de.time,onChange:Ae=>ve(Ie,{time:Ae.target.value})}),U==="weekly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:de.dayOfWeek,onChange:Ae=>ve(Ie,{dayOfWeek:Ae.target.value}),children:_E.map((Ae,Ot)=>b.jsx("option",{value:String(Ot),children:Ae},Ot))}),b.jsx("input",{className:"form-input",type:"time",value:de.time,onChange:Ae=>ve(Ie,{time:Ae.target.value})})]}),U==="monthly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:de.dayOfMonth,onChange:Ae=>ve(Ie,{dayOfMonth:Ae.target.value}),children:Array.from({length:28},(Ae,Ot)=>Ot+1).map(Ae=>b.jsxs("option",{value:String(Ae),children:["Day ",Ae]},Ae))}),b.jsx("input",{className:"form-input",type:"time",value:de.time,onChange:Ae=>ve(Ie,{time:Ae.target.value})})]}),U==="specific_times"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("input",{className:"form-input",type:"date",value:de.onceDate,min:new Date().toISOString().split("T")[0],onChange:Ae=>ve(Ie,{onceDate:Ae.target.value})}),b.jsx("input",{className:"form-input",type:"time",value:de.onceTime,min:de.onceDate===new Date().toISOString().split("T")[0]?new Date().toTimeString().slice(0,5):void 0,onChange:Ae=>ve(Ie,{onceTime:Ae.target.value})})]})]}),te.length>1&&b.jsx("button",{className:"trigger-remove-btn",onClick:()=>Ue(Ie),title:"Remove trigger",children:"×"})]},Ie)),b.jsx("button",{className:"trigger-add-btn",onClick:Je,children:"+ Add"})]}),r==="win32"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:Y,onChange:de=>H(de.target.checked),disabled:be}),"Run in the foreground (host must login to Windows)"]}),Ve&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:q,onChange:de=>R(de.target.checked),disabled:be}),"Confirm before each run"]}),U!=="ondemand"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:V,onChange:de=>X(de.target.checked),disabled:be}),"Enabled"]})]})}),!le&&ft&&!ft.supportsPermissions&&b.jsxs("div",{className:"form-warning",children:["Palmier does not support runtime permission granting for ",ft.label,". The task may fail if required permissions are not pre-configured."]}),b.jsxs("div",{className:"form-actions",children:[b.jsxs("button",{className:"btn btn-primary",onClick:()=>_n()&&Wt(),disabled:!fe||be,children:[be&&b.jsx("span",{className:"btn-spinner"}),yt]}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{ht&&g.trim()&&!confirm("You have unsaved changes. Discard?")||c()},style:{marginLeft:"auto"},children:"Cancel"})]})]})}),$e&&(()=>{const de=Ne.trim().toLowerCase(),Ie=de?xe.filter(Ae=>Ae.packageName.toLowerCase().includes(de)||Ae.appName.toLowerCase().includes(de)):xe;return b.jsx("div",{className:"app-filter-overlay",onClick:Fe,children:b.jsxs("div",{className:"app-filter-dialog",onClick:Ae=>Ae.stopPropagation(),children:[b.jsxs("div",{className:"app-filter-header",children:[b.jsx("h2",{children:"Select app"}),b.jsx("button",{className:"app-filter-close",onClick:Fe,"aria-label":"Close",children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:b.jsx("path",{d:"M4 4L12 12M12 4L4 12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})})]}),b.jsx("input",{className:"form-input app-filter-search",type:"text",value:Ne,onChange:Ae=>Te(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&Ne.trim()&&(A(Ne.trim()),Fe())},placeholder:"Search or type a package name",autoFocus:!0}),b.jsxs("ul",{className:"app-filter-list",children:[je&&xe.length===0?Array.from({length:6}).map((Ae,Ot)=>b.jsx("li",{className:"app-filter-row app-filter-skeleton",children:b.jsx("div",{className:"app-filter-skeleton-bar"})},`sk-${Ot}`)):Ie.length===0&&!Ne.trim()?b.jsx("li",{className:"app-filter-empty",children:"No apps"}):Ie.map(Ae=>b.jsx("li",{className:"app-filter-row",onClick:()=>{A(Ae.packageName),Fe()},children:b.jsxs("div",{className:"app-filter-row-labels",children:[b.jsx("div",{className:"app-filter-row-name",children:Ae.appName||Ae.packageName}),Ae.appName&&b.jsx("div",{className:"app-filter-row-pkg",children:Ae.packageName})]})},Ae.packageName)),Ne.trim()&&b.jsx("li",{className:"app-filter-row",onClick:()=>{A(Ne.trim()),Fe()},children:b.jsx("div",{className:"app-filter-row-labels",children:b.jsx("div",{className:"app-filter-row-name",children:Ne.trim()})})})]})]})})})()]})}function Lx({pullDistance:e,refreshing:t,threshold:r}){const s=e>0||t,l=e>=r;return b.jsx("div",{className:"pull-to-refresh",style:{transform:`translateY(${e}px)`,opacity:s?Math.min(1,e/30):0},"aria-hidden":!s,children:b.jsx("div",{className:"pull-to-refresh-badge",children:t?b.jsx("div",{className:"spinner"}):b.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.25",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s"},children:[b.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b.jsx("polyline",{points:"19 12 12 19 5 12"})]})})})}function zx({onRefresh:e,threshold:t=70,maxPull:r=110,enabled:s=!0}){const[l,u]=j.useState(0),[c,f]=j.useState(!1),d=j.useRef(null),m=j.useRef(!1),y=j.useRef(0),g=j.useRef(!1),x=j.useRef(e);return j.useEffect(()=>{x.current=e}),j.useEffect(()=>{if(!s)return;const w=L=>{if(g.current||window.scrollY>0){d.current=null;return}d.current=L.touches[0].clientY,m.current=!1,y.current=0},S=L=>{if(g.current||d.current==null)return;const M=L.touches[0].clientY-d.current;if(M<=0){m.current=!1,y.current=0,u(0);return}m.current=!0;const P=Math.min(r,M*.5);y.current=P,u(P),L.cancelable&&L.preventDefault()},T=()=>{if(!m.current){d.current=null,u(0);return}const L=y.current;d.current=null,m.current=!1,y.current=0,L>=t?(g.current=!0,f(!0),u(t),Promise.resolve(x.current()).catch(()=>{}).finally(()=>{g.current=!1,f(!1),u(0)})):u(0)};return window.addEventListener("touchstart",w,{passive:!0}),window.addEventListener("touchmove",S,{passive:!1}),window.addEventListener("touchend",T,{passive:!0}),window.addEventListener("touchcancel",T,{passive:!0}),()=>{window.removeEventListener("touchstart",w),window.removeEventListener("touchmove",S),window.removeEventListener("touchend",T),window.removeEventListener("touchcancel",T)}},[s,t,r]),{pullDistance:l,refreshing:c,threshold:t}}function NE({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,isNotificationListener:c,onViewRun:f}){const[d,m]=j.useState([]),[y,g]=j.useState(!1),[x,w]=j.useState(null),[S,T]=j.useState(new Map),[L,M]=j.useState(!1),[P,F]=j.useState(void 0),ce=j.useCallback(()=>{M(!1),F(void 0)},[]),U=j.useCallback(async()=>{if(e){g(!0),w(null);try{const R=(await r("task.list")).tasks??[],V=new Map;for(const X of R)X.status&&V.set(X.id,X.status);T(V),m(R)}catch(q){const R=q instanceof Error?q.message:String(q);R==="Not connected"||R.includes("503")||R.toLowerCase().includes("no responders")?w(null):w(R),m([])}finally{g(!1)}}},[e,t,r]);j.useEffect(()=>{e?U():(m([]),g(!1))},[e,t,U]);const D=zx({onRefresh:U,enabled:e});j.useEffect(()=>!e||!t?void 0:s(t,async R=>{const V=R.subject.split(".");if(V.length<3)return;const X=V.slice(2).join(".");let le={};try{le=JSON.parse(new TextDecoder().decode(R.data))}catch{return}const ee=le.event_type;if(!(ee!=="running-state"&&ee!=="permission-resolved"))try{const Y=await r("task.status",{id:X},{timeout:5e3});if(Y.error)return;T(H=>{const W=new Map(H);return W.set(X,Y),W})}catch{}}),[e,t,s,r]);function te(q){m(R=>{const V=R.findIndex(X=>X.id===q.id);if(V>=0){const X=[...R];return X[V]=q,X}return[q,...R]}),M(!1),F(void 0)}function $(q){m(R=>R.filter(V=>V.id!==q)),T(R=>{const V=new Map(R);return V.delete(q),V})}return b.jsxs(b.Fragment,{children:[b.jsx(Lx,{pullDistance:D.pullDistance,refreshing:D.refreshing,threshold:D.threshold}),x&&b.jsxs("div",{className:"form-error",children:[x,x.toLowerCase().includes("failed to fetch")&&b.jsxs(b.Fragment,{children:[" ",b.jsx("a",{href:"#",onClick:q=>{q.preventDefault(),window.location.reload()},children:"Reload"})]})]}),y&&!d.length?b.jsx("div",{className:"task-list",children:[0,1,2].map(q=>b.jsxs("div",{className:"task-card",style:{pointerEvents:"none"},children:[b.jsx("div",{className:"task-card-header",children:b.jsxs("div",{className:"task-card-title-row",children:[b.jsx("div",{className:"skeleton-line",style:{width:10,height:10,borderRadius:"50%"}}),b.jsx("div",{className:"skeleton-line",style:{width:`${60+q*12}%`}})]})}),b.jsxs("div",{className:"task-card-meta",children:[b.jsx("div",{className:"skeleton-line",style:{width:"30%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"25%"}})]})]},q))}):d.length===0?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No tasks yet"}),b.jsx("p",{className:"empty-state-hint",children:"Tap the + button to create your first task."})]}):b.jsx("div",{className:"task-list",children:d.map(q=>b.jsx(xE,{task:q,lastEvent:S.get(q.id),onEdit:async R=>{try{const V=await r("task.get",{id:R.id});F(V.error?R:V)}catch{F(R)}M(!0)},onDelete:$,onViewRun:f},q.id))}),b.jsx("button",{className:"fab",onClick:()=>{F(void 0),M(!0)},"aria-label":"New task",title:"New task",children:b.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),L&&b.jsx(TE,{initial:P,agents:l,hostPlatform:u,isNotificationListener:c,onSaved:te,onRun:f,onCancel:ce})]})}let ha=null;function I0(e){ha&&(e.preventDefault(),e.returnValue="")}function Rh(e){const t=!!ha;ha=e;const r=!!ha;r&&!t?window.addEventListener("beforeunload",I0):!r&&t&&window.removeEventListener("beforeunload",I0)}function ps(){return ha?window.confirm(ha):!0}function OE(){const e=Or(),t=or(),{hostId:r}=Yu(),s=t.pathname.endsWith("/tasks"),l=!s;function u(c){ps()&&r&&e(`/hosts/${encodeURIComponent(r)}${c}`)}return b.jsxs(b.Fragment,{children:[b.jsxs("button",{className:`tab-btn ${l?"tab-btn-active":""}`,onClick:()=>u(""),children:[b.jsx("svg",{className:"tab-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M2 8H4.5L6 4L8 12L10 6L11.5 8H14"})}),"Sessions"]}),b.jsxs("button",{className:`tab-btn ${s?"tab-btn-active":""}`,onClick:()=>u("/tasks"),children:[b.jsxs("svg",{className:"tab-icon",width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"}),b.jsx("path",{d:"M5.5 8L7 9.5L10.5 6"})]}),"Tasks"]})]})}function Ux(e){const[t,r]=j.useState(()=>window.matchMedia(e).matches);return j.useEffect(()=>{const s=window.matchMedia(e),l=u=>r(u.matches);return s.addEventListener("change",l),r(s.matches),()=>s.removeEventListener("change",l)},[e]),t}const ku=Vn.isNativePlatform(),RE=["Device","Data","Messaging"],ME=[{capability:"sms-read",label:"Read SMS",group:"Messaging"},{capability:"sms-send",label:"Send SMS",group:"Messaging"},{capability:"send-email",label:"Send Email",group:"Messaging"},{capability:"notifications",label:"Notifications from Other Apps",group:"Data"},{capability:"contacts",label:"Manage Contacts",group:"Data"},{capability:"calendar",label:"Manage Calendar",group:"Data"},{capability:"location",label:"Get Location",group:"Device"},{capability:"dnd",label:"Set Ringer Mode",group:"Device"},{capability:"alarm",label:"Trigger Alarms",group:"Device"}];async function DE(){if(!ku||!mn)return new Set;try{const{capabilities:e}=await mn.getCapabilityStatus();return new Set(e.filter(t=>t.enabled).map(t=>t.name))}catch{return new Set}}function Bx({onChange:e,confirmDisable:t=!1}){const[r,s]=j.useState(new Map),[l,u]=j.useState(null),[c,f]=j.useState(null),d=j.useCallback(async()=>{if(!(!ku||!mn))try{const{capabilities:S}=await mn.getCapabilityStatus(),T=new Map;for(const L of S)T.set(L.name,L);s(T),e==null||e(new Set(S.filter(L=>L.enabled).map(L=>L.name)))}catch(S){console.error("Failed to read capability status:",S)}},[e]);j.useEffect(()=>{d()},[d]),j.useEffect(()=>{if(!ku)return;const S=hd.addListener("resume",d);return()=>{S.then(T=>T.remove())}},[d]);async function m(S,T){if(mn){u(S.capability);try{const L=await mn.setCapabilityEnabled({capability:S.capability,enabled:T});!L.enabled&&L.reason==="no-email-client"&&alert("No email app is installed on this device. Install one (e.g. Gmail) before enabling Send Email."),await d()}catch(L){console.error(`Failed to toggle ${S.capability}:`,L)}finally{u(null)}}}function y(S){const T=r.get(S.capability);if(T){if(T.enabled&&t){f(S);return}m(S,!T.enabled)}}function g(){const S=c;S&&(f(null),m(S,!1))}if(!ku)return null;const x=RE.map(S=>({group:S,items:ME.filter(T=>{const L=r.get(T.capability);return T.group===S&&(L==null?void 0:L.supported)})})).filter(S=>S.items.length>0);if(x.length===0)return b.jsx("div",{className:"capability-toggles-loading",children:b.jsx("span",{className:"spinner"})});const w=c&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>f(null),children:b.jsxs("div",{className:"confirm-modal",onClick:S=>S.stopPropagation(),children:[b.jsxs("h2",{className:"confirm-modal-title",children:["Disable ",c.label,"?"]}),b.jsxs("p",{className:"confirm-modal-message",children:["All hosts linked to this device will no longer be able to use ",c.label,"."]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>f(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:g,children:"Disable"})]})]})}),document.body);return b.jsxs(b.Fragment,{children:[x.map(({group:S,items:T},L)=>b.jsx("div",{className:L>0?"drawer-toggle-group drawer-toggle-group-divided":"drawer-toggle-group",children:T.map(M=>{const P=r.get(M.capability),F=!!(P!=null&&P.enabled);return b.jsxs("label",{className:"drawer-toggle",children:[b.jsx("span",{className:"drawer-toggle-label",children:M.label}),b.jsx("button",{className:`toggle-switch ${F?"toggle-switch-on":""}`,onClick:()=>y(M),disabled:l===M.capability,role:"switch","aria-checked":F,children:b.jsx("span",{className:"toggle-switch-thumb"})})]},M.capability)})},S)),w]})}const F0=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),LE=Vn.isNativePlatform();function $0({daemonVersion:e,linkedClientToken:t,request:r,onEnabledCapabilitiesChange:s,onLinkedClientTokenChange:l}){var Ce;const{pairedHosts:u,removePairedHost:c,renamePairedHost:f}=Pi(),{activeHost:d}=Hi(),m=Or(),y=or(),x=Yu().hostId??null,w=d.clientToken||null,S=!!w&&t===w,T=Ux("(min-width: 768px)"),[L,M]=j.useState(!1);async function P(){if(!(!mn||!r||!w)){M(!0);try{const{token:Ne}=await mn.getFcmToken();if(!Ne)return;await r("device.link",{fcmToken:Ne}),l==null||l(w)}catch(Ne){console.error("Failed to make this the linked device:",Ne)}finally{M(!1)}}}async function F(Ne){const Te=Ne===x;if(Te&&r)try{await r("clients.revoke_self")}catch{}c(Ne),ee(null),Te&&m("/",{replace:!0})}function ce(Ne){const Fe=y.pathname.endsWith("/tasks")?"/tasks":"";m(`/hosts/${encodeURIComponent(Ne)}${Fe}`)}const[U,D]=j.useState(!1),[te,$]=j.useState(!1),[q,R]=j.useState(null),[V,X]=j.useState(""),[le,ee]=j.useState(null),[Y,H]=j.useState(!1),W=j.useRef(null),oe=j.useRef(null),be=j.useCallback(()=>{$(!0)},[]);function k(){te&&(D(!1),$(!1))}function z(){$(!1),D(!0)}function K(Ne,Te){R(Ne),X(Te)}function A(){q&&V.trim()&&f(q,V.trim()),R(null),X("")}function xe(){R(null),X("")}j.useEffect(()=>{q&&oe.current&&(oe.current.focus(),oe.current.select())},[q]),j.useEffect(()=>{if(!U||te)return;function Ne(Te){Te.key==="Escape"&&be()}return document.addEventListener("keydown",Ne),()=>{document.removeEventListener("keydown",Ne)}},[U,te,be]);const _e=b.jsxs(b.Fragment,{children:[!T&&b.jsx("button",{className:"drawer-close-btn",onClick:be,"aria-label":"Close menu",children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:b.jsx("path",{d:"M4 4L12 12M12 4L4 12",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),!F0&&u.length>0&&b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Hosts"}),b.jsx("div",{className:"host-picker-inline",children:b.jsx("div",{className:"host-picker-list",role:"listbox",children:u.map(Ne=>{const Te=Ne.hostId===x,Fe=q===Ne.hostId,Qe=Ne.name||Ne.hostId.slice(0,8);return b.jsx("div",{className:"host-picker-item-wrapper",children:b.jsxs("div",{className:`host-picker-item ${Te?"host-picker-item-active":""}`,onClick:()=>{if(!Fe&&!Te){if(!ps())return;ce(Ne.hostId),T||be()}},role:"option","aria-selected":Te,children:[Fe?b.jsx("input",{ref:oe,className:"form-input host-picker-rename-input",type:"text",value:V,onChange:qe=>X(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&A(),qe.key==="Escape"&&xe()},onBlur:A,onClick:qe=>qe.stopPropagation()}):b.jsx("span",{className:"host-picker-item-name",children:Qe}),b.jsxs("div",{className:"host-picker-item-actions",children:[Te&&!Fe&&b.jsx("button",{className:"host-picker-edit-btn",onClick:qe=>{qe.stopPropagation(),K(Ne.hostId,Qe)},"aria-label":"Rename host",children:b.jsx("svg",{width:"13",height:"13",viewBox:"0 0 13 13",fill:"none",children:b.jsx("path",{d:"M9.5 1.5L11.5 3.5M1.5 11.5L2 9L9 2L11 4L4 11L1.5 11.5Z",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})}),!Te&&b.jsx("button",{className:"host-picker-delete-btn",onClick:qe=>{qe.stopPropagation(),ee(Ne.hostId)},"aria-label":`Unpair ${Qe}`,children:b.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:b.jsx("path",{d:"M4 5.5V11C4 11.2761 4.22386 11.5 4.5 11.5H9.5C9.77614 11.5 10 11.2761 10 11V5.5M3 4H11M5.5 4V3C5.5 2.72386 5.72386 2.5 6 2.5H8C8.27614 2.5 8.5 2.72386 8.5 3V4M6.5 6.5V9.5M7.5 6.5V9.5",stroke:"currentColor",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})},Ne.hostId)})})})]}),!F0&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsx("div",{className:"drawer-section",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:()=>{ps()&&(m("/pair"),T||be())},children:"Add New Host"})})]}),LE&&r&&b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-divider"}),b.jsxs("div",{className:"drawer-section",children:[b.jsx("h3",{className:"drawer-section-label",children:"Device Capabilities"}),S?b.jsx(Bx,{onChange:s,confirmDisable:!0}):b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"drawer-section-hint",children:"This device isn't the linked device for the host, so it can't provide capabilities (SMS, contacts, location, etc.)."}),b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>{t&&t!==w?H(!0):P()},disabled:L,children:L?"Linking…":"Link the host to this device"})]})]})]}),b.jsxs("div",{className:"drawer-footer",children:[e&&b.jsxs("div",{className:"drawer-version",children:["Palmier v",e]}),b.jsxs("div",{className:"drawer-legal",children:[b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms"}),b.jsx("span",{className:"drawer-legal-sep",children:"·"}),b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy"})]})]})]}),je=!!le&&le===x&&S,Le=le&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>ee(null),children:b.jsxs("div",{className:"confirm-modal",onClick:Ne=>Ne.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove host?"}),b.jsxs("p",{className:"confirm-modal-message",children:['"',((Ce=u.find(Ne=>Ne.hostId===le))==null?void 0:Ce.name)||le.slice(0,8),'" will be ',je?"removed and unlinked":"removed",".",je&&b.jsx(b.Fragment,{children:" This device is currently linked to the host — unlinking will revoke its access to all device capabilities (SMS, contacts, location, etc.) until another device is linked."})]}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>ee(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:()=>F(le),children:"Remove"})]})]})}),document.body),$e=Y&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>H(!1),children:b.jsxs("div",{className:"confirm-modal",onClick:Ne=>Ne.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:()=>H(!1),children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:()=>{H(!1),P()},children:"Link"})]})]})}),document.body);return T?b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-panel drawer-panel-desktop",ref:W,children:_e}),Le,$e]}):b.jsxs(b.Fragment,{children:[b.jsx("button",{className:"hamburger-btn",onClick:z,"aria-label":"Open menu",children:b.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",children:b.jsx("path",{d:"M3 5H17M3 10H17M3 15H17",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})}),U&&ds.createPortal(b.jsx("div",{className:`drawer-overlay ${te?"drawer-overlay-closing":""}`,onClick:be,onAnimationEnd:k,children:b.jsx("div",{className:`drawer-panel ${te?"drawer-panel-closing":""}`,ref:W,onClick:Ne=>Ne.stopPropagation(),children:_e})}),document.body),Le,$e]})}const zE=Vn.isNativePlatform(),Fd={width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function UE(){return b.jsxs("svg",{...Fd,"aria-hidden":"true",children:[b.jsx("path",{d:"M5 12.55a11 11 0 0 1 14.08 0"}),b.jsx("path",{d:"M1.42 9a16 16 0 0 1 21.16 0"}),b.jsx("path",{d:"M8.53 16.11a6 6 0 0 1 6.95 0"}),b.jsx("line",{x1:"12",y1:"20",x2:"12.01",y2:"20"})]})}function Y0(){return b.jsxs("svg",{...Fd,"aria-hidden":"true",children:[b.jsx("circle",{cx:"12",cy:"12",r:"10"}),b.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),b.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}function BE(){return b.jsxs("svg",{...Fd,"aria-hidden":"true",children:[b.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),b.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),b.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function PE(){const{mode:e}=Hi(),[t,r]=j.useState(!1),s=j.useRef(null);if(j.useEffect(()=>{if(!t)return;function f(m){var y;(y=s.current)!=null&&y.contains(m.target)||r(!1)}document.addEventListener("pointerdown",f);const d=window.setTimeout(()=>r(!1),3e3);return()=>{document.removeEventListener("pointerdown",f),clearTimeout(d)}},[t]),e==="direct")return null;let l,u,c;switch(e){case"lan":l=b.jsx(UE,{}),u="Connected via LAN",c="lan";break;case"nats":l=b.jsx(Y0,{}),u=zE?"Connected via relay":"Connected",c="relay";break;case"disconnected":l=b.jsx(BE,{}),u="Disconnected",c="disconnected";break;case"connecting":default:l=b.jsx(Y0,{}),u="Connecting…",c="connecting";break}return b.jsxs("div",{ref:s,className:`conn-status conn-status--${c}`,children:[b.jsx("button",{type:"button",className:"conn-status-btn","aria-label":u,onClick:()=>r(f=>!f),children:l}),b.jsx("div",{className:`conn-status-popover ${t?"conn-status-popover--open":""}`,role:"tooltip",children:u})]})}function G0(e,t){var s;const r=e.map(l=>l.key);return t&&r.includes(t)?t:((s=e[0])==null?void 0:s.key)??""}function qE({agents:e,hostPlatform:t,onStarted:r}){const{request:s,activeHost:l}=Hi(),{setHostLastAgent:u}=Pi(),[c,f]=j.useState(""),[d,m]=j.useState(()=>G0(e,l.lastAgent)),[y,g]=j.useState(!1),[x,w]=j.useState(!1),[S,T]=j.useState(null);j.useEffect(()=>{e.length&&(e.find(D=>D.key===d)||m(G0(e,l.lastAgent)))},[e,d,l.lastAgent]),j.useEffect(()=>{const D=c.trim().length>0;return Rh(D?"Your session draft will be lost. Continue?":null),()=>Rh(null)},[c]);const L=e.find(D=>D.key===d),M=!!(L!=null&&L.supportsYolo);j.useEffect(()=>{!M&&y&&g(!1)},[M,y]);const P=!!c.trim()&&!!d&&!x;function F(){return y?confirm(`Yolo mode is enabled. The agent will auto-approve all tool calls — it can read, write, delete files, run arbitrary commands, and access the network without asking for permission.
|
|
91
91
|
|
|
92
92
|
Are you sure you want to continue?`):!0}async function ce(){if(!(!P||!F())){w(!0),T(null);try{const D=await s("task.run_oneoff",{user_prompt:c,agent:d,yolo_mode:y,...t==="win32"?{foreground_mode:!0}:{}});if(D.error){T(D.error);return}u(l.hostId,d),f(""),Rh(null),D.task_id&&r(D.task_id,D.run_id)}catch(D){T(D instanceof Error?D.message:String(D))}finally{w(!1)}}}function U(D){D.key==="Enter"&&(D.metaKey||D.ctrlKey)&&(D.preventDefault(),ce())}return b.jsxs("div",{className:"session-composer",children:[S&&b.jsx("div",{className:"form-error",children:S}),b.jsx("textarea",{className:"session-composer-textarea",value:c,onChange:D=>f(D.target.value),onKeyDown:U,placeholder:"What can I do for you?",rows:3,disabled:x}),b.jsxs("div",{className:"session-composer-controls",children:[b.jsxs("div",{className:"agent-picker-section-inline",children:[b.jsx("span",{className:"agent-picker-label",children:"Run with"}),b.jsx("select",{className:"form-select form-select-sm",value:d,onChange:D=>m(D.target.value),disabled:x||!e.length,children:e.map(D=>b.jsx("option",{value:D.key,children:D.label},D.key))})]}),M&&b.jsxs("label",{className:"session-composer-yolo",children:[b.jsx("input",{type:"checkbox",checked:y,onChange:D=>g(D.target.checked),disabled:x}),"Yolo"]}),b.jsx("button",{className:"btn btn-primary chat-send-btn",onClick:ce,disabled:!P,"aria-label":"Run session",title:"Run session",children:x?b.jsx("span",{className:"btn-spinner"}):b.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),b.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]}),M&&y&&b.jsx("p",{className:"command-help-text",children:"The agent will auto-approve all tool calls without asking for permission."})]})}const fs=72,V0=6;function HE({id:e,revealedId:t,setRevealedId:r,onDelete:s,onClick:l,children:u,actionLabel:c="Delete",confirmMessage:f="Delete this item? This can't be undone."}){const d=t===e,[m,y]=j.useState(0),[g,x]=j.useState(!1),w=j.useRef(0),S=j.useRef(0),T=j.useRef(null),L=j.useRef(0),M=j.useRef(!1),P=j.useRef(null);j.useEffect(()=>{d||y(0)},[d]),j.useEffect(()=>{if(!d)return;function $(q){var R;(R=P.current)!=null&&R.contains(q.target)||r(null)}return document.addEventListener("pointerdown",$),()=>document.removeEventListener("pointerdown",$)},[d,r]);function F($){$.button!==void 0&&$.button!==0||(w.current=$.clientX,S.current=$.clientY,T.current=null,L.current=d?-fs:0,M.current=!1)}function ce($){if($.pointerType==="mouse"&&$.buttons===0)return;const q=$.clientX-w.current,R=$.clientY-S.current;if(T.current===null){if(Math.abs(q)<V0&&Math.abs(R)<V0)return;if(T.current=Math.abs(q)>Math.abs(R)?"x":"y",T.current==="x")try{$.currentTarget.setPointerCapture($.pointerId)}catch{}}if(T.current!=="x")return;M.current=!0,g||x(!0);let V=L.current+q;V>0&&(V=V/4),V<-fs&&(V=-fs+(V+fs)/4),y(V)}function U(){if(T.current!=="x"){x(!1);return}T.current=null,x(!1),m<=-36?(y(-fs),r(e)):(y(0),d&&r(null))}function D($){if(M.current){M.current=!1,$.stopPropagation(),$.preventDefault();return}d&&($.stopPropagation(),$.preventDefault(),r(null))}const te=m!==0?m:d?-fs:0;return b.jsxs("div",{ref:P,className:"swipe-row",children:[b.jsxs("button",{type:"button",className:"swipe-row-action",style:{width:fs},onClick:$=>{$.stopPropagation(),window.confirm(f)&&s()},tabIndex:d?0:-1,"aria-hidden":!d,"aria-label":c,children:[b.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[b.jsx("polyline",{points:"3 6 5 6 21 6"}),b.jsx("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),b.jsx("path",{d:"M10 11v6M14 11v6"}),b.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2"})]}),b.jsx("span",{className:"swipe-row-action-label",children:c})]}),b.jsx("div",{className:`swipe-row-content ${g?"swipe-row-content-dragging":""}`,style:{transform:`translateX(${te}px)`},onPointerDown:F,onPointerMove:ce,onPointerUp:U,onPointerCancel:U,onClickCapture:D,onClick:l,children:u})]})}const IE=10;function FE({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,filterTaskId:c,onClearFilter:f}){const[d,m]=j.useState([]),[y,g]=j.useState(0),[x,w]=j.useState(!1),[S,T]=j.useState(!1),[L,M]=j.useState(null),P=Or();async function F(Y){const H=`${Y.task_id}:${Y.run_id}`;m(W=>W.filter(oe=>`${oe.task_id}:${oe.run_id}`!==H)),g(W=>Math.max(0,W-1)),M(null);try{await r("taskrun.delete",{task_id:Y.task_id,run_id:Y.run_id})}catch(W){console.error("Failed to delete run:",W),m(oe=>[Y,...oe]),g(oe=>oe+1)}}const ce=j.useRef(null),U=j.useCallback(Y=>{const H={offset:Y,limit:IE};return c&&(H.task_id=c),H},[c]),D=j.useCallback(async(Y,H)=>{if(e){H?T(!0):w(!0);try{const W=await r("taskrun.list",U(Y)),oe=W.entries??[];g(W.total??0),m(H?be=>{const k=new Set(be.map(K=>`${K.task_id}:${K.run_id}`)),z=oe.filter(K=>!k.has(`${K.task_id}:${K.run_id}`));return[...be,...z]}:oe)}catch(W){W instanceof Error&&W.message==="Not connected"||console.error("Failed to load runs:",W)}finally{w(!1),T(!1)}}},[e,r,U]);j.useEffect(()=>{e?(m([]),g(0),D(0,!1)):(m([]),g(0))},[e,t,D,c]);const te=zx({onRefresh:()=>D(0,!1),enabled:e});j.useEffect(()=>!e||!t?void 0:s(t,async H=>{try{const W=JSON.parse(new TextDecoder().decode(H.data));if(W.event_type==="running-state"&&W.running_state&&["monitoring","started","finished","failed","aborted"].includes(W.running_state)){const oe=await r("taskrun.list",U(0)),be=oe.entries??[];g(oe.total??0),m(k=>{const z=new Map(be.map(_e=>[`${_e.task_id}:${_e.run_id}`,_e])),K=k.map(_e=>{const je=`${_e.task_id}:${_e.run_id}`;return z.get(je)??_e}),A=new Set(K.map(_e=>`${_e.task_id}:${_e.run_id}`));return[...be.filter(_e=>!A.has(`${_e.task_id}:${_e.run_id}`)),...K]})}}catch{}}),[e,t,s,r]),j.useEffect(()=>{const Y=ce.current;if(!Y)return;const H=new IntersectionObserver(W=>{W[0].isIntersecting&&!S&&d.length<y&&D(d.length,!0)},{threshold:.1});return H.observe(Y),()=>H.disconnect()},[d.length,y,S,D]);function $(Y,H){if(!Y||!H)return"";const W=Math.round((H-Y)/1e3);if(W<60)return`${W}s`;const oe=Math.floor(W/60),be=W%60;return`${oe}m ${be}s`}const q={monitoring:"Monitoring",started:"Running",finished:"Finished",failed:"Failed",aborted:"Aborted"};function R(Y,H){ps()&&t&&P(`/hosts/${encodeURIComponent(t)}/runs/${encodeURIComponent(Y)}/${encodeURIComponent(H)}`)}const V=!c&&b.jsx(qE,{agents:l,hostPlatform:u,onStarted:(Y,H)=>{if(!t)return;const W=`/hosts/${encodeURIComponent(t)}/runs/${encodeURIComponent(Y)}`;P(H?`${W}/${encodeURIComponent(H)}`:W)}}),X=b.jsx(Lx,{pullDistance:te.pullDistance,refreshing:te.refreshing,threshold:te.threshold}),le=c&&f&&b.jsx("div",{style:{marginBottom:"var(--space-sm)"},children:b.jsxs("span",{className:"sessions-filter-chip",children:["Filtered by task",b.jsx("button",{onClick:f,"aria-label":"Clear filter",children:"×"})]})});function ee(Y){if(Y==="failed")return"var(--color-error)";if(Y==="aborted")return"var(--color-warning, #d97706)"}return x&&d.length===0&&e?b.jsxs(b.Fragment,{children:[X,V,b.jsx("div",{className:"task-list",children:[0,1,2].map(Y=>b.jsxs("div",{className:"task-card",style:{pointerEvents:"none"},children:[b.jsx("div",{className:"task-card-header",children:b.jsx("div",{className:"task-card-title-row",children:b.jsx("div",{className:"skeleton-line",style:{width:`${70+Y*10}%`}})})}),b.jsx("div",{className:"task-card-meta",children:b.jsx("div",{className:"skeleton-line",style:{width:"45%"}})})]},Y))})]}):!e||x&&d.length===0?b.jsxs(b.Fragment,{children:[X,V,b.jsx("div",{className:"sessions-view",children:b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"Sessions"}),b.jsx("p",{className:"empty-state-hint",children:"Your sessions will appear here"})]})})]}):d.length===0?b.jsxs(b.Fragment,{children:[X,V,le,b.jsx("div",{className:"sessions-view",children:b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No sessions yet"}),b.jsx("p",{className:"empty-state-hint",children:c?"This task hasn't been executed yet. Run it from the task menu or wait for its next trigger.":"Your sessions will appear here."})]})})]}):b.jsxs(b.Fragment,{children:[X,V,le,b.jsxs("div",{className:"task-list",children:[d.map((Y,H)=>{const W=`${Y.task_id}:${Y.run_id}`;return b.jsx(HE,{id:W,revealedId:L,setRevealedId:M,onDelete:()=>F(Y),confirmMessage:"Delete this session? Its run history will be removed from the host.",onClick:()=>!Y.error&&R(Y.task_id,Y.run_id),children:b.jsxs("div",{className:"sessions-card",children:[b.jsxs("div",{className:"sessions-card-body",children:[b.jsx("h3",{className:"sessions-card-name",children:Y.task_name||Y.task_id}),b.jsxs("div",{className:"sessions-card-meta",children:[Y.running_state==="started"?b.jsx("span",{className:"status-spinner","aria-label":"Running",children:b.jsx("span",{})}):b.jsx("span",{style:{color:ee(Y.running_state)},children:q[Y.running_state??""]??Y.running_state}),Y.end_time&&b.jsx("span",{children:Bu(Y.end_time)}),Y.start_time&&Y.end_time&&b.jsx("span",{style:{color:"var(--color-muted)"},children:$(Y.start_time,Y.end_time)}),Y.error&&b.jsx("span",{style:{color:"var(--color-muted)"},children:Y.error})]})]}),b.jsx("span",{className:"sessions-card-chevron",children:"›"})]})},`${W}-${H}`)}),b.jsx("div",{ref:ce,style:{height:1}}),S&&b.jsx("div",{className:"loading-state",style:{padding:"var(--space-md)"},children:b.jsx("div",{className:"spinner"})})]})]})}function $E(e,t){const r={};return(e[e.length-1]===""?[...e,""]:e).join((r.padRight?" ":"")+","+(r.padLeft===!1?"":" ")).trim()}const YE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,GE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,VE={};function J0(e,t){return(VE.jsx?GE:YE).test(e)}const JE=/[ \t\n\f\r]/g;function XE(e){return typeof e=="object"?e.type==="text"?X0(e.value):!1:X0(e)}function X0(e){return e.replace(JE,"")===""}class Gl{constructor(t,r,s){this.normal=r,this.property=t,s&&(this.space=s)}}Gl.prototype.normal={};Gl.prototype.property={};Gl.prototype.space=void 0;function Px(e,t){const r={},s={};for(const l of e)Object.assign(r,l.property),Object.assign(s,l.normal);return new Gl(r,s,t)}function pd(e){return e.toLowerCase()}class On{constructor(t,r){this.attribute=r,this.property=t}}On.prototype.attribute="";On.prototype.booleanish=!1;On.prototype.boolean=!1;On.prototype.commaOrSpaceSeparated=!1;On.prototype.commaSeparated=!1;On.prototype.defined=!1;On.prototype.mustUseProperty=!1;On.prototype.number=!1;On.prototype.overloadedBoolean=!1;On.prototype.property="";On.prototype.spaceSeparated=!1;On.prototype.space=void 0;let KE=0;const Ke=bs(),Zt=bs(),gd=bs(),we=bs(),Nt=bs(),da=bs(),qn=bs();function bs(){return 2**++KE}const yd=Object.freeze(Object.defineProperty({__proto__:null,boolean:Ke,booleanish:Zt,commaOrSpaceSeparated:qn,commaSeparated:da,number:we,overloadedBoolean:gd,spaceSeparated:Nt},Symbol.toStringTag,{value:"Module"})),Mh=Object.keys(yd);class $d extends On{constructor(t,r,s,l){let u=-1;if(super(t,r),K0(this,"space",l),typeof s=="number")for(;++u<Mh.length;){const c=Mh[u];K0(this,Mh[u],(s&yd[c])===yd[c])}}}$d.prototype.defined=!0;function K0(e,t,r){r&&(e[t]=r)}function _a(e){const t={},r={};for(const[s,l]of Object.entries(e.properties)){const u=new $d(s,e.transform(e.attributes||{},s),l,e.space);e.mustUseProperty&&e.mustUseProperty.includes(s)&&(u.mustUseProperty=!0),t[s]=u,r[pd(s)]=s,r[pd(u.attribute)]=s}return new Gl(t,r,e.space)}const qx=_a({properties:{ariaActiveDescendant:null,ariaAtomic:Zt,ariaAutoComplete:null,ariaBusy:Zt,ariaChecked:Zt,ariaColCount:we,ariaColIndex:we,ariaColSpan:we,ariaControls:Nt,ariaCurrent:null,ariaDescribedBy:Nt,ariaDetails:null,ariaDisabled:Zt,ariaDropEffect:Nt,ariaErrorMessage:null,ariaExpanded:Zt,ariaFlowTo:Nt,ariaGrabbed:Zt,ariaHasPopup:null,ariaHidden:Zt,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Nt,ariaLevel:we,ariaLive:null,ariaModal:Zt,ariaMultiLine:Zt,ariaMultiSelectable:Zt,ariaOrientation:null,ariaOwns:Nt,ariaPlaceholder:null,ariaPosInSet:we,ariaPressed:Zt,ariaReadOnly:Zt,ariaRelevant:null,ariaRequired:Zt,ariaRoleDescription:Nt,ariaRowCount:we,ariaRowIndex:we,ariaRowSpan:we,ariaSelected:Zt,ariaSetSize:we,ariaSort:null,ariaValueMax:we,ariaValueMin:we,ariaValueNow:we,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function Hx(e,t){return t in e?e[t]:t}function Ix(e,t){return Hx(e,t.toLowerCase())}const QE=_a({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:da,acceptCharset:Nt,accessKey:Nt,action:null,allow:null,allowFullScreen:Ke,allowPaymentRequest:Ke,allowUserMedia:Ke,alt:null,as:null,async:Ke,autoCapitalize:null,autoComplete:Nt,autoFocus:Ke,autoPlay:Ke,blocking:Nt,capture:null,charSet:null,checked:Ke,cite:null,className:Nt,cols:we,colSpan:null,content:null,contentEditable:Zt,controls:Ke,controlsList:Nt,coords:we|da,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Ke,defer:Ke,dir:null,dirName:null,disabled:Ke,download:gd,draggable:Zt,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Ke,formTarget:null,headers:Nt,height:we,hidden:gd,high:we,href:null,hrefLang:null,htmlFor:Nt,httpEquiv:Nt,id:null,imageSizes:null,imageSrcSet:null,inert:Ke,inputMode:null,integrity:null,is:null,isMap:Ke,itemId:null,itemProp:Nt,itemRef:Nt,itemScope:Ke,itemType:Nt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Ke,low:we,manifest:null,max:null,maxLength:we,media:null,method:null,min:null,minLength:we,multiple:Ke,muted:Ke,name:null,nonce:null,noModule:Ke,noValidate:Ke,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Ke,optimum:we,pattern:null,ping:Nt,placeholder:null,playsInline:Ke,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Ke,referrerPolicy:null,rel:Nt,required:Ke,reversed:Ke,rows:we,rowSpan:we,sandbox:Nt,scope:null,scoped:Ke,seamless:Ke,selected:Ke,shadowRootClonable:Ke,shadowRootDelegatesFocus:Ke,shadowRootMode:null,shape:null,size:we,sizes:null,slot:null,span:we,spellCheck:Zt,src:null,srcDoc:null,srcLang:null,srcSet:null,start:we,step:null,style:null,tabIndex:we,target:null,title:null,translate:null,type:null,typeMustMatch:Ke,useMap:null,value:Zt,width:we,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Nt,axis:null,background:null,bgColor:null,border:we,borderColor:null,bottomMargin:we,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Ke,declare:Ke,event:null,face:null,frame:null,frameBorder:null,hSpace:we,leftMargin:we,link:null,longDesc:null,lowSrc:null,marginHeight:we,marginWidth:we,noResize:Ke,noHref:Ke,noShade:Ke,noWrap:Ke,object:null,profile:null,prompt:null,rev:null,rightMargin:we,rules:null,scheme:null,scrolling:Zt,standby:null,summary:null,text:null,topMargin:we,valueType:null,version:null,vAlign:null,vLink:null,vSpace:we,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Ke,disableRemotePlayback:Ke,prefix:null,property:null,results:we,security:null,unselectable:null},space:"html",transform:Ix}),ZE=_a({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:qn,accentHeight:we,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:we,amplitude:we,arabicForm:null,ascent:we,attributeName:null,attributeType:null,azimuth:we,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:we,by:null,calcMode:null,capHeight:we,className:Nt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:we,diffuseConstant:we,direction:null,display:null,dur:null,divisor:we,dominantBaseline:null,download:Ke,dx:null,dy:null,edgeMode:null,editable:null,elevation:we,enableBackground:null,end:null,event:null,exponent:we,externalResourcesRequired:null,fill:null,fillOpacity:we,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:da,g2:da,glyphName:da,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:we,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:we,horizOriginX:we,horizOriginY:we,id:null,ideographic:we,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:we,k:we,k1:we,k2:we,k3:we,k4:we,kernelMatrix:qn,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:we,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:we,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:we,overlineThickness:we,paintOrder:null,panose1:null,path:null,pathLength:we,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Nt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:we,pointsAtY:we,pointsAtZ:we,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:qn,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:qn,rev:qn,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:qn,requiredFeatures:qn,requiredFonts:qn,requiredFormats:qn,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:we,specularExponent:we,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:we,strikethroughThickness:we,string:null,stroke:null,strokeDashArray:qn,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:we,strokeOpacity:we,strokeWidth:null,style:null,surfaceScale:we,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:qn,tabIndex:we,tableValues:null,target:null,targetX:we,targetY:we,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:qn,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:we,underlineThickness:we,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:we,values:null,vAlphabetic:we,vMathematical:we,vectorEffect:null,vHanging:we,vIdeographic:we,version:null,vertAdvY:we,vertOriginX:we,vertOriginY:we,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:we,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Hx}),Fx=_a({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),$x=_a({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Ix}),Yx=_a({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),WE={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},eC=/[A-Z]/g,Q0=/-[a-z]/g,tC=/^data[-\w.:]+$/i;function nC(e,t){const r=pd(t);let s=t,l=On;if(r in e.normal)return e.property[e.normal[r]];if(r.length>4&&r.slice(0,4)==="data"&&tC.test(t)){if(t.charAt(4)==="-"){const u=t.slice(5).replace(Q0,iC);s="data"+u.charAt(0).toUpperCase()+u.slice(1)}else{const u=t.slice(4);if(!Q0.test(u)){let c=u.replace(eC,rC);c.charAt(0)!=="-"&&(c="-"+c),t="data"+c}}l=$d}return new l(s,t)}function rC(e){return"-"+e.toLowerCase()}function iC(e){return e.charAt(1).toUpperCase()}const sC=Px([qx,QE,Fx,$x,Yx],"html"),Yd=Px([qx,ZE,Fx,$x,Yx],"svg");function aC(e){return e.join(" ").trim()}var ta={},Dh,Z0;function lC(){if(Z0)return Dh;Z0=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,r=/^\s*/,s=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,l=/^:\s*/,u=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,f=/^\s+|\s+$/g,d=`
|
|
93
93
|
`,m="/",y="*",g="",x="comment",w="declaration";function S(L,M){if(typeof L!="string")throw new TypeError("First argument must be a string");if(!L)return[];M=M||{};var P=1,F=1;function ce(ee){var Y=ee.match(t);Y&&(P+=Y.length);var H=ee.lastIndexOf(d);F=~H?ee.length-H:F+ee.length}function U(){var ee={line:P,column:F};return function(Y){return Y.position=new D(ee),q(),Y}}function D(ee){this.start=ee,this.end={line:P,column:F},this.source=M.source}D.prototype.content=L;function te(ee){var Y=new Error(M.source+":"+P+":"+F+": "+ee);if(Y.reason=ee,Y.filename=M.source,Y.line=P,Y.column=F,Y.source=L,!M.silent)throw Y}function $(ee){var Y=ee.exec(L);if(Y){var H=Y[0];return ce(H),L=L.slice(H.length),Y}}function q(){$(r)}function R(ee){var Y;for(ee=ee||[];Y=V();)Y!==!1&&ee.push(Y);return ee}function V(){var ee=U();if(!(m!=L.charAt(0)||y!=L.charAt(1))){for(var Y=2;g!=L.charAt(Y)&&(y!=L.charAt(Y)||m!=L.charAt(Y+1));)++Y;if(Y+=2,g===L.charAt(Y-1))return te("End of comment missing");var H=L.slice(2,Y-2);return F+=2,ce(H),L=L.slice(Y),F+=2,ee({type:x,comment:H})}}function X(){var ee=U(),Y=$(s);if(Y){if(V(),!$(l))return te("property missing ':'");var H=$(u),W=ee({type:w,property:T(Y[0].replace(e,g)),value:H?T(H[0].replace(e,g)):g});return $(c),W}}function le(){var ee=[];R(ee);for(var Y;Y=X();)Y!==!1&&(ee.push(Y),R(ee));return ee}return q(),le()}function T(L){return L?L.replace(f,g):g}return Dh=S,Dh}var W0;function oC(){if(W0)return ta;W0=1;var e=ta&&ta.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(ta,"__esModule",{value:!0}),ta.default=r;const t=e(lC());function r(s,l){let u=null;if(!s||typeof s!="string")return u;const c=(0,t.default)(s),f=typeof l=="function";return c.forEach(d=>{if(d.type!=="declaration")return;const{property:m,value:y}=d;f?l(m,y,d):y&&(u=u||{},u[m]=y)}),u}return ta}var vl={},eb;function uC(){if(eb)return vl;eb=1,Object.defineProperty(vl,"__esModule",{value:!0}),vl.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,r=/^[^-]+$/,s=/^-(webkit|moz|ms|o|khtml)-/,l=/^-(ms)-/,u=function(m){return!m||r.test(m)||e.test(m)},c=function(m,y){return y.toUpperCase()},f=function(m,y){return"".concat(y,"-")},d=function(m,y){return y===void 0&&(y={}),u(m)?m:(m=m.toLowerCase(),y.reactCompat?m=m.replace(l,f):m=m.replace(s,f),m.replace(t,c))};return vl.camelCase=d,vl}var wl,tb;function cC(){if(tb)return wl;tb=1;var e=wl&&wl.__importDefault||function(l){return l&&l.__esModule?l:{default:l}},t=e(oC()),r=uC();function s(l,u){var c={};return!l||typeof l!="string"||(0,t.default)(l,function(f,d){f&&d&&(c[(0,r.camelCase)(f,u)]=d)}),c}return s.default=s,wl=s,wl}var fC=cC();const hC=Hb(fC),Gx=Vx("end"),Gd=Vx("start");function Vx(e){return t;function t(r){const s=r&&r.position&&r.position[e]||{};if(typeof s.line=="number"&&s.line>0&&typeof s.column=="number"&&s.column>0)return{line:s.line,column:s.column,offset:typeof s.offset=="number"&&s.offset>-1?s.offset:void 0}}}function dC(e){const t=Gd(e),r=Gx(e);if(t&&r)return{start:t,end:r}}function Ol(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?nb(e.position):"start"in e||"end"in e?nb(e):"line"in e||"column"in e?bd(e):""}function bd(e){return rb(e&&e.line)+":"+rb(e&&e.column)}function nb(e){return bd(e&&e.start)+"-"+bd(e&&e.end)}function rb(e){return e&&typeof e=="number"?e:1}class gn extends Error{constructor(t,r,s){super(),typeof r=="string"&&(s=r,r=void 0);let l="",u={},c=!1;if(r&&("line"in r&&"column"in r?u={place:r}:"start"in r&&"end"in r?u={place:r}:"type"in r?u={ancestors:[r],place:r.position}:u={...r}),typeof t=="string"?l=t:!u.cause&&t&&(c=!0,l=t.message,u.cause=t),!u.ruleId&&!u.source&&typeof s=="string"){const d=s.indexOf(":");d===-1?u.ruleId=s:(u.source=s.slice(0,d),u.ruleId=s.slice(d+1))}if(!u.place&&u.ancestors&&u.ancestors){const d=u.ancestors[u.ancestors.length-1];d&&(u.place=d.position)}const f=u.place&&"start"in u.place?u.place.start:u.place;this.ancestors=u.ancestors||void 0,this.cause=u.cause||void 0,this.column=f?f.column:void 0,this.fatal=void 0,this.file="",this.message=l,this.line=f?f.line:void 0,this.name=Ol(u.place)||"1:1",this.place=u.place||void 0,this.reason=this.message,this.ruleId=u.ruleId||void 0,this.source=u.source||void 0,this.stack=c&&u.cause&&typeof u.cause.stack=="string"?u.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}gn.prototype.file="";gn.prototype.name="";gn.prototype.reason="";gn.prototype.message="";gn.prototype.stack="";gn.prototype.column=void 0;gn.prototype.line=void 0;gn.prototype.ancestors=void 0;gn.prototype.cause=void 0;gn.prototype.fatal=void 0;gn.prototype.place=void 0;gn.prototype.ruleId=void 0;gn.prototype.source=void 0;const Vd={}.hasOwnProperty,mC=new Map,pC=/[A-Z]/g,gC=new Set(["table","tbody","thead","tfoot","tr"]),yC=new Set(["td","th"]),Jx="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function bC(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const r=t.filePath||void 0;let s;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");s=CC(r,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");s=EC(r,t.jsx,t.jsxs)}const l={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:s,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:r,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?Yd:sC,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},u=Xx(l,e,void 0);return u&&typeof u!="string"?u:l.create(e,l.Fragment,{children:u||void 0},void 0)}function Xx(e,t,r){if(t.type==="element")return xC(e,t,r);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return vC(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return SC(e,t,r);if(t.type==="mdxjsEsm")return wC(e,t);if(t.type==="root")return _C(e,t,r);if(t.type==="text")return kC(e,t)}function xC(e,t,r){const s=e.schema;let l=s;t.tagName.toLowerCase()==="svg"&&s.space==="html"&&(l=Yd,e.schema=l),e.ancestors.push(t);const u=Qx(e,t.tagName,!1),c=AC(e,t);let f=Xd(e,t);return gC.has(t.tagName)&&(f=f.filter(function(d){return typeof d=="string"?!XE(d):!0})),Kx(e,c,u,t),Jd(c,f),e.ancestors.pop(),e.schema=s,e.create(t,u,c,r)}function vC(e,t){if(t.data&&t.data.estree&&e.evaluater){const s=t.data.estree.body[0];return s.type,e.evaluater.evaluateExpression(s.expression)}ql(e,t.position)}function wC(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);ql(e,t.position)}function SC(e,t,r){const s=e.schema;let l=s;t.name==="svg"&&s.space==="html"&&(l=Yd,e.schema=l),e.ancestors.push(t);const u=t.name===null?e.Fragment:Qx(e,t.name,!0),c=jC(e,t),f=Xd(e,t);return Kx(e,c,u,t),Jd(c,f),e.ancestors.pop(),e.schema=s,e.create(t,u,c,r)}function _C(e,t,r){const s={};return Jd(s,Xd(e,t)),e.create(t,e.Fragment,s,r)}function kC(e,t){return t.value}function Kx(e,t,r,s){typeof r!="string"&&r!==e.Fragment&&e.passNode&&(t.node=s)}function Jd(e,t){if(t.length>0){const r=t.length>1?t:t[0];r&&(e.children=r)}}function EC(e,t,r){return s;function s(l,u,c,f){const m=Array.isArray(c.children)?r:t;return f?m(u,c,f):m(u,c)}}function CC(e,t){return r;function r(s,l,u,c){const f=Array.isArray(u.children),d=Gd(s);return t(l,u,c,f,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function AC(e,t){const r={};let s,l;for(l in t.properties)if(l!=="children"&&Vd.call(t.properties,l)){const u=TC(e,l,t.properties[l]);if(u){const[c,f]=u;e.tableCellAlignToStyle&&c==="align"&&typeof f=="string"&&yC.has(t.tagName)?s=f:r[c]=f}}if(s){const u=r.style||(r.style={});u[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=s}return r}function jC(e,t){const r={};for(const s of t.attributes)if(s.type==="mdxJsxExpressionAttribute")if(s.data&&s.data.estree&&e.evaluater){const u=s.data.estree.body[0];u.type;const c=u.expression;c.type;const f=c.properties[0];f.type,Object.assign(r,e.evaluater.evaluateExpression(f.argument))}else ql(e,t.position);else{const l=s.name;let u;if(s.value&&typeof s.value=="object")if(s.value.data&&s.value.data.estree&&e.evaluater){const f=s.value.data.estree.body[0];f.type,u=e.evaluater.evaluateExpression(f.expression)}else ql(e,t.position);else u=s.value===null?!0:s.value;r[l]=u}return r}function Xd(e,t){const r=[];let s=-1;const l=e.passKeys?new Map:mC;for(;++s<t.children.length;){const u=t.children[s];let c;if(e.passKeys){const d=u.type==="element"?u.tagName:u.type==="mdxJsxFlowElement"||u.type==="mdxJsxTextElement"?u.name:void 0;if(d){const m=l.get(d)||0;c=d+"-"+m,l.set(d,m+1)}}const f=Xx(e,u,c);f!==void 0&&r.push(f)}return r}function TC(e,t,r){const s=nC(e.schema,t);if(!(r==null||typeof r=="number"&&Number.isNaN(r))){if(Array.isArray(r)&&(r=s.commaSeparated?$E(r):aC(r)),s.property==="style"){let l=typeof r=="object"?r:NC(e,String(r));return e.stylePropertyNameCase==="css"&&(l=OC(l)),["style",l]}return[e.elementAttributeNameCase==="react"&&s.space?WE[s.property]||s.property:s.attribute,r]}}function NC(e,t){try{return hC(t,{reactCompat:!0})}catch(r){if(e.ignoreInvalidStyle)return{};const s=r,l=new gn("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:s,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw l.file=e.filePath||void 0,l.url=Jx+"#cannot-parse-style-attribute",l}}function Qx(e,t,r){let s;if(!r)s={type:"Literal",value:t};else if(t.includes(".")){const l=t.split(".");let u=-1,c;for(;++u<l.length;){const f=J0(l[u])?{type:"Identifier",name:l[u]}:{type:"Literal",value:l[u]};c=c?{type:"MemberExpression",object:c,property:f,computed:!!(u&&f.type==="Literal"),optional:!1}:f}s=c}else s=J0(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(s.type==="Literal"){const l=s.value;return Vd.call(e.components,l)?e.components[l]:l}if(e.evaluater)return e.evaluater.evaluateExpression(s);ql(e)}function ql(e,t){const r=new gn("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Jx+"#cannot-handle-mdx-estrees-without-createevaluater",r}function OC(e){const t={};let r;for(r in e)Vd.call(e,r)&&(t[RC(r)]=e[r]);return t}function RC(e){let t=e.replace(pC,MC);return t.slice(0,3)==="ms-"&&(t="-"+t),t}function MC(e){return"-"+e.toLowerCase()}const Lh={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},DC={};function Kd(e,t){const r=DC,s=typeof r.includeImageAlt=="boolean"?r.includeImageAlt:!0,l=typeof r.includeHtml=="boolean"?r.includeHtml:!0;return Zx(e,s,l)}function Zx(e,t,r){if(LC(e)){if("value"in e)return e.type==="html"&&!r?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return ib(e.children,t,r)}return Array.isArray(e)?ib(e,t,r):""}function ib(e,t,r){const s=[];let l=-1;for(;++l<e.length;)s[l]=Zx(e[l],t,r);return s.join("")}function LC(e){return!!(e&&typeof e=="object")}const sb=document.createElement("i");function Qd(e){const t="&"+e+";";sb.innerHTML=t;const r=sb.textContent;return r.charCodeAt(r.length-1)===59&&e!=="semi"||r===t?!1:r}function Yn(e,t,r,s){const l=e.length;let u=0,c;if(t<0?t=-t>l?0:l+t:t=t>l?l:t,r=r>0?r:0,s.length<1e4)c=Array.from(s),c.unshift(t,r),e.splice(...c);else for(r&&e.splice(t,r);u<s.length;)c=s.slice(u,u+1e4),c.unshift(t,0),e.splice(...c),u+=1e4,t+=1e4}function lr(e,t){return e.length>0?(Yn(e,e.length,0,t),e):t}const ab={}.hasOwnProperty;function Wx(e){const t={};let r=-1;for(;++r<e.length;)zC(t,e[r]);return t}function zC(e,t){let r;for(r in t){const l=(ab.call(e,r)?e[r]:void 0)||(e[r]={}),u=t[r];let c;if(u)for(c in u){ab.call(l,c)||(l[c]=[]);const f=u[c];UC(l[c],Array.isArray(f)?f:f?[f]:[])}}}function UC(e,t){let r=-1;const s=[];for(;++r<t.length;)(t[r].add==="after"?e:s).push(t[r]);Yn(e,0,0,s)}function e1(e,t){const r=Number.parseInt(e,t);return r<9||r===11||r>13&&r<32||r>126&&r<160||r>55295&&r<57344||r>64975&&r<65008||(r&65535)===65535||(r&65535)===65534||r>1114111?"�":String.fromCodePoint(r)}function xr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const wn=Ii(/[A-Za-z]/),pn=Ii(/[\dA-Za-z]/),BC=Ii(/[#-'*+\--9=?A-Z^-~]/);function Pu(e){return e!==null&&(e<32||e===127)}const xd=Ii(/\d/),PC=Ii(/[\dA-Fa-f]/),qC=Ii(/[!-/:-@[-`{-~]/);function Be(e){return e!==null&&e<-2}function jt(e){return e!==null&&(e<0||e===32)}function tt(e){return e===-2||e===-1||e===32}const Zu=Ii(new RegExp("\\p{P}|\\p{S}","u")),gs=Ii(/\s/);function Ii(e){return t;function t(r){return r!==null&&r>-1&&e.test(String.fromCharCode(r))}}function ka(e){const t=[];let r=-1,s=0,l=0;for(;++r<e.length;){const u=e.charCodeAt(r);let c="";if(u===37&&pn(e.charCodeAt(r+1))&&pn(e.charCodeAt(r+2)))l=2;else if(u<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(u))||(c=String.fromCharCode(u));else if(u>55295&&u<57344){const f=e.charCodeAt(r+1);u<56320&&f>56319&&f<57344?(c=String.fromCharCode(u,f),l=1):c="�"}else c=String.fromCharCode(u);c&&(t.push(e.slice(s,r),encodeURIComponent(c)),s=r+l+1,c=""),l&&(r+=l,l=0)}return t.join("")+e.slice(s)}function ot(e,t,r,s){const l=s?s-1:Number.POSITIVE_INFINITY;let u=0;return c;function c(d){return tt(d)?(e.enter(r),f(d)):t(d)}function f(d){return tt(d)&&u++<l?(e.consume(d),f):(e.exit(r),t(d))}}const HC={tokenize:IC};function IC(e){const t=e.attempt(this.parser.constructs.contentInitial,s,l);let r;return t;function s(f){if(f===null){e.consume(f);return}return e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),ot(e,t,"linePrefix")}function l(f){return e.enter("paragraph"),u(f)}function u(f){const d=e.enter("chunkText",{contentType:"text",previous:r});return r&&(r.next=d),r=d,c(f)}function c(f){if(f===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(f);return}return Be(f)?(e.consume(f),e.exit("chunkText"),u):(e.consume(f),c)}}const FC={tokenize:$C},lb={tokenize:YC};function $C(e){const t=this,r=[];let s=0,l,u,c;return f;function f(F){if(s<r.length){const ce=r[s];return t.containerState=ce[1],e.attempt(ce[0].continuation,d,m)(F)}return m(F)}function d(F){if(s++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,l&&P();const ce=t.events.length;let U=ce,D;for(;U--;)if(t.events[U][0]==="exit"&&t.events[U][1].type==="chunkFlow"){D=t.events[U][1].end;break}M(s);let te=ce;for(;te<t.events.length;)t.events[te][1].end={...D},te++;return Yn(t.events,U+1,0,t.events.slice(ce)),t.events.length=te,m(F)}return f(F)}function m(F){if(s===r.length){if(!l)return x(F);if(l.currentConstruct&&l.currentConstruct.concrete)return S(F);t.interrupt=!!(l.currentConstruct&&!l._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(lb,y,g)(F)}function y(F){return l&&P(),M(s),x(F)}function g(F){return t.parser.lazy[t.now().line]=s!==r.length,c=t.now().offset,S(F)}function x(F){return t.containerState={},e.attempt(lb,w,S)(F)}function w(F){return s++,r.push([t.currentConstruct,t.containerState]),x(F)}function S(F){if(F===null){l&&P(),M(0),e.consume(F);return}return l=l||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:l,contentType:"flow",previous:u}),T(F)}function T(F){if(F===null){L(e.exit("chunkFlow"),!0),M(0),e.consume(F);return}return Be(F)?(e.consume(F),L(e.exit("chunkFlow")),s=0,t.interrupt=void 0,f):(e.consume(F),T)}function L(F,ce){const U=t.sliceStream(F);if(ce&&U.push(null),F.previous=u,u&&(u.next=F),u=F,l.defineSkip(F.start),l.write(U),t.parser.lazy[F.start.line]){let D=l.events.length;for(;D--;)if(l.events[D][1].start.offset<c&&(!l.events[D][1].end||l.events[D][1].end.offset>c))return;const te=t.events.length;let $=te,q,R;for(;$--;)if(t.events[$][0]==="exit"&&t.events[$][1].type==="chunkFlow"){if(q){R=t.events[$][1].end;break}q=!0}for(M(s),D=te;D<t.events.length;)t.events[D][1].end={...R},D++;Yn(t.events,$+1,0,t.events.slice(te)),t.events.length=D}}function M(F){let ce=r.length;for(;ce-- >F;){const U=r[ce];t.containerState=U[1],U[0].exit.call(t,e)}r.length=F}function P(){l.write([null]),u=void 0,l=void 0,t.containerState._closeFlow=void 0}}function YC(e,t,r){return ot(e,e.attempt(this.parser.constructs.document,t,r),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ba(e){if(e===null||jt(e)||gs(e))return 1;if(Zu(e))return 2}function Wu(e,t,r){const s=[];let l=-1;for(;++l<e.length;){const u=e[l].resolveAll;u&&!s.includes(u)&&(t=u(t,r),s.push(u))}return t}const vd={name:"attention",resolveAll:GC,tokenize:VC};function GC(e,t){let r=-1,s,l,u,c,f,d,m,y;for(;++r<e.length;)if(e[r][0]==="enter"&&e[r][1].type==="attentionSequence"&&e[r][1]._close){for(s=r;s--;)if(e[s][0]==="exit"&&e[s][1].type==="attentionSequence"&&e[s][1]._open&&t.sliceSerialize(e[s][1]).charCodeAt(0)===t.sliceSerialize(e[r][1]).charCodeAt(0)){if((e[s][1]._close||e[r][1]._open)&&(e[r][1].end.offset-e[r][1].start.offset)%3&&!((e[s][1].end.offset-e[s][1].start.offset+e[r][1].end.offset-e[r][1].start.offset)%3))continue;d=e[s][1].end.offset-e[s][1].start.offset>1&&e[r][1].end.offset-e[r][1].start.offset>1?2:1;const g={...e[s][1].end},x={...e[r][1].start};ob(g,-d),ob(x,d),c={type:d>1?"strongSequence":"emphasisSequence",start:g,end:{...e[s][1].end}},f={type:d>1?"strongSequence":"emphasisSequence",start:{...e[r][1].start},end:x},u={type:d>1?"strongText":"emphasisText",start:{...e[s][1].end},end:{...e[r][1].start}},l={type:d>1?"strong":"emphasis",start:{...c.start},end:{...f.end}},e[s][1].end={...c.start},e[r][1].start={...f.end},m=[],e[s][1].end.offset-e[s][1].start.offset&&(m=lr(m,[["enter",e[s][1],t],["exit",e[s][1],t]])),m=lr(m,[["enter",l,t],["enter",c,t],["exit",c,t],["enter",u,t]]),m=lr(m,Wu(t.parser.constructs.insideSpan.null,e.slice(s+1,r),t)),m=lr(m,[["exit",u,t],["enter",f,t],["exit",f,t],["exit",l,t]]),e[r][1].end.offset-e[r][1].start.offset?(y=2,m=lr(m,[["enter",e[r][1],t],["exit",e[r][1],t]])):y=0,Yn(e,s-1,r-s+3,m),r=s+m.length-y-2;break}}for(r=-1;++r<e.length;)e[r][1].type==="attentionSequence"&&(e[r][1].type="data");return e}function VC(e,t){const r=this.parser.constructs.attentionMarkers.null,s=this.previous,l=ba(s);let u;return c;function c(d){return u=d,e.enter("attentionSequence"),f(d)}function f(d){if(d===u)return e.consume(d),f;const m=e.exit("attentionSequence"),y=ba(d),g=!y||y===2&&l||r.includes(d),x=!l||l===2&&y||r.includes(s);return m._open=!!(u===42?g:g&&(l||!x)),m._close=!!(u===42?x:x&&(y||!g)),t(d)}}function ob(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const JC={name:"autolink",tokenize:XC};function XC(e,t,r){let s=0;return l;function l(w){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(w),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),u}function u(w){return wn(w)?(e.consume(w),c):w===64?r(w):m(w)}function c(w){return w===43||w===45||w===46||pn(w)?(s=1,f(w)):m(w)}function f(w){return w===58?(e.consume(w),s=0,d):(w===43||w===45||w===46||pn(w))&&s++<32?(e.consume(w),f):(s=0,m(w))}function d(w){return w===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(w),e.exit("autolinkMarker"),e.exit("autolink"),t):w===null||w===32||w===60||Pu(w)?r(w):(e.consume(w),d)}function m(w){return w===64?(e.consume(w),y):BC(w)?(e.consume(w),m):r(w)}function y(w){return pn(w)?g(w):r(w)}function g(w){return w===46?(e.consume(w),s=0,y):w===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(w),e.exit("autolinkMarker"),e.exit("autolink"),t):x(w)}function x(w){if((w===45||pn(w))&&s++<63){const S=w===45?x:g;return e.consume(w),S}return r(w)}}const Vl={partial:!0,tokenize:KC};function KC(e,t,r){return s;function s(u){return tt(u)?ot(e,l,"linePrefix")(u):l(u)}function l(u){return u===null||Be(u)?t(u):r(u)}}const t1={continuation:{tokenize:ZC},exit:WC,name:"blockQuote",tokenize:QC};function QC(e,t,r){const s=this;return l;function l(c){if(c===62){const f=s.containerState;return f.open||(e.enter("blockQuote",{_container:!0}),f.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(c),e.exit("blockQuoteMarker"),u}return r(c)}function u(c){return tt(c)?(e.enter("blockQuotePrefixWhitespace"),e.consume(c),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(c))}}function ZC(e,t,r){const s=this;return l;function l(c){return tt(c)?ot(e,u,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c):u(c)}function u(c){return e.attempt(t1,t,r)(c)}}function WC(e){e.exit("blockQuote")}const n1={name:"characterEscape",tokenize:eA};function eA(e,t,r){return s;function s(u){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(u),e.exit("escapeMarker"),l}function l(u){return qC(u)?(e.enter("characterEscapeValue"),e.consume(u),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):r(u)}}const r1={name:"characterReference",tokenize:tA};function tA(e,t,r){const s=this;let l=0,u,c;return f;function f(g){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),d}function d(g){return g===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(g),e.exit("characterReferenceMarkerNumeric"),m):(e.enter("characterReferenceValue"),u=31,c=pn,y(g))}function m(g){return g===88||g===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(g),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),u=6,c=PC,y):(e.enter("characterReferenceValue"),u=7,c=xd,y(g))}function y(g){if(g===59&&l){const x=e.exit("characterReferenceValue");return c===pn&&!Qd(s.sliceSerialize(x))?r(g):(e.enter("characterReferenceMarker"),e.consume(g),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return c(g)&&l++<u?(e.consume(g),y):r(g)}}const ub={partial:!0,tokenize:rA},cb={concrete:!0,name:"codeFenced",tokenize:nA};function nA(e,t,r){const s=this,l={partial:!0,tokenize:U};let u=0,c=0,f;return d;function d(D){return m(D)}function m(D){const te=s.events[s.events.length-1];return u=te&&te[1].type==="linePrefix"?te[2].sliceSerialize(te[1],!0).length:0,f=D,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),y(D)}function y(D){return D===f?(c++,e.consume(D),y):c<3?r(D):(e.exit("codeFencedFenceSequence"),tt(D)?ot(e,g,"whitespace")(D):g(D))}function g(D){return D===null||Be(D)?(e.exit("codeFencedFence"),s.interrupt?t(D):e.check(ub,T,ce)(D)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),x(D))}function x(D){return D===null||Be(D)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),g(D)):tt(D)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),ot(e,w,"whitespace")(D)):D===96&&D===f?r(D):(e.consume(D),x)}function w(D){return D===null||Be(D)?g(D):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),S(D))}function S(D){return D===null||Be(D)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),g(D)):D===96&&D===f?r(D):(e.consume(D),S)}function T(D){return e.attempt(l,ce,L)(D)}function L(D){return e.enter("lineEnding"),e.consume(D),e.exit("lineEnding"),M}function M(D){return u>0&&tt(D)?ot(e,P,"linePrefix",u+1)(D):P(D)}function P(D){return D===null||Be(D)?e.check(ub,T,ce)(D):(e.enter("codeFlowValue"),F(D))}function F(D){return D===null||Be(D)?(e.exit("codeFlowValue"),P(D)):(e.consume(D),F)}function ce(D){return e.exit("codeFenced"),t(D)}function U(D,te,$){let q=0;return R;function R(Y){return D.enter("lineEnding"),D.consume(Y),D.exit("lineEnding"),V}function V(Y){return D.enter("codeFencedFence"),tt(Y)?ot(D,X,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(Y):X(Y)}function X(Y){return Y===f?(D.enter("codeFencedFenceSequence"),le(Y)):$(Y)}function le(Y){return Y===f?(q++,D.consume(Y),le):q>=c?(D.exit("codeFencedFenceSequence"),tt(Y)?ot(D,ee,"whitespace")(Y):ee(Y)):$(Y)}function ee(Y){return Y===null||Be(Y)?(D.exit("codeFencedFence"),te(Y)):$(Y)}}}function rA(e,t,r){const s=this;return l;function l(c){return c===null?r(c):(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),u)}function u(c){return s.parser.lazy[s.now().line]?r(c):t(c)}}const zh={name:"codeIndented",tokenize:sA},iA={partial:!0,tokenize:aA};function sA(e,t,r){const s=this;return l;function l(m){return e.enter("codeIndented"),ot(e,u,"linePrefix",5)(m)}function u(m){const y=s.events[s.events.length-1];return y&&y[1].type==="linePrefix"&&y[2].sliceSerialize(y[1],!0).length>=4?c(m):r(m)}function c(m){return m===null?d(m):Be(m)?e.attempt(iA,c,d)(m):(e.enter("codeFlowValue"),f(m))}function f(m){return m===null||Be(m)?(e.exit("codeFlowValue"),c(m)):(e.consume(m),f)}function d(m){return e.exit("codeIndented"),t(m)}}function aA(e,t,r){const s=this;return l;function l(c){return s.parser.lazy[s.now().line]?r(c):Be(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),l):ot(e,u,"linePrefix",5)(c)}function u(c){const f=s.events[s.events.length-1];return f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?t(c):Be(c)?l(c):r(c)}}const lA={name:"codeText",previous:uA,resolve:oA,tokenize:cA};function oA(e){let t=e.length-4,r=3,s,l;if((e[r][1].type==="lineEnding"||e[r][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(s=r;++s<t;)if(e[s][1].type==="codeTextData"){e[r][1].type="codeTextPadding",e[t][1].type="codeTextPadding",r+=2,t-=2;break}}for(s=r-1,t++;++s<=t;)l===void 0?s!==t&&e[s][1].type!=="lineEnding"&&(l=s):(s===t||e[s][1].type==="lineEnding")&&(e[l][1].type="codeTextData",s!==l+2&&(e[l][1].end=e[s-1][1].end,e.splice(l+2,s-l-2),t-=s-l-2,s=l+2),l=void 0);return e}function uA(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function cA(e,t,r){let s=0,l,u;return c;function c(g){return e.enter("codeText"),e.enter("codeTextSequence"),f(g)}function f(g){return g===96?(e.consume(g),s++,f):(e.exit("codeTextSequence"),d(g))}function d(g){return g===null?r(g):g===32?(e.enter("space"),e.consume(g),e.exit("space"),d):g===96?(u=e.enter("codeTextSequence"),l=0,y(g)):Be(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),d):(e.enter("codeTextData"),m(g))}function m(g){return g===null||g===32||g===96||Be(g)?(e.exit("codeTextData"),d(g)):(e.consume(g),m)}function y(g){return g===96?(e.consume(g),l++,y):l===s?(e.exit("codeTextSequence"),e.exit("codeText"),t(g)):(u.type="codeTextData",m(g))}}class fA{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,r){const s=r??Number.POSITIVE_INFINITY;return s<this.left.length?this.left.slice(t,s):t>this.left.length?this.right.slice(this.right.length-s+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-s+this.left.length).reverse())}splice(t,r,s){const l=r||0;this.setCursor(Math.trunc(t));const u=this.right.splice(this.right.length-l,Number.POSITIVE_INFINITY);return s&&Sl(this.left,s),u.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),Sl(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),Sl(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const r=this.left.splice(t,Number.POSITIVE_INFINITY);Sl(this.right,r.reverse())}else{const r=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);Sl(this.left,r.reverse())}}}function Sl(e,t){let r=0;if(t.length<1e4)e.push(...t);else for(;r<t.length;)e.push(...t.slice(r,r+1e4)),r+=1e4}function i1(e){const t={};let r=-1,s,l,u,c,f,d,m;const y=new fA(e);for(;++r<y.length;){for(;r in t;)r=t[r];if(s=y.get(r),r&&s[1].type==="chunkFlow"&&y.get(r-1)[1].type==="listItemPrefix"&&(d=s[1]._tokenizer.events,u=0,u<d.length&&d[u][1].type==="lineEndingBlank"&&(u+=2),u<d.length&&d[u][1].type==="content"))for(;++u<d.length&&d[u][1].type!=="content";)d[u][1].type==="chunkText"&&(d[u][1]._isInFirstContentOfListItem=!0,u++);if(s[0]==="enter")s[1].contentType&&(Object.assign(t,hA(y,r)),r=t[r],m=!0);else if(s[1]._container){for(u=r,l=void 0;u--;)if(c=y.get(u),c[1].type==="lineEnding"||c[1].type==="lineEndingBlank")c[0]==="enter"&&(l&&(y.get(l)[1].type="lineEndingBlank"),c[1].type="lineEnding",l=u);else if(!(c[1].type==="linePrefix"||c[1].type==="listItemIndent"))break;l&&(s[1].end={...y.get(l)[1].start},f=y.slice(l,r),f.unshift(s),y.splice(l,r-l+1,f))}}return Yn(e,0,Number.POSITIVE_INFINITY,y.slice(0)),!m}function hA(e,t){const r=e.get(t)[1],s=e.get(t)[2];let l=t-1;const u=[];let c=r._tokenizer;c||(c=s.parser[r.contentType](r.start),r._contentTypeTextTrailing&&(c._contentTypeTextTrailing=!0));const f=c.events,d=[],m={};let y,g,x=-1,w=r,S=0,T=0;const L=[T];for(;w;){for(;e.get(++l)[1]!==w;);u.push(l),w._tokenizer||(y=s.sliceStream(w),w.next||y.push(null),g&&c.defineSkip(w.start),w._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=!0),c.write(y),w._isInFirstContentOfListItem&&(c._gfmTasklistFirstContentOfListItem=void 0)),g=w,w=w.next}for(w=r;++x<f.length;)f[x][0]==="exit"&&f[x-1][0]==="enter"&&f[x][1].type===f[x-1][1].type&&f[x][1].start.line!==f[x][1].end.line&&(T=x+1,L.push(T),w._tokenizer=void 0,w.previous=void 0,w=w.next);for(c.events=[],w?(w._tokenizer=void 0,w.previous=void 0):L.pop(),x=L.length;x--;){const M=f.slice(L[x],L[x+1]),P=u.pop();d.push([P,P+M.length-1]),e.splice(P,2,M)}for(d.reverse(),x=-1;++x<d.length;)m[S+d[x][0]]=S+d[x][1],S+=d[x][1]-d[x][0]-1;return m}const dA={resolve:pA,tokenize:gA},mA={partial:!0,tokenize:yA};function pA(e){return i1(e),e}function gA(e,t){let r;return s;function s(f){return e.enter("content"),r=e.enter("chunkContent",{contentType:"content"}),l(f)}function l(f){return f===null?u(f):Be(f)?e.check(mA,c,u)(f):(e.consume(f),l)}function u(f){return e.exit("chunkContent"),e.exit("content"),t(f)}function c(f){return e.consume(f),e.exit("chunkContent"),r.next=e.enter("chunkContent",{contentType:"content",previous:r}),r=r.next,l}}function yA(e,t,r){const s=this;return l;function l(c){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),ot(e,u,"linePrefix")}function u(c){if(c===null||Be(c))return r(c);const f=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&f&&f[1].type==="linePrefix"&&f[2].sliceSerialize(f[1],!0).length>=4?t(c):e.interrupt(s.parser.constructs.flow,r,t)(c)}}function s1(e,t,r,s,l,u,c,f,d){const m=d||Number.POSITIVE_INFINITY;let y=0;return g;function g(M){return M===60?(e.enter(s),e.enter(l),e.enter(u),e.consume(M),e.exit(u),x):M===null||M===32||M===41||Pu(M)?r(M):(e.enter(s),e.enter(c),e.enter(f),e.enter("chunkString",{contentType:"string"}),T(M))}function x(M){return M===62?(e.enter(u),e.consume(M),e.exit(u),e.exit(l),e.exit(s),t):(e.enter(f),e.enter("chunkString",{contentType:"string"}),w(M))}function w(M){return M===62?(e.exit("chunkString"),e.exit(f),x(M)):M===null||M===60||Be(M)?r(M):(e.consume(M),M===92?S:w)}function S(M){return M===60||M===62||M===92?(e.consume(M),w):w(M)}function T(M){return!y&&(M===null||M===41||jt(M))?(e.exit("chunkString"),e.exit(f),e.exit(c),e.exit(s),t(M)):y<m&&M===40?(e.consume(M),y++,T):M===41?(e.consume(M),y--,T):M===null||M===32||M===40||Pu(M)?r(M):(e.consume(M),M===92?L:T)}function L(M){return M===40||M===41||M===92?(e.consume(M),T):T(M)}}function a1(e,t,r,s,l,u){const c=this;let f=0,d;return m;function m(w){return e.enter(s),e.enter(l),e.consume(w),e.exit(l),e.enter(u),y}function y(w){return f>999||w===null||w===91||w===93&&!d||w===94&&!f&&"_hiddenFootnoteSupport"in c.parser.constructs?r(w):w===93?(e.exit(u),e.enter(l),e.consume(w),e.exit(l),e.exit(s),t):Be(w)?(e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),y):(e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||w===91||w===93||Be(w)||f++>999?(e.exit("chunkString"),y(w)):(e.consume(w),d||(d=!tt(w)),w===92?x:g)}function x(w){return w===91||w===92||w===93?(e.consume(w),f++,g):g(w)}}function l1(e,t,r,s,l,u){let c;return f;function f(x){return x===34||x===39||x===40?(e.enter(s),e.enter(l),e.consume(x),e.exit(l),c=x===40?41:x,d):r(x)}function d(x){return x===c?(e.enter(l),e.consume(x),e.exit(l),e.exit(s),t):(e.enter(u),m(x))}function m(x){return x===c?(e.exit(u),d(c)):x===null?r(x):Be(x)?(e.enter("lineEnding"),e.consume(x),e.exit("lineEnding"),ot(e,m,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),y(x))}function y(x){return x===c||x===null||Be(x)?(e.exit("chunkString"),m(x)):(e.consume(x),x===92?g:y)}function g(x){return x===c||x===92?(e.consume(x),y):y(x)}}function Rl(e,t){let r;return s;function s(l){return Be(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r=!0,s):tt(l)?ot(e,s,r?"linePrefix":"lineSuffix")(l):t(l)}}const bA={name:"definition",tokenize:vA},xA={partial:!0,tokenize:wA};function vA(e,t,r){const s=this;let l;return u;function u(w){return e.enter("definition"),c(w)}function c(w){return a1.call(s,e,f,r,"definitionLabel","definitionLabelMarker","definitionLabelString")(w)}function f(w){return l=xr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),w===58?(e.enter("definitionMarker"),e.consume(w),e.exit("definitionMarker"),d):r(w)}function d(w){return jt(w)?Rl(e,m)(w):m(w)}function m(w){return s1(e,y,r,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(w)}function y(w){return e.attempt(xA,g,g)(w)}function g(w){return tt(w)?ot(e,x,"whitespace")(w):x(w)}function x(w){return w===null||Be(w)?(e.exit("definition"),s.parser.defined.push(l),t(w)):r(w)}}function wA(e,t,r){return s;function s(f){return jt(f)?Rl(e,l)(f):r(f)}function l(f){return l1(e,u,r,"definitionTitle","definitionTitleMarker","definitionTitleString")(f)}function u(f){return tt(f)?ot(e,c,"whitespace")(f):c(f)}function c(f){return f===null||Be(f)?t(f):r(f)}}const SA={name:"hardBreakEscape",tokenize:_A};function _A(e,t,r){return s;function s(u){return e.enter("hardBreakEscape"),e.consume(u),l}function l(u){return Be(u)?(e.exit("hardBreakEscape"),t(u)):r(u)}}const kA={name:"headingAtx",resolve:EA,tokenize:CA};function EA(e,t){let r=e.length-2,s=3,l,u;return e[s][1].type==="whitespace"&&(s+=2),r-2>s&&e[r][1].type==="whitespace"&&(r-=2),e[r][1].type==="atxHeadingSequence"&&(s===r-1||r-4>s&&e[r-2][1].type==="whitespace")&&(r-=s+1===r?2:4),r>s&&(l={type:"atxHeadingText",start:e[s][1].start,end:e[r][1].end},u={type:"chunkText",start:e[s][1].start,end:e[r][1].end,contentType:"text"},Yn(e,s,r-s+1,[["enter",l,t],["enter",u,t],["exit",u,t],["exit",l,t]])),e}function CA(e,t,r){let s=0;return l;function l(y){return e.enter("atxHeading"),u(y)}function u(y){return e.enter("atxHeadingSequence"),c(y)}function c(y){return y===35&&s++<6?(e.consume(y),c):y===null||jt(y)?(e.exit("atxHeadingSequence"),f(y)):r(y)}function f(y){return y===35?(e.enter("atxHeadingSequence"),d(y)):y===null||Be(y)?(e.exit("atxHeading"),t(y)):tt(y)?ot(e,f,"whitespace")(y):(e.enter("atxHeadingText"),m(y))}function d(y){return y===35?(e.consume(y),d):(e.exit("atxHeadingSequence"),f(y))}function m(y){return y===null||y===35||jt(y)?(e.exit("atxHeadingText"),f(y)):(e.consume(y),m)}}const AA=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],fb=["pre","script","style","textarea"],jA={concrete:!0,name:"htmlFlow",resolveTo:OA,tokenize:RA},TA={partial:!0,tokenize:DA},NA={partial:!0,tokenize:MA};function OA(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function RA(e,t,r){const s=this;let l,u,c,f,d;return m;function m(A){return y(A)}function y(A){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(A),g}function g(A){return A===33?(e.consume(A),x):A===47?(e.consume(A),u=!0,T):A===63?(e.consume(A),l=3,s.interrupt?t:k):wn(A)?(e.consume(A),c=String.fromCharCode(A),L):r(A)}function x(A){return A===45?(e.consume(A),l=2,w):A===91?(e.consume(A),l=5,f=0,S):wn(A)?(e.consume(A),l=4,s.interrupt?t:k):r(A)}function w(A){return A===45?(e.consume(A),s.interrupt?t:k):r(A)}function S(A){const xe="CDATA[";return A===xe.charCodeAt(f++)?(e.consume(A),f===xe.length?s.interrupt?t:X:S):r(A)}function T(A){return wn(A)?(e.consume(A),c=String.fromCharCode(A),L):r(A)}function L(A){if(A===null||A===47||A===62||jt(A)){const xe=A===47,_e=c.toLowerCase();return!xe&&!u&&fb.includes(_e)?(l=1,s.interrupt?t(A):X(A)):AA.includes(c.toLowerCase())?(l=6,xe?(e.consume(A),M):s.interrupt?t(A):X(A)):(l=7,s.interrupt&&!s.parser.lazy[s.now().line]?r(A):u?P(A):F(A))}return A===45||pn(A)?(e.consume(A),c+=String.fromCharCode(A),L):r(A)}function M(A){return A===62?(e.consume(A),s.interrupt?t:X):r(A)}function P(A){return tt(A)?(e.consume(A),P):R(A)}function F(A){return A===47?(e.consume(A),R):A===58||A===95||wn(A)?(e.consume(A),ce):tt(A)?(e.consume(A),F):R(A)}function ce(A){return A===45||A===46||A===58||A===95||pn(A)?(e.consume(A),ce):U(A)}function U(A){return A===61?(e.consume(A),D):tt(A)?(e.consume(A),U):F(A)}function D(A){return A===null||A===60||A===61||A===62||A===96?r(A):A===34||A===39?(e.consume(A),d=A,te):tt(A)?(e.consume(A),D):$(A)}function te(A){return A===d?(e.consume(A),d=null,q):A===null||Be(A)?r(A):(e.consume(A),te)}function $(A){return A===null||A===34||A===39||A===47||A===60||A===61||A===62||A===96||jt(A)?U(A):(e.consume(A),$)}function q(A){return A===47||A===62||tt(A)?F(A):r(A)}function R(A){return A===62?(e.consume(A),V):r(A)}function V(A){return A===null||Be(A)?X(A):tt(A)?(e.consume(A),V):r(A)}function X(A){return A===45&&l===2?(e.consume(A),H):A===60&&l===1?(e.consume(A),W):A===62&&l===4?(e.consume(A),z):A===63&&l===3?(e.consume(A),k):A===93&&l===5?(e.consume(A),be):Be(A)&&(l===6||l===7)?(e.exit("htmlFlowData"),e.check(TA,K,le)(A)):A===null||Be(A)?(e.exit("htmlFlowData"),le(A)):(e.consume(A),X)}function le(A){return e.check(NA,ee,K)(A)}function ee(A){return e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),Y}function Y(A){return A===null||Be(A)?le(A):(e.enter("htmlFlowData"),X(A))}function H(A){return A===45?(e.consume(A),k):X(A)}function W(A){return A===47?(e.consume(A),c="",oe):X(A)}function oe(A){if(A===62){const xe=c.toLowerCase();return fb.includes(xe)?(e.consume(A),z):X(A)}return wn(A)&&c.length<8?(e.consume(A),c+=String.fromCharCode(A),oe):X(A)}function be(A){return A===93?(e.consume(A),k):X(A)}function k(A){return A===62?(e.consume(A),z):A===45&&l===2?(e.consume(A),k):X(A)}function z(A){return A===null||Be(A)?(e.exit("htmlFlowData"),K(A)):(e.consume(A),z)}function K(A){return e.exit("htmlFlow"),t(A)}}function MA(e,t,r){const s=this;return l;function l(c){return Be(c)?(e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),u):r(c)}function u(c){return s.parser.lazy[s.now().line]?r(c):t(c)}}function DA(e,t,r){return s;function s(l){return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),e.attempt(Vl,t,r)}}const LA={name:"htmlText",tokenize:zA};function zA(e,t,r){const s=this;let l,u,c;return f;function f(k){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(k),d}function d(k){return k===33?(e.consume(k),m):k===47?(e.consume(k),U):k===63?(e.consume(k),F):wn(k)?(e.consume(k),$):r(k)}function m(k){return k===45?(e.consume(k),y):k===91?(e.consume(k),u=0,S):wn(k)?(e.consume(k),P):r(k)}function y(k){return k===45?(e.consume(k),w):r(k)}function g(k){return k===null?r(k):k===45?(e.consume(k),x):Be(k)?(c=g,W(k)):(e.consume(k),g)}function x(k){return k===45?(e.consume(k),w):g(k)}function w(k){return k===62?H(k):k===45?x(k):g(k)}function S(k){const z="CDATA[";return k===z.charCodeAt(u++)?(e.consume(k),u===z.length?T:S):r(k)}function T(k){return k===null?r(k):k===93?(e.consume(k),L):Be(k)?(c=T,W(k)):(e.consume(k),T)}function L(k){return k===93?(e.consume(k),M):T(k)}function M(k){return k===62?H(k):k===93?(e.consume(k),M):T(k)}function P(k){return k===null||k===62?H(k):Be(k)?(c=P,W(k)):(e.consume(k),P)}function F(k){return k===null?r(k):k===63?(e.consume(k),ce):Be(k)?(c=F,W(k)):(e.consume(k),F)}function ce(k){return k===62?H(k):F(k)}function U(k){return wn(k)?(e.consume(k),D):r(k)}function D(k){return k===45||pn(k)?(e.consume(k),D):te(k)}function te(k){return Be(k)?(c=te,W(k)):tt(k)?(e.consume(k),te):H(k)}function $(k){return k===45||pn(k)?(e.consume(k),$):k===47||k===62||jt(k)?q(k):r(k)}function q(k){return k===47?(e.consume(k),H):k===58||k===95||wn(k)?(e.consume(k),R):Be(k)?(c=q,W(k)):tt(k)?(e.consume(k),q):H(k)}function R(k){return k===45||k===46||k===58||k===95||pn(k)?(e.consume(k),R):V(k)}function V(k){return k===61?(e.consume(k),X):Be(k)?(c=V,W(k)):tt(k)?(e.consume(k),V):q(k)}function X(k){return k===null||k===60||k===61||k===62||k===96?r(k):k===34||k===39?(e.consume(k),l=k,le):Be(k)?(c=X,W(k)):tt(k)?(e.consume(k),X):(e.consume(k),ee)}function le(k){return k===l?(e.consume(k),l=void 0,Y):k===null?r(k):Be(k)?(c=le,W(k)):(e.consume(k),le)}function ee(k){return k===null||k===34||k===39||k===60||k===61||k===96?r(k):k===47||k===62||jt(k)?q(k):(e.consume(k),ee)}function Y(k){return k===47||k===62||jt(k)?q(k):r(k)}function H(k){return k===62?(e.consume(k),e.exit("htmlTextData"),e.exit("htmlText"),t):r(k)}function W(k){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),oe}function oe(k){return tt(k)?ot(e,be,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):be(k)}function be(k){return e.enter("htmlTextData"),c(k)}}const Zd={name:"labelEnd",resolveAll:qA,resolveTo:HA,tokenize:IA},UA={tokenize:FA},BA={tokenize:$A},PA={tokenize:YA};function qA(e){let t=-1;const r=[];for(;++t<e.length;){const s=e[t][1];if(r.push(e[t]),s.type==="labelImage"||s.type==="labelLink"||s.type==="labelEnd"){const l=s.type==="labelImage"?4:2;s.type="data",t+=l}}return e.length!==r.length&&Yn(e,0,e.length,r),e}function HA(e,t){let r=e.length,s=0,l,u,c,f;for(;r--;)if(l=e[r][1],u){if(l.type==="link"||l.type==="labelLink"&&l._inactive)break;e[r][0]==="enter"&&l.type==="labelLink"&&(l._inactive=!0)}else if(c){if(e[r][0]==="enter"&&(l.type==="labelImage"||l.type==="labelLink")&&!l._balanced&&(u=r,l.type!=="labelLink")){s=2;break}}else l.type==="labelEnd"&&(c=r);const d={type:e[u][1].type==="labelLink"?"link":"image",start:{...e[u][1].start},end:{...e[e.length-1][1].end}},m={type:"label",start:{...e[u][1].start},end:{...e[c][1].end}},y={type:"labelText",start:{...e[u+s+2][1].end},end:{...e[c-2][1].start}};return f=[["enter",d,t],["enter",m,t]],f=lr(f,e.slice(u+1,u+s+3)),f=lr(f,[["enter",y,t]]),f=lr(f,Wu(t.parser.constructs.insideSpan.null,e.slice(u+s+4,c-3),t)),f=lr(f,[["exit",y,t],e[c-2],e[c-1],["exit",m,t]]),f=lr(f,e.slice(c+1)),f=lr(f,[["exit",d,t]]),Yn(e,u,e.length,f),e}function IA(e,t,r){const s=this;let l=s.events.length,u,c;for(;l--;)if((s.events[l][1].type==="labelImage"||s.events[l][1].type==="labelLink")&&!s.events[l][1]._balanced){u=s.events[l][1];break}return f;function f(x){return u?u._inactive?g(x):(c=s.parser.defined.includes(xr(s.sliceSerialize({start:u.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(x),e.exit("labelMarker"),e.exit("labelEnd"),d):r(x)}function d(x){return x===40?e.attempt(UA,y,c?y:g)(x):x===91?e.attempt(BA,y,c?m:g)(x):c?y(x):g(x)}function m(x){return e.attempt(PA,y,g)(x)}function y(x){return t(x)}function g(x){return u._balanced=!0,r(x)}}function FA(e,t,r){return s;function s(g){return e.enter("resource"),e.enter("resourceMarker"),e.consume(g),e.exit("resourceMarker"),l}function l(g){return jt(g)?Rl(e,u)(g):u(g)}function u(g){return g===41?y(g):s1(e,c,f,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(g)}function c(g){return jt(g)?Rl(e,d)(g):y(g)}function f(g){return r(g)}function d(g){return g===34||g===39||g===40?l1(e,m,r,"resourceTitle","resourceTitleMarker","resourceTitleString")(g):y(g)}function m(g){return jt(g)?Rl(e,y)(g):y(g)}function y(g){return g===41?(e.enter("resourceMarker"),e.consume(g),e.exit("resourceMarker"),e.exit("resource"),t):r(g)}}function $A(e,t,r){const s=this;return l;function l(f){return a1.call(s,e,u,c,"reference","referenceMarker","referenceString")(f)}function u(f){return s.parser.defined.includes(xr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(f):r(f)}function c(f){return r(f)}}function YA(e,t,r){return s;function s(u){return e.enter("reference"),e.enter("referenceMarker"),e.consume(u),e.exit("referenceMarker"),l}function l(u){return u===93?(e.enter("referenceMarker"),e.consume(u),e.exit("referenceMarker"),e.exit("reference"),t):r(u)}}const GA={name:"labelStartImage",resolveAll:Zd.resolveAll,tokenize:VA};function VA(e,t,r){const s=this;return l;function l(f){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(f),e.exit("labelImageMarker"),u}function u(f){return f===91?(e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelImage"),c):r(f)}function c(f){return f===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(f):t(f)}}const JA={name:"labelStartLink",resolveAll:Zd.resolveAll,tokenize:XA};function XA(e,t,r){const s=this;return l;function l(c){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelLink"),u}function u(c){return c===94&&"_hiddenFootnoteSupport"in s.parser.constructs?r(c):t(c)}}const Uh={name:"lineEnding",tokenize:KA};function KA(e,t){return r;function r(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),ot(e,t,"linePrefix")}}const Eu={name:"thematicBreak",tokenize:QA};function QA(e,t,r){let s=0,l;return u;function u(m){return e.enter("thematicBreak"),c(m)}function c(m){return l=m,f(m)}function f(m){return m===l?(e.enter("thematicBreakSequence"),d(m)):s>=3&&(m===null||Be(m))?(e.exit("thematicBreak"),t(m)):r(m)}function d(m){return m===l?(e.consume(m),s++,d):(e.exit("thematicBreakSequence"),tt(m)?ot(e,f,"whitespace")(m):f(m))}}const Nn={continuation:{tokenize:tj},exit:rj,name:"list",tokenize:ej},ZA={partial:!0,tokenize:ij},WA={partial:!0,tokenize:nj};function ej(e,t,r){const s=this,l=s.events[s.events.length-1];let u=l&&l[1].type==="linePrefix"?l[2].sliceSerialize(l[1],!0).length:0,c=0;return f;function f(w){const S=s.containerState.type||(w===42||w===43||w===45?"listUnordered":"listOrdered");if(S==="listUnordered"?!s.containerState.marker||w===s.containerState.marker:xd(w)){if(s.containerState.type||(s.containerState.type=S,e.enter(S,{_container:!0})),S==="listUnordered")return e.enter("listItemPrefix"),w===42||w===45?e.check(Eu,r,m)(w):m(w);if(!s.interrupt||w===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(w)}return r(w)}function d(w){return xd(w)&&++c<10?(e.consume(w),d):(!s.interrupt||c<2)&&(s.containerState.marker?w===s.containerState.marker:w===41||w===46)?(e.exit("listItemValue"),m(w)):r(w)}function m(w){return e.enter("listItemMarker"),e.consume(w),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||w,e.check(Vl,s.interrupt?r:y,e.attempt(ZA,x,g))}function y(w){return s.containerState.initialBlankLine=!0,u++,x(w)}function g(w){return tt(w)?(e.enter("listItemPrefixWhitespace"),e.consume(w),e.exit("listItemPrefixWhitespace"),x):r(w)}function x(w){return s.containerState.size=u+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(w)}}function tj(e,t,r){const s=this;return s.containerState._closeFlow=void 0,e.check(Vl,l,u);function l(f){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,ot(e,t,"listItemIndent",s.containerState.size+1)(f)}function u(f){return s.containerState.furtherBlankLines||!tt(f)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,c(f)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(WA,t,c)(f))}function c(f){return s.containerState._closeFlow=!0,s.interrupt=void 0,ot(e,e.attempt(Nn,t,r),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(f)}}function nj(e,t,r){const s=this;return ot(e,l,"listItemIndent",s.containerState.size+1);function l(u){const c=s.events[s.events.length-1];return c&&c[1].type==="listItemIndent"&&c[2].sliceSerialize(c[1],!0).length===s.containerState.size?t(u):r(u)}}function rj(e){e.exit(this.containerState.type)}function ij(e,t,r){const s=this;return ot(e,l,"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function l(u){const c=s.events[s.events.length-1];return!tt(u)&&c&&c[1].type==="listItemPrefixWhitespace"?t(u):r(u)}}const hb={name:"setextUnderline",resolveTo:sj,tokenize:aj};function sj(e,t){let r=e.length,s,l,u;for(;r--;)if(e[r][0]==="enter"){if(e[r][1].type==="content"){s=r;break}e[r][1].type==="paragraph"&&(l=r)}else e[r][1].type==="content"&&e.splice(r,1),!u&&e[r][1].type==="definition"&&(u=r);const c={type:"setextHeading",start:{...e[s][1].start},end:{...e[e.length-1][1].end}};return e[l][1].type="setextHeadingText",u?(e.splice(l,0,["enter",c,t]),e.splice(u+1,0,["exit",e[s][1],t]),e[s][1].end={...e[u][1].end}):e[s][1]=c,e.push(["exit",c,t]),e}function aj(e,t,r){const s=this;let l;return u;function u(m){let y=s.events.length,g;for(;y--;)if(s.events[y][1].type!=="lineEnding"&&s.events[y][1].type!=="linePrefix"&&s.events[y][1].type!=="content"){g=s.events[y][1].type==="paragraph";break}return!s.parser.lazy[s.now().line]&&(s.interrupt||g)?(e.enter("setextHeadingLine"),l=m,c(m)):r(m)}function c(m){return e.enter("setextHeadingLineSequence"),f(m)}function f(m){return m===l?(e.consume(m),f):(e.exit("setextHeadingLineSequence"),tt(m)?ot(e,d,"lineSuffix")(m):d(m))}function d(m){return m===null||Be(m)?(e.exit("setextHeadingLine"),t(m)):r(m)}}const lj={tokenize:oj};function oj(e){const t=this,r=e.attempt(Vl,s,e.attempt(this.parser.constructs.flowInitial,l,ot(e,e.attempt(this.parser.constructs.flow,l,e.attempt(dA,l)),"linePrefix")));return r;function s(u){if(u===null){e.consume(u);return}return e.enter("lineEndingBlank"),e.consume(u),e.exit("lineEndingBlank"),t.currentConstruct=void 0,r}function l(u){if(u===null){e.consume(u);return}return e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),t.currentConstruct=void 0,r}}const uj={resolveAll:u1()},cj=o1("string"),fj=o1("text");function o1(e){return{resolveAll:u1(e==="text"?hj:void 0),tokenize:t};function t(r){const s=this,l=this.parser.constructs[e],u=r.attempt(l,c,f);return c;function c(y){return m(y)?u(y):f(y)}function f(y){if(y===null){r.consume(y);return}return r.enter("data"),r.consume(y),d}function d(y){return m(y)?(r.exit("data"),u(y)):(r.consume(y),d)}function m(y){if(y===null)return!0;const g=l[y];let x=-1;if(g)for(;++x<g.length;){const w=g[x];if(!w.previous||w.previous.call(s,s.previous))return!0}return!1}}}function u1(e){return t;function t(r,s){let l=-1,u;for(;++l<=r.length;)u===void 0?r[l]&&r[l][1].type==="data"&&(u=l,l++):(!r[l]||r[l][1].type!=="data")&&(l!==u+2&&(r[u][1].end=r[l-1][1].end,r.splice(u+2,l-u-2),l=u+2),u=void 0);return e?e(r,s):r}}function hj(e,t){let r=0;for(;++r<=e.length;)if((r===e.length||e[r][1].type==="lineEnding")&&e[r-1][1].type==="data"){const s=e[r-1][1],l=t.sliceStream(s);let u=l.length,c=-1,f=0,d;for(;u--;){const m=l[u];if(typeof m=="string"){for(c=m.length;m.charCodeAt(c-1)===32;)f++,c--;if(c)break;c=-1}else if(m===-2)d=!0,f++;else if(m!==-1){u++;break}}if(t._contentTypeTextTrailing&&r===e.length&&(f=0),f){const m={type:r===e.length||d||f<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:u?c:s.start._bufferIndex+c,_index:s.start._index+u,line:s.end.line,column:s.end.column-f,offset:s.end.offset-f},end:{...s.end}};s.end={...m.start},s.start.offset===s.end.offset?Object.assign(s,m):(e.splice(r,0,["enter",m,t],["exit",m,t]),r+=2)}r++}return e}const dj={42:Nn,43:Nn,45:Nn,48:Nn,49:Nn,50:Nn,51:Nn,52:Nn,53:Nn,54:Nn,55:Nn,56:Nn,57:Nn,62:t1},mj={91:bA},pj={[-2]:zh,[-1]:zh,32:zh},gj={35:kA,42:Eu,45:[hb,Eu],60:jA,61:hb,95:Eu,96:cb,126:cb},yj={38:r1,92:n1},bj={[-5]:Uh,[-4]:Uh,[-3]:Uh,33:GA,38:r1,42:vd,60:[JC,LA],91:JA,92:[SA,n1],93:Zd,95:vd,96:lA},xj={null:[vd,uj]},vj={null:[42,95]},wj={null:[]},Sj=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:vj,contentInitial:mj,disable:wj,document:dj,flow:gj,flowInitial:pj,insideSpan:xj,string:yj,text:bj},Symbol.toStringTag,{value:"Module"}));function _j(e,t,r){let s={_bufferIndex:-1,_index:0,line:r&&r.line||1,column:r&&r.column||1,offset:r&&r.offset||0};const l={},u=[];let c=[],f=[];const d={attempt:te(U),check:te(D),consume:P,enter:F,exit:ce,interrupt:te(D,{interrupt:!0})},m={code:null,containerState:{},defineSkip:T,events:[],now:S,parser:e,previous:null,sliceSerialize:x,sliceStream:w,write:g};let y=t.tokenize.call(m,d);return t.resolveAll&&u.push(t),m;function g(V){return c=lr(c,V),L(),c[c.length-1]!==null?[]:($(t,0),m.events=Wu(u,m.events,m),m.events)}function x(V,X){return Ej(w(V),X)}function w(V){return kj(c,V)}function S(){const{_bufferIndex:V,_index:X,line:le,column:ee,offset:Y}=s;return{_bufferIndex:V,_index:X,line:le,column:ee,offset:Y}}function T(V){l[V.line]=V.column,R()}function L(){let V;for(;s._index<c.length;){const X=c[s._index];if(typeof X=="string")for(V=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===V&&s._bufferIndex<X.length;)M(X.charCodeAt(s._bufferIndex));else M(X)}}function M(V){y=y(V)}function P(V){Be(V)?(s.line++,s.column=1,s.offset+=V===-3?2:1,R()):V!==-1&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===c[s._index].length&&(s._bufferIndex=-1,s._index++)),m.previous=V}function F(V,X){const le=X||{};return le.type=V,le.start=S(),m.events.push(["enter",le,m]),f.push(le),le}function ce(V){const X=f.pop();return X.end=S(),m.events.push(["exit",X,m]),X}function U(V,X){$(V,X.from)}function D(V,X){X.restore()}function te(V,X){return le;function le(ee,Y,H){let W,oe,be,k;return Array.isArray(ee)?K(ee):"tokenize"in ee?K([ee]):z(ee);function z(je){return Le;function Le($e){const Ce=$e!==null&&je[$e],Ne=$e!==null&&je.null,Te=[...Array.isArray(Ce)?Ce:Ce?[Ce]:[],...Array.isArray(Ne)?Ne:Ne?[Ne]:[]];return K(Te)($e)}}function K(je){return W=je,oe=0,je.length===0?H:A(je[oe])}function A(je){return Le;function Le($e){return k=q(),be=je,je.partial||(m.currentConstruct=je),je.name&&m.parser.constructs.disable.null.includes(je.name)?_e():je.tokenize.call(X?Object.assign(Object.create(m),X):m,d,xe,_e)($e)}}function xe(je){return V(be,k),Y}function _e(je){return k.restore(),++oe<W.length?A(W[oe]):H}}}function $(V,X){V.resolveAll&&!u.includes(V)&&u.push(V),V.resolve&&Yn(m.events,X,m.events.length-X,V.resolve(m.events.slice(X),m)),V.resolveTo&&(m.events=V.resolveTo(m.events,m))}function q(){const V=S(),X=m.previous,le=m.currentConstruct,ee=m.events.length,Y=Array.from(f);return{from:ee,restore:H};function H(){s=V,m.previous=X,m.currentConstruct=le,m.events.length=ee,f=Y,R()}}function R(){s.line in l&&s.column<2&&(s.column=l[s.line],s.offset+=l[s.line]-1)}}function kj(e,t){const r=t.start._index,s=t.start._bufferIndex,l=t.end._index,u=t.end._bufferIndex;let c;if(r===l)c=[e[r].slice(s,u)];else{if(c=e.slice(r,l),s>-1){const f=c[0];typeof f=="string"?c[0]=f.slice(s):c.shift()}u>0&&c.push(e[l].slice(0,u))}return c}function Ej(e,t){let r=-1;const s=[];let l;for(;++r<e.length;){const u=e[r];let c;if(typeof u=="string")c=u;else switch(u){case-5:{c="\r";break}case-4:{c=`
|
|
@@ -117,4 +117,4 @@ Are you sure you want to continue?`):!0}async function ce(){if(!(!P||!F())){w(!0
|
|
|
117
117
|
`))+1))}const c="#".repeat(l),f=r.enter("headingAtx"),d=r.enter("phrasing");u.move(c+" ");let m=r.containerPhrasing(e,{before:"# ",after:`
|
|
118
118
|
`,...u.current()});return/^[\t ]/.test(m)&&(m=Hl(m.charCodeAt(0))+m.slice(1)),m=m?c+" "+m:c,r.options.closeAtx&&(m+=" "+c),d(),f(),m}C1.peek=e3;function C1(e){return e.value||""}function e3(){return"<"}A1.peek=t3;function A1(e,t,r,s){const l=sm(r),u=l==='"'?"Quote":"Apostrophe",c=r.enter("image");let f=r.enter("label");const d=r.createTracker(s);let m=d.move("![");return m+=d.move(r.safe(e.alt,{before:m,after:"]",...d.current()})),m+=d.move("]("),f(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(f=r.enter("destinationLiteral"),m+=d.move("<"),m+=d.move(r.safe(e.url,{before:m,after:">",...d.current()})),m+=d.move(">")):(f=r.enter("destinationRaw"),m+=d.move(r.safe(e.url,{before:m,after:e.title?" ":")",...d.current()}))),f(),e.title&&(f=r.enter(`title${u}`),m+=d.move(" "+l),m+=d.move(r.safe(e.title,{before:m,after:l,...d.current()})),m+=d.move(l),f()),m+=d.move(")"),c(),m}function t3(){return"!"}j1.peek=n3;function j1(e,t,r,s){const l=e.referenceType,u=r.enter("imageReference");let c=r.enter("label");const f=r.createTracker(s);let d=f.move("![");const m=r.safe(e.alt,{before:d,after:"]",...f.current()});d+=f.move(m+"]["),c();const y=r.stack;r.stack=[],c=r.enter("reference");const g=r.safe(r.associationId(e),{before:d,after:"]",...f.current()});return c(),r.stack=y,u(),l==="full"||!m||m!==g?d+=f.move(g+"]"):l==="shortcut"?d=d.slice(0,-1):d+=f.move("]"),d}function n3(){return"!"}T1.peek=r3;function T1(e,t,r){let s=e.value||"",l="`",u=-1;for(;new RegExp("(^|[^`])"+l+"([^`]|$)").test(s);)l+="`";for(/[^ \r\n]/.test(s)&&(/^[ \r\n]/.test(s)&&/[ \r\n]$/.test(s)||/^`|`$/.test(s))&&(s=" "+s+" ");++u<r.unsafe.length;){const c=r.unsafe[u],f=r.compilePattern(c);let d;if(c.atBreak)for(;d=f.exec(s);){let m=d.index;s.charCodeAt(m)===10&&s.charCodeAt(m-1)===13&&m--,s=s.slice(0,m)+" "+s.slice(d.index+1)}}return l+s+l}function r3(){return"`"}function N1(e,t){const r=Kd(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(r===e.url||"mailto:"+r===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}O1.peek=i3;function O1(e,t,r,s){const l=sm(r),u=l==='"'?"Quote":"Apostrophe",c=r.createTracker(s);let f,d;if(N1(e,r)){const y=r.stack;r.stack=[],f=r.enter("autolink");let g=c.move("<");return g+=c.move(r.containerPhrasing(e,{before:g,after:">",...c.current()})),g+=c.move(">"),f(),r.stack=y,g}f=r.enter("link"),d=r.enter("label");let m=c.move("[");return m+=c.move(r.containerPhrasing(e,{before:m,after:"](",...c.current()})),m+=c.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=r.enter("destinationLiteral"),m+=c.move("<"),m+=c.move(r.safe(e.url,{before:m,after:">",...c.current()})),m+=c.move(">")):(d=r.enter("destinationRaw"),m+=c.move(r.safe(e.url,{before:m,after:e.title?" ":")",...c.current()}))),d(),e.title&&(d=r.enter(`title${u}`),m+=c.move(" "+l),m+=c.move(r.safe(e.title,{before:m,after:l,...c.current()})),m+=c.move(l),d()),m+=c.move(")"),f(),m}function i3(e,t,r){return N1(e,r)?"<":"["}R1.peek=s3;function R1(e,t,r,s){const l=e.referenceType,u=r.enter("linkReference");let c=r.enter("label");const f=r.createTracker(s);let d=f.move("[");const m=r.containerPhrasing(e,{before:d,after:"]",...f.current()});d+=f.move(m+"]["),c();const y=r.stack;r.stack=[],c=r.enter("reference");const g=r.safe(r.associationId(e),{before:d,after:"]",...f.current()});return c(),r.stack=y,u(),l==="full"||!m||m!==g?d+=f.move(g+"]"):l==="shortcut"?d=d.slice(0,-1):d+=f.move("]"),d}function s3(){return"["}function am(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function a3(e){const t=am(e),r=e.options.bulletOther;if(!r)return t==="*"?"-":"*";if(r!=="*"&&r!=="+"&&r!=="-")throw new Error("Cannot serialize items with `"+r+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(r===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+r+"`) to be different");return r}function l3(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function M1(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function o3(e,t,r,s){const l=r.enter("list"),u=r.bulletCurrent;let c=e.ordered?l3(r):am(r);const f=e.ordered?c==="."?")":".":a3(r);let d=t&&r.bulletLastUsed?c===r.bulletLastUsed:!1;if(!e.ordered){const y=e.children?e.children[0]:void 0;if((c==="*"||c==="-")&&y&&(!y.children||!y.children[0])&&r.stack[r.stack.length-1]==="list"&&r.stack[r.stack.length-2]==="listItem"&&r.stack[r.stack.length-3]==="list"&&r.stack[r.stack.length-4]==="listItem"&&r.indexStack[r.indexStack.length-1]===0&&r.indexStack[r.indexStack.length-2]===0&&r.indexStack[r.indexStack.length-3]===0&&(d=!0),M1(r)===c&&y){let g=-1;for(;++g<e.children.length;){const x=e.children[g];if(x&&x.type==="listItem"&&x.children&&x.children[0]&&x.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(c=f),r.bulletCurrent=c;const m=r.containerFlow(e,s);return r.bulletLastUsed=c,r.bulletCurrent=u,l(),m}function u3(e){const t=e.options.listItemIndent||"one";if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function c3(e,t,r,s){const l=u3(r);let u=r.bulletCurrent||am(r);t&&t.type==="list"&&t.ordered&&(u=(typeof t.start=="number"&&t.start>-1?t.start:1)+(r.options.incrementListMarker===!1?0:t.children.indexOf(e))+u);let c=u.length+1;(l==="tab"||l==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(c=Math.ceil(c/4)*4);const f=r.createTracker(s);f.move(u+" ".repeat(c-u.length)),f.shift(c);const d=r.enter("listItem"),m=r.indentLines(r.containerFlow(e,f.current()),y);return d(),m;function y(g,x,w){return x?(w?"":" ".repeat(c))+g:(w?u:u+" ".repeat(c-u.length))+g}}function f3(e,t,r,s){const l=r.enter("paragraph"),u=r.enter("phrasing"),c=r.containerPhrasing(e,s);return u(),l(),c}const h3=tc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function d3(e,t,r,s){return(e.children.some(function(c){return h3(c)})?r.containerPhrasing:r.containerFlow).call(r,e,s)}function m3(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}D1.peek=p3;function D1(e,t,r,s){const l=m3(r),u=r.enter("strong"),c=r.createTracker(s),f=c.move(l+l);let d=c.move(r.containerPhrasing(e,{after:l,before:f,...c.current()}));const m=d.charCodeAt(0),y=Iu(s.before.charCodeAt(s.before.length-1),m,l);y.inside&&(d=Hl(m)+d.slice(1));const g=d.charCodeAt(d.length-1),x=Iu(s.after.charCodeAt(0),g,l);x.inside&&(d=d.slice(0,-1)+Hl(g));const w=c.move(l+l);return u(),r.attentionEncodeSurroundingInfo={after:x.outside,before:y.outside},f+d+w}function p3(e,t,r){return r.options.strong||"*"}function g3(e,t,r,s){return r.safe(e.value,s)}function y3(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function b3(e,t,r){const s=(M1(r)+(r.options.ruleSpaces?" ":"")).repeat(y3(r));return r.options.ruleSpaces?s.slice(0,-1):s}const L1={blockquote:HN,break:Db,code:VN,definition:XN,emphasis:E1,hardBreak:Db,heading:WN,html:C1,image:A1,imageReference:j1,inlineCode:T1,link:O1,linkReference:R1,list:o3,listItem:c3,paragraph:f3,root:d3,strong:D1,text:g3,thematicBreak:b3};function x3(){return{enter:{table:v3,tableData:Lb,tableHeader:Lb,tableRow:S3},exit:{codeText:_3,table:w3,tableData:Xh,tableHeader:Xh,tableRow:Xh}}}function v3(e){const t=e._align;this.enter({type:"table",align:t.map(function(r){return r==="none"?null:r}),children:[]},e),this.data.inTable=!0}function w3(e){this.exit(e),this.data.inTable=void 0}function S3(e){this.enter({type:"tableRow",children:[]},e)}function Xh(e){this.exit(e)}function Lb(e){this.enter({type:"tableCell",children:[]},e)}function _3(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,k3));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function k3(e,t){return t==="|"?t:e}function E3(e){const t=e||{},r=t.tableCellPadding,s=t.tablePipeAlign,l=t.stringLength,u=r?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
119
119
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:x,table:c,tableCell:d,tableRow:f}};function c(w,S,T,L){return m(y(w,T,L),w.align)}function f(w,S,T,L){const M=g(w,T,L),P=m([M]);return P.slice(0,P.indexOf(`
|
|
120
|
-
`))}function d(w,S,T,L){const M=T.enter("tableCell"),P=T.enter("phrasing"),F=T.containerPhrasing(w,{...L,before:u,after:u});return P(),M(),F}function m(w,S){return PN(w,{align:S,alignDelimiters:s,padding:r,stringLength:l})}function y(w,S,T){const L=w.children;let M=-1;const P=[],F=S.enter("table");for(;++M<L.length;)P[M]=g(L[M],S,T);return F(),P}function g(w,S,T){const L=w.children;let M=-1;const P=[],F=S.enter("tableRow");for(;++M<L.length;)P[M]=d(L[M],w,S,T);return F(),P}function x(w,S,T){let L=L1.inlineCode(w,S,T);return T.stack.includes("tableCell")&&(L=L.replace(/\|/g,"\\$&")),L}}function C3(){return{exit:{taskListCheckValueChecked:zb,taskListCheckValueUnchecked:zb,paragraph:j3}}}function A3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:T3}}}function zb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function j3(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const l=t.children;let u=-1,c;for(;++u<l.length;){const f=l[u];if(f.type==="paragraph"){c=f;break}}c===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function T3(e,t,r,s){const l=e.children[0],u=typeof e.checked=="boolean"&&l&&l.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=r.createTracker(s);u&&f.move(c);let d=L1.listItem(e,t,r,{...s,...f.current()});return u&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(y){return y+c}}function N3(){return[oN(),TN(),MN(),x3(),C3()]}function O3(e){return{extensions:[uN(),NN(e),DN(),E3(e),A3()]}}const R3={tokenize:B3,partial:!0},z1={tokenize:P3,partial:!0},U1={tokenize:q3,partial:!0},B1={tokenize:H3,partial:!0},M3={tokenize:I3,partial:!0},P1={name:"wwwAutolink",tokenize:z3,previous:H1},q1={name:"protocolAutolink",tokenize:U3,previous:I1},ri={name:"emailAutolink",tokenize:L3,previous:F1},Rr={};function D3(){return{text:Rr}}let hs=48;for(;hs<123;)Rr[hs]=ri,hs++,hs===58?hs=65:hs===91&&(hs=97);Rr[43]=ri;Rr[45]=ri;Rr[46]=ri;Rr[95]=ri;Rr[72]=[ri,q1];Rr[104]=[ri,q1];Rr[87]=[ri,P1];Rr[119]=[ri,P1];function L3(e,t,r){const s=this;let l,u;return c;function c(g){return!Ed(g)||!F1.call(s,s.previous)||lm(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return Ed(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(M3,y,m)(g):g===45||g===95||pn(g)?(u=!0,e.consume(g),d):y(g)}function m(g){return e.consume(g),l=!0,d}function y(g){return u&&l&&wn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function z3(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!H1.call(s,s.previous)||lm(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(R3,e.attempt(z1,e.attempt(U1,u),r),r)(c))}function u(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function U3(e,t,r){const s=this;let l="",u=!1;return c;function c(g){return(g===72||g===104)&&I1.call(s,s.previous)&&!lm(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(wn(g)&&l.length<5)return l+=String.fromCodePoint(g),e.consume(g),f;if(g===58){const x=l.toLowerCase();if(x==="http"||x==="https")return e.consume(g),d}return r(g)}function d(g){return g===47?(e.consume(g),u?m:(u=!0,d)):r(g)}function m(g){return g===null||Pu(g)||jt(g)||gs(g)||Zu(g)?r(g):e.attempt(z1,e.attempt(U1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function B3(e,t,r){let s=0;return l;function l(c){return(c===87||c===119)&&s<3?(s++,e.consume(c),l):c===46&&s===3?(e.consume(c),u):r(c)}function u(c){return c===null?r(c):t(c)}}function P3(e,t,r){let s,l,u;return c;function c(m){return m===46||m===95?e.check(B1,d,f)(m):m===null||jt(m)||gs(m)||m!==45&&Zu(m)?d(m):(u=!0,e.consume(m),c)}function f(m){return m===95?s=!0:(l=s,s=void 0),e.consume(m),c}function d(m){return l||s||!u?r(m):t(m)}}function q3(e,t){let r=0,s=0;return l;function l(c){return c===40?(r++,e.consume(c),l):c===41&&s<r?u(c):c===33||c===34||c===38||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===60||c===63||c===93||c===95||c===126?e.check(B1,t,u)(c):c===null||jt(c)||gs(c)?t(c):(e.consume(c),l)}function u(c){return c===41&&s++,e.consume(c),l}}function H3(e,t,r){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),u):f===93?(e.consume(f),l):f===60||f===null||jt(f)||gs(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||jt(f)||gs(f)?t(f):s(f)}function u(f){return wn(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):wn(f)?(e.consume(f),c):r(f)}}function I3(e,t,r){return s;function s(u){return e.consume(u),l}function l(u){return pn(u)?r(u):t(u)}}function H1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||jt(e)}function I1(e){return!wn(e)}function F1(e){return!(e===47||Ed(e))}function Ed(e){return e===43||e===45||e===46||e===95||pn(e)}function lm(e){let t=e.length,r=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const F3={tokenize:Q3,partial:!0};function $3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:J3,continuation:{tokenize:X3},exit:K3}},text:{91:{name:"gfmFootnoteCall",tokenize:V3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Y3,resolveTo:G3}}}}function Y3(e,t,r){const s=this;let l=s.events.length;const u=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;l--;){const d=s.events[l][1];if(d.type==="labelImage"){c=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return f;function f(d){if(!c||!c._balanced)return r(d);const m=xr(s.sliceSerialize({start:c.end,end:s.now()}));return m.codePointAt(0)!==94||!u.includes(m.slice(1))?r(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),t(d))}}function G3(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},l={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};l.end.column++,l.end.offset++,l.end._bufferIndex++;const u={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},u.start),end:Object.assign({},u.end)},f=[e[r+1],e[r+2],["enter",s,t],e[r+3],e[r+4],["enter",l,t],["exit",l,t],["enter",u,t],["enter",c,t],["exit",c,t],["exit",u,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(r,e.length-r+1,...f),e}function V3(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u=0,c;return f;function f(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),d}function d(g){return g!==94?r(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",m)}function m(g){if(u>999||g===93&&!c||g===null||g===91||jt(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(xr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return jt(g)||(c=!0),u++,e.consume(g),g===92?y:m}function y(g){return g===91||g===92||g===93?(e.consume(g),u++,m):m(g)}}function J3(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u,c=0,f;return d;function d(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",y):r(S)}function y(S){if(c>999||S===93&&!f||S===null||S===91||jt(S))return r(S);if(S===93){e.exit("chunkString");const T=e.exit("gfmFootnoteDefinitionLabelString");return u=xr(s.sliceSerialize(T)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return jt(S)||(f=!0),c++,e.consume(S),S===92?g:y}function g(S){return S===91||S===92||S===93?(e.consume(S),c++,y):y(S)}function x(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),l.includes(u)||l.push(u),ot(e,w,"gfmFootnoteDefinitionWhitespace")):r(S)}function w(S){return t(S)}}function X3(e,t,r){return e.check(Vl,t,e.attempt(F3,t,r))}function K3(e){e.exit("gfmFootnoteDefinition")}function Q3(e,t,r){const s=this;return ot(e,l,"gfmFootnoteDefinitionIndent",5);function l(u){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(u):r(u)}}function Z3(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:u,resolveAll:l};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function l(c,f){let d=-1;for(;++d<c.length;)if(c[d][0]==="enter"&&c[d][1].type==="strikethroughSequenceTemporary"&&c[d][1]._close){let m=d;for(;m--;)if(c[m][0]==="exit"&&c[m][1].type==="strikethroughSequenceTemporary"&&c[m][1]._open&&c[d][1].end.offset-c[d][1].start.offset===c[m][1].end.offset-c[m][1].start.offset){c[d][1].type="strikethroughSequence",c[m][1].type="strikethroughSequence";const y={type:"strikethrough",start:Object.assign({},c[m][1].start),end:Object.assign({},c[d][1].end)},g={type:"strikethroughText",start:Object.assign({},c[m][1].end),end:Object.assign({},c[d][1].start)},x=[["enter",y,f],["enter",c[m][1],f],["exit",c[m][1],f],["enter",g,f]],w=f.parser.constructs.insideSpan.null;w&&Yn(x,x.length,0,Wu(w,c.slice(m+1,d),f)),Yn(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),Yn(c,m-1,d-m+3,x),d=m+x.length-2;break}}for(d=-1;++d<c.length;)c[d][1].type==="strikethroughSequenceTemporary"&&(c[d][1].type="data");return c}function u(c,f,d){const m=this.previous,y=this.events;let g=0;return x;function x(S){return m===126&&y[y.length-1][1].type!=="characterEscape"?d(S):(c.enter("strikethroughSequenceTemporary"),w(S))}function w(S){const T=ba(m);if(S===126)return g>1?d(S):(c.consume(S),g++,w);if(g<2&&!r)return d(S);const L=c.exit("strikethroughSequenceTemporary"),M=ba(S);return L._open=!M||M===2&&!!T,L._close=!T||T===2&&!!M,f(S)}}}class W3{constructor(){this.map=[]}add(t,r,s){eO(this,t,r,s)}consume(t){if(this.map.sort(function(u,c){return u[0]-c[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];s.push(t.slice()),t.length=0;let l=s.pop();for(;l;){for(const u of l)t.push(u);l=s.pop()}this.map.length=0}}function eO(e,t,r,s){let l=0;if(!(r===0&&s.length===0)){for(;l<e.map.length;){if(e.map[l][0]===t){e.map[l][1]+=r,e.map[l][2].push(...s);return}l+=1}e.map.push([t,r,s])}}function tO(e,t){let r=!1;const s=[];for(;t<e.length;){const l=e[t];if(r){if(l[0]==="enter")l[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(l[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const u=s.length-1;s[u]=s[u]==="left"?"center":"right"}}else if(l[1].type==="tableDelimiterRow")break}else l[0]==="enter"&&l[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return s}function nO(){return{flow:{null:{name:"table",tokenize:rO,resolveAll:iO}}}}function rO(e,t,r){const s=this;let l=0,u=0,c;return f;function f(R){let V=s.events.length-1;for(;V>-1;){const ee=s.events[V][1].type;if(ee==="lineEnding"||ee==="linePrefix")V--;else break}const X=V>-1?s.events[V][1].type:null,le=X==="tableHead"||X==="tableRow"?D:d;return le===D&&s.parser.lazy[s.now().line]?r(R):le(R)}function d(R){return e.enter("tableHead"),e.enter("tableRow"),m(R)}function m(R){return R===124||(c=!0,u+=1),y(R)}function y(R){return R===null?r(R):Be(R)?u>1?(u=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(R),e.exit("lineEnding"),w):r(R):tt(R)?ot(e,y,"whitespace")(R):(u+=1,c&&(c=!1,l+=1),R===124?(e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(R)))}function g(R){return R===null||R===124||jt(R)?(e.exit("data"),y(R)):(e.consume(R),R===92?x:g)}function x(R){return R===92||R===124?(e.consume(R),g):g(R)}function w(R){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(R):(e.enter("tableDelimiterRow"),c=!1,tt(R)?ot(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):S(R))}function S(R){return R===45||R===58?L(R):R===124?(c=!0,e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),T):U(R)}function T(R){return tt(R)?ot(e,L,"whitespace")(R):L(R)}function L(R){return R===58?(u+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(R),e.exit("tableDelimiterMarker"),M):R===45?(u+=1,M(R)):R===null||Be(R)?ce(R):U(R)}function M(R){return R===45?(e.enter("tableDelimiterFiller"),P(R)):U(R)}function P(R){return R===45?(e.consume(R),P):R===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(R),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(R))}function F(R){return tt(R)?ot(e,ce,"whitespace")(R):ce(R)}function ce(R){return R===124?S(R):R===null||Be(R)?!c||l!==u?U(R):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(R)):U(R)}function U(R){return r(R)}function D(R){return e.enter("tableRow"),te(R)}function te(R){return R===124?(e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),te):R===null||Be(R)?(e.exit("tableRow"),t(R)):tt(R)?ot(e,te,"whitespace")(R):(e.enter("data"),$(R))}function $(R){return R===null||R===124||jt(R)?(e.exit("data"),te(R)):(e.consume(R),R===92?q:$)}function q(R){return R===92||R===124?(e.consume(R),$):$(R)}}function iO(e,t){let r=-1,s=!0,l=0,u=[0,0,0,0],c=[0,0,0,0],f=!1,d=0,m,y,g;const x=new W3;for(;++r<e.length;){const w=e[r],S=w[1];w[0]==="enter"?S.type==="tableHead"?(f=!1,d!==0&&(Ub(x,t,d,m,y),y=void 0,d=0),m={type:"table",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",m,t]])):S.type==="tableRow"||S.type==="tableDelimiterRow"?(s=!0,g=void 0,u=[0,0,0,0],c=[0,r+1,0,0],f&&(f=!1,y={type:"tableBody",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",y,t]])),l=S.type==="tableDelimiterRow"?2:y?3:1):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(u[1]!==0&&(c[0]=c[1],g=bu(x,t,u,l,void 0,g),u=[0,0,0,0]),c[2]=r)):S.type==="tableCellDivider"&&(s?s=!1:(u[1]!==0&&(c[0]=c[1],g=bu(x,t,u,l,void 0,g)),u=c,c=[u[1],r,0,0])):S.type==="tableHead"?(f=!0,d=r):S.type==="tableRow"||S.type==="tableDelimiterRow"?(d=r,u[1]!==0?(c[0]=c[1],g=bu(x,t,u,l,r,g)):c[1]!==0&&(g=bu(x,t,c,l,r,g)),l=0):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Ub(x,t,d,m,y),x.consume(t.events),r=-1;++r<t.events.length;){const w=t.events[r];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=tO(t.events,r))}return e}function bu(e,t,r,s,l,u){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";r[0]!==0&&(u.end=Object.assign({},ia(t.events,r[0])),e.add(r[0],0,[["exit",u,t]]));const d=ia(t.events,r[1]);if(u={type:c,start:Object.assign({},d),end:Object.assign({},d)},e.add(r[1],0,[["enter",u,t]]),r[2]!==0){const m=ia(t.events,r[2]),y=ia(t.events,r[3]),g={type:f,start:Object.assign({},m),end:Object.assign({},y)};if(e.add(r[2],0,[["enter",g,t]]),s!==2){const x=t.events[r[2]],w=t.events[r[3]];if(x[1].end=Object.assign({},w[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const S=r[2]+1,T=r[3]-r[2]-1;e.add(S,T,[])}}e.add(r[3]+1,0,[["exit",g,t]])}return l!==void 0&&(u.end=Object.assign({},ia(t.events,l)),e.add(l,0,[["exit",u,t]]),u=void 0),u}function Ub(e,t,r,s,l){const u=[],c=ia(t.events,r);l&&(l.end=Object.assign({},c),u.push(["exit",l,t])),s.end=Object.assign({},c),u.push(["exit",s,t]),e.add(r+1,0,u)}function ia(e,t){const r=e[t],s=r[0]==="enter"?"start":"end";return r[1][s]}const sO={name:"tasklistCheck",tokenize:lO};function aO(){return{text:{91:sO}}}function lO(e,t,r){const s=this;return l;function l(d){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),u)}function u(d){return jt(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),c):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),c):r(d)}function c(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):r(d)}function f(d){return Be(d)?t(d):tt(d)?e.check({tokenize:oO},t,r)(d):r(d)}}function oO(e,t,r){return ot(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function uO(e){return Wx([D3(),$3(),Z3(e),nO(),aO()])}const cO={};function Bb(e){const t=this,r=e||cO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),u=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(uO(r)),u.push(N3()),c.push(O3(r))}function fO(e){v1(e,[/\r?\n|\r/g,hO])}function hO(){return{type:"break"}}function Pb(){return function(e){fO(e)}}function dO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:u}){const c=Or(),[f,d]=j.useState(!0),[m,y]=j.useState([]),[g,x]=j.useState(),[w,S]=j.useState(),T=g==="started"||g==="monitoring",L=g==="followup",M=g==="started"||g==="followup",[P,F]=j.useState(null);md(P!==null,()=>F(null));const[ce,U]=j.useState(!1),[D,te]=j.useState(""),[$,q]=j.useState(!1),R=j.useRef(null),V=j.useRef(null),X=j.useRef(null),[le,ee]=j.useState(u==="latest"?void 0:u),Y=u==="latest"&&le===null;j.useEffect(()=>{if(u!=="latest"){ee(u);return}e&&(ee(void 0),r("taskrun.list",{task_id:l,limit:1}).then(k=>{var z,K;return ee(((K=(z=k.entries)==null?void 0:z[0])==null?void 0:K.run_id)??null)}).catch(()=>ee(null)))},[u,l,e,r]);async function H(){if(le)try{const k=await r("task.result",{id:l,run_id:le});if(k.error){console.error("No result:",k.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}y(k.messages??[]),x(k.running_state),S(k.agent)}catch(k){console.error("Failed to load result:",k),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{d(!1)}}async function W(k){var z;if(le)try{const A=(z=(await r("task.reports",{id:l,run_id:le,report_files:[k]})).reports)==null?void 0:z[0];A!=null&&A.data_url?F({file:k,data_url:A.data_url}):F({file:k,content:(A==null?void 0:A.content)??"Report not found."})}catch{F({file:k,content:"Failed to load report."})}}j.useEffect(()=>{!e||!le||(d(!0),H())},[e,l,le]),j.useEffect(()=>!e||!t||!le?void 0:s(t,async z=>{try{const K=JSON.parse(new TextDecoder().decode(z.data));if(K.event_type!=="running-state"&&K.event_type!=="result-updated"||z.subject.split(".").pop()!==l||K.event_type==="result-updated"&&K.run_id&&K.run_id!==le)return;H()}catch{}}),[e,t,l,le,s,r]),j.useEffect(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight)},[m]),j.useEffect(()=>{f||Y||!le||X.current!==le&&(X.current=le,requestAnimationFrame(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[f,Y,le]);function oe(k){if(k==="input")return"User Input";if(k==="permission")return"Permission";if(k==="confirmation")return"Confirmation"}function be(k){return k==="started"?"Task started":k==="finished"?"Task finished":k==="failed"?"Task failed":k==="error"?"Command failed":k==="aborted"?"Task aborted":k==="confirmation"?"Task confirmed":k==="stopped"?"Follow-up stopped":k??""}return b.jsxs("div",{className:"run-detail",children:[b.jsxs("button",{className:"run-detail-back",onClick:()=>c(-1),children:[b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M15 18l-6-6 6-6"})}),"Back"]}),Y?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No runs yet"}),b.jsx("p",{className:"empty-state-hint",children:"This task hasn't been executed yet. Run it from the task menu or wait for its next trigger."})]}):f?b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)",padding:"var(--space-sm) 0"},children:[b.jsx("div",{className:"skeleton-line",style:{width:"40%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"55%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"8rem",marginTop:"var(--space-sm)"}})]}):b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"chat-thread",ref:R,children:[m.map((k,z)=>{const K=M&&k.role==="assistant"&&!m.slice(z+1).some(A=>A.role==="assistant"||A.role==="user");return k.role==="status"&&k.type==="monitoring"?null:k.role==="status"?b.jsxs("div",{className:`chat-status${k.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[be(k.type),k.time>0&&b.jsx("span",{className:"chat-status-time",children:Bu(k.time)})]}),k.content&&b.jsx("pre",{className:"chat-status-detail",children:k.content})]},z):b.jsxs("div",{className:`chat-message chat-message--${k.role}`,children:[k.role==="assistant"&&w&&b.jsx("div",{className:"chat-message-agent",children:dd(w)}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(Nb,{remarkPlugins:[Bb,Pb],children:k.content}),K&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),k.attachments&&k.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:k.attachments.map(A=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>W(A),children:A},A))}),b.jsxs("div",{className:"chat-message-meta",children:[oe(k.type)&&b.jsx("span",{className:"chat-message-type",children:oe(k.type)}),k.time>0&&b.jsx("span",{children:Bu(k.time)})]})]},z)}),M&&(()=>{const k=m.filter(z=>z.role!=="status");return k.length===0||k[k.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[w&&b.jsx("div",{className:"chat-message-agent",children:dd(w)}),b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),g==="monitoring"&&b.jsxs("div",{className:"chat-monitoring-indicator",children:[b.jsx("span",{className:"chat-monitoring-dot"}),"Monitoring command output"]})]}),T?b.jsx("div",{className:"chat-abort-bar",children:b.jsx("button",{className:"btn btn-secondary chat-abort-btn",disabled:ce,onClick:async()=>{if(confirm("Abort this task?")){U(!0);try{await r("task.abort",{id:l})}catch(k){console.error("Abort failed:",k)}finally{U(!1)}}},children:ce?"Aborting...":"Abort Task"})}):L?b.jsx("div",{className:"chat-input-bar",children:b.jsx("button",{className:"btn btn-secondary chat-stop-btn",disabled:ce,onClick:async()=>{U(!0);try{await r("task.stop_followup",{id:l,run_id:le})}catch(k){console.error("Stop failed:",k)}finally{U(!1)}},children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:b.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})})}):b.jsxs("form",{className:"chat-input-bar",onSubmit:async k=>{k.preventDefault();const z=D.trim();if(!(!z||$)){q(!0);try{await r("task.followup",{id:l,run_id:le,message:z}),te("")}catch(K){console.error("Follow-up failed:",K)}finally{q(!1)}}},children:[b.jsx("input",{ref:V,className:"chat-input",type:"text",placeholder:"Follow-up message",value:D,onChange:k=>te(k.target.value),disabled:$}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!D.trim()||$,children:b.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),b.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]}),P&&b.jsx("div",{className:"report-dialog-overlay",onClick:()=>F(null),children:b.jsxs("div",{className:"report-dialog",onClick:k=>k.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:P.file}),b.jsx("button",{className:"report-dialog-close",onClick:()=>F(null),"aria-label":"Close",children:b.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),b.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),b.jsx("div",{className:"report-dialog-body",children:P.data_url?b.jsx("img",{src:P.data_url,alt:P.file,style:{maxWidth:"100%",height:"auto"}}):b.jsx(Nb,{remarkPlugins:[Bb,Pb],components:{a:({...k})=>b.jsx("a",{...k,target:"_blank",rel:"noopener noreferrer"})},children:P.content??""})})]})})]})}function mO(){const{activeHost:e}=Hi(),t=j.useRef(null);j.useEffect(()=>{if(Vn.isNativePlatform()||e.directUrl||t.current===e.hostId)return;async function r(){var s;try{if(!("serviceWorker"in navigator)||!("PushManager"in window)){console.warn("[Push] Push notifications not supported");return}const l=await navigator.serviceWorker.ready;(s=l.active)==null||s.postMessage({type:"set-host-id",hostId:e.hostId});let u=await l.pushManager.getSubscription();if(!u){const{publicKey:f}=await hE("/api/push/vapid-key");if(!f){console.warn("[Push] No VAPID public key configured on server");return}if(await Notification.requestPermission()!=="granted"){console.log("[Push] Permission denied");return}u=await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}const c=u.toJSON();await fE("/api/push/subscribe",{hostId:e.hostId,endpoint:c.endpoint,keys:{p256dh:c.keys.p256dh,auth:c.keys.auth}}),t.current=e.hostId}catch(l){console.error("[Push] Subscription failed:",l)}}r()},[e])}const pO="0.9.2";function gO(e,t){if(e.includes("-"))return!1;const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let l=0;l<3;l++){if((r[l]??0)<(s[l]??0))return!0;if((r[l]??0)>(s[l]??0))return!1}return!1}function xu(){const{removePairedHost:e,setHostLanUrl:t}=Pi(),{connected:r,request:s,subscribeEvents:l,unauthorized:u,activeHost:c}=Hi(),f=c.hostId,d=c.clientToken||null,m=Or(),y=or(),g=Yu(),x=Ux("(min-width: 768px)"),w=y.pathname.endsWith("/tasks"),S=g.runId?void 0:g.taskId,T=!!(g.taskId&&g.runId),[L,M]=j.useState(!1),[P,F]=j.useState(!1),[ce,U]=j.useState(null),[D,te]=j.useState(null),[$,q]=j.useState(null),[R,V]=j.useState(new Set),[X,le]=j.useState([]),[ee,Y]=j.useState(),H=!!d&&$===d,[W,oe]=j.useState(new Map),[be,k]=j.useState(new Map),[z,K]=j.useState(new Map),[A,xe]=j.useState(new Map);mO(),j.useEffect(()=>{window.scrollTo(0,0)},[f]),j.useEffect(()=>{let Te=!1;return DE().then(Fe=>{Te||V(Fe)}),()=>{Te=!0}},[]),j.useEffect(()=>{r&&s("host.info").then(Te=>{var Ve,He,nt,ft,rt,qt;le(Te.agents??[]),Y(Te.host_platform),q(Te.linked_client_token??null),yE(Te.agents??[]);const Fe=Te.version??null;te(Fe),M(!!Fe&&gO(Fe,pO)),t(f,Te.lan_url??void 0);const Qe=new Map,qe=new Map,ct=new Map,vt=new Map;for(const Tt of Te.pending_prompts??[])if(Tt.type==="confirmation")Qe.set(Tt.key,{description:((Ve=Tt.meta)==null?void 0:Ve.description)??"",sessionName:(He=Tt.meta)==null?void 0:He.session_name});else if(Tt.type==="permission")qe.set(Tt.key,{permissions:Tt.params??[],sessionName:(nt=Tt.meta)==null?void 0:nt.session_name});else if(Tt.type==="input"){const ht=Tt.params??((ft=Tt.meta)==null?void 0:ft.input_questions)??[];ct.set(Tt.key,{questions:ht,description:(rt=Tt.meta)==null?void 0:rt.description,sessionName:(qt=Tt.meta)==null?void 0:qt.session_name}),vt.set(Tt.key,new Array(ht.length).fill(""))}oe(Qe),k(qe),K(ct),xe(vt)}).catch(()=>{})},[r,f,s,t]),j.useEffect(()=>r?l(f,Fe=>{const Qe=Fe.subject.split(".");if(Qe.length<3)return;const qe=Qe.slice(2).join(".");let ct={};try{ct=JSON.parse(new TextDecoder().decode(Fe.data))}catch{return}const vt=ct.event_type,Ve=ct.session_id;if(vt==="input-request"&&Ve){const He=ct.input_questions,nt=ct.session_name,ft=ct.description;He!=null&&He.length&&(K(rt=>{if(rt.has(Ve))return rt;const qt=new Map(rt);return qt.set(Ve,{questions:He,description:ft,sessionName:nt}),qt}),xe(rt=>{if(rt.has(Ve))return rt;const qt=new Map(rt);return qt.set(Ve,new Array(He.length).fill("")),qt}));return}if(vt==="input-resolved"&&Ve){K(He=>{if(!He.has(Ve))return He;const nt=new Map(He);return nt.delete(Ve),nt}),xe(He=>{const nt=new Map(He);return nt.delete(Ve),nt});return}if(vt==="confirm-request"&&Ve){const He=ct.description,nt=ct.session_name;He&&oe(ft=>{if(ft.has(Ve))return ft;const rt=new Map(ft);return rt.set(Ve,{description:He,sessionName:nt}),rt});return}if(vt==="confirm-resolved"&&Ve){oe(He=>{if(!He.has(Ve))return He;const nt=new Map(He);return nt.delete(Ve),nt});return}if(vt==="permission-request"){const He=ct.required_permissions,nt=ct.session_name;He!=null&&He.length&&k(ft=>{if(ft.has(qe))return ft;const rt=new Map(ft);return rt.set(qe,{permissions:He,sessionName:nt}),rt});return}if(vt==="permission-resolved"){k(He=>{if(!He.has(qe))return He;const nt=new Map(He);return nt.delete(qe),nt});return}}):void 0,[r,f,l]);async function _e(Te,Fe){try{await s("task.user_input",{id:Te,value:[Fe]})}catch(Qe){console.error("[Dashboard] Failed to respond to confirmation:",Qe)}}async function je(Te,Fe){try{await s("task.user_input",{id:Te,value:[Fe]})}catch(Qe){console.error("[Dashboard] Failed to respond to permission request:",Qe)}}async function Le(Te,Fe){try{await s("task.user_input",{id:Te,value:Fe})}catch(Qe){console.error("[Dashboard] Failed to respond to input request:",Qe)}}function $e(Te,Fe){if(!ps())return;const Qe=`/hosts/${encodeURIComponent(f)}/runs/${encodeURIComponent(Te)}`;m(Fe?`${Qe}/${encodeURIComponent(Fe)}`:Qe)}async function Ce(){F(!0),U(null);try{const Te=await s("host.update");if(Te.error){U(Te.error),F(!1);return}}catch{}setTimeout(()=>window.location.reload(),15e3)}const Ne=r&&!u;return b.jsxs("div",{className:"dashboard",children:[x&&b.jsx($0,{daemonVersion:D,linkedClientToken:$,request:s,onEnabledCapabilitiesChange:V,onLinkedClientTokenChange:q}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!x&&b.jsx($0,{daemonVersion:D,linkedClientToken:$,request:s,onEnabledCapabilitiesChange:V,onLinkedClientTokenChange:q}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(PE,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(OE,{})})]}),b.jsx("main",{className:"dashboard-main",children:u?b.jsxs("div",{className:"revoked-state",children:[b.jsx("div",{className:"revoked-icon",children:b.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),b.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}),b.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"18"})]})}),b.jsx("h2",{className:"revoked-title",children:"Client Revoked"}),b.jsx("p",{className:"revoked-description",children:"This client was revoked by the host. To reconnect, generate a new pairing code on the host machine."}),b.jsx("div",{className:"revoked-command",children:b.jsx("code",{children:"palmier pair"})}),b.jsxs("div",{className:"revoked-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>{ps()&&m("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(f),m("/",{replace:!0})},children:"Remove Host"})]})]}):Ne?b.jsxs(b.Fragment,{children:[w&&!T&&b.jsx(NE,{connected:r,hostId:f,request:s,subscribeEvents:l,agents:X,hostPlatform:ee,isNotificationListener:H&&R.has("notifications"),onViewRun:$e}),T?b.jsx(dO,{connected:r,hostId:f,request:s,subscribeEvents:l,taskId:g.taskId,runId:decodeURIComponent(g.runId)}):w?null:b.jsx(FE,{connected:r,hostId:f,request:s,subscribeEvents:l,agents:X,hostPlatform:ee,filterTaskId:S,onClearFilter:()=>{ps()&&m(`/hosts/${encodeURIComponent(f)}`)}})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{children:"Connecting to host..."})})}),L&&!P&&!ce&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Update Required"}),b.jsxs("p",{className:"confirm-modal-message",children:["Your Palmier host",D?` (v${D})`:""," is too old for this version of the app. Please update to continue."]}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-primary",onClick:Ce,children:"Update Now"})})]})}),P&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Updating..."}),b.jsx("p",{className:"confirm-modal-message",children:"Installing update and restarting daemon. Please wait..."})]})}),ce&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Update Failed"}),b.jsx("p",{className:"confirm-modal-message",style:{whiteSpace:"pre-line"},children:ce}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{U(null)},children:"Retry"})})]})})]}),ds.createPortal(b.jsxs(b.Fragment,{children:[[...W.entries()].map(([Te,{description:Fe,sessionName:Qe}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Confirmation Required"}),Qe&&b.jsx("p",{className:"confirm-modal-subtitle",children:Qe}),b.jsx("p",{className:"confirm-modal-message",children:Fe}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>_e(Te,"confirmed"),children:"Confirm"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>_e(Te,"aborted"),children:"Abort"})]})]})},Te)),[...be.entries()].map(([Te,{permissions:Fe,sessionName:Qe}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal permission-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Permission Required"}),b.jsx("p",{className:"confirm-modal-message",children:b.jsx("strong",{children:Qe||Te})}),b.jsx("div",{className:"permission-list",children:Fe.map((qe,ct)=>b.jsxs("div",{className:"permission-item",children:[b.jsx("span",{className:"permission-name",children:qe.name}),qe.description&&b.jsx("span",{className:"permission-desc",children:qe.description})]},ct))}),b.jsxs("div",{className:"permission-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>je(Te,"granted"),children:"Allow Once"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>je(Te,"granted_all"),children:"Allow Always"})]}),b.jsx("button",{className:"permission-abort-link",onClick:()=>je(Te,"aborted"),children:"Deny & Abort Task"})]})},Te)),[...z.entries()].map(([Te,{questions:Fe,description:Qe,sessionName:qe}])=>{const ct=A.get(Te)??new Array(Fe.length).fill("");return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal input-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Input Required"}),qe&&b.jsx("p",{className:"confirm-modal-subtitle",children:qe}),Qe&&b.jsx("p",{className:"confirm-modal-message",children:Qe}),b.jsx("div",{className:"input-list",children:Fe.map((vt,Ve)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:vt}),b.jsx("input",{type:"text",className:"input-field",value:ct[Ve]??"",onChange:He=>{xe(nt=>{const ft=new Map(nt),rt=[...ft.get(Te)??[]];return rt[Ve]=He.target.value,ft.set(Te,rt),ft})},autoFocus:Ve===0})]},Ve))}),b.jsx("div",{className:"input-actions",children:b.jsx("button",{className:"btn btn-primary",disabled:ct.some(vt=>!vt.trim()),onClick:()=>Le(Te,ct),children:"Submit"})}),b.jsx("button",{className:"permission-abort-link",onClick:()=>Le(Te,["aborted"]),children:"Cancel"})]})},Te)})]}),document.body)]})}const yO=ys("Preferences",{web:()=>Id(()=>import("./web-DdzXb-jW.js"),[]).then(e=>new e.PreferencesWeb)}),kl=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),qb=Vn.isNativePlatform();function bO(){const[e,t]=j.useState(""),[r,s]=j.useState(!0),[l,u]=j.useState(!1),[c,f]=j.useState(null),{addPairedHost:d}=Pi(),m=Or();async function y(){const g=e.trim().toUpperCase();if(!g){f("Enter a pairing code.");return}u(!0),f(null);try{let x;if(kl){const T=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g,label:navigator.userAgent})});if(!T.ok){const L=await T.json().catch(()=>({error:"Connection failed"}));throw new Error(L.error||`HTTP ${T.status}`)}x=await T.json()}else{const T=await fetch(`${Uu}/api/config`);if(!T.ok)throw new Error("Failed to fetch server config");const L=await T.json();if(!L.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const M=await Nx({servers:L.natsWsUrl,authenticator:wx(L.natsJwt,new TextEncoder().encode(L.natsNkeySeed))}),P=Nu(),F=`pair.${g}`,ce=await M.request(F,P.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});x=JSON.parse(P.decode(ce.data)),await M.close()}const w={hostId:x.hostId,clientToken:x.clientToken,directUrl:kl?window.location.origin:void 0,...x.hostName?{name:x.hostName}:{}};if(d(w),Vn.isNativePlatform()&&mn){await yO.set({key:"hostId",value:x.hostId});try{const{token:T}=await mn.getFcmToken();await fetch(`${Uu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:x.hostId,fcmToken:T})})}catch(T){console.warn("FCM token registration failed:",T)}}const S=`/hosts/${encodeURIComponent(x.hostId)}`;m(qb&&r?`${S}/pair/setup`:S)}catch(x){const w=x instanceof Error?x.message:String(x);w.includes("timeout")||w.includes("TIMEOUT")||w.includes("503")||w.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(w)}finally{u(!1)}}return b.jsx("div",{className:"pair-page",children:b.jsxs("div",{className:"pair-card",children:[b.jsxs("div",{className:"pair-header",children:[b.jsx("h1",{className:"pair-title",children:kl?"Pair":"Pair with Host"}),b.jsx("p",{className:"pair-subtitle",children:kl?"Enter the pairing code shown in your terminal.":"Connect this device to a Palmier host"})]}),!kl&&b.jsxs("div",{className:"pair-instructions",children:[b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Setting up a new host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Install at least one agent CLI (e.g., ",b.jsx("a",{href:"https://www.palmier.me/agents",target:"_blank",rel:"noopener noreferrer",children:"Claude Code, Gemini CLI, Codex CLI"}),")"]}),b.jsxs("li",{children:["Install Palmier on your host machine.",b.jsx("span",{className:"pair-platform-label",children:"Linux / macOS:"}),b.jsx("code",{className:"pair-command",children:"curl -fsSL https://palmier.me/install.sh | bash"}),b.jsx("span",{className:"pair-platform-label",children:"Windows (PowerShell):"}),b.jsx("code",{className:"pair-command",children:"irm https://palmier.me/install.ps1 | iex"})]}),b.jsxs("li",{children:["Run the setup wizard:",b.jsx("code",{className:"pair-command",children:"palmier init"})]}),b.jsx("li",{children:"A pairing code will display automatically"})]})]}),b.jsx("div",{className:"pair-instruction-divider"}),b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Pairing an existing host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Run ",b.jsx("code",{children:"palmier pair"})," on the host machine"]}),b.jsx("li",{children:"Enter the 6-character code below"})]})]})]}),b.jsxs("div",{className:"pair-form",children:[b.jsxs("label",{className:"form-label",htmlFor:"pair-code",children:["Pairing code",b.jsx("input",{id:"pair-code",type:"text",maxLength:6,value:e,onChange:g=>t(g.target.value.toUpperCase()),placeholder:"A7K9M2",className:"form-input form-input-mono pair-code-input",autoFocus:!0,autoComplete:"off",disabled:l})]}),qb&&b.jsxs("label",{className:"pair-checkbox",children:[b.jsx("input",{type:"checkbox",checked:r,onChange:g=>s(g.target.checked),disabled:l}),b.jsxs("span",{className:"pair-checkbox-text",children:[b.jsx("span",{className:"pair-checkbox-title",children:"Link the host to this device"}),b.jsx("span",{className:"pair-checkbox-hint",children:r?"The host will use this device for SMS, contacts, calendar, location, and alarms. Only one device can be linked to the host.":"This device won't provide SMS, contacts, calendar, location, or alarms to the host. You can link it later from the menu."})]})]}),c&&b.jsx("p",{className:"pair-error",children:c}),b.jsxs("button",{className:"btn btn-primary btn-full",onClick:y,disabled:l||!e.trim(),children:[l&&b.jsx("span",{className:"btn-spinner"}),l?"Pairing...":"Pair"]}),b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>m("/"),disabled:l,children:"Cancel"}),b.jsxs("p",{className:"pair-consent",children:["By pairing, you agree to our"," ",b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," and"," ",b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]})]})]})})}function xO(){const e=Or(),{connected:t,request:r,activeHost:s}=Hi(),{setHostLanUrl:l,pairedHosts:u}=Pi(),c=u.length<=1,[f,d]=j.useState("loading"),[m,y]=j.useState(null),[g,x]=j.useState(null);function w(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}j.useEffect(()=>{if(!t||f!=="loading")return;let P=!1;return r("host.info").catch(()=>({})).then(F=>{if(P)return;l(s.hostId,F.lan_url??void 0);const ce=F.linked_client_token??null;y(ce);const U=!!ce&&ce!==s.clientToken;d(U?"confirming":"linking")}),()=>{P=!0}},[t,f,s,r,l]),j.useEffect(()=>{if(f!=="linking")return;let P=!1;return(async()=>{try{if(mn){const{token:F}=await mn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(P)return;c?d("wizard"):w()}catch(F){if(P)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{P=!0}},[f]);function S(){d("linking")}function T(){w()}function L(){x(null),d("linking")}const M=f==="confirming"&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:T,children:b.jsxs("div",{className:"confirm-modal",onClick:P=>P.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:T,children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:S,children:"Link"})]})]})}),document.body);if(f==="loading"||f==="confirming"||f==="linking"||f==="linkError"){const P=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[P&&b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsxs("div",{className:"pair-setup-loading",children:[F&&b.jsx("span",{className:"spinner spinner-lg"}),f==="loading"&&b.jsx("span",{children:"Connecting to host…"}),f==="confirming"&&b.jsx("span",{children:"Awaiting confirmation…"}),f==="linking"&&b.jsx("span",{children:"Linking device…"}),f==="linkError"&&b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"pair-error",children:g}),b.jsx("button",{className:"btn btn-primary",onClick:L,children:"Retry"}),b.jsx("button",{className:"btn btn-secondary",onClick:w,children:"Skip linking"})]})]})]}),M]})}return b.jsx("div",{className:"pair-setup",children:b.jsxs("div",{className:"pair-setup-inner",children:[b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsx("p",{className:"pair-setup-description",children:"Choose what the host can use this device for. You can change these later from the menu."}),b.jsx(Bx,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:w,children:"Finish"})})]})})}function vO(){const e=Or();return j.useEffect(()=>{if(!mn)return;const t=mn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function wO(){const{pairedHosts:e}=Pi();return e.length===0?b.jsx(Ll,{to:"/pair",replace:!0}):b.jsx(Ll,{to:`/hosts/${encodeURIComponent(e[0].hostId)}`,replace:!0})}function SO(){const{hostId:e}=Yu(),{pairedHosts:t}=Pi(),r=t.find(s=>s.hostId===e)??null;return r?b.jsx(gE,{activeHost:r,children:b.jsxs(nx,{children:[b.jsx(gr,{index:!0,element:b.jsx(xu,{})}),b.jsx(gr,{path:"tasks",element:b.jsx(xu,{})}),b.jsx(gr,{path:"runs/:taskId",element:b.jsx(xu,{})}),b.jsx(gr,{path:"runs/:taskId/:runId",element:b.jsx(xu,{})}),b.jsx(gr,{path:"pair/setup",element:b.jsx(xO,{})}),b.jsx(gr,{path:"*",element:b.jsx(Ll,{to:".",replace:!0})})]})}):b.jsx(Ll,{to:"/",replace:!0})}function _O(){return b.jsxs(q_,{children:[b.jsx(vO,{}),b.jsxs(nx,{children:[b.jsx(gr,{path:"/",element:b.jsx(wO,{})}),b.jsx(gr,{path:"/pair",element:b.jsx(bO,{})}),b.jsx(gr,{path:"/hosts/:hostId/*",element:b.jsx(SO,{})}),b.jsx(gr,{path:"*",element:b.jsx(Ll,{to:"/",replace:!0})})]})]})}lS.createRoot(document.getElementById("root")).render(b.jsx(j.StrictMode,{children:b.jsx(A_,{children:b.jsx(_O,{})})}));export{Hd as W};
|
|
120
|
+
`))}function d(w,S,T,L){const M=T.enter("tableCell"),P=T.enter("phrasing"),F=T.containerPhrasing(w,{...L,before:u,after:u});return P(),M(),F}function m(w,S){return PN(w,{align:S,alignDelimiters:s,padding:r,stringLength:l})}function y(w,S,T){const L=w.children;let M=-1;const P=[],F=S.enter("table");for(;++M<L.length;)P[M]=g(L[M],S,T);return F(),P}function g(w,S,T){const L=w.children;let M=-1;const P=[],F=S.enter("tableRow");for(;++M<L.length;)P[M]=d(L[M],w,S,T);return F(),P}function x(w,S,T){let L=L1.inlineCode(w,S,T);return T.stack.includes("tableCell")&&(L=L.replace(/\|/g,"\\$&")),L}}function C3(){return{exit:{taskListCheckValueChecked:zb,taskListCheckValueUnchecked:zb,paragraph:j3}}}function A3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:T3}}}function zb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function j3(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const r=this.stack[this.stack.length-1];r.type;const s=r.children[0];if(s&&s.type==="text"){const l=t.children;let u=-1,c;for(;++u<l.length;){const f=l[u];if(f.type==="paragraph"){c=f;break}}c===r&&(s.value=s.value.slice(1),s.value.length===0?r.children.shift():r.position&&s.position&&typeof s.position.start.offset=="number"&&(s.position.start.column++,s.position.start.offset++,r.position.start=Object.assign({},s.position.start)))}}this.exit(e)}function T3(e,t,r,s){const l=e.children[0],u=typeof e.checked=="boolean"&&l&&l.type==="paragraph",c="["+(e.checked?"x":" ")+"] ",f=r.createTracker(s);u&&f.move(c);let d=L1.listItem(e,t,r,{...s,...f.current()});return u&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,m)),d;function m(y){return y+c}}function N3(){return[oN(),TN(),MN(),x3(),C3()]}function O3(e){return{extensions:[uN(),NN(e),DN(),E3(e),A3()]}}const R3={tokenize:B3,partial:!0},z1={tokenize:P3,partial:!0},U1={tokenize:q3,partial:!0},B1={tokenize:H3,partial:!0},M3={tokenize:I3,partial:!0},P1={name:"wwwAutolink",tokenize:z3,previous:H1},q1={name:"protocolAutolink",tokenize:U3,previous:I1},ri={name:"emailAutolink",tokenize:L3,previous:F1},Rr={};function D3(){return{text:Rr}}let hs=48;for(;hs<123;)Rr[hs]=ri,hs++,hs===58?hs=65:hs===91&&(hs=97);Rr[43]=ri;Rr[45]=ri;Rr[46]=ri;Rr[95]=ri;Rr[72]=[ri,q1];Rr[104]=[ri,q1];Rr[87]=[ri,P1];Rr[119]=[ri,P1];function L3(e,t,r){const s=this;let l,u;return c;function c(g){return!Ed(g)||!F1.call(s,s.previous)||lm(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return Ed(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(M3,y,m)(g):g===45||g===95||pn(g)?(u=!0,e.consume(g),d):y(g)}function m(g){return e.consume(g),l=!0,d}function y(g){return u&&l&&wn(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function z3(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!H1.call(s,s.previous)||lm(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(R3,e.attempt(z1,e.attempt(U1,u),r),r)(c))}function u(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function U3(e,t,r){const s=this;let l="",u=!1;return c;function c(g){return(g===72||g===104)&&I1.call(s,s.previous)&&!lm(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(wn(g)&&l.length<5)return l+=String.fromCodePoint(g),e.consume(g),f;if(g===58){const x=l.toLowerCase();if(x==="http"||x==="https")return e.consume(g),d}return r(g)}function d(g){return g===47?(e.consume(g),u?m:(u=!0,d)):r(g)}function m(g){return g===null||Pu(g)||jt(g)||gs(g)||Zu(g)?r(g):e.attempt(z1,e.attempt(U1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function B3(e,t,r){let s=0;return l;function l(c){return(c===87||c===119)&&s<3?(s++,e.consume(c),l):c===46&&s===3?(e.consume(c),u):r(c)}function u(c){return c===null?r(c):t(c)}}function P3(e,t,r){let s,l,u;return c;function c(m){return m===46||m===95?e.check(B1,d,f)(m):m===null||jt(m)||gs(m)||m!==45&&Zu(m)?d(m):(u=!0,e.consume(m),c)}function f(m){return m===95?s=!0:(l=s,s=void 0),e.consume(m),c}function d(m){return l||s||!u?r(m):t(m)}}function q3(e,t){let r=0,s=0;return l;function l(c){return c===40?(r++,e.consume(c),l):c===41&&s<r?u(c):c===33||c===34||c===38||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===60||c===63||c===93||c===95||c===126?e.check(B1,t,u)(c):c===null||jt(c)||gs(c)?t(c):(e.consume(c),l)}function u(c){return c===41&&s++,e.consume(c),l}}function H3(e,t,r){return s;function s(f){return f===33||f===34||f===39||f===41||f===42||f===44||f===46||f===58||f===59||f===63||f===95||f===126?(e.consume(f),s):f===38?(e.consume(f),u):f===93?(e.consume(f),l):f===60||f===null||jt(f)||gs(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||jt(f)||gs(f)?t(f):s(f)}function u(f){return wn(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):wn(f)?(e.consume(f),c):r(f)}}function I3(e,t,r){return s;function s(u){return e.consume(u),l}function l(u){return pn(u)?r(u):t(u)}}function H1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||jt(e)}function I1(e){return!wn(e)}function F1(e){return!(e===47||Ed(e))}function Ed(e){return e===43||e===45||e===46||e===95||pn(e)}function lm(e){let t=e.length,r=!1;for(;t--;){const s=e[t][1];if((s.type==="labelLink"||s.type==="labelImage")&&!s._balanced){r=!0;break}if(s._gfmAutolinkLiteralWalkedInto){r=!1;break}}return e.length>0&&!r&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),r}const F3={tokenize:Q3,partial:!0};function $3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:J3,continuation:{tokenize:X3},exit:K3}},text:{91:{name:"gfmFootnoteCall",tokenize:V3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Y3,resolveTo:G3}}}}function Y3(e,t,r){const s=this;let l=s.events.length;const u=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let c;for(;l--;){const d=s.events[l][1];if(d.type==="labelImage"){c=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return f;function f(d){if(!c||!c._balanced)return r(d);const m=xr(s.sliceSerialize({start:c.end,end:s.now()}));return m.codePointAt(0)!==94||!u.includes(m.slice(1))?r(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),t(d))}}function G3(e,t){let r=e.length;for(;r--;)if(e[r][1].type==="labelImage"&&e[r][0]==="enter"){e[r][1];break}e[r+1][1].type="data",e[r+3][1].type="gfmFootnoteCallLabelMarker";const s={type:"gfmFootnoteCall",start:Object.assign({},e[r+3][1].start),end:Object.assign({},e[e.length-1][1].end)},l={type:"gfmFootnoteCallMarker",start:Object.assign({},e[r+3][1].end),end:Object.assign({},e[r+3][1].end)};l.end.column++,l.end.offset++,l.end._bufferIndex++;const u={type:"gfmFootnoteCallString",start:Object.assign({},l.end),end:Object.assign({},e[e.length-1][1].start)},c={type:"chunkString",contentType:"string",start:Object.assign({},u.start),end:Object.assign({},u.end)},f=[e[r+1],e[r+2],["enter",s,t],e[r+3],e[r+4],["enter",l,t],["exit",l,t],["enter",u,t],["enter",c,t],["exit",c,t],["exit",u,t],e[e.length-2],e[e.length-1],["exit",s,t]];return e.splice(r,e.length-r+1,...f),e}function V3(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u=0,c;return f;function f(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),d}function d(g){return g!==94?r(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",m)}function m(g){if(u>999||g===93&&!c||g===null||g===91||jt(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(xr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return jt(g)||(c=!0),u++,e.consume(g),g===92?y:m}function y(g){return g===91||g===92||g===93?(e.consume(g),u++,m):m(g)}}function J3(e,t,r){const s=this,l=s.parser.gfmFootnotes||(s.parser.gfmFootnotes=[]);let u,c=0,f;return d;function d(S){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),m}function m(S){return S===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",y):r(S)}function y(S){if(c>999||S===93&&!f||S===null||S===91||jt(S))return r(S);if(S===93){e.exit("chunkString");const T=e.exit("gfmFootnoteDefinitionLabelString");return u=xr(s.sliceSerialize(T)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return jt(S)||(f=!0),c++,e.consume(S),S===92?g:y}function g(S){return S===91||S===92||S===93?(e.consume(S),c++,y):y(S)}function x(S){return S===58?(e.enter("definitionMarker"),e.consume(S),e.exit("definitionMarker"),l.includes(u)||l.push(u),ot(e,w,"gfmFootnoteDefinitionWhitespace")):r(S)}function w(S){return t(S)}}function X3(e,t,r){return e.check(Vl,t,e.attempt(F3,t,r))}function K3(e){e.exit("gfmFootnoteDefinition")}function Q3(e,t,r){const s=this;return ot(e,l,"gfmFootnoteDefinitionIndent",5);function l(u){const c=s.events[s.events.length-1];return c&&c[1].type==="gfmFootnoteDefinitionIndent"&&c[2].sliceSerialize(c[1],!0).length===4?t(u):r(u)}}function Z3(e){let r=(e||{}).singleTilde;const s={name:"strikethrough",tokenize:u,resolveAll:l};return r==null&&(r=!0),{text:{126:s},insideSpan:{null:[s]},attentionMarkers:{null:[126]}};function l(c,f){let d=-1;for(;++d<c.length;)if(c[d][0]==="enter"&&c[d][1].type==="strikethroughSequenceTemporary"&&c[d][1]._close){let m=d;for(;m--;)if(c[m][0]==="exit"&&c[m][1].type==="strikethroughSequenceTemporary"&&c[m][1]._open&&c[d][1].end.offset-c[d][1].start.offset===c[m][1].end.offset-c[m][1].start.offset){c[d][1].type="strikethroughSequence",c[m][1].type="strikethroughSequence";const y={type:"strikethrough",start:Object.assign({},c[m][1].start),end:Object.assign({},c[d][1].end)},g={type:"strikethroughText",start:Object.assign({},c[m][1].end),end:Object.assign({},c[d][1].start)},x=[["enter",y,f],["enter",c[m][1],f],["exit",c[m][1],f],["enter",g,f]],w=f.parser.constructs.insideSpan.null;w&&Yn(x,x.length,0,Wu(w,c.slice(m+1,d),f)),Yn(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),Yn(c,m-1,d-m+3,x),d=m+x.length-2;break}}for(d=-1;++d<c.length;)c[d][1].type==="strikethroughSequenceTemporary"&&(c[d][1].type="data");return c}function u(c,f,d){const m=this.previous,y=this.events;let g=0;return x;function x(S){return m===126&&y[y.length-1][1].type!=="characterEscape"?d(S):(c.enter("strikethroughSequenceTemporary"),w(S))}function w(S){const T=ba(m);if(S===126)return g>1?d(S):(c.consume(S),g++,w);if(g<2&&!r)return d(S);const L=c.exit("strikethroughSequenceTemporary"),M=ba(S);return L._open=!M||M===2&&!!T,L._close=!T||T===2&&!!M,f(S)}}}class W3{constructor(){this.map=[]}add(t,r,s){eO(this,t,r,s)}consume(t){if(this.map.sort(function(u,c){return u[0]-c[0]}),this.map.length===0)return;let r=this.map.length;const s=[];for(;r>0;)r-=1,s.push(t.slice(this.map[r][0]+this.map[r][1]),this.map[r][2]),t.length=this.map[r][0];s.push(t.slice()),t.length=0;let l=s.pop();for(;l;){for(const u of l)t.push(u);l=s.pop()}this.map.length=0}}function eO(e,t,r,s){let l=0;if(!(r===0&&s.length===0)){for(;l<e.map.length;){if(e.map[l][0]===t){e.map[l][1]+=r,e.map[l][2].push(...s);return}l+=1}e.map.push([t,r,s])}}function tO(e,t){let r=!1;const s=[];for(;t<e.length;){const l=e[t];if(r){if(l[0]==="enter")l[1].type==="tableContent"&&s.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(l[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const u=s.length-1;s[u]=s[u]==="left"?"center":"right"}}else if(l[1].type==="tableDelimiterRow")break}else l[0]==="enter"&&l[1].type==="tableDelimiterRow"&&(r=!0);t+=1}return s}function nO(){return{flow:{null:{name:"table",tokenize:rO,resolveAll:iO}}}}function rO(e,t,r){const s=this;let l=0,u=0,c;return f;function f(R){let V=s.events.length-1;for(;V>-1;){const ee=s.events[V][1].type;if(ee==="lineEnding"||ee==="linePrefix")V--;else break}const X=V>-1?s.events[V][1].type:null,le=X==="tableHead"||X==="tableRow"?D:d;return le===D&&s.parser.lazy[s.now().line]?r(R):le(R)}function d(R){return e.enter("tableHead"),e.enter("tableRow"),m(R)}function m(R){return R===124||(c=!0,u+=1),y(R)}function y(R){return R===null?r(R):Be(R)?u>1?(u=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(R),e.exit("lineEnding"),w):r(R):tt(R)?ot(e,y,"whitespace")(R):(u+=1,c&&(c=!1,l+=1),R===124?(e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(R)))}function g(R){return R===null||R===124||jt(R)?(e.exit("data"),y(R)):(e.consume(R),R===92?x:g)}function x(R){return R===92||R===124?(e.consume(R),g):g(R)}function w(R){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(R):(e.enter("tableDelimiterRow"),c=!1,tt(R)?ot(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):S(R))}function S(R){return R===45||R===58?L(R):R===124?(c=!0,e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),T):U(R)}function T(R){return tt(R)?ot(e,L,"whitespace")(R):L(R)}function L(R){return R===58?(u+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(R),e.exit("tableDelimiterMarker"),M):R===45?(u+=1,M(R)):R===null||Be(R)?ce(R):U(R)}function M(R){return R===45?(e.enter("tableDelimiterFiller"),P(R)):U(R)}function P(R){return R===45?(e.consume(R),P):R===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(R),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(R))}function F(R){return tt(R)?ot(e,ce,"whitespace")(R):ce(R)}function ce(R){return R===124?S(R):R===null||Be(R)?!c||l!==u?U(R):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(R)):U(R)}function U(R){return r(R)}function D(R){return e.enter("tableRow"),te(R)}function te(R){return R===124?(e.enter("tableCellDivider"),e.consume(R),e.exit("tableCellDivider"),te):R===null||Be(R)?(e.exit("tableRow"),t(R)):tt(R)?ot(e,te,"whitespace")(R):(e.enter("data"),$(R))}function $(R){return R===null||R===124||jt(R)?(e.exit("data"),te(R)):(e.consume(R),R===92?q:$)}function q(R){return R===92||R===124?(e.consume(R),$):$(R)}}function iO(e,t){let r=-1,s=!0,l=0,u=[0,0,0,0],c=[0,0,0,0],f=!1,d=0,m,y,g;const x=new W3;for(;++r<e.length;){const w=e[r],S=w[1];w[0]==="enter"?S.type==="tableHead"?(f=!1,d!==0&&(Ub(x,t,d,m,y),y=void 0,d=0),m={type:"table",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",m,t]])):S.type==="tableRow"||S.type==="tableDelimiterRow"?(s=!0,g=void 0,u=[0,0,0,0],c=[0,r+1,0,0],f&&(f=!1,y={type:"tableBody",start:Object.assign({},S.start),end:Object.assign({},S.end)},x.add(r,0,[["enter",y,t]])),l=S.type==="tableDelimiterRow"?2:y?3:1):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")?(s=!1,c[2]===0&&(u[1]!==0&&(c[0]=c[1],g=bu(x,t,u,l,void 0,g),u=[0,0,0,0]),c[2]=r)):S.type==="tableCellDivider"&&(s?s=!1:(u[1]!==0&&(c[0]=c[1],g=bu(x,t,u,l,void 0,g)),u=c,c=[u[1],r,0,0])):S.type==="tableHead"?(f=!0,d=r):S.type==="tableRow"||S.type==="tableDelimiterRow"?(d=r,u[1]!==0?(c[0]=c[1],g=bu(x,t,u,l,r,g)):c[1]!==0&&(g=bu(x,t,c,l,r,g)),l=0):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Ub(x,t,d,m,y),x.consume(t.events),r=-1;++r<t.events.length;){const w=t.events[r];w[0]==="enter"&&w[1].type==="table"&&(w[1]._align=tO(t.events,r))}return e}function bu(e,t,r,s,l,u){const c=s===1?"tableHeader":s===2?"tableDelimiter":"tableData",f="tableContent";r[0]!==0&&(u.end=Object.assign({},ia(t.events,r[0])),e.add(r[0],0,[["exit",u,t]]));const d=ia(t.events,r[1]);if(u={type:c,start:Object.assign({},d),end:Object.assign({},d)},e.add(r[1],0,[["enter",u,t]]),r[2]!==0){const m=ia(t.events,r[2]),y=ia(t.events,r[3]),g={type:f,start:Object.assign({},m),end:Object.assign({},y)};if(e.add(r[2],0,[["enter",g,t]]),s!==2){const x=t.events[r[2]],w=t.events[r[3]];if(x[1].end=Object.assign({},w[1].end),x[1].type="chunkText",x[1].contentType="text",r[3]>r[2]+1){const S=r[2]+1,T=r[3]-r[2]-1;e.add(S,T,[])}}e.add(r[3]+1,0,[["exit",g,t]])}return l!==void 0&&(u.end=Object.assign({},ia(t.events,l)),e.add(l,0,[["exit",u,t]]),u=void 0),u}function Ub(e,t,r,s,l){const u=[],c=ia(t.events,r);l&&(l.end=Object.assign({},c),u.push(["exit",l,t])),s.end=Object.assign({},c),u.push(["exit",s,t]),e.add(r+1,0,u)}function ia(e,t){const r=e[t],s=r[0]==="enter"?"start":"end";return r[1][s]}const sO={name:"tasklistCheck",tokenize:lO};function aO(){return{text:{91:sO}}}function lO(e,t,r){const s=this;return l;function l(d){return s.previous!==null||!s._gfmTasklistFirstContentOfListItem?r(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),u)}function u(d){return jt(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),c):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),c):r(d)}function c(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),f):r(d)}function f(d){return Be(d)?t(d):tt(d)?e.check({tokenize:oO},t,r)(d):r(d)}}function oO(e,t,r){return ot(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function uO(e){return Wx([D3(),$3(),Z3(e),nO(),aO()])}const cO={};function Bb(e){const t=this,r=e||cO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),u=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(uO(r)),u.push(N3()),c.push(O3(r))}function fO(e){v1(e,[/\r?\n|\r/g,hO])}function hO(){return{type:"break"}}function Pb(){return function(e){fO(e)}}function dO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:u}){const c=Or(),[f,d]=j.useState(!0),[m,y]=j.useState([]),[g,x]=j.useState(),[w,S]=j.useState(),T=g==="started"||g==="monitoring",L=g==="followup",M=g==="started"||g==="followup",[P,F]=j.useState(null);md(P!==null,()=>F(null));const[ce,U]=j.useState(!1),[D,te]=j.useState(""),[$,q]=j.useState(!1),R=j.useRef(null),V=j.useRef(null),X=j.useRef(null),[le,ee]=j.useState(u==="latest"?void 0:u),Y=u==="latest"&&le===null;j.useEffect(()=>{if(u!=="latest"){ee(u);return}e&&(ee(void 0),r("taskrun.list",{task_id:l,limit:1}).then(k=>{var z,K;return ee(((K=(z=k.entries)==null?void 0:z[0])==null?void 0:K.run_id)??null)}).catch(()=>ee(null)))},[u,l,e,r]);async function H(){if(le)try{const k=await r("task.result",{id:l,run_id:le});if(k.error){console.error("No result:",k.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}y(k.messages??[]),x(k.running_state),S(k.agent)}catch(k){console.error("Failed to load result:",k),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{d(!1)}}async function W(k){var z;if(le)try{const A=(z=(await r("task.reports",{id:l,run_id:le,report_files:[k]})).reports)==null?void 0:z[0];A!=null&&A.data_url?F({file:k,data_url:A.data_url}):F({file:k,content:(A==null?void 0:A.content)??"Report not found."})}catch{F({file:k,content:"Failed to load report."})}}j.useEffect(()=>{!e||!le||(d(!0),H())},[e,l,le]),j.useEffect(()=>!e||!t||!le?void 0:s(t,async z=>{try{const K=JSON.parse(new TextDecoder().decode(z.data));if(K.event_type!=="running-state"&&K.event_type!=="result-updated"||z.subject.split(".").pop()!==l||K.event_type==="result-updated"&&K.run_id&&K.run_id!==le)return;H()}catch{}}),[e,t,l,le,s,r]),j.useEffect(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight)},[m]),j.useEffect(()=>{f||Y||!le||X.current!==le&&(X.current=le,requestAnimationFrame(()=>{R.current&&(R.current.scrollTop=R.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[f,Y,le]);function oe(k){if(k==="input")return"User Input";if(k==="permission")return"Permission";if(k==="confirmation")return"Confirmation"}function be(k){return k==="started"?"Task started":k==="finished"?"Task finished":k==="failed"?"Task failed":k==="error"?"Command failed":k==="aborted"?"Task aborted":k==="confirmation"?"Task confirmed":k==="stopped"?"Follow-up stopped":k??""}return b.jsxs("div",{className:"run-detail",children:[b.jsxs("button",{className:"run-detail-back",onClick:()=>c(-1),children:[b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:b.jsx("path",{d:"M15 18l-6-6 6-6"})}),"Back"]}),Y?b.jsxs("div",{className:"empty-state",children:[b.jsx("p",{className:"empty-state-text",children:"No runs yet"}),b.jsx("p",{className:"empty-state-hint",children:"This task hasn't been executed yet. Run it from the task menu or wait for its next trigger."})]}):f?b.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)",padding:"var(--space-sm) 0"},children:[b.jsx("div",{className:"skeleton-line",style:{width:"40%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"55%"}}),b.jsx("div",{className:"skeleton-line",style:{width:"100%",height:"8rem",marginTop:"var(--space-sm)"}})]}):b.jsxs(b.Fragment,{children:[b.jsxs("div",{className:"chat-thread",ref:R,children:[m.map((k,z)=>{const K=M&&k.role==="assistant"&&!m.slice(z+1).some(A=>A.role==="assistant"||A.role==="user");return k.role==="status"&&k.type==="monitoring"?null:k.role==="status"?b.jsxs("div",{className:`chat-status${k.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[be(k.type),k.time>0&&b.jsx("span",{className:"chat-status-time",children:Bu(k.time)})]}),k.content&&b.jsx("pre",{className:"chat-status-detail",children:k.content})]},z):b.jsxs("div",{className:`chat-message chat-message--${k.role}`,children:[k.role==="assistant"&&w&&b.jsx("div",{className:"chat-message-agent",children:dd(w)}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(Nb,{remarkPlugins:[Bb,Pb],children:k.content}),K&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),k.attachments&&k.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:k.attachments.map(A=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>W(A),children:A},A))}),b.jsxs("div",{className:"chat-message-meta",children:[oe(k.type)&&b.jsx("span",{className:"chat-message-type",children:oe(k.type)}),k.time>0&&b.jsx("span",{children:Bu(k.time)})]})]},z)}),M&&(()=>{const k=m.filter(z=>z.role!=="status");return k.length===0||k[k.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[w&&b.jsx("div",{className:"chat-message-agent",children:dd(w)}),b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),g==="monitoring"&&b.jsxs("div",{className:"chat-monitoring-indicator",children:[b.jsx("span",{className:"chat-monitoring-dot"}),"Monitoring command output"]})]}),T?b.jsx("div",{className:"chat-abort-bar",children:b.jsx("button",{className:"btn btn-secondary chat-abort-btn",disabled:ce,onClick:async()=>{if(confirm("Abort this task?")){U(!0);try{await r("task.abort",{id:l})}catch(k){console.error("Abort failed:",k)}finally{U(!1)}}},children:ce?"Aborting...":"Abort Task"})}):L?b.jsx("div",{className:"chat-input-bar",children:b.jsx("button",{className:"btn btn-secondary chat-stop-btn",disabled:ce,onClick:async()=>{U(!0);try{await r("task.stop_followup",{id:l,run_id:le})}catch(k){console.error("Stop failed:",k)}finally{U(!1)}},children:b.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:b.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})})}):b.jsxs("form",{className:"chat-input-bar",onSubmit:async k=>{k.preventDefault();const z=D.trim();if(!(!z||$)){q(!0);try{await r("task.followup",{id:l,run_id:le,message:z}),te("")}catch(K){console.error("Follow-up failed:",K)}finally{q(!1)}}},children:[b.jsx("input",{ref:V,className:"chat-input",type:"text",placeholder:"Follow up",value:D,onChange:k=>te(k.target.value),disabled:$}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!D.trim()||$,children:b.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),b.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})})]})]}),P&&b.jsx("div",{className:"report-dialog-overlay",onClick:()=>F(null),children:b.jsxs("div",{className:"report-dialog",onClick:k=>k.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:P.file}),b.jsx("button",{className:"report-dialog-close",onClick:()=>F(null),"aria-label":"Close",children:b.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),b.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),b.jsx("div",{className:"report-dialog-body",children:P.data_url?b.jsx("img",{src:P.data_url,alt:P.file,style:{maxWidth:"100%",height:"auto"}}):b.jsx(Nb,{remarkPlugins:[Bb,Pb],components:{a:({...k})=>b.jsx("a",{...k,target:"_blank",rel:"noopener noreferrer"})},children:P.content??""})})]})})]})}function mO(){const{activeHost:e}=Hi(),t=j.useRef(null);j.useEffect(()=>{if(Vn.isNativePlatform()||e.directUrl||t.current===e.hostId)return;async function r(){var s;try{if(!("serviceWorker"in navigator)||!("PushManager"in window)){console.warn("[Push] Push notifications not supported");return}const l=await navigator.serviceWorker.ready;(s=l.active)==null||s.postMessage({type:"set-host-id",hostId:e.hostId});let u=await l.pushManager.getSubscription();if(!u){const{publicKey:f}=await hE("/api/push/vapid-key");if(!f){console.warn("[Push] No VAPID public key configured on server");return}if(await Notification.requestPermission()!=="granted"){console.log("[Push] Permission denied");return}u=await l.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:f})}const c=u.toJSON();await fE("/api/push/subscribe",{hostId:e.hostId,endpoint:c.endpoint,keys:{p256dh:c.keys.p256dh,auth:c.keys.auth}}),t.current=e.hostId}catch(l){console.error("[Push] Subscription failed:",l)}}r()},[e])}const pO="0.9.2";function gO(e,t){if(e.includes("-"))return!1;const r=e.split(".").map(Number),s=t.split(".").map(Number);for(let l=0;l<3;l++){if((r[l]??0)<(s[l]??0))return!0;if((r[l]??0)>(s[l]??0))return!1}return!1}function xu(){const{removePairedHost:e,setHostLanUrl:t}=Pi(),{connected:r,request:s,subscribeEvents:l,unauthorized:u,activeHost:c}=Hi(),f=c.hostId,d=c.clientToken||null,m=Or(),y=or(),g=Yu(),x=Ux("(min-width: 768px)"),w=y.pathname.endsWith("/tasks"),S=g.runId?void 0:g.taskId,T=!!(g.taskId&&g.runId),[L,M]=j.useState(!1),[P,F]=j.useState(!1),[ce,U]=j.useState(null),[D,te]=j.useState(null),[$,q]=j.useState(null),[R,V]=j.useState(new Set),[X,le]=j.useState([]),[ee,Y]=j.useState(),H=!!d&&$===d,[W,oe]=j.useState(new Map),[be,k]=j.useState(new Map),[z,K]=j.useState(new Map),[A,xe]=j.useState(new Map);mO(),j.useEffect(()=>{window.scrollTo(0,0)},[f]),j.useEffect(()=>{let Te=!1;return DE().then(Fe=>{Te||V(Fe)}),()=>{Te=!0}},[]),j.useEffect(()=>{r&&s("host.info").then(Te=>{var Ve,He,nt,ft,rt,qt;le(Te.agents??[]),Y(Te.host_platform),q(Te.linked_client_token??null),yE(Te.agents??[]);const Fe=Te.version??null;te(Fe),M(!!Fe&&gO(Fe,pO)),t(f,Te.lan_url??void 0);const Qe=new Map,qe=new Map,ct=new Map,vt=new Map;for(const Tt of Te.pending_prompts??[])if(Tt.type==="confirmation")Qe.set(Tt.key,{description:((Ve=Tt.meta)==null?void 0:Ve.description)??"",sessionName:(He=Tt.meta)==null?void 0:He.session_name});else if(Tt.type==="permission")qe.set(Tt.key,{permissions:Tt.params??[],sessionName:(nt=Tt.meta)==null?void 0:nt.session_name});else if(Tt.type==="input"){const ht=Tt.params??((ft=Tt.meta)==null?void 0:ft.input_questions)??[];ct.set(Tt.key,{questions:ht,description:(rt=Tt.meta)==null?void 0:rt.description,sessionName:(qt=Tt.meta)==null?void 0:qt.session_name}),vt.set(Tt.key,new Array(ht.length).fill(""))}oe(Qe),k(qe),K(ct),xe(vt)}).catch(()=>{})},[r,f,s,t]),j.useEffect(()=>r?l(f,Fe=>{const Qe=Fe.subject.split(".");if(Qe.length<3)return;const qe=Qe.slice(2).join(".");let ct={};try{ct=JSON.parse(new TextDecoder().decode(Fe.data))}catch{return}const vt=ct.event_type,Ve=ct.session_id;if(vt==="input-request"&&Ve){const He=ct.input_questions,nt=ct.session_name,ft=ct.description;He!=null&&He.length&&(K(rt=>{if(rt.has(Ve))return rt;const qt=new Map(rt);return qt.set(Ve,{questions:He,description:ft,sessionName:nt}),qt}),xe(rt=>{if(rt.has(Ve))return rt;const qt=new Map(rt);return qt.set(Ve,new Array(He.length).fill("")),qt}));return}if(vt==="input-resolved"&&Ve){K(He=>{if(!He.has(Ve))return He;const nt=new Map(He);return nt.delete(Ve),nt}),xe(He=>{const nt=new Map(He);return nt.delete(Ve),nt});return}if(vt==="confirm-request"&&Ve){const He=ct.description,nt=ct.session_name;He&&oe(ft=>{if(ft.has(Ve))return ft;const rt=new Map(ft);return rt.set(Ve,{description:He,sessionName:nt}),rt});return}if(vt==="confirm-resolved"&&Ve){oe(He=>{if(!He.has(Ve))return He;const nt=new Map(He);return nt.delete(Ve),nt});return}if(vt==="permission-request"){const He=ct.required_permissions,nt=ct.session_name;He!=null&&He.length&&k(ft=>{if(ft.has(qe))return ft;const rt=new Map(ft);return rt.set(qe,{permissions:He,sessionName:nt}),rt});return}if(vt==="permission-resolved"){k(He=>{if(!He.has(qe))return He;const nt=new Map(He);return nt.delete(qe),nt});return}}):void 0,[r,f,l]);async function _e(Te,Fe){try{await s("task.user_input",{id:Te,value:[Fe]})}catch(Qe){console.error("[Dashboard] Failed to respond to confirmation:",Qe)}}async function je(Te,Fe){try{await s("task.user_input",{id:Te,value:[Fe]})}catch(Qe){console.error("[Dashboard] Failed to respond to permission request:",Qe)}}async function Le(Te,Fe){try{await s("task.user_input",{id:Te,value:Fe})}catch(Qe){console.error("[Dashboard] Failed to respond to input request:",Qe)}}function $e(Te,Fe){if(!ps())return;const Qe=`/hosts/${encodeURIComponent(f)}/runs/${encodeURIComponent(Te)}`;m(Fe?`${Qe}/${encodeURIComponent(Fe)}`:Qe)}async function Ce(){F(!0),U(null);try{const Te=await s("host.update");if(Te.error){U(Te.error),F(!1);return}}catch{}setTimeout(()=>window.location.reload(),15e3)}const Ne=r&&!u;return b.jsxs("div",{className:"dashboard",children:[x&&b.jsx($0,{daemonVersion:D,linkedClientToken:$,request:s,onEnabledCapabilitiesChange:V,onLinkedClientTokenChange:q}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!x&&b.jsx($0,{daemonVersion:D,linkedClientToken:$,request:s,onEnabledCapabilitiesChange:V,onLinkedClientTokenChange:q}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(PE,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(OE,{})})]}),b.jsx("main",{className:"dashboard-main",children:u?b.jsxs("div",{className:"revoked-state",children:[b.jsx("div",{className:"revoked-icon",children:b.jsxs("svg",{width:"32",height:"32",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[b.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),b.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}),b.jsx("line",{x1:"12",y1:"15",x2:"12",y2:"18"})]})}),b.jsx("h2",{className:"revoked-title",children:"Client Revoked"}),b.jsx("p",{className:"revoked-description",children:"This client was revoked by the host. To reconnect, generate a new pairing code on the host machine."}),b.jsx("div",{className:"revoked-command",children:b.jsx("code",{children:"palmier pair"})}),b.jsxs("div",{className:"revoked-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>{ps()&&m("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(f),m("/",{replace:!0})},children:"Remove Host"})]})]}):Ne?b.jsxs(b.Fragment,{children:[w&&!T&&b.jsx(NE,{connected:r,hostId:f,request:s,subscribeEvents:l,agents:X,hostPlatform:ee,isNotificationListener:H&&R.has("notifications"),onViewRun:$e}),T?b.jsx(dO,{connected:r,hostId:f,request:s,subscribeEvents:l,taskId:g.taskId,runId:decodeURIComponent(g.runId)}):w?null:b.jsx(FE,{connected:r,hostId:f,request:s,subscribeEvents:l,agents:X,hostPlatform:ee,filterTaskId:S,onClearFilter:()=>{ps()&&m(`/hosts/${encodeURIComponent(f)}`)}})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{children:"Connecting to host..."})})}),L&&!P&&!ce&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Update Required"}),b.jsxs("p",{className:"confirm-modal-message",children:["Your Palmier host",D?` (v${D})`:""," is too old for this version of the app. Please update to continue."]}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-primary",onClick:Ce,children:"Update Now"})})]})}),P&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Updating..."}),b.jsx("p",{className:"confirm-modal-message",children:"Installing update and restarting daemon. Please wait..."})]})}),ce&&b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Update Failed"}),b.jsx("p",{className:"confirm-modal-message",style:{whiteSpace:"pre-line"},children:ce}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{U(null)},children:"Retry"})})]})})]}),ds.createPortal(b.jsxs(b.Fragment,{children:[[...W.entries()].map(([Te,{description:Fe,sessionName:Qe}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Confirmation Required"}),Qe&&b.jsx("p",{className:"confirm-modal-subtitle",children:Qe}),b.jsx("p",{className:"confirm-modal-message",children:Fe}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>_e(Te,"confirmed"),children:"Confirm"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>_e(Te,"aborted"),children:"Abort"})]})]})},Te)),[...be.entries()].map(([Te,{permissions:Fe,sessionName:Qe}])=>b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal permission-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Permission Required"}),b.jsx("p",{className:"confirm-modal-message",children:b.jsx("strong",{children:Qe||Te})}),b.jsx("div",{className:"permission-list",children:Fe.map((qe,ct)=>b.jsxs("div",{className:"permission-item",children:[b.jsx("span",{className:"permission-name",children:qe.name}),qe.description&&b.jsx("span",{className:"permission-desc",children:qe.description})]},ct))}),b.jsxs("div",{className:"permission-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>je(Te,"granted"),children:"Allow Once"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>je(Te,"granted_all"),children:"Allow Always"})]}),b.jsx("button",{className:"permission-abort-link",onClick:()=>je(Te,"aborted"),children:"Deny & Abort Task"})]})},Te)),[...z.entries()].map(([Te,{questions:Fe,description:Qe,sessionName:qe}])=>{const ct=A.get(Te)??new Array(Fe.length).fill("");return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal input-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:"Input Required"}),qe&&b.jsx("p",{className:"confirm-modal-subtitle",children:qe}),Qe&&b.jsx("p",{className:"confirm-modal-message",children:Qe}),b.jsx("div",{className:"input-list",children:Fe.map((vt,Ve)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:vt}),b.jsx("input",{type:"text",className:"input-field",value:ct[Ve]??"",onChange:He=>{xe(nt=>{const ft=new Map(nt),rt=[...ft.get(Te)??[]];return rt[Ve]=He.target.value,ft.set(Te,rt),ft})},autoFocus:Ve===0})]},Ve))}),b.jsx("div",{className:"input-actions",children:b.jsx("button",{className:"btn btn-primary",disabled:ct.some(vt=>!vt.trim()),onClick:()=>Le(Te,ct),children:"Submit"})}),b.jsx("button",{className:"permission-abort-link",onClick:()=>Le(Te,["aborted"]),children:"Cancel"})]})},Te)})]}),document.body)]})}const yO=ys("Preferences",{web:()=>Id(()=>import("./web-Dcldtodb.js"),[]).then(e=>new e.PreferencesWeb)}),kl=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),qb=Vn.isNativePlatform();function bO(){const[e,t]=j.useState(""),[r,s]=j.useState(!0),[l,u]=j.useState(!1),[c,f]=j.useState(null),{addPairedHost:d}=Pi(),m=Or();async function y(){const g=e.trim().toUpperCase();if(!g){f("Enter a pairing code.");return}u(!0),f(null);try{let x;if(kl){const T=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:g,label:navigator.userAgent})});if(!T.ok){const L=await T.json().catch(()=>({error:"Connection failed"}));throw new Error(L.error||`HTTP ${T.status}`)}x=await T.json()}else{const T=await fetch(`${Uu}/api/config`);if(!T.ok)throw new Error("Failed to fetch server config");const L=await T.json();if(!L.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const M=await Nx({servers:L.natsWsUrl,authenticator:wx(L.natsJwt,new TextEncoder().encode(L.natsNkeySeed))}),P=Nu(),F=`pair.${g}`,ce=await M.request(F,P.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});x=JSON.parse(P.decode(ce.data)),await M.close()}const w={hostId:x.hostId,clientToken:x.clientToken,directUrl:kl?window.location.origin:void 0,...x.hostName?{name:x.hostName}:{}};if(d(w),Vn.isNativePlatform()&&mn){await yO.set({key:"hostId",value:x.hostId});try{const{token:T}=await mn.getFcmToken();await fetch(`${Uu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:x.hostId,fcmToken:T})})}catch(T){console.warn("FCM token registration failed:",T)}}const S=`/hosts/${encodeURIComponent(x.hostId)}`;m(qb&&r?`${S}/pair/setup`:S)}catch(x){const w=x instanceof Error?x.message:String(x);w.includes("timeout")||w.includes("TIMEOUT")||w.includes("503")||w.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(w)}finally{u(!1)}}return b.jsx("div",{className:"pair-page",children:b.jsxs("div",{className:"pair-card",children:[b.jsxs("div",{className:"pair-header",children:[b.jsx("h1",{className:"pair-title",children:kl?"Pair":"Pair with Host"}),b.jsx("p",{className:"pair-subtitle",children:kl?"Enter the pairing code shown in your terminal.":"Connect this device to a Palmier host"})]}),!kl&&b.jsxs("div",{className:"pair-instructions",children:[b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Setting up a new host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Install at least one agent CLI (e.g., ",b.jsx("a",{href:"https://www.palmier.me/agents",target:"_blank",rel:"noopener noreferrer",children:"Claude Code, Gemini CLI, Codex CLI"}),")"]}),b.jsxs("li",{children:["Install Palmier on your host machine.",b.jsx("span",{className:"pair-platform-label",children:"Linux / macOS:"}),b.jsx("code",{className:"pair-command",children:"curl -fsSL https://palmier.me/install.sh | bash"}),b.jsx("span",{className:"pair-platform-label",children:"Windows (PowerShell):"}),b.jsx("code",{className:"pair-command",children:"irm https://palmier.me/install.ps1 | iex"})]}),b.jsxs("li",{children:["Run the setup wizard:",b.jsx("code",{className:"pair-command",children:"palmier init"})]}),b.jsx("li",{children:"A pairing code will display automatically"})]})]}),b.jsx("div",{className:"pair-instruction-divider"}),b.jsxs("div",{className:"pair-instruction-block",children:[b.jsx("h3",{className:"pair-instruction-heading",children:"Pairing an existing host?"}),b.jsxs("ol",{className:"pair-steps",children:[b.jsxs("li",{children:["Run ",b.jsx("code",{children:"palmier pair"})," on the host machine"]}),b.jsx("li",{children:"Enter the 6-character code below"})]})]})]}),b.jsxs("div",{className:"pair-form",children:[b.jsxs("label",{className:"form-label",htmlFor:"pair-code",children:["Pairing code",b.jsx("input",{id:"pair-code",type:"text",maxLength:6,value:e,onChange:g=>t(g.target.value.toUpperCase()),placeholder:"A7K9M2",className:"form-input form-input-mono pair-code-input",autoFocus:!0,autoComplete:"off",disabled:l})]}),qb&&b.jsxs("label",{className:"pair-checkbox",children:[b.jsx("input",{type:"checkbox",checked:r,onChange:g=>s(g.target.checked),disabled:l}),b.jsxs("span",{className:"pair-checkbox-text",children:[b.jsx("span",{className:"pair-checkbox-title",children:"Link the host to this device"}),b.jsx("span",{className:"pair-checkbox-hint",children:r?"The host will use this device for SMS, contacts, calendar, location, and alarms. Only one device can be linked to the host.":"This device won't provide SMS, contacts, calendar, location, or alarms to the host. You can link it later from the menu."})]})]}),c&&b.jsx("p",{className:"pair-error",children:c}),b.jsxs("button",{className:"btn btn-primary btn-full",onClick:y,disabled:l||!e.trim(),children:[l&&b.jsx("span",{className:"btn-spinner"}),l?"Pairing...":"Pair"]}),b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>m("/"),disabled:l,children:"Cancel"}),b.jsxs("p",{className:"pair-consent",children:["By pairing, you agree to our"," ",b.jsx("a",{href:"https://www.palmier.me/terms",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," and"," ",b.jsx("a",{href:"https://www.palmier.me/privacy",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]})]})]})})}function xO(){const e=Or(),{connected:t,request:r,activeHost:s}=Hi(),{setHostLanUrl:l,pairedHosts:u}=Pi(),c=u.length<=1,[f,d]=j.useState("loading"),[m,y]=j.useState(null),[g,x]=j.useState(null);function w(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}j.useEffect(()=>{if(!t||f!=="loading")return;let P=!1;return r("host.info").catch(()=>({})).then(F=>{if(P)return;l(s.hostId,F.lan_url??void 0);const ce=F.linked_client_token??null;y(ce);const U=!!ce&&ce!==s.clientToken;d(U?"confirming":"linking")}),()=>{P=!0}},[t,f,s,r,l]),j.useEffect(()=>{if(f!=="linking")return;let P=!1;return(async()=>{try{if(mn){const{token:F}=await mn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(P)return;c?d("wizard"):w()}catch(F){if(P)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{P=!0}},[f]);function S(){d("linking")}function T(){w()}function L(){x(null),d("linking")}const M=f==="confirming"&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:T,children:b.jsxs("div",{className:"confirm-modal",onClick:P=>P.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Link the host to this device?"}),b.jsx("p",{className:"confirm-modal-message",children:"Another device is already linked to this host. Only one device can be linked to the host — switching will disable those capabilities on the currently linked device."}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-secondary",onClick:T,children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:S,children:"Link"})]})]})}),document.body);if(f==="loading"||f==="confirming"||f==="linking"||f==="linkError"){const P=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[P&&b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsxs("div",{className:"pair-setup-loading",children:[F&&b.jsx("span",{className:"spinner spinner-lg"}),f==="loading"&&b.jsx("span",{children:"Connecting to host…"}),f==="confirming"&&b.jsx("span",{children:"Awaiting confirmation…"}),f==="linking"&&b.jsx("span",{children:"Linking device…"}),f==="linkError"&&b.jsxs(b.Fragment,{children:[b.jsx("p",{className:"pair-error",children:g}),b.jsx("button",{className:"btn btn-primary",onClick:L,children:"Retry"}),b.jsx("button",{className:"btn btn-secondary",onClick:w,children:"Skip linking"})]})]})]}),M]})}return b.jsx("div",{className:"pair-setup",children:b.jsxs("div",{className:"pair-setup-inner",children:[b.jsx("h1",{className:"pair-setup-title",children:"Device Capabilities"}),b.jsx("p",{className:"pair-setup-description",children:"Choose what the host can use this device for. You can change these later from the menu."}),b.jsx(Bx,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:w,children:"Finish"})})]})})}function vO(){const e=Or();return j.useEffect(()=>{if(!mn)return;const t=mn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function wO(){const{pairedHosts:e}=Pi();return e.length===0?b.jsx(Ll,{to:"/pair",replace:!0}):b.jsx(Ll,{to:`/hosts/${encodeURIComponent(e[0].hostId)}`,replace:!0})}function SO(){const{hostId:e}=Yu(),{pairedHosts:t}=Pi(),r=t.find(s=>s.hostId===e)??null;return r?b.jsx(gE,{activeHost:r,children:b.jsxs(nx,{children:[b.jsx(gr,{index:!0,element:b.jsx(xu,{})}),b.jsx(gr,{path:"tasks",element:b.jsx(xu,{})}),b.jsx(gr,{path:"runs/:taskId",element:b.jsx(xu,{})}),b.jsx(gr,{path:"runs/:taskId/:runId",element:b.jsx(xu,{})}),b.jsx(gr,{path:"pair/setup",element:b.jsx(xO,{})}),b.jsx(gr,{path:"*",element:b.jsx(Ll,{to:".",replace:!0})})]})}):b.jsx(Ll,{to:"/",replace:!0})}function _O(){return b.jsxs(q_,{children:[b.jsx(vO,{}),b.jsxs(nx,{children:[b.jsx(gr,{path:"/",element:b.jsx(wO,{})}),b.jsx(gr,{path:"/pair",element:b.jsx(bO,{})}),b.jsx(gr,{path:"/hosts/:hostId/*",element:b.jsx(SO,{})}),b.jsx(gr,{path:"*",element:b.jsx(Ll,{to:"/",replace:!0})})]})]})}lS.createRoot(document.getElementById("root")).render(b.jsx(j.StrictMode,{children:b.jsx(A_,{children:b.jsx(_O,{})})}));export{Hd as W};
|