@sma1lboy/rove 0.9.276 → 0.9.277-next.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{chunk-mkfc9a09.js → chunk-0a65j1zj.js} +1 -1
- package/dist/cli/{chunk-xb3p11g0.js → chunk-0rvydb9q.js} +1 -1
- package/dist/cli/chunk-1g6vhgfe.js +14 -0
- package/dist/cli/{chunk-eq7vey2j.js → chunk-1vxtd8rh.js} +2 -2
- package/dist/cli/chunk-1wwqf6kx.js +3 -0
- package/dist/cli/{chunk-1jjqk7sq.js → chunk-2kbzb24j.js} +1 -1
- package/dist/cli/chunk-2kt0mfvf.js +2 -0
- package/dist/cli/{chunk-mz1ffkqb.js → chunk-2vph030z.js} +3 -3
- package/dist/cli/{chunk-nr7e3e82.js → chunk-2y70y8na.js} +1 -1
- package/dist/cli/{chunk-jckx79gk.js → chunk-36eyrv4r.js} +3 -3
- package/dist/cli/chunk-37fas9aj.js +2 -0
- package/dist/cli/chunk-3dhv5n19.js +2 -0
- package/dist/cli/{chunk-zkp6nty3.js → chunk-3x5g06mw.js} +1 -1
- package/dist/cli/{chunk-c6fy8xew.js → chunk-3y0z478f.js} +1 -1
- package/dist/cli/{chunk-91tcwxph.js → chunk-4w4tpsqx.js} +1 -1
- package/dist/cli/chunk-5apxck3d.js +97 -0
- package/dist/cli/chunk-5vrg6h71.js +3 -0
- package/dist/cli/{chunk-k1pwp155.js → chunk-5xpvd182.js} +1 -1
- package/dist/cli/{chunk-8dd60adw.js → chunk-5yh5trgy.js} +1 -1
- package/dist/cli/{chunk-r7ntkd6y.js → chunk-61cn88e7.js} +1 -1
- package/dist/cli/{chunk-e3cd4qd2.js → chunk-671ak750.js} +2 -2
- package/dist/cli/{chunk-82apkcrk.js → chunk-676f3tva.js} +1 -1
- package/dist/cli/chunk-6hcyvg0m.js +3 -0
- package/dist/cli/{chunk-h2gznz46.js → chunk-6mg5zp8y.js} +1 -1
- package/dist/cli/chunk-6q4br0pt.js +2 -0
- package/dist/cli/chunk-6wfhq8xd.js +4 -0
- package/dist/cli/{chunk-3xkhcfet.js → chunk-748656h7.js} +3 -3
- package/dist/cli/{chunk-2kqxz9a4.js → chunk-7bakcyes.js} +1 -1
- package/dist/cli/{chunk-yk9b8zgn.js → chunk-7kgcy89w.js} +1 -1
- package/dist/cli/{chunk-e3t1zbv1.js → chunk-8qkyd589.js} +1 -1
- package/dist/cli/chunk-9ckvdy0j.js +3 -0
- package/dist/cli/{chunk-5e9y8aw5.js → chunk-9fdy8vne.js} +1 -1
- package/dist/cli/chunk-9x2xd1rz.js +2 -0
- package/dist/cli/{chunk-je80r59s.js → chunk-9zswhjkv.js} +1 -1
- package/dist/cli/{chunk-c7mz2aq0.js → chunk-aq4j8ar4.js} +1 -1
- package/dist/cli/{chunk-dt676ks9.js → chunk-aqwckba5.js} +1 -1
- package/dist/cli/chunk-atg13xab.js +3 -0
- package/dist/cli/{chunk-wvqn1t55.js → chunk-bagwgxsg.js} +1 -1
- package/dist/cli/{chunk-syn0tfwy.js → chunk-bcyex84w.js} +1 -1
- package/dist/cli/chunk-bv050ssb.js +8 -0
- package/dist/cli/chunk-bykqhbvy.js +2 -0
- package/dist/cli/{chunk-81thm1eb.js → chunk-ca4x8s96.js} +3 -3
- package/dist/cli/{chunk-syfs63r2.js → chunk-cakyme4s.js} +1 -1
- package/dist/cli/{chunk-63cwjceg.js → chunk-ccmke5sx.js} +1 -1
- package/dist/cli/{chunk-5nvg3ek8.js → chunk-cf3vpsm5.js} +1 -1
- package/dist/cli/{chunk-zat16a83.js → chunk-d552cvb2.js} +1 -1
- package/dist/cli/{chunk-awh7np6x.js → chunk-dsdtq087.js} +1 -1
- package/dist/cli/{chunk-d0hpes59.js → chunk-e58kj4gm.js} +1 -1
- package/dist/cli/chunk-ee314raa.js +2 -0
- package/dist/cli/{chunk-f76gzvq3.js → chunk-fgtc1xq9.js} +1 -1
- package/dist/cli/{chunk-h7vwn62z.js → chunk-fq2pefc5.js} +1 -1
- package/dist/cli/{chunk-4117kgmx.js → chunk-g4p5znv1.js} +1 -1
- package/dist/cli/{chunk-1ca2j9w6.js → chunk-g9xknhjq.js} +1 -1
- package/dist/cli/chunk-gbd5j3dv.js +2 -0
- package/dist/cli/{chunk-4xvmrg86.js → chunk-ggjmcqpt.js} +1 -1
- package/dist/cli/chunk-hv79ys32.js +1 -1
- package/dist/cli/chunk-hz1x3hak.js +3 -0
- package/dist/cli/{chunk-h64rsbrx.js → chunk-hzz020xx.js} +1 -1
- package/dist/cli/{chunk-ma21srvx.js → chunk-j1qy79fd.js} +1 -1
- package/dist/cli/chunk-j9tsdn1d.js +2 -0
- package/dist/cli/chunk-jejmt4k0.js +140 -0
- package/dist/cli/chunk-jj5f4n51.js +1 -1
- package/dist/cli/{chunk-x3n4y5sp.js → chunk-k225696b.js} +1 -1
- package/dist/cli/{chunk-d7xbm9jp.js → chunk-kag7cfbr.js} +1 -1
- package/dist/cli/{chunk-283vd9h7.js → chunk-kdnk8m5j.js} +1 -1
- package/dist/cli/{chunk-xd93fm1k.js → chunk-kxp04jnp.js} +1 -1
- package/dist/cli/chunk-m4z6kepz.js +3 -0
- package/dist/cli/{chunk-372g44dg.js → chunk-mjyhy152.js} +1 -1
- package/dist/cli/chunk-mqvkd2g1.js +2 -0
- package/dist/cli/{chunk-t4qr9sv4.js → chunk-mvtqstte.js} +1 -1
- package/dist/cli/{chunk-m2a19yt4.js → chunk-mxx0y791.js} +1 -1
- package/dist/cli/{chunk-d9643dwf.js → chunk-n2zgej1a.js} +1 -1
- package/dist/cli/{chunk-xn2f56tg.js → chunk-n94vzkbe.js} +1 -1
- package/dist/cli/{chunk-9gh8kgjs.js → chunk-njncqdwf.js} +1 -1
- package/dist/cli/{chunk-t52gzaeb.js → chunk-nw092jak.js} +1 -1
- package/dist/cli/{chunk-gafkp74h.js → chunk-pfagrkt6.js} +1 -1
- package/dist/cli/{chunk-511103e8.js → chunk-pnrftncm.js} +1 -1
- package/dist/cli/{chunk-9c3brkb3.js → chunk-pqr6td4z.js} +1 -1
- package/dist/cli/{chunk-tvdrvgen.js → chunk-qcjkactr.js} +1 -1
- package/dist/cli/{chunk-v1r83m3n.js → chunk-qs359899.js} +1 -1
- package/dist/cli/{chunk-n6marmjn.js → chunk-qzzmd63x.js} +2 -3
- package/dist/cli/{chunk-fn7ffyam.js → chunk-r2bb8b11.js} +1 -1
- package/dist/cli/chunk-rjy900p4.js +4 -0
- package/dist/cli/{chunk-b035pej7.js → chunk-rmsdybs3.js} +1 -1
- package/dist/cli/{chunk-6mtfafaw.js → chunk-rztqccs3.js} +1 -1
- package/dist/cli/chunk-s1308b3d.js +63 -0
- package/dist/cli/{chunk-ne6x6g2c.js → chunk-se00fc8v.js} +1 -1
- package/dist/cli/{chunk-zcrs4sm2.js → chunk-shtm72c0.js} +1 -1
- package/dist/cli/{chunk-gq57he03.js → chunk-t9vjj8sy.js} +1 -1
- package/dist/cli/{chunk-0d7517kk.js → chunk-ta1p2nwa.js} +1 -1
- package/dist/cli/chunk-teh40faw.js +1 -1
- package/dist/cli/{chunk-eyvw70yb.js → chunk-tnatqcy7.js} +1 -1
- package/dist/cli/{chunk-mq88bvj6.js → chunk-tt58819p.js} +1 -1
- package/dist/cli/{chunk-pdq3ya2e.js → chunk-tw9tfs1d.js} +2 -2
- package/dist/cli/chunk-v6dz59gy.js +2 -0
- package/dist/cli/chunk-v6v272b3.js +3 -0
- package/dist/cli/{chunk-hhcmzs67.js → chunk-vkv1v3xn.js} +6 -28
- package/dist/cli/chunk-vkz6kkmm.js +24 -0
- package/dist/cli/chunk-vp29jgbt.js +4 -0
- package/dist/cli/chunk-vpsarakj.js +2 -0
- package/dist/cli/{chunk-745pg3xm.js → chunk-vr2r2ncm.js} +1 -1
- package/dist/cli/{chunk-3y9xzbqh.js → chunk-vvqwgcge.js} +1 -1
- package/dist/cli/{chunk-m73x5nry.js → chunk-vwpf55cr.js} +2 -2
- package/dist/cli/{chunk-vz0f8e8q.js → chunk-vytrhm50.js} +1 -1
- package/dist/cli/{chunk-c63vgbkw.js → chunk-w7v71t7e.js} +1 -1
- package/dist/cli/{chunk-hcvp84b3.js → chunk-wfgrn8p2.js} +1 -1
- package/dist/cli/chunk-wzss4pzh.js +3 -0
- package/dist/cli/chunk-x1ghdmp1.js +1 -1
- package/dist/cli/chunk-x1jxxmtc.js +3 -0
- package/dist/cli/{chunk-d7f022eb.js → chunk-x83xbzjd.js} +3 -3
- package/dist/cli/{chunk-22rgewg0.js → chunk-x85rcep5.js} +1 -1
- package/dist/cli/{chunk-j9b285x6.js → chunk-x89zw7br.js} +1 -1
- package/dist/cli/{chunk-ccwe9n56.js → chunk-xg42e2ff.js} +1 -1
- package/dist/cli/{chunk-jfcn77n9.js → chunk-xte4phd1.js} +1 -1
- package/dist/cli/chunk-y8b2p44q.js +1 -1
- package/dist/cli/chunk-ys6v36ph.js +2 -0
- package/dist/cli/{chunk-n8t4y0bj.js → chunk-yzdrhytj.js} +1 -1
- package/dist/cli/{chunk-qna1s1r4.js → chunk-z3qz6enf.js} +1 -1
- package/dist/cli/chunk-z3wrbtcq.js +22 -0
- package/dist/cli/{chunk-cfzg8q3e.js → chunk-z43e08kw.js} +1 -1
- package/dist/cli/{chunk-ehm9abge.js → chunk-zpwvjt14.js} +7 -5
- package/dist/cli/{chunk-k235z3ct.js → chunk-zrf93zrx.js} +1 -1
- package/dist/cli/index.js +9 -12
- package/dist/cli/pty-host-node.mjs +1 -3
- package/dist/cli/rove-run.js +1 -1
- package/dist/completions/rove.bash +1 -1
- package/dist/completions/rove.fish +1 -1
- package/dist/completions/rove.zsh +1 -1
- package/dist/skills/rove/SKILL.md +4 -3
- package/dist/skills/rove/references/api-flags.md +12 -5
- package/dist/web/assets/index-BVQbpUea.css +1 -0
- package/dist/web/assets/index-Cn_7vMHX.js +152 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-600-normal-8K4wrrwR.woff +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-600-normal-EVf6-Yzo.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
- package/dist/web/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-600-normal-H7WoG9Et.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-600-normal-mc2nkWzM.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-600-normal-BfsvjouI.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-600-normal-C8RAYTDA.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-600-normal-BfB_LPfz.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-600-normal-DObL3zCW.woff +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-600-normal-OWROknRo.woff +0 -0
- package/dist/web/index.html +2 -2
- package/dist/web/relay/index.html +34 -0
- package/dist/web-ui/assets/{harness-pEyVtWV4.js → harness-C7ciHx2w.js} +2 -2
- package/dist/web-ui/assets/{index-Dyg-qcgB.js → index-B1FLht5L.js} +2 -2
- package/dist/web-ui/assets/{index-Bsn8NuKa.css → index-BDIkPexK.css} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/cli/chunk-1eef3z5v.js +0 -3
- package/dist/cli/chunk-1n03wzx4.js +0 -3
- package/dist/cli/chunk-387w0db1.js +0 -2
- package/dist/cli/chunk-4a05fgdh.js +0 -2
- package/dist/cli/chunk-59p3h5e9.js +0 -2
- package/dist/cli/chunk-6xga1a2d.js +0 -3
- package/dist/cli/chunk-84pvn784.js +0 -2
- package/dist/cli/chunk-883fyezq.js +0 -3
- package/dist/cli/chunk-a4r45qdn.js +0 -3
- package/dist/cli/chunk-brgfsm5v.js +0 -2
- package/dist/cli/chunk-bw98jn7g.js +0 -18
- package/dist/cli/chunk-cbrt4s7m.js +0 -3
- package/dist/cli/chunk-d9e4ssy7.js +0 -12
- package/dist/cli/chunk-dgx02565.js +0 -3
- package/dist/cli/chunk-g4dtqbrj.js +0 -2
- package/dist/cli/chunk-gctqthxq.js +0 -97
- package/dist/cli/chunk-hmjg1qh3.js +0 -2
- package/dist/cli/chunk-jn10xeft.js +0 -2
- package/dist/cli/chunk-nbpq1tkx.js +0 -98
- package/dist/cli/chunk-ns35rdyk.js +0 -3
- package/dist/cli/chunk-pap7k3b4.js +0 -3
- package/dist/cli/chunk-r7kmn4js.js +0 -2
- package/dist/cli/chunk-tz373e5w.js +0 -3
- package/dist/cli/chunk-vp171as9.js +0 -65
- package/dist/cli/chunk-vtcr71fs.js +0 -8
- package/dist/cli/chunk-w7v4jzwy.js +0 -3
- package/dist/cli/chunk-xv3217yv.js +0 -2
- package/dist/cli/chunk-yhytkwpv.js +0 -2
- package/dist/web/assets/index-C5t3gibI.css +0 -1
- package/dist/web/assets/index-Djp7M6r8.js +0 -122
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{RemoteOrchestrator}from"./chunk-
|
|
2
|
+
import{RemoteOrchestrator}from"./chunk-v6v272b3.js";import{dedupeMachines,discoverMachine,duplicateAliasOf,learnedFrom,listMachines,readMachines,setMachineIdentity,startTunnel,updateMachine}from"./chunk-vytrhm50.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{RoveDaemonClient}from"./chunk-qzzmd63x.js";import{logClient,logClientError}from"./chunk-0g4wc808.js";function discoverReason(failure){switch(failure.code){case"SSH_FAILED":return!failure.ssh||failure.ssh==="unknown"?"ssh-failed":failure.ssh;case"NO_ROVE":return"no-rove";case"NO_DAEMON":return"no-daemon";default:return"bad-status"}}var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map},PEER_CHANNELS=["task.snapshot","engine-state","worktree.changes","task.tokens"];class MachineHub{slots=new Map;machinesAcc=createStateCell([],"machines.status");tasksAcc=createStateCell([],"machines.tasks");liveAcc=createStateCell(NO_LIVE,"machines.live");disposed=!1;machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}remoteTaskIds(){let ids=new Set;for(let slot of this.slots.values())for(let task of slot.tasks)ids.add(String(task.id));return ids}sync(entries=dedupeMachines(listMachines())){if(this.disposed)return;let wanted=new Map(entries.map((entry)=>[entry.alias,entry])),fresh=[];for(let[alias,slot]of this.slots){let next=wanted.get(alias);if(next&&sameAddress(slot.entry,next))slot.entry=next;else this.drop(alias)}for(let entry of entries){if(this.slots.has(entry.alias))continue;this.slots.set(entry.alias,{entry,tasks:[]}),fresh.push(entry)}if(fresh.length===0&&wanted.size===this.slots.size&&this.machinesAcc.get().length===wanted.size)return;let known=new Map(this.machinesAcc.get().map((row)=>[row.alias,row]));this.machinesAcc.set([...this.slots.values()].map((slot)=>known.get(slot.entry.alias)??{alias:slot.entry.alias,hostLabel:slot.entry.alias,state:"connecting"})),this.republishTasks(),this.republishLive();for(let entry of fresh)this.connect(entry)}drop(alias){let slot=this.slots.get(alias);if(!slot)return;this.slots.delete(alias),slot.unsubscribe?.(),slot.orchestrator?.dispose(),slot.tunnel?.stop()}async connect(entry){let slot=this.slots.get(entry.alias);if(!slot||this.disposed)return;let found=await discoverMachine(entry.alias,entry);if(this.disposed||this.slots.get(entry.alias)!==slot)return;let sockets=found.ok?{daemon:found.status.socketPath,pty:found.status.ptySocketPath}:entry.sockets,failed=found.ok?{}:{error:found.message,reason:discoverReason(found)};if(!sockets){this.setStatus(entry.alias,{state:"offline",...failed});return}if(!found.ok)this.setStatus(entry.alias,failed);let learned=found.ok?learnedFrom(found):{};if(found.ok)updateMachine(entry.alias,learned);let tunnel=startTunnel({alias:entry.alias,config:{...entry,...learned,sockets},remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(slot.tunnel=tunnel,tunnel.state()==="unsupported"){this.setStatus(entry.alias,{state:"unsupported",error:"SSH unix-socket forwarding is not available on Windows",reason:"no-forwarding"});return}if(tunnel.onState((state)=>{if(this.slots.get(entry.alias)!==slot)return;if(state==="online")this.openOrchestrator(entry,tunnel);else if(state==="offline"){let known=this.machinesAcc.get().find((row)=>row.alias===entry.alias)?.reason;this.setStatus(entry.alias,{state:"offline",reason:known??"lost"}),this.republishTasks()}}),tunnel.state()==="online")await this.openOrchestrator(entry,tunnel)}async openOrchestrator(entry,tunnel){let slot=this.slots.get(entry.alias);if(!slot||this.disposed||slot.orchestrator)return;let client=new RoveDaemonClient(tunnel.daemonSocketPath),orchestrator=new RemoteOrchestrator(client,{role:"gui",channels:PEER_CHANNELS,expectForeignHome:!0,onPeerIdentity:(peer)=>this.onPeerIdentity(entry.alias,peer)});slot.orchestrator=orchestrator;try{if(await orchestrator.init(),this.slots.get(entry.alias)!==slot)return}catch(err){let message=err instanceof Error?err.message:String(err);this.setStatus(entry.alias,{state:classifyHandshakeFailure(message),error:message,reason:"handshake"}),logClientError("machines",err);return}let stopTasks=orchestrator.tasksSignal().subscribe(()=>{slot.tasks=orchestrator.tasksSignal().get(),this.republishTasks()}),stopConnection=orchestrator.connectionStateSignal().subscribe(()=>{let connected=orchestrator.connectionStateSignal().get()==="online";if(this.slots.get(entry.alias)!==slot)return;this.setStatus(entry.alias,connected?{state:"online",error:void 0,reason:void 0}:{state:"offline",reason:"lost"}),this.republishTasks()}),live=[orchestrator.engineStateSignal(),orchestrator.worktreeChangesSignal(),orchestrator.rowTokensSignal()].map((signal)=>signal.subscribe(()=>this.republishLive()));slot.unsubscribe=()=>{stopTasks(),stopConnection();for(let stop of live)stop()},slot.tasks=orchestrator.tasksSignal().get(),this.setStatus(entry.alias,{state:"online",version:orchestrator.daemonVersionSignal().get()??void 0,error:void 0,reason:void 0}),this.republishTasks(),this.republishLive(),logClient("machines",`${entry.alias} online (${slot.tasks.length} tasks)`)}republishLive(){let activity=new Map,changes=new Map,tokens=new Map;for(let slot of this.slots.values()){let o=slot.orchestrator;if(!o)continue;for(let[id,state]of o.engineStateSignal().get())activity.set(id,state);for(let[path,change]of o.worktreeChangesSignal().get()??[])changes.set(path,change);for(let[id,chips]of o.rowTokensSignal().get())tokens.set(id,chips)}this.liveAcc.set({activity,changes,tokens})}onPeerIdentity(alias,peer){if(!peer.hostname&&!peer.homeDir)return;let identity={hostname:peer.hostname,homeDir:peer.homeDir,daemonPid:peer.daemonPid};setMachineIdentity(alias,identity);let duplicate=duplicateAliasOf(readMachines(loadStateFile()),alias,identity);this.setStatus(alias,{hostname:peer.hostname||void 0,version:peer.roveVersion||void 0,...duplicate?{duplicateOf:duplicate}:{}})}setStatus(alias,patch){let next=this.machinesAcc.get().map((row)=>row.alias===alias?{...row,...patch}:row);this.machinesAcc.set(next)}republishTasks(){let merged=[];for(let slot of this.slots.values()){let status=this.machinesAcc.get().find((row)=>row.alias===slot.entry.alias);if(status?.duplicateOf)continue;let hostLabel=status?.hostLabel||slot.entry.alias,stale=status?.state!=="online";for(let task of slot.tasks)merged.push(stampOrigin(task,slot.entry.alias,hostLabel,stale))}this.tasksAcc.set(merged)}dispose(){this.disposed=!0;for(let alias of[...this.slots.keys()])this.drop(alias)}}function classifyHandshakeFailure(message){return/protocol v\d/i.test(message)?"mismatch":"offline"}function sameAddress(a,b){return a.host===b.host&&a.user===b.user&&a.port===b.port&&JSON.stringify(a.auth)===JSON.stringify(b.auth)}function stampOrigin(task,machineId,hostLabel,stale=!1){return{...task,origin:{machineId,hostLabel,...stale?{stale:!0}:{}}}}
|
|
3
3
|
export{MachineHub,stampOrigin};
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{DAEMON_CHANNELS}from"./chunk-96kvwzj8.js";import{logClientError}from"./chunk-0g4wc808.js";import{samePath}from"./chunk-pn5ygqn6.js";import{preRenameRuntimePaths}from"./chunk-f8gg8cqh.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{connect}from"net";import{StringDecoder}from"string_decoder";
|
|
3
|
-
`).filter(Boolean).sort()[0];return root?`root:${root}`:void 0}var memo=new Map;function repoIdOf(path){if(!path)return;if(memo.has(path))return memo.get(path);if(!existsSync(path))return;let id=computeRepoId(path);return memo.set(path,id),id}function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"||status==="script_failed"}var ROUTINE_RESPONSE_MAX_CHARS=32000,ROUTINE_RESPONSE_WINDOW_MS=7200000;function routineRunResponseState(run,nowMs){if(run.response)return"responded";if(run.status!=="dispatched"&&run.status!=="revived")return null;if(run.deliveryStatus==="missing")return"missing";if(run.deliveryStatus==="awaiting")return"awaiting";return nowMs-Date.parse(run.at)>ROUTINE_RESPONSE_WINDOW_MS?"missing":"awaiting"}var GATE_QUESTION_MAX=500,GATE_CONTEXT_MAX=4000,GATE_OPTIONS_MAX=6;function gateInboxKey(gateId){return`\x00gate\x00${gateId}`}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","dead","routine_failed","report_missing","decision_needed"];function isRoutineInboxState(state){return state==="routine_failed"}function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(isRoutineInboxState(item.state)&&item.detail?.routine)return`\x00${item.state}\x00${item.detail.routine.automationId}`;if(item.state==="report_missing"&&item.detail?.delivery)return`\x00delivery\x00${item.detail.delivery.id}`;if(item.state==="decision_needed"&&item.detail?.gate)return gateInboxKey(item.detail.gate.id);return`${item.taskId}\x00${item.tabId??""}`}var DELIVERY_OUTCOMES=["done","partial","blocked","failed"],DELIVERY_SUMMARY_MAX_CHARS=32000,DELIVERY_EVIDENCE_MAX_ITEMS=50,DELIVERY_EVIDENCE_MAX_CHARS=2000,DELIVERY_NEXT_MAX_CHARS=4000,DELIVERY_PROMPT_HEAD_CHARS=200,MAX_DELIVERIES_PER_TASK=50,DELIVERY_STALL_MS=600000;function deliveryFooter(deliveryId,api){return`[ROVE] When this turn ends, report: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026]`}var SKIP_REASONS=["task-missing","awaiting-owner","report-missing","quota","engine-error","engine-dead","awaiting-permission","busy"],SHOULD_RUN_SKIP_EXIT_CODE=3;function parseSkipVerdict(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(raw.run!==!1||!SKIP_REASONS.includes(raw.reason))return;let text=(v)=>typeof v==="string"&&v.length>0?v:void 0;return{run:!1,reason:raw.reason,...text(raw.detail)?{detail:raw.detail}:{},...text(raw.until)?{until:raw.until}:{},...Array.isArray(raw.gateIds)?{gateIds:raw.gateIds.filter((g)=>typeof g==="string")}:{}}}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var DAEMON_PROTOCOL_VERSION=5,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;return!samePath(daemonHome,clientHome)}var BLOCKING_RPCS=new Set(["api.invoke","ui.prompt","task.land","workitem.start","automation.runNow","pr.rerunFailedChecks","pr.reviewComments","task.ensureWorktree","task.spawn","task.ensureMain","task.moveToProject","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove","task.checkpoint","task.rewind","task.exportBranch"]),PTY_STOP_REFUSED="PtyStopRefused";function displayTaskTitle(task){return task.title||task.branch||task.worktreePath||task.repo||"scratch"}function serializeTask(task){let repoId=repoIdOf(task.repo);return{id:task.id,title:displayTaskTitle(task),repo:task.repo,branch:task.branch,worktreePath:task.worktreePath,kind:task.kind??"task",...task.scratch?{scratch:!0}:{},...task.noProject?{noProject:!0}:{},...task.routine?{routine:task.routine}:{},status:task.status,pinned:task.pinned??!1,...task.archived?{archived:!0}:{},vendor:task.vendor,command:task.command,prStatus:task.prStatus,modelEffort:task.modelEffort,model:task.model,tier:task.tier,groupId:task.groupId,observedLanguage:task.observedLanguage,deletion:task.deletion,quotaResume:task.quotaResume,linkedWorkItem:task.linkedWorkItem,dispatcher:task.dispatcher,...task.parentTaskId?{parentTaskId:task.parentTaskId}:{},...task.sharesWorkspaceOf?{sharesWorkspaceOf:task.sharesWorkspaceOf}:{},...task.cwdSubpath?{cwdSubpath:task.cwdSubpath}:{},...task.ptyAlias?{ptyAlias:task.ptyAlias}:{},...task.extraRepos?.length?{extraRepos:task.extraRepos}:{},...task.workspace?{workspace:task.workspace}:{},...task.sessionPrs?.length?{sessionPrs:task.sessionPrs}:{},requireReport:task.requireReport,prompt:task.prompt,baseRef:task.baseRef,worktreeName:task.worktreeName,report:task.report,...repoId?{repoId}:{},createdAt:task.createdAt,updatedAt:task.updatedAt}}function frameToLine(frame){return`${JSON.stringify(frame)}
|
|
2
|
+
import{DAEMON_CHANNELS}from"./chunk-96kvwzj8.js";import{logClientError}from"./chunk-0g4wc808.js";import{samePath}from"./chunk-pn5ygqn6.js";import{preRenameRuntimePaths}from"./chunk-f8gg8cqh.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{connect}from"net";import{StringDecoder}from"string_decoder";function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"||status==="script_failed"}var ROUTINE_RESPONSE_MAX_CHARS=32000,ROUTINE_RESPONSE_WINDOW_MS=7200000;function routineRunResponseState(run,nowMs){if(run.response)return"responded";if(run.status!=="dispatched"&&run.status!=="revived")return null;if(run.deliveryStatus==="missing")return"missing";if(run.deliveryStatus==="awaiting")return"awaiting";return nowMs-Date.parse(run.at)>ROUTINE_RESPONSE_WINDOW_MS?"missing":"awaiting"}var GATE_QUESTION_MAX=500,GATE_CONTEXT_MAX=4000,GATE_OPTIONS_MAX=6;function gateInboxKey(gateId){return`\x00gate\x00${gateId}`}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","dead","routine_failed","report_missing","decision_needed"];function isRoutineInboxState(state){return state==="routine_failed"}function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(isRoutineInboxState(item.state)&&item.detail?.routine)return`\x00${item.state}\x00${item.detail.routine.automationId}`;if(item.state==="report_missing"&&item.detail?.delivery)return`\x00delivery\x00${item.detail.delivery.id}`;if(item.state==="decision_needed"&&item.detail?.gate)return gateInboxKey(item.detail.gate.id);return`${item.taskId}\x00${item.tabId??""}`}var DELIVERY_OUTCOMES=["done","partial","blocked","failed"],DELIVERY_SUMMARY_MAX_CHARS=32000,DELIVERY_EVIDENCE_MAX_ITEMS=50,DELIVERY_EVIDENCE_MAX_CHARS=2000,DELIVERY_NEXT_MAX_CHARS=4000,DELIVERY_PROMPT_HEAD_CHARS=200,MAX_DELIVERIES_PER_TASK=50,DELIVERY_STALL_MS=600000;function deliveryFooter(deliveryId,api){return`[ROVE] When this turn ends, report: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026]`}var SKIP_REASONS=["task-missing","awaiting-owner","report-missing","quota","engine-error","engine-dead","awaiting-permission","busy"],SHOULD_RUN_SKIP_EXIT_CODE=3;function parseSkipVerdict(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(raw.run!==!1||!SKIP_REASONS.includes(raw.reason))return;let text=(v)=>typeof v==="string"&&v.length>0?v:void 0;return{run:!1,reason:raw.reason,...text(raw.detail)?{detail:raw.detail}:{},...text(raw.until)?{until:raw.until}:{},...Array.isArray(raw.gateIds)?{gateIds:raw.gateIds.filter((g)=>typeof g==="string")}:{}}}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var DAEMON_PROTOCOL_VERSION=5,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;return!samePath(daemonHome,clientHome)}var BLOCKING_RPCS=new Set(["api.invoke","ui.prompt","task.land","workitem.start","automation.runNow","task.startScheduledNow","pr.rerunFailedChecks","pr.reviewComments","task.ensureWorktree","task.spawn","task.ensureMain","task.moveToProject","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove","task.checkpoint","task.rewind","task.exportBranch"]),PTY_STOP_REFUSED="PtyStopRefused";function frameToLine(frame){return`${JSON.stringify(frame)}
|
|
4
3
|
`}class RpcTimeoutError extends Error{constructor(name,timeoutMs){super(`daemon rpc "${name}" timed out after ${timeoutMs}ms (daemon wedged?)`);this.name="RpcTimeoutError"}}function rpcTimeoutMs(){let raw=readRoveEnv("RPC_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 20000}class ConnectTimeoutError extends Error{constructor(socketPath,timeoutMs){super(`connecting to ${socketPath} timed out after ${timeoutMs}ms \u2014 nothing accepted the connection (daemon or PTY host not listening at that address)`);this.name="ConnectTimeoutError"}}function connectTimeoutMs(){let raw=readRoveEnv("CONNECT_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 5000}class RoveDaemonClient{socketPath;socket=null;buffer="";nextId=1;pending=new Map;handlers=new Map;lifecycleHandlers=new Map;connecting=null;disposed=!1;constructor(socketPath){this.socketPath=socketPath}connect(){if(this.socket)return Promise.resolve();if(this.disposed)return Promise.reject(Error("daemon client disposed"));if(this.connecting)return this.connecting;let p=this.openSocketWithFallback();this.connecting=p;let cleanup=()=>{if(this.connecting===p)this.connecting=null};return p.then(cleanup,cleanup),p}get isDisposed(){return this.disposed}close(){this.disposed=!0,this.socket?.end(),this.socket=null,this.failPending()}forceDisconnect(){let socket=this.socket;if(!socket)return;this.socket=null,socket.destroy(),this.failPending()}failPending(){if(this.pending.size===0)return;let err=Error("daemon connection closed");for(let pending of this.pending.values()){if(pending.timer)clearTimeout(pending.timer);pending.reject(err)}this.pending.clear()}on(name,handler){let set=this.handlers.get(name);if(!set)set=new Set,this.handlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.handlers.delete(name)}}onChannel(channel,handler){return this.on(channel,(frame)=>handler(frame.payload))}subscribe(opts={}){let payload={};if(opts.channels)payload.channels=opts.channels;if(opts.role)payload.role=opts.role;if(opts.cellPixelSize)payload.cellPixelWidth=opts.cellPixelSize.width,payload.cellPixelHeight=opts.cellPixelSize.height;return this.request("subscribe",payload)}onLifecycle(name,handler){let set=this.lifecycleHandlers.get(name);if(!set)set=new Set,this.lifecycleHandlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.lifecycleHandlers.delete(name)}}async request(name,payload){await this.connect();let socket=this.socket;if(!socket)throw Error("daemon connection is not open");let id=String(this.nextId++),promise=new Promise((resolve,reject)=>{let entry={resolve:(value)=>resolve(value),reject},timeoutMs=rpcTimeoutMs();if(timeoutMs>0&&!BLOCKING_RPCS.has(name))entry.timer=setTimeout(()=>this.onRequestTimeout(id,name,timeoutMs),timeoutMs);this.pending.set(id,entry)});return socket.write(frameToLine({type:"request",id,name,payload})),promise}onRequestTimeout(id,name,timeoutMs){let pending=this.pending.get(id);if(!pending)return;this.pending.delete(id),pending.reject(new RpcTimeoutError(name,timeoutMs)),this.forceDisconnect(),this.emitLifecycle("close")}async openSocketWithFallback(){try{await this.openSocket(this.socketPath);return}catch(err){if(!(err instanceof Error)||!("code"in err)||!["ENOENT","ECONNREFUSED"].includes(String(err.code)))throw err;for(let path of preRenameRuntimePaths(this.socketPath)){if(this.disposed)throw err;try{await this.openSocket(path);return}catch{}}throw err}}openSocket(path){return new Promise((resolve,reject)=>{let socket=connect(path);this.socket=socket;let timeoutMs=connectTimeoutMs(),timer;if(timeoutMs>0)timer=setTimeout(()=>{if(socket.off("connect",onConnect),socket.off("error",onError),socket.destroy(),this.socket===socket)this.socket=null;reject(new ConnectTimeoutError(this.socketPath,timeoutMs))},timeoutMs);let onConnect=()=>{if(timer)clearTimeout(timer);socket.off("error",onError),socket.on("error",()=>socket.destroy()),resolve()},onError=(err)=>{if(timer)clearTimeout(timer);if(socket.off("connect",onConnect),this.socket===socket)this.socket=null;reject(err)};socket.once("connect",onConnect),socket.once("error",onError);let decoder=new StringDecoder("utf8");this.buffer="",socket.on("data",(chunk)=>this.onData(decoder.write(chunk))),socket.on("close",()=>this.onSocketClose(socket))})}onSocketClose(which){if(this.socket!==which)return;this.socket=null,this.failPending(),this.emitLifecycle("close")}emitLifecycle(name){for(let handler of this.lifecycleHandlers.get(name)??[])try{handler()}catch(err){console.error(`[rove] lifecycle handler for "${name}" threw:`,err)}}onData(chunk){this.buffer+=chunk;let nl=this.buffer.indexOf(`
|
|
5
4
|
`);while(nl!==-1){let line=this.buffer.slice(0,nl);if(this.buffer=this.buffer.slice(nl+1),line.trim().length>0)this.onLine(line);nl=this.buffer.indexOf(`
|
|
6
5
|
`)}}onLine(line){let frame;try{frame=JSON.parse(line)}catch(err){logClientError("client-frame",err);return}if(frame.type==="event"){this.emit(frame);return}if(frame.type!=="response")return;let pending=this.pending.get(frame.id);if(!pending)return;if(this.pending.delete(frame.id),pending.timer)clearTimeout(pending.timer);if(frame.error){let err=Error(frame.error.message);if(frame.error.name)err.name=frame.error.name;if(frame.error.data!==void 0)err.data=frame.error.data;pending.reject(err)}else pending.resolve(frame.payload)}emit(frame){for(let handler of this.handlers.get(frame.name)??[])try{handler(frame)}catch(err){logClientError("client-event",err)}for(let handler of this.handlers.get("*")??[])try{handler(frame)}catch(err){logClientError("client-event",err)}}}
|
|
7
|
-
export{automationRunNeedsAttention,ROUTINE_RESPONSE_MAX_CHARS,routineRunResponseState,GATE_QUESTION_MAX,GATE_CONTEXT_MAX,GATE_OPTIONS_MAX,isRoutineInboxState,isAttentionInboxState,attentionInboxItemKey,DELIVERY_OUTCOMES,DELIVERY_SUMMARY_MAX_CHARS,DELIVERY_EVIDENCE_MAX_ITEMS,DELIVERY_EVIDENCE_MAX_CHARS,DELIVERY_NEXT_MAX_CHARS,DELIVERY_PROMPT_HEAD_CHARS,MAX_DELIVERIES_PER_TASK,DELIVERY_STALL_MS,deliveryFooter,SKIP_REASONS,SHOULD_RUN_SKIP_EXIT_CODE,parseSkipVerdict,
|
|
6
|
+
export{automationRunNeedsAttention,ROUTINE_RESPONSE_MAX_CHARS,routineRunResponseState,GATE_QUESTION_MAX,GATE_CONTEXT_MAX,GATE_OPTIONS_MAX,isRoutineInboxState,isAttentionInboxState,attentionInboxItemKey,DELIVERY_OUTCOMES,DELIVERY_SUMMARY_MAX_CHARS,DELIVERY_EVIDENCE_MAX_ITEMS,DELIVERY_EVIDENCE_MAX_CHARS,DELIVERY_NEXT_MAX_CHARS,DELIVERY_PROMPT_HEAD_CHARS,MAX_DELIVERIES_PER_TASK,DELIVERY_STALL_MS,deliveryFooter,SKIP_REASONS,SHOULD_RUN_SKIP_EXIT_CODE,parseSkipVerdict,CHANNEL_NAMES,normalizeChannelFilter,DAEMON_PROTOCOL_VERSION,MIN_COMPATIBLE_PROTOCOL_VERSION,isProtocolCompatible,isDaemonVersionStale,isForeignDaemonHome,PTY_STOP_REFUSED,frameToLine,RpcTimeoutError,ConnectTimeoutError,RoveDaemonClient};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{interactiveEngineCommand,listPresetIds}from"./chunk-
|
|
2
|
+
import{interactiveEngineCommand,listPresetIds}from"./chunk-atg13xab.js";import{engineEntry}from"./chunk-x83xbzjd.js";import{installedEngineIds}from"./chunk-hzz020xx.js";import{spawnSync}from"child_process";import{statSync}from"fs";import path from"path";function whichOnPath(bin){let bunWhich=globalThis.Bun?.which;if(bunWhich)return bunWhich(bin);let out=spawnSync(process.platform==="win32"?"where":"which",[bin],{encoding:"utf8"});if(out.status!==0)return null;return out.stdout.split(`
|
|
3
3
|
`).map((l)=>l.trim()).find(Boolean)??null}var defaultDeps={which:whichOnPath,command:(vendor)=>interactiveEngineCommand(vendor)};function probeLaunchBinary(argv,which){let bin=argv[0]?.trim();if(!bin)return{found:!1,error:"no launch command"};if(bin.includes(path.sep)||bin.startsWith(".")){try{if(statSync(bin).isFile())return{found:!0,path:bin}}catch{}return{found:!1,error:`not found at ${bin}`}}let found=which(bin);return found?{found:!0,path:found}:{found:!1,error:"not found on PATH"}}async function detectEngineStatus(vendor,over={}){let deps={...defaultDeps,...over},detector=engineEntry(vendor).detectAccount;if(!detector)return{vendor,binary:probeLaunchBinary(deps.command(vendor),deps.which),account:null};let status=await detector(deps.accountDeps),binary=status.binary.found?status.binary:probeLaunchBinary(deps.command(vendor),deps.which);return{vendor,binary,account:status.account,accountError:status.accountError}}function detectEngineStatuses(vendors,over={}){return Promise.all(vendors.map((v)=>detectEngineStatus(v,over)))}function describeAccount(account){if(account===null)return"login not detectable";switch(account.kind){case"oauth":return"email"in account?`logged in (${account.email}${account.organization?`, ${account.organization}`:""})`:"logged in";case"chatgpt":return`logged in (${account.email}${account.plan?`, ${account.plan}`:""})`;case"apikey":return"API key";case"token":return`token (${account.source})`;default:return"no account"}}function engineUsable(status){return status.binary.found&&status.account?.kind!=="none"}async function probeableEngineIds(){return[...new Set([...listPresetIds(),...await installedEngineIds()])]}function summarizeEngines(statuses){let usable=[],signedOut=[];for(let status of statuses)if(engineUsable(status))usable.push(status.vendor);else if(status.binary.found)signedOut.push(status.vendor);return{usable,signedOut}}
|
|
4
4
|
export{detectEngineStatus,detectEngineStatuses,describeAccount,probeableEngineIds,summarizeEngines};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{expandTilde}from"./chunk-2r1fgng9.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{pathSyntax}from"./chunk-pn5ygqn6.js";import{__require}from"./chunk-91sykzqq.js";import{statSync}from"fs";import{resolve}from"path";function isPathLikeArg(arg){return arg==="."||arg===".."||arg.startsWith("./")||arg.startsWith("../")||arg.startsWith(".\\")||arg.startsWith("..\\")||pathSyntax(arg).isAbsolute(arg)||arg.startsWith("/")||arg==="~"||arg.startsWith("~/")||arg.startsWith("~\\")}async function projectRootFor(dir){let{isGitRepo,resolveRepoRoot}=await import("./chunk-hv79ys32.js"),{projectRejection}=await import("./chunk-qnpkhvrn.js"),top=resolveRepoRoot(dir);if(top!==dir)return null;return projectRejection(top,isGitRepo,"explicit")?null:top}async function runOpenDirectory(arg){let dir=resolve(process.cwd(),expandTilde(arg)),isDir=!1;try{isDir=statSync(dir).isDirectory()}catch{isDir=!1}if(!isDir)process.stderr.write(`${ROVE_PRODUCT_NAME}: "${arg}" is not a directory (resolved to ${dir}).
|
|
3
|
+
`),process.exit(1);let projectRoot=await projectRootFor(dir),{withDaemonOrLocal}=await import("./chunk-mqvkd2g1.js");await withDaemonOrLocal({daemon:async(client)=>{let taskId;if(projectRoot)taskId=(await client.request("task.ensureMain",{repo:projectRoot})).task.id;else taskId=(await client.request("task.openDir",{dir})).taskId;await client.request("task.setActive",{taskId})},local:async(orch)=>{let task=projectRoot?await orch.ensureMainTask(projectRoot):await orch.openDirectoryTask({dir}),{writeLastActiveTaskId}=await import("./chunk-y8b2p44q.js");writeLastActiveTaskId(String(task.id))}});let{publishRoveTerminalTitle}=await import("./chunk-g8wrdp7n.js");publishRoveTerminalTitle();let{launchTui}=await import("./chunk-9fdy8vne.js");await launchTui()}
|
|
4
|
+
export{isPathLikeArg,runOpenDirectory};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{FINISHED_ALERTS_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,TOAST_DURATION_MS,ZEN_ACTIVE_KEY,addUnread,armPrefixNow,bindingReachability,configurePrefix,currentPrefixConfiguration,dispatchKeyEvent,inputPassthroughReachable,insertRegistration,invokeArmedPrefixAction,isCtrlModifierKeyName,osc9,persistedSoundVolume,prefixHudHideDirect,prefixHudShowDirect,readKeybindingsFile,removeUnread,resetKeybindingsFileCache,resetPrefixConfiguration,resetPrefixState,resolveUserKeybindings,shouldAlert,shouldPlaySound,shouldShowToast}from"./chunk-22rgewg0.js";import{$Fragment,$jsx,$jsxs,createRoot,flushSync,useRenderer}from"./chunk-29kvfqeh.js";import{require_react_production}from"./chunk-2wd4744g.js";import{RemoteOrchestrator}from"./chunk-tz373e5w.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{updaterShell,updaterShellFailureHint}from"./chunk-jfcn77n9.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,applyDisplayOverlay,readPersistedUiPrefs,resolveTheme,resolveThemeMode}from"./chunk-5nvg3ek8.js";import{loadUserThemes}from"./chunk-xd93fm1k.js";import{TERMINAL_TABS_PREFIX}from"./chunk-mdc7b01e.js";import{CURRENT_VERSION}from"./chunk-a4r45qdn.js";import{tildify}from"./chunk-2r1fgng9.js";import{connectIfRunning}from"./chunk-d0hpes59.js";import{loadStateFile,patchStateFile,readStateFileStrict,replaceStateFile}from"./chunk-32j6y5d1.js";import{localeState,setLocaleLang,t}from"./chunk-372g44dg.js";import{isLocaleId}from"./chunk-1eef3z5v.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-cmp64q4j.js";import{kvStatePath}from"./chunk-z1nj22va.js";import{installClientCrashHandlers,logClient,logClientError,setClientLogContext}from"./chunk-0g4wc808.js";import{__toESM}from"./chunk-91sykzqq.js";import{RGBA}from"@opentui/core";var import_react3=__toESM(require_react_production(),1);var import_react=__toESM(require_react_production(),1);function useAccessor(state){return import_react.useSyncExternalStore(state.subscribe,state.get,state.get)}var store=createStateCell({themes:{...BUNDLED_THEMES},active:DEFAULT_THEME,mode:DEFAULT_THEME_MODE,transparentBackground:!0,focusAccent:"primary"});function listThemes(){return Object.keys(store.get().themes)}function hasTheme(name){return Boolean(store.get().themes[name])}function addTheme(name,theme){if(!name)return!1;if(!theme||typeof theme!=="object"||!theme.theme)return!1;return store.update((s)=>({...s,themes:{...s.themes,[name]:theme}})),!0}function selectedTheme(){return store.get().active}function setTheme(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0}function transparentBackground(){return store.get().transparentBackground}function setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))}function focusAccent(){return store.get().focusAccent}function setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))}function themeMode(){return store.get().mode}function setThemeMode(mode){store.update((s)=>({...s,mode}))}var ThemeContext=import_react3.createContext(null),HOST_PALETTE_QUERY_TIMEOUT_MS=2000;function resolveActive(state,mode){let active=state.themes[state.active];if(active)return resolveTheme(active,mode);let fallback=state.themes[DEFAULT_THEME]??Object.values(state.themes)[0];if(!fallback)return resolveTheme({theme:{background:"#000000",text:"#ffffff"}},mode);return resolveTheme(fallback,mode)}function useHostThemeMode(renderer){let[mode,setMode]=import_react3.useState(()=>renderer?.themeMode??null);return import_react3.useEffect(()=>{if(!renderer)return;let onChange=(next)=>setMode(next);return renderer.on("theme_mode",onChange),setMode(renderer.themeMode),()=>{renderer.off("theme_mode",onChange)}},[renderer]),mode}function ThemeProvider(props){import_react3.useMemo(()=>{store.update((s)=>({...s,mode:props.mode??s.mode,active:props.theme&&s.themes[props.theme]?props.theme:s.active}))},[]);let state=useAccessor(store),renderer=useRenderer(),hostMode=useHostThemeMode(renderer),mode=resolveThemeMode(state.mode,hostMode),[hostBackground,setHostBackground]=import_react3.useState(null);import_react3.useEffect(()=>{if(!state.transparentBackground)return;if(renderer?.screenMode==="split-footer")return;if(!renderer)return;let cancelled=!1;return renderer.getPalette({timeout:HOST_PALETTE_QUERY_TIMEOUT_MS}).then((colors)=>{if(cancelled||!colors.defaultBackground)return;setHostBackground(RGBA.fromHex(colors.defaultBackground))}).catch(()=>{}),()=>{cancelled=!0}},[renderer,state.transparentBackground]);let theme=import_react3.useMemo(()=>applyDisplayOverlay(resolveActive(state,mode),state.focusAccent,state.transparentBackground,hostBackground??void 0),[state,mode,hostBackground]);import_react3.useEffect(()=>{if(renderer?.screenMode==="split-footer")return;renderer?.setBackgroundColor(theme.background??RGBA.fromInts(0,0,0))},[renderer,theme]);let value=import_react3.useMemo(()=>({theme,selected:state.active,transparentBackground:state.transparentBackground,focusAccent:state.focusAccent,modePreference:state.mode,mode:()=>mode,set(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0},setMode(next){store.update((s)=>({...s,mode:next}))},setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))},setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))},preview:(options)=>applyDisplayOverlay(resolveActive({...state,active:options.themeName},resolveThemeMode(options.themeMode,hostMode)),options.focusAccent,options.transparentBackground,hostBackground??void 0),all:listThemes,has:hasTheme}),[theme,state,mode,hostMode,hostBackground]);return $jsx(ThemeContext.Provider,{value,children:props.children})}function useTheme(){let value=import_react3.useContext(ThemeContext);if(!value)throw Error("Theme context must be used within a context provider");return value}var import_react4=__toESM(require_react_production(),1);function useLang(){return useAccessor(localeState())}function useT(){let lang=useLang();return import_react4.useCallback((key,params)=>t(key,params),[lang])}var import_react7=__toESM(require_react_production(),1);var CTRL_HOLD_THRESHOLD_MS=400;function createCtrlHoldDetector(callbacks){let state={kind:"idle"},held=new Set,reset=()=>{if(state.kind==="pending")clearTimeout(state.timer);if(state.kind==="visible")callbacks.onHide();state={kind:"idle"}},cancel=()=>{reset(),held.clear()};return{keypress:(event)=>{if(!isCtrlModifierKeyName(event.name)){cancel();return}if(event.eventType==="repeat"&&held.has(event.name))return;if(event.eventType!=="press")return;if(held.add(event.name),state.kind!=="idle")return;state={kind:"pending",timer:setTimeout(()=>{state={kind:"visible"},callbacks.onReveal()},CTRL_HOLD_THRESHOLD_MS)}},keyrelease:(event)=>{if(!isCtrlModifierKeyName(event.name)||event.eventType!=="release")return;if(held.delete(event.name),held.size===0)reset()},cancel}}function availableActions(stack){let seen=new Set,actions=[],passthrough=inputPassthroughReachable(stack);for(let registration of[...stack].reverse()){let config=registration.config();if(config.enabled===!1)continue;for(let binding of config.bindings){if(binding.prefix&¤tPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}function bindByIds(handlers){let out=[];for(let id in handlers){let handler=handlers[id];if(!handler)continue;let action=typeof handler==="function"?void 0:handler,cmd=typeof handler==="function"?handler:()=>handler.run(),binding=findBinding(id),chords=binding?.keys??[],prefixChords=binding?.prefixKeys??[];if(chords.length===0&&prefixChords.length===0){console.warn(`[rove/keybindings] bindByIds: id="${id}" has no chords (or doesn't exist in RoveKeymap)`);continue}chords.forEach((key,slot)=>out.push({key,cmd,action,slot,id,yieldToPassthrough:binding?.yieldToPassthrough})),prefixChords.forEach((key,slot)=>out.push({key,prefix:!0,cmd,action,slot,id}))}return out}var KEYMAP_DEFAULTS=new Map(RoveKeymap.map((b)=>[b.id,{keys:[...b.keys],prefixKeys:b.prefixKeys&&[...b.prefixKeys],hint:b.hint?{...b.hint}:void 0}]));function defaultChordsOf(id){return KEYMAP_DEFAULTS.get(id)?.keys??[]}function resetKeymapToDefaults(){for(let row of RoveKeymap){let def=KEYMAP_DEFAULTS.get(row.id);if(!def)continue;let mutable=row;mutable.keys=[...def.keys],mutable.prefixKeys=def.prefixKeys&&[...def.prefixKeys],mutable.hint=def.hint?{...def.hint}:void 0}}var keymapVersionValue=0,keymapVersionListeners=new Set;function keymapVersion(){return keymapVersionValue}function subscribeKeymapVersion(listener){return keymapVersionListeners.add(listener),()=>{keymapVersionListeners.delete(listener)}}function bumpKeymapVersion(){keymapVersionValue+=1;for(let listener of[...keymapVersionListeners])listener()}var KEYMAP_BY_ID=new Map(RoveKeymap.map((b)=>[b.id,b]));function findBinding(id){return KEYMAP_BY_ID.get(id)}var MODIFIER_GLYPH={ctrl:"\u2303",control:"\u2303",alt:"\u2325",opt:"\u2325",option:"\u2325",shift:"\u21E7",cmd:"\u2318",command:"\u2318",meta:"\u2318",super:"\u2318"},KEY_GLYPH={enter:"\u23CE",return:"\u23CE",esc:"\u238B",escape:"\u238B",space:"\u2423",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",backspace:"\u232B",delete:"\u2326",del:"\u2326",pgup:"\u21DE",pageup:"\u21DE",pgdn:"\u21DF",pagedown:"\u21DF",home:"\u2196",end:"\u2198"};function formatKey(k,upper){if(k.includes("/"))return k.split("/").map((part)=>formatKey(part,upper)).join("/");let low=k.toLowerCase();if(low==="tab")return"tab";let named=KEY_GLYPH[low];if(named)return named;if(/^f\d{1,2}$/.test(low))return low.toUpperCase();if(!upper)return k;if(/^[a-z]$/.test(low))return k.toUpperCase();return k.replace(/[a-z]+/gi,(run)=>run.toUpperCase())}function formatChord(chord,prefixGlyph="\u2303A"){let s=chord.trim();if(!s)return s;let pm=/^prefix\s+(.+)$/i.exec(s);if(pm){let suffix=pm[1]??"";return`${prefixGlyph} ${suffix.includes("+")?formatChord(suffix,prefixGlyph):formatKey(suffix,!0)}`}let parts=s.split("+");if(parts.length===1)return formatKey(parts[0]??"",!1);let key=parts[parts.length-1]??"";return`${parts.slice(0,-1).map((p)=>MODIFIER_GLYPH[p.toLowerCase().trim()]??p).join("")} ${formatKey(key,!0)}`}var DIRECT_GUIDE_PREFIX_ACTION_ID="prefix.moreCommands",CTRL_FOLLOW_UP_CHORD=/^ctrl\+[^+]+$/;function ctrlFollowUpKey(chord){return CTRL_FOLLOW_UP_CHORD.test(chord)?chord.slice(5):null}function shortcutCaption(input){let binding=findBinding(input.bindingId);if(!binding)return null;if(input.reachability.direct.has(input.bindingId)){let direct=binding.keys[0];if(direct)return formatChord(direct)}if(input.prefixKey&&input.reachability.prefix.has(input.bindingId)){let stroke=binding.prefixKeys?.[0];if(stroke)return`${formatChord(input.prefixKey)} ${formatChord(stroke)}`}return null}function directGuideOptions(reachability,prefixKey){let options=RoveKeymap.filter((binding)=>reachability.direct.has(binding.id)).flatMap((binding)=>{let strokes=binding.keys.flatMap((chord)=>ctrlFollowUpKey(chord)??[]);if(strokes.length>2)return[{stroke:`${strokes[0]}-${strokes.at(-1)}`,action:binding.id}];return strokes.map((stroke)=>({stroke,action:binding.id}))}),prefixStroke=prefixKey?ctrlFollowUpKey(prefixKey):null;if(prefixStroke&&reachability.prefix.size>0)options.push({stroke:prefixStroke,action:DIRECT_GUIDE_PREFIX_ACTION_ID});return options}var import_react5=__toESM(require_react_production(),1);function useLatest(value){let ref=import_react5.useRef(value);return ref.current=value,ref}var ModalScopeContext=import_react7.createContext(null),nextId=1,stack=[],installedRenderer=null,installed=null,listener=null,releaseListener=null,ctrlHoldDetector=null,supersededRenderers=new WeakSet;function ensureInstalled(renderer){if(!renderer)throw Error("useBindings: no renderer in scope; call inside a component rendered by @opentui/react.");if(installedRenderer===renderer)return;if(supersededRenderers.has(renderer))return;if(installed&&listener)installed.off("keypress",listener);if(installed&&releaseListener)installed.off("keyrelease",releaseListener);if(ctrlHoldDetector?.cancel(),installedRenderer)supersededRenderers.add(installedRenderer);stack.length=0,resetPrefixState(),installedRenderer=renderer,installed=renderer.keyInput,ctrlHoldDetector=createCtrlHoldDetector({onReveal:()=>{resetPrefixState();let options=directGuideOptions(bindingReachability(stack),currentPrefixConfiguration().key);if(options.length>0)prefixHudShowDirect(options)},onHide:prefixHudHideDirect}),listener=(evt)=>{profileTick("key"),ctrlHoldDetector?.keypress(evt),dispatchKeyEvent(stack,evt,Date.now(),{flushSync})},releaseListener=(evt)=>ctrlHoldDetector?.keyrelease(evt),installed.on("keypress",listener),installed.on("keyrelease",releaseListener)}function modalActive(){return stack.some((r)=>r.modalOwner!==void 0)}function currentBindingReachability(){return bindingReachability(stack)}function armPrefixFromCurrentStack(){return armPrefixNow(stack)}function invokeArmedPrefixActionFromCurrentStack(actionId,stroke){return invokeArmedPrefixAction(stack,actionId,stroke)}var stackVersion=0,stackListeners=new Set;function bumpStackVersion(){prefixHudHideDirect(),stackVersion++;for(let listener2 of stackListeners)listener2()}function bindingReachabilitySignature(config){let bindings=config.bindings.map((binding)=>[binding.id??"",binding.key,binding.prefix===!0?"p":"d",binding.passthrough===!0?"i":"u"].join(":")).join("|");return`${config.enabled===!1?"off":"on"};${config.modal===!0?"modal":"plain"};${bindings}`}function subscribeBindingStack(listener2){return stackListeners.add(listener2),()=>{stackListeners.delete(listener2)}}function useBindingStackVersion(){return import_react7.useSyncExternalStore((onChange)=>{return stackListeners.add(onChange),()=>stackListeners.delete(onChange)},()=>stackVersion)}function useBindings(config,opts){let renderer=useRenderer();ensureInstalled(renderer);let configRef=useLatest(config),scope=import_react7.useContext(ModalScopeContext),reachabilitySignature=bindingReachabilitySignature(config()),previousReachabilitySignature=import_react7.useRef(reachabilitySignature);import_react7.useEffect(()=>{if(previousReachabilitySignature.current===reachabilitySignature)return;previousReachabilitySignature.current=reachabilitySignature,bumpStackVersion()},[reachabilitySignature]),import_react7.useEffect(()=>{if(supersededRenderers.has(renderer))return;if(opts?.modalOwner!==void 0)resetPrefixState();let reg={config:()=>configRef.current(),id:nextId++,modalOwner:opts?.modalOwner,modalMember:opts?.modalOwner===void 0?scope??void 0:void 0};return insertRegistration(stack,reg),bumpStackVersion(),()=>{let i=stack.findIndex((r)=>r.id===reg.id);if(i>=0)stack.splice(i,1);bumpStackVersion()}},[])}function pageCloseBindings(cmd){return[{key:"escape",cmd},{key:"q",cmd},{key:"ctrl+c",cmd}]}function currentPaletteActions(){return capturePaletteActions(stack)}import{createCliRenderer}from"@opentui/core";var import_react21=__toESM(require_react_production(),1);async function connectPaneOrchestrator(options={}){let tag=options.logTag??"orch-connect",connect=options.connect??connectIfRunning,remote=null;try{let client=await connect();if(!client)return logClient(tag,"no daemon running \u2014 caller degrades"),null;return remote=new RemoteOrchestrator(client,{...options.orchestratorOptions,channels:options.channels}),await remote.init(),remote}catch(err){return logClientError(tag,err),remote?.dispose(),null}}var cached=null;function applyUserKeybindings(){if(cached)return cached;let{report,prefix}=resolveUserKeybindings(readKeybindingsFile(),RoveKeymap,process.platform);if(report.exists)configurePrefix(prefix);for(let w of report.warnings)console.warn(`[rove/keybindings] ${w}`);return cached=report,cached}function pluginKeybindings(){return userKeybindingsReport().plugins}function userKeybindingsReport(){return cached??applyUserKeybindings()}function reloadUserKeybindings(){cached=null,resetKeybindingsFileCache(),resetKeymapToDefaults(),resetPrefixConfiguration();let report=applyUserKeybindings();return bumpKeymapVersion(),report}var UI_PREFS_FOCUS_ACCENT_SLOTS=["primary","success","info"];var UI_PREFS_THEME_MODES=["dark","light","auto"];function applyUiPrefs(target,prefs){if(typeof prefs.theme==="string"&&prefs.theme.length>0&&prefs.theme!==target.selectedTheme()){if(!target.hasTheme(prefs.theme))target.reloadUserThemes();if(target.hasTheme(prefs.theme))target.setTheme(prefs.theme)}if(prefs.themeMode===null||typeof prefs.themeMode==="string"){let mode=normalizeThemeMode(prefs.themeMode);if(mode&&mode!==target.themeMode())target.setThemeMode(mode)}if(typeof prefs.transparentBackground==="boolean"&&prefs.transparentBackground!==target.transparentBackground())target.setTransparentBackground(prefs.transparentBackground);if(prefs.focusAccent===null||typeof prefs.focusAccent==="string"){let slot=normalizeFocusAccent(prefs.focusAccent);if(slot&&slot!==target.focusAccent())target.setFocusAccent(slot)}}function normalizeFocusAccent(value){if(value===null)return"primary";return UI_PREFS_FOCUS_ACCENT_SLOTS.includes(value)?value:null}function normalizeThemeMode(value){if(value===null)return"dark";return UI_PREFS_THEME_MODES.includes(value)?value:null}var STALL_HEARTBEAT_MS=1000,STALL_THRESHOLD_MS=2000;function stallReport(gapMs,mem,heartbeatMs=STALL_HEARTBEAT_MS,thresholdMs=STALL_THRESHOLD_MS){let stallMs=gapMs-heartbeatMs;if(stallMs<thresholdMs)return null;let mb=(n)=>Math.round(n/1048576);return`event loop stalled ~${stallMs}ms \u2014 rss=${mb(mem.rss)}MB heapUsed=${mb(mem.heapUsed)}MB`}function installEventLoopStallTelemetry(){let last=Date.now(),timer=setInterval(()=>{let now=Date.now(),gap=now-last;last=now;let report=stallReport(gap,process.memoryUsage());if(report)logClient("stall",report)},STALL_HEARTBEAT_MS);return timer.unref?.(),()=>clearInterval(timer)}var KITTY_KEYBOARD={};function hostTargetFps(){return 60}function hostRenderOptions(onDestroy){let base={backgroundColor:"transparent",externalOutputMode:"passthrough",exitOnCtrlC:!1,screenMode:"alternate-screen",useKittyKeyboard:KITTY_KEYBOARD,targetFps:hostTargetFps()};return onDestroy?{...base,onDestroy}:base}function inlineRenderOptions(heightRows,onDestroy){let base={backgroundColor:"transparent",exitOnCtrlC:!1,screenMode:"split-footer",footerHeight:heightRows,useKittyKeyboard:KITTY_KEYBOARD};return onDestroy?{...base,onDestroy}:base}function installExitRestoreBackstop(renderer){process.on("exit",()=>renderer.destroy())}var BRACKETED_PASTE_ON="\x1B[?2004h",BRACKETED_PASTE_OFF="\x1B[?2004l";function installBracketedPasteMode(stdout=process.stdout){if(!stdout.isTTY)return()=>{};let write=(seq)=>{try{stdout.write(seq)}catch{}};write(BRACKETED_PASTE_ON);let restored=!1,restore=()=>{if(restored)return;restored=!0,write(BRACKETED_PASTE_OFF)};return process.on("exit",restore),restore}var exitCriticalWork=new Set;async function whenExitReady(){while(exitCriticalWork.size>0)await Promise.allSettled([...exitCriticalWork])}function installPaneExitBackstop(opts={}){let ceilingMs=opts.ceilingMs??5000,exit=opts.exit??((code)=>process.exit(code)),exitScheduled=!1,exited=!1,exitOnce=()=>{if(exited)return;exited=!0,exit(0)},scheduleExit=()=>{if(exitScheduled)return;exitScheduled=!0;let ceiling=setTimeout(()=>{console.error(`[rove] exit backstop: ${exitCriticalWork.size} task(s) still in flight after ${ceilingMs}ms \u2014 exiting anyway`),exitOnce()},ceilingMs);ceiling.unref?.(),whenExitReady().then(()=>{clearTimeout(ceiling),exitOnce()})};for(let signal of["SIGHUP","SIGTERM","SIGINT"])process.on(signal,scheduleExit)}function installOrphanExitWatchdog(intervalMs=5000){let timer=setInterval(()=>{if(process.ppid===1)process.exit(0)},intervalMs);return timer.unref?.(),()=>clearInterval(timer)}var SYNC_START=Buffer.from("\x1B[?2026h"),SYNC_END=Buffer.from("\x1B[?2026l");class ImeAnchorController{owner=null;anchor=null;claim(owner,anchor){this.owner=owner,this.anchor={x:Math.max(0,Math.trunc(anchor.x)),y:Math.max(0,Math.trunc(anchor.y))}}release(owner){if(this.owner!==owner)return!1;return this.owner=null,this.anchor=null,!0}current(){return this.anchor}}var imeAnchorController=new ImeAnchorController;class ImeAnchorFrameTransformer{controller;pending=Buffer.alloc(0);frame=Buffer.alloc(0);constructor(controller){this.controller=controller}push(chunk){let data=this.pending.length>0?Buffer.concat([this.pending,chunk]):chunk;this.pending=Buffer.alloc(0);let output=[],offset=0;while(offset<data.length){if(this.frame.length===0){let start=data.indexOf(SYNC_START,offset);if(start<0){let tail2=data.subarray(offset),pendingLength2=longestMarkerPrefixSuffix(tail2,[SYNC_START]),safeLength2=tail2.length-pendingLength2;if(safeLength2>0)output.push(tail2.subarray(0,safeLength2));if(pendingLength2>0)this.pending=Buffer.from(tail2.subarray(safeLength2));break}if(start>offset)output.push(data.subarray(offset,start));this.frame=Buffer.from(SYNC_START),offset=start+SYNC_START.length;continue}let end=data.indexOf(SYNC_END,offset),restart=data.indexOf(SYNC_START,offset);if(restart>=0&&(end<0||restart<end)){this.frame=Buffer.from(SYNC_START),offset=restart+SYNC_START.length;continue}if(end>=0){if(end>offset)this.frame=Buffer.concat([this.frame,data.subarray(offset,end)]);output.push(this.frame);let anchor=this.controller.current();if(anchor)output.push(Buffer.from(`\x1B[${anchor.y+1};${anchor.x+1}H\x1B[?25l`));output.push(SYNC_END),this.frame=Buffer.alloc(0),offset=end+SYNC_END.length;continue}let tail=data.subarray(offset),pendingLength=longestMarkerPrefixSuffix(tail,[SYNC_START,SYNC_END]),safeLength=tail.length-pendingLength;if(safeLength>0)this.frame=Buffer.concat([this.frame,tail.subarray(0,safeLength)]);if(pendingLength>0)this.pending=Buffer.from(tail.subarray(safeLength));break}return output.length>0?Buffer.concat(output):Buffer.alloc(0)}flush(){if(this.frame.length>0)return this.frame=Buffer.alloc(0),this.pending=Buffer.alloc(0),Buffer.alloc(0);let pending=this.pending;return this.pending=Buffer.alloc(0),pending}}function longestMarkerPrefixSuffix(bytes,markers){let max=Math.min(bytes.length,Math.max(...markers.map((marker)=>marker.length-1)));for(let length=max;length>0;length-=1){let suffix=bytes.subarray(bytes.length-length);if(markers.some((marker)=>length<marker.length&&suffix.equals(marker.subarray(0,length))))return length}return 0}function asBuffer(chunk,encodingOrCallback){if(typeof chunk!=="string")return Buffer.from(chunk);let encoding=typeof encodingOrCallback==="string"?encodingOrCallback:void 0;return Buffer.from(chunk,encoding)}function writeCallback(encodingOrCallback,maybeCallback){return typeof encodingOrCallback==="function"?encodingOrCallback:maybeCallback}function createImeAnchoredOutput(target,controller=imeAnchorController){let transformer=new ImeAnchorFrameTransformer(controller),exposedWrite=(chunk,encodingOrCallback,maybeCallback)=>{let transformed=transformer.push(asBuffer(chunk,encodingOrCallback)),callback=writeCallback(encodingOrCallback,maybeCallback);if(transformed.length===0){if(callback)queueMicrotask(()=>callback(null));return!0}return callback?target.write(transformed,callback):target.write(transformed)};return{stdout:new Proxy(target,{get(stream,property){if(property==="write")return exposedWrite;let value=Reflect.get(stream,property,stream);return typeof value==="function"?value.bind(stream):value},set(stream,property,value){if(property==="write")return exposedWrite=value,!0;return Reflect.set(stream,property,value,stream)}}),flush(){let pending=transformer.flush();if(pending.length>0)target.write(pending)}}}var IME_ANCHOR_PLATFORMS=new Set(["darwin","win32"]);function createHostImeOutput(opts){if(!IME_ANCHOR_PLATFORMS.has(opts.platform)||!opts.fullscreen)return{active:!1,rendererOptions:{},attach:()=>()=>{},flush:()=>{}};let output=createImeAnchoredOutput(opts.stdout,opts.controller);return{active:!0,rendererOptions:{stdout:output.stdout,remote:!1},attach:(renderer)=>installRendererResizeForwarder(renderer,opts.stdout),flush:()=>output.flush()}}function installRendererResizeForwarder(renderer,terminal,signals=process){let onResize=()=>{let{columns:width,rows:height}=terminal;if(!width||!height)return;renderer.resize(width,height)};return signals.on("SIGWINCH",onResize),()=>signals.removeListener("SIGWINCH",onResize)}function needsScreenSelfHeal(platform){return platform==="win32"}function requestFullRepaint(renderer){if(renderer.screenMode!=="alternate-screen")return!1;let internals=renderer;return internals.forceFullRepaintRequested=!0,renderer.requestRender(),!0}function writeThroughRenderer(renderer,chunk,fallback=process.stdout){let writeOut=renderer?.writeOut;try{if(typeof writeOut==="function")writeOut.call(renderer,chunk);else fallback.write(chunk)}catch{}}function redrawScreen(renderer){if(renderer.screenMode!=="alternate-screen")return!1;return writeThroughRenderer(renderer,"\x1B[H\x1B[2J"),requestFullRepaint(renderer)}function installScreenSelfHeal(opts){let platform=opts.platform??process.platform;if(!needsScreenSelfHeal(platform))return()=>{};let{renderer}=opts,repaint=()=>{requestFullRepaint(renderer)};return renderer.on("resize",repaint),renderer.on("focus",repaint),()=>{renderer.off("resize",repaint),renderer.off("focus",repaint)}}var import_react9=__toESM(require_react_production(),1);var PANE_ORDER=["sidebar","workspace","files","terminal"],FocusContext=import_react9.createContext(null);function FocusProvider(props){let[focused,setFocusedState]=import_react9.useState(props.initial??"sidebar"),renderer=useRenderer(),focusedRef=useLatest(focused),setFocused=import_react9.useCallback((pane)=>{if(focusedRef.current===pane)return;let current=renderer?.currentFocusedRenderable;if(current&&!current.isDestroyed)try{current.blur()}catch{}setFocusedState(pane)},[renderer]),cycle=import_react9.useCallback((delta)=>{let next=(PANE_ORDER.indexOf(focusedRef.current)+delta+PANE_ORDER.length)%PANE_ORDER.length;setFocused(PANE_ORDER[next])},[setFocused]),value=import_react9.useMemo(()=>({focused,is:(pane)=>focused===pane,setFocused,cycle}),[focused,setFocused,cycle]);return $jsx(FocusContext.Provider,{value,children:props.children})}function useFocus(){let ctx=import_react9.useContext(FocusContext);if(!ctx)throw Error("useFocus: must be called inside <FocusProvider>. See src/tui-react/context/focus.tsx.");return ctx}function useOptionalFocus(){return import_react9.useContext(FocusContext)}var import_react10=__toESM(require_react_production(),1);var WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,ZEN_ACTIVE_KEY]);function createKvCore(){let store2=createStateCell(loadStateFile(),"kv.snapshot"),dirtyKeys=new Set,quiet=new Map,seeded=new Map,writeTimer=null,errorListeners=new Set,reportedKeys=new Set;function reportWriteError(err){let fresh=[...dirtyKeys].filter((key)=>!reportedKeys.has(key));if(fresh.length===0)return;for(let key of fresh)reportedKeys.add(key);let failure={keys:fresh,file:kvStatePath(),error:err};for(let listener2 of errorListeners)listener2(failure)}function writeNow(label){if(dirtyKeys.size===0)return!0;try{let patch={},snap=store2.get();for(let key of dirtyKeys)patch[key]=quiet.has(key)?quiet.get(key):snap[key];return patchStateFile(patch,"strict"),dirtyKeys.clear(),reportedKeys.clear(),!0}catch(err){return console.error(`[rove] kv ${label} failed:`,err),reportWriteError(err),!1}}function cancelTimer(){if(writeTimer)clearTimeout(writeTimer),writeTimer=null}function scheduleWrite(){cancelTimer(),writeTimer=setTimeout(()=>{writeTimer=null,writeNow("write")},WRITE_DEBOUNCE_MS)}function merge(fresh,keepQuiet){let before=store2.get(),next={...fresh};for(let[key,value]of seeded)if(next[key]===void 0)next[key]=value;for(let key of dirtyKeys)if(before[key]===void 0)delete next[key];else next[key]=before[key];let quietChanged=!1;for(let key of[...quiet.keys()]){if(dirtyKeys.has(key))continue;if(!keepQuiet||JSON.stringify(quiet.get(key))!==JSON.stringify(fresh[key])){quietChanged=!0,quiet.delete(key);continue}if(before[key]===void 0)delete next[key];else next[key]=before[key]}if(dirtyKeys.size>0)scheduleWrite();let changed=0;for(let key of new Set([...Object.keys(before),...Object.keys(next)]))if(JSON.stringify(before[key])!==JSON.stringify(next[key]))changed++;if(changed>0||quietChanged)store2.set(next);return changed}return{snapshot:store2.get,subscribe:store2.subscribe,get(key,defaultValue){return(quiet.has(key)?quiet.get(key):store2.get()[key])??defaultValue},set(key,value){if(key.startsWith(TERMINAL_TABS_PREFIX)){logClientError("kv",Error(`refused a local write of ${key}: tabs go through the daemon`));return}quiet.delete(key),store2.update((s)=>{if(value!==void 0)return{...s,[key]:value};if(!(key in s))return s;let next={...s};return delete next[key],next}),dirtyKeys.add(key),scheduleWrite()},setQuiet(key,value){quiet.set(key,value),dirtyKeys.add(key),scheduleWrite()},seed(key,value){if(!seeded.has(key))seeded.set(key,value);if(quiet.has(key)||store2.get()[key]!==void 0)return;store2.update((s)=>({...s,[key]:value}))},flush(){return cancelTimer(),writeNow("flush")},clear(){try{replaceStateFile({})}catch(err){return console.error("[rove] kv clear write failed:",err),!1}return cancelTimer(),dirtyKeys.clear(),reportedKeys.clear(),quiet.clear(),store2.set({}),!0},reload(){try{return readStateFileStrict(),cancelTimer(),writeNow("reload flush"),{ok:!0,changed:merge(readStateFileStrict(),!1)}}catch(error){return{ok:!1,error}}},follow(shared){let next={...shared};for(let key of PER_WINDOW_KEYS)delete next[key];for(let[key,value]of Object.entries(store2.get()))if(isUnpublishedStateKey(key)||PER_WINDOW_KEYS.has(key))next[key]=value;merge(next,!0)},onWriteError(listener2){return errorListeners.add(listener2),()=>{errorListeners.delete(listener2)}}}}var Ctx=import_react10.createContext(null);function KVProvider(props){let[core]=import_react10.useState(createKvCore),snapshot=import_react10.useSyncExternalStore(core.subscribe,core.snapshot,core.snapshot);import_react10.useEffect(()=>{let flush=()=>{core.flush()};return process.on("exit",flush),()=>{process.off("exit",flush)}},[core]);let value=import_react10.useMemo(()=>({ready:!0,store:snapshot,signal(name,defaultValue){return core.seed(name,defaultValue),[()=>core.get(name)??defaultValue,(next)=>core.set(name,next)]},get:core.get,set:core.set,setQuiet:core.setQuiet,flush:core.flush,clear:core.clear,reload:core.reload,follow:core.follow,onWriteError:core.onWriteError}),[core,snapshot]);return $jsx(Ctx.Provider,{value,children:props.children})}function useKV(){let value=import_react10.useContext(Ctx);if(!value)throw Error("KV context must be used within a context provider");return value}function useOptionalKV(){return import_react10.useContext(Ctx)??null}var import_react13=__toESM(require_react_production(),1);var import_react12=__toESM(require_react_production(),1);import{existsSync,mkdirSync}from"fs";import{tmpdir}from"os";import{basename,delimiter,extname,isAbsolute,join,resolve}from"path";var pulse_default="../pulse-ynhb2ave.wav";function scaleWavVolume(wav,volume){let gain=Math.min(1,Math.max(0,volume));if(wav.length<12)return null;if(wav.readUInt32BE(0)!==1380533830||wav.readUInt32BE(8)!==1463899717)return null;let bitsPerSample,format,data;for(let offset=12;offset+8<=wav.length;){let id=wav.readUInt32BE(offset),size=wav.readUInt32LE(offset+4),start=offset+8,end=start+size;if(size<0||end>wav.length)return null;if(id===1718449184){if(size<16)return null;format=wav.readUInt16LE(start),bitsPerSample=wav.readUInt16LE(start+14)}else if(id===1684108385)data={start,end};offset=end+size%2}if(format!==1||bitsPerSample!==16||!data)return null;if((data.end-data.start)%2!==0)return null;let out=Buffer.from(wav);if(gain===1)return out;for(let i=data.start;i<data.end;i+=2){let scaled=Math.round(out.readInt16LE(i)*gain);out.writeInt16LE(Math.min(32767,Math.max(-32768,scaled)),i)}return out}var pulseAsset=isAbsolute(pulse_default)?pulse_default:resolve(import.meta.dir,pulse_default),DIR=join(tmpdir(),"rove-sfx"),PLAYERS=["ffplay","mpv","mpg123","mpg321","mplayer","afplay","play","omxplayer","aplay","cmdmp3","cvlc","powershell.exe"];function args(player,file){if(player==="ffplay")return[player,"-autoexit","-nodisp",file];if(player==="mpv")return[player,"--no-video","--audio-display=no",file];if(player==="mplayer")return[player,"-vo","null",file];if(player==="cvlc")return[player,"--play-and-exit",file];if(player==="powershell.exe")return[player,"-c",`(New-Object Media.SoundPlayer '${file.replace(/'/g,"''")}').PlaySync()`];return[player,file]}var cachedPlayer,cachedPaths=new Map;function pathDirs(rawPath,delim=delimiter){return rawPath.split(delim).filter(Boolean)}function pickPlayer(){if(cachedPlayer!==void 0)return cachedPlayer;let segments=pathDirs(process.env.PATH??"");return cachedPlayer=PLAYERS.find((p)=>segments.some((dir)=>existsSync(join(dir,p))))??null,cachedPlayer}function assetNameFor(assetPath,volume){let name=basename(assetPath),ext=extname(name);return`${name.slice(0,name.length-ext.length)}@${Math.round(volume*100)}${ext}`}async function ensureAsset(volume){let cached2=cachedPaths.get(volume);if(cached2)return cached2;let pending=(async()=>{mkdirSync(DIR,{recursive:!0});let dest=join(DIR,assetNameFor(pulseAsset,volume)),out=Bun.file(dest);if(await out.exists())return dest;let source=Buffer.from(await Bun.file(pulseAsset).arrayBuffer());return await Bun.write(out,scaleWavVolume(source,volume)??source),dest})();return cachedPaths.set(volume,pending),pending}function pulse(volume=persistedSoundVolume()){if(!(volume>0))return;let player=pickPlayer();if(!player)return;ensureAsset(volume).then((path)=>{try{Bun.spawn(args(player,path),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref?.()}catch{}}).catch(()=>{return})}var ctx=import_react12.createContext(null);function NotificationsProvider(props){let[toasts,setToasts]=import_react12.useState([]),[unread,setUnread]=import_react12.useState(new Map),kv=useOptionalKV(),renderer=useRenderer(),snapshot=import_react12.useMemo(()=>loadStateFile(),[]),prefs=import_react12.useMemo(()=>({"notifications.sound.enabled":kv?.get("notifications.sound.enabled")??snapshot["notifications.sound.enabled"],"notifications.toast.enabled":kv?.get("notifications.toast.enabled")??snapshot["notifications.toast.enabled"],[FINISHED_ALERTS_KEY]:kv?.get(FINISHED_ALERTS_KEY)??snapshot[FINISHED_ALERTS_KEY]}),[kv,snapshot]),counter=import_react12.useRef(0),timers=import_react12.useRef(new Set);import_react12.useEffect(()=>()=>{for(let id of timers.current)clearTimeout(id);timers.current.clear()},[]);let dismiss=import_react12.useCallback((id)=>{setToasts((prev)=>prev.filter((t2)=>t2.id!==id))},[]),notify=import_react12.useCallback((input)=>{if(setUnread((prev)=>addUnread(prev,input)),!shouldAlert(input,prefs[FINISHED_ALERTS_KEY]!==!1))return;let soundEnabled=prefs["notifications.sound.enabled"]!==!1;if(shouldPlaySound(input,soundEnabled))writeThroughRenderer(renderer,`\x07${osc9(`Rove \u2014 ${input.title}`)}`),pulse();let toastEnabled=prefs["notifications.toast.enabled"]!==!1;if(shouldShowToast(input.kind,toastEnabled)){let id=++counter.current;setToasts((prev)=>[...prev,{id,...input}]);let timer=setTimeout(()=>{timers.current.delete(timer),dismiss(id)},TOAST_DURATION_MS);timers.current.add(timer)}},[prefs,dismiss,renderer]),markRead=import_react12.useCallback((taskId,tabId)=>{setUnread((prev)=>removeUnread(prev,taskId,tabId))},[]),value=import_react12.useMemo(()=>({toasts,unread,notify,dismiss,markRead}),[toasts,unread,notify,dismiss,markRead]);return $jsx(ctx.Provider,{value,children:props.children})}function useNotifications(){let value=import_react12.useContext(ctx);if(!value)throw Error("useNotifications must be used within a NotificationsProvider");return value}function useOptionalNotifications(){return import_react12.useContext(ctx)}function KvWriteErrorToasts(){let kv=useOptionalKV(),notifications=useOptionalNotifications();return import_react13.useEffect(()=>{if(!kv||!notifications)return;return kv.onWriteError((failure)=>{notifications.notify({taskId:"",tabId:"",kind:"error",title:t("settings.stateWrite.failedTitle"),body:t("settings.stateWrite.failedBody",{file:tildify(failure.file),keys:failure.keys.join(", ")})})})},[kv,notifications]),null}var import_react17=__toESM(require_react_production(),1);function isNarrowWidth(cols){return cols<70}function narrowSurface(args2){if(args2.focusedPane==="sidebar")return"sidebar";return args2.hasSelection||args2.hasOpenPage?"content":"sidebar"}var import_react15=__toESM(require_react_production(),1);var stores=new WeakMap;function terminalSizeStore(source){let existing=stores.get(source);if(existing)return existing;let listeners=new Set,size={width:source.width,height:source.height},notify=()=>{for(let listener2 of listeners)listener2()},store2={subscribe(listener2){if(listeners.add(listener2),listeners.size===1)source.on("resize",notify);return()=>{if(listeners.delete(listener2),listeners.size===0)source.off("resize",notify)}},snapshot(){if(size.width!==source.width||size.height!==source.height)size={width:source.width,height:source.height};return size}};return stores.set(source,store2),store2}function useTerminalSize(){let store2=terminalSizeStore(useRenderer());return import_react15.useSyncExternalStore(store2.subscribe,store2.snapshot)}function useDialogPaddingX(){let dims=useTerminalSize();return isNarrowWidth(dims.width)?1:2}var DIALOG_CONTENT_OPACITY=0.5,TRANSPARENT_DIALOG_CONTENT_OPACITY=0.75;function Dialog(props){let dimensions=useTerminalSize(),{theme}=useTheme(),renderer=useRenderer(),dismissRef=import_react17.useRef(!1),width=props.size==="xlarge"?140:props.size==="large"?110:props.size==="small"?50:80,VERTICAL_MARGIN=2,upperFifth=props.placement==="upper-fifth"&&!isNarrowWidth(dimensions.width),headerTop=Math.max(2,Math.floor(dimensions.height/5)),cardTop=upperFifth?Math.max(2,headerTop-1):0,maxCardHeight=Math.max(8,upperFifth?dimensions.height-cardTop-2:dimensions.height-4);return $jsx("box",{onMouseDown:()=>{dismissRef.current=!!renderer?.getSelection()},onMouseUp:()=>{if(dismissRef.current){dismissRef.current=!1;return}props.onClose?.()},width:dimensions.width,height:dimensions.height,alignItems:"center",justifyContent:upperFifth?"flex-start":"center",paddingTop:cardTop,position:"absolute",zIndex:3000,left:0,top:0,shouldFill:!1,children:$jsx("box",{onMouseUp:(e)=>{dismissRef.current=!1,e.stopPropagation()},width,maxWidth:dimensions.width-2,maxHeight:maxCardHeight,flexShrink:1,flexGrow:0,backgroundColor:theme.backgroundDialog,paddingTop:1,children:props.children})})}var entrySeq=0,ctx2=import_react17.createContext(null);function DialogProvider(props){let[stack2,setStack]=import_react17.useState([]),[size,setSize]=import_react17.useState("medium"),[placement,setPlacement]=import_react17.useState("center"),renderer=useRenderer(),{transparentBackground:transparentBackground2}=useTheme(),focusRef=import_react17.useRef(null),refocusTimer=import_react17.useRef(null);import_react17.useEffect(()=>()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current)},[]);let refocus=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);refocusTimer.current=setTimeout(()=>{let focus=focusRef.current;if(!focus||focus.isDestroyed)return;function find(item){for(let child of item.getChildren()){if(child===focus)return!0;if(find(child))return!0}return!1}let root=renderer?.root;if(!root)return;if(!find(root))return;focus.focus()},1)},[renderer]),stackRef=useLatest(stack2),captureFocusIfFirst=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);if(stackRef.current.length===0)focusRef.current=renderer?.currentFocusedRenderable??null,focusRef.current?.blur()},[renderer]),dismissTop=import_react17.useCallback(()=>{let selection=renderer?.getSelection();if(selection){if(renderer?.clearSelection(),selection.getSelectedText())return}stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),refocus()},[renderer,refocus]),value=import_react17.useMemo(()=>({clear(options){for(let item of stackRef.current)item.onClose?.();if(setSize("medium"),setPlacement("center"),setStack([]),options?.refocus===!1)focusRef.current=null;else refocus()},replace(thunk,onClose){captureFocusIfFirst();for(let item of stackRef.current)item.onClose?.();setSize("medium"),setPlacement("center"),setStack([{key:++entrySeq,element:thunk,onClose}])},push(thunk,onClose){captureFocusIfFirst(),setStack((s)=>[...s,{key:++entrySeq,element:thunk,onClose}])},pop(){if(stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),stackRef.current.length<=1)refocus()},get stack(){return stackRef.current},get size(){return size},setSize,get placement(){return placement},setPlacement}),[stack2,size,placement,refocus,captureFocusIfFirst]),top=stack2.at(-1),contentOpacity=top?transparentBackground2?TRANSPARENT_DIALOG_CONTENT_OPACITY:DIALOG_CONTENT_OPACITY:1;return $jsxs(ctx2.Provider,{value,children:[$jsx("box",{flexGrow:1,backgroundColor:top&&!transparentBackground2?"black":"transparent",children:$jsx("box",{flexGrow:1,opacity:contentOpacity,children:props.children})}),$jsx("box",{position:"absolute",zIndex:3000,children:top?$jsxs(ModalScopeContext,{value:MODAL_SCOPE,children:[$jsx(ModalBarrier,{dismissTop}),$jsx(Dialog,{onClose:()=>value.clear(),size,placement,children:top.element()},top.key)]}):null})]})}var MODAL_SCOPE=Symbol("rove.dialog.modal");function ModalBarrier(props){return useBindings(()=>({modal:!0,bindings:[{key:"escape",cmd:props.dismissTop},{key:"ctrl+c",cmd:props.dismissTop}]}),{modalOwner:MODAL_SCOPE}),null}function useDialog(){let value=import_react17.useContext(ctx2);if(!value)throw Error("useDialog must be used within a DialogProvider");return value}function useOptionalDialog(){return import_react17.useContext(ctx2)}function showDialog(dialog,body,opts){return new Promise((resolve2)=>{if(dialog.replace(()=>body(resolve2),()=>resolve2(void 0)),opts?.size)dialog.setSize(opts.size)})}var import_react18=__toESM(require_react_production(),1);function PaneCrashFallback(props){let{theme}=useTheme(),t2=useT(),sizing=props.width===void 0?{flexGrow:1}:{width:props.width,flexShrink:0};return $jsxs("box",{...sizing,flexDirection:"column",backgroundColor:theme.background,paddingLeft:1,paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:props.region?t2("common.paneCrash.regionTitle",{region:t2(`common.paneCrash.region.${props.region}`)}):t2("common.paneCrash.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t2(props.region?"common.paneCrash.regionHint":"common.paneCrash.hint")}),$jsx("text",{fg:theme.focusAccent,onMouseUp:props.onRetry,children:t2("common.paneCrash.retry")})]})}function formatPaneCrashDiagnostic(region,error,info){let base=error instanceof Error?error.stack??error.message:String(error),componentStack=info.componentStack?.trim()||"(unavailable)",stateChanges=recentStateChangesForDiagnostics();return`region: ${region??"root"}
|
|
2
|
+
import{FINISHED_ALERTS_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,TOAST_DURATION_MS,ZEN_ACTIVE_KEY,addUnread,armPrefixNow,bindingReachability,configurePrefix,currentPrefixConfiguration,dispatchKeyEvent,inputPassthroughReachable,insertRegistration,invokeArmedPrefixAction,isCtrlModifierKeyName,osc9,persistedSoundVolume,prefixHudHideDirect,prefixHudShowDirect,readKeybindingsFile,removeUnread,resetKeybindingsFileCache,resetPrefixConfiguration,resetPrefixState,resolveUserKeybindings,shouldAlert,shouldPlaySound,shouldShowToast}from"./chunk-x85rcep5.js";import{$Fragment,$jsx,$jsxs,createRoot,flushSync,useRenderer}from"./chunk-29kvfqeh.js";import{require_react_production}from"./chunk-2wd4744g.js";import{RemoteOrchestrator}from"./chunk-v6v272b3.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{updaterShell,updaterShellFailureHint}from"./chunk-xte4phd1.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,applyDisplayOverlay,readPersistedUiPrefs,resolveTheme,resolveThemeMode}from"./chunk-cf3vpsm5.js";import{loadUserThemes}from"./chunk-kxp04jnp.js";import{TERMINAL_TABS_PREFIX}from"./chunk-mdc7b01e.js";import{connectIfRunning}from"./chunk-e58kj4gm.js";import{CURRENT_VERSION}from"./chunk-9ckvdy0j.js";import{tildify}from"./chunk-2r1fgng9.js";import{loadStateFile,patchStateFile,readStateFileStrict,replaceStateFile}from"./chunk-32j6y5d1.js";import{localeState,setLocaleLang,t}from"./chunk-mjyhy152.js";import{isLocaleId}from"./chunk-wzss4pzh.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-cmp64q4j.js";import{kvStatePath}from"./chunk-z1nj22va.js";import{installClientCrashHandlers,logClient,logClientError,setClientLogContext}from"./chunk-0g4wc808.js";import{__toESM}from"./chunk-91sykzqq.js";import{RGBA}from"@opentui/core";var import_react3=__toESM(require_react_production(),1);var import_react=__toESM(require_react_production(),1);function useAccessor(state){return import_react.useSyncExternalStore(state.subscribe,state.get,state.get)}var store=createStateCell({themes:{...BUNDLED_THEMES},active:DEFAULT_THEME,mode:DEFAULT_THEME_MODE,transparentBackground:!0,focusAccent:"primary"});function listThemes(){return Object.keys(store.get().themes)}function hasTheme(name){return Boolean(store.get().themes[name])}function addTheme(name,theme){if(!name)return!1;if(!theme||typeof theme!=="object"||!theme.theme)return!1;return store.update((s)=>({...s,themes:{...s.themes,[name]:theme}})),!0}function selectedTheme(){return store.get().active}function setTheme(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0}function transparentBackground(){return store.get().transparentBackground}function setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))}function focusAccent(){return store.get().focusAccent}function setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))}function themeMode(){return store.get().mode}function setThemeMode(mode){store.update((s)=>({...s,mode}))}var ThemeContext=import_react3.createContext(null),HOST_PALETTE_QUERY_TIMEOUT_MS=2000;function resolveActive(state,mode){let active=state.themes[state.active];if(active)return resolveTheme(active,mode);let fallback=state.themes[DEFAULT_THEME]??Object.values(state.themes)[0];if(!fallback)return resolveTheme({theme:{background:"#000000",text:"#ffffff"}},mode);return resolveTheme(fallback,mode)}function useHostThemeMode(renderer){let[mode,setMode]=import_react3.useState(()=>renderer?.themeMode??null);return import_react3.useEffect(()=>{if(!renderer)return;let onChange=(next)=>setMode(next);return renderer.on("theme_mode",onChange),setMode(renderer.themeMode),()=>{renderer.off("theme_mode",onChange)}},[renderer]),mode}function ThemeProvider(props){import_react3.useMemo(()=>{store.update((s)=>({...s,mode:props.mode??s.mode,active:props.theme&&s.themes[props.theme]?props.theme:s.active}))},[]);let state=useAccessor(store),renderer=useRenderer(),hostMode=useHostThemeMode(renderer),mode=resolveThemeMode(state.mode,hostMode),[hostBackground,setHostBackground]=import_react3.useState(null);import_react3.useEffect(()=>{if(!state.transparentBackground)return;if(renderer?.screenMode==="split-footer")return;if(!renderer)return;let cancelled=!1;return renderer.getPalette({timeout:HOST_PALETTE_QUERY_TIMEOUT_MS}).then((colors)=>{if(cancelled||!colors.defaultBackground)return;setHostBackground(RGBA.fromHex(colors.defaultBackground))}).catch(()=>{}),()=>{cancelled=!0}},[renderer,state.transparentBackground]);let theme=import_react3.useMemo(()=>applyDisplayOverlay(resolveActive(state,mode),state.focusAccent,state.transparentBackground,hostBackground??void 0),[state,mode,hostBackground]);import_react3.useEffect(()=>{if(renderer?.screenMode==="split-footer")return;renderer?.setBackgroundColor(theme.background??RGBA.fromInts(0,0,0))},[renderer,theme]);let value=import_react3.useMemo(()=>({theme,selected:state.active,transparentBackground:state.transparentBackground,focusAccent:state.focusAccent,modePreference:state.mode,mode:()=>mode,set(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0},setMode(next){store.update((s)=>({...s,mode:next}))},setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))},setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))},preview:(options)=>applyDisplayOverlay(resolveActive({...state,active:options.themeName},resolveThemeMode(options.themeMode,hostMode)),options.focusAccent,options.transparentBackground,hostBackground??void 0),all:listThemes,has:hasTheme}),[theme,state,mode,hostMode,hostBackground]);return $jsx(ThemeContext.Provider,{value,children:props.children})}function useTheme(){let value=import_react3.useContext(ThemeContext);if(!value)throw Error("Theme context must be used within a context provider");return value}var import_react4=__toESM(require_react_production(),1);function useLang(){return useAccessor(localeState())}function useT(){let lang=useLang();return import_react4.useCallback((key,params)=>t(key,params),[lang])}var import_react7=__toESM(require_react_production(),1);var CTRL_HOLD_THRESHOLD_MS=400;function createCtrlHoldDetector(callbacks){let state={kind:"idle"},held=new Set,reset=()=>{if(state.kind==="pending")clearTimeout(state.timer);if(state.kind==="visible")callbacks.onHide();state={kind:"idle"}},cancel=()=>{reset(),held.clear()};return{keypress:(event)=>{if(!isCtrlModifierKeyName(event.name)){cancel();return}if(event.eventType==="repeat"&&held.has(event.name))return;if(event.eventType!=="press")return;if(held.add(event.name),state.kind!=="idle")return;state={kind:"pending",timer:setTimeout(()=>{state={kind:"visible"},callbacks.onReveal()},CTRL_HOLD_THRESHOLD_MS)}},keyrelease:(event)=>{if(!isCtrlModifierKeyName(event.name)||event.eventType!=="release")return;if(held.delete(event.name),held.size===0)reset()},cancel}}function availableActions(stack){let seen=new Set,actions=[],passthrough=inputPassthroughReachable(stack);for(let registration of[...stack].reverse()){let config=registration.config();if(config.enabled===!1)continue;for(let binding of config.bindings){if(binding.prefix&¤tPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}function bindByIds(handlers){let out=[];for(let id in handlers){let handler=handlers[id];if(!handler)continue;let action=typeof handler==="function"?void 0:handler,cmd=typeof handler==="function"?handler:()=>handler.run(),binding=findBinding(id),chords=binding?.keys??[],prefixChords=binding?.prefixKeys??[];if(chords.length===0&&prefixChords.length===0){console.warn(`[rove/keybindings] bindByIds: id="${id}" has no chords (or doesn't exist in RoveKeymap)`);continue}chords.forEach((key,slot)=>out.push({key,cmd,action,slot,id,yieldToPassthrough:binding?.yieldToPassthrough})),prefixChords.forEach((key,slot)=>out.push({key,prefix:!0,cmd,action,slot,id}))}return out}var KEYMAP_DEFAULTS=new Map(RoveKeymap.map((b)=>[b.id,{keys:[...b.keys],prefixKeys:b.prefixKeys&&[...b.prefixKeys],hint:b.hint?{...b.hint}:void 0}]));function defaultChordsOf(id){return KEYMAP_DEFAULTS.get(id)?.keys??[]}function resetKeymapToDefaults(){for(let row of RoveKeymap){let def=KEYMAP_DEFAULTS.get(row.id);if(!def)continue;let mutable=row;mutable.keys=[...def.keys],mutable.prefixKeys=def.prefixKeys&&[...def.prefixKeys],mutable.hint=def.hint?{...def.hint}:void 0}}var keymapVersionValue=0,keymapVersionListeners=new Set;function keymapVersion(){return keymapVersionValue}function subscribeKeymapVersion(listener){return keymapVersionListeners.add(listener),()=>{keymapVersionListeners.delete(listener)}}function bumpKeymapVersion(){keymapVersionValue+=1;for(let listener of[...keymapVersionListeners])listener()}var KEYMAP_BY_ID=new Map(RoveKeymap.map((b)=>[b.id,b]));function findBinding(id){return KEYMAP_BY_ID.get(id)}var MODIFIER_GLYPH={ctrl:"\u2303",control:"\u2303",alt:"\u2325",opt:"\u2325",option:"\u2325",shift:"\u21E7",cmd:"\u2318",command:"\u2318",meta:"\u2318",super:"\u2318"},KEY_GLYPH={enter:"\u23CE",return:"\u23CE",esc:"\u238B",escape:"\u238B",space:"\u2423",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",backspace:"\u232B",delete:"\u2326",del:"\u2326",pgup:"\u21DE",pageup:"\u21DE",pgdn:"\u21DF",pagedown:"\u21DF",home:"\u2196",end:"\u2198"};function formatKey(k,upper){if(k.includes("/"))return k.split("/").map((part)=>formatKey(part,upper)).join("/");let low=k.toLowerCase();if(low==="tab")return"tab";let named=KEY_GLYPH[low];if(named)return named;if(/^f\d{1,2}$/.test(low))return low.toUpperCase();if(!upper)return k;if(/^[a-z]$/.test(low))return k.toUpperCase();return k.replace(/[a-z]+/gi,(run)=>run.toUpperCase())}function formatChord(chord,prefixGlyph="\u2303A"){let s=chord.trim();if(!s)return s;let pm=/^prefix\s+(.+)$/i.exec(s);if(pm){let suffix=pm[1]??"";return`${prefixGlyph} ${suffix.includes("+")?formatChord(suffix,prefixGlyph):formatKey(suffix,!0)}`}let parts=s.split("+");if(parts.length===1)return formatKey(parts[0]??"",!1);let key=parts[parts.length-1]??"";return`${parts.slice(0,-1).map((p)=>MODIFIER_GLYPH[p.toLowerCase().trim()]??p).join("")} ${formatKey(key,!0)}`}var DIRECT_GUIDE_PREFIX_ACTION_ID="prefix.moreCommands",CTRL_FOLLOW_UP_CHORD=/^ctrl\+[^+]+$/;function ctrlFollowUpKey(chord){return CTRL_FOLLOW_UP_CHORD.test(chord)?chord.slice(5):null}function shortcutCaption(input){let binding=findBinding(input.bindingId);if(!binding)return null;if(input.reachability.direct.has(input.bindingId)){let direct=binding.keys[0];if(direct)return formatChord(direct)}if(input.prefixKey&&input.reachability.prefix.has(input.bindingId)){let stroke=binding.prefixKeys?.[0];if(stroke)return`${formatChord(input.prefixKey)} ${formatChord(stroke)}`}return null}function directGuideOptions(reachability,prefixKey){let options=RoveKeymap.filter((binding)=>reachability.direct.has(binding.id)).flatMap((binding)=>{let strokes=binding.keys.flatMap((chord)=>ctrlFollowUpKey(chord)??[]);if(strokes.length>2)return[{stroke:`${strokes[0]}-${strokes.at(-1)}`,action:binding.id}];return strokes.map((stroke)=>({stroke,action:binding.id}))}),prefixStroke=prefixKey?ctrlFollowUpKey(prefixKey):null;if(prefixStroke&&reachability.prefix.size>0)options.push({stroke:prefixStroke,action:DIRECT_GUIDE_PREFIX_ACTION_ID});return options}var import_react5=__toESM(require_react_production(),1);function useLatest(value){let ref=import_react5.useRef(value);return ref.current=value,ref}var ModalScopeContext=import_react7.createContext(null),nextId=1,stack=[],installedRenderer=null,installed=null,listener=null,releaseListener=null,ctrlHoldDetector=null,supersededRenderers=new WeakSet;function ensureInstalled(renderer){if(!renderer)throw Error("useBindings: no renderer in scope; call inside a component rendered by @opentui/react.");if(installedRenderer===renderer)return;if(supersededRenderers.has(renderer))return;if(installed&&listener)installed.off("keypress",listener);if(installed&&releaseListener)installed.off("keyrelease",releaseListener);if(ctrlHoldDetector?.cancel(),installedRenderer)supersededRenderers.add(installedRenderer);stack.length=0,resetPrefixState(),installedRenderer=renderer,installed=renderer.keyInput,ctrlHoldDetector=createCtrlHoldDetector({onReveal:()=>{resetPrefixState();let options=directGuideOptions(bindingReachability(stack),currentPrefixConfiguration().key);if(options.length>0)prefixHudShowDirect(options)},onHide:prefixHudHideDirect}),listener=(evt)=>{profileTick("key"),ctrlHoldDetector?.keypress(evt),dispatchKeyEvent(stack,evt,Date.now(),{flushSync})},releaseListener=(evt)=>ctrlHoldDetector?.keyrelease(evt),installed.on("keypress",listener),installed.on("keyrelease",releaseListener)}function modalActive(){return stack.some((r)=>r.modalOwner!==void 0)}function currentBindingReachability(){return bindingReachability(stack)}function armPrefixFromCurrentStack(){return armPrefixNow(stack)}function invokeArmedPrefixActionFromCurrentStack(actionId,stroke){return invokeArmedPrefixAction(stack,actionId,stroke)}var stackVersion=0,stackListeners=new Set;function bumpStackVersion(){prefixHudHideDirect(),stackVersion++;for(let listener2 of stackListeners)listener2()}function bindingReachabilitySignature(config){let bindings=config.bindings.map((binding)=>[binding.id??"",binding.key,binding.prefix===!0?"p":"d",binding.passthrough===!0?"i":"u"].join(":")).join("|");return`${config.enabled===!1?"off":"on"};${config.modal===!0?"modal":"plain"};${bindings}`}function subscribeBindingStack(listener2){return stackListeners.add(listener2),()=>{stackListeners.delete(listener2)}}function useBindingStackVersion(){return import_react7.useSyncExternalStore((onChange)=>{return stackListeners.add(onChange),()=>stackListeners.delete(onChange)},()=>stackVersion)}function useBindings(config,opts){let renderer=useRenderer();ensureInstalled(renderer);let configRef=useLatest(config),scope=import_react7.useContext(ModalScopeContext),reachabilitySignature=bindingReachabilitySignature(config()),previousReachabilitySignature=import_react7.useRef(reachabilitySignature);import_react7.useEffect(()=>{if(previousReachabilitySignature.current===reachabilitySignature)return;previousReachabilitySignature.current=reachabilitySignature,bumpStackVersion()},[reachabilitySignature]),import_react7.useEffect(()=>{if(supersededRenderers.has(renderer))return;if(opts?.modalOwner!==void 0)resetPrefixState();let reg={config:()=>configRef.current(),id:nextId++,modalOwner:opts?.modalOwner,modalMember:opts?.modalOwner===void 0?scope??void 0:void 0};return insertRegistration(stack,reg),bumpStackVersion(),()=>{let i=stack.findIndex((r)=>r.id===reg.id);if(i>=0)stack.splice(i,1);bumpStackVersion()}},[])}function pageCloseBindings(cmd){return[{key:"escape",cmd},{key:"q",cmd},{key:"ctrl+c",cmd}]}function currentPaletteActions(){return capturePaletteActions(stack)}import{createCliRenderer}from"@opentui/core";var import_react21=__toESM(require_react_production(),1);async function connectPaneOrchestrator(options={}){let tag=options.logTag??"orch-connect",connect=options.connect??connectIfRunning,remote=null;try{let client=await connect();if(!client)return logClient(tag,"no daemon running \u2014 caller degrades"),null;return remote=new RemoteOrchestrator(client,{...options.orchestratorOptions,channels:options.channels}),await remote.init(),remote}catch(err){return logClientError(tag,err),remote?.dispose(),null}}var cached=null;function applyUserKeybindings(){if(cached)return cached;let{report,prefix}=resolveUserKeybindings(readKeybindingsFile(),RoveKeymap,process.platform);if(report.exists)configurePrefix(prefix);for(let w of report.warnings)console.warn(`[rove/keybindings] ${w}`);return cached=report,cached}function pluginKeybindings(){return userKeybindingsReport().plugins}function userKeybindingsReport(){return cached??applyUserKeybindings()}function reloadUserKeybindings(){cached=null,resetKeybindingsFileCache(),resetKeymapToDefaults(),resetPrefixConfiguration();let report=applyUserKeybindings();return bumpKeymapVersion(),report}var UI_PREFS_FOCUS_ACCENT_SLOTS=["primary","success","info"];var UI_PREFS_THEME_MODES=["dark","light","auto"];function applyUiPrefs(target,prefs){if(typeof prefs.theme==="string"&&prefs.theme.length>0&&prefs.theme!==target.selectedTheme()){if(!target.hasTheme(prefs.theme))target.reloadUserThemes();if(target.hasTheme(prefs.theme))target.setTheme(prefs.theme)}if(prefs.themeMode===null||typeof prefs.themeMode==="string"){let mode=normalizeThemeMode(prefs.themeMode);if(mode&&mode!==target.themeMode())target.setThemeMode(mode)}if(typeof prefs.transparentBackground==="boolean"&&prefs.transparentBackground!==target.transparentBackground())target.setTransparentBackground(prefs.transparentBackground);if(prefs.focusAccent===null||typeof prefs.focusAccent==="string"){let slot=normalizeFocusAccent(prefs.focusAccent);if(slot&&slot!==target.focusAccent())target.setFocusAccent(slot)}}function normalizeFocusAccent(value){if(value===null)return"primary";return UI_PREFS_FOCUS_ACCENT_SLOTS.includes(value)?value:null}function normalizeThemeMode(value){if(value===null)return"dark";return UI_PREFS_THEME_MODES.includes(value)?value:null}var STALL_HEARTBEAT_MS=1000,STALL_THRESHOLD_MS=2000;function stallReport(gapMs,mem,heartbeatMs=STALL_HEARTBEAT_MS,thresholdMs=STALL_THRESHOLD_MS){let stallMs=gapMs-heartbeatMs;if(stallMs<thresholdMs)return null;let mb=(n)=>Math.round(n/1048576);return`event loop stalled ~${stallMs}ms \u2014 rss=${mb(mem.rss)}MB heapUsed=${mb(mem.heapUsed)}MB`}function installEventLoopStallTelemetry(){let last=Date.now(),timer=setInterval(()=>{let now=Date.now(),gap=now-last;last=now;let report=stallReport(gap,process.memoryUsage());if(report)logClient("stall",report)},STALL_HEARTBEAT_MS);return timer.unref?.(),()=>clearInterval(timer)}var KITTY_KEYBOARD={};function hostTargetFps(){return 60}function hostRenderOptions(onDestroy){let base={backgroundColor:"transparent",externalOutputMode:"passthrough",exitOnCtrlC:!1,screenMode:"alternate-screen",useKittyKeyboard:KITTY_KEYBOARD,targetFps:hostTargetFps()};return onDestroy?{...base,onDestroy}:base}function inlineRenderOptions(heightRows,onDestroy){let base={backgroundColor:"transparent",exitOnCtrlC:!1,screenMode:"split-footer",footerHeight:heightRows,useKittyKeyboard:KITTY_KEYBOARD};return onDestroy?{...base,onDestroy}:base}function installExitRestoreBackstop(renderer){process.on("exit",()=>renderer.destroy())}var BRACKETED_PASTE_ON="\x1B[?2004h",BRACKETED_PASTE_OFF="\x1B[?2004l";function installBracketedPasteMode(stdout=process.stdout){if(!stdout.isTTY)return()=>{};let write=(seq)=>{try{stdout.write(seq)}catch{}};write(BRACKETED_PASTE_ON);let restored=!1,restore=()=>{if(restored)return;restored=!0,write(BRACKETED_PASTE_OFF)};return process.on("exit",restore),restore}var exitCriticalWork=new Set;async function whenExitReady(){while(exitCriticalWork.size>0)await Promise.allSettled([...exitCriticalWork])}function installPaneExitBackstop(opts={}){let ceilingMs=opts.ceilingMs??5000,exit=opts.exit??((code)=>process.exit(code)),exitScheduled=!1,exited=!1,exitOnce=()=>{if(exited)return;exited=!0,exit(0)},scheduleExit=()=>{if(exitScheduled)return;exitScheduled=!0;let ceiling=setTimeout(()=>{console.error(`[rove] exit backstop: ${exitCriticalWork.size} task(s) still in flight after ${ceilingMs}ms \u2014 exiting anyway`),exitOnce()},ceilingMs);ceiling.unref?.(),whenExitReady().then(()=>{clearTimeout(ceiling),exitOnce()})};for(let signal of["SIGHUP","SIGTERM","SIGINT"])process.on(signal,scheduleExit)}function installOrphanExitWatchdog(intervalMs=5000){let timer=setInterval(()=>{if(process.ppid===1)process.exit(0)},intervalMs);return timer.unref?.(),()=>clearInterval(timer)}var SYNC_START=Buffer.from("\x1B[?2026h"),SYNC_END=Buffer.from("\x1B[?2026l");class ImeAnchorController{owner=null;anchor=null;claim(owner,anchor){this.owner=owner,this.anchor={x:Math.max(0,Math.trunc(anchor.x)),y:Math.max(0,Math.trunc(anchor.y))}}release(owner){if(this.owner!==owner)return!1;return this.owner=null,this.anchor=null,!0}current(){return this.anchor}}var imeAnchorController=new ImeAnchorController;class ImeAnchorFrameTransformer{controller;pending=Buffer.alloc(0);frame=Buffer.alloc(0);constructor(controller){this.controller=controller}push(chunk){let data=this.pending.length>0?Buffer.concat([this.pending,chunk]):chunk;this.pending=Buffer.alloc(0);let output=[],offset=0;while(offset<data.length){if(this.frame.length===0){let start=data.indexOf(SYNC_START,offset);if(start<0){let tail2=data.subarray(offset),pendingLength2=longestMarkerPrefixSuffix(tail2,[SYNC_START]),safeLength2=tail2.length-pendingLength2;if(safeLength2>0)output.push(tail2.subarray(0,safeLength2));if(pendingLength2>0)this.pending=Buffer.from(tail2.subarray(safeLength2));break}if(start>offset)output.push(data.subarray(offset,start));this.frame=Buffer.from(SYNC_START),offset=start+SYNC_START.length;continue}let end=data.indexOf(SYNC_END,offset),restart=data.indexOf(SYNC_START,offset);if(restart>=0&&(end<0||restart<end)){this.frame=Buffer.from(SYNC_START),offset=restart+SYNC_START.length;continue}if(end>=0){if(end>offset)this.frame=Buffer.concat([this.frame,data.subarray(offset,end)]);output.push(this.frame);let anchor=this.controller.current();if(anchor)output.push(Buffer.from(`\x1B[${anchor.y+1};${anchor.x+1}H\x1B[?25l`));output.push(SYNC_END),this.frame=Buffer.alloc(0),offset=end+SYNC_END.length;continue}let tail=data.subarray(offset),pendingLength=longestMarkerPrefixSuffix(tail,[SYNC_START,SYNC_END]),safeLength=tail.length-pendingLength;if(safeLength>0)this.frame=Buffer.concat([this.frame,tail.subarray(0,safeLength)]);if(pendingLength>0)this.pending=Buffer.from(tail.subarray(safeLength));break}return output.length>0?Buffer.concat(output):Buffer.alloc(0)}flush(){if(this.frame.length>0)return this.frame=Buffer.alloc(0),this.pending=Buffer.alloc(0),Buffer.alloc(0);let pending=this.pending;return this.pending=Buffer.alloc(0),pending}}function longestMarkerPrefixSuffix(bytes,markers){let max=Math.min(bytes.length,Math.max(...markers.map((marker)=>marker.length-1)));for(let length=max;length>0;length-=1){let suffix=bytes.subarray(bytes.length-length);if(markers.some((marker)=>length<marker.length&&suffix.equals(marker.subarray(0,length))))return length}return 0}function asBuffer(chunk,encodingOrCallback){if(typeof chunk!=="string")return Buffer.from(chunk);let encoding=typeof encodingOrCallback==="string"?encodingOrCallback:void 0;return Buffer.from(chunk,encoding)}function writeCallback(encodingOrCallback,maybeCallback){return typeof encodingOrCallback==="function"?encodingOrCallback:maybeCallback}function createImeAnchoredOutput(target,controller=imeAnchorController){let transformer=new ImeAnchorFrameTransformer(controller),exposedWrite=(chunk,encodingOrCallback,maybeCallback)=>{let transformed=transformer.push(asBuffer(chunk,encodingOrCallback)),callback=writeCallback(encodingOrCallback,maybeCallback);if(transformed.length===0){if(callback)queueMicrotask(()=>callback(null));return!0}return callback?target.write(transformed,callback):target.write(transformed)};return{stdout:new Proxy(target,{get(stream,property){if(property==="write")return exposedWrite;let value=Reflect.get(stream,property,stream);return typeof value==="function"?value.bind(stream):value},set(stream,property,value){if(property==="write")return exposedWrite=value,!0;return Reflect.set(stream,property,value,stream)}}),flush(){let pending=transformer.flush();if(pending.length>0)target.write(pending)}}}var IME_ANCHOR_PLATFORMS=new Set(["darwin","win32"]);function createHostImeOutput(opts){if(!IME_ANCHOR_PLATFORMS.has(opts.platform)||!opts.fullscreen)return{active:!1,rendererOptions:{},attach:()=>()=>{},flush:()=>{}};let output=createImeAnchoredOutput(opts.stdout,opts.controller);return{active:!0,rendererOptions:{stdout:output.stdout,remote:!1},attach:(renderer)=>installRendererResizeForwarder(renderer,opts.stdout),flush:()=>output.flush()}}function installRendererResizeForwarder(renderer,terminal,signals=process){let onResize=()=>{let{columns:width,rows:height}=terminal;if(!width||!height)return;renderer.resize(width,height)};return signals.on("SIGWINCH",onResize),()=>signals.removeListener("SIGWINCH",onResize)}function needsScreenSelfHeal(platform){return platform==="win32"}function requestFullRepaint(renderer){if(renderer.screenMode!=="alternate-screen")return!1;let internals=renderer;return internals.forceFullRepaintRequested=!0,renderer.requestRender(),!0}function writeThroughRenderer(renderer,chunk,fallback=process.stdout){let writeOut=renderer?.writeOut;try{if(typeof writeOut==="function")writeOut.call(renderer,chunk);else fallback.write(chunk)}catch{}}function redrawScreen(renderer){if(renderer.screenMode!=="alternate-screen")return!1;return writeThroughRenderer(renderer,"\x1B[H\x1B[2J"),requestFullRepaint(renderer)}function installScreenSelfHeal(opts){let platform=opts.platform??process.platform;if(!needsScreenSelfHeal(platform))return()=>{};let{renderer}=opts,repaint=()=>{requestFullRepaint(renderer)};return renderer.on("resize",repaint),renderer.on("focus",repaint),()=>{renderer.off("resize",repaint),renderer.off("focus",repaint)}}var import_react9=__toESM(require_react_production(),1);var PANE_ORDER=["sidebar","workspace","files","terminal"],FocusContext=import_react9.createContext(null);function FocusProvider(props){let[focused,setFocusedState]=import_react9.useState(props.initial??"sidebar"),renderer=useRenderer(),focusedRef=useLatest(focused),setFocused=import_react9.useCallback((pane)=>{if(focusedRef.current===pane)return;let current=renderer?.currentFocusedRenderable;if(current&&!current.isDestroyed)try{current.blur()}catch{}setFocusedState(pane)},[renderer]),cycle=import_react9.useCallback((delta)=>{let next=(PANE_ORDER.indexOf(focusedRef.current)+delta+PANE_ORDER.length)%PANE_ORDER.length;setFocused(PANE_ORDER[next])},[setFocused]),value=import_react9.useMemo(()=>({focused,is:(pane)=>focused===pane,setFocused,cycle}),[focused,setFocused,cycle]);return $jsx(FocusContext.Provider,{value,children:props.children})}function useFocus(){let ctx=import_react9.useContext(FocusContext);if(!ctx)throw Error("useFocus: must be called inside <FocusProvider>. See src/tui-react/context/focus.tsx.");return ctx}function useOptionalFocus(){return import_react9.useContext(FocusContext)}var import_react10=__toESM(require_react_production(),1);var WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,ZEN_ACTIVE_KEY]);function createKvCore(){let store2=createStateCell(loadStateFile(),"kv.snapshot"),dirtyKeys=new Set,quiet=new Map,seeded=new Map,writeTimer=null,errorListeners=new Set,reportedKeys=new Set;function reportWriteError(err){let fresh=[...dirtyKeys].filter((key)=>!reportedKeys.has(key));if(fresh.length===0)return;for(let key of fresh)reportedKeys.add(key);let failure={keys:fresh,file:kvStatePath(),error:err};for(let listener2 of errorListeners)listener2(failure)}function writeNow(label){if(dirtyKeys.size===0)return!0;try{let patch={},snap=store2.get();for(let key of dirtyKeys)patch[key]=quiet.has(key)?quiet.get(key):snap[key];return patchStateFile(patch,"strict"),dirtyKeys.clear(),reportedKeys.clear(),!0}catch(err){return console.error(`[rove] kv ${label} failed:`,err),reportWriteError(err),!1}}function cancelTimer(){if(writeTimer)clearTimeout(writeTimer),writeTimer=null}function scheduleWrite(){cancelTimer(),writeTimer=setTimeout(()=>{writeTimer=null,writeNow("write")},WRITE_DEBOUNCE_MS)}function merge(fresh,keepQuiet){let before=store2.get(),next={...fresh};for(let[key,value]of seeded)if(next[key]===void 0)next[key]=value;for(let key of dirtyKeys)if(before[key]===void 0)delete next[key];else next[key]=before[key];let quietChanged=!1;for(let key of[...quiet.keys()]){if(dirtyKeys.has(key))continue;if(!keepQuiet||JSON.stringify(quiet.get(key))!==JSON.stringify(fresh[key])){quietChanged=!0,quiet.delete(key);continue}if(before[key]===void 0)delete next[key];else next[key]=before[key]}if(dirtyKeys.size>0)scheduleWrite();let changed=0;for(let key of new Set([...Object.keys(before),...Object.keys(next)]))if(JSON.stringify(before[key])!==JSON.stringify(next[key]))changed++;if(changed>0||quietChanged)store2.set(next);return changed}return{snapshot:store2.get,subscribe:store2.subscribe,get(key,defaultValue){return(quiet.has(key)?quiet.get(key):store2.get()[key])??defaultValue},set(key,value){if(key.startsWith(TERMINAL_TABS_PREFIX)){logClientError("kv",Error(`refused a local write of ${key}: tabs go through the daemon`));return}quiet.delete(key),store2.update((s)=>{if(value!==void 0)return{...s,[key]:value};if(!(key in s))return s;let next={...s};return delete next[key],next}),dirtyKeys.add(key),scheduleWrite()},setQuiet(key,value){quiet.set(key,value),dirtyKeys.add(key),scheduleWrite()},seed(key,value){if(!seeded.has(key))seeded.set(key,value);if(quiet.has(key)||store2.get()[key]!==void 0)return;store2.update((s)=>({...s,[key]:value}))},flush(){return cancelTimer(),writeNow("flush")},clear(){try{replaceStateFile({})}catch(err){return console.error("[rove] kv clear write failed:",err),!1}return cancelTimer(),dirtyKeys.clear(),reportedKeys.clear(),quiet.clear(),store2.set({}),!0},reload(){try{return readStateFileStrict(),cancelTimer(),writeNow("reload flush"),{ok:!0,changed:merge(readStateFileStrict(),!1)}}catch(error){return{ok:!1,error}}},follow(shared){let next={...shared};for(let key of PER_WINDOW_KEYS)delete next[key];for(let[key,value]of Object.entries(store2.get()))if(isUnpublishedStateKey(key)||PER_WINDOW_KEYS.has(key))next[key]=value;merge(next,!0)},onWriteError(listener2){return errorListeners.add(listener2),()=>{errorListeners.delete(listener2)}}}}var Ctx=import_react10.createContext(null);function KVProvider(props){let[core]=import_react10.useState(createKvCore),snapshot=import_react10.useSyncExternalStore(core.subscribe,core.snapshot,core.snapshot);import_react10.useEffect(()=>{let flush=()=>{core.flush()};return process.on("exit",flush),()=>{process.off("exit",flush)}},[core]);let value=import_react10.useMemo(()=>({ready:!0,store:snapshot,signal(name,defaultValue){return core.seed(name,defaultValue),[()=>core.get(name)??defaultValue,(next)=>core.set(name,next)]},get:core.get,set:core.set,setQuiet:core.setQuiet,flush:core.flush,clear:core.clear,reload:core.reload,follow:core.follow,onWriteError:core.onWriteError}),[core,snapshot]);return $jsx(Ctx.Provider,{value,children:props.children})}function useKV(){let value=import_react10.useContext(Ctx);if(!value)throw Error("KV context must be used within a context provider");return value}function useOptionalKV(){return import_react10.useContext(Ctx)??null}var import_react13=__toESM(require_react_production(),1);var import_react12=__toESM(require_react_production(),1);import{existsSync,mkdirSync}from"fs";import{tmpdir}from"os";import{basename,delimiter,extname,isAbsolute,join,resolve}from"path";var pulse_default="../pulse-ynhb2ave.wav";function scaleWavVolume(wav,volume){let gain=Math.min(1,Math.max(0,volume));if(wav.length<12)return null;if(wav.readUInt32BE(0)!==1380533830||wav.readUInt32BE(8)!==1463899717)return null;let bitsPerSample,format,data;for(let offset=12;offset+8<=wav.length;){let id=wav.readUInt32BE(offset),size=wav.readUInt32LE(offset+4),start=offset+8,end=start+size;if(size<0||end>wav.length)return null;if(id===1718449184){if(size<16)return null;format=wav.readUInt16LE(start),bitsPerSample=wav.readUInt16LE(start+14)}else if(id===1684108385)data={start,end};offset=end+size%2}if(format!==1||bitsPerSample!==16||!data)return null;if((data.end-data.start)%2!==0)return null;let out=Buffer.from(wav);if(gain===1)return out;for(let i=data.start;i<data.end;i+=2){let scaled=Math.round(out.readInt16LE(i)*gain);out.writeInt16LE(Math.min(32767,Math.max(-32768,scaled)),i)}return out}var pulseAsset=isAbsolute(pulse_default)?pulse_default:resolve(import.meta.dir,pulse_default),DIR=join(tmpdir(),"rove-sfx"),PLAYERS=["ffplay","mpv","mpg123","mpg321","mplayer","afplay","play","omxplayer","aplay","cmdmp3","cvlc","powershell.exe"];function args(player,file){if(player==="ffplay")return[player,"-autoexit","-nodisp",file];if(player==="mpv")return[player,"--no-video","--audio-display=no",file];if(player==="mplayer")return[player,"-vo","null",file];if(player==="cvlc")return[player,"--play-and-exit",file];if(player==="powershell.exe")return[player,"-c",`(New-Object Media.SoundPlayer '${file.replace(/'/g,"''")}').PlaySync()`];return[player,file]}var cachedPlayer,cachedPaths=new Map;function pathDirs(rawPath,delim=delimiter){return rawPath.split(delim).filter(Boolean)}function pickPlayer(){if(cachedPlayer!==void 0)return cachedPlayer;let segments=pathDirs(process.env.PATH??"");return cachedPlayer=PLAYERS.find((p)=>segments.some((dir)=>existsSync(join(dir,p))))??null,cachedPlayer}function assetNameFor(assetPath,volume){let name=basename(assetPath),ext=extname(name);return`${name.slice(0,name.length-ext.length)}@${Math.round(volume*100)}${ext}`}async function ensureAsset(volume){let cached2=cachedPaths.get(volume);if(cached2)return cached2;let pending=(async()=>{mkdirSync(DIR,{recursive:!0});let dest=join(DIR,assetNameFor(pulseAsset,volume)),out=Bun.file(dest);if(await out.exists())return dest;let source=Buffer.from(await Bun.file(pulseAsset).arrayBuffer());return await Bun.write(out,scaleWavVolume(source,volume)??source),dest})();return cachedPaths.set(volume,pending),pending}function pulse(volume=persistedSoundVolume()){if(!(volume>0))return;let player=pickPlayer();if(!player)return;ensureAsset(volume).then((path)=>{try{Bun.spawn(args(player,path),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref?.()}catch{}}).catch(()=>{return})}var ctx=import_react12.createContext(null);function NotificationsProvider(props){let[toasts,setToasts]=import_react12.useState([]),[unread,setUnread]=import_react12.useState(new Map),kv=useOptionalKV(),renderer=useRenderer(),snapshot=import_react12.useMemo(()=>loadStateFile(),[]),prefs=import_react12.useMemo(()=>({"notifications.sound.enabled":kv?.get("notifications.sound.enabled")??snapshot["notifications.sound.enabled"],"notifications.toast.enabled":kv?.get("notifications.toast.enabled")??snapshot["notifications.toast.enabled"],[FINISHED_ALERTS_KEY]:kv?.get(FINISHED_ALERTS_KEY)??snapshot[FINISHED_ALERTS_KEY]}),[kv,snapshot]),counter=import_react12.useRef(0),timers=import_react12.useRef(new Set);import_react12.useEffect(()=>()=>{for(let id of timers.current)clearTimeout(id);timers.current.clear()},[]);let dismiss=import_react12.useCallback((id)=>{setToasts((prev)=>prev.filter((t2)=>t2.id!==id))},[]),notify=import_react12.useCallback((input)=>{if(setUnread((prev)=>addUnread(prev,input)),!shouldAlert(input,prefs[FINISHED_ALERTS_KEY]!==!1))return;let soundEnabled=prefs["notifications.sound.enabled"]!==!1;if(shouldPlaySound(input,soundEnabled))writeThroughRenderer(renderer,`\x07${osc9(`Rove \u2014 ${input.title}`)}`),pulse();let toastEnabled=prefs["notifications.toast.enabled"]!==!1;if(shouldShowToast(input.kind,toastEnabled)){let id=++counter.current;setToasts((prev)=>[...prev,{id,...input}]);let timer=setTimeout(()=>{timers.current.delete(timer),dismiss(id)},TOAST_DURATION_MS);timers.current.add(timer)}},[prefs,dismiss,renderer]),markRead=import_react12.useCallback((taskId,tabId)=>{setUnread((prev)=>removeUnread(prev,taskId,tabId))},[]),value=import_react12.useMemo(()=>({toasts,unread,notify,dismiss,markRead}),[toasts,unread,notify,dismiss,markRead]);return $jsx(ctx.Provider,{value,children:props.children})}function useNotifications(){let value=import_react12.useContext(ctx);if(!value)throw Error("useNotifications must be used within a NotificationsProvider");return value}function useOptionalNotifications(){return import_react12.useContext(ctx)}function KvWriteErrorToasts(){let kv=useOptionalKV(),notifications=useOptionalNotifications();return import_react13.useEffect(()=>{if(!kv||!notifications)return;return kv.onWriteError((failure)=>{notifications.notify({taskId:"",tabId:"",kind:"error",title:t("settings.stateWrite.failedTitle"),body:t("settings.stateWrite.failedBody",{file:tildify(failure.file),keys:failure.keys.join(", ")})})})},[kv,notifications]),null}var import_react17=__toESM(require_react_production(),1);function isNarrowWidth(cols){return cols<70}function narrowSurface(args2){if(args2.focusedPane==="sidebar")return"sidebar";return args2.hasSelection||args2.hasOpenPage?"content":"sidebar"}var import_react15=__toESM(require_react_production(),1);var stores=new WeakMap;function terminalSizeStore(source){let existing=stores.get(source);if(existing)return existing;let listeners=new Set,size={width:source.width,height:source.height},notify=()=>{for(let listener2 of listeners)listener2()},store2={subscribe(listener2){if(listeners.add(listener2),listeners.size===1)source.on("resize",notify);return()=>{if(listeners.delete(listener2),listeners.size===0)source.off("resize",notify)}},snapshot(){if(size.width!==source.width||size.height!==source.height)size={width:source.width,height:source.height};return size}};return stores.set(source,store2),store2}function useTerminalSize(){let store2=terminalSizeStore(useRenderer());return import_react15.useSyncExternalStore(store2.subscribe,store2.snapshot)}function useDialogPaddingX(){let dims=useTerminalSize();return isNarrowWidth(dims.width)?1:2}var DIALOG_CONTENT_OPACITY=0.5,TRANSPARENT_DIALOG_CONTENT_OPACITY=0.75;function Dialog(props){let dimensions=useTerminalSize(),{theme}=useTheme(),renderer=useRenderer(),dismissRef=import_react17.useRef(!1),width=props.size==="xlarge"?140:props.size==="large"?110:props.size==="small"?50:80,VERTICAL_MARGIN=2,upperFifth=props.placement==="upper-fifth"&&!isNarrowWidth(dimensions.width),headerTop=Math.max(2,Math.floor(dimensions.height/5)),cardTop=upperFifth?Math.max(2,headerTop-1):0,maxCardHeight=Math.max(8,upperFifth?dimensions.height-cardTop-2:dimensions.height-4);return $jsx("box",{onMouseDown:()=>{dismissRef.current=!!renderer?.getSelection()},onMouseUp:()=>{if(dismissRef.current){dismissRef.current=!1;return}props.onClose?.()},width:dimensions.width,height:dimensions.height,alignItems:"center",justifyContent:upperFifth?"flex-start":"center",paddingTop:cardTop,position:"absolute",zIndex:3000,left:0,top:0,shouldFill:!1,children:$jsx("box",{onMouseUp:(e)=>{dismissRef.current=!1,e.stopPropagation()},width,maxWidth:dimensions.width-2,maxHeight:maxCardHeight,flexShrink:1,flexGrow:0,backgroundColor:theme.backgroundDialog,paddingTop:1,children:props.children})})}var entrySeq=0,ctx2=import_react17.createContext(null);function DialogProvider(props){let[stack2,setStack]=import_react17.useState([]),[size,setSize]=import_react17.useState("medium"),[placement,setPlacement]=import_react17.useState("center"),renderer=useRenderer(),{transparentBackground:transparentBackground2}=useTheme(),focusRef=import_react17.useRef(null),refocusTimer=import_react17.useRef(null);import_react17.useEffect(()=>()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current)},[]);let refocus=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);refocusTimer.current=setTimeout(()=>{let focus=focusRef.current;if(!focus||focus.isDestroyed)return;function find(item){for(let child of item.getChildren()){if(child===focus)return!0;if(find(child))return!0}return!1}let root=renderer?.root;if(!root)return;if(!find(root))return;focus.focus()},1)},[renderer]),stackRef=useLatest(stack2),captureFocusIfFirst=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);if(stackRef.current.length===0)focusRef.current=renderer?.currentFocusedRenderable??null,focusRef.current?.blur()},[renderer]),dismissTop=import_react17.useCallback(()=>{let selection=renderer?.getSelection();if(selection){if(renderer?.clearSelection(),selection.getSelectedText())return}stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),refocus()},[renderer,refocus]),value=import_react17.useMemo(()=>({clear(options){for(let item of stackRef.current)item.onClose?.();if(setSize("medium"),setPlacement("center"),setStack([]),options?.refocus===!1)focusRef.current=null;else refocus()},replace(thunk,onClose){captureFocusIfFirst();for(let item of stackRef.current)item.onClose?.();setSize("medium"),setPlacement("center"),setStack([{key:++entrySeq,element:thunk,onClose}])},push(thunk,onClose){captureFocusIfFirst(),setStack((s)=>[...s,{key:++entrySeq,element:thunk,onClose}])},pop(){if(stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),stackRef.current.length<=1)refocus()},get stack(){return stackRef.current},get size(){return size},setSize,get placement(){return placement},setPlacement}),[stack2,size,placement,refocus,captureFocusIfFirst]),top=stack2.at(-1),contentOpacity=top?transparentBackground2?TRANSPARENT_DIALOG_CONTENT_OPACITY:DIALOG_CONTENT_OPACITY:1;return $jsxs(ctx2.Provider,{value,children:[$jsx("box",{flexGrow:1,backgroundColor:top&&!transparentBackground2?"black":"transparent",children:$jsx("box",{flexGrow:1,opacity:contentOpacity,children:props.children})}),$jsx("box",{position:"absolute",zIndex:3000,children:top?$jsxs(ModalScopeContext,{value:MODAL_SCOPE,children:[$jsx(ModalBarrier,{dismissTop}),$jsx(Dialog,{onClose:()=>value.clear(),size,placement,children:top.element()},top.key)]}):null})]})}var MODAL_SCOPE=Symbol("rove.dialog.modal");function ModalBarrier(props){return useBindings(()=>({modal:!0,bindings:[{key:"escape",cmd:props.dismissTop},{key:"ctrl+c",cmd:props.dismissTop}]}),{modalOwner:MODAL_SCOPE}),null}function useDialog(){let value=import_react17.useContext(ctx2);if(!value)throw Error("useDialog must be used within a DialogProvider");return value}function useOptionalDialog(){return import_react17.useContext(ctx2)}function showDialog(dialog,body,opts){return new Promise((resolve2)=>{if(dialog.replace(()=>body(resolve2),()=>resolve2(void 0)),opts?.size)dialog.setSize(opts.size)})}var import_react18=__toESM(require_react_production(),1);function PaneCrashFallback(props){let{theme}=useTheme(),t2=useT(),sizing=props.width===void 0?{flexGrow:1}:{width:props.width,flexShrink:0};return $jsxs("box",{...sizing,flexDirection:"column",backgroundColor:theme.background,paddingLeft:1,paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:props.region?t2("common.paneCrash.regionTitle",{region:t2(`common.paneCrash.region.${props.region}`)}):t2("common.paneCrash.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t2(props.region?"common.paneCrash.regionHint":"common.paneCrash.hint")}),$jsx("text",{fg:theme.focusAccent,onMouseUp:props.onRetry,children:t2("common.paneCrash.retry")})]})}function formatPaneCrashDiagnostic(region,error,info){let base=error instanceof Error?error.stack??error.message:String(error),componentStack=info.componentStack?.trim()||"(unavailable)",stateChanges=recentStateChangesForDiagnostics();return`region: ${region??"root"}
|
|
3
3
|
${base}
|
|
4
4
|
React component stack:
|
|
5
5
|
${componentStack}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{findVerb}from"./chunk-
|
|
2
|
+
import{findVerb}from"./chunk-z3wrbtcq.js";import{VERB_GROUP_IDS}from"./chunk-r5j8fycq.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
|
|
3
3
|
export{INBOUND_KEY,INBOUND_CLASSES,inboundClassOf,deniedClasses,inboundRefusal,setInbound};
|