@sma1lboy/rove 0.9.308-next.458 → 0.9.308-next.459

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.
Files changed (50) hide show
  1. package/dist/cli/{chunk-adfxyz0h.js → chunk-1zen8bjk.js} +1 -1
  2. package/dist/cli/{chunk-1af32mg7.js → chunk-2wssd1sw.js} +1 -1
  3. package/dist/cli/{chunk-4myc34a0.js → chunk-36bsnj0x.js} +1 -1
  4. package/dist/cli/{chunk-r7wcpkc8.js → chunk-3ev72eyq.js} +1 -1
  5. package/dist/cli/{chunk-5g9hbkq5.js → chunk-4q4n8mra.js} +2 -2
  6. package/dist/cli/{chunk-vfzwggkc.js → chunk-5ah6mx39.js} +1 -1
  7. package/dist/cli/{chunk-a1jdqcqq.js → chunk-5hke7red.js} +1 -1
  8. package/dist/cli/{chunk-qk7te5tx.js → chunk-5phb439h.js} +1 -1
  9. package/dist/cli/{chunk-daepgv4q.js → chunk-61y9f33z.js} +1 -1
  10. package/dist/cli/{chunk-5r8v89qz.js → chunk-7c3a3qf3.js} +1 -1
  11. package/dist/cli/{chunk-pg1g9sq7.js → chunk-89yh9q4e.js} +4 -4
  12. package/dist/cli/{chunk-1w7f9mbx.js → chunk-8kp2bc1e.js} +1 -1
  13. package/dist/cli/{chunk-tv3yyrm1.js → chunk-8pfyg0h1.js} +1 -1
  14. package/dist/cli/{chunk-81axh7y2.js → chunk-9bqptsce.js} +1 -1
  15. package/dist/cli/{chunk-wjx8kehz.js → chunk-9py9q0rg.js} +1 -1
  16. package/dist/cli/{chunk-zq7gk3te.js → chunk-ag99nbps.js} +2 -2
  17. package/dist/cli/{chunk-fqyja8kw.js → chunk-cjyxcmcq.js} +1 -1
  18. package/dist/cli/{chunk-nmgvpvm0.js → chunk-ck90wxfe.js} +1 -1
  19. package/dist/cli/{chunk-kxfxn5ys.js → chunk-djqps5wy.js} +1 -1
  20. package/dist/cli/{chunk-srgdpqtc.js → chunk-djzaesm7.js} +2 -2
  21. package/dist/cli/{chunk-dqatj3x0.js → chunk-dndvx3va.js} +1 -1
  22. package/dist/cli/{chunk-k77jjpfs.js → chunk-ejgg8apw.js} +1 -1
  23. package/dist/cli/{chunk-6s6cz4vf.js → chunk-gayywacb.js} +1 -1
  24. package/dist/cli/{chunk-hk3tds7a.js → chunk-h443vrza.js} +1 -1
  25. package/dist/cli/{chunk-7zksk1t6.js → chunk-h91hjcvv.js} +1 -1
  26. package/dist/cli/{chunk-rh6kjc4w.js → chunk-kt6wbfwe.js} +1 -1
  27. package/dist/cli/{chunk-3jpt7be5.js → chunk-m4peq9ma.js} +1 -1
  28. package/dist/cli/{chunk-8g1dkra6.js → chunk-mzfzxmak.js} +1 -1
  29. package/dist/cli/{chunk-djkqvbxx.js → chunk-pbxj6mqv.js} +1 -1
  30. package/dist/cli/{chunk-tj77gkzk.js → chunk-psnh7v8y.js} +1 -1
  31. package/dist/cli/{chunk-51zva1y3.js → chunk-q7yffb4v.js} +1 -1
  32. package/dist/cli/{chunk-26yve83p.js → chunk-qh8aa5z5.js} +1 -1
  33. package/dist/cli/{chunk-qad5kas1.js → chunk-qkzy0vqf.js} +1 -1
  34. package/dist/cli/{chunk-dc0sectg.js → chunk-qwp8wbff.js} +1 -1
  35. package/dist/cli/{chunk-4e5k5sek.js → chunk-r108k31w.js} +1 -1
  36. package/dist/cli/{chunk-88hjwpzw.js → chunk-r240bf0g.js} +1 -1
  37. package/dist/cli/{chunk-zvcfhx1n.js → chunk-rdqab8k3.js} +1 -1
  38. package/dist/cli/{chunk-4zae7xn6.js → chunk-s3fnh2ke.js} +1 -1
  39. package/dist/cli/{chunk-r1zh9snn.js → chunk-sg1kqr92.js} +1 -1
  40. package/dist/cli/{chunk-wadea4v3.js → chunk-sxbdca35.js} +1 -1
  41. package/dist/cli/{chunk-5t4dggxf.js → chunk-tezrgk1z.js} +1 -1
  42. package/dist/cli/{chunk-p3tkczs9.js → chunk-vkagzyfb.js} +1 -1
  43. package/dist/cli/{chunk-0rffqvag.js → chunk-vrjv9c79.js} +2 -2
  44. package/dist/cli/{chunk-0kkee6sj.js → chunk-vt1pej2x.js} +1 -1
  45. package/dist/cli/{chunk-g3h0m06y.js → chunk-w2cycap3.js} +1 -1
  46. package/dist/cli/{chunk-b523a35f.js → chunk-z3m0wzws.js} +1 -1
  47. package/dist/cli/{chunk-a4kqnhy9.js → chunk-zv8acfk4.js} +1 -1
  48. package/dist/cli/index.js +2 -2
  49. package/dist/cli/rove.js +1 -1
  50. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-kxfxn5ys.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-0kkee6sj.js";import{ensurePluginEnginesLoaded}from"./chunk-ty0ptx0v.js";import{openDaemonSession}from"./chunk-j2k6f128.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-1tdca3cn.js";import{ApiError,requireVerbInstalled,verbInstalled}from"./chunk-jz1kj4sf.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{errorMessage}from"./chunk-9gctbddn.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
2
+ import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-djqps5wy.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-vt1pej2x.js";import{ensurePluginEnginesLoaded}from"./chunk-ty0ptx0v.js";import{openDaemonSession}from"./chunk-j2k6f128.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-1tdca3cn.js";import{ApiError,requireVerbInstalled,verbInstalled}from"./chunk-jz1kj4sf.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{errorMessage}from"./chunk-9gctbddn.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
3
3
  `)}function emit(value,pretty){let warning=takeIdentityWarning(),payload=warning&&value&&typeof value==="object"&&!Array.isArray(value)?{...value,identityWarning:warning}:value;writeJson(envelopeMode?successEnvelope(payload):payload,pretty)}function fail(message,code,exitCode=1,data){let error=errorBody(new ApiError(message,code,data));if(envelopeMode)writeJson({apiVersion:ROVE_API_VERSION,ok:!1,error},!1);else writeJson({error},!1,process.stderr);process.exit(exitCode)}var USAGE_ERROR_CODES=new Set(["BAD_VERB","UNKNOWN_VERB","BAD_FLAG","MISSING_FLAG","MISSING_VERB","BAD_DAEMON","UNKNOWN_MACHINE"]);async function invokeVerb(verbName,argv,deps){return runVerb(verbName,{argv},deps)}async function runApiSubcommand(argv){let[verbName,...withMachine]=argv,{machine,rest}=takeMachineFlag(withMachine);if(envelopeMode=argvHasFlag(rest,"--envelope"),!verbName||verbName==="--help"||verbName==="-h"||verbName==="help"){if(!verbName)fail(apiUsage(),"MISSING_VERB",2);process.stdout.write(`${apiUsage()}
4
4
  `);return}ensurePluginEnginesLoaded();let verb=findVerb(verbName);if(!verb){let err=unknownVerbError(verbName);fail(`${err.message}
5
5
  ${apiUsage()}`,err.code,2,err.data)}let parsed;try{parsed=parseFlags(rest,booleanFlagsOf(verb),repeatableFlagsOf(verb))}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(parsed.help){if(!verbInstalled(verb))try{requireVerbInstalled(verb)}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data)}process.stdout.write(`${verbHelp(verb)}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{writeOutdatedCache}from"./chunk-498t9sjd.js";import{PluginCliError,installPlugin}from"./chunk-tv3yyrm1.js";import{loadPluginRegistry,removePluginEntry,savePluginRegistry}from"./chunk-psxhek7n.js";import"./chunk-81axh7y2.js";import{pluginCheckoutDir,pluginConfigDir,pluginDataDir,pluginStateDir}from"./chunk-ws2q07kb.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import"./chunk-yt15y085.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{execFileSync}from"child_process";import{existsSync,mkdirSync,readdirSync,renameSync}from"fs";import{join}from"path";function gitOut(args,cwd){try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function checkEntry(entry){let repoSpec=entry.source.spec.split("/").slice(0,2).join("/"),localSha=gitOut(["rev-parse","HEAD"],pluginCheckoutDir(entry.id)),remote=gitOut(["ls-remote",`https://github.com/${repoSpec}.git`,"HEAD"]),remoteSha=remote?remote.split(/\s+/)[0]??null:null;return{id:entry.id,spec:entry.source.spec,version:entry.version,localSha,remoteSha,behind:Boolean(localSha&&remoteSha&&localSha!==remoteSha)}}function listOutdated(){let rows=loadPluginRegistry().plugins.filter((p)=>p.source.kind==="github").map(checkEntry);return writeOutdatedCache(rows.filter((r)=>r.behind).map((r)=>r.id)),rows}function printOutdated(){let rows=listOutdated();if(rows.length===0){console.log("no GitHub-installed plugins.");return}for(let r of rows){let status=r.behind?"update available":r.remoteSha===null?"remote unreachable":r.localSha===null?"local sha unreadable":"up to date";console.log(`${r.id} v${r.version} ${status}`)}}function migrateRenamedPlugin(oldId,newId){for(let dirOf of[pluginConfigDir,pluginStateDir]){let from=dirOf(oldId),to=dirOf(newId);if(!existsSync(from))continue;mkdirSync(to,{recursive:!0});for(let entry of readdirSync(from)){if(existsSync(join(to,entry)))continue;renameSync(join(from,entry),join(to,entry))}}savePluginRegistry(removePluginEntry(loadPluginRegistry(),oldId)),console.log(`renamed ${oldId} \u2192 ${newId}: settings and state carried over, old entry unregistered`),console.log(` leftover checkout (safe to remove): ${pluginDataDir(oldId)}`)}async function updatePlugins(ids,opts){let rows=listOutdated(),targets;if(opts.all){if(targets=rows.filter((r)=>r.behind),targets.length===0){console.log("all plugins up to date.");return}}else{if(ids.length===0)throw new PluginCliError("update takes plugin ids or --all");targets=ids.map((id)=>{let row=rows.find((r)=>r.id===id);if(!row)throw new PluginCliError(`\`${id}\` is not a GitHub-installed plugin; see \`${ROVE_PRODUCT_NAME} plugin list\``);return row})}for(let target of targets){if(!target.behind&&!ids.includes(target.id))continue;console.log(`updating ${target.id} (${target.spec})\u2026`);let installedId=await installPlugin(target.spec,{yes:opts.yes});if(installedId!==target.id)migrateRenamedPlugin(target.id,installedId)}listOutdated()}export{updatePlugins,printOutdated};
2
+ import{writeOutdatedCache}from"./chunk-498t9sjd.js";import{PluginCliError,installPlugin}from"./chunk-8pfyg0h1.js";import{loadPluginRegistry,removePluginEntry,savePluginRegistry}from"./chunk-psxhek7n.js";import"./chunk-9bqptsce.js";import{pluginCheckoutDir,pluginConfigDir,pluginDataDir,pluginStateDir}from"./chunk-ws2q07kb.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import"./chunk-yt15y085.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{execFileSync}from"child_process";import{existsSync,mkdirSync,readdirSync,renameSync}from"fs";import{join}from"path";function gitOut(args,cwd){try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function checkEntry(entry){let repoSpec=entry.source.spec.split("/").slice(0,2).join("/"),localSha=gitOut(["rev-parse","HEAD"],pluginCheckoutDir(entry.id)),remote=gitOut(["ls-remote",`https://github.com/${repoSpec}.git`,"HEAD"]),remoteSha=remote?remote.split(/\s+/)[0]??null:null;return{id:entry.id,spec:entry.source.spec,version:entry.version,localSha,remoteSha,behind:Boolean(localSha&&remoteSha&&localSha!==remoteSha)}}function listOutdated(){let rows=loadPluginRegistry().plugins.filter((p)=>p.source.kind==="github").map(checkEntry);return writeOutdatedCache(rows.filter((r)=>r.behind).map((r)=>r.id)),rows}function printOutdated(){let rows=listOutdated();if(rows.length===0){console.log("no GitHub-installed plugins.");return}for(let r of rows){let status=r.behind?"update available":r.remoteSha===null?"remote unreachable":r.localSha===null?"local sha unreadable":"up to date";console.log(`${r.id} v${r.version} ${status}`)}}function migrateRenamedPlugin(oldId,newId){for(let dirOf of[pluginConfigDir,pluginStateDir]){let from=dirOf(oldId),to=dirOf(newId);if(!existsSync(from))continue;mkdirSync(to,{recursive:!0});for(let entry of readdirSync(from)){if(existsSync(join(to,entry)))continue;renameSync(join(from,entry),join(to,entry))}}savePluginRegistry(removePluginEntry(loadPluginRegistry(),oldId)),console.log(`renamed ${oldId} \u2192 ${newId}: settings and state carried over, old entry unregistered`),console.log(` leftover checkout (safe to remove): ${pluginDataDir(oldId)}`)}async function updatePlugins(ids,opts){let rows=listOutdated(),targets;if(opts.all){if(targets=rows.filter((r)=>r.behind),targets.length===0){console.log("all plugins up to date.");return}}else{if(ids.length===0)throw new PluginCliError("update takes plugin ids or --all");targets=ids.map((id)=>{let row=rows.find((r)=>r.id===id);if(!row)throw new PluginCliError(`\`${id}\` is not a GitHub-installed plugin; see \`${ROVE_PRODUCT_NAME} plugin list\``);return row})}for(let target of targets){if(!target.behind&&!ids.includes(target.id))continue;console.log(`updating ${target.id} (${target.spec})\u2026`);let installedId=await installPlugin(target.spec,{yes:opts.yes});if(installedId!==target.id)migrateRenamedPlugin(target.id,installedId)}listOutdated()}export{updatePlugins,printOutdated};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{upgradeMachine}from"./chunk-5t4dggxf.js";import"./chunk-qk7te5tx.js";import"./chunk-a6s52zm5.js";import"./chunk-81axh7y2.js";import"./chunk-y1xnjx8x.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-xasg8z9e.js";import"./chunk-7kysxgbq.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{upgradeMachine};
2
+ import{upgradeMachine}from"./chunk-tezrgk1z.js";import"./chunk-5phb439h.js";import"./chunk-a6s52zm5.js";import"./chunk-9bqptsce.js";import"./chunk-y1xnjx8x.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-xasg8z9e.js";import"./chunk-7kysxgbq.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{upgradeMachine};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RemoteOrchestrator}from"./chunk-qad5kas1.js";import{startTunnel}from"./chunk-ejs6dnxf.js";import{discoverMachine,learnedFrom}from"./chunk-a6s52zm5.js";import{dedupeMachines,duplicateAliasOf,listMachines,readMachines,setMachineIdentity,updateMachine}from"./chunk-37g0yabr.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{logClient,logClientError}from"./chunk-y8hjgmn0.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}:{}}}}
2
+ import{RemoteOrchestrator}from"./chunk-qkzy0vqf.js";import{startTunnel}from"./chunk-ejs6dnxf.js";import{discoverMachine,learnedFrom}from"./chunk-a6s52zm5.js";import{dedupeMachines,duplicateAliasOf,listMachines,readMachines,setMachineIdentity,updateMachine}from"./chunk-37g0yabr.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{logClient,logClientError}from"./chunk-y8hjgmn0.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,6 +1,6 @@
1
1
  // @bun
2
- import{failureHint}from"./chunk-h0s8vdyf.js";import{PluginCliError,installPlugin,linkPlugin}from"./chunk-tv3yyrm1.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{buildPaneArgv}from"./chunk-38hnq4aq.js";import{buildPluginEnv}from"./chunk-d1vv8xk6.js";import{currentPluginPlatform,loadPluginRegistry,qualifiedActionId,readPluginManifest,removePluginEntry,savePluginRegistry,supportsPlatform}from"./chunk-psxhek7n.js";import"./chunk-81axh7y2.js";import{SUBCOMMAND_VERBS}from"./chunk-ypvnrqg4.js";import{BUILTIN_MODS,installedBuiltinMods,isBuiltinModId,setBuiltinModInstalled}from"./chunk-v8nbqjwc.js";import{pluginCheckoutDir,pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import{flagValue}from"./chunk-zsfyj36g.js";import{errorMessage}from"./chunk-9gctbddn.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-yt15y085.js";import{defaultDaemonSocketPath}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{readFileSync,rmSync}from"fs";function builtinModRows(homeDir){let installed=new Set(installedBuiltinMods(homeDir));return BUILTIN_MODS.map((mod)=>`${mod.id} first-party ${installed.has(mod.id)?"installed":"not installed"} (${mod.description})`)}function setBuiltinMod(id,install,homeDir){let was=installedBuiltinMods(homeDir).includes(id);if(setBuiltinModInstalled(id,install,homeDir),install)return was?`${id} is already installed`:`installed ${id}`;return was?`uninstalled ${id} (its data stays on disk; reinstall picks it up)`:`${id} is not installed`}var CLI_NAME=ROVE_PRODUCT_NAME;function printUsage(out){out.write([`usage: ${CLI_NAME} plugin <command>`,""," install <owner/repo[/subdir]> [--yes] [--ref <rev>] clone from GitHub, preview, build, register"," install kanban | issues install a first-party mod (uninstall keeps its data)"," link <dir> register a local plugin directory (dev)"," list first-party mods, installed + linked plugins"," search [query] browse the marketplace (GitHub topic rove-plugin)"," outdated check GitHub-installed plugins against upstream"," update <id\u2026> | --all [--yes] reinstall stale plugins from GitHub"," enable <id> | disable <id> toggle a plugin without unregistering it"," unlink <id> unregister a linked plugin (files untouched)"," uninstall <id-or-spec> unregister + remove the managed checkout"," config-dir <id> print the plugin's config directory"," log <id> [-n <count>] tail the plugin's command-run log"," action list [--plugin <id>] declared actions"," action invoke <plugin-id.action-id> run an action now"," pane open <plugin-id.pane-id> [--task <task-id>] open a plugin pane as a terminal tab (JSON:"," clients \u2014 0 = no attached UI performed the split)","","Marketplace: https://github.com/topics/rove-plugin",""].join(`
2
+ import{failureHint}from"./chunk-h0s8vdyf.js";import{PluginCliError,installPlugin,linkPlugin}from"./chunk-8pfyg0h1.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{buildPaneArgv}from"./chunk-38hnq4aq.js";import{buildPluginEnv}from"./chunk-d1vv8xk6.js";import{currentPluginPlatform,loadPluginRegistry,qualifiedActionId,readPluginManifest,removePluginEntry,savePluginRegistry,supportsPlatform}from"./chunk-psxhek7n.js";import"./chunk-9bqptsce.js";import{SUBCOMMAND_VERBS}from"./chunk-ypvnrqg4.js";import{BUILTIN_MODS,installedBuiltinMods,isBuiltinModId,setBuiltinModInstalled}from"./chunk-v8nbqjwc.js";import{pluginCheckoutDir,pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import{flagValue}from"./chunk-zsfyj36g.js";import{errorMessage}from"./chunk-9gctbddn.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-yt15y085.js";import{defaultDaemonSocketPath}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{readFileSync,rmSync}from"fs";function builtinModRows(homeDir){let installed=new Set(installedBuiltinMods(homeDir));return BUILTIN_MODS.map((mod)=>`${mod.id} first-party ${installed.has(mod.id)?"installed":"not installed"} (${mod.description})`)}function setBuiltinMod(id,install,homeDir){let was=installedBuiltinMods(homeDir).includes(id);if(setBuiltinModInstalled(id,install,homeDir),install)return was?`${id} is already installed`:`installed ${id}`;return was?`uninstalled ${id} (its data stays on disk; reinstall picks it up)`:`${id} is not installed`}var CLI_NAME=ROVE_PRODUCT_NAME;function printUsage(out){out.write([`usage: ${CLI_NAME} plugin <command>`,""," install <owner/repo[/subdir]> [--yes] [--ref <rev>] clone from GitHub, preview, build, register"," install kanban | issues install a first-party mod (uninstall keeps its data)"," link <dir> register a local plugin directory (dev)"," list first-party mods, installed + linked plugins"," search [query] browse the marketplace (GitHub topic rove-plugin)"," outdated check GitHub-installed plugins against upstream"," update <id\u2026> | --all [--yes] reinstall stale plugins from GitHub"," enable <id> | disable <id> toggle a plugin without unregistering it"," unlink <id> unregister a linked plugin (files untouched)"," uninstall <id-or-spec> unregister + remove the managed checkout"," config-dir <id> print the plugin's config directory"," log <id> [-n <count>] tail the plugin's command-run log"," action list [--plugin <id>] declared actions"," action invoke <plugin-id.action-id> run an action now"," pane open <plugin-id.pane-id> [--task <task-id>] open a plugin pane as a terminal tab (JSON:"," clients \u2014 0 = no attached UI performed the split)","","Marketplace: https://github.com/topics/rove-plugin",""].join(`
3
3
  `))}function loadAll(){return loadPluginRegistry().plugins.map((entry)=>{try{return{entry,manifest:readPluginManifest(entry.root).manifest}}catch{return{entry,manifest:void 0}}})}function requireEntry(id){let entry=loadPluginRegistry().plugins.find((p)=>p.id===id);if(!entry)throw new PluginCliError(`no plugin registered as \`${id}\`; see \`${CLI_NAME} plugin list\``);return entry}function listPlugins(){for(let row of builtinModRows())console.log(row);let all=loadAll();if(all.length===0){console.log(`no other plugins installed. Try: ${CLI_NAME} plugin install <owner/repo> \u2014 browse the \`rove-plugin\` GitHub topic.`);return}for(let{entry,manifest}of all){let state=entry.enabled?"enabled":"disabled",kind=entry.source.kind==="link"?`linked ${entry.root}`:entry.source.spec,broken=manifest?"":" [manifest unreadable]";console.log(`${entry.id} v${entry.version} ${state} (${kind})${broken}`)}}function setEnabled(id,enabled){let entry=requireEntry(id),registry=loadPluginRegistry();savePluginRegistry({plugins:registry.plugins.map((p)=>p.id===id?{...entry,enabled}:p)}),console.log(`${enabled?"enabled":"disabled"} ${id}`)}function unlink(id){let entry=requireEntry(id);if(entry.source.kind!=="link")throw new PluginCliError(`\`${id}\` is a GitHub install; use uninstall`);savePluginRegistry(removePluginEntry(loadPluginRegistry(),id)),console.log(`unlinked ${id} (files untouched at ${entry.root})`)}function uninstall(idOrSpec){let registry=loadPluginRegistry(),entry=registry.plugins.find((p)=>p.id===idOrSpec||p.source.kind==="github"&&p.source.spec===idOrSpec);if(!entry)throw new PluginCliError(`no plugin registered as \`${idOrSpec}\``);if(entry.source.kind==="link")throw new PluginCliError(`\`${entry.id}\` is linked; use unlink`);savePluginRegistry(removePluginEntry(registry,entry.id)),rmSync(pluginCheckoutDir(entry.id),{recursive:!0,force:!0}),console.log(`uninstalled ${entry.id} (config/state kept under ~/.rove/plugins/${entry.id}/)`)}function listActions(pluginFilter){for(let{entry,manifest}of loadAll()){if(!manifest||pluginFilter&&entry.id!==pluginFilter)continue;for(let action of manifest.actions)console.log(`${qualifiedActionId(entry.id,action.id)} ${action.title}`)}}function findByLongestPluginPrefix(qualified,options,findItem){for(let{entry,manifest}of loadAll().filter(({entry:entry2,manifest:manifest2})=>Boolean(manifest2&&(!options.enabledOnly||entry2.enabled)&&qualified.startsWith(`${entry2.id}.`))).sort((a,b)=>b.entry.id.length-a.entry.id.length)){let item=findItem(manifest,qualified.slice(entry.id.length+1));if(item!==void 0)return{entry,manifest,item}}return}function assertPlatformSupported(label,item,manifest){if(supportsPlatform(item,manifest,currentPluginPlatform()))return;let declared=(item.platforms??manifest.platforms??[]).join(", ");throw new PluginCliError(`\`${label}\` is not supported on this platform (declares ${declared})`)}function invokeAction(qualified,extraArgs){let hit=findByLongestPluginPrefix(qualified,{enabledOnly:!0},(manifest,actionId)=>manifest.actions.find((a)=>a.id===actionId));if(!hit)throw new PluginCliError(`no action \`${qualified}\`; see \`${CLI_NAME} plugin action list\``);assertPlatformSupported(qualified,hit.item,hit.manifest);let action=hit.item,[cmd,...args]=[...action.command,...extraArgs],res=spawnSync(cmd,args,{cwd:hit.entry.root,stdio:"inherit",env:buildPluginEnv({socketPath:defaultDaemonSocketPath(),binPath:resolvePluginBinPath(),pluginId:hit.entry.id,pluginRoot:hit.entry.root,extra:{ROVE_PLUGIN_ACTION_ID:action.id,ROVE_PLUGIN_INVOKE_CWD:process.cwd()}})});process.exit(res.status??1)}function resolvePaneQualified(qualified){let hit=findByLongestPluginPrefix(qualified,{enabledOnly:!1},(manifest,entrypoint)=>manifest.panes.find((p)=>p.id===entrypoint));if(!hit)throw new PluginCliError(`no pane \`${qualified}\`; see \`${CLI_NAME} plugin list\``);return{pluginId:hit.entry.id,entrypoint:hit.item.id}}async function openPane(pluginId,entrypoint,taskFlag){let loaded=loadAll().find(({entry})=>entry.id===pluginId);if(!loaded?.manifest)throw new PluginCliError(`no plugin \`${pluginId}\` (or its manifest is unreadable)`);if(!loaded.entry.enabled)throw new PluginCliError(`\`${pluginId}\` is disabled`);let pane=loaded.manifest.panes.find((p)=>p.id===entrypoint);if(!pane)throw new PluginCliError(`no pane \`${entrypoint}\` in \`${pluginId}\`; declare it under [[panes]]`);assertPlatformSupported(`${pluginId}.${pane.id}`,pane,loaded.manifest);let{openDaemonSession,resolveActiveTaskId}=await import("./chunk-2cf5enj3.js"),session=await openDaemonSession({mode:"start"});try{let taskId=taskFlag??await resolveActiveTaskId(session.client);if(!taskId)throw new PluginCliError("no active task; pass --task <id>");let argv=buildPaneArgv(loaded.entry.id,loaded.entry.root,pane,{socketPath:defaultDaemonSocketPath(),binPath:resolvePluginBinPath(),taskId}),reply=await session.client.request("tab.open",{taskId,argv,title:pane.title,placement:pane.placement});console.log(JSON.stringify({...reply,ok:!0,pane:`${pluginId}.${pane.id}`,taskId,title:pane.title}))}finally{session.close()}}function tailLog(id,count){requireEntry(id);let text;try{text=readFileSync(pluginLogPath(id),"utf8")}catch{console.log("(no runs logged yet)");return}let lines=text.trimEnd().split(`
4
- `);for(let line of lines.slice(-count))console.log(line)}async function runPluginSubcommand(rest){let[command,...args]=rest;if(command!==void 0&&!SUBCOMMAND_VERBS.plugin.includes(command)){let isHelp=command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}try{switch(command){case"install":{let spec=args.find((a)=>!a.startsWith("-"));if(!spec)throw new PluginCliError("install needs <owner/repo[/subdir]>");if(isBuiltinModId(spec)){console.log(setBuiltinMod(spec,!0));return}await installPlugin(spec,{yes:args.includes("--yes"),ref:flagValue(args,"--ref")});return}case"link":{if(!args[0])throw new PluginCliError("link needs a directory");linkPlugin(args[0]);return}case"list":listPlugins();return;case"search":{let{searchMarketplace}=await import("./chunk-094cgrcc.js");await searchMarketplace(args.find((a)=>!a.startsWith("-")));return}case"outdated":{let{printOutdated}=await import("./chunk-1af32mg7.js");printOutdated();return}case"update":{let{updatePlugins}=await import("./chunk-1af32mg7.js");await updatePlugins(args.filter((a)=>!a.startsWith("-")),{all:args.includes("--all"),yes:args.includes("--yes")});return}case"enable":case"disable":{if(!args[0])throw new PluginCliError(`${command} needs a plugin id`);if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],command==="enable"));else setEnabled(args[0],command==="enable");return}case"unlink":{if(!args[0])throw new PluginCliError("unlink needs a plugin id");unlink(args[0]);return}case"uninstall":{if(!args[0])throw new PluginCliError("uninstall needs a plugin id or owner/repo spec");if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],!1));else uninstall(args[0]);return}case"config-dir":{if(!args[0])throw new PluginCliError("config-dir needs a plugin id");requireEntry(args[0]),console.log(pluginConfigDir(args[0]));return}case"log":{if(!args[0])throw new PluginCliError("log needs a plugin id");tailLog(args[0],Number.parseInt(flagValue(args,"-n")??"20",10)||20);return}case"pane":{let[sub,...paneArgs]=args;if(sub==="open"){let positional=paneArgs.find((a)=>!a.startsWith("-")&&a!==flagValue(paneArgs,"--task")),pluginId=flagValue(paneArgs,"--plugin"),entrypoint=flagValue(paneArgs,"--entrypoint");if(!pluginId||!entrypoint){if(!positional)throw new PluginCliError("pane open needs <plugin-id.pane-id> (or --plugin <id> --entrypoint <pane-id>) [--task <task-id>]");({pluginId,entrypoint}=resolvePaneQualified(positional))}await openPane(pluginId,entrypoint,flagValue(paneArgs,"--task"));return}printUsage(process.stderr),process.exit(2);return}case"action":{let[sub,...actionArgs]=args;if(sub==="list"){listActions(flagValue(actionArgs,"--plugin"));return}if(sub==="invoke"){if(!actionArgs[0])throw new PluginCliError("action invoke needs <plugin-id.action-id>");invokeAction(actionArgs[0],actionArgs.slice(1));return}printUsage(process.stderr),process.exit(2);return}default:{let isHelp=command===void 0||command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}}}catch(err){if(err instanceof PluginCliError)console.error(`${CLI_NAME} plugin: ${err.message}
4
+ `);for(let line of lines.slice(-count))console.log(line)}async function runPluginSubcommand(rest){let[command,...args]=rest;if(command!==void 0&&!SUBCOMMAND_VERBS.plugin.includes(command)){let isHelp=command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}try{switch(command){case"install":{let spec=args.find((a)=>!a.startsWith("-"));if(!spec)throw new PluginCliError("install needs <owner/repo[/subdir]>");if(isBuiltinModId(spec)){console.log(setBuiltinMod(spec,!0));return}await installPlugin(spec,{yes:args.includes("--yes"),ref:flagValue(args,"--ref")});return}case"link":{if(!args[0])throw new PluginCliError("link needs a directory");linkPlugin(args[0]);return}case"list":listPlugins();return;case"search":{let{searchMarketplace}=await import("./chunk-094cgrcc.js");await searchMarketplace(args.find((a)=>!a.startsWith("-")));return}case"outdated":{let{printOutdated}=await import("./chunk-2wssd1sw.js");printOutdated();return}case"update":{let{updatePlugins}=await import("./chunk-2wssd1sw.js");await updatePlugins(args.filter((a)=>!a.startsWith("-")),{all:args.includes("--all"),yes:args.includes("--yes")});return}case"enable":case"disable":{if(!args[0])throw new PluginCliError(`${command} needs a plugin id`);if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],command==="enable"));else setEnabled(args[0],command==="enable");return}case"unlink":{if(!args[0])throw new PluginCliError("unlink needs a plugin id");unlink(args[0]);return}case"uninstall":{if(!args[0])throw new PluginCliError("uninstall needs a plugin id or owner/repo spec");if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],!1));else uninstall(args[0]);return}case"config-dir":{if(!args[0])throw new PluginCliError("config-dir needs a plugin id");requireEntry(args[0]),console.log(pluginConfigDir(args[0]));return}case"log":{if(!args[0])throw new PluginCliError("log needs a plugin id");tailLog(args[0],Number.parseInt(flagValue(args,"-n")??"20",10)||20);return}case"pane":{let[sub,...paneArgs]=args;if(sub==="open"){let positional=paneArgs.find((a)=>!a.startsWith("-")&&a!==flagValue(paneArgs,"--task")),pluginId=flagValue(paneArgs,"--plugin"),entrypoint=flagValue(paneArgs,"--entrypoint");if(!pluginId||!entrypoint){if(!positional)throw new PluginCliError("pane open needs <plugin-id.pane-id> (or --plugin <id> --entrypoint <pane-id>) [--task <task-id>]");({pluginId,entrypoint}=resolvePaneQualified(positional))}await openPane(pluginId,entrypoint,flagValue(paneArgs,"--task"));return}printUsage(process.stderr),process.exit(2);return}case"action":{let[sub,...actionArgs]=args;if(sub==="list"){listActions(flagValue(actionArgs,"--plugin"));return}if(sub==="invoke"){if(!actionArgs[0])throw new PluginCliError("action invoke needs <plugin-id.action-id>");invokeAction(actionArgs[0],actionArgs.slice(1));return}printUsage(process.stderr),process.exit(2);return}default:{let isHelp=command===void 0||command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}}}catch(err){if(err instanceof PluginCliError)console.error(`${CLI_NAME} plugin: ${err.message}
5
5
  Run ${CLI_NAME} plugin --help for usage.`),process.exit(1);console.error(`${CLI_NAME} plugin: ${errorMessage(err)}
6
6
  ${failureHint(err,CLI_NAME)}`),process.exit(1)}}export{runPluginSubcommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{CURRENT_VERSION}from"./chunk-81axh7y2.js";import{ensureMcpForwards,isRemoteWorkspace,machineMcp,readRemoteWorkspace,rxPath}from"./chunk-78rtznxy.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{flagValue}from"./chunk-zsfyj36g.js";import"./chunk-xasg8z9e.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir));else if(args[0]==="mcp-hook"){let ws=readRemoteWorkspace(dir);if(ws)ensureMcpForwards(ws.machine,machineMcp(ws.machine))}}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}var ROVE_COMMAND=/^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*\/)?rove(?:\s|$)/;function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command)||ROVE_COMMAND.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
2
+ import{CURRENT_VERSION}from"./chunk-9bqptsce.js";import{ensureMcpForwards,isRemoteWorkspace,machineMcp,readRemoteWorkspace,rxPath}from"./chunk-78rtznxy.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{flagValue}from"./chunk-zsfyj36g.js";import"./chunk-xasg8z9e.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir));else if(args[0]==="mcp-hook"){let ws=readRemoteWorkspace(dir);if(ws)ensureMcpForwards(ws.machine,machineMcp(ws.machine))}}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}var ROVE_COMMAND=/^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*\/)?rove(?:\s|$)/;function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command)||ROVE_COMMAND.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
3
3
  `);if(lines.length<=count+1)return text;return`${lines.slice(0,count).join(`
4
4
  `)}
5
5
  [cut at line ${from+count-1}; pass offset to read on]`}if(name==="write"){if(typeof a.content!=="string")throw Error("content is required");return write(a.content),`wrote ${path}`}if(name==="edit"){let{old_string:from,new_string:to}=a;if(typeof from!=="string"||typeof to!=="string"||!from)throw Error("old_string and new_string are required");let text=must(run(`cat -- ${file}`)),hits=text.split(from).length-1;if(hits===0)throw Error(`old_string not found in ${path}`);if(hits>1&&a.replace_all!==!0)throw Error(`old_string occurs ${hits} times in ${path}; add context to make it unique, or pass replace_all`);return write(text.split(from).join(to)),`edited ${path} (${hits} replacement${hits===1?"":"s"})`}throw Error(`unknown tool: ${name}`)}function mcpReply(run,msg){if(msg.id===void 0||!msg.method)return null;let result=(value)=>({jsonrpc:"2.0",id:msg.id,result:value});if(msg.method==="initialize")return result({protocolVersion:typeof msg.params?.protocolVersion==="string"?msg.params.protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rove-workspace",version:CURRENT_VERSION}});if(msg.method==="ping")return result({});if(msg.method==="tools/list")return result({tools:TOOLS});if(msg.method==="tools/call"){let args=msg.params?.arguments??{};try{let text=callWorkspaceTool(run,String(msg.params?.name??""),args);return result({content:[{type:"text",text}]})}catch(err){return result({content:[{type:"text",text:err instanceof Error?err.message:String(err)}],isError:!0})}}return{jsonrpc:"2.0",id:msg.id,error:{code:-32601,message:`method not found: ${msg.method}`}}}async function serveMcp(rx){let run=runThrough(rx);for await(let line of createInterface({input:process.stdin})){if(!line.trim())continue;let msg;try{msg=JSON.parse(line)}catch{continue}let reply=mcpReply(run,msg);if(reply)process.stdout.write(`${JSON.stringify(reply)}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{MachineHub}from"./chunk-r7wcpkc8.js";import"./chunk-qad5kas1.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-5t4dggxf.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-qk7te5tx.js";import{machineDaemonSocket}from"./chunk-1tdca3cn.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-81axh7y2.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-9h7zv8ge.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import{isWindowsMachine}from"./chunk-cw9h73h5.js";import{listMachines}from"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
2
+ import{MachineHub}from"./chunk-3ev72eyq.js";import"./chunk-qkzy0vqf.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-tezrgk1z.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-5phb439h.js";import{machineDaemonSocket}from"./chunk-1tdca3cn.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-9bqptsce.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-9h7zv8ge.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import{isWindowsMachine}from"./chunk-cw9h73h5.js";import{listMachines}from"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RELEASE_CHANNELS,channelOf}from"./chunk-81axh7y2.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
2
+ import{RELEASE_CHANNELS,channelOf}from"./chunk-9bqptsce.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
3
3
  export{UPDATE_CHANNEL_KEY,UPDATE_NOTIFY_KEY,normalizeReleaseChannel,preferredReleaseChannel,updateNotifyEnabled,rememberReleaseChannel,updateDelayHours};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{invokeVerb}from"./chunk-adfxyz0h.js";import"./chunk-kxfxn5ys.js";import{defaultApiRuntime,loadContext}from"./chunk-0kkee6sj.js";import"./chunk-ntmypfsy.js";import"./chunk-ty0ptx0v.js";import"./chunk-38hnq4aq.js";import"./chunk-ajpsnr22.js";import"./chunk-e7wxpvat.js";import"./chunk-j2k6f128.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-72g45nwx.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-hk3tds7a.js";import"./chunk-5t4dggxf.js";import"./chunk-mdx18vtz.js";import"./chunk-qk7te5tx.js";import"./chunk-1tdca3cn.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-qkehg2c1.js";import"./chunk-s5h7ay1w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-81axh7y2.js";import{SUBCOMMAND_VERBS}from"./chunk-ypvnrqg4.js";import"./chunk-4mj47dk3.js";import"./chunk-vjpe5s4v.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-7j4qsbg4.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-9h7zv8ge.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{execFile}from"child_process";var LARK_CLI="lark-cli";function larkCli(args,timeoutMs=30000){return new Promise((resolve)=>{execFile(LARK_CLI,[...args],{timeout:timeoutMs,encoding:"utf8"},(err,stdout,stderr)=>resolve({ok:!err,stdout:stdout??"",stderr:stderr||(err?err.message:"")}))})}function json(stdout){try{let value=JSON.parse(stdout);return value&&typeof value==="object"?value:null}catch{return null}}async function botInfo(){let res=await larkCli(["api","GET","/open-apis/bot/v3/info","--as","bot"]),data=json(res.stdout)?.data??json(res.stdout)?.bot;return typeof data?.open_id==="string"&&data.open_id?{openId:data.open_id,name:typeof data.app_name==="string"?data.app_name:""}:null}async function authStatus(){let raw=json((await larkCli(["auth","status"])).stdout),user=raw?.identities?.user;return{...typeof raw?.appId==="string"&&raw.appId?{appId:raw.appId}:{},...typeof user?.openId==="string"&&user.openId?{userOpenId:user.openId}:{},...typeof user?.userName==="string"?{userName:user.userName}:{}}}async function react(messageId,emoji){return await larkCli(["im","reactions","create","--as","bot","--message-id",messageId,"--data",JSON.stringify({reaction_type:{emoji_type:emoji}})])}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var SEEN_CAP=500,DEFAULT_TONE="\u7B80\u77ED\u76F4\u63A5\uFF0C\u50CF\u540C\u4E8B\u804A\u5929\uFF0C\u7ED3\u8BBA\u5148\u8BF4\uFF0C\u4E0D\u5BA2\u5957",strings=(value)=>Array.isArray(value)?value.filter((v)=>typeof v==="string"):[];function readJson(path){try{let value=JSON.parse(readFileSync(path,"utf8"));return value&&typeof value==="object"?value:null}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
2
+ import{invokeVerb}from"./chunk-1zen8bjk.js";import"./chunk-djqps5wy.js";import{defaultApiRuntime,loadContext}from"./chunk-vt1pej2x.js";import"./chunk-ntmypfsy.js";import"./chunk-ty0ptx0v.js";import"./chunk-38hnq4aq.js";import"./chunk-ajpsnr22.js";import"./chunk-e7wxpvat.js";import"./chunk-j2k6f128.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-72g45nwx.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-h443vrza.js";import"./chunk-tezrgk1z.js";import"./chunk-mdx18vtz.js";import"./chunk-5phb439h.js";import"./chunk-1tdca3cn.js";import"./chunk-y0e28qha.js";import"./chunk-ejs6dnxf.js";import"./chunk-a6s52zm5.js";import"./chunk-qkehg2c1.js";import"./chunk-s5h7ay1w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-9bqptsce.js";import{SUBCOMMAND_VERBS}from"./chunk-ypvnrqg4.js";import"./chunk-4mj47dk3.js";import"./chunk-vjpe5s4v.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-7j4qsbg4.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-9h7zv8ge.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-021xteq8.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-s4dxjqgt.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{execFile}from"child_process";var LARK_CLI="lark-cli";function larkCli(args,timeoutMs=30000){return new Promise((resolve)=>{execFile(LARK_CLI,[...args],{timeout:timeoutMs,encoding:"utf8"},(err,stdout,stderr)=>resolve({ok:!err,stdout:stdout??"",stderr:stderr||(err?err.message:"")}))})}function json(stdout){try{let value=JSON.parse(stdout);return value&&typeof value==="object"?value:null}catch{return null}}async function botInfo(){let res=await larkCli(["api","GET","/open-apis/bot/v3/info","--as","bot"]),data=json(res.stdout)?.data??json(res.stdout)?.bot;return typeof data?.open_id==="string"&&data.open_id?{openId:data.open_id,name:typeof data.app_name==="string"?data.app_name:""}:null}async function authStatus(){let raw=json((await larkCli(["auth","status"])).stdout),user=raw?.identities?.user;return{...typeof raw?.appId==="string"&&raw.appId?{appId:raw.appId}:{},...typeof user?.openId==="string"&&user.openId?{userOpenId:user.openId}:{},...typeof user?.userName==="string"?{userName:user.userName}:{}}}async function react(messageId,emoji){return await larkCli(["im","reactions","create","--as","bot","--message-id",messageId,"--data",JSON.stringify({reaction_type:{emoji_type:emoji}})])}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var SEEN_CAP=500,DEFAULT_TONE="\u7B80\u77ED\u76F4\u63A5\uFF0C\u50CF\u540C\u4E8B\u804A\u5929\uFF0C\u7ED3\u8BBA\u5148\u8BF4\uFF0C\u4E0D\u5BA2\u5957",strings=(value)=>Array.isArray(value)?value.filter((v)=>typeof v==="string"):[];function readJson(path){try{let value=JSON.parse(readFileSync(path,"utf8"));return value&&typeof value==="object"?value:null}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
3
3
  `,{mode:384}),renameSync(tmp,path)}class LarkStore{dir;constructor(homeDir){this.dir=join(resolveDaemonHomeDir(homeDir),ROVE_STATE_DIR_BASENAME,"lark")}get agentDir(){return join(this.dir,"agent")}ensureDir(){mkdirSync(this.dir,{recursive:!0,mode:448})}readConfig(){let raw=readJson(join(this.dir,"config.json"));if(!raw||typeof raw.botOpenId!=="string"||!raw.botOpenId)return null;return{botOpenId:raw.botOpenId,botName:typeof raw.botName==="string"?raw.botName:"",...typeof raw.ownerOpenId==="string"&&raw.ownerOpenId?{ownerOpenId:raw.ownerOpenId}:{},...typeof raw.ownerName==="string"&&raw.ownerName?{ownerName:raw.ownerName}:{},allow:strings(raw.allow),tone:typeof raw.tone==="string"&&raw.tone?raw.tone:DEFAULT_TONE,savedAt:typeof raw.savedAt==="string"?raw.savedAt:""}}writeConfig(config){this.ensureDir(),writeJson(join(this.dir,"config.json"),config)}clearConfig(){let had=this.readConfig()!==null;return rmSync(join(this.dir,"config.json"),{force:!0}),rmSync(join(this.dir,"state.json"),{force:!0}),had}readState(){let raw=readJson(join(this.dir,"state.json")),agent=raw?.agent;return{...typeof agent?.taskId==="string"&&typeof agent.tab==="string"?{agent:{taskId:agent.taskId,tab:agent.tab}}:{},...typeof raw?.tone==="string"?{tone:raw.tone}:{},seen:strings(raw?.seen),pending:strings(raw?.pending)}}writeState(state){this.ensureDir(),writeJson(join(this.dir,"state.json"),{...state,seen:state.seen.slice(-SEEN_CAP)})}}var run=(args)=>spawnSync(LARK_CLI,[...args],{stdio:"inherit"}).status===0;async function connectLark(store,opts){let say=opts.say??(()=>{}),terminal={ok:!1,message:"rove lark connect"};if(spawnSync(LARK_CLI,["--version"],{stdio:"ignore"}).error)return{ok:!1,message:"npm i -g @larksuite/cli && rove lark connect"};if(!(await authStatus()).appId){if(!opts.interactive)return terminal;if(say("No Lark app yet: lark-cli will create one in your browser."),!run(["config","init","--new",...opts.brand?["--brand",opts.brand]:[]]))return{ok:!1,message:"lark-cli config init did not finish"}}let bot=await botInfo();if(!bot)return{ok:!1,message:`${LARK_CLI} api GET /open-apis/bot/v3/info --as bot`};let owner=await authStatus();if(!owner.userOpenId){if(!opts.interactive)return terminal;if(say("Sign in to Lark as yourself, so the bot knows who you are."),!run(["auth","login","--scope","auth:user.id:read"]))return{ok:!1,message:"lark-cli auth login did not finish"};owner=await authStatus()}let previous=store.readConfig(),config={botOpenId:bot.openId,botName:bot.name,...owner.userOpenId?{ownerOpenId:owner.userOpenId}:{},...owner.userName?{ownerName:owner.userName}:{},allow:(previous?.allow??[]).filter((id)=>id!==owner.userOpenId),tone:previous?.tone??DEFAULT_TONE,savedAt:previous?.savedAt||new Date().toISOString()};return store.writeConfig(config),{ok:!0,config}}var CLI_NAME=ROVE_PRODUCT_NAME,LARK_USAGE=[`Usage: ${CLI_NAME} lark <connect|disconnect|status|allow|deny|tone>`,"","Talk to your own Rove agent from Lark (\u98DE\u4E66): DM the bot or @ it in a group. The agent","answers in the thread and starts Rove tasks for real work. The daemon must be running.","Lark is reached through lark-cli (npm i -g @larksuite/cli), which keeps the app's credentials.","","Commands:"," connect [--brand feishu|lark] Set up lark-cli's app if there is none (opens the browser),"," check its bot, and let you (lark-cli's signed-in user) talk to it"," disconnect Stop listening; the agent's project and the lark-cli app stay"," status The bot, allowed senders and tone"," allow <open_id> Let another person talk to the agent (ids: the daemon log's refusals)"," deny <open_id> Revoke a person added with allow",` tone [text] How the agent sounds; no text resets it to "${DEFAULT_TONE}"`,""].join(`
4
4
  `);function fail(message){process.stderr.write(`${CLI_NAME} lark: ${message}
5
5
  `),process.exit(1)}async function connect(store,argv){let at=argv.indexOf("--brand"),brand=at>=0?argv[at+1]:void 0,say=(line)=>process.stdout.write(`${line}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-dh2e2yqb.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-983c1za4.js";import"./chunk-zcqjevxc.js";import"./chunk-a4hsqj1b.js";import"./chunk-xzk96zfj.js";import"./chunk-rmnm3f9n.js";import{skillOverview}from"./chunk-v3mtzde5.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-39rn20pf.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines,withEngineVersions}from"./chunk-ajpsnr22.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-y0e28qha.js";import"./chunk-eaav6ajz.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import{CURRENT_VERSION,package_default}from"./chunk-81axh7y2.js";import{resolveNodeBinary}from"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import{t}from"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import{readableLegacyIndexPath}from"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import{readPidFile}from"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-2z2jwetd.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{preRenameStateDir}from"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
2
+ import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-dh2e2yqb.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-983c1za4.js";import"./chunk-zcqjevxc.js";import"./chunk-a4hsqj1b.js";import"./chunk-xzk96zfj.js";import"./chunk-rmnm3f9n.js";import{skillOverview}from"./chunk-v3mtzde5.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-39rn20pf.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines,withEngineVersions}from"./chunk-ajpsnr22.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-y0e28qha.js";import"./chunk-eaav6ajz.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import{CURRENT_VERSION,package_default}from"./chunk-9bqptsce.js";import{resolveNodeBinary}from"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-1590vtyb.js";import"./chunk-g9ba25q5.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import"./chunk-vqgmdehh.js";import"./chunk-89xeg26e.js";import"./chunk-kgnb7x69.js";import"./chunk-78rtznxy.js";import"./chunk-w7zv47mp.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-62ewk1qg.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-9gctbddn.js";import"./chunk-3pp65k25.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import{t}from"./chunk-n9e31hs7.js";import"./chunk-cmp64q4j.js";import"./chunk-sp6vvssh.js";import"./chunk-sbm7qcw4.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-pgvfx31j.js";import{readableLegacyIndexPath}from"./chunk-cwfs2kae.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import{readPidFile}from"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-2z2jwetd.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{preRenameStateDir}from"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
3
3
  `)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids,deps={}){let runProbe=deps.run??run,readEnviron=deps.readEnviron??((pid)=>readFileSync(`/proc/${pid}/environ`,"utf8")),marked=new Set;if(pids.length===0)return{marked,failed:null};if((deps.platform??process.platform)==="linux"){let refused=null;for(let pid of pids)try{if(readEnviron(pid).split("\x00").includes(PTY_MARKER))marked.add(pid)}catch(err){let code=err.code;if(code!=="ENOENT"&&code!=="ESRCH")refused??=`/proc/${pid}/environ: ${code??"unreadable"}`}return{marked,failed:refused}}let result=await runProbe(["ps","eww","-o","pid=,command=","-p",pids.join(",")]);if(result.code!==0)return{marked,failed:`ps eww exited ${result.code}`};let marker=new RegExp(`(^|\\s)${PTY_MARKER}(\\s|$)`);for(let line of result.stdout.split(`
4
4
  `)){let pid=Number.parseInt(line.trim().split(/\s+/)[0]??"",10);if(Number.isFinite(pid)&&marker.test(line))marked.add(pid)}return{marked,failed:null}}async function ownPgid(runProbe){let result=await runProbe(["ps","-o","pgid=","-p",String(process.pid)]),pgid=Number.parseInt(result.stdout.trim(),10);return Number.isFinite(pgid)?pgid:-1}async function collectOrphans(liveSessionPids,deps={}){let runProbe=deps.run??run;if((deps.platform??process.platform)==="win32")return{orphans:[],error:null};let ps=await runProbe(["ps","-A","-o","pid=,ppid=,pgid=,etime=,rss=,command="]);if(ps.code!==0)return{orphans:[],error:`could not read the process table \u2014 ps exited ${ps.code}`};let rows=parsePsRows(ps.stdout),candidates=orphanCandidates(rows,await ownPgid(runProbe),liveSessionPids),{marked,failed}=await markedPids(candidates.map((row)=>row.pid),deps);if(failed)return{orphans:[],error:`could not read process environments \u2014 ${failed}`};return{orphans:candidates.filter((row)=>marked.has(row.pid)),error:null}}function formatMb(rssKb){return`${(rssKb/1024).toFixed(0)} MB`}function orphanDoctorLines(orphans,error,cliName,killing=!1){if(error)return[`orphans: \u2717 ${error}`];if(orphans.length===0)return["orphans: \u2713 none \u2014 no processes left behind by a dead PTY session"];let totalMb=orphans.reduce((sum,row)=>sum+row.rssKb,0)/1024,lines=[`orphans: \u26A0 ${orphans.length} process(es) outlived the PTY session that spawned them (${totalMb.toFixed(0)} MB RSS)`," each is reparented to init, carries Rove's PTY marker, and its process"," group leader is gone \u2014 no live task owns them"];for(let row of[...orphans].sort((a,b)=>b.rssKb-a.rssKb))lines.push(` pid ${row.pid} (group ${row.pgid}) up ${row.etime}, ${formatMb(row.rssKb)}: ${row.command.slice(0,90)}`);if(!killing)lines.push(` \u2192 \`${cliName} doctor --kill-orphans\` ends those process groups (SIGTERM, then SIGKILL)`," read the list first: something you backgrounded from a Rove terminal and then"," closed the tab on looks exactly like a leak, and doctor cannot tell them apart");return lines}var GROUP_EXIT_GRACE_MS=2000,GROUP_POLL_MS=100;function logOrphanKill(pgid,signal,logPath=defaultDaemonLogPath()){try{appendFileSync(logPath,formatDaemonInfo("doctor-kill-orphans",`${signal} process group ${pgid}`))}catch{}}function groupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(err){return err.code!=="ESRCH"}}async function killOrphanGroups(orphans){let groups=[...new Set(orphans.map((row)=>row.pgid))];for(let pgid of groups)try{process.kill(-pgid,"SIGTERM"),logOrphanKill(pgid,"SIGTERM")}catch{}let deadline=Date.now()+GROUP_EXIT_GRACE_MS,survivors=groups.filter(groupAlive);while(survivors.length>0&&Date.now()<deadline)await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),survivors=survivors.filter(groupAlive);for(let pgid of survivors)try{process.kill(-pgid,"SIGKILL"),logOrphanKill(pgid,"SIGKILL")}catch{}return await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),{groups,survivors:survivors.filter(groupAlive)}}function multiplexerLabel(env){if(env.TMUX)return"tmux";if(env.ZELLIJ)return"zellij";if(env.STY)return"screen";return"no"}function terminalEnvLines(env){let show=(v)=>v&&v.length>0?v:"(unset)",program=env.TERM_PROGRAM?`${env.TERM_PROGRAM}${env.TERM_PROGRAM_VERSION?` v${env.TERM_PROGRAM_VERSION}`:""}`:"(unset)";return[`terminal: TERM=${show(env.TERM)} TERM_PROGRAM=${program} COLORTERM=${show(env.COLORTERM)}`,` running inside a multiplexer: ${multiplexerLabel(env)}`]}function parseKittyProbeReply(data){let kitty=data.match(/\x1b\[\?(\d+)u/);if(kitty?.[1]!==void 0)return{kind:"supported",flags:Number.parseInt(kitty[1],10)};if(/\x1b\[\?[\d;]*c/.test(data))return{kind:"unsupported"};return null}function kittyProbeLine(result){switch(result.kind){case"supported":return` kitty keyboard protocol: \u2713 answered (flags=${result.flags})`;case"unsupported":return[" kitty keyboard protocol: \u2717 not supported \u2014 legacy key path"," (ctrl+h/ctrl+j arrive as C0 backspace/linefeed bytes; the"," split chords ctrl+\\ and ctrl+= cannot be encoded at all)"].join(`
5
5
  `);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}async function probeGit(){try{let proc=Bun.spawn(["git","--version"],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),text=(await new Response(proc.stdout).text()).trim();if(await proc.exited===0&&text)return{line:`git: \u2713 ${text}`,found:!0}}catch{}return{line:"git: \u2717 not found on PATH",found:!1}}function binaryLabel(binary){return binary.found?`\u2713 ${binary.path}`:`\u2717 ${binary.error}`}async function probeEngines(){let statuses=await withEngineVersions(await detectEngineStatuses(await probeableEngineIds())),lines=["engines:"];for(let status of statuses){let account=describeAccount(status.account),name=`${status.vendor.padEnd(7)} `,version=status.version?` (${status.version})`:"";if(lines.push(` ${name}${binaryLabel(status.binary)}${version}${status.binary.found?` \u2014 ${account}`:""}`),status.accountError)lines.push(` \u26A0 ${status.accountError}`)}let{usable,signedOut}=summarizeEngines(statuses);return{lines,anyUsable:usable.length>0,signedOut}}var CLI_NAME=ROVE_PRODUCT_NAME;function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new RoveDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(readFileSync2(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function tailFile(path,count){try{return readFileSync2(path,"utf8").split(`