palmier 0.9.17 → 0.9.18

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.
@@ -25,8 +25,6 @@ export interface AgentTool {
25
25
  supportsYolo?: boolean;
26
26
  /** When true, the run loop will not listen to or persist the agent's stderr output. */
27
27
  suppressStdErr?: boolean;
28
- /** npm package that provides this agent's CLI, if installable via `npm install -g`.
29
- * Used by `palmier init` to offer one-click installation when no agents are detected. */
30
28
  npmPackage?: string;
31
29
  /** Optional human-readable note about free-usage availability (e.g. "Free Tier").
32
30
  * Surfaced next to the agent in the installer. */
@@ -49,12 +47,9 @@ export interface DetectedAgent {
49
47
  label: string;
50
48
  supportsPermissions?: boolean;
51
49
  supportsYolo?: boolean;
52
- /** npm package name, present iff the agent is installable via npm. */
53
50
  npmPackage?: string;
54
- /** Currently-installed version (resolved via `npm ls -g`) for npm-installed agents. */
51
+ /** Runtime marker for "managed by Palmier" present iff Palmier installed/manages this agent. */
55
52
  version?: string;
56
- /** True when this agent was installed by Palmier (the init wizard). Persists across detections. */
57
- palmierManaged?: boolean;
58
53
  }
59
54
  export interface InstallableAgent {
60
55
  key: string;
@@ -115,16 +115,14 @@ export async function detectAgents(previous) {
115
115
  const ok = await probeAgent(agent);
116
116
  if (!ok)
117
117
  continue;
118
- const version = agent.npmPackage ? getNpmInstalledVersion(agent.npmPackage) ?? undefined : undefined;
119
- const prevManaged = previousByKey.get(key)?.palmierManaged;
118
+ const prevVersion = previousByKey.get(key)?.version;
120
119
  detected.push({
121
120
  key,
122
121
  label,
123
122
  supportsPermissions: agent.supportsPermissions,
124
123
  supportsYolo: agent.supportsYolo,
125
124
  ...(agent.npmPackage ? { npmPackage: agent.npmPackage } : {}),
126
- ...(version ? { version } : {}),
127
- ...(prevManaged ? { palmierManaged: true } : {}),
125
+ ...(prevVersion ? { version: prevVersion } : {}),
128
126
  });
129
127
  }
130
128
  return detected;
@@ -1,7 +1,7 @@
1
1
  import * as readline from "readline";
2
2
  import { spawnSync } from "child_process";
3
3
  import { loadConfig, saveConfig } from "../config.js";
4
- import { detectAgents, listInstallableAgents } from "../agents/agent.js";
4
+ import { detectAgents, getNpmInstalledVersion, listInstallableAgents } from "../agents/agent.js";
5
5
  import { getPlatform } from "../platform/index.js";
6
6
  import { pairCommand } from "./pair.js";
7
7
  import { detectDefaultInterface, getInterfaceIpv4 } from "../network.js";
@@ -155,7 +155,9 @@ async function offerAgentInstall(currentAgents) {
155
155
  console.log(`${red(`${choice.label} still not detected after install.`)} It may not be on PATH yet — open a new terminal and run ${cyan("palmier init")} again.`);
156
156
  return agents;
157
157
  }
158
- installedAgent.palmierManaged = true;
158
+ const version = getNpmInstalledVersion(choice.npmPackage);
159
+ if (version)
160
+ installedAgent.version = version;
159
161
  console.log(green(` ${choice.label} installed.`));
160
162
  console.log(`\n${bold("Next: authenticate the CLI.")}`);
161
163
  console.log(` Run ${cyan(choice.command)} in another terminal and follow the sign-in prompts.`);
@@ -84,7 +84,7 @@ ${d}`),g(S);return}f(null,N),s.strategy===xr.Count&&(m--,m===0&&g()),s.strategy=
84
84
 
85
85
  ${f.stack}`),d.unsubscribe(),c.reject(m)):(m=gx(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 xx(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(je.errorForCode(_e.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(je.errorForCode(_e.ConnectionClosed)):this.isDraining()?Promise.reject(je.errorForCode(_e.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 sn;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 Bk(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===_e.NoResponders&&(l.code=_e.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Hd(this,t)}getServerVersion(){const t=this.info;return t?ms(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw je.errorForCode(_e.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 Ik(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(je.errorForCode(_e.ConnectionClosed)):this.isDraining()?Promise.reject(je.errorForCode(_e.ConnectionDraining)):this.protocol.reconnect()}}class Ik{constructor(t){E(this,"nc");this.nc=t}add(t){try{return new Vl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new wk(this.nc,t,r)}}class Fk{constructor(t,r,s){E(this,"bucket");E(this,"sm");E(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(Uu)||"PUT"}get length(){const t=this.sm.header.get(kn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class $k{constructor(t,r,s){E(this,"bucket");E(this,"key");E(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Ld(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(Uu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(kn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Rx extends w2{constructor(r,s,l){super(r.nc,s,l);E(this,"js");E(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=ni(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const u=this.info;u.config.name=Pi.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 je(`unable to recreate ordered consumer ${u.stream} at seq ${r}`,_e.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(Ld(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=t2(409,`${or.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 Ud(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(kn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(kn.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 Yk extends Rx{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(ct.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 Vk(e,t){return e?Jk(t):Gk(t)}function Gk(e){return(t,r)=>t?[t,null]:(t=ua(r),t?[t,null]:[null,Hl(r,e)])}function Jk(e){return(t,r)=>{if(t)return[t,null];const s=ua(r);return s!==null?[Mx(s),null]:[null,Hl(r,e)]}}function Mx(e){if(e!==null)switch(e.code){case _e.JetStream404NoMessages:case _e.JetStream408RequestTimeout:return null;case _e.JetStream409:return n2(e)?e:null;default:return e}return null}function Xk(e){e&&e.ack()}function Kk(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 Qk{constructor(t,r){E(this,"msg");E(this,"di");E(this,"didAck");E(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=Kk(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 xx(u.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);u.request(f);try{u.publish(this.msg.reply,L0,{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(L0)}nak(t){let r=Ok;t&&(r=Ou().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=vr().encode(s),u=ga.concat(Rk,Dk,l),c=t?{reply:t}:void 0;this.msg.respond(u,c)}term(t=""){let r=Mk;(t==null?void 0:t.length)>0&&(r=Ou().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const Zk="1.30.3",Wk="nats.ws";class eE{constructor(){E(this,"version");E(this,"lang");E(this,"closeError");E(this,"connected");E(this,"done");E(this,"socket");E(this,"options");E(this,"socketClosed");E(this,"encrypted");E(this,"peeked");E(this,"yields");E(this,"signal");E(this,"closedNotification");this.version=Zk,this.lang=Wk,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 je("tls",_e.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=A2(c);if(f!==""){const d=dk.exec(f);if(!d){r.debug&&console.error("!!!",fu(c)),s.reject(new Error("unexpected response from server"));return}try{const m=JSON.parse(d[1]);fk(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 je(c.message,_e.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(`> ${fu(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(`< ${fu(t)}`);return}catch(r){this.options.debug&&console.error(`!!! ${fu(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 tE(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 Dx(e={}){return S2({defaultPort:443,urlParseFn:tE,factory:()=>new eE}),qd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var ya;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(ya||(ya={}));class Th extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const nE=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"},rE=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:nE(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(),N=f(g);let z;const O=async()=>(!z&&S in x?z=typeof x[S]=="function"?z=await x[S]():z=x[S]:t!==null&&!z&&"web"in x&&(z=typeof x.web=="function"?z=await x.web():z=x.web),z),H=($,q)=>{var M,V;if(N){const J=N==null?void 0:N.methods.find(fe=>q===fe.name);if(J)return J.rtype==="promise"?fe=>r.nativePromise(g,q.toString(),fe):(fe,ie)=>r.nativeCallback(g,q.toString(),fe,ie);if($)return(M=$[q])===null||M===void 0?void 0:M.bind($)}else{if($)return(V=$[q])===null||V===void 0?void 0:V.bind($);throw new Th(`"${g}" plugin is not implemented on ${S}`,ya.Unimplemented)}},F=$=>{let q;const M=(...V)=>{const J=O().then(fe=>{const ie=H(fe,$);if(ie){const Q=ie(...V);return q=Q==null?void 0:Q.remove,Q}else throw new Th(`"${g}.${$}()" is not implemented on ${S}`,ya.Unimplemented)});return $==="addListener"&&(J.remove=async()=>q()),J};return M.toString=()=>`${$.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:$,writable:!1,configurable:!1}),M},oe=F("addListener"),U=F("removeListener"),D=($,q)=>{const M=oe({eventName:$},q),V=async()=>{const fe=await M;U({eventName:$,callbackId:fe},q)},J=new Promise(fe=>M.then(()=>fe({remove:V})));return J.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await V()},J},ee=new Proxy({},{get($,q){switch(q){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return N?D:oe;case"removeListener":return U;default:return F(q)}}});return s[g]=ee,m.set(g,{name:g,proxy:ee,platforms:new Set([...Object.keys(x),...N?[S]:[]])}),ee};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=u,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=Th,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},iE=e=>e.Capacitor=rE(e),Jn=iE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ys=Jn.registerPlugin;class Id{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 Jn.Exception(t,ya.Unimplemented)}unavailable(t="not available"){return new Jn.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 U0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),B0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class sE extends Id{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=B0(l).trim(),u=B0(u).trim(),r[l]=u}),r}async setCookie(t){try{const r=U0(t.key),s=U0(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 sE});const aE=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)}),lE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,u,c)=>(l[u]=e[t[c]],l),{})},oE=(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,uE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=lE(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 cE extends Id{async request(t){const r=uE(t,t.webFetchExtra),s=oE(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 aE(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 cE});var P0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(P0||(P0={}));var H0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(H0||(H0={}));class fE extends Id{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 fE});const hE="modulepreload",dE=function(e){return"/"+e},q0={},Fd=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=dE(m),m in q0)return;q0[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":hE,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)})},dd=ys("App",{web:()=>Fd(()=>import("./web-Dv6FIZ03.js"),[]).then(e=>new e.AppWeb)}),mE=ys("Network",{web:()=>Fd(()=>import("./web-6nrvzqi7.js"),[]).then(e=>new e.NetworkWeb)}),Bu=Jn.isNativePlatform()?"https://app.palmier.me":"";async function Lx(e,t,r,s){const l=`${Bu}${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 pE(e,t,r){return Lx("POST",e,t)}function gE(e,t){return Lx("GET",e,void 0)}const I0=Jn.isNativePlatform(),zx=T.createContext(null),yE=2e3,jh=6e3,bE=1500,xE=6e4;function vE({children:e,activeHost:t}){const[r,s]=T.useState(null),[l,u]=T.useState(!1),c=T.useRef(null),[f,d]=T.useState(!1),[m,y]=T.useState(!1),[g,x]=T.useState(!1),[w,S]=T.useState(!1),N=T.useRef(Ou()),z=T.useRef(new Set),O=T.useRef(0),H=!!t.directUrl,F=I0&&!H&&!!t.lanUrl&&w,oe=m||g?"disconnected":H?f?"direct":"connecting":l?F?"lan":"nats":"connecting",U=oe!=="connecting"&&oe!=="disconnected";T.useEffect(()=>{y(!1),x(!1)},[t.hostId,t.clientToken]),T.useEffect(()=>{if(!I0||H||!t.lanUrl){S(!1);return}let $=!1;const q=t.lanUrl,M=t.hostId;async function V(){console.log("[HOST/LAN] probing",q);try{const Q=await fetch(`${q}/health`,{signal:AbortSignal.timeout(bE)});if($)return;if(!Q.ok){console.log("[HOST/LAN] probe got non-ok:",Q.status),S(!1);return}const P=await Q.json(),te=P.hostId===M;te?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",P.hostId,"expected:",M),S(te)}catch(Q){$||(console.log("[HOST/LAN] probe failed:",Q instanceof Error?Q.message:Q),S(!1))}}V();const J=window.setInterval(V,xE),fe=dd.addListener("appStateChange",Q=>{Q.isActive&&V()}),ie=mE.addListener("networkStatusChange",()=>V());return()=>{$=!0,clearInterval(J),fe.then(Q=>Q.remove()),ie.then(Q=>Q.remove())}},[t.hostId,t.lanUrl,H]),T.useEffect(()=>{if(H){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1));return}let $=!1,q=1e3;const M=3e4;async function V(){for(;!$;)try{const J=await fetch(`${Bu}/api/nats-credentials/${t.hostId}`);if($)return;if(J.status===401||J.status===403||J.status===404){console.error("[NATS] Host not found or rejected by relay:",J.status),x(!0);return}if(!J.ok)throw new Error(`credentials fetch ${J.status}`);const fe=await J.json();if(!fe.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if($)return;console.log("[NATS] Connecting to",fe.natsWsUrl);const ie=await Dx({servers:fe.natsWsUrl,authenticator:Ex(fe.natsJwt,new TextEncoder().encode(fe.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if($){ie.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=ie,s(ie),u(!0),q=1e3,await ie.closed(),$)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),u(!1)}catch(J){if($)return;console.warn(`[NATS] Connect failed, retrying in ${q}ms:`,J),u(!1),await new Promise(fe=>setTimeout(fe,q)),q=Math.min(q*2,M)}}return V(),()=>{$=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1))}},[H,t]),T.useEffect(()=>{if(H)return;const $=dd.addListener("appStateChange",q=>{if(!q.isActive||!c.current)return;const M=c.current;Promise.race([M.flush(),new Promise((V,J)=>setTimeout(()=>J(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),M.close().catch(()=>{})})});return()=>{$.then(q=>q.remove())}},[H]),T.useEffect(()=>{if(!H){d(!1);return}const $=new AbortController;async function q(){var fe;const V=new AbortController,J=setTimeout(()=>V.abort(),yE);$.signal.addEventListener("abort",()=>V.abort());try{const ie=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:V.signal});return clearTimeout(J),ie.ok?((fe=ie.body)==null?void 0:fe.getReader())??null:null}catch{return clearTimeout(J),null}}async function M(V){d(!0),console.log("[HOST] SSE connected to",t.directUrl),O.current=Date.now();function J(){setTimeout(()=>{$.signal.aborted||Date.now()-O.current<jh||(console.log("[HOST] Heartbeat timeout — no data for",jh/1e3,"s"),$.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},jh)}J();const fe=new TextDecoder;let ie="";try{for(;;){const{done:Q,value:P}=await V.read();if(Q)break;ie+=fe.decode(P,{stream:!0}),O.current=Date.now(),J();const te=ie.split(`
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 xx(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(je.errorForCode(_e.ConnectionClosed)):this.protocol.flush()}drain(){return this.isClosed()?Promise.reject(je.errorForCode(_e.ConnectionClosed)):this.isDraining()?Promise.reject(je.errorForCode(_e.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 sn;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 Bk(this,t);if(t.checkAPI!==!1)try{await r.getAccountInfo()}catch(s){const l=s;throw l.code===_e.NoResponders&&(l.code=_e.JetStreamNotEnabled),l}return r}jetstream(t={}){return new Hd(this,t)}getServerVersion(){const t=this.info;return t?ms(t.version):void 0}async rtt(){if(!this.protocol._closed&&!this.protocol.connected)throw je.errorForCode(_e.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 Ik(this)),this._services}reconnect(){return this.isClosed()?Promise.reject(je.errorForCode(_e.ConnectionClosed)):this.isDraining()?Promise.reject(je.errorForCode(_e.ConnectionDraining)):this.protocol.reconnect()}}class Ik{constructor(t){E(this,"nc");this.nc=t}add(t){try{return new Vl(this.nc,t).start()}catch(r){return Promise.reject(r)}}client(t,r){return new wk(this.nc,t,r)}}class Fk{constructor(t,r,s){E(this,"bucket");E(this,"sm");E(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(Uu)||"PUT"}get length(){const t=this.sm.header.get(kn.MessageSizeHdr)||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class $k{constructor(t,r,s){E(this,"bucket");E(this,"key");E(this,"sm");this.bucket=t,this.key=r,this.sm=s}get value(){return this.sm.data}get created(){return new Date(Ld(this.sm.info.timestampNanos))}get revision(){return this.sm.seq}get operation(){var t;return((t=this.sm.headers)==null?void 0:t.get(Uu))||"PUT"}get delta(){return this.sm.info.pending}get length(){var r;const t=((r=this.sm.headers)==null?void 0:r.get(kn.MessageSizeHdr))||"";return t!==""?parseInt(t,10):this.sm.data.length}json(){return this.sm.json()}string(){return this.sm.string()}}class Rx extends w2{constructor(r,s,l){super(r.nc,s,l);E(this,"js");E(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=ni(this.js.nc.options.inboxPrefix);this.js.nc._resub(this.sub,s);const u=this.info;u.config.name=Pi.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 je(`unable to recreate ordered consumer ${u.stream} at seq ${r}`,_e.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(Ld(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=t2(409,`${or.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 Ud(r,c,l)}_checkHbOrderConsumer(r){const s=r.headers.get(kn.ConsumerStalledHdr);s!==""&&this.js.nc.publish(s);const l=parseInt(r.headers.get(kn.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 Yk extends Rx{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(ct.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 Vk(e,t){return e?Jk(t):Gk(t)}function Gk(e){return(t,r)=>t?[t,null]:(t=ua(r),t?[t,null]:[null,Hl(r,e)])}function Jk(e){return(t,r)=>{if(t)return[t,null];const s=ua(r);return s!==null?[Mx(s),null]:[null,Hl(r,e)]}}function Mx(e){if(e!==null)switch(e.code){case _e.JetStream404NoMessages:case _e.JetStream408RequestTimeout:return null;case _e.JetStream409:return n2(e)?e:null;default:return e}return null}function Xk(e){e&&e.ack()}function Kk(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 Qk{constructor(t,r){E(this,"msg");E(this,"di");E(this,"didAck");E(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=Kk(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 xx(u.muxSubscriptions,this.msg.reply,{timeout:t.timeout},c);u.request(f);try{u.publish(this.msg.reply,L0,{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(L0)}nak(t){let r=Ok;t&&(r=Ou().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=vr().encode(s),u=ga.concat(Rk,Dk,l),c=t?{reply:t}:void 0;this.msg.respond(u,c)}term(t=""){let r=Mk;(t==null?void 0:t.length)>0&&(r=Ou().encode(`+TERM ${t}`)),this.doAck(r)}json(){return this.msg.json()}string(){return this.msg.string()}}const Zk="1.30.3",Wk="nats.ws";class eE{constructor(){E(this,"version");E(this,"lang");E(this,"closeError");E(this,"connected");E(this,"done");E(this,"socket");E(this,"options");E(this,"socketClosed");E(this,"encrypted");E(this,"peeked");E(this,"yields");E(this,"signal");E(this,"closedNotification");this.version=Zk,this.lang=Wk,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 je("tls",_e.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=A2(c);if(f!==""){const d=dk.exec(f);if(!d){r.debug&&console.error("!!!",fu(c)),s.reject(new Error("unexpected response from server"));return}try{const m=JSON.parse(d[1]);fk(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 je(c.message,_e.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(`> ${fu(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(`< ${fu(t)}`);return}catch(r){this.options.debug&&console.error(`!!! ${fu(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 tE(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 Dx(e={}){return S2({defaultPort:443,urlParseFn:tE,factory:()=>new eE}),qd.connect(e)}/*! Capacitor: https://capacitorjs.com/ - MIT License */var ya;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(ya||(ya={}));class Th extends Error{constructor(t,r,s){super(t),this.message=t,this.code=r,this.data=s}}const nE=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"},rE=e=>{const t=e.CapacitorCustomPlatform||null,r=e.Capacitor||{},s=r.Plugins=r.Plugins||{},l=()=>t!==null?t.name:nE(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(),N=f(g);let z;const O=async()=>(!z&&S in x?z=typeof x[S]=="function"?z=await x[S]():z=x[S]:t!==null&&!z&&"web"in x&&(z=typeof x.web=="function"?z=await x.web():z=x.web),z),H=($,q)=>{var M,V;if(N){const J=N==null?void 0:N.methods.find(fe=>q===fe.name);if(J)return J.rtype==="promise"?fe=>r.nativePromise(g,q.toString(),fe):(fe,ie)=>r.nativeCallback(g,q.toString(),fe,ie);if($)return(M=$[q])===null||M===void 0?void 0:M.bind($)}else{if($)return(V=$[q])===null||V===void 0?void 0:V.bind($);throw new Th(`"${g}" plugin is not implemented on ${S}`,ya.Unimplemented)}},F=$=>{let q;const M=(...V)=>{const J=O().then(fe=>{const ie=H(fe,$);if(ie){const Q=ie(...V);return q=Q==null?void 0:Q.remove,Q}else throw new Th(`"${g}.${$}()" is not implemented on ${S}`,ya.Unimplemented)});return $==="addListener"&&(J.remove=async()=>q()),J};return M.toString=()=>`${$.toString()}() { [capacitor code] }`,Object.defineProperty(M,"name",{value:$,writable:!1,configurable:!1}),M},oe=F("addListener"),U=F("removeListener"),D=($,q)=>{const M=oe({eventName:$},q),V=async()=>{const fe=await M;U({eventName:$,callbackId:fe},q)},J=new Promise(fe=>M.then(()=>fe({remove:V})));return J.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await V()},J},ee=new Proxy({},{get($,q){switch(q){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return N?D:oe;case"removeListener":return U;default:return F(q)}}});return s[g]=ee,m.set(g,{name:g,proxy:ee,platforms:new Set([...Object.keys(x),...N?[S]:[]])}),ee};return r.convertFileSrc||(r.convertFileSrc=g=>g),r.getPlatform=l,r.handleError=d,r.isNativePlatform=u,r.isPluginAvailable=c,r.registerPlugin=y,r.Exception=Th,r.DEBUG=!!r.DEBUG,r.isLoggingEnabled=!!r.isLoggingEnabled,r},iE=e=>e.Capacitor=rE(e),Jn=iE(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),ys=Jn.registerPlugin;class Id{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 Jn.Exception(t,ya.Unimplemented)}unavailable(t="not available"){return new Jn.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 U0=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),B0=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class sE extends Id{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=B0(l).trim(),u=B0(u).trim(),r[l]=u}),r}async setCookie(t){try{const r=U0(t.key),s=U0(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 sE});const aE=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)}),lE=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(l=>l.toLocaleLowerCase()).reduce((l,u,c)=>(l[u]=e[t[c]],l),{})},oE=(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,uE=(e,t={})=>{const r=Object.assign({method:e.method||"GET",headers:e.headers},t),l=lE(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 cE extends Id{async request(t){const r=uE(t,t.webFetchExtra),s=oE(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 aE(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 cE});var P0;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(P0||(P0={}));var H0;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(H0||(H0={}));class fE extends Id{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 fE});const hE="modulepreload",dE=function(e){return"/"+e},q0={},Fd=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=dE(m),m in q0)return;q0[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":hE,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)})},dd=ys("App",{web:()=>Fd(()=>import("./web-BuyV-_jZ.js"),[]).then(e=>new e.AppWeb)}),mE=ys("Network",{web:()=>Fd(()=>import("./web-BM8S3YX9.js"),[]).then(e=>new e.NetworkWeb)}),Bu=Jn.isNativePlatform()?"https://app.palmier.me":"";async function Lx(e,t,r,s){const l=`${Bu}${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 pE(e,t,r){return Lx("POST",e,t)}function gE(e,t){return Lx("GET",e,void 0)}const I0=Jn.isNativePlatform(),zx=T.createContext(null),yE=2e3,jh=6e3,bE=1500,xE=6e4;function vE({children:e,activeHost:t}){const[r,s]=T.useState(null),[l,u]=T.useState(!1),c=T.useRef(null),[f,d]=T.useState(!1),[m,y]=T.useState(!1),[g,x]=T.useState(!1),[w,S]=T.useState(!1),N=T.useRef(Ou()),z=T.useRef(new Set),O=T.useRef(0),H=!!t.directUrl,F=I0&&!H&&!!t.lanUrl&&w,oe=m||g?"disconnected":H?f?"direct":"connecting":l?F?"lan":"nats":"connecting",U=oe!=="connecting"&&oe!=="disconnected";T.useEffect(()=>{y(!1),x(!1)},[t.hostId,t.clientToken]),T.useEffect(()=>{if(!I0||H||!t.lanUrl){S(!1);return}let $=!1;const q=t.lanUrl,M=t.hostId;async function V(){console.log("[HOST/LAN] probing",q);try{const Q=await fetch(`${q}/health`,{signal:AbortSignal.timeout(bE)});if($)return;if(!Q.ok){console.log("[HOST/LAN] probe got non-ok:",Q.status),S(!1);return}const P=await Q.json(),te=P.hostId===M;te?console.log("[HOST/LAN] reachable"):console.log("[HOST/LAN] hostId mismatch — got:",P.hostId,"expected:",M),S(te)}catch(Q){$||(console.log("[HOST/LAN] probe failed:",Q instanceof Error?Q.message:Q),S(!1))}}V();const J=window.setInterval(V,xE),fe=dd.addListener("appStateChange",Q=>{Q.isActive&&V()}),ie=mE.addListener("networkStatusChange",()=>V());return()=>{$=!0,clearInterval(J),fe.then(Q=>Q.remove()),ie.then(Q=>Q.remove())}},[t.hostId,t.lanUrl,H]),T.useEffect(()=>{if(H){c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1));return}let $=!1,q=1e3;const M=3e4;async function V(){for(;!$;)try{const J=await fetch(`${Bu}/api/nats-credentials/${t.hostId}`);if($)return;if(J.status===401||J.status===403||J.status===404){console.error("[NATS] Host not found or rejected by relay:",J.status),x(!0);return}if(!J.ok)throw new Error(`credentials fetch ${J.status}`);const fe=await J.json();if(!fe.natsWsUrl){console.error("[NATS] Relay returned empty natsWsUrl — treating as terminal"),x(!0);return}if($)return;console.log("[NATS] Connecting to",fe.natsWsUrl);const ie=await Dx({servers:fe.natsWsUrl,authenticator:Ex(fe.natsJwt,new TextEncoder().encode(fe.natsNkeySeed)),pingInterval:3e4,maxPingOut:2});if($){ie.close().catch(()=>{});return}if(console.log("[NATS] Connected"),c.current=ie,s(ie),u(!0),q=1e3,await ie.closed(),$)return;console.log("[NATS] Connection closed, will reconnect"),c.current=null,s(null),u(!1)}catch(J){if($)return;console.warn(`[NATS] Connect failed, retrying in ${q}ms:`,J),u(!1),await new Promise(fe=>setTimeout(fe,q)),q=Math.min(q*2,M)}}return V(),()=>{$=!0,c.current&&(c.current.close().catch(()=>{}),c.current=null,s(null),u(!1))}},[H,t]),T.useEffect(()=>{if(H)return;const $=dd.addListener("appStateChange",q=>{if(!q.isActive||!c.current)return;const M=c.current;Promise.race([M.flush(),new Promise((V,J)=>setTimeout(()=>J(new Error("ping timeout")),2e3))]).catch(()=>{console.log("[NATS] Resume probe failed — cycling conn"),M.close().catch(()=>{})})});return()=>{$.then(q=>q.remove())}},[H]),T.useEffect(()=>{if(!H){d(!1);return}const $=new AbortController;async function q(){var fe;const V=new AbortController,J=setTimeout(()=>V.abort(),yE);$.signal.addEventListener("abort",()=>V.abort());try{const ie=await fetch(`${t.directUrl}/events`,{headers:{Authorization:`Bearer ${t.clientToken}`},signal:V.signal});return clearTimeout(J),ie.ok?((fe=ie.body)==null?void 0:fe.getReader())??null:null}catch{return clearTimeout(J),null}}async function M(V){d(!0),console.log("[HOST] SSE connected to",t.directUrl),O.current=Date.now();function J(){setTimeout(()=>{$.signal.aborted||Date.now()-O.current<jh||(console.log("[HOST] Heartbeat timeout — no data for",jh/1e3,"s"),$.abort(),d(!1),console.log("[HOST] Direct host unreachable"))},jh)}J();const fe=new TextDecoder;let ie="";try{for(;;){const{done:Q,value:P}=await V.read();if(Q)break;ie+=fe.decode(P,{stream:!0}),O.current=Date.now(),J();const te=ie.split(`
88
88
  `);ie=te.pop()??"";for(const ue of te)if(ue.startsWith("data: ")){const ve=ue.slice(6);try{const L=JSON.parse(ve);if(L.task_id&&L.event_type){const C=`host-event.${t.hostId}.${L.task_id}`;for(const X of z.current)X({subject:C,data:N.current.encode(ve)})}}catch{}}}}catch{}}return(async()=>{const V=await q();V&&await M(V)})(),()=>{$.abort(),d(!1)}},[t,H]);const D=T.useCallback(async($,q,M)=>{function V(ie){ie&&typeof ie=="object"&&ie.error==="Unauthorized"&&y(!0)}async function J(ie,Q){console.log(`[HOST/${Q}] → ${$}`,q??"");const P=await fetch(`${ie}/rpc/${$}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.clientToken}`},body:q!=null?JSON.stringify(q):void 0,signal:M!=null&&M.timeout?AbortSignal.timeout(M.timeout):void 0});if(P.status===401)throw y(!0),new Error("Unauthorized");const te=await P.json();return V(te),console.log(`[HOST/${Q}] ← ${$}`,te),te}async function fe(){if(!c.current)throw new Error("Not connected");const ie=`host.${t.hostId}.rpc.${$}`,Q={...q??{},clientToken:t.clientToken},P=N.current.encode(JSON.stringify(Q));console.log(`[HOST/NATS] → ${$}`,q??"");const te=await c.current.request(ie,P,{timeout:(M==null?void 0:M.timeout)??1e4}),ue=JSON.parse(N.current.decode(te.data));return V(ue),console.log(`[HOST/NATS] ← ${$}`,ue),ue}if(H)return J(t.directUrl,"HTTP");if(F&&t.lanUrl)try{return await J(t.lanUrl,"LAN")}catch(ie){if(ie instanceof Error&&ie.message==="Unauthorized")throw ie;console.log("[HOST/LAN] failed, falling back to NATS:",ie),S(!1)}return fe()},[t,H,F]),ee=T.useCallback(($,q)=>{if(H)return z.current.add(q),()=>{z.current.delete(q)};if(c.current){const M=c.current.subscribe(`host-event.${$}.>`);let V=!1;return(async()=>{try{for await(const J of M){if(V)break;q({subject:J.subject,data:J.data})}}catch{}})(),()=>{V=!0,M.unsubscribe()}}return()=>{}},[t,H]);return b.jsx(zx.Provider,{value:{connected:U,mode:oe,nc:r,request:D,subscribeEvents:ee,activeHost:t,unauthorized:m},children:e})}function si(){const e=T.useContext(zx);if(!e)throw new Error("useHostConnection must be used within HostConnectionProvider");return e}const dn=Jn.isNativePlatform()?ys("Device"):null;function wE(e,t){const r=new Date(e),s=new Date,l={year:"numeric",month:"2-digit",day:"2-digit",timeZone:t};return r.toLocaleDateString(void 0,l)===s.toLocaleDateString(void 0,l)?new Intl.DateTimeFormat(void 0,{timeStyle:"short",timeZone:t}).format(r):new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short",timeZone:t}).format(r)}function $d(){const{activeHost:e}=si(),t=e.timezone;return T.useCallback(r=>wE(r,t),[t])}function SE(e){const t=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date),r=s=>{var l;return((l=t.find(u=>u.type===s))==null?void 0:l.value)??""};return{date:`${r("year")}-${r("month")}-${r("day")}`,time:`${r("hour")}:${r("minute")}`}}function _E(e){const t=new Intl.DateTimeFormat("en-CA",{timeZone:e,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(new Date),r=s=>{var l;return Number(((l=t.find(u=>u.type===s))==null?void 0:l.value)??"0")};return{year:r("year"),month:r("month"),day:r("day"),hour:r("hour")%24,minute:r("minute")}}function kE(e,t,r){return new Date(Date.UTC(e,t-1,r)).getUTCDay()}function EE(e,t){return new Date(Date.UTC(e,t,0)).getUTCDate()}function F0(e,t){const r=new Date(Date.UTC(e.year,e.month-1,e.day));return r.setUTCDate(r.getUTCDate()+t),{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:e.hour,minute:e.minute}}function Ol(e,t){return e.year!==t.year?e.year-t.year:e.month!==t.month?e.month-t.month:e.day!==t.day?e.day-t.day:e.hour!==t.hour?e.hour-t.hour:e.minute-t.minute}function CE(e,t){const r=Date.UTC(e.year,e.month-1,e.day,e.hour,e.minute);if(!t)return r;const s=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).formatToParts(new Date(r)),l=c=>{var f;return Number(((f=s.find(d=>d.type===c))==null?void 0:f.value)??"0")},u=Date.UTC(l("year"),l("month")-1,l("day"),l("hour")%24,l("minute"),l("second"));return r-(u-r)}function AE(e,t){const r=e.split(" ");if(r.length!==5)return null;const[s,l,u,,c]=r;if(l==="*"){const y=Number(s);if(Number.isNaN(y))return null;if(y>t.minute)return{...t,minute:y};const g=new Date(Date.UTC(t.year,t.month-1,t.day,t.hour+1,y));return{year:g.getUTCFullYear(),month:g.getUTCMonth()+1,day:g.getUTCDate(),hour:g.getUTCHours(),minute:g.getUTCMinutes()}}const f=Number(s),d=Number(l);if(Number.isNaN(f)||Number.isNaN(d))return null;if(c!=="*"){const y=Number(c);if(Number.isNaN(y))return null;for(let g=0;g<8;g++){const x=F0({...t,hour:d,minute:f},g);if(kE(x.year,x.month,x.day)===y&&Ol(x,t)>0)return x}return null}if(u!=="*"){const y=Number(u);if(Number.isNaN(y))return null;let g=t.year,x=t.month;for(let w=0;w<24;w++){if(y<=EE(g,x)){const S={year:g,month:x,day:y,hour:d,minute:f};if(Ol(S,t)>0)return S}x++,x>12&&(x=1,g++)}return null}const m={...t,hour:d,minute:f};return Ol(m,t)>0?m:F0(m,1)}function TE(e){const t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/.exec(e);return t?{year:Number(t[1]),month:Number(t[2]),day:Number(t[3]),hour:Number(t[4]),minute:Number(t[5])}:null}function jE(e,t,r){if(!e||!t||t.length===0||e==="on_new_notification"||e==="on_new_sms")return null;const s=_E(r),l=[];for(const u of t)if(e==="specific_times"){const c=TE(u);c&&Ol(c,s)>0&&l.push(c)}else{const c=AE(u,s);c&&l.push(c)}return l.length===0?null:(l.sort(Ol),CE(l[0],r))}const Ux={};function NE(e){for(const t of e)Ux[t.key]=t.label}function md(e){return Ux[e]??e}const OE=()=>window.matchMedia("(max-width: 600px)").matches;function RE({task:e,lastEvent:t,onEdit:r,onDelete:s,onViewRun:l}){var ie;const{request:u,activeHost:c}=si(),f=$d(),d=c.timezone,[m,y]=T.useState(!1),[g,x]=T.useState(!1),[w,S]=T.useState(!1),N=T.useRef(null),z=(t==null?void 0:t.running_state)==="started",O=(((ie=e.schedule_values)==null?void 0:ie.length)??0)>0,H=e.schedule_type==="on_new_notification"||e.schedule_type==="on_new_sms",oe=!!e.schedule_enabled&&!!e.schedule_type&&(O||H)?z?"var(--color-success)":(t==null?void 0:t.running_state)==="failed"?"var(--color-error)":"var(--color-success)":"var(--color-text-secondary)";T.useEffect(()=>{if(!g)return;function Q(P){N.current&&!N.current.contains(P.target)&&x(!1)}return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[g]);function U(){OE()?S(!0):x(Q=>!Q)}function D(){x(!1),S(!1)}async function ee(){if(D(),!!confirm("Abort this task?")){y(!0);try{await u("task.abort",{id:e.id})}catch(Q){console.error("Abort failed:",Q)}finally{y(!1)}}}async function $(){D();try{const Q=await u("task.run",{id:e.id});l(e.id,Q.run_id)}catch(Q){console.error("Run failed:",Q)}}async function q(){if(D(),!!confirm("Delete this task? Results and reports will be kept."))try{await u("task.delete",{id:e.id}),s(e.id)}catch(Q){console.error("Delete failed:",Q)}}const M={started:"Started",finished:"Finished",aborted:"Aborted",failed:"Failed"};function V(){if(e.schedule_type==="on_new_notification")return"On new notification";if(e.schedule_type==="on_new_sms")return"On new SMS";const Q=jE(e.schedule_type,e.schedule_values,d);return Q===null?"No upcoming runs":`Next: ${f(Q)}`}const J=V(),fe=b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:()=>{D(),r(e)},children:[b.jsx("span",{className:"menu-icon",children:"✎"}),"Edit"]}),b.jsxs("button",{onClick:()=>{D(),l(e.id)},children:[b.jsx("span",{className:"menu-icon",children:"📄"}),"View All Runs"]}),z?b.jsxs("button",{className:"menu-item-danger",onClick:ee,disabled:m,children:[b.jsx("span",{className:"menu-icon",children:"◼"}),"Abort"]}):b.jsxs(b.Fragment,{children:[b.jsxs("button",{onClick:$,children:[b.jsx("span",{className:"menu-icon",children:"▶"}),"Run Now"]}),b.jsxs("button",{className:"menu-item-danger",onClick:q,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:[z?b.jsx("span",{className:"status-spinner",children:b.jsx("span",{})}):b.jsx("span",{className:"status-dot",style:{backgroundColor:oe}}),b.jsx("h3",{className:"task-card-name",children:e.name||e.user_prompt})]}),b.jsx("div",{className:"task-card-actions",onClick:Q=>Q.stopPropagation(),children:b.jsxs("div",{className:"task-card-menu",ref:N,children:[b.jsx("button",{className:"task-card-menu-btn",onClick:U,"aria-label":"Task actions",children:"⋮"}),g&&b.jsx("div",{className:"task-card-menu-dropdown",children:fe})]})})]}),b.jsxs("div",{className:"task-card-meta",children:[e.agent&&b.jsx("span",{className:"task-card-agent",children:md(e.agent)}),t&&M[t.running_state]&&b.jsxs("span",{className:"task-card-last-event",children:[M[t.running_state]," ",f(t.time_stamp)]}),e.schedule_type&&(O||H)&&b.jsx("span",{className:"task-card-triggers",children:e.schedule_enabled?J:"Schedule disabled"})]})]}),w&&ds.createPortal(b.jsx("div",{className:"bottom-sheet-overlay",onClick:()=>S(!1),children:b.jsxs("div",{className:"bottom-sheet",onClick:Q=>Q.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:fe})]})}),document.body)]})}function ME({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 DE(){const e=ra.pop();e&&(e.pushed.current=!1,e.close())}let $0=!1;function LE(){$0||($0=!0,window.addEventListener("popstate",DE))}function pd(e,t){const r=T.useRef(!1),s=T.useRef(t);s.current=t;const l=T.useCallback(()=>s.current(),[]),u=T.useRef({close:l,pushed:r});u.current.close=l,T.useEffect(()=>{if(e&&!r.current)LE(),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]),T.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 zE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],UE=["specific_times","hourly","daily","weekly","monthly"];function pu(e){return UE.includes(e)}function BE(e){return e==="on_new_notification"||e==="on_new_sms"}function ti(e="daily"){return{schedule:e,time:"00:00",dayOfWeek:"1",dayOfMonth:"1",onceDate:"",onceTime:"00:00"}}function PE(e){const t=e.split(" ");if(t.length!==5)return ti();const[r,s,l,,u]=t;if(s==="*")return ti("hourly");const c=`${s.padStart(2,"0")}:${r.padStart(2,"0")}`;return u!=="*"?{...ti("weekly"),time:c,dayOfWeek:u}:l!=="*"?{...ti("monthly"),time:c,dayOfMonth:l}:{...ti("daily"),time:c}}function Bx(e,t){if(e==="specific_times"){const[r,s]=t.split("T");return{...ti("specific_times"),onceDate:r??"",onceTime:(s??"09:00").slice(0,5)}}return PE(t)}function HE(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 qE(e){return e.schedule==="specific_times"?e.onceDate?`${e.onceDate}T${e.onceTime}`:null:HE(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?Bx(t,r).schedule:"ondemand"}function IE({initial:e,agents:t,hostPlatform:r,isNotificationListener:s,onSaved:l,onRun:u,onCancel:c}){var Je;const{request:f,activeHost:d}=si(),{setHostLastAgent:m}=qi(),y=()=>{var Me;const pe=d.lastAgent,Pe=t.map(kt=>kt.key);return pe&&Pe.includes(pe)?pe:((Me=t[0])==null?void 0:Me.key)??""},[g,x]=T.useState((e==null?void 0:e.user_prompt)??""),[w,S]=T.useState((e==null?void 0:e.agent)??y()),N=!!((Je=e==null?void 0:e.permissions)!=null&&Je.length)&&w===(e==null?void 0:e.agent),[z,O]=T.useState(!1),H=T.useCallback(()=>O(!1),[]);pd(z,H);const[F,oe]=T.useState(null),[U,D]=T.useState(()=>Oh(e)),[ee,$]=T.useState(()=>{const pe=e==null?void 0:e.schedule_type,Pe=e==null?void 0:e.schedule_values;if(Pe&&(pe==="crons"||pe==="specific_times"))return Pe.map(kt=>Bx(pe,kt));const Me=Oh(e);return pu(Me)?[ti(Me)]:[]}),[q,M]=T.useState((e==null?void 0:e.requires_confirmation)??!1),[V,J]=T.useState(e!=null&&e.schedule_type?e.schedule_enabled??!0:!0),[fe,ie]=T.useState((e==null?void 0:e.yolo_mode)??!1),[Q,P]=T.useState((e==null?void 0:e.foreground_mode)??!1),[te,ue]=T.useState((e==null?void 0:e.command)??""),[ve,L]=T.useState(!1),C=(e==null?void 0:e.schedule_type)==="on_new_notification"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[X,A]=T.useState(C),[xe,Le]=T.useState([]),[ke,ze]=T.useState(!1),[Ye,Ae]=T.useState(!1),[tt,Pt]=T.useState(""),Gt=T.useCallback(()=>Ae(!1),[]);pd(Ye,Gt),T.useEffect(()=>{if(U!=="on_new_notification"||!s||!Jn.isNativePlatform()||!dn)return;let pe=!1;return ze(!0),dn.getInstalledApps().then(({apps:Pe})=>{if(pe)return;const Me="com.palmier.app",kt=Pe.filter(Dt=>Dt.packageName!==Me).sort((Dt,bn)=>(Dt.appName||Dt.packageName).localeCompare(bn.appName||bn.packageName));Le(kt)}).catch(()=>{}).finally(()=>{pe||ze(!1)}),()=>{pe=!0}},[U,s]);const Be=(e==null?void 0:e.schedule_type)==="on_new_sms"&&e.schedule_values&&e.schedule_values.length>0?e.schedule_values[0]:"",[et,Tt]=T.useState(Be),jt=T.useRef(null),pt=pu(U),Ht=U==="command",gn=BE(U),an=t.find(pe=>pe.key===w),Wt=!!(an!=null&&an.supportsYolo);T.useEffect(()=>{!Wt&&fe&&ie(!1)},[Wt,fe]);const yn=!!e,Kn=Oh(e),dt=!yn||g!==((e==null?void 0:e.user_prompt)??"")||w!==((e==null?void 0:e.agent)??"")||U!==Kn||q!==((e==null?void 0:e.requires_confirmation)??!1)||V!==(e!=null&&e.schedule_type?e.schedule_enabled??!0:!0)||fe!==((e==null?void 0:e.yolo_mode)??!1)||Q!==((e==null?void 0:e.foreground_mode)??!1)||Ht&&te!==((e==null?void 0:e.command)??"")||pt&&(JSON.stringify(Fe())!==JSON.stringify((e==null?void 0:e.schedule_values)??[])||Nh(U)!==((e==null?void 0:e.schedule_type)??void 0))||gn&&U!==(e==null?void 0:e.schedule_type)||U==="on_new_notification"&&X.trim()!==C.trim()||U==="on_new_sms"&&et.trim()!==Be.trim(),Te=SE(d.timezone),Z=pt&&ee.some(pe=>pe.schedule==="specific_times"&&(!pe.onceDate||pe.onceDate<Te.date||pe.onceDate===Te.date&&(pe.onceTime??"")<=Te.time)),he=dt&&!!g.trim()&&!Z&&(!Ht||!!te.trim())&&(!pt||ee.length>0);function Se(pe,Pe){$(Me=>Me.map((kt,Dt)=>Dt===pe?{...kt,...Pe}:kt))}function Ne(pe){$(Pe=>Pe.filter((Me,kt)=>kt!==pe))}function Ie(){pu(U)&&$(pe=>[...pe,pe.length>0?{...pe[pe.length-1]}:ti(U)])}function Ke(pe){D(pe),pu(pe)?$([ti(pe)]):($([]),M(!1)),pe==="command"?setTimeout(()=>{var Pe;return(Pe=jt.current)==null?void 0:Pe.focus()},0):ue(""),pe!=="on_new_notification"&&A(C),pe!=="on_new_sms"&&Tt(Be)}function Fe(){return ee.flatMap(pe=>{const Pe=qE(pe);return Pe?[Pe]:[]})}function Ge(){return fe?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
90
  Are you sure you want to continue?`):!0}async function $e(){L(!0),oe(null);try{const pe=pt?Fe():U==="on_new_notification"&&X.trim()?[X.trim()]:U==="on_new_sms"&&et.trim()?[et.trim()]:[],Pe=pt||gn?Nh(U):null,Me={user_prompt:g,agent:w,schedule_type:Pe,schedule_values:pe.length>0?pe:null,schedule_enabled:U==="ondemand"?!0:V,requires_confirmation:pt?q:!1,yolo_mode:fe,foreground_mode:Q,command:Ht?te:""};yn&&(Me.id=e.id);const Dt=await f(yn?"task.update":"task.create",Me,{timeout:45e3});if(Dt.error){oe(Dt.error);return}if(yn||m(d.hostId,w),Ht&&!yn){l(Dt);try{const bn=await f("task.run",{id:Dt.id});bn.run_id?u(Dt.id,bn.run_id):bn.error||u(Dt.id)}catch{}return}l(Dt)}catch(pe){oe(pe instanceof Error?pe.message:String(pe))}finally{L(!1)}}const Qe=yn?"Save":Ht?"Run":(pt||gn)&&V?"Schedule":"Save";return b.jsxs("div",{className:"task-form-overlay",children:[b.jsx("div",{className:"task-form",children:z?b.jsx(ME,{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:pe=>x(pe.target.value),placeholder:Ht?"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:ve}),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:pe=>S(pe.target.value),disabled:ve,children:t.map(pe=>b.jsx("option",{value:pe.key,children:pe.label},pe.key))})]}),Wt&&b.jsxs("label",{className:"yolo-inline",style:{marginLeft:"auto"},children:[b.jsx("input",{type:"checkbox",checked:fe,onChange:pe=>ie(pe.target.checked),disabled:ve}),"Yolo"]}),Wt&&fe&&b.jsx("p",{className:"yolo-warning",children:"The agent will auto-approve all tool calls without asking for permission."}),N&&b.jsx("div",{className:"granted-permissions-row",children:b.jsx("button",{className:"btn btn-link",onClick:()=>O(!0),children:"Granted Permissions"})})]}),b.jsx("div",{className:"toggles-group",children:b.jsxs("div",{className:"schedule-section",children:[b.jsxs("h3",{className:"schedule-section-title",children:["Schedule ",b.jsx("span",{className:"schedule-section-hint",children:"based on host time"})]}),b.jsxs("select",{className:"form-select",value:U,onChange:pe=>Ke(pe.target.value),disabled:ve,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"})]}),gn&&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 pe=xe.find(Me=>Me.packageName===X),Pe=(pe==null?void 0:pe.appName)||X;return b.jsxs(b.Fragment,{children:[s?X.trim()?b.jsxs("div",{className:"app-filter-selected",children:[b.jsx("span",{className:"app-filter-selected-name",children:Pe}),(pe==null?void 0:pe.appName)&&b.jsx("span",{className:"app-filter-selected-pkg",children:pe.packageName}),b.jsx("button",{type:"button",className:"app-filter-selected-clear",onClick:()=>A(""),"aria-label":"Clear app filter",disabled:ve,children:"✕"})]}):b.jsx("button",{type:"button",className:"btn btn-link app-filter-trigger",onClick:()=>{Pt(""),Ae(!0)},disabled:ve,children:"Select app"}):b.jsx("input",{className:"form-input",type:"text",value:X,onChange:Me=>A(Me.target.value),placeholder:"App (optional), e.g. com.google.android.gm",disabled:ve}),b.jsx("p",{className:"command-help-text app-filter-help",children:X.trim()?`Only notifications from ${Pe} 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:et,onChange:pe=>Tt(pe.target.value),placeholder:"From (optional), e.g. +1 555-1234)",disabled:ve}),b.jsx("p",{className:"command-help-text app-filter-help",children:et.trim()?`Only SMS from ${et.trim()} will trigger this task. Formatting (spaces, dashes, parens) is ignored.`:"Every SMS that arrives on your device triggers this task."})]})]}),Ht&&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:jt,className:"form-input form-input-mono",type:"text",value:te,onChange:pe=>ue(pe.target.value),placeholder:"gws gmail +watch --project my-project",disabled:ve})]}),pt&&U!=="hourly"&&b.jsxs(b.Fragment,{children:[ee.map((pe,Pe)=>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:pe.time,onChange:Me=>Se(Pe,{time:Me.target.value})}),U==="weekly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:pe.dayOfWeek,onChange:Me=>Se(Pe,{dayOfWeek:Me.target.value}),children:zE.map((Me,kt)=>b.jsx("option",{value:String(kt),children:Me},kt))}),b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Me=>Se(Pe,{time:Me.target.value})})]}),U==="monthly"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("select",{className:"form-select",value:pe.dayOfMonth,onChange:Me=>Se(Pe,{dayOfMonth:Me.target.value}),children:Array.from({length:28},(Me,kt)=>kt+1).map(Me=>b.jsxs("option",{value:String(Me),children:["Day ",Me]},Me))}),b.jsx("input",{className:"form-input",type:"time",value:pe.time,onChange:Me=>Se(Pe,{time:Me.target.value})})]}),U==="specific_times"&&b.jsxs("div",{className:"trigger-row-top",children:[b.jsx("input",{className:"form-input",type:"date",value:pe.onceDate,min:Te.date,onChange:Me=>Se(Pe,{onceDate:Me.target.value})}),b.jsx("input",{className:"form-input",type:"time",value:pe.onceTime,min:pe.onceDate===Te.date?Te.time:void 0,onChange:Me=>Se(Pe,{onceTime:Me.target.value})})]})]}),ee.length>1&&b.jsx("button",{className:"trigger-remove-btn",onClick:()=>Ne(Pe),title:"Remove trigger",children:"×"})]},Pe)),b.jsx("button",{className:"trigger-add-btn",onClick:Ie,children:"+ Add"})]}),r==="win32"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:Q,onChange:pe=>P(pe.target.checked),disabled:ve}),"Run in the foreground (host must login to Windows)"]}),pt&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:q,onChange:pe=>M(pe.target.checked),disabled:ve}),"Confirm before each run"]}),U!=="ondemand"&&b.jsxs("label",{className:"toggle-label",children:[b.jsx("input",{type:"checkbox",checked:V,onChange:pe=>J(pe.target.checked),disabled:ve}),"Enabled"]})]})}),!fe&&an&&!an.supportsPermissions&&b.jsxs("div",{className:"form-warning",children:["Palmier does not support runtime permission granting for ",an.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:()=>Ge()&&$e(),disabled:!he||ve,children:[ve&&b.jsx("span",{className:"btn-spinner"}),Qe]}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{dt&&g.trim()&&!confirm("You have unsaved changes. Discard?")||c()},style:{marginLeft:"auto"},children:"Cancel"})]})]})}),Ye&&(()=>{const pe=tt.trim().toLowerCase(),Pe=pe?xe.filter(Me=>Me.packageName.toLowerCase().includes(pe)||Me.appName.toLowerCase().includes(pe)):xe;return b.jsx("div",{className:"app-filter-overlay",onClick:Gt,children:b.jsxs("div",{className:"app-filter-dialog",onClick:Me=>Me.stopPropagation(),children:[b.jsxs("div",{className:"app-filter-header",children:[b.jsx("h2",{children:"Select app"}),b.jsx("button",{className:"app-filter-close",onClick:Gt,"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:tt,onChange:Me=>Pt(Me.target.value),onKeyDown:Me=>{Me.key==="Enter"&&tt.trim()&&(A(tt.trim()),Gt())},placeholder:"Search or type a package name",autoFocus:!0}),b.jsxs("ul",{className:"app-filter-list",children:[ke&&xe.length===0?Array.from({length:6}).map((Me,kt)=>b.jsx("li",{className:"app-filter-row app-filter-skeleton",children:b.jsx("div",{className:"app-filter-skeleton-bar"})},`sk-${kt}`)):Pe.length===0&&!tt.trim()?b.jsx("li",{className:"app-filter-empty",children:"No apps"}):Pe.map(Me=>b.jsx("li",{className:"app-filter-row",onClick:()=>{A(Me.packageName),Gt()},children:b.jsxs("div",{className:"app-filter-row-labels",children:[b.jsx("div",{className:"app-filter-row-name",children:Me.appName||Me.packageName}),Me.appName&&b.jsx("div",{className:"app-filter-row-pkg",children:Me.packageName})]})},Me.packageName)),tt.trim()&&b.jsx("li",{className:"app-filter-row",onClick:()=>{A(tt.trim()),Gt()},children:b.jsx("div",{className:"app-filter-row-labels",children:b.jsx("div",{className:"app-filter-row-name",children:tt.trim()})})})]})]})})})()]})}function Px({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 Hx({onRefresh:e,threshold:t=70,maxPull:r=110,enabled:s=!0}){const[l,u]=T.useState(0),[c,f]=T.useState(!1),d=T.useRef(null),m=T.useRef(!1),y=T.useRef(0),g=T.useRef(!1),x=T.useRef(e);return T.useEffect(()=>{x.current=e}),T.useEffect(()=>{if(!s)return;const w=z=>{if(g.current||window.scrollY>0){d.current=null;return}if(FE(z.target)){d.current=null;return}d.current=z.touches[0].clientY,m.current=!1,y.current=0},S=z=>{if(g.current||d.current==null)return;const O=z.touches[0].clientY-d.current;if(O<=0){m.current=!1,y.current=0,u(0);return}m.current=!0;const H=Math.min(r,O*.5);y.current=H,u(H),z.cancelable&&z.preventDefault()},N=()=>{if(!m.current){d.current=null,u(0);return}const z=y.current;d.current=null,m.current=!1,y.current=0,z>=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",N,{passive:!0}),window.addEventListener("touchcancel",N,{passive:!0}),()=>{window.removeEventListener("touchstart",w),window.removeEventListener("touchmove",S),window.removeEventListener("touchend",N),window.removeEventListener("touchcancel",N)}},[s,t,r]),{pullDistance:l,refreshing:c,threshold:t}}function FE(e){let t=e;for(;t&&t!==document.body&&t!==document.documentElement;){const r=window.getComputedStyle(t).overflowY;if((r==="auto"||r==="scroll")&&t.scrollHeight>t.clientHeight)return!0;t=t.parentElement}return!1}function $E({connected:e,hostId:t,request:r,subscribeEvents:s,agents:l,hostPlatform:u,isNotificationListener:c,onViewRun:f}){const[d,m]=T.useState([]),[y,g]=T.useState(!1),[x,w]=T.useState(null),[S,N]=T.useState(new Map),[z,O]=T.useState(!1),[H,F]=T.useState(void 0),oe=T.useCallback(()=>{O(!1),F(void 0)},[]),U=T.useCallback(async()=>{if(e){g(!0),w(null);try{const M=(await r("task.list")).tasks??[],V=new Map;for(const J of M)J.status&&V.set(J.id,J.status);N(V),m(M)}catch(q){const M=q instanceof Error?q.message:String(q);M==="Not connected"||M.includes("503")||M.toLowerCase().includes("no responders")?w(null):w(M),m([])}finally{g(!1)}}},[e,t,r]);T.useEffect(()=>{e?U():(m([]),g(!1))},[e,t,U]);const D=Hx({onRefresh:U,enabled:e});T.useEffect(()=>!e||!t?void 0:s(t,async M=>{const V=M.subject.split(".");if(V.length<3)return;const J=V.slice(2).join(".");let fe={};try{fe=JSON.parse(new TextDecoder().decode(M.data))}catch{return}const ie=fe.event_type;if(!(ie!=="running-state"&&ie!=="permission-resolved"))try{const Q=await r("task.status",{id:J},{timeout:5e3});if(Q.error)return;N(P=>{const te=new Map(P);return te.set(J,Q),te})}catch{}}),[e,t,s,r]);function ee(q){m(M=>{const V=M.findIndex(J=>J.id===q.id);if(V>=0){const J=[...M];return J[V]=q,J}return[q,...M]}),O(!1),F(void 0)}function $(q){m(M=>M.filter(V=>V.id!==q)),N(M=>{const V=new Map(M);return V.delete(q),V})}return b.jsxs(b.Fragment,{children:[b.jsx(Px,{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(RE,{task:q,lastEvent:S.get(q.id),onEdit:async M=>{try{const V=await r("task.get",{id:M.id});F(V.error?M:V)}catch{F(M)}O(!0)},onDelete:$,onViewRun:f},q.id))}),b.jsx("button",{className:"fab",onClick:()=>{F(void 0),O(!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"})]})}),z&&b.jsx(IE,{initial:H,agents:l,hostPlatform:u,isNotificationListener:c,onSaved:ee,onRun:f,onCancel:oe})]})}let ha=null;function Y0(e){ha&&(e.preventDefault(),e.returnValue="")}function Rh(e){const t=!!ha;ha=e;const r=!!ha;r&&!t?window.addEventListener("beforeunload",Y0):!r&&t&&window.removeEventListener("beforeunload",Y0)}function ps(){return ha?window.confirm(ha):!0}function YE(){const e=Mr(),t=cr(),{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 qx(e){const[t,r]=T.useState(()=>window.matchMedia(e).matches);return T.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 Eu=Jn.isNativePlatform(),VE=["Device","Data","Messaging"],GE=[{capability:"sms-read",label:"Read SMS",group:"Messaging"},{capability:"sms-send",label:"Send SMS",group:"Messaging"},{capability:"send-email",label:"Prompt Email to Send",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 JE(){if(!Eu||!dn)return new Set;try{const{capabilities:e}=await dn.getCapabilityStatus();return new Set(e.filter(t=>t.enabled).map(t=>t.name))}catch{return new Set}}function Ix({onChange:e,confirmDisable:t=!1}){const[r,s]=T.useState(new Map),[l,u]=T.useState(null),[c,f]=T.useState(null),d=T.useCallback(async()=>{if(!(!Eu||!dn))try{const{capabilities:S}=await dn.getCapabilityStatus(),N=new Map;for(const z of S)N.set(z.name,z);s(N),e==null||e(new Set(S.filter(z=>z.enabled).map(z=>z.name)))}catch(S){console.error("Failed to read capability status:",S)}},[e]);T.useEffect(()=>{d()},[d]),T.useEffect(()=>{if(!Eu)return;const S=dd.addListener("resume",d);return()=>{S.then(N=>N.remove())}},[d]);async function m(S,N){if(dn){u(S.capability);try{const z=await dn.setCapabilityEnabled({capability:S.capability,enabled:N});!z.enabled&&z.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(z){console.error(`Failed to toggle ${S.capability}:`,z)}finally{u(null)}}}function y(S){const N=r.get(S.capability);if(N){if(N.enabled&&t){f(S);return}m(S,!N.enabled)}}function g(){const S=c;S&&(f(null),m(S,!1))}if(!Eu)return null;const x=VE.map(S=>({group:S,items:GE.filter(N=>{const z=r.get(N.capability);return N.group===S&&(z==null?void 0:z.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:N},z)=>b.jsx("div",{className:z>0?"drawer-toggle-group drawer-toggle-group-divided":"drawer-toggle-group",children:N.map(O=>{const H=r.get(O.capability),F=!!(H!=null&&H.enabled);return b.jsxs("label",{className:"drawer-toggle",children:[b.jsx("span",{className:"drawer-toggle-label",children:O.label}),b.jsx("button",{className:`toggle-switch ${F?"toggle-switch-on":""}`,onClick:()=>y(O),disabled:l===O.capability,role:"switch","aria-checked":F,children:b.jsx("span",{className:"toggle-switch-thumb"})})]},O.capability)})},S)),w]})}const V0=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),XE=Jn.isNativePlatform();function G0({daemonVersion:e,linkedClientToken:t,request:r,onEnabledCapabilitiesChange:s,onLinkedClientTokenChange:l}){var Gt;const{pairedHosts:u,removePairedHost:c,renamePairedHost:f}=qi(),{activeHost:d}=si(),m=Mr(),y=cr(),x=Yu().hostId??null,w=d.clientToken||null,S=!!w&&t===w,N=qx("(min-width: 768px)"),[z,O]=T.useState(!1),[H,F]=T.useState(()=>Date.now());T.useEffect(()=>{const Be=()=>F(Date.now()),et=6e4-Date.now()%6e4,Tt=setTimeout(()=>{Be();const jt=setInterval(Be,6e4);Tt._iv=jt},et);return()=>{const jt=Tt._iv;jt&&clearInterval(jt),clearTimeout(Tt)}},[]);const oe=d.timezone?new Date(H).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:d.timezone}):"";async function U(){if(!(!dn||!r||!w)){O(!0);try{const{token:Be}=await dn.getFcmToken();if(!Be)return;await r("device.link",{fcmToken:Be}),l==null||l(w)}catch(Be){console.error("Failed to make this the linked device:",Be)}finally{O(!1)}}}async function D(Be){const et=Be===x;if(et&&r)try{await r("clients.revoke_self")}catch{}c(Be),te(null),et&&m("/",{replace:!0})}function ee(Be){const Tt=y.pathname.endsWith("/tasks")?"/tasks":"";m(`/hosts/${encodeURIComponent(Be)}${Tt}`)}const[$,q]=T.useState(!1),[M,V]=T.useState(!1),[J,fe]=T.useState(null),[ie,Q]=T.useState(""),[P,te]=T.useState(null),[ue,ve]=T.useState(!1),L=T.useRef(null),C=T.useRef(null),X=T.useCallback(()=>{V(!0)},[]);function A(){M&&(q(!1),V(!1))}function xe(){V(!1),q(!0)}function Le(Be,et){fe(Be),Q(et)}function ke(){J&&ie.trim()&&f(J,ie.trim()),fe(null),Q("")}function ze(){fe(null),Q("")}T.useEffect(()=>{J&&C.current&&(C.current.focus(),C.current.select())},[J]),T.useEffect(()=>{if(!$||M)return;function Be(et){et.key==="Escape"&&X()}return document.addEventListener("keydown",Be),()=>{document.removeEventListener("keydown",Be)}},[$,M,X]);const Ye=b.jsxs(b.Fragment,{children:[!N&&b.jsx("button",{className:"drawer-close-btn",onClick:X,"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"})})}),!V0&&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(Be=>{const et=Be.hostId===x,Tt=J===Be.hostId,jt=Be.name||Be.hostId.slice(0,8);return b.jsx("div",{className:"host-picker-item-wrapper",children:b.jsxs("div",{className:`host-picker-item ${et?"host-picker-item-active":""}`,onClick:()=>{if(!Tt&&!et){if(!ps())return;ee(Be.hostId),N||X()}},role:"option","aria-selected":et,children:[Tt?b.jsx("input",{ref:C,className:"form-input host-picker-rename-input",type:"text",value:ie,onChange:pt=>Q(pt.target.value),onKeyDown:pt=>{pt.key==="Enter"&&ke(),pt.key==="Escape"&&ze()},onBlur:ke,onClick:pt=>pt.stopPropagation()}):b.jsx("span",{className:"host-picker-item-name",children:jt}),b.jsxs("div",{className:"host-picker-item-actions",children:[et&&!Tt&&b.jsx("button",{className:"host-picker-edit-btn",onClick:pt=>{pt.stopPropagation(),Le(Be.hostId,jt)},"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"})})}),!et&&b.jsx("button",{className:"host-picker-delete-btn",onClick:pt=>{pt.stopPropagation(),te(Be.hostId)},"aria-label":`Unpair ${jt}`,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"})})})]})]})},Be.hostId)})})})]}),!V0&&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"),N||X())},children:"Add New Host"})})]}),XE&&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(Ix,{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?ve(!0):U()},disabled:z,children:z?"Linking…":"Link the host to this device"})]})]})]}),b.jsxs("div",{className:"drawer-footer",children:[d.timezone&&b.jsxs("div",{className:"drawer-host-time",children:["Host time: ",oe," · ",d.timezone]}),e&&b.jsxs("div",{className:"drawer-version",children:["Host version: 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"})]})]})]}),Ae=!!P&&P===x&&S,tt=P&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>te(null),children:b.jsxs("div",{className:"confirm-modal",onClick:Be=>Be.stopPropagation(),children:[b.jsx("h2",{className:"confirm-modal-title",children:"Remove host?"}),b.jsxs("p",{className:"confirm-modal-message",children:['"',((Gt=u.find(Be=>Be.hostId===P))==null?void 0:Gt.name)||P.slice(0,8),'" will be ',Ae?"removed and unlinked":"removed",".",Ae&&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:()=>te(null),children:"Cancel"}),b.jsx("button",{className:"btn btn-danger",onClick:()=>D(P),children:"Remove"})]})]})}),document.body),Pt=ue&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:()=>ve(!1),children:b.jsxs("div",{className:"confirm-modal",onClick:Be=>Be.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:()=>ve(!1),children:"Cancel"}),b.jsx("button",{className:"btn btn-primary",onClick:()=>{ve(!1),U()},children:"Link"})]})]})}),document.body);return N?b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"drawer-panel drawer-panel-desktop",ref:L,children:Ye}),tt,Pt]}):b.jsxs(b.Fragment,{children:[b.jsx("button",{className:"hamburger-btn",onClick:xe,"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"})})}),$&&ds.createPortal(b.jsx("div",{className:`drawer-overlay ${M?"drawer-overlay-closing":""}`,onClick:X,onAnimationEnd:A,children:b.jsx("div",{className:`drawer-panel ${M?"drawer-panel-closing":""}`,ref:L,onClick:Be=>Be.stopPropagation(),children:Ye})}),document.body),tt,Pt]})}const KE=Jn.isNativePlatform(),Yd={width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};function QE(){return b.jsxs("svg",{...Yd,"aria-hidden":"true",children:[b.jsx("path",{d:"M3 11 L12 3 L21 11"}),b.jsx("path",{d:"M5 9.5 V21 H19 V9.5"})]})}function J0(){return b.jsxs("svg",{...Yd,"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 ZE(){return b.jsxs("svg",{...Yd,"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 WE(){const{mode:e}=si(),[t,r]=T.useState(!1),s=T.useRef(null);if(T.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(QE,{}),u="Connected via LAN",c="lan";break;case"nats":l=b.jsx(J0,{}),u=KE?"Connected via relay":"Connected",c="relay";break;case"disconnected":l=b.jsx(ZE,{}),u="Disconnected",c="disconnected";break;case"connecting":default:l=b.jsx(J0,{}),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 X0(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 eC({agents:e,hostPlatform:t,onStarted:r}){const{request:s,activeHost:l}=si(),{setHostLastAgent:u}=qi(),[c,f]=T.useState(""),[d,m]=T.useState(()=>X0(e,l.lastAgent)),[y,g]=T.useState(!1),[x,w]=T.useState(!1),[S,N]=T.useState(null);T.useEffect(()=>{e.length&&(e.find(D=>D.key===d)||m(X0(e,l.lastAgent)))},[e,d,l.lastAgent]),T.useEffect(()=>{const D=c.trim().length>0;return Rh(D?"Your session draft will be lost. Continue?":null),()=>Rh(null)},[c]);const z=e.find(D=>D.key===d),O=!!(z!=null&&z.supportsYolo);T.useEffect(()=>{!O&&y&&g(!1)},[O,y]);const H=!!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.
@@ -117,4 +117,4 @@ Are you sure you want to continue?`):!0}async function oe(){if(!(!H||!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=Il(m.charCodeAt(0))+m.slice(1)),m=m?c+" "+m:c,r.options.closeAtx&&(m+=" "+c),d(),f(),m}N1.peek=m3;function N1(e){return e.value||""}function m3(){return"<"}O1.peek=p3;function O1(e,t,r,s){const l=lm(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 p3(){return"!"}R1.peek=g3;function R1(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 g3(){return"!"}M1.peek=y3;function M1(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 y3(){return"`"}function D1(e,t){const r=Zd(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))}L1.peek=b3;function L1(e,t,r,s){const l=lm(r),u=l==='"'?"Quote":"Apostrophe",c=r.createTracker(s);let f,d;if(D1(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 b3(e,t,r){return D1(e,r)?"<":"["}z1.peek=x3;function z1(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 x3(){return"["}function om(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 v3(e){const t=om(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 w3(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 U1(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 S3(e,t,r,s){const l=r.enter("list"),u=r.bulletCurrent;let c=e.ordered?w3(r):om(r);const f=e.ordered?c==="."?")":".":v3(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),U1(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 _3(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 k3(e,t,r,s){const l=_3(r);let u=r.bulletCurrent||om(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 E3(e,t,r,s){const l=r.enter("paragraph"),u=r.enter("phrasing"),c=r.containerPhrasing(e,s);return u(),l(),c}const C3=tc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function A3(e,t,r,s){return(e.children.some(function(c){return C3(c)})?r.containerPhrasing:r.containerFlow).call(r,e,s)}function T3(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}B1.peek=j3;function B1(e,t,r,s){const l=T3(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=Il(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)+Il(g));const w=c.move(l+l);return u(),r.attentionEncodeSurroundingInfo={after:x.outside,before:y.outside},f+d+w}function j3(e,t,r){return r.options.strong||"*"}function N3(e,t,r,s){return r.safe(e.value,s)}function O3(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 R3(e,t,r){const s=(U1(r)+(r.options.ruleSpaces?" ":"")).repeat(O3(r));return r.options.ruleSpaces?s.slice(0,-1):s}const P1={blockquote:t3,break:Ub,code:l3,definition:u3,emphasis:j1,hardBreak:Ub,heading:d3,html:N1,image:O1,imageReference:R1,inlineCode:M1,link:L1,linkReference:z1,list:S3,listItem:k3,paragraph:E3,root:A3,strong:B1,text:N3,thematicBreak:R3};function M3(){return{enter:{table:D3,tableData:Bb,tableHeader:Bb,tableRow:z3},exit:{codeText:U3,table:L3,tableData:Xh,tableHeader:Xh,tableRow:Xh}}}function D3(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 L3(e){this.exit(e),this.data.inTable=void 0}function z3(e){this.enter({type:"tableRow",children:[]},e)}function Xh(e){this.exit(e)}function Bb(e){this.enter({type:"tableCell",children:[]},e)}function U3(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,B3));const r=this.stack[this.stack.length-1];r.type,r.value=t,this.exit(e)}function B3(e,t){return t==="|"?t:e}function P3(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,N,z){return m(y(w,N,z),w.align)}function f(w,S,N,z){const O=g(w,N,z),H=m([O]);return H.slice(0,H.indexOf(`
120
- `))}function d(w,S,N,z){const O=N.enter("tableCell"),H=N.enter("phrasing"),F=N.containerPhrasing(w,{...z,before:u,after:u});return H(),O(),F}function m(w,S){return WN(w,{align:S,alignDelimiters:s,padding:r,stringLength:l})}function y(w,S,N){const z=w.children;let O=-1;const H=[],F=S.enter("table");for(;++O<z.length;)H[O]=g(z[O],S,N);return F(),H}function g(w,S,N){const z=w.children;let O=-1;const H=[],F=S.enter("tableRow");for(;++O<z.length;)H[O]=d(z[O],w,S,N);return F(),H}function x(w,S,N){let z=P1.inlineCode(w,S,N);return N.stack.includes("tableCell")&&(z=z.replace(/\|/g,"\\$&")),z}}function H3(){return{exit:{taskListCheckValueChecked:Pb,taskListCheckValueUnchecked:Pb,paragraph:I3}}}function q3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:F3}}}function Pb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function I3(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 F3(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=P1.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 $3(){return[SN(),FN(),GN(),M3(),H3()]}function Y3(e){return{extensions:[_N(),$N(e),JN(),P3(e),q3()]}}const V3={tokenize:Z3,partial:!0},H1={tokenize:W3,partial:!0},q1={tokenize:eO,partial:!0},I1={tokenize:tO,partial:!0},G3={tokenize:nO,partial:!0},F1={name:"wwwAutolink",tokenize:K3,previous:Y1},$1={name:"protocolAutolink",tokenize:Q3,previous:V1},ai={name:"emailAutolink",tokenize:X3,previous:G1},Dr={};function J3(){return{text:Dr}}let hs=48;for(;hs<123;)Dr[hs]=ai,hs++,hs===58?hs=65:hs===91&&(hs=97);Dr[43]=ai;Dr[45]=ai;Dr[46]=ai;Dr[95]=ai;Dr[72]=[ai,$1];Dr[104]=[ai,$1];Dr[87]=[ai,F1];Dr[119]=[ai,F1];function X3(e,t,r){const s=this;let l,u;return c;function c(g){return!Cd(g)||!G1.call(s,s.previous)||um(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return Cd(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(G3,y,m)(g):g===45||g===95||mn(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&&_n(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function K3(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!Y1.call(s,s.previous)||um(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(V3,e.attempt(H1,e.attempt(q1,u),r),r)(c))}function u(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function Q3(e,t,r){const s=this;let l="",u=!1;return c;function c(g){return(g===72||g===104)&&V1.call(s,s.previous)&&!um(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(_n(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)||At(g)||gs(g)||Zu(g)?r(g):e.attempt(H1,e.attempt(q1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function Z3(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 W3(e,t,r){let s,l,u;return c;function c(m){return m===46||m===95?e.check(I1,d,f)(m):m===null||At(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 eO(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(I1,t,u)(c):c===null||At(c)||gs(c)?t(c):(e.consume(c),l)}function u(c){return c===41&&s++,e.consume(c),l}}function tO(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||At(f)||gs(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||At(f)||gs(f)?t(f):s(f)}function u(f){return _n(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):_n(f)?(e.consume(f),c):r(f)}}function nO(e,t,r){return s;function s(u){return e.consume(u),l}function l(u){return mn(u)?r(u):t(u)}}function Y1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||At(e)}function V1(e){return!_n(e)}function G1(e){return!(e===47||Cd(e))}function Cd(e){return e===43||e===45||e===46||e===95||mn(e)}function um(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 rO={tokenize:fO,partial:!0};function iO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:oO,continuation:{tokenize:uO},exit:cO}},text:{91:{name:"gfmFootnoteCall",tokenize:lO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:sO,resolveTo:aO}}}}function sO(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=wr(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 aO(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 lO(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||At(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(wr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return At(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 oO(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||At(S))return r(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return u=wr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return At(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),ut(e,w,"gfmFootnoteDefinitionWhitespace")):r(S)}function w(S){return t(S)}}function uO(e,t,r){return e.check(Jl,t,e.attempt(rO,t,r))}function cO(e){e.exit("gfmFootnoteDefinition")}function fO(e,t,r){const s=this;return ut(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 hO(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&&Vn(x,x.length,0,Wu(w,c.slice(m+1,d),f)),Vn(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),Vn(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 N=ba(m);if(S===126)return g>1?d(S):(c.consume(S),g++,w);if(g<2&&!r)return d(S);const z=c.exit("strikethroughSequenceTemporary"),O=ba(S);return z._open=!O||O===2&&!!N,z._close=!N||N===2&&!!O,f(S)}}}class dO{constructor(){this.map=[]}add(t,r,s){mO(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 mO(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 pO(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 gO(){return{flow:{null:{name:"table",tokenize:yO,resolveAll:bO}}}}function yO(e,t,r){const s=this;let l=0,u=0,c;return f;function f(M){let V=s.events.length-1;for(;V>-1;){const ie=s.events[V][1].type;if(ie==="lineEnding"||ie==="linePrefix")V--;else break}const J=V>-1?s.events[V][1].type:null,fe=J==="tableHead"||J==="tableRow"?D:d;return fe===D&&s.parser.lazy[s.now().line]?r(M):fe(M)}function d(M){return e.enter("tableHead"),e.enter("tableRow"),m(M)}function m(M){return M===124||(c=!0,u+=1),y(M)}function y(M){return M===null?r(M):He(M)?u>1?(u=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),w):r(M):st(M)?ut(e,y,"whitespace")(M):(u+=1,c&&(c=!1,l+=1),M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(M)))}function g(M){return M===null||M===124||At(M)?(e.exit("data"),y(M)):(e.consume(M),M===92?x:g)}function x(M){return M===92||M===124?(e.consume(M),g):g(M)}function w(M){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(M):(e.enter("tableDelimiterRow"),c=!1,st(M)?ut(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):S(M))}function S(M){return M===45||M===58?z(M):M===124?(c=!0,e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),N):U(M)}function N(M){return st(M)?ut(e,z,"whitespace")(M):z(M)}function z(M){return M===58?(u+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),O):M===45?(u+=1,O(M)):M===null||He(M)?oe(M):U(M)}function O(M){return M===45?(e.enter("tableDelimiterFiller"),H(M)):U(M)}function H(M){return M===45?(e.consume(M),H):M===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(M))}function F(M){return st(M)?ut(e,oe,"whitespace")(M):oe(M)}function oe(M){return M===124?S(M):M===null||He(M)?!c||l!==u?U(M):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(M)):U(M)}function U(M){return r(M)}function D(M){return e.enter("tableRow"),ee(M)}function ee(M){return M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),ee):M===null||He(M)?(e.exit("tableRow"),t(M)):st(M)?ut(e,ee,"whitespace")(M):(e.enter("data"),$(M))}function $(M){return M===null||M===124||At(M)?(e.exit("data"),ee(M)):(e.consume(M),M===92?q:$)}function q(M){return M===92||M===124?(e.consume(M),$):$(M)}}function bO(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 dO;for(;++r<e.length;){const w=e[r],S=w[1];w[0]==="enter"?S.type==="tableHead"?(f=!1,d!==0&&(Hb(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=xu(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=xu(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=xu(x,t,u,l,r,g)):c[1]!==0&&(g=xu(x,t,c,l,r,g)),l=0):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Hb(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=pO(t.events,r))}return e}function xu(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,N=r[3]-r[2]-1;e.add(S,N,[])}}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 Hb(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 xO={name:"tasklistCheck",tokenize:wO};function vO(){return{text:{91:xO}}}function wO(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 At(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 He(d)?t(d):st(d)?e.check({tokenize:SO},t,r)(d):r(d)}}function SO(e,t,r){return ut(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function _O(e){return r1([J3(),iO(),hO(e),gO(),vO()])}const kO={};function qb(e){const t=this,r=e||kO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),u=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(_O(r)),u.push($3()),c.push(Y3(r))}function EO(e){k1(e,[/\r?\n|\r/g,CO])}function CO(){return{type:"break"}}function Ib(){return function(e){EO(e)}}function AO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:u}){const c=Mr(),f=$d(),[d,m]=T.useState(!0),[y,g]=T.useState([]),[x,w]=T.useState(),[S,N]=T.useState(),z=x==="started"||x==="monitoring",O=x==="followup",H=x==="started"||x==="followup",[F,oe]=T.useState(null);pd(F!==null,()=>oe(null));const[U,D]=T.useState(!1),[ee,$]=T.useState(""),[q,M]=T.useState(!1),V=T.useRef(null),J=T.useRef(null),fe=T.useRef(null),[ie,Q]=T.useState(u==="latest"?void 0:u),P=u==="latest"&&ie===null;T.useEffect(()=>{if(u!=="latest"){Q(u);return}e&&(Q(void 0),r("taskrun.list",{task_id:l,limit:1}).then(C=>{var X,A;return Q(((A=(X=C.entries)==null?void 0:X[0])==null?void 0:A.run_id)??null)}).catch(()=>Q(null)))},[u,l,e,r]);async function te(){if(ie)try{const C=await r("task.result",{id:l,run_id:ie});if(C.error){console.error("No result:",C.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}g(C.messages??[]),w(C.running_state),N(C.agent)}catch(C){console.error("Failed to load result:",C),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{m(!1)}}async function ue(C){var X;if(ie)try{const xe=(X=(await r("task.reports",{id:l,run_id:ie,report_files:[C]})).reports)==null?void 0:X[0];xe!=null&&xe.data_url?oe({file:C,data_url:xe.data_url}):oe({file:C,content:(xe==null?void 0:xe.content)??"Report not found."})}catch{oe({file:C,content:"Failed to load report."})}}T.useEffect(()=>{!e||!ie||(m(!0),te())},[e,l,ie]),T.useEffect(()=>!e||!t||!ie?void 0:s(t,async X=>{try{const A=JSON.parse(new TextDecoder().decode(X.data));if(A.event_type!=="running-state"&&A.event_type!=="result-updated"||X.subject.split(".").pop()!==l||A.event_type==="result-updated"&&A.run_id&&A.run_id!==ie)return;te()}catch{}}),[e,t,l,ie,s,r]),T.useEffect(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight)},[y]),T.useEffect(()=>{d||P||!ie||fe.current!==ie&&(fe.current=ie,requestAnimationFrame(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[d,P,ie]);function ve(C){if(C==="input")return"User Input";if(C==="permission")return"Permission";if(C==="confirmation")return"Confirmation"}function L(C){return C==="started"?"Task started":C==="finished"?"Task finished":C==="failed"?"Task failed":C==="error"?"Command failed":C==="aborted"?"Task aborted":C==="confirmation"?"Task confirmed":C==="stopped"?"Follow-up stopped":C??""}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"]}),P?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."})]}):d?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:V,children:[y.map((C,X)=>{const A=H&&C.role==="assistant"&&!y.slice(X+1).some(xe=>xe.role==="assistant"||xe.role==="user");return C.role==="status"&&C.type==="monitoring"?null:C.role==="status"?b.jsxs("div",{className:`chat-status${C.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[L(C.type),C.time>0&&b.jsx("span",{className:"chat-status-time",children:f(C.time)})]}),C.content&&b.jsx("pre",{className:"chat-status-detail",children:C.content})]},X):b.jsxs("div",{className:`chat-message chat-message--${C.role}${C.role==="assistant"&&C.stream==="stderr"?" chat-message--stderr":""}`,children:[C.role==="assistant"&&S&&b.jsx("div",{className:"chat-message-agent",children:md(S)}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...xe})=>b.jsx("a",{...xe,target:"_blank",rel:"noopener noreferrer"})},children:C.content}),A&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),C.attachments&&C.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:C.attachments.map(xe=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>ue(xe),children:xe},xe))}),b.jsxs("div",{className:"chat-message-meta",children:[ve(C.type)&&b.jsx("span",{className:"chat-message-type",children:ve(C.type)}),C.time>0&&b.jsx("span",{children:f(C.time)})]})]},X)}),H&&(()=>{const C=y.filter(X=>X.role!=="status");return C.length===0||C[C.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[S&&b.jsx("div",{className:"chat-message-agent",children:md(S)}),b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),x==="monitoring"&&b.jsxs("div",{className:"chat-monitoring-indicator",children:[b.jsx("span",{className:"chat-monitoring-dot"}),"Monitoring command output"]})]}),z?b.jsx("div",{className:"chat-abort-bar",children:b.jsx("button",{className:"btn btn-secondary chat-abort-btn",disabled:U,onClick:async()=>{if(confirm("Abort this task?")){D(!0);try{await r("task.abort",{id:l})}catch(C){console.error("Abort failed:",C)}finally{D(!1)}}},children:U?"Aborting...":"Abort Task"})}):O?b.jsx("div",{className:"chat-input-bar",children:b.jsx("button",{className:"btn btn-secondary chat-stop-btn",disabled:U,onClick:async()=>{D(!0);try{await r("task.stop_followup",{id:l,run_id:ie})}catch(C){console.error("Stop failed:",C)}finally{D(!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 C=>{C.preventDefault();const X=ee.trim();if(!(!X||q)){M(!0);try{await r("task.followup",{id:l,run_id:ie,message:X}),$("")}catch(A){console.error("Follow-up failed:",A)}finally{M(!1)}}},children:[b.jsx("input",{ref:J,className:"chat-input",type:"text",placeholder:"Follow-up message",value:ee,onChange:C=>$(C.target.value),disabled:q}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!ee.trim()||q,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"})]})})]})]}),F&&b.jsx("div",{className:"report-dialog-overlay",onClick:()=>oe(null),children:b.jsxs("div",{className:"report-dialog",onClick:C=>C.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:F.file}),b.jsx("button",{className:"report-dialog-close",onClick:()=>oe(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:F.data_url?b.jsx("img",{src:F.data_url,alt:F.file,style:{maxWidth:"100%",height:"auto"}}):b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...C})=>b.jsx("a",{...C,target:"_blank",rel:"noopener noreferrer"})},children:F.content??""})})]})})]})}function Fb({title:e,message:t,onUpdate:r,onDismiss:s}){return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:e}),b.jsx("p",{className:"confirm-modal-message",children:t}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:r,children:"Update Now"}),s&&b.jsx("button",{className:"btn btn-secondary",onClick:s,children:"Dismiss"})]})]})})}function TO(){const{activeHost:e}=si(),t=T.useRef(null);T.useEffect(()=>{if(Jn.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 gE("/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 pE("/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 jO="0.9.9";function Kh(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 vu(){const{removePairedHost:e,setHostLanUrl:t,setHostTimezone:r}=qi(),{connected:s,request:l,subscribeEvents:u,unauthorized:c,activeHost:f}=si(),d=f.hostId,m=f.clientToken||null,y=Mr(),g=cr(),x=Yu(),w=qx("(min-width: 768px)"),S=g.pathname.endsWith("/tasks"),N=x.runId?void 0:x.taskId,z=!!(x.taskId&&x.runId),[O,H]=T.useState(!1),[F,oe]=T.useState(!1),[U,D]=T.useState(null),[ee,$]=T.useState(null),[q,M]=T.useState(null),[V,J]=T.useState(()=>localStorage.getItem("palmier.dismissedUpdateVersion")),[fe,ie]=T.useState({}),[Q,P]=T.useState({}),[te,ue]=T.useState(null),[ve,L]=T.useState(new Set),[C,X]=T.useState([]),[A,xe]=T.useState(),Le=!!m&&te===m,[ke,ze]=T.useState(new Map),[Ye,Ae]=T.useState(new Map),[tt,Pt]=T.useState(new Map),[Gt,Be]=T.useState(new Map);TO(),T.useEffect(()=>{window.scrollTo(0,0)},[d]),T.useEffect(()=>{let Te=!1;return JE().then(Z=>{Te||L(Z)}),()=>{Te=!0}},[]),T.useEffect(()=>{s&&l("host.info").then(Te=>{var Ke,Fe,Ge,$e,Qe,Je;X(Te.agents??[]),xe(Te.host_platform),ue(Te.linked_client_token??null),NE(Te.agents??[]);const Z=Te.version??null;$(Z),H(!!Z&&Kh(Z,jO)),t(d,Te.lan_url??void 0),r(d,Te.host_timezone);const he=new Map,Se=new Map,Ne=new Map,Ie=new Map;for(const pe of Te.pending_prompts??[])if(pe.type==="confirmation")he.set(pe.key,{description:((Ke=pe.meta)==null?void 0:Ke.description)??"",sessionName:(Fe=pe.meta)==null?void 0:Fe.session_name});else if(pe.type==="permission")Se.set(pe.key,{permissions:pe.params??[],sessionName:(Ge=pe.meta)==null?void 0:Ge.session_name});else if(pe.type==="input"){const Pe=pe.params??(($e=pe.meta)==null?void 0:$e.input_questions)??[];Ne.set(pe.key,{questions:Pe,description:(Qe=pe.meta)==null?void 0:Qe.description,sessionName:(Je=pe.meta)==null?void 0:Je.session_name}),Ie.set(pe.key,new Array(Pe.length).fill(""))}ze(he),Ae(Se),Pt(Ne),Be(Ie)}).catch(()=>{})},[s,d,l,t,r]),T.useEffect(()=>s?u(d,Z=>{const he=Z.subject.split(".");if(he.length<3)return;const Se=he.slice(2).join(".");let Ne={};try{Ne=JSON.parse(new TextDecoder().decode(Z.data))}catch{return}const Ie=Ne.event_type,Ke=Ne.session_id;if(Ie==="input-request"&&Ke){const Fe=Ne.input_questions,Ge=Ne.session_name,$e=Ne.description;Fe!=null&&Fe.length&&(Pt(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,{questions:Fe,description:$e,sessionName:Ge}),Je}),Be(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,new Array(Fe.length).fill("")),Je}));return}if(Ie==="input-resolved"&&Ke){Pt(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge}),Be(Fe=>{const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="confirm-request"&&Ke){const Fe=Ne.description,Ge=Ne.session_name;Fe&&ze($e=>{if($e.has(Ke))return $e;const Qe=new Map($e);return Qe.set(Ke,{description:Fe,sessionName:Ge}),Qe});return}if(Ie==="confirm-resolved"&&Ke){ze(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="permission-request"){const Fe=Ne.required_permissions,Ge=Ne.session_name;Fe!=null&&Fe.length&&Ae($e=>{if($e.has(Se))return $e;const Qe=new Map($e);return Qe.set(Se,{permissions:Fe,sessionName:Ge}),Qe});return}if(Ie==="permission-resolved"){Ae(Fe=>{if(!Fe.has(Se))return Fe;const Ge=new Map(Fe);return Ge.delete(Se),Ge});return}}):void 0,[s,d,u]);async function et(Te,Z){try{await l("task.user_input",{id:Te,value:[Z]})}catch(he){console.error("[Dashboard] Failed to respond to confirmation:",he)}}async function Tt(Te,Z){try{await l("task.user_input",{id:Te,value:[Z]})}catch(he){console.error("[Dashboard] Failed to respond to permission request:",he)}}async function jt(Te,Z){try{await l("task.user_input",{id:Te,value:Z})}catch(he){console.error("[Dashboard] Failed to respond to input request:",he)}}function pt(Te,Z){if(!ps())return;const he=`/hosts/${encodeURIComponent(d)}/runs/${encodeURIComponent(Te)}`;y(Z?`${he}/${encodeURIComponent(Z)}`:he)}T.useEffect(()=>{if(!ee)return;let Te=!1;return fetch("https://registry.npmjs.org/-/package/palmier/dist-tags").then(Z=>Z.ok?Z.json():null).then(Z=>{!Te&&(Z!=null&&Z.latest)&&M(Z.latest)}).catch(()=>{}),()=>{Te=!0}},[ee]),T.useEffect(()=>{let Te=!1;const Z={};for(const he of C){if(!he.palmierManaged)continue;const Se=localStorage.getItem(`palmier.dismissedAgentUpdate.${he.key}`);Se&&(Z[he.key]=Se)}P(Z);for(const he of C)!he.palmierManaged||!he.npmPackage||fetch(`https://registry.npmjs.org/-/package/${encodeURIComponent(he.npmPackage)}/dist-tags`).then(Se=>Se.ok?Se.json():null).then(Se=>{Te||!(Se!=null&&Se.latest)||ie(Ne=>Ne[he.key]===Se.latest?Ne:{...Ne,[he.key]:Se.latest})}).catch(()=>{});return()=>{Te=!0}},[C]);const Ht=C.find(Te=>{if(!Te.palmierManaged||!Te.version)return!1;const Z=fe[Te.key];return!Z||!Kh(Te.version,Z)?!1:Q[Te.key]!==Z});function gn(Te,Z){localStorage.setItem(`palmier.dismissedAgentUpdate.${Te}`,Z),P(he=>({...he,[Te]:Z}))}async function an(Te){oe(!0),D(null);try{const Z=await l("host.updateAgent",{key:Te});if(Z.error){D(Z.error),oe(!1);return}const he=await l("host.info");he.agents&&X(he.agents)}catch(Z){D(Z instanceof Error?Z.message:String(Z))}finally{oe(!1)}}const Wt=!O&&!!ee&&!!q&&Kh(ee,q)&&V!==q;function yn(){q&&(localStorage.setItem("palmier.dismissedUpdateVersion",q),J(q))}async function Kn(){oe(!0),D(null);try{const Te=await l("host.update");if(Te.error){D(Te.error),oe(!1);return}}catch{}setTimeout(()=>window.location.reload(),15e3)}const dt=s&&!c;return b.jsxs("div",{className:"dashboard",children:[w&&b.jsx(G0,{daemonVersion:ee,linkedClientToken:te,request:l,onEnabledCapabilitiesChange:L,onLinkedClientTokenChange:ue}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!w&&b.jsx(G0,{daemonVersion:ee,linkedClientToken:te,request:l,onEnabledCapabilitiesChange:L,onLinkedClientTokenChange:ue}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(WE,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(YE,{})})]}),b.jsx("main",{className:"dashboard-main",children:c?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()&&y("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(d),y("/",{replace:!0})},children:"Remove Host"})]})]}):dt?b.jsxs(b.Fragment,{children:[S&&!z&&b.jsx($E,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:C,hostPlatform:A,isNotificationListener:Le&&ve.has("notifications"),onViewRun:pt}),z?b.jsx(AO,{connected:s,hostId:d,request:l,subscribeEvents:u,taskId:x.taskId,runId:decodeURIComponent(x.runId)}):S?null:b.jsx(rC,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:C,hostPlatform:A,filterTaskId:N,onClearFilter:()=>{ps()&&y(`/hosts/${encodeURIComponent(d)}`)}})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{children:"Connecting to host..."})})}),(O||Wt)&&!F&&!U&&b.jsx(Fb,{title:O?"Update Required":"Update Available",message:O?`Your Palmier host${ee?` (v${ee})`:""} is too old for this version of the app. Please update to continue.`:`A new version of Palmier (v${q}) is available. You're running v${ee}.`,onUpdate:Kn,onDismiss:O?void 0:yn}),!O&&!Wt&&Ht&&!F&&!U&&b.jsx(Fb,{title:"Agent Update Available",message:`A new version of ${Ht.label} (v${fe[Ht.key]}) is available. You're running v${Ht.version}.`,onUpdate:()=>an(Ht.key),onDismiss:()=>gn(Ht.key,fe[Ht.key])}),F&&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..."})]})}),U&&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:U}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{D(null)},children:"Retry"})})]})})]}),ds.createPortal(b.jsxs(b.Fragment,{children:[[...ke.entries()].map(([Te,{description:Z,sessionName:he}])=>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"}),he&&b.jsx("p",{className:"confirm-modal-subtitle",children:he}),b.jsx("p",{className:"confirm-modal-message",children:Z}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>et(Te,"confirmed"),children:"Confirm"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>et(Te,"aborted"),children:"Abort"})]})]})},Te)),[...Ye.entries()].map(([Te,{permissions:Z,sessionName:he}])=>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:he||Te})}),b.jsx("div",{className:"permission-list",children:Z.map((Se,Ne)=>b.jsxs("div",{className:"permission-item",children:[b.jsx("span",{className:"permission-name",children:Se.name}),Se.description&&b.jsx("span",{className:"permission-desc",children:Se.description})]},Ne))}),b.jsxs("div",{className:"permission-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>Tt(Te,"granted"),children:"Allow Once"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>Tt(Te,"granted_all"),children:"Allow Always"})]}),b.jsx("button",{className:"permission-abort-link",onClick:()=>Tt(Te,"aborted"),children:"Deny & Abort Task"})]})},Te)),[...tt.entries()].map(([Te,{questions:Z,description:he,sessionName:Se}])=>{const Ne=Gt.get(Te)??new Array(Z.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"}),Se&&b.jsx("p",{className:"confirm-modal-subtitle",children:Se}),he&&b.jsx("p",{className:"confirm-modal-message",children:he}),b.jsx("div",{className:"input-list",children:Z.map((Ie,Ke)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:Ie}),b.jsx("input",{type:"text",className:"input-field",value:Ne[Ke]??"",onChange:Fe=>{Be(Ge=>{const $e=new Map(Ge),Qe=[...$e.get(Te)??[]];return Qe[Ke]=Fe.target.value,$e.set(Te,Qe),$e})},autoFocus:Ke===0})]},Ke))}),b.jsx("div",{className:"input-actions",children:b.jsx("button",{className:"btn btn-primary",disabled:Ne.some(Ie=>!Ie.trim()),onClick:()=>jt(Te,Ne),children:"Submit"})}),b.jsx("button",{className:"permission-abort-link",onClick:()=>jt(Te,["aborted"]),children:"Cancel"})]})},Te)})]}),document.body)]})}const NO=ys("Preferences",{web:()=>Fd(()=>import("./web-Btb09jZq.js"),[]).then(e=>new e.PreferencesWeb)}),kl=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),$b=Jn.isNativePlatform();function OO(){const[e,t]=T.useState(""),[r,s]=T.useState(!0),[l,u]=T.useState(!1),[c,f]=T.useState(null),{addPairedHost:d,pairedHosts:m}=qi(),y=Mr();async function g(){const x=e.trim().toUpperCase();if(!x){f("Enter a pairing code.");return}u(!0),f(null);try{let w;if(kl){const z=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,label:navigator.userAgent})});if(!z.ok){const O=await z.json().catch(()=>({error:"Connection failed"}));throw new Error(O.error||`HTTP ${z.status}`)}w=await z.json()}else{const z=await fetch(`${Bu}/api/config`);if(!z.ok)throw new Error("Failed to fetch server config");const O=await z.json();if(!O.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const H=await Dx({servers:O.natsWsUrl,authenticator:Ex(O.natsJwt,new TextEncoder().encode(O.natsNkeySeed))}),F=Ou(),oe=`pair.${x}`,U=await H.request(oe,F.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});w=JSON.parse(F.decode(U.data)),await H.close()}const S={hostId:w.hostId,clientToken:w.clientToken,directUrl:kl?window.location.origin:void 0,...w.hostName?{name:w.hostName}:{}};if(d(S),Jn.isNativePlatform()&&dn){await NO.set({key:"hostId",value:w.hostId});try{const{token:z}=await dn.getFcmToken();await fetch(`${Bu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:w.hostId,fcmToken:z})})}catch(z){console.warn("FCM token registration failed:",z)}}const N=`/hosts/${encodeURIComponent(w.hostId)}`;y($b&&r?`${N}/pair/setup`:N)}catch(w){const S=w instanceof Error?w.message:String(w);S.includes("timeout")||S.includes("TIMEOUT")||S.includes("503")||S.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(S)}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:x=>t(x.target.value.toUpperCase()),placeholder:"A7K9M2",className:"form-input form-input-mono pair-code-input",autoFocus:!0,autoComplete:"off",disabled:l})]}),$b&&b.jsxs("label",{className:"pair-checkbox",children:[b.jsx("input",{type:"checkbox",checked:r,onChange:x=>s(x.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:g,disabled:l||!e.trim(),children:[l&&b.jsx("span",{className:"btn-spinner"}),l?"Pairing...":"Pair"]}),m.length>0&&b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>y("/"),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 RO(){const e=Mr(),{connected:t,request:r,activeHost:s}=si(),{setHostLanUrl:l,pairedHosts:u}=qi(),c=u.length<=1,[f,d]=T.useState("loading"),[m,y]=T.useState(null),[g,x]=T.useState(null);function w(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}T.useEffect(()=>{if(!t||f!=="loading")return;let H=!1;return r("host.info").catch(()=>({})).then(F=>{if(H)return;l(s.hostId,F.lan_url??void 0);const oe=F.linked_client_token??null;y(oe);const U=!!oe&&oe!==s.clientToken;d(U?"confirming":"linking")}),()=>{H=!0}},[t,f,s,r,l]),T.useEffect(()=>{if(f!=="linking")return;let H=!1;return(async()=>{try{if(dn){const{token:F}=await dn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(H)return;c?d("wizard"):w()}catch(F){if(H)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{H=!0}},[f]);function S(){d("linking")}function N(){w()}function z(){x(null),d("linking")}const O=f==="confirming"&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:N,children:b.jsxs("div",{className:"confirm-modal",onClick:H=>H.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:N,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 H=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[H&&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:z,children:"Retry"}),b.jsx("button",{className:"btn btn-secondary",onClick:w,children:"Skip linking"})]})]})]}),O]})}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(Ix,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:w,children:"Finish"})})]})})}function MO(){const e=Mr();return T.useEffect(()=>{if(!dn)return;const t=dn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function DO(){const{pairedHosts:e}=qi();return e.length===0?b.jsx(zl,{to:"/pair",replace:!0}):b.jsx(zl,{to:`/hosts/${encodeURIComponent(e[0].hostId)}`,replace:!0})}function LO(){const{hostId:e}=Yu(),{pairedHosts:t}=qi(),r=t.find(s=>s.hostId===e)??null;return r?b.jsx(vE,{activeHost:r,children:b.jsxs(ax,{children:[b.jsx(br,{index:!0,element:b.jsx(vu,{})}),b.jsx(br,{path:"tasks",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId/:runId",element:b.jsx(vu,{})}),b.jsx(br,{path:"pair/setup",element:b.jsx(RO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:".",replace:!0})})]})}):b.jsx(zl,{to:"/",replace:!0})}function zO(){return b.jsxs($_,{children:[b.jsx(MO,{}),b.jsxs(ax,{children:[b.jsx(br,{path:"/",element:b.jsx(DO,{})}),b.jsx(br,{path:"/pair",element:b.jsx(OO,{})}),b.jsx(br,{path:"/hosts/:hostId/*",element:b.jsx(LO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:"/",replace:!0})})]})]})}fS.createRoot(document.getElementById("root")).render(b.jsx(T.StrictMode,{children:b.jsx(O_,{children:b.jsx(zO,{})})}));export{Id as W};
120
+ `))}function d(w,S,N,z){const O=N.enter("tableCell"),H=N.enter("phrasing"),F=N.containerPhrasing(w,{...z,before:u,after:u});return H(),O(),F}function m(w,S){return WN(w,{align:S,alignDelimiters:s,padding:r,stringLength:l})}function y(w,S,N){const z=w.children;let O=-1;const H=[],F=S.enter("table");for(;++O<z.length;)H[O]=g(z[O],S,N);return F(),H}function g(w,S,N){const z=w.children;let O=-1;const H=[],F=S.enter("tableRow");for(;++O<z.length;)H[O]=d(z[O],w,S,N);return F(),H}function x(w,S,N){let z=P1.inlineCode(w,S,N);return N.stack.includes("tableCell")&&(z=z.replace(/\|/g,"\\$&")),z}}function H3(){return{exit:{taskListCheckValueChecked:Pb,taskListCheckValueUnchecked:Pb,paragraph:I3}}}function q3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:F3}}}function Pb(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function I3(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 F3(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=P1.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 $3(){return[SN(),FN(),GN(),M3(),H3()]}function Y3(e){return{extensions:[_N(),$N(e),JN(),P3(e),q3()]}}const V3={tokenize:Z3,partial:!0},H1={tokenize:W3,partial:!0},q1={tokenize:eO,partial:!0},I1={tokenize:tO,partial:!0},G3={tokenize:nO,partial:!0},F1={name:"wwwAutolink",tokenize:K3,previous:Y1},$1={name:"protocolAutolink",tokenize:Q3,previous:V1},ai={name:"emailAutolink",tokenize:X3,previous:G1},Dr={};function J3(){return{text:Dr}}let hs=48;for(;hs<123;)Dr[hs]=ai,hs++,hs===58?hs=65:hs===91&&(hs=97);Dr[43]=ai;Dr[45]=ai;Dr[46]=ai;Dr[95]=ai;Dr[72]=[ai,$1];Dr[104]=[ai,$1];Dr[87]=[ai,F1];Dr[119]=[ai,F1];function X3(e,t,r){const s=this;let l,u;return c;function c(g){return!Cd(g)||!G1.call(s,s.previous)||um(s.events)?r(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),f(g))}function f(g){return Cd(g)?(e.consume(g),f):g===64?(e.consume(g),d):r(g)}function d(g){return g===46?e.check(G3,y,m)(g):g===45||g===95||mn(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&&_n(s.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):r(g)}}function K3(e,t,r){const s=this;return l;function l(c){return c!==87&&c!==119||!Y1.call(s,s.previous)||um(s.events)?r(c):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(V3,e.attempt(H1,e.attempt(q1,u),r),r)(c))}function u(c){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(c)}}function Q3(e,t,r){const s=this;let l="",u=!1;return c;function c(g){return(g===72||g===104)&&V1.call(s,s.previous)&&!um(s.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),l+=String.fromCodePoint(g),e.consume(g),f):r(g)}function f(g){if(_n(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)||At(g)||gs(g)||Zu(g)?r(g):e.attempt(H1,e.attempt(q1,y),r)(g)}function y(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function Z3(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 W3(e,t,r){let s,l,u;return c;function c(m){return m===46||m===95?e.check(I1,d,f)(m):m===null||At(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 eO(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(I1,t,u)(c):c===null||At(c)||gs(c)?t(c):(e.consume(c),l)}function u(c){return c===41&&s++,e.consume(c),l}}function tO(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||At(f)||gs(f)?t(f):r(f)}function l(f){return f===null||f===40||f===91||At(f)||gs(f)?t(f):s(f)}function u(f){return _n(f)?c(f):r(f)}function c(f){return f===59?(e.consume(f),s):_n(f)?(e.consume(f),c):r(f)}}function nO(e,t,r){return s;function s(u){return e.consume(u),l}function l(u){return mn(u)?r(u):t(u)}}function Y1(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||At(e)}function V1(e){return!_n(e)}function G1(e){return!(e===47||Cd(e))}function Cd(e){return e===43||e===45||e===46||e===95||mn(e)}function um(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 rO={tokenize:fO,partial:!0};function iO(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:oO,continuation:{tokenize:uO},exit:cO}},text:{91:{name:"gfmFootnoteCall",tokenize:lO},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:sO,resolveTo:aO}}}}function sO(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=wr(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 aO(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 lO(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||At(g))return r(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteCallString");return l.includes(wr(s.sliceSerialize(x)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):r(g)}return At(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 oO(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||At(S))return r(S);if(S===93){e.exit("chunkString");const N=e.exit("gfmFootnoteDefinitionLabelString");return u=wr(s.sliceSerialize(N)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(S),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),x}return At(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),ut(e,w,"gfmFootnoteDefinitionWhitespace")):r(S)}function w(S){return t(S)}}function uO(e,t,r){return e.check(Jl,t,e.attempt(rO,t,r))}function cO(e){e.exit("gfmFootnoteDefinition")}function fO(e,t,r){const s=this;return ut(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 hO(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&&Vn(x,x.length,0,Wu(w,c.slice(m+1,d),f)),Vn(x,x.length,0,[["exit",g,f],["enter",c[d][1],f],["exit",c[d][1],f],["exit",y,f]]),Vn(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 N=ba(m);if(S===126)return g>1?d(S):(c.consume(S),g++,w);if(g<2&&!r)return d(S);const z=c.exit("strikethroughSequenceTemporary"),O=ba(S);return z._open=!O||O===2&&!!N,z._close=!N||N===2&&!!O,f(S)}}}class dO{constructor(){this.map=[]}add(t,r,s){mO(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 mO(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 pO(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 gO(){return{flow:{null:{name:"table",tokenize:yO,resolveAll:bO}}}}function yO(e,t,r){const s=this;let l=0,u=0,c;return f;function f(M){let V=s.events.length-1;for(;V>-1;){const ie=s.events[V][1].type;if(ie==="lineEnding"||ie==="linePrefix")V--;else break}const J=V>-1?s.events[V][1].type:null,fe=J==="tableHead"||J==="tableRow"?D:d;return fe===D&&s.parser.lazy[s.now().line]?r(M):fe(M)}function d(M){return e.enter("tableHead"),e.enter("tableRow"),m(M)}function m(M){return M===124||(c=!0,u+=1),y(M)}function y(M){return M===null?r(M):He(M)?u>1?(u=0,s.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),w):r(M):st(M)?ut(e,y,"whitespace")(M):(u+=1,c&&(c=!1,l+=1),M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),c=!0,y):(e.enter("data"),g(M)))}function g(M){return M===null||M===124||At(M)?(e.exit("data"),y(M)):(e.consume(M),M===92?x:g)}function x(M){return M===92||M===124?(e.consume(M),g):g(M)}function w(M){return s.interrupt=!1,s.parser.lazy[s.now().line]?r(M):(e.enter("tableDelimiterRow"),c=!1,st(M)?ut(e,S,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):S(M))}function S(M){return M===45||M===58?z(M):M===124?(c=!0,e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),N):U(M)}function N(M){return st(M)?ut(e,z,"whitespace")(M):z(M)}function z(M){return M===58?(u+=1,c=!0,e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),O):M===45?(u+=1,O(M)):M===null||He(M)?oe(M):U(M)}function O(M){return M===45?(e.enter("tableDelimiterFiller"),H(M)):U(M)}function H(M){return M===45?(e.consume(M),H):M===58?(c=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),F):(e.exit("tableDelimiterFiller"),F(M))}function F(M){return st(M)?ut(e,oe,"whitespace")(M):oe(M)}function oe(M){return M===124?S(M):M===null||He(M)?!c||l!==u?U(M):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(M)):U(M)}function U(M){return r(M)}function D(M){return e.enter("tableRow"),ee(M)}function ee(M){return M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),ee):M===null||He(M)?(e.exit("tableRow"),t(M)):st(M)?ut(e,ee,"whitespace")(M):(e.enter("data"),$(M))}function $(M){return M===null||M===124||At(M)?(e.exit("data"),ee(M)):(e.consume(M),M===92?q:$)}function q(M){return M===92||M===124?(e.consume(M),$):$(M)}}function bO(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 dO;for(;++r<e.length;){const w=e[r],S=w[1];w[0]==="enter"?S.type==="tableHead"?(f=!1,d!==0&&(Hb(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=xu(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=xu(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=xu(x,t,u,l,r,g)):c[1]!==0&&(g=xu(x,t,c,l,r,g)),l=0):l&&(S.type==="data"||S.type==="tableDelimiterMarker"||S.type==="tableDelimiterFiller")&&(c[3]=r)}for(d!==0&&Hb(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=pO(t.events,r))}return e}function xu(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,N=r[3]-r[2]-1;e.add(S,N,[])}}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 Hb(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 xO={name:"tasklistCheck",tokenize:wO};function vO(){return{text:{91:xO}}}function wO(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 At(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 He(d)?t(d):st(d)?e.check({tokenize:SO},t,r)(d):r(d)}}function SO(e,t,r){return ut(e,s,"whitespace");function s(l){return l===null?r(l):t(l)}}function _O(e){return r1([J3(),iO(),hO(e),gO(),vO()])}const kO={};function qb(e){const t=this,r=e||kO,s=t.data(),l=s.micromarkExtensions||(s.micromarkExtensions=[]),u=s.fromMarkdownExtensions||(s.fromMarkdownExtensions=[]),c=s.toMarkdownExtensions||(s.toMarkdownExtensions=[]);l.push(_O(r)),u.push($3()),c.push(Y3(r))}function EO(e){k1(e,[/\r?\n|\r/g,CO])}function CO(){return{type:"break"}}function Ib(){return function(e){EO(e)}}function AO({connected:e,hostId:t,request:r,subscribeEvents:s,taskId:l,runId:u}){const c=Mr(),f=$d(),[d,m]=T.useState(!0),[y,g]=T.useState([]),[x,w]=T.useState(),[S,N]=T.useState(),z=x==="started"||x==="monitoring",O=x==="followup",H=x==="started"||x==="followup",[F,oe]=T.useState(null);pd(F!==null,()=>oe(null));const[U,D]=T.useState(!1),[ee,$]=T.useState(""),[q,M]=T.useState(!1),V=T.useRef(null),J=T.useRef(null),fe=T.useRef(null),[ie,Q]=T.useState(u==="latest"?void 0:u),P=u==="latest"&&ie===null;T.useEffect(()=>{if(u!=="latest"){Q(u);return}e&&(Q(void 0),r("taskrun.list",{task_id:l,limit:1}).then(C=>{var X,A;return Q(((A=(X=C.entries)==null?void 0:X[0])==null?void 0:A.run_id)??null)}).catch(()=>Q(null)))},[u,l,e,r]);async function te(){if(ie)try{const C=await r("task.result",{id:l,run_id:ie});if(C.error){console.error("No result:",C.error),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0});return}g(C.messages??[]),w(C.running_state),N(C.agent)}catch(C){console.error("Failed to load result:",C),c(t?`/hosts/${encodeURIComponent(t)}`:"/",{replace:!0})}finally{m(!1)}}async function ue(C){var X;if(ie)try{const xe=(X=(await r("task.reports",{id:l,run_id:ie,report_files:[C]})).reports)==null?void 0:X[0];xe!=null&&xe.data_url?oe({file:C,data_url:xe.data_url}):oe({file:C,content:(xe==null?void 0:xe.content)??"Report not found."})}catch{oe({file:C,content:"Failed to load report."})}}T.useEffect(()=>{!e||!ie||(m(!0),te())},[e,l,ie]),T.useEffect(()=>!e||!t||!ie?void 0:s(t,async X=>{try{const A=JSON.parse(new TextDecoder().decode(X.data));if(A.event_type!=="running-state"&&A.event_type!=="result-updated"||X.subject.split(".").pop()!==l||A.event_type==="result-updated"&&A.run_id&&A.run_id!==ie)return;te()}catch{}}),[e,t,l,ie,s,r]),T.useEffect(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight)},[y]),T.useEffect(()=>{d||P||!ie||fe.current!==ie&&(fe.current=ie,requestAnimationFrame(()=>{V.current&&(V.current.scrollTop=V.current.scrollHeight),window.scrollTo({top:document.documentElement.scrollHeight,behavior:"auto"})}))},[d,P,ie]);function ve(C){if(C==="input")return"User Input";if(C==="permission")return"Permission";if(C==="confirmation")return"Confirmation"}function L(C){return C==="started"?"Task started":C==="finished"?"Task finished":C==="failed"?"Task failed":C==="error"?"Command failed":C==="aborted"?"Task aborted":C==="confirmation"?"Task confirmed":C==="stopped"?"Follow-up stopped":C??""}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"]}),P?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."})]}):d?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:V,children:[y.map((C,X)=>{const A=H&&C.role==="assistant"&&!y.slice(X+1).some(xe=>xe.role==="assistant"||xe.role==="user");return C.role==="status"&&C.type==="monitoring"?null:C.role==="status"?b.jsxs("div",{className:`chat-status${C.type==="error"?" chat-status--error":""}`,children:[b.jsxs("div",{children:[L(C.type),C.time>0&&b.jsx("span",{className:"chat-status-time",children:f(C.time)})]}),C.content&&b.jsx("pre",{className:"chat-status-detail",children:C.content})]},X):b.jsxs("div",{className:`chat-message chat-message--${C.role}${C.role==="assistant"&&C.stream==="stderr"?" chat-message--stderr":""}`,children:[C.role==="assistant"&&S&&b.jsx("div",{className:"chat-message-agent",children:md(S)}),b.jsxs("div",{className:"chat-message-content",children:[b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...xe})=>b.jsx("a",{...xe,target:"_blank",rel:"noopener noreferrer"})},children:C.content}),A&&b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),C.attachments&&C.attachments.length>0&&b.jsx("div",{className:"chat-message-attachments",children:C.attachments.map(xe=>b.jsx("button",{className:"chat-attachment-chip",onClick:()=>ue(xe),children:xe},xe))}),b.jsxs("div",{className:"chat-message-meta",children:[ve(C.type)&&b.jsx("span",{className:"chat-message-type",children:ve(C.type)}),C.time>0&&b.jsx("span",{children:f(C.time)})]})]},X)}),H&&(()=>{const C=y.filter(X=>X.role!=="status");return C.length===0||C[C.length-1].role!=="assistant"})()&&b.jsxs("div",{className:"chat-message chat-message--assistant",children:[S&&b.jsx("div",{className:"chat-message-agent",children:md(S)}),b.jsxs("div",{className:"chat-typing-indicator",children:[b.jsx("span",{}),b.jsx("span",{}),b.jsx("span",{})]})]}),x==="monitoring"&&b.jsxs("div",{className:"chat-monitoring-indicator",children:[b.jsx("span",{className:"chat-monitoring-dot"}),"Monitoring command output"]})]}),z?b.jsx("div",{className:"chat-abort-bar",children:b.jsx("button",{className:"btn btn-secondary chat-abort-btn",disabled:U,onClick:async()=>{if(confirm("Abort this task?")){D(!0);try{await r("task.abort",{id:l})}catch(C){console.error("Abort failed:",C)}finally{D(!1)}}},children:U?"Aborting...":"Abort Task"})}):O?b.jsx("div",{className:"chat-input-bar",children:b.jsx("button",{className:"btn btn-secondary chat-stop-btn",disabled:U,onClick:async()=>{D(!0);try{await r("task.stop_followup",{id:l,run_id:ie})}catch(C){console.error("Stop failed:",C)}finally{D(!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 C=>{C.preventDefault();const X=ee.trim();if(!(!X||q)){M(!0);try{await r("task.followup",{id:l,run_id:ie,message:X}),$("")}catch(A){console.error("Follow-up failed:",A)}finally{M(!1)}}},children:[b.jsx("input",{ref:J,className:"chat-input",type:"text",placeholder:"Follow-up message",value:ee,onChange:C=>$(C.target.value),disabled:q}),b.jsx("button",{className:"btn btn-primary chat-send-btn",type:"submit",disabled:!ee.trim()||q,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"})]})})]})]}),F&&b.jsx("div",{className:"report-dialog-overlay",onClick:()=>oe(null),children:b.jsxs("div",{className:"report-dialog",onClick:C=>C.stopPropagation(),children:[b.jsxs("div",{className:"report-dialog-header",children:[b.jsx("span",{className:"report-dialog-title",children:F.file}),b.jsx("button",{className:"report-dialog-close",onClick:()=>oe(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:F.data_url?b.jsx("img",{src:F.data_url,alt:F.file,style:{maxWidth:"100%",height:"auto"}}):b.jsx(Mb,{remarkPlugins:[qb,Ib],components:{a:({...C})=>b.jsx("a",{...C,target:"_blank",rel:"noopener noreferrer"})},children:F.content??""})})]})})]})}function Fb({title:e,message:t,onUpdate:r,onDismiss:s}){return b.jsx("div",{className:"confirm-modal-overlay",children:b.jsxs("div",{className:"confirm-modal",children:[b.jsx("h2",{className:"confirm-modal-title",children:e}),b.jsx("p",{className:"confirm-modal-message",children:t}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:r,children:"Update Now"}),s&&b.jsx("button",{className:"btn btn-secondary",onClick:s,children:"Dismiss"})]})]})})}function TO(){const{activeHost:e}=si(),t=T.useRef(null);T.useEffect(()=>{if(Jn.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 gE("/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 pE("/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 jO="0.9.9";function Kh(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 vu(){const{removePairedHost:e,setHostLanUrl:t,setHostTimezone:r}=qi(),{connected:s,request:l,subscribeEvents:u,unauthorized:c,activeHost:f}=si(),d=f.hostId,m=f.clientToken||null,y=Mr(),g=cr(),x=Yu(),w=qx("(min-width: 768px)"),S=g.pathname.endsWith("/tasks"),N=x.runId?void 0:x.taskId,z=!!(x.taskId&&x.runId),[O,H]=T.useState(!1),[F,oe]=T.useState(!1),[U,D]=T.useState(null),[ee,$]=T.useState(null),[q,M]=T.useState(null),[V,J]=T.useState(()=>localStorage.getItem(`palmier.${d}.dismissedUpdateVersion`)),[fe,ie]=T.useState({}),[Q,P]=T.useState({}),[te,ue]=T.useState(null),[ve,L]=T.useState(new Set),[C,X]=T.useState([]),[A,xe]=T.useState(),Le=!!m&&te===m,[ke,ze]=T.useState(new Map),[Ye,Ae]=T.useState(new Map),[tt,Pt]=T.useState(new Map),[Gt,Be]=T.useState(new Map);TO(),T.useEffect(()=>{window.scrollTo(0,0)},[d]),T.useEffect(()=>{let Te=!1;return JE().then(Z=>{Te||L(Z)}),()=>{Te=!0}},[]),T.useEffect(()=>{s&&l("host.info").then(Te=>{var Ke,Fe,Ge,$e,Qe,Je;X(Te.agents??[]),xe(Te.host_platform),ue(Te.linked_client_token??null),NE(Te.agents??[]);const Z=Te.version??null;$(Z),H(!!Z&&Kh(Z,jO)),t(d,Te.lan_url??void 0),r(d,Te.host_timezone);const he=new Map,Se=new Map,Ne=new Map,Ie=new Map;for(const pe of Te.pending_prompts??[])if(pe.type==="confirmation")he.set(pe.key,{description:((Ke=pe.meta)==null?void 0:Ke.description)??"",sessionName:(Fe=pe.meta)==null?void 0:Fe.session_name});else if(pe.type==="permission")Se.set(pe.key,{permissions:pe.params??[],sessionName:(Ge=pe.meta)==null?void 0:Ge.session_name});else if(pe.type==="input"){const Pe=pe.params??(($e=pe.meta)==null?void 0:$e.input_questions)??[];Ne.set(pe.key,{questions:Pe,description:(Qe=pe.meta)==null?void 0:Qe.description,sessionName:(Je=pe.meta)==null?void 0:Je.session_name}),Ie.set(pe.key,new Array(Pe.length).fill(""))}ze(he),Ae(Se),Pt(Ne),Be(Ie)}).catch(()=>{})},[s,d,l,t,r]),T.useEffect(()=>s?u(d,Z=>{const he=Z.subject.split(".");if(he.length<3)return;const Se=he.slice(2).join(".");let Ne={};try{Ne=JSON.parse(new TextDecoder().decode(Z.data))}catch{return}const Ie=Ne.event_type,Ke=Ne.session_id;if(Ie==="input-request"&&Ke){const Fe=Ne.input_questions,Ge=Ne.session_name,$e=Ne.description;Fe!=null&&Fe.length&&(Pt(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,{questions:Fe,description:$e,sessionName:Ge}),Je}),Be(Qe=>{if(Qe.has(Ke))return Qe;const Je=new Map(Qe);return Je.set(Ke,new Array(Fe.length).fill("")),Je}));return}if(Ie==="input-resolved"&&Ke){Pt(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge}),Be(Fe=>{const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="confirm-request"&&Ke){const Fe=Ne.description,Ge=Ne.session_name;Fe&&ze($e=>{if($e.has(Ke))return $e;const Qe=new Map($e);return Qe.set(Ke,{description:Fe,sessionName:Ge}),Qe});return}if(Ie==="confirm-resolved"&&Ke){ze(Fe=>{if(!Fe.has(Ke))return Fe;const Ge=new Map(Fe);return Ge.delete(Ke),Ge});return}if(Ie==="permission-request"){const Fe=Ne.required_permissions,Ge=Ne.session_name;Fe!=null&&Fe.length&&Ae($e=>{if($e.has(Se))return $e;const Qe=new Map($e);return Qe.set(Se,{permissions:Fe,sessionName:Ge}),Qe});return}if(Ie==="permission-resolved"){Ae(Fe=>{if(!Fe.has(Se))return Fe;const Ge=new Map(Fe);return Ge.delete(Se),Ge});return}}):void 0,[s,d,u]);async function et(Te,Z){try{await l("task.user_input",{id:Te,value:[Z]})}catch(he){console.error("[Dashboard] Failed to respond to confirmation:",he)}}async function Tt(Te,Z){try{await l("task.user_input",{id:Te,value:[Z]})}catch(he){console.error("[Dashboard] Failed to respond to permission request:",he)}}async function jt(Te,Z){try{await l("task.user_input",{id:Te,value:Z})}catch(he){console.error("[Dashboard] Failed to respond to input request:",he)}}function pt(Te,Z){if(!ps())return;const he=`/hosts/${encodeURIComponent(d)}/runs/${encodeURIComponent(Te)}`;y(Z?`${he}/${encodeURIComponent(Z)}`:he)}T.useEffect(()=>{if(!ee)return;let Te=!1;return fetch("https://registry.npmjs.org/palmier/latest").then(Z=>Z.ok?Z.json():null).then(Z=>{!Te&&(Z!=null&&Z.version)&&M(Z.version)}).catch(()=>{}),()=>{Te=!0}},[ee]),T.useEffect(()=>{let Te=!1;const Z={};for(const he of C){if(!he.version)continue;const Se=localStorage.getItem(`palmier.${d}.dismissedAgentUpdate.${he.key}`);Se&&(Z[he.key]=Se)}P(Z);for(const he of C)!he.version||!he.npmPackage||fetch(`https://registry.npmjs.org/${he.npmPackage}/latest`).then(Se=>Se.ok?Se.json():null).then(Se=>{Te||!(Se!=null&&Se.version)||ie(Ne=>Ne[he.key]===Se.version?Ne:{...Ne,[he.key]:Se.version})}).catch(()=>{});return()=>{Te=!0}},[C]);const Ht=C.find(Te=>{if(!Te.version)return!1;const Z=fe[Te.key];return!Z||!Kh(Te.version,Z)?!1:Q[Te.key]!==Z});function gn(Te,Z){localStorage.setItem(`palmier.${d}.dismissedAgentUpdate.${Te}`,Z),P(he=>({...he,[Te]:Z}))}async function an(Te){oe(!0),D(null);try{const Z=await l("host.updateAgent",{key:Te});if(Z.error){D(Z.error),oe(!1);return}const he=await l("host.info");he.agents&&X(he.agents)}catch(Z){D(Z instanceof Error?Z.message:String(Z))}finally{oe(!1)}}const Wt=!O&&!!ee&&!!q&&Kh(ee,q)&&V!==q;function yn(){q&&(localStorage.setItem(`palmier.${d}.dismissedUpdateVersion`,q),J(q))}async function Kn(){oe(!0),D(null);try{const Te=await l("host.update");if(Te.error){D(Te.error),oe(!1);return}}catch{}setTimeout(()=>window.location.reload(),15e3)}const dt=s&&!c;return b.jsxs("div",{className:"dashboard",children:[w&&b.jsx(G0,{daemonVersion:ee,linkedClientToken:te,request:l,onEnabledCapabilitiesChange:L,onLinkedClientTokenChange:ue}),b.jsxs("div",{className:"dashboard-content",children:[b.jsxs("header",{className:"app-header",children:[b.jsxs("div",{className:"app-title-bar",children:[!w&&b.jsx(G0,{daemonVersion:ee,linkedClientToken:te,request:l,onEnabledCapabilitiesChange:L,onLinkedClientTokenChange:ue}),b.jsx("h1",{className:"app-title",children:"Palmier"}),b.jsx(WE,{})]}),b.jsx("div",{className:"tab-bar",children:b.jsx(YE,{})})]}),b.jsx("main",{className:"dashboard-main",children:c?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()&&y("/pair")},children:"Re-pair Device"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>{e(d),y("/",{replace:!0})},children:"Remove Host"})]})]}):dt?b.jsxs(b.Fragment,{children:[S&&!z&&b.jsx($E,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:C,hostPlatform:A,isNotificationListener:Le&&ve.has("notifications"),onViewRun:pt}),z?b.jsx(AO,{connected:s,hostId:d,request:l,subscribeEvents:u,taskId:x.taskId,runId:decodeURIComponent(x.runId)}):S?null:b.jsx(rC,{connected:s,hostId:d,request:l,subscribeEvents:u,agents:C,hostPlatform:A,filterTaskId:N,onClearFilter:()=>{ps()&&y(`/hosts/${encodeURIComponent(d)}`)}})]}):b.jsx("div",{className:"empty-state",children:b.jsx("p",{children:"Connecting to host..."})})}),(O||Wt)&&!F&&!U&&b.jsx(Fb,{title:O?"Update Required":"Update Available",message:O?`Your Palmier host${ee?` (v${ee})`:""} is too old for this version of the app. Please update to continue.`:`A new version of Palmier (v${q}) is available. You're running v${ee}.`,onUpdate:Kn,onDismiss:O?void 0:yn}),!O&&!Wt&&Ht&&!F&&!U&&b.jsx(Fb,{title:"Agent Update Available",message:`A new version of ${Ht.label} (v${fe[Ht.key]}) is available. You're running v${Ht.version}.`,onUpdate:()=>an(Ht.key),onDismiss:()=>gn(Ht.key,fe[Ht.key])}),F&&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..."})]})}),U&&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:U}),b.jsx("div",{className:"confirm-modal-actions",children:b.jsx("button",{className:"btn btn-secondary",onClick:()=>{D(null)},children:"Retry"})})]})})]}),ds.createPortal(b.jsxs(b.Fragment,{children:[[...ke.entries()].map(([Te,{description:Z,sessionName:he}])=>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"}),he&&b.jsx("p",{className:"confirm-modal-subtitle",children:he}),b.jsx("p",{className:"confirm-modal-message",children:Z}),b.jsxs("div",{className:"confirm-modal-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>et(Te,"confirmed"),children:"Confirm"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>et(Te,"aborted"),children:"Abort"})]})]})},Te)),[...Ye.entries()].map(([Te,{permissions:Z,sessionName:he}])=>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:he||Te})}),b.jsx("div",{className:"permission-list",children:Z.map((Se,Ne)=>b.jsxs("div",{className:"permission-item",children:[b.jsx("span",{className:"permission-name",children:Se.name}),Se.description&&b.jsx("span",{className:"permission-desc",children:Se.description})]},Ne))}),b.jsxs("div",{className:"permission-actions",children:[b.jsx("button",{className:"btn btn-primary",onClick:()=>Tt(Te,"granted"),children:"Allow Once"}),b.jsx("button",{className:"btn btn-secondary",onClick:()=>Tt(Te,"granted_all"),children:"Allow Always"})]}),b.jsx("button",{className:"permission-abort-link",onClick:()=>Tt(Te,"aborted"),children:"Deny & Abort Task"})]})},Te)),[...tt.entries()].map(([Te,{questions:Z,description:he,sessionName:Se}])=>{const Ne=Gt.get(Te)??new Array(Z.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"}),Se&&b.jsx("p",{className:"confirm-modal-subtitle",children:Se}),he&&b.jsx("p",{className:"confirm-modal-message",children:he}),b.jsx("div",{className:"input-list",children:Z.map((Ie,Ke)=>b.jsxs("div",{className:"input-item",children:[b.jsx("label",{className:"input-label",children:Ie}),b.jsx("input",{type:"text",className:"input-field",value:Ne[Ke]??"",onChange:Fe=>{Be(Ge=>{const $e=new Map(Ge),Qe=[...$e.get(Te)??[]];return Qe[Ke]=Fe.target.value,$e.set(Te,Qe),$e})},autoFocus:Ke===0})]},Ke))}),b.jsx("div",{className:"input-actions",children:b.jsx("button",{className:"btn btn-primary",disabled:Ne.some(Ie=>!Ie.trim()),onClick:()=>jt(Te,Ne),children:"Submit"})}),b.jsx("button",{className:"permission-abort-link",onClick:()=>jt(Te,["aborted"]),children:"Cancel"})]})},Te)})]}),document.body)]})}const NO=ys("Preferences",{web:()=>Fd(()=>import("./web-OvMaxdX0.js"),[]).then(e=>new e.PreferencesWeb)}),kl=!!window.__PALMIER_SERVE__&&(window.location.hostname==="localhost"||window.location.hostname==="127.0.0.1"),$b=Jn.isNativePlatform();function OO(){const[e,t]=T.useState(""),[r,s]=T.useState(!0),[l,u]=T.useState(!1),[c,f]=T.useState(null),{addPairedHost:d,pairedHosts:m}=qi(),y=Mr();async function g(){const x=e.trim().toUpperCase();if(!x){f("Enter a pairing code.");return}u(!0),f(null);try{let w;if(kl){const z=await fetch("/pair",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:x,label:navigator.userAgent})});if(!z.ok){const O=await z.json().catch(()=>({error:"Connection failed"}));throw new Error(O.error||`HTTP ${z.status}`)}w=await z.json()}else{const z=await fetch(`${Bu}/api/config`);if(!z.ok)throw new Error("Failed to fetch server config");const O=await z.json();if(!O.natsWsUrl)throw new Error("Server has no NATS WebSocket URL configured");const H=await Dx({servers:O.natsWsUrl,authenticator:Ex(O.natsJwt,new TextEncoder().encode(O.natsNkeySeed))}),F=Ou(),oe=`pair.${x}`,U=await H.request(oe,F.encode(JSON.stringify({label:navigator.userAgent})),{timeout:1e4});w=JSON.parse(F.decode(U.data)),await H.close()}const S={hostId:w.hostId,clientToken:w.clientToken,directUrl:kl?window.location.origin:void 0,...w.hostName?{name:w.hostName}:{}};if(d(S),Jn.isNativePlatform()&&dn){await NO.set({key:"hostId",value:w.hostId});try{const{token:z}=await dn.getFcmToken();await fetch(`${Bu}/api/fcm/register`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({hostId:w.hostId,fcmToken:z})})}catch(z){console.warn("FCM token registration failed:",z)}}const N=`/hosts/${encodeURIComponent(w.hostId)}`;y($b&&r?`${N}/pair/setup`:N)}catch(w){const S=w instanceof Error?w.message:String(w);S.includes("timeout")||S.includes("TIMEOUT")||S.includes("503")||S.toLowerCase().includes("no responders")?f("Code not found or expired. Check the code and try again."):f(S)}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:x=>t(x.target.value.toUpperCase()),placeholder:"A7K9M2",className:"form-input form-input-mono pair-code-input",autoFocus:!0,autoComplete:"off",disabled:l})]}),$b&&b.jsxs("label",{className:"pair-checkbox",children:[b.jsx("input",{type:"checkbox",checked:r,onChange:x=>s(x.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:g,disabled:l||!e.trim(),children:[l&&b.jsx("span",{className:"btn-spinner"}),l?"Pairing...":"Pair"]}),m.length>0&&b.jsx("button",{className:"btn btn-secondary btn-full",onClick:()=>y("/"),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 RO(){const e=Mr(),{connected:t,request:r,activeHost:s}=si(),{setHostLanUrl:l,pairedHosts:u}=qi(),c=u.length<=1,[f,d]=T.useState("loading"),[m,y]=T.useState(null),[g,x]=T.useState(null);function w(){e(`/hosts/${encodeURIComponent(s.hostId)}`,{replace:!0})}T.useEffect(()=>{if(!t||f!=="loading")return;let H=!1;return r("host.info").catch(()=>({})).then(F=>{if(H)return;l(s.hostId,F.lan_url??void 0);const oe=F.linked_client_token??null;y(oe);const U=!!oe&&oe!==s.clientToken;d(U?"confirming":"linking")}),()=>{H=!0}},[t,f,s,r,l]),T.useEffect(()=>{if(f!=="linking")return;let H=!1;return(async()=>{try{if(dn){const{token:F}=await dn.getFcmToken();if(!F)throw new Error("Could not read FCM token");await r("device.link",{fcmToken:F})}if(H)return;c?d("wizard"):w()}catch(F){if(H)return;x(F instanceof Error?F.message:String(F)),d("linkError")}})(),()=>{H=!0}},[f]);function S(){d("linking")}function N(){w()}function z(){x(null),d("linking")}const O=f==="confirming"&&ds.createPortal(b.jsx("div",{className:"confirm-modal-overlay",onClick:N,children:b.jsxs("div",{className:"confirm-modal",onClick:H=>H.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:N,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 H=c,F=f==="loading"||f==="confirming"||f==="linking";return b.jsxs("div",{className:"pair-setup",children:[b.jsxs("div",{className:"pair-setup-inner",children:[H&&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:z,children:"Retry"}),b.jsx("button",{className:"btn btn-secondary",onClick:w,children:"Skip linking"})]})]})]}),O]})}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(Ix,{}),b.jsx("div",{className:"pair-setup-actions",children:b.jsx("button",{className:"btn btn-primary btn-full",onClick:w,children:"Finish"})})]})})}function MO(){const e=Mr();return T.useEffect(()=>{if(!dn)return;const t=dn.addListener("deepLink",({path:r})=>e(r));return()=>{t.then(r=>r.remove())}},[e]),null}function DO(){const{pairedHosts:e}=qi();return e.length===0?b.jsx(zl,{to:"/pair",replace:!0}):b.jsx(zl,{to:`/hosts/${encodeURIComponent(e[0].hostId)}`,replace:!0})}function LO(){const{hostId:e}=Yu(),{pairedHosts:t}=qi(),r=t.find(s=>s.hostId===e)??null;return r?b.jsx(vE,{activeHost:r,children:b.jsxs(ax,{children:[b.jsx(br,{index:!0,element:b.jsx(vu,{})}),b.jsx(br,{path:"tasks",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId",element:b.jsx(vu,{})}),b.jsx(br,{path:"runs/:taskId/:runId",element:b.jsx(vu,{})}),b.jsx(br,{path:"pair/setup",element:b.jsx(RO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:".",replace:!0})})]})}):b.jsx(zl,{to:"/",replace:!0})}function zO(){return b.jsxs($_,{children:[b.jsx(MO,{}),b.jsxs(ax,{children:[b.jsx(br,{path:"/",element:b.jsx(DO,{})}),b.jsx(br,{path:"/pair",element:b.jsx(OO,{})}),b.jsx(br,{path:"/hosts/:hostId/*",element:b.jsx(LO,{})}),b.jsx(br,{path:"*",element:b.jsx(zl,{to:"/",replace:!0})})]})]})}fS.createRoot(document.getElementById("root")).render(b.jsx(T.StrictMode,{children:b.jsx(O_,{children:b.jsx(zO,{})})}));export{Id as W};
@@ -1 +1 @@
1
- import{W as i}from"./index-yaoUw47d.js";function o(){const t=window.navigator.connection||window.navigator.mozConnection||window.navigator.webkitConnection;let n="unknown";const e=t?t.type||t.effectiveType:null;if(e&&typeof e=="string")switch(e){case"bluetooth":case"cellular":n="cellular";break;case"none":n="none";break;case"ethernet":case"wifi":case"wimax":n="wifi";break;case"other":case"unknown":n="unknown";break;case"slow-2g":case"2g":case"3g":n="cellular";break;case"4g":n="wifi";break}return n}class s extends i{constructor(){super(),this.handleOnline=()=>{const e={connected:!0,connectionType:o()};this.notifyListeners("networkStatusChange",e)},this.handleOffline=()=>{const n={connected:!1,connectionType:"none"};this.notifyListeners("networkStatusChange",n)},typeof window<"u"&&(window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline))}async getStatus(){if(!window.navigator)throw this.unavailable("Browser does not support the Network Information API");const n=window.navigator.onLine,e=o();return{connected:n,connectionType:n?e:"none"}}}const r=new s;export{r as Network,s as NetworkWeb};
1
+ import{W as i}from"./index-DJ-f-zPM.js";function o(){const t=window.navigator.connection||window.navigator.mozConnection||window.navigator.webkitConnection;let n="unknown";const e=t?t.type||t.effectiveType:null;if(e&&typeof e=="string")switch(e){case"bluetooth":case"cellular":n="cellular";break;case"none":n="none";break;case"ethernet":case"wifi":case"wimax":n="wifi";break;case"other":case"unknown":n="unknown";break;case"slow-2g":case"2g":case"3g":n="cellular";break;case"4g":n="wifi";break}return n}class s extends i{constructor(){super(),this.handleOnline=()=>{const e={connected:!0,connectionType:o()};this.notifyListeners("networkStatusChange",e)},this.handleOffline=()=>{const n={connected:!1,connectionType:"none"};this.notifyListeners("networkStatusChange",n)},typeof window<"u"&&(window.addEventListener("online",this.handleOnline),window.addEventListener("offline",this.handleOffline))}async getStatus(){if(!window.navigator)throw this.unavailable("Browser does not support the Network Information API");const n=window.navigator.onLine,e=o();return{connected:n,connectionType:n?e:"none"}}}const r=new s;export{r as Network,s as NetworkWeb};
@@ -1 +1 @@
1
- import{W as t}from"./index-yaoUw47d.js";class s extends t{constructor(){super(),this.handleVisibilityChange=()=>{const e={isActive:document.hidden!==!0};this.notifyListeners("appStateChange",e),document.hidden?this.notifyListeners("pause",null):this.notifyListeners("resume",null)},document.addEventListener("visibilitychange",this.handleVisibilityChange,!1)}exitApp(){throw this.unimplemented("Not implemented on web.")}async getInfo(){throw this.unimplemented("Not implemented on web.")}async getLaunchUrl(){return{url:""}}async getState(){return{isActive:document.hidden!==!0}}async minimizeApp(){throw this.unimplemented("Not implemented on web.")}async toggleBackButtonHandler(){throw this.unimplemented("Not implemented on web.")}async getAppLanguage(){return{value:navigator.language.split("-")[0].toLowerCase()}}}export{s as AppWeb};
1
+ import{W as t}from"./index-DJ-f-zPM.js";class s extends t{constructor(){super(),this.handleVisibilityChange=()=>{const e={isActive:document.hidden!==!0};this.notifyListeners("appStateChange",e),document.hidden?this.notifyListeners("pause",null):this.notifyListeners("resume",null)},document.addEventListener("visibilitychange",this.handleVisibilityChange,!1)}exitApp(){throw this.unimplemented("Not implemented on web.")}async getInfo(){throw this.unimplemented("Not implemented on web.")}async getLaunchUrl(){return{url:""}}async getState(){return{isActive:document.hidden!==!0}}async minimizeApp(){throw this.unimplemented("Not implemented on web.")}async toggleBackButtonHandler(){throw this.unimplemented("Not implemented on web.")}async getAppLanguage(){return{value:navigator.language.split("-")[0].toLowerCase()}}}export{s as AppWeb};
@@ -1 +1 @@
1
- import{W as p}from"./index-yaoUw47d.js";class f extends p{constructor(){super(...arguments),this.group="CapacitorStorage"}async configure({group:e}){typeof e=="string"&&(this.group=e)}async get(e){return{value:this.impl.getItem(this.applyPrefix(e.key))}}async set(e){this.impl.setItem(this.applyPrefix(e.key),e.value)}async remove(e){this.impl.removeItem(this.applyPrefix(e.key))}async keys(){return{keys:this.rawKeys().map(t=>t.substring(this.prefix.length))}}async clear(){for(const e of this.rawKeys())this.impl.removeItem(e)}async migrate(){var e;const t=[],s=[],n="_cap_",o=Object.keys(this.impl).filter(i=>i.indexOf(n)===0);for(const i of o){const r=i.substring(n.length),a=(e=this.impl.getItem(i))!==null&&e!==void 0?e:"",{value:l}=await this.get({key:r});typeof l=="string"?s.push(r):(await this.set({key:r,value:a}),t.push(r))}return{migrated:t,existing:s}}async removeOld(){const e="_cap_",t=Object.keys(this.impl).filter(s=>s.indexOf(e)===0);for(const s of t)this.impl.removeItem(s)}get impl(){return window.localStorage}get prefix(){return this.group==="NativeStorage"?"":`${this.group}.`}rawKeys(){return Object.keys(this.impl).filter(e=>e.indexOf(this.prefix)===0)}applyPrefix(e){return this.prefix+e}}export{f as PreferencesWeb};
1
+ import{W as p}from"./index-DJ-f-zPM.js";class f extends p{constructor(){super(...arguments),this.group="CapacitorStorage"}async configure({group:e}){typeof e=="string"&&(this.group=e)}async get(e){return{value:this.impl.getItem(this.applyPrefix(e.key))}}async set(e){this.impl.setItem(this.applyPrefix(e.key),e.value)}async remove(e){this.impl.removeItem(this.applyPrefix(e.key))}async keys(){return{keys:this.rawKeys().map(t=>t.substring(this.prefix.length))}}async clear(){for(const e of this.rawKeys())this.impl.removeItem(e)}async migrate(){var e;const t=[],s=[],n="_cap_",o=Object.keys(this.impl).filter(i=>i.indexOf(n)===0);for(const i of o){const r=i.substring(n.length),a=(e=this.impl.getItem(i))!==null&&e!==void 0?e:"",{value:l}=await this.get({key:r});typeof l=="string"?s.push(r):(await this.set({key:r,value:a}),t.push(r))}return{migrated:t,existing:s}}async removeOld(){const e="_cap_",t=Object.keys(this.impl).filter(s=>s.indexOf(e)===0);for(const s of t)this.impl.removeItem(s)}get impl(){return window.localStorage}get prefix(){return this.group==="NativeStorage"?"":`${this.group}.`}rawKeys(){return Object.keys(this.impl).filter(e=>e.indexOf(this.prefix)===0)}applyPrefix(e){return this.prefix+e}}export{f as PreferencesWeb};
@@ -8,7 +8,7 @@
8
8
  <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
9
9
  <title>Palmier</title>
10
10
  <meta name="description" content="Run tasks from anywhere, approve actions on the go, and let your agents use your phone’s built-in capabilities when needed." />
11
- <script type="module" crossorigin src="/assets/index-yaoUw47d.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-DJ-f-zPM.js"></script>
12
12
  <link rel="stylesheet" crossorigin href="/assets/index-7Atn3jMz.css">
13
13
  <link rel="manifest" href="/manifest.webmanifest"><script id="vite-plugin-pwa:register-sw" src="/registerSW.js"></script></head>
14
14
  <body>
@@ -619,10 +619,10 @@ export function createRpcHandler(config, nc) {
619
619
  const entry = (config.agents ?? []).find((a) => a.key === params.key);
620
620
  if (!entry)
621
621
  return { error: `Unknown agent: ${params.key}` };
622
+ if (!entry.version)
623
+ return { error: `Agent ${params.key} is not managed by Palmier` };
622
624
  if (!entry.npmPackage)
623
625
  return { error: `Agent ${params.key} has no npm package` };
624
- if (!entry.palmierManaged)
625
- return { error: `Agent ${params.key} is not managed by Palmier` };
626
626
  const error = await performAgentUpdate(entry.npmPackage);
627
627
  if (error)
628
628
  return { error };
package/dist/types.d.ts CHANGED
@@ -11,8 +11,8 @@ export interface HostConfig {
11
11
  supportsPermissions?: boolean;
12
12
  supportsYolo?: boolean;
13
13
  npmPackage?: string;
14
+ /** Runtime marker for "managed by Palmier" — present iff Palmier installed/manages this agent. */
14
15
  version?: string;
15
- palmierManaged?: boolean;
16
16
  }>;
17
17
  httpPort?: number;
18
18
  /** OS network interface name of the IPv4 default route, captured on the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "palmier",
3
- "version": "0.9.17",
3
+ "version": "0.9.18",
4
4
  "description": "Palmier host CLI - provisions, executes tasks, and serves NATS RPC",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Hongxu Cai",