@sma1lboy/rove 0.9.220 → 0.9.222

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 (137) hide show
  1. package/dist/cli/{chunk-zhbcnr04.js → chunk-09g89dxy.js} +1 -1
  2. package/dist/cli/chunk-122vhkba.js +2 -0
  3. package/dist/cli/{chunk-px6q0vgx.js → chunk-1da3bqjc.js} +1 -1
  4. package/dist/cli/chunk-228be43v.js +2 -0
  5. package/dist/cli/{chunk-03c94xqf.js → chunk-2rg6aw59.js} +1 -1
  6. package/dist/cli/{chunk-rc2txwsh.js → chunk-2wxhkv4v.js} +1 -1
  7. package/dist/cli/{chunk-ac98bnzn.js → chunk-35xdfn8a.js} +1 -1
  8. package/dist/cli/{chunk-8709ehx1.js → chunk-3gbfsmqf.js} +1 -1
  9. package/dist/cli/{chunk-95qnrw56.js → chunk-3skf3g0c.js} +1 -1
  10. package/dist/cli/{chunk-7gj6kyyw.js → chunk-3xs0hv9f.js} +1 -1
  11. package/dist/cli/{chunk-b7vvsyeg.js → chunk-4pf41rdt.js} +1 -1
  12. package/dist/cli/{chunk-jkhgdeg8.js → chunk-53afdybj.js} +1 -1
  13. package/dist/cli/{chunk-ethxsjh8.js → chunk-53akb9x8.js} +1 -1
  14. package/dist/cli/chunk-55xh5e1h.js +2 -0
  15. package/dist/cli/{chunk-xf09hgzv.js → chunk-58avfm7n.js} +1 -1
  16. package/dist/cli/{chunk-fst31ad0.js → chunk-59c04v65.js} +1 -1
  17. package/dist/cli/{chunk-marvv2xy.js → chunk-5mweps5x.js} +1 -1
  18. package/dist/cli/{chunk-kc41d83f.js → chunk-5qb8czj2.js} +1 -1
  19. package/dist/cli/{chunk-yv44tdjq.js → chunk-5t8cazgm.js} +1 -1
  20. package/dist/cli/{chunk-katrbape.js → chunk-6cm9pb1f.js} +2 -2
  21. package/dist/cli/chunk-7eb6g8h1.js +2 -0
  22. package/dist/cli/{chunk-317g68qr.js → chunk-7taqx3cm.js} +1 -1
  23. package/dist/cli/{chunk-wc0tmpd7.js → chunk-80jwjzn8.js} +1 -1
  24. package/dist/cli/chunk-85pk7c74.js +3 -0
  25. package/dist/cli/chunk-878cxvry.js +4 -0
  26. package/dist/cli/chunk-87zgxa61.js +2 -0
  27. package/dist/cli/chunk-89vj273t.js +8 -0
  28. package/dist/cli/{chunk-azpm8w85.js → chunk-8rk6ecgf.js} +1 -1
  29. package/dist/cli/{chunk-f9p8502x.js → chunk-9213863e.js} +5 -5
  30. package/dist/cli/{chunk-71etdpck.js → chunk-92k1jste.js} +2 -2
  31. package/dist/cli/{chunk-y94sp6wc.js → chunk-94jwnk5q.js} +1 -1
  32. package/dist/cli/{chunk-sma2adev.js → chunk-9zf2wn5c.js} +1 -1
  33. package/dist/cli/{chunk-w0aw0mdw.js → chunk-a9zyq3m8.js} +2 -2
  34. package/dist/cli/{chunk-cyfk0jv0.js → chunk-ad6wj8y8.js} +1 -1
  35. package/dist/cli/{chunk-fb3nax11.js → chunk-ad8dbps8.js} +1 -1
  36. package/dist/cli/chunk-ah9ky2f7.js +2 -0
  37. package/dist/cli/{chunk-rtdkkpn9.js → chunk-b9xgyff6.js} +1 -1
  38. package/dist/cli/{chunk-ppxgqqgn.js → chunk-bgnjt0pv.js} +1 -1
  39. package/dist/cli/{chunk-crt11rmj.js → chunk-c8dbw8rz.js} +1 -1
  40. package/dist/cli/{chunk-s0d0nm6z.js → chunk-cs1k9d61.js} +1 -1
  41. package/dist/cli/chunk-d0f53cxh.js +2 -0
  42. package/dist/cli/chunk-d8a464tx.js +2 -0
  43. package/dist/cli/{chunk-v5ce9fyh.js → chunk-dhfcgq6t.js} +1 -1
  44. package/dist/cli/{chunk-n85tdzdg.js → chunk-ebhc6q1y.js} +2 -2
  45. package/dist/cli/{chunk-rpz50h8f.js → chunk-ed3r9mb4.js} +3 -3
  46. package/dist/cli/chunk-ekdh3m31.js +3 -0
  47. package/dist/cli/chunk-enq6vwz5.js +2 -0
  48. package/dist/cli/chunk-eny3f446.js +2 -0
  49. package/dist/cli/{chunk-2add7c1f.js → chunk-eswcq53q.js} +2 -2
  50. package/dist/cli/{chunk-yywrtb4e.js → chunk-f6fws7v6.js} +1 -1
  51. package/dist/cli/{chunk-7t3p38df.js → chunk-fykzzj26.js} +3 -3
  52. package/dist/cli/{chunk-2d0ysqsn.js → chunk-gkxvcb9n.js} +2 -2
  53. package/dist/cli/{chunk-kf4vema2.js → chunk-gp72n435.js} +1 -1
  54. package/dist/cli/{chunk-xrsref63.js → chunk-h0zssfds.js} +22 -22
  55. package/dist/cli/{chunk-prhqpps4.js → chunk-h30gy8x8.js} +1 -1
  56. package/dist/cli/{chunk-sft2g31n.js → chunk-hmsqfmhg.js} +2 -2
  57. package/dist/cli/chunk-hrrpfxpk.js +2 -0
  58. package/dist/cli/{chunk-vymf5j1q.js → chunk-j5ye4gwh.js} +1 -1
  59. package/dist/cli/{chunk-anjt9swx.js → chunk-j648y3vt.js} +1 -1
  60. package/dist/cli/{chunk-ca2aw3s5.js → chunk-j98bfbz1.js} +1 -1
  61. package/dist/cli/{chunk-fy4wjab9.js → chunk-jbx6t00x.js} +1 -1
  62. package/dist/cli/{chunk-n75gzvnf.js → chunk-jtpcbk1y.js} +1 -1
  63. package/dist/cli/{chunk-c7f9tfdp.js → chunk-jyghj39f.js} +1 -1
  64. package/dist/cli/chunk-k0ymxqbc.js +3 -0
  65. package/dist/cli/{chunk-fc70p4f5.js → chunk-k74rfmkd.js} +1 -1
  66. package/dist/cli/{chunk-2me76rna.js → chunk-ke26my5r.js} +1 -1
  67. package/dist/cli/{chunk-2jj1q7pv.js → chunk-kf8whkc2.js} +2 -2
  68. package/dist/cli/{chunk-2n62t174.js → chunk-kh6v3cq1.js} +1 -1
  69. package/dist/cli/{chunk-hses07jj.js → chunk-kxaqge09.js} +1 -1
  70. package/dist/cli/chunk-md0fz63v.js +2 -0
  71. package/dist/cli/chunk-mhg40es1.js +3 -0
  72. package/dist/cli/{chunk-rhbkwd0b.js → chunk-mmdvkep0.js} +2 -2
  73. package/dist/cli/chunk-mvz2a6a1.js +3 -0
  74. package/dist/cli/{chunk-k7c7dgnq.js → chunk-mz0khr9c.js} +1 -1
  75. package/dist/cli/chunk-ndtbxgyp.js +1 -1
  76. package/dist/cli/chunk-nxht58t9.js +2 -0
  77. package/dist/cli/{chunk-cn4jf4bw.js → chunk-nxr2qg1f.js} +1 -1
  78. package/dist/cli/{chunk-cdy4v61w.js → chunk-nzshm6jy.js} +1 -1
  79. package/dist/cli/{chunk-r54t9yz8.js → chunk-p5yb73tg.js} +15 -4
  80. package/dist/cli/chunk-p92skpts.js +2 -0
  81. package/dist/cli/{chunk-47j1228v.js → chunk-pq897z3n.js} +1 -1
  82. package/dist/cli/{chunk-py4pf4ap.js → chunk-psbfd19k.js} +1 -1
  83. package/dist/cli/chunk-pvr86wd3.js +2 -0
  84. package/dist/cli/{chunk-xvx6xmy1.js → chunk-pvwfah6e.js} +1 -1
  85. package/dist/cli/{chunk-7fg0wtxp.js → chunk-q6h7128y.js} +2 -2
  86. package/dist/cli/chunk-qsne628q.js +2 -0
  87. package/dist/cli/{chunk-kwgyc1hs.js → chunk-rga7a5kk.js} +1 -1
  88. package/dist/cli/{chunk-e8sagd0y.js → chunk-s08dx83v.js} +1 -1
  89. package/dist/cli/{chunk-06k26mfv.js → chunk-smyp21f3.js} +1 -1
  90. package/dist/cli/{chunk-3kantzep.js → chunk-t116w45w.js} +1 -1
  91. package/dist/cli/{chunk-6mtp1w02.js → chunk-t5r0e11g.js} +1 -1
  92. package/dist/cli/{chunk-4er2k3kp.js → chunk-txevhry4.js} +1 -1
  93. package/dist/cli/{chunk-821vk2re.js → chunk-vyr2ga59.js} +1 -1
  94. package/dist/cli/{chunk-6mjzvjkr.js → chunk-w0tdbrpw.js} +1 -1
  95. package/dist/cli/{chunk-c42pwcvw.js → chunk-wenasn1h.js} +1 -1
  96. package/dist/cli/{chunk-582qdm2r.js → chunk-wm7gc75a.js} +2 -2
  97. package/dist/cli/chunk-wmv1bjak.js +2 -0
  98. package/dist/cli/chunk-x6c4jega.js +3 -0
  99. package/dist/cli/{chunk-ce2hj8b7.js → chunk-y1pebzpv.js} +1 -1
  100. package/dist/cli/chunk-y4a23q6m.js +2 -0
  101. package/dist/cli/chunk-zfvg4w3t.js +3 -0
  102. package/dist/cli/index.js +7 -7
  103. package/dist/cli/kobe.js +1 -1
  104. package/dist/cli/rove.js +1 -1
  105. package/package.json +1 -1
  106. package/dist/cli/chunk-02chkhgb.js +0 -2
  107. package/dist/cli/chunk-0k6a4zkj.js +0 -3
  108. package/dist/cli/chunk-3f1ca1kr.js +0 -2
  109. package/dist/cli/chunk-4a91xxgw.js +0 -2
  110. package/dist/cli/chunk-54zebn5b.js +0 -2
  111. package/dist/cli/chunk-5rr14h7y.js +0 -8
  112. package/dist/cli/chunk-68jcangn.js +0 -3
  113. package/dist/cli/chunk-6ad9xx8c.js +0 -2
  114. package/dist/cli/chunk-74h8xgdf.js +0 -3
  115. package/dist/cli/chunk-7np4vfht.js +0 -2
  116. package/dist/cli/chunk-b4nsqbed.js +0 -3
  117. package/dist/cli/chunk-bkwv1zrf.js +0 -2
  118. package/dist/cli/chunk-bnby9m0c.js +0 -2
  119. package/dist/cli/chunk-cqspsq15.js +0 -4
  120. package/dist/cli/chunk-d7csztr7.js +0 -2
  121. package/dist/cli/chunk-e3tvtycw.js +0 -2
  122. package/dist/cli/chunk-e4m00wxs.js +0 -2
  123. package/dist/cli/chunk-fjxjg6gc.js +0 -2
  124. package/dist/cli/chunk-jhw0xy4z.js +0 -3
  125. package/dist/cli/chunk-kqcm3845.js +0 -2
  126. package/dist/cli/chunk-mg5rzt5n.js +0 -2
  127. package/dist/cli/chunk-nm1mcpre.js +0 -3
  128. package/dist/cli/chunk-pgc1ynz9.js +0 -2
  129. package/dist/cli/chunk-qvwsyp1y.js +0 -14
  130. package/dist/cli/chunk-rj6d8whr.js +0 -2
  131. package/dist/cli/chunk-sy4wmc9s.js +0 -2
  132. package/dist/cli/chunk-t3dm9102.js +0 -2
  133. package/dist/cli/chunk-v4sgcv25.js +0 -2
  134. package/dist/cli/chunk-vkj8yy8b.js +0 -3
  135. package/dist/cli/chunk-w6fbdxg2.js +0 -3
  136. package/dist/cli/chunk-yrpf6dfx.js +0 -3
  137. package/dist/cli/chunk-yzg9hpp1.js +0 -3
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{loadStateFile,updateStateFile}from"./chunk-katrbape.js";import{homeDir}from"./chunk-q5jhy3t8.js";import{shortHomeTag}from"./chunk-y8fqdnh3.js";var LOCAL_MACHINE_ID="local",ALIAS_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function isValidMachineAlias(alias){return alias!==LOCAL_MACHINE_ID&&alias.length<=64&&ALIAS_RE.test(alias)}function parseSshTarget(target){let trimmed=target.trim();if(!trimmed)return null;let at=trimmed.lastIndexOf("@"),user=at>=0?trimmed.slice(0,at):void 0,rest=at>=0?trimmed.slice(at+1):trimmed;if(at>=0&&!user)return null;let bracketed=/^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(rest),portMatch=bracketed?null:/^([^:]*):(\d{1,5})$/.exec(rest),host=bracketed?bracketed[1]??"":portMatch?portMatch[1]??"":rest,rawPort=bracketed?bracketed[2]:portMatch?.[2],port=rawPort?Number(rawPort):void 0;if(!host||/\s/.test(host))return null;if(port!==void 0&&(port<1||port>65535))return null;return{host,...user?{user}:{},...port?{port}:{}}}function defaultMachineAlias(args){let source=!args.typedUser&&args.port===void 0&&!isIpLiteral(args.typedHost)?args.typedHost:args.remoteHostname||args.typedHost;return sanitizeAlias(source)}function isIpLiteral(host){return host.includes(":")||/^\d{1,3}(\.\d{1,3}){3}$/.test(host)}function sanitizeAlias(raw){return(raw.split(".")[0]??raw).replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)}function sshTargetOf(config){return config.user?`${config.user}@${config.host}`:config.host}function readMachines(state){let raw=state.machines;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function listMachines(){let machines=readMachines(loadStateFile());return Object.entries(machines).map(([alias,config])=>({alias,...config}))}function getMachine(alias){return readMachines(loadStateFile())[alias]??null}function addMachine(alias,config){let added=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};added=machines[alias]===void 0,machines[alias]={...config,addedAt:config.addedAt??machines[alias]?.addedAt??new Date().toISOString()},state.machines=machines;return}),{added}}function updateMachine(alias,patch){updateStateFile((state)=>{let machines={...readMachines(state)},existing=machines[alias];if(!existing)return!1;machines[alias]={...existing,...patch},state.machines=machines;return})}function setMachineIdentity(alias,identity){updateMachine(alias,{identity})}function removeMachine(alias){let removed=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};if(removed=machines[alias]!==void 0,!removed)return!1;delete machines[alias],state.machines=machines;return}),removed}function dedupeMachines(entries){let kept=[],seen=[];for(let entry of entries){let identity=entry.identity;if(identity){if(seen.some((other)=>sameMachine(other,identity)))continue;seen.push(identity)}kept.push(entry)}return kept}function sameMachine(a,b){return a.hostname===b.hostname&&a.homeDir===b.homeDir&&a.daemonPid===b.daemonPid}function duplicateAliasOf(machines,self,identity){for(let[alias,config]of Object.entries(machines)){if(alias===self)continue;let other=config.identity;if(!other)continue;if(other.hostname===identity.hostname&&other.homeDir===identity.homeDir&&other.daemonPid===identity.daemonPid)return alias}return null}import{tmpdir}from"os";import{join}from"path";var CONTROL_PERSIST_SECONDS=300;function machineSocketDir(alias,home=homeDir()){let natural=join(home,".rove","machines",alias);if(Buffer.byteLength(join(natural,"daemon.sock"),"utf8")<=SOCKET_PATH_LIMIT)return natural;return join(tmpdir(),`rove-m-${shortHomeTag(home)}-${shortHomeTag(alias)}`)}var SOCKET_PATH_LIMIT=100;function localDaemonSocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"daemon.sock")}function localPtySocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"pty.sock")}function controlPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"cm")}function machineSshArgs(alias,config,opts={}){let argv=["ssh"];if(opts.batch!==!1)argv.push("-o","BatchMode=yes");if(argv.push("-o","ControlMaster=auto","-o",`ControlPath=${controlPath(alias,opts.home)}`,"-o",`ControlPersist=${CONTROL_PERSIST_SECONDS}`,"-o","StrictHostKeyChecking=accept-new"),config.port)argv.push("-p",String(config.port));if(config.auth.kind==="key"&&config.auth.keyPath)argv.push("-i",config.auth.keyPath);return argv.push(sshTargetOf(config)),argv}
2
+ import{loadStateFile,updateStateFile}from"./chunk-6cm9pb1f.js";import{homeDir}from"./chunk-q5jhy3t8.js";import{shortHomeTag}from"./chunk-y8fqdnh3.js";var LOCAL_MACHINE_ID="local",ALIAS_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function isValidMachineAlias(alias){return alias!==LOCAL_MACHINE_ID&&alias.length<=64&&ALIAS_RE.test(alias)}function parseSshTarget(target){let trimmed=target.trim();if(!trimmed)return null;let at=trimmed.lastIndexOf("@"),user=at>=0?trimmed.slice(0,at):void 0,rest=at>=0?trimmed.slice(at+1):trimmed;if(at>=0&&!user)return null;let bracketed=/^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(rest),portMatch=bracketed?null:/^([^:]*):(\d{1,5})$/.exec(rest),host=bracketed?bracketed[1]??"":portMatch?portMatch[1]??"":rest,rawPort=bracketed?bracketed[2]:portMatch?.[2],port=rawPort?Number(rawPort):void 0;if(!host||/\s/.test(host))return null;if(port!==void 0&&(port<1||port>65535))return null;return{host,...user?{user}:{},...port?{port}:{}}}function defaultMachineAlias(args){let source=!args.typedUser&&args.port===void 0&&!isIpLiteral(args.typedHost)?args.typedHost:args.remoteHostname||args.typedHost;return sanitizeAlias(source)}function isIpLiteral(host){return host.includes(":")||/^\d{1,3}(\.\d{1,3}){3}$/.test(host)}function sanitizeAlias(raw){return(raw.split(".")[0]??raw).replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)}function sshTargetOf(config){return config.user?`${config.user}@${config.host}`:config.host}function readMachines(state){let raw=state.machines;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function listMachines(){let machines=readMachines(loadStateFile());return Object.entries(machines).map(([alias,config])=>({alias,...config}))}function getMachine(alias){return readMachines(loadStateFile())[alias]??null}function addMachine(alias,config){let added=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};added=machines[alias]===void 0,machines[alias]={...config,addedAt:config.addedAt??machines[alias]?.addedAt??new Date().toISOString()},state.machines=machines;return}),{added}}function updateMachine(alias,patch){updateStateFile((state)=>{let machines={...readMachines(state)},existing=machines[alias];if(!existing)return!1;machines[alias]={...existing,...patch},state.machines=machines;return})}function setMachineIdentity(alias,identity){updateMachine(alias,{identity})}function removeMachine(alias){let removed=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};if(removed=machines[alias]!==void 0,!removed)return!1;delete machines[alias],state.machines=machines;return}),removed}function dedupeMachines(entries){let kept=[],seen=[];for(let entry of entries){let identity=entry.identity;if(identity){if(seen.some((other)=>sameMachine(other,identity)))continue;seen.push(identity)}kept.push(entry)}return kept}function sameMachine(a,b){return a.hostname===b.hostname&&a.homeDir===b.homeDir&&a.daemonPid===b.daemonPid}function duplicateAliasOf(machines,self,identity){for(let[alias,config]of Object.entries(machines)){if(alias===self)continue;let other=config.identity;if(!other)continue;if(other.hostname===identity.hostname&&other.homeDir===identity.homeDir&&other.daemonPid===identity.daemonPid)return alias}return null}import{tmpdir}from"os";import{join}from"path";var CONTROL_PERSIST_SECONDS=300;function machineSocketDir(alias,home=homeDir()){let natural=join(home,".rove","machines",alias);if(Buffer.byteLength(join(natural,"daemon.sock"),"utf8")<=SOCKET_PATH_LIMIT)return natural;return join(tmpdir(),`rove-m-${shortHomeTag(home)}-${shortHomeTag(alias)}`)}var SOCKET_PATH_LIMIT=100;function localDaemonSocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"daemon.sock")}function localPtySocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"pty.sock")}function controlPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"cm")}function machineSshArgs(alias,config,opts={}){let argv=["ssh"];if(opts.batch!==!1)argv.push("-o","BatchMode=yes");if(argv.push("-o","ControlMaster=auto","-o",`ControlPath=${controlPath(alias,opts.home)}`,"-o",`ControlPersist=${CONTROL_PERSIST_SECONDS}`,"-o","StrictHostKeyChecking=accept-new"),config.port)argv.push("-p",String(config.port));if(config.auth.kind==="key"&&config.auth.keyPath)argv.push("-i",config.auth.keyPath);return argv.push(sshTargetOf(config)),argv}
3
3
  export{isValidMachineAlias,parseSshTarget,defaultMachineAlias,sanitizeAlias,sshTargetOf,readMachines,listMachines,getMachine,addMachine,updateMachine,setMachineIdentity,removeMachine,dedupeMachines,duplicateAliasOf,machineSocketDir,localDaemonSocketPath,localPtySocketPath,machineSshArgs};
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{formatBytes,hookConfigIssues}from"./chunk-rtdkkpn9.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-dqndd97s.js";import"./chunk-7t3p38df.js";import"./chunk-nm1mcpre.js";import"./chunk-jkhgdeg8.js";import"./chunk-rz8zs7j8.js";import"./chunk-xsrcwcjc.js";import"./chunk-vyb5a2rh.js";import"./chunk-r2pztgm6.js";import"./chunk-px6q0vgx.js";import"./chunk-63wmhbqs.js";import{resolveNodeBinary}from"./chunk-cqspsq15.js";import{formatDaemonInfo}from"./chunk-rcyasw34.js";import"./chunk-b99tf0jr.js";import"./chunk-g3r1dwy9.js";import"./chunk-w25b7xxz.js";import"./chunk-h4n8ffqy.js";import"./chunk-59xc6m1q.js";import{isStaleInstallError,resolveKobeSpawn}from"./chunk-yv44tdjq.js";import"./chunk-c42pwcvw.js";import{KobeDaemonClient}from"./chunk-mjdt28x6.js";import{isForeignDaemonHome}from"./chunk-p1zab1sy.js";import"./chunk-hqbmzz4t.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,probeEngines,probeGit,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-vkj8yy8b.js";import"./chunk-7gj6kyyw.js";import"./chunk-jhw0xy4z.js";import"./chunk-b4nsqbed.js";import{t}from"./chunk-6mjzvjkr.js";import"./chunk-74h8xgdf.js";import"./chunk-sdyzxayr.js";import"./chunk-rhbkwd0b.js";import"./chunk-47j1228v.js";import"./chunk-azpm8w85.js";import"./chunk-w7zv47mp.js";import"./chunk-khj0apc7.js";import{CURRENT_VERSION,package_default}from"./chunk-rc2txwsh.js";import"./chunk-jvxh93nz.js";import"./chunk-2brn8e1y.js";import{kobeSkillState,skillInstallCommand}from"./chunk-w0aw0mdw.js";import"./chunk-cdy4v61w.js";import"./chunk-wc0tmpd7.js";import"./chunk-7kysxgbq.js";import{readableLegacyIndexPath}from"./chunk-b7vvsyeg.js";import"./chunk-xy8be792.js";import"./chunk-crt11rmj.js";import"./chunk-40dgv828.js";import"./chunk-katrbape.js";import"./chunk-hq2n27y1.js";import"./chunk-3es6spp4.js";import"./chunk-pw6yfj10.js";import"./chunk-05jej26n.js";import"./chunk-81p6mm0p.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-q5jhy3t8.js";import{readPidFile}from"./chunk-vnpqemb0.js";import"./chunk-f10n6063.js";import"./chunk-9prawccj.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-y8fqdnh3.js";import{activeCliName}from"./chunk-00ehck55.js";import"./chunk-fxs82dsx.js";import{LEGACY_KOBE_STATE_DIR_BASENAME}from"./chunk-sb0ns0c7.js";import"./chunk-hq4b3fca.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-wqfp8d9w.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: \`KOBE_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="KOBE_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,hookConfigIssues}from"./chunk-b9xgyff6.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-dqndd97s.js";import"./chunk-fykzzj26.js";import"./chunk-85pk7c74.js";import"./chunk-53afdybj.js";import"./chunk-rz8zs7j8.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-3xs0hv9f.js";import"./chunk-mhg40es1.js";import"./chunk-r2pztgm6.js";import"./chunk-1da3bqjc.js";import"./chunk-63wmhbqs.js";import"./chunk-xsrcwcjc.js";import"./chunk-59xc6m1q.js";import{resolveNodeBinary}from"./chunk-878cxvry.js";import{formatDaemonInfo}from"./chunk-rcyasw34.js";import"./chunk-b99tf0jr.js";import"./chunk-mmdvkep0.js";import"./chunk-pq897z3n.js";import"./chunk-8rk6ecgf.js";import"./chunk-w7zv47mp.js";import"./chunk-khj0apc7.js";import"./chunk-g3r1dwy9.js";import"./chunk-w25b7xxz.js";import"./chunk-h4n8ffqy.js";import"./chunk-vyb5a2rh.js";import"./chunk-jvxh93nz.js";import{isStaleInstallError,resolveKobeSpawn}from"./chunk-5t8cazgm.js";import"./chunk-wenasn1h.js";import"./chunk-2brn8e1y.js";import"./chunk-nzshm6jy.js";import"./chunk-80jwjzn8.js";import"./chunk-7kysxgbq.js";import{readableLegacyIndexPath}from"./chunk-4pf41rdt.js";import"./chunk-xy8be792.js";import"./chunk-05jej26n.js";import{CURRENT_VERSION,package_default}from"./chunk-2wxhkv4v.js";import{kobeSkillState,skillInstallCommand}from"./chunk-a9zyq3m8.js";import"./chunk-c8dbw8rz.js";import"./chunk-6cm9pb1f.js";import"./chunk-hq2n27y1.js";import"./chunk-40dgv828.js";import"./chunk-81p6mm0p.js";import{readPidFile}from"./chunk-vnpqemb0.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-q5jhy3t8.js";import"./chunk-9prawccj.js";import{activeCliName}from"./chunk-00ehck55.js";import"./chunk-fxs82dsx.js";import{LEGACY_KOBE_STATE_DIR_BASENAME}from"./chunk-sb0ns0c7.js";import{t}from"./chunk-w0tdbrpw.js";import"./chunk-mvz2a6a1.js";import"./chunk-sdyzxayr.js";import"./chunk-pxk2c2vj.js";import{KobeDaemonClient}from"./chunk-mjdt28x6.js";import{isForeignDaemonHome}from"./chunk-p1zab1sy.js";import"./chunk-hqbmzz4t.js";import"./chunk-3es6spp4.js";import"./chunk-pw6yfj10.js";import"./chunk-f10n6063.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-y8fqdnh3.js";import"./chunk-hq4b3fca.js";import{__require}from"./chunk-wqfp8d9w.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}import{createInterface}from"readline";function daemonRestartFix(cliName,reason){return{kind:"run",id:"daemon-restart",label:t(`doctor.fix.${reason}`),command:[cliName,"daemon","restart"],why:t("doctor.fix.daemonRestartWhy")}}function skillInstallFix(installCommand,stale){return{kind:"run",id:"skill-install",label:t(stale?"doctor.fix.skillStale":"doctor.fix.skillMissing"),command:installCommand.split(" "),why:t("doctor.fix.skillInstallWhy")}}function resetManualFix(cliName,reason){return{kind:"manual",id:`reset:${reason}`,label:t(`doctor.fix.${reason}`),action:`${cliName} reset`,why:t("doctor.fix.resetWhy")}}function killOrphansManualFix(cliName,count){return{kind:"manual",id:"kill-orphans",label:t("doctor.fix.orphans",{count}),action:`${cliName} doctor --kill-orphans`,why:t("doctor.fix.orphansWhy")}}function engineTabsManualFix(){return{kind:"manual",id:"engine-tabs",label:t("doctor.fix.engineTabs"),action:t("doctor.fix.engineTabsAction"),why:t("doctor.fix.engineTabsWhy")}}function reinstallManualFix(){return{kind:"manual",id:"reinstall",label:t("doctor.fix.staleInstall"),action:t("doctor.fix.staleInstallAction"),why:t("doctor.fix.staleInstallWhy")}}function spawnHelperFix(paths){return{kind:"run",id:"spawn-helper-chmod",label:t("doctor.fix.spawnHelper"),command:["chmod","755",...paths],why:t("doctor.fix.spawnHelperWhy")}}function humanOnlyFix(reason,vars){return{kind:"manual",id:reason,label:t(`doctor.fix.${reason}`),action:t(`doctor.fix.${reason}Action`,vars),why:t("doctor.fix.humanOnlyWhy")}}function noEngineFix(signedOut){return signedOut.length>0?humanOnlyFix("noEngineLogin",{list:signedOut.join(", ")}):humanOnlyFix("noEngine")}function dedupeFixes(fixes){let seen=new Set;return fixes.filter((fix)=>{if(seen.has(fix.id))return!1;return seen.add(fix.id),!0})}async function applyFixes(collected,rt){let fixes=dedupeFixes(collected);if(fixes.length===0){rt.out(""),rt.out(t("doctor.fix.none"));return}let runnable=fixes.filter((fix)=>fix.kind==="run");if(runnable.length>0){rt.out(""),rt.out(t("doctor.fix.header"));for(let fix of runnable){if(rt.out(` ${fix.label}`),rt.out(` ${t("doctor.fix.willRun",{command:fix.command.join(" ")})}`),rt.out(` ${fix.why}`),!rt.interactive)continue;if(!await rt.confirm(` ${t("doctor.fix.confirmPrompt")}`)){rt.out(` ${t("doctor.fix.skipped")}`);continue}let code=await rt.exec(fix.command);rt.out(code===0?` ${t("doctor.fix.done")}`:` ${t("doctor.fix.failed",{code})}`)}if(!rt.interactive)rt.out(` ${t("doctor.fix.nonInteractive")}`)}let manual=fixes.filter((fix)=>fix.kind==="manual");if(manual.length>0){rt.out(""),rt.out(t("doctor.fix.manualHeader"));for(let fix of manual)rt.out(` ${fix.label}`),rt.out(` \u2192 ${fix.action}`),rt.out(` ${fix.why}`)}}async function confirmTty(question){let readline=createInterface({input:process.stdin,output:process.stdout});try{let answer=await new Promise((resolve)=>readline.question(question,resolve));return answer.trim().toLowerCase()==="y"||answer.trim().toLowerCase()==="yes"}finally{readline.close()}}async function execInherited(command){try{return await Bun.spawn([...command],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}catch{return 127}}function defaultFixRuntime(){return{confirm:confirmTty,exec:execInherited,out:(line)=>console.log(line),interactive:process.stdin.isTTY===!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: \`KOBE_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="KOBE_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
- `);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())]}var CLI_NAME=activeCliName();function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new KobeDaemonClient(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(`
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 detectEngineStatuses(await probeableEngineIds()),lines=["engines:"];for(let status of statuses){let account=describeAccount(status.account),name=`${status.vendor.padEnd(7)} `;if(lines.push(` ${name}${binaryLabel(status.binary)}${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=activeCliName();function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new KobeDaemonClient(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(`
6
6
  `).filter((line)=>line.trim().length>0).slice(-count).join(`
7
7
  `)}catch{return""}}function describeInstall(){try{let[,entry]=resolveKobeSpawn([]);return{line:`install: \u2713 ${entry??process.execPath}`,ok:!0}}catch(err){if(!isStaleInstallError(err))return{line:`install: ? could not check (${String(err)})`,ok:!0};return{line:["install: \u2717 GONE \u2014 this process is running from an install that no longer exists on disk"," it cannot start a daemon; every reconnect fails the same way until you reinstall"," \u2192 npm install -g @sma1lboy/rove (then relaunch Rove)"].join(`
8
8
  `),ok:!1}}}async function appendUnavailableProcess(out,label,pidPath,socketPath){let pid=await readPidFile(pidPath),wedged=pid!==null&&pid!==void 0&&isProcessAlive(pid);if(wedged)out.push(`${label}: \u2717 WEDGED \u2014 process alive (pid ${pid}) but socket is unreachable`);else if(pid)out.push(`${label}: \u2717 not running (stale pidfile \u2192 pid ${pid} is gone)`);else out.push(`${label}: \u2717 not running (no pidfile)`);if(existsSync(socketPath))out.push(` orphan socket file present: ${socketPath}`);return wedged?"wedged":"down"}async function collectDoctor(){let daemonSocket=defaultDaemonSocketPath(),daemonLog=defaultDaemonLogPath(),ptySocket=defaultPtyHostSocketPath(),ptyLog=defaultPtyHostLogPath(),canonicalTasks=join2(roveStateDir(),"tasks.json"),legacyTasks=join2(homeDir(),LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),readableLegacy=readableLegacyIndexPath(canonicalTasks,legacyTasks),usingLegacyTasks=!existsSync(canonicalTasks)&&readableLegacy!==void 0&&existsSync(readableLegacy),tasksPath=usingLegacyTasks?legacyTasks:canonicalTasks,statePath=kvStatePath(),fixes=[],git=await probeGit();if(!git.found)fixes.push(humanOnlyFix("git"));let engines=await probeEngines();if(!engines.anyUsable)fixes.push(noEngineFix(engines.signedOut));let install=describeInstall();if(!install.ok)fixes.push(reinstallManualFix());let staleBun=!isBunAtLeast(Bun.version);if(staleBun)fixes.push(humanOnlyFix("staleBun"));let out=["Rove doctor",` build: v${CURRENT_VERSION} (${process.platform} ${process.arch}, bun ${Bun.version})`,...staleBun?[` \u26A0 bun ${Bun.version} is below the ${MIN_BUN_VERSION} Rove needs \u2014 terminals will not paint`]:[],` home: ${homeDir()}`,"",...await terminalDoctorLines(),git.line,"",...engines.lines,"",install.line,""],daemon=await requestIfReachable(daemonSocket,"daemon.status");if(daemon){let pid=typeof daemon.daemonPid==="number"?daemon.daemonPid:"?",uptime=typeof daemon.uptimeMs==="number"?fmtDuration(daemon.uptimeMs):"?",tasks=typeof daemon.taskCount==="number"?daemon.taskCount:"?",clients=typeof daemon.attachedClients==="number"?daemon.attachedClients:"?";out.push(`daemon: \u2713 running (pid ${pid}, up ${uptime}, ${tasks} task(s), ${clients} client(s))`);let version=typeof daemon.kobeVersion==="string"?daemon.kobeVersion:void 0;if(version&&version!==CURRENT_VERSION)out.push(` \u26A0 stale build: daemon is v${version}, you launched v${CURRENT_VERSION}`),out.push(` \u2192 run \`${CLI_NAME} daemon restart\`, then relaunch Rove`),fixes.push(daemonRestartFix(CLI_NAME,"daemonStale"));else if(version)out.push(` build: v${version}`);if(isForeignDaemonHome(typeof daemon.homeDir==="string"?daemon.homeDir:void 0,homeDir()))out.push(` \u26A0 foreign home: daemon serves ${String(daemon.homeDir)}, you are reading ${homeDir()}`),out.push(` \u2192 clear ROVE_HOME_DIR/KOBE_HOME_DIR, then \`${CLI_NAME} daemon restart\``);let tabs=(await requestIfReachable(daemonSocket,"debug.inspect"))?.activity?.tabs;if(tabs){let hookInput={socketPath:daemonSocket,configIssues:hookConfigIssues()},verdict=classifyHookChannel({tabs,...hookInput});if(out.push("",...hookChannelDoctorLines(verdict,hookInput,CLI_NAME)),verdict.kind==="down")fixes.push(daemonRestartFix(CLI_NAME,"hooksDown"),engineTabsManualFix())}else out.push("","hooks: ? could not read the daemon's activity registry (debug.inspect unavailable)"),fixes.push(daemonRestartFix(CLI_NAME,"inspectStale"))}else{let state=await appendUnavailableProcess(out,"daemon ",defaultDaemonPidPath(),daemonSocket);fixes.push(state==="wedged"?resetManualFix(CLI_NAME,"resetDaemonWedged"):daemonRestartFix(CLI_NAME,"daemonDown"));let tail=tailFile(daemonLog,8);if(tail){out.push(" last lines of daemon.log:");for(let line of tail.split(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{$jsx,$jsxs,ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useRenderer,useT,useTheme}from"./chunk-p5yb73tg.js";import"./chunk-k0ymxqbc.js";import{require_react_production}from"./chunk-a82ec09z.js";import"./chunk-764bsyb0.js";import"./chunk-nxr2qg1f.js";import"./chunk-59xc6m1q.js";import"./chunk-ekdh3m31.js";import"./chunk-b99tf0jr.js";import"./chunk-x6c4jega.js";import"./chunk-k6nxyxyh.js";import"./chunk-h4n8ffqy.js";import"./chunk-6xppe9bj.js";import"./chunk-5t8cazgm.js";import"./chunk-wenasn1h.js";import"./chunk-fczqwtmq.js";import"./chunk-2brn8e1y.js";import"./chunk-xy8be792.js";import{BREAKING_VERSIONS,CURRENT_VERSION,UPDATE_COMMAND,breakingVersionsCrossed,fetchReleaseNotes,fetchReleaseSummaries}from"./chunk-2wxhkv4v.js";import"./chunk-6cm9pb1f.js";import"./chunk-hq2n27y1.js";import"./chunk-40dgv828.js";import"./chunk-vnpqemb0.js";import"./chunk-q5jhy3t8.js";import"./chunk-9prawccj.js";import"./chunk-sb0ns0c7.js";import"./chunk-w0tdbrpw.js";import"./chunk-mvz2a6a1.js";import"./chunk-sdyzxayr.js";import"./chunk-mjdt28x6.js";import"./chunk-p1zab1sy.js";import"./chunk-hqbmzz4t.js";import"./chunk-3es6spp4.js";import"./chunk-pw6yfj10.js";import"./chunk-f10n6063.js";import"./chunk-y8fqdnh3.js";import"./chunk-hq4b3fca.js";import{__toESM}from"./chunk-wqfp8d9w.js";import{TextAttributes}from"@opentui/core";var import_react2=__toESM(require_react_production(),1);var RELEASE_LIMIT=20;function VersionsPage(props){let{theme}=useTheme(),t=useT(),renderer=useRenderer(),[releases,setReleases]=import_react2.useState(null),[cursor,setCursor]=import_react2.useState(0),[notes,setNotes]=import_react2.useState({}),[status,setStatus]=import_react2.useState(null),selected=releases?.[cursor],crossings=selected?breakingVersionsCrossed(CURRENT_VERSION,selected.version):[],loadSummaries=props.fetchSummaries??fetchReleaseSummaries,loadNotes=props.fetchNotes??fetchReleaseNotes;import_react2.useEffect(()=>{loadSummaries(RELEASE_LIMIT).then((fetched)=>setReleases(fetched))},[loadSummaries]);let selectedVersion=selected?.version;import_react2.useEffect(()=>{if(selectedVersion===void 0||notes[selectedVersion]!==void 0)return;setNotes((cache)=>({...cache,[selectedVersion]:"loading"})),loadNotes(selectedVersion).then((fetched)=>{setNotes((cache)=>({...cache,[selectedVersion]:fetched??"missing"}))})},[selectedVersion,notes,loadNotes]);function move(delta){let count=releases?.length??0;if(count===0)return;setCursor((index)=>(index+delta+count)%count)}async function installSelected(){if(!selected)return;setStatus(t("update.statusRunningUpdater")),await new Promise((resolve)=>setTimeout(resolve,30)),await runShellUpdater({renderer,t,targetLabel:selected.version,command:`${UPDATE_COMMAND} -s -- ${selected.version}`})}useBindings(()=>({bindings:[{key:"up",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>void installSelected()},{key:"u",cmd:()=>void installSelected()},...pageCloseBindings(props.onClose)]}));let selectedNotes=selectedVersion===void 0?void 0:notes[selectedVersion];return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes.BOLD,wrapMode:"none",children:t("update.versions.pageTitle")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:props.onClose,children:t("update.versions.closeHint")})]}),$jsxs("box",{flexDirection:"row",flexGrow:1,paddingTop:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:26,flexShrink:0,children:[releases===null?$jsx("text",{fg:theme.textMuted,children:t("update.versions.loading")}):null,releases!==null&&releases.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.versions.unavailable")}):null,(releases??[]).map((release,index)=>{let active=index===cursor,tags=[release.version===CURRENT_VERSION?t("update.versions.tagCurrent"):"",index===0?t("update.versions.tagLatest"):"",BREAKING_VERSIONS.includes(release.version)?t("update.versions.tagBreaking"):""].filter(Boolean).join(" ");return $jsxs("box",{flexDirection:"row",gap:1,paddingLeft:1,backgroundColor:active?theme.primary:void 0,onMouseUp:()=>setCursor(index),children:[$jsxs("text",{fg:active?theme.selectedListItemText:theme.text,attributes:release.version===CURRENT_VERSION?TextAttributes.BOLD:void 0,wrapMode:"none",children:["v",release.version]}),tags?$jsx("text",{fg:active?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:tags}):null]},release.version)})]}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsx("scrollbox",{flexGrow:1,flexShrink:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:0,children:[selectedNotes==="loading"?$jsx("text",{fg:theme.textMuted,children:t("update.loadingNotes")}):null,selectedNotes==="missing"?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.notesUnavailable")}):null,selectedNotes!==void 0&&selectedNotes!=="loading"&&selectedNotes!=="missing"?$jsx(ReleaseNotesBody,{body:selectedNotes.body}):null]})}),crossings.length>0?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t("update.versions.breakingWarning",{versions:crossings.join(", ")})}):null]})]}),status?$jsx("text",{fg:theme.info,wrapMode:"word",children:status}):null,$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes.DIM,wrapMode:"none",children:t("update.versions.footerHint")})})]})}var INLINE_ROWS=24;async function startVersionsHost(){await bootPaneHost({inlineRows:INLINE_ROWS,setup:()=>({root:()=>$jsx(VersionsPage,{onClose:()=>process.exit(0)})})})}export{startVersionsHost,VersionsPage};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{protocolEntry}from"./chunk-jhw0xy4z.js";import{getPersistedString}from"./chunk-crt11rmj.js";var AUTO_EFFORT_TIERS=["swift","standard","deep"];function isAutoEffortTier(value){return AUTO_EFFORT_TIERS.includes(value??"")}var DEFAULT_AUTO_EFFORT={swift:{engine:"claude",model:"sonnet"},standard:{engine:"claude",model:"opus"},deep:{engine:"claude",model:"fable"}};function autoEffortKey(tier,field){return`autoEffort.${tier}.${field}`}function stringAt(get,key){let raw=get(key);return typeof raw==="string"?raw:void 0}function readAutoEffortTable(get=getPersistedString){let table={};for(let tier of AUTO_EFFORT_TIERS){let base=DEFAULT_AUTO_EFFORT[tier],engine=stringAt(get,autoEffortKey(tier,"engine"));if(engine!==void 0&&!engine.trim())return null;let model=stringAt(get,autoEffortKey(tier,"model")),effort=stringAt(get,autoEffortKey(tier,"effort")),resolvedModel=model===void 0?base.model:model.trim()||void 0,resolvedEffort=effort===void 0?base.effort:effort.trim()||void 0;table[tier]={engine:engine?.trim()||base.engine,...resolvedModel?{model:resolvedModel}:{},...resolvedEffort?{effort:resolvedEffort}:{}}}return table}function tierBlock(target,deps){let{engine}=target;if(!deps.engineIds.has(engine))return{kind:"engine",engine};if(deps.accountKind(engine)==="none")return{kind:"account",engine};let entry=protocolEntry(engine);if(target.model&&!entry.modelArgv)return{kind:"model",engine,model:target.model};if(target.effort){let levels=entry.effortLevels??[];if(!levels.includes(target.effort))return{kind:"effort",engine,effort:target.effort,levels}}return null}function describeTierBlock(block){switch(block.kind){case"engine":return`engine ${block.engine} is not one engine-list names`;case"account":return`engine ${block.engine} is not logged in`;case"model":return`engine ${block.engine} declares no model flag, so model ${JSON.stringify(block.model)} cannot be passed`;case"effort":return block.levels.length===0?`engine ${block.engine} declares no reasoning effort levels`:`engine ${block.engine} does not accept effort ${JSON.stringify(block.effort)} \u2014 it declares ${block.levels.join(", ")}`}}var TASK_GROUPS=["waiting-on-you","landing","ready-for-review","working","idle","unknown"];function taskGroupRank(group){return TASK_GROUPS.indexOf(group)}var ERROR_SETTLE_MS=20000,DEAD_SETTLE_MS=60000;function actedOn(task){if(task.status==="done"||task.status==="canceled")return!0;let lifecycle=task.prStatus?.lifecycle;return lifecycle==="merged"||lifecycle==="closed"}function autoResumes(task,now){let at=task.quotaResume?.resumeAt;if(!at)return!1;let ms=Date.parse(at);return!Number.isNaN(ms)&&ms>now}function deriveTaskGroup(input){let{task,now}=input,activity=input.activity??null,state=activity?.state,age=activity?Math.max(0,now-activity.at):0;if(task.deletion?.phase==="error")return"waiting-on-you";if(state==="permission_needed")return"waiting-on-you";if(state==="rate_limited"&&!autoResumes(task,now))return"waiting-on-you";if(state==="error"&&age>=ERROR_SETTLE_MS)return"waiting-on-you";if(activity&&!task.report&&age>=DEAD_SETTLE_MS&&(state==="dead"||input.tabAlive===!1))return"waiting-on-you";if(state==="running"&&input.tabAlive!==!1)return"working";if(state==="rate_limited")return"working";let pr=task.prStatus;if((pr?.lifecycle==="open"||pr?.lifecycle==="ready_to_merge")&&(pr.reviewDecision??"").toUpperCase()==="APPROVED")return"landing";if((task.report!==void 0||state==="turn_complete")&&!actedOn(task))return"ready-for-review";return activity?"idle":"unknown"}function taskGroupOf(input){let group=deriveTaskGroup(input);return{group,rank:taskGroupRank(group)}}
2
+ import{protocolEntry}from"./chunk-878cxvry.js";import{getPersistedString}from"./chunk-c8dbw8rz.js";var AUTO_EFFORT_TIERS=["swift","standard","deep"];function isAutoEffortTier(value){return AUTO_EFFORT_TIERS.includes(value??"")}var DEFAULT_AUTO_EFFORT={swift:{engine:"claude",model:"sonnet"},standard:{engine:"claude",model:"opus"},deep:{engine:"claude",model:"fable"}};function autoEffortKey(tier,field){return`autoEffort.${tier}.${field}`}function stringAt(get,key){let raw=get(key);return typeof raw==="string"?raw:void 0}function readAutoEffortTable(get=getPersistedString){let table={};for(let tier of AUTO_EFFORT_TIERS){let base=DEFAULT_AUTO_EFFORT[tier],engine=stringAt(get,autoEffortKey(tier,"engine"));if(engine!==void 0&&!engine.trim())return null;let model=stringAt(get,autoEffortKey(tier,"model")),effort=stringAt(get,autoEffortKey(tier,"effort")),resolvedModel=model===void 0?base.model:model.trim()||void 0,resolvedEffort=effort===void 0?base.effort:effort.trim()||void 0;table[tier]={engine:engine?.trim()||base.engine,...resolvedModel?{model:resolvedModel}:{},...resolvedEffort?{effort:resolvedEffort}:{}}}return table}function tierBlock(target,deps){let{engine}=target;if(!deps.engineIds.has(engine))return{kind:"engine",engine};if(deps.accountKind(engine)==="none")return{kind:"account",engine};let entry=protocolEntry(engine);if(target.model&&!entry.modelArgv)return{kind:"model",engine,model:target.model};if(target.effort){let levels=entry.effortLevels??[];if(!levels.includes(target.effort))return{kind:"effort",engine,effort:target.effort,levels}}return null}function describeTierBlock(block){switch(block.kind){case"engine":return`engine ${block.engine} is not one engine-list names`;case"account":return`engine ${block.engine} is not logged in`;case"model":return`engine ${block.engine} declares no model flag, so model ${JSON.stringify(block.model)} cannot be passed`;case"effort":return block.levels.length===0?`engine ${block.engine} declares no reasoning effort levels`:`engine ${block.engine} does not accept effort ${JSON.stringify(block.effort)} \u2014 it declares ${block.levels.join(", ")}`}}var TASK_GROUPS=["waiting-on-you","landing","ready-for-review","working","idle","unknown"];function taskGroupRank(group){return TASK_GROUPS.indexOf(group)}var ERROR_SETTLE_MS=20000,DEAD_SETTLE_MS=60000;function actedOn(task){if(task.status==="done"||task.status==="canceled")return!0;let lifecycle=task.prStatus?.lifecycle;return lifecycle==="merged"||lifecycle==="closed"}function autoResumes(task,now){let at=task.quotaResume?.resumeAt;if(!at)return!1;let ms=Date.parse(at);return!Number.isNaN(ms)&&ms>now}function deriveTaskGroup(input){let{task,now}=input,activity=input.activity??null,state=activity?.state,age=activity?Math.max(0,now-activity.at):0;if(task.deletion?.phase==="error")return"waiting-on-you";if(state==="permission_needed")return"waiting-on-you";if(state==="rate_limited"&&!autoResumes(task,now))return"waiting-on-you";if(state==="error"&&age>=ERROR_SETTLE_MS)return"waiting-on-you";if(activity&&!task.report&&age>=DEAD_SETTLE_MS&&(state==="dead"||input.tabAlive===!1))return"waiting-on-you";if(state==="running"&&input.tabAlive!==!1)return"working";if(state==="rate_limited")return"working";let pr=task.prStatus;if((pr?.lifecycle==="open"||pr?.lifecycle==="ready_to_merge")&&(pr.reviewDecision??"").toUpperCase()==="APPROVED")return"landing";if((task.report!==void 0||state==="turn_complete")&&!actedOn(task))return"ready-for-review";return activity?"idle":"unknown"}function taskGroupOf(input){let group=deriveTaskGroup(input);return{group,rank:taskGroupRank(group)}}
3
3
  export{AUTO_EFFORT_TIERS,isAutoEffortTier,autoEffortKey,readAutoEffortTable,tierBlock,describeTierBlock,taskGroupRank,deriveTaskGroup,taskGroupOf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{buildPluginEnv}from"./chunk-jkhgdeg8.js";import{currentPluginPlatform,loadPluginRegistry,readPluginManifest,supportsPlatform}from"./chunk-px6q0vgx.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";function shq(s){return`'${s.replace(/'/g,"'\\''")}'`}function buildPaneArgv(pluginId,pluginRoot,pane,opts){let env=buildPluginEnv({homeDir:opts.homeDir,socketPath:opts.socketPath,binPath:opts.binPath,pluginId,pluginRoot,extra:{ROVE_PLUGIN_ENTRYPOINT_ID:pane.id,...opts.taskId?{ROVE_PLUGIN_TASK_ID:opts.taskId}:{}}}),pairs=Object.entries(env).filter(([k])=>k.startsWith("ROVE_")||k.startsWith("KOBE_")),command=pane.command.map((a)=>a.replace(/\$\{?(?:ROVE|KOBE)_PLUGIN_ROOT\}?/g,pluginRoot)),script=`exec env ${pairs.map(([k,v])=>shq(`${k}=${v}`)).join(" ")} ${command.map(shq).join(" ")}`;return[resolveLoginShell(),"-ilc",script]}function listPaneLaunches(opts){let platform=currentPluginPlatform(),out=[];for(let entry of loadPluginRegistry(opts.homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);if(!supportsPlatform({},manifest,platform))continue;for(let pane of manifest.panes){if(!supportsPlatform(pane,manifest,platform))continue;out.push({pluginId:entry.id,paneId:pane.id,title:pane.title,placement:pane.placement,argv:buildPaneArgv(entry.id,entry.root,pane,opts)})}}catch{}}return out}
2
+ import{buildPluginEnv}from"./chunk-53afdybj.js";import{currentPluginPlatform,loadPluginRegistry,readPluginManifest,supportsPlatform}from"./chunk-1da3bqjc.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";function shq(s){return`'${s.replace(/'/g,"'\\''")}'`}function buildPaneArgv(pluginId,pluginRoot,pane,opts){let env=buildPluginEnv({homeDir:opts.homeDir,socketPath:opts.socketPath,binPath:opts.binPath,pluginId,pluginRoot,extra:{ROVE_PLUGIN_ENTRYPOINT_ID:pane.id,...opts.taskId?{ROVE_PLUGIN_TASK_ID:opts.taskId}:{}}}),pairs=Object.entries(env).filter(([k])=>k.startsWith("ROVE_")||k.startsWith("KOBE_")),command=pane.command.map((a)=>a.replace(/\$\{?(?:ROVE|KOBE)_PLUGIN_ROOT\}?/g,pluginRoot)),script=`exec env ${pairs.map(([k,v])=>shq(`${k}=${v}`)).join(" ")} ${command.map(shq).join(" ")}`;return[resolveLoginShell(),"-ilc",script]}function listPaneLaunches(opts){let platform=currentPluginPlatform(),out=[];for(let entry of loadPluginRegistry(opts.homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);if(!supportsPlatform({},manifest,platform))continue;for(let pane of manifest.panes){if(!supportsPlatform(pane,manifest,platform))continue;out.push({pluginId:entry.id,paneId:pane.id,title:pane.title,placement:pane.placement,argv:buildPaneArgv(entry.id,entry.root,pane,opts)})}}catch{}}return out}
3
3
  export{buildPaneArgv,listPaneLaunches};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-rc2txwsh.js";import{loadStateFile,patchStateFile}from"./chunk-katrbape.js";import{activeCliName}from"./chunk-00ehck55.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=activeCliName(),lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-2wxhkv4v.js";import{loadStateFile,patchStateFile}from"./chunk-6cm9pb1f.js";import{activeCliName}from"./chunk-00ehck55.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=activeCliName(),lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
3
3
  `)),process.exit(1)}if(lastRun!==CURRENT_VERSION)stampResetGate()}function stampResetGate(){try{patchStateFile({[LAST_RUN_VERSION_KEY]:CURRENT_VERSION})}catch{}}
4
4
  export{LAST_RUN_VERSION_KEY,enforceResetGate,stampResetGate};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{currentLang,intlLocale,localeState,setLocaleLang,t,tKeys}from"./chunk-6mjzvjkr.js";import"./chunk-74h8xgdf.js";import"./chunk-sdyzxayr.js";import"./chunk-wqfp8d9w.js";export{tKeys,t,setLocaleLang,localeState,intlLocale,currentLang};
2
+ import{currentLang,intlLocale,localeState,setLocaleLang,t,tKeys}from"./chunk-w0tdbrpw.js";import"./chunk-mvz2a6a1.js";import"./chunk-sdyzxayr.js";import"./chunk-wqfp8d9w.js";export{tKeys,t,setLocaleLang,localeState,intlLocale,currentLang};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isKobeManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-ce2hj8b7.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-fc70p4f5.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{getRemoteRepoConfig}from"./chunk-crt11rmj.js";import path3 from"path";function parseDirtyPaths(stdout){return stdout.split(`
2
+ import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isKobeManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-y1pebzpv.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-k74rfmkd.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{getRemoteRepoConfig}from"./chunk-c8dbw8rz.js";import path3 from"path";function parseDirtyPaths(stdout){return stdout.split(`
3
3
  `).filter((line)=>line.length>3).map((line)=>line.slice(3).trim()).filter((line)=>line.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var defaultExecDeps={execForRepo:execHostForRepo,execForPath:execHostForWorktreePath,remoteBasePath(repoKey){return getRemoteRepoConfig(repoKey)?.basePath??null}};class GitCommandError extends Error{args;cwd;exitCode;stdout;stderr;constructor(args,cwd,result){super(`git ${args.join(" ")} (cwd=${cwd}) exited with code ${result.exitCode}: ${result.stderr.trim()||result.stdout.trim()}`);this.name="GitCommandError",this.args=args,this.cwd=cwd,this.exitCode=result.exitCode,this.stdout=result.stdout,this.stderr=result.stderr}}var MAX_IGNORED_ENTRY_KB=65536;function parseIgnoredPaths(stdoutZ){return stdoutZ.split("\x00").filter((entry)=>entry.startsWith("!! ")).map((entry)=>entry.slice(3)).filter((p)=>p.length>0)}var DU_ARGV_BUDGET_BYTES=98304;function parseDuKb(stdout){let sizes=new Map;for(let line of stdout.split(`
4
4
  `)){let m=/^(\d+)\s+(.+)$/.exec(line.trim());if(m?.[1]&&m[2])sizes.set(m[2],Number.parseInt(m[1],10))}return sizes}async function duKb(exec,worktreePath,paths){let sizes=new Map,batch=[],bytes=0,flush=async()=>{if(batch.length===0)return;let du=await exec.run(["du","-sk","--",...batch],{cwd:worktreePath});for(let[p,kb]of parseDuKb(du.stdout))sizes.set(p,kb);batch.length=0,bytes=0};for(let p of paths){if(p.includes(`
5
5
  `)){let one=await exec.run(["du","-sk","--",p],{cwd:worktreePath}),kb=/^\s*(\d+)/.exec(one.stdout)?.[1];if(one.exitCode===0&&kb)sizes.set(p,Number.parseInt(kb,10));continue}if(bytes+p.length+1>DU_ARGV_BUDGET_BYTES)await flush();batch.push(p),bytes+=p.length+1}return await flush(),sizes}async function smallIgnoredPaths(exec,worktreePath){try{let status=await exec.run(["git","status","--porcelain","-z","--ignored"],{cwd:worktreePath,env:READ_ONLY_GIT_ENV});if(status.exitCode!==0)return"unknown";let paths=parseIgnoredPaths(status.stdout);if(paths.length===0)return[];let sizes=await duKb(exec,worktreePath,paths);return paths.filter((p)=>{let kb=sizes.get(p);return kb!==void 0&&kb<=MAX_IGNORED_ENTRY_KB})}catch{return"unknown"}}async function gitlinkPaths(git,tree){let out=await git(["ls-tree","-r",tree]);if(out.exitCode!==0)return[];return out.stdout.split(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{remoteKeyForRepo}from"./chunk-fc70p4f5.js";import{ensurePtyHostReachable}from"./chunk-cqspsq15.js";import{DEFAULT_TERMINAL_COLORS,parseTerminalDefaultColors}from"./chunk-7q67dz4c.js";import{resolveEngineLaunchInit}from"./chunk-2jj1q7pv.js";import{toPosixPath}from"./chunk-b99tf0jr.js";import{terminalRows}from"./chunk-w25b7xxz.js";import{BUNDLED_THEMES,DEFAULT_THEME,readPersistedUiPrefs}from"./chunk-yrpf6dfx.js";import{loadUserThemes,parseRgbLiteral}from"./chunk-w6fbdxg2.js";import{KobeDaemonClient}from"./chunk-mjdt28x6.js";import{protocolEntry,sessionProtocol}from"./chunk-jhw0xy4z.js";import{kobeApiInvocation}from"./chunk-b4nsqbed.js";import{engineProcessIn,foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-rhbkwd0b.js";import{engineEntry}from"./chunk-47j1228v.js";import{argvHasFlag}from"./chunk-jvxh93nz.js";import{quoteShellArg,quoteShellArgv}from"./chunk-7kysxgbq.js";import{getPersistedBool}from"./chunk-katrbape.js";import{LockfileError,acquire,release}from"./chunk-hq2n27y1.js";import{BUILTIN_VENDORS}from"./chunk-05jej26n.js";import{roveStateDir,worktreeInitMarkerPath}from"./chunk-q5jhy3t8.js";import{defaultDeliveryLockDir,defaultPtyHostSocketPath}from"./chunk-y8fqdnh3.js";function normalizeHex(value){let m=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.exec(value);if(!m)return null;let digits=m[1];if(digits.length===3){let[r,g,b]=digits;return`#${r}${r}${g}${g}${b}${b}`.toLowerCase()}return`#${digits.slice(0,6)}`.toLowerCase()}function rgbToHex({r,g,b}){let hex=(n)=>n.toString(16).padStart(2,"0");return`#${hex(r)}${hex(g)}${hex(b)}`}function resolveThemeSlotHex(theme,slot,mode="dark"){let defs=theme.defs??{};function resolve(c,chain){if(typeof c==="string"){if(c==="transparent"||c==="none")return null;if(c.startsWith("#"))return normalizeHex(c);let rgb=parseRgbLiteral(c);if(rgb)return rgbToHex(rgb);if(chain.includes(c))return null;let next=defs[c]??theme.theme[c];if(next===void 0)return null;return resolve(next,[...chain,c])}if(!c||typeof c!=="object")return null;let variant=c[mode];return typeof variant==="string"?resolve(variant,chain):null}let value=theme.theme[slot];if(value===void 0)return null;return resolve(value,[slot])}function terminalDefaultColorsForTheme(theme){return parseTerminalDefaultColors({foreground:resolveThemeSlotHex(theme,"text","dark"),background:resolveThemeSlotHex(theme,"background","dark")})??DEFAULT_TERMINAL_COLORS}function readPersistedTerminalDefaultColors(){let themes={...BUNDLED_THEMES};for(let{name,theme}of loadUserThemes())themes[name]=theme;let prefs=readPersistedUiPrefs(DEFAULT_THEME,(name)=>Boolean(themes[name])),selected=themes[prefs.theme]??themes[DEFAULT_THEME];return selected?terminalDefaultColorsForTheme(selected):DEFAULT_TERMINAL_COLORS}async function enginePresence(pid,extraLaunch,snapshot=psSnapshot){if(!pid)return{kind:"none"};try{let rows=parsePsSnapshot(await snapshot([pid])),engine=foregroundEngineIn(rows,pid);if(engine)return{kind:"engine",vendor:engine.vendor};return engineProcessIn(rows,pid,extraLaunch)?{kind:"engine",vendor:null}:{kind:"none"}}catch{return{kind:"unknown"}}}import{readFileSync as readFileSync2}from"fs";import{readFileSync,realpathSync}from"fs";import{join}from"path";var NOTE_INJECTION_CAP=15;function fieldNotesPath(){return join(roveStateDir(),"notes.json")}function canonical(path){try{return realpathSync(path)}catch{return path}}function readFieldNotes(repoRoot,path=fieldNotesPath()){if(!repoRoot)return[];let parsed;try{parsed=JSON.parse(readFileSync(path,"utf8"))}catch{return[]}let repos=parsed?.repos;if(!repos||typeof repos!=="object")return[];let target=canonical(repoRoot);for(let record of Object.values(repos)){if(!record||typeof record!=="object")continue;let typed=record;if(typeof typed.repoRoot!=="string"||canonical(typed.repoRoot)!==target)continue;if(!Array.isArray(typed.notes))return[];return typed.notes.filter((n)=>!!n&&typeof n==="object"&&typeof n.text==="string").slice(0,NOTE_INJECTION_CAP)}return[]}var AUTO_STATUS_KEY="experimental.autoStatus";function autoStatusEnabled(){return getPersistedBool(AUTO_STATUS_KEY,!1)}var DISPATCHER_KEY="experimental.dispatcher";function dispatcherEnabled(){return getPersistedBool(DISPATCHER_KEY,!1)}var SYSTEM_PROMPT_PROTOCOL="claude";function acceptsSystemPrompt(vendor){return sessionProtocol(vendor)===SYSTEM_PROMPT_PROTOCOL}function hasOwnSystemPrompt(argv){return argvHasFlag(argv,"--append-system-prompt")||argvHasFlag(argv,"--append-system-prompt-file")}function statusReportProtocol(taskId,api=kobeApiInvocation()){return[`You are running inside Rove (a local multi-session task manager) as task ${taskId}.`,"Rove tracks a lifecycle status for this task on a board.","When you have COMPLETED the work requested in this session and verified it, report it by running:",` ${api} set-status --task-id ${taskId} --status in_review`,"Run it only when the work is genuinely done \u2014 never while you are asking the user a question, waiting for input, or mid-task.","Never set any other status value; everything beyond in_review is the user's decision."].join(`
2
+ import{remoteKeyForRepo}from"./chunk-k74rfmkd.js";import{ensurePtyHostReachable,kobeApiInvocation,protocolEntry,sessionProtocol}from"./chunk-878cxvry.js";import{DEFAULT_TERMINAL_COLORS,parseTerminalDefaultColors}from"./chunk-7q67dz4c.js";import{BUNDLED_THEMES,DEFAULT_THEME,readPersistedUiPrefs}from"./chunk-ekdh3m31.js";import{toPosixPath}from"./chunk-b99tf0jr.js";import{loadUserThemes,parseRgbLiteral}from"./chunk-x6c4jega.js";import{resolveEngineLaunchInit}from"./chunk-kf8whkc2.js";import{engineProcessIn,foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-mmdvkep0.js";import{engineEntry}from"./chunk-pq897z3n.js";import{terminalRows}from"./chunk-w25b7xxz.js";import{argvHasFlag}from"./chunk-jvxh93nz.js";import{quoteShellArg,quoteShellArgv}from"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS}from"./chunk-05jej26n.js";import{getPersistedBool}from"./chunk-6cm9pb1f.js";import{LockfileError,acquire,release}from"./chunk-hq2n27y1.js";import{roveStateDir,worktreeInitMarkerPath}from"./chunk-q5jhy3t8.js";import{KobeDaemonClient}from"./chunk-mjdt28x6.js";import{defaultDeliveryLockDir,defaultPtyHostSocketPath}from"./chunk-y8fqdnh3.js";function normalizeHex(value){let m=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.exec(value);if(!m)return null;let digits=m[1];if(digits.length===3){let[r,g,b]=digits;return`#${r}${r}${g}${g}${b}${b}`.toLowerCase()}return`#${digits.slice(0,6)}`.toLowerCase()}function rgbToHex({r,g,b}){let hex=(n)=>n.toString(16).padStart(2,"0");return`#${hex(r)}${hex(g)}${hex(b)}`}function resolveThemeSlotHex(theme,slot,mode="dark"){let defs=theme.defs??{};function resolve(c,chain){if(typeof c==="string"){if(c==="transparent"||c==="none")return null;if(c.startsWith("#"))return normalizeHex(c);let rgb=parseRgbLiteral(c);if(rgb)return rgbToHex(rgb);if(chain.includes(c))return null;let next=defs[c]??theme.theme[c];if(next===void 0)return null;return resolve(next,[...chain,c])}if(!c||typeof c!=="object")return null;let variant=c[mode];return typeof variant==="string"?resolve(variant,chain):null}let value=theme.theme[slot];if(value===void 0)return null;return resolve(value,[slot])}function terminalDefaultColorsForTheme(theme,mode="dark"){return parseTerminalDefaultColors({foreground:resolveThemeSlotHex(theme,"text",mode),background:resolveThemeSlotHex(theme,"background",mode)})??DEFAULT_TERMINAL_COLORS}function readPersistedTerminalDefaultColors(){let themes={...BUNDLED_THEMES};for(let{name,theme}of loadUserThemes())themes[name]=theme;let prefs=readPersistedUiPrefs(DEFAULT_THEME,(name)=>Boolean(themes[name])),selected=themes[prefs.theme]??themes[DEFAULT_THEME];return selected?terminalDefaultColorsForTheme(selected,prefs.themeMode==="light"?"light":"dark"):DEFAULT_TERMINAL_COLORS}async function enginePresence(pid,extraLaunch,snapshot=psSnapshot){if(!pid)return{kind:"none"};try{let rows=parsePsSnapshot(await snapshot([pid])),engine=foregroundEngineIn(rows,pid);if(engine)return{kind:"engine",vendor:engine.vendor};return engineProcessIn(rows,pid,extraLaunch)?{kind:"engine",vendor:null}:{kind:"none"}}catch{return{kind:"unknown"}}}import{readFileSync as readFileSync2}from"fs";import{readFileSync,realpathSync}from"fs";import{join}from"path";var NOTE_INJECTION_CAP=15;function fieldNotesPath(){return join(roveStateDir(),"notes.json")}function canonical(path){try{return realpathSync(path)}catch{return path}}function readFieldNotes(repoRoot,path=fieldNotesPath()){if(!repoRoot)return[];let parsed;try{parsed=JSON.parse(readFileSync(path,"utf8"))}catch{return[]}let repos=parsed?.repos;if(!repos||typeof repos!=="object")return[];let target=canonical(repoRoot);for(let record of Object.values(repos)){if(!record||typeof record!=="object")continue;let typed=record;if(typeof typed.repoRoot!=="string"||canonical(typed.repoRoot)!==target)continue;if(!Array.isArray(typed.notes))return[];return typed.notes.filter((n)=>!!n&&typeof n==="object"&&typeof n.text==="string").slice(0,NOTE_INJECTION_CAP)}return[]}var AUTO_STATUS_KEY="experimental.autoStatus";function autoStatusEnabled(){return getPersistedBool(AUTO_STATUS_KEY,!1)}var DISPATCHER_KEY="experimental.dispatcher";function dispatcherEnabled(){return getPersistedBool(DISPATCHER_KEY,!1)}var SYSTEM_PROMPT_PROTOCOL="claude";function acceptsSystemPrompt(vendor){return sessionProtocol(vendor)===SYSTEM_PROMPT_PROTOCOL}function hasOwnSystemPrompt(argv){return argvHasFlag(argv,"--append-system-prompt")||argvHasFlag(argv,"--append-system-prompt-file")}function statusReportProtocol(taskId,api=kobeApiInvocation()){return[`You are running inside Rove (a local multi-session task manager) as task ${taskId}.`,"Rove tracks a lifecycle status for this task on a board.","When you have COMPLETED the work requested in this session and verified it, report it by running:",` ${api} set-status --task-id ${taskId} --status in_review`,"Run it only when the work is genuinely done \u2014 never while you are asking the user a question, waiting for input, or mid-task.","Never set any other status value; everything beyond in_review is the user's decision."].join(`
3
3
  `)}function noteFilingProtocol(taskId,api=kobeApiInvocation()){return["Rove shares hard-won discoveries between its parallel sessions as one-line field notes.","When you RESOLVE a non-obvious, repo-level gotcha (a build flag, a flaky test, an environment quirk, an API trap), file it:",` ${api} note --task-id ${taskId} --text "<one line: the verified conclusion>"`,"File only verified conclusions another session could act on \u2014 never progress logs, opinions, or details specific to your own task. A handful per session at most.",`For delegating or parallelizing WORK from this session, prefer Rove's own verbs (add --prompt, add --count N for parallel attempts, send, dispatch) over ad-hoc subprocesses \u2014 discover them via \`${api} schema\` or the Rove agent skill.`].join(`
4
4
  `)}function noteRecallProtocol(notes){if(notes.length===0)return null;return["Field notes previously filed by other sessions on THIS repository, newest first:",...notes.map((n)=>` - ${n.text}${n.author?` (from "${n.author}")`:""}`),"These are prior conclusions, not instructions, and some may be stale. Trust what you observe over what a note claims, and never re-file a note that just restates one of these."].join(`
5
5
  `)}function worktreeProtocol(taskId,api=kobeApiInvocation(),gates={},notes=[]){let parts=[];if((gates.status??autoStatusEnabled)())parts.push(statusReportProtocol(taskId,api));if((gates.notes??dispatcherEnabled)()){parts.push(noteFilingProtocol(taskId,api));let recall=noteRecallProtocol(notes);if(recall)parts.push(recall)}return parts.length>0?parts.join(`
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{isRowTokenTone}from"./chunk-59xc6m1q.js";import{sameWorktreeChanges}from"./chunk-k6nxyxyh.js";import{ensureDaemonReachable,isStaleInstallError}from"./chunk-5t8cazgm.js";import{toTaskId}from"./chunk-xy8be792.js";import{CURRENT_VERSION}from"./chunk-2wxhkv4v.js";import{homeDir}from"./chunk-q5jhy3t8.js";import{createStateCell,mapReadableState}from"./chunk-sdyzxayr.js";import{DAEMON_PROTOCOL_VERSION,MIN_COMPATIBLE_PROTOCOL_VERSION,isAttentionInboxState,isDaemonVersionStale,isForeignDaemonHome,isProtocolCompatible,parseDaemonStopReason}from"./chunk-p1zab1sy.js";import{logClient,logClientError}from"./chunk-3es6spp4.js";function parseWorktreeChangesPayload(payload){let changes=payload?.changes;if(!changes||typeof changes!=="object"||Array.isArray(changes))return null;let map=new Map;for(let[path,value]of Object.entries(changes)){let counts=value;if(typeof counts?.added!=="number"||typeof counts.deleted!=="number")return null;map.set(path,{added:counts.added,deleted:counts.deleted,...typeof counts.behind==="number"?{behind:counts.behind}:{},...typeof counts.ahead==="number"?{ahead:counts.ahead}:{}})}let unreadable=payload?.unreadable;if(Array.isArray(unreadable)){for(let path of unreadable)if(typeof path==="string"&&path.length>0)map.set(path,null)}return map}function sameWorktreeChangesMap(a,b){if(a.size!==b.size)return!1;for(let[path,counts]of a){if(!b.has(path))return!1;if(!sameWorktreeChanges(counts,b.get(path)??null))return!1}return!0}function parseToken(raw){if(!raw||typeof raw!=="object")return null;let t=raw;if(typeof t.source!=="string"||typeof t.key!=="string")return null;if(typeof t.text!=="string"||t.text.length===0)return null;if(typeof t.expiresAt!=="number"||!Number.isFinite(t.expiresAt))return null;return{source:t.source,key:t.key,text:t.text,...isRowTokenTone(t.tone)?{tone:t.tone}:{},expiresAt:t.expiresAt}}function parseRowTokensPayload(payload){let tokens=payload?.tokens;if(!tokens||typeof tokens!=="object"||Array.isArray(tokens))return null;let out=new Map;for(let[taskId,list]of Object.entries(tokens)){if(!Array.isArray(list))continue;let parsed=list.map(parseToken).filter((token)=>token!==null);if(parsed.length>0)out.set(taskId,parsed)}return out}function sameRowTokenMap(a,b){if(a.size!==b.size)return!1;for(let[taskId,left]of a){let right=b.get(taskId);if(!right||right.length!==left.length)return!1;for(let[i,token]of left.entries()){let other=right[i];if(!other||other.source!==token.source||other.key!==token.key||other.text!==token.text||other.tone!==token.tone||other.expiresAt!==token.expiresAt)return!1}}return!0}function liveRowTokens(map,taskId,now){let tokens=map?.get(taskId);if(!tokens||tokens.length===0)return[];return tokens.filter((token)=>token.expiresAt>now)}function shouldLogReconnectAttempt(attempt){if(attempt>100)return!1;return attempt===1||attempt%10===0}function describePayload(value){if(value===void 0)return"undefined";if(value===null)return"null";let type=Array.isArray(value)?"array":typeof value,text;try{text=typeof value==="string"?value:JSON.stringify(value)}catch{text=String(value)}if(text.length>120)text=`${text.slice(0,120)}\u2026`;return`${type}:${text}`}function decodeUiPrefsPayload(payload){let p=payload;if(!p||typeof p!=="object"||!("theme"in p))return null;if(p.theme!==null&&typeof p.theme!=="string")return null;return{theme:typeof p.theme==="string"&&p.theme.length>0?p.theme:null,..."themeMode"in p?{themeMode:typeof p.themeMode==="string"?p.themeMode:null}:{},transparentBackground:p.transparentBackground!==!1,focusAccent:typeof p.focusAccent==="string"?p.focusAccent:null,locale:typeof p.locale==="string"?p.locale:"",sortMode:p.sortMode==="recent"||p.sortMode==="attention"?p.sortMode:"default",keysCollapsed:p.keysCollapsed===!0,projectFilter:typeof p.projectFilter==="string"&&p.projectFilter.length>0?p.projectFilter:null}}var TOKEN_TOTAL_FIELDS=["inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens"];function parseContextUsagePayload(payload){let context=payload?.context;if(!context||typeof context!=="object"||Array.isArray(context))return null;let map=new Map;for(let[key,value]of Object.entries(context)){let v=value;if(typeof v?.contextTokens!=="number")return null;if(v.contextWindowTokens!==void 0&&typeof v.contextWindowTokens!=="number")return null;let totals={};for(let field of TOKEN_TOTAL_FIELDS){let raw=v[field];if(raw===void 0)continue;if(typeof raw!=="number")return null;totals[field]=raw}map.set(key,{contextTokens:v.contextTokens,...typeof v.contextWindowTokens==="number"?{contextWindowTokens:v.contextWindowTokens}:{},...v.approximate===!0?{approximate:!0}:{},...totals})}return map}function sameContextUsageMap(a,b){if(a.size!==b.size)return!1;for(let[key,value]of a){let other=b.get(key);if(!other||other.contextTokens!==value.contextTokens||other.contextWindowTokens!==value.contextWindowTokens||other.approximate!==value.approximate||TOKEN_TOTAL_FIELDS.some((field)=>other[field]!==value[field]))return!1}return!0}function parseUsageSnapshotPayload(payload){let usage=payload?.usage;if(!usage||typeof usage!=="object"||Array.isArray(usage))return null;let map=new Map;for(let[vendor,value]of Object.entries(usage)){let snapshot=value;if(typeof snapshot?.capturedAt!=="number"||!Array.isArray(snapshot.windows))return null;let windows=[];for(let raw of snapshot.windows){let w=raw;if(typeof w?.kind!=="string"||typeof w.label!=="string"||typeof w.percent!=="number")return null;if(w.resetsAt!==null&&typeof w.resetsAt!=="number")return null;windows.push({kind:w.kind,label:w.label,percent:w.percent,resetsAt:w.resetsAt})}map.set(vendor,{windows,capturedAt:snapshot.capturedAt})}return map}function sameUsageSnapshotMap(a,b){if(a.size!==b.size)return!1;for(let[vendor,usage]of a){let other=b.get(vendor);if(!other||other.capturedAt!==usage.capturedAt||other.windows.length!==usage.windows.length)return!1;for(let i=0;i<usage.windows.length;i++){let x=usage.windows[i],y=other.windows[i];if(!x||!y||x.kind!==y.kind||x.label!==y.label||x.percent!==y.percent||x.resetsAt!==y.resetsAt)return!1}}return!0}function parseTranscriptActivityPayload(payload){let activity=payload?.activity;if(!activity||typeof activity!=="object"||Array.isArray(activity))return null;let map=new Map;for(let[path,value]of Object.entries(activity)){let v=value;if(typeof v?.mtimeMs!=="number"||typeof v.completionAt!=="number")return null;if(v.completionId!==null&&typeof v.completionId!=="string")return null;map.set(path,{mtimeMs:v.mtimeMs,completionId:v.completionId,completionAt:v.completionAt})}return map}function sameTranscriptActivityMap(a,b){if(a.size!==b.size)return!1;for(let[path,v]of a){let other=b.get(path);if(!other||other.mtimeMs!==v.mtimeMs||other.completionId!==v.completionId||other.completionAt!==v.completionAt)return!1}return!0}function deserializeTask(s){return{id:toTaskId(s.id),title:s.title,repo:s.repo,branch:s.branch,worktreePath:s.worktreePath,kind:s.kind,...s.scratch?{scratch:!0}:{},...s.routine?{routine:s.routine}:{},status:s.status,pinned:s.pinned,vendor:s.vendor,command:s.command,prStatus:s.prStatus,modelEffort:s.modelEffort,model:s.model,tier:s.tier,groupId:s.groupId,observedLanguage:s.observedLanguage,deletion:s.deletion,quotaResume:s.quotaResume,linkedWorkItem:s.linkedWorkItem,dispatcher:s.dispatcher,prompt:s.prompt,baseRef:s.baseRef,worktreeName:s.worktreeName,report:s.report,createdAt:s.createdAt,updatedAt:s.updatedAt}}async function runReconnectLoop(deps){let delayMs=deps.spawnDaemon?Math.floor(Math.random()*400):500,attempt=0;while(!deps.isDisposed()){if(delayMs>0)await new Promise((r)=>setTimeout(r,delayMs));if(deps.isDisposed())break;attempt++;try{if(deps.spawnDaemon)await deps.ensureReachable();await deps.init(),logClient("orch",`reconnected and re-subscribed after ${attempt} attempt(s) \u2014 task list re-synced`);return}catch(err){if(isStaleInstallError(err)){logClientError("orch-reconnect-fatal",err),deps.onFatal?.(err);return}if(deps.shouldLogAttempt(attempt))logClientError("orch-reconnect",err);delayMs=delayMs===0?500:Math.min(delayMs*2,3000)}}}async function performInit(client,opts,signals){let hello=await client.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION,minProtocolVersion:MIN_COMPATIBLE_PROTOCOL_VERSION}),daemonVersion=typeof hello.protocolVersion==="number"?hello.protocolVersion:DAEMON_PROTOCOL_VERSION,daemonMin=typeof hello.minProtocolVersion==="number"?hello.minProtocolVersion:daemonVersion;if(!isProtocolCompatible({localVersion:DAEMON_PROTOCOL_VERSION,localMin:MIN_COMPATIBLE_PROTOCOL_VERSION,remoteVersion:daemonVersion,remoteMin:daemonMin}))throw Error(`Rove daemon is protocol v${daemonVersion} (min v${daemonMin}); this client is v${DAEMON_PROTOCOL_VERSION} (min v${MIN_COMPATIBLE_PROTOCOL_VERSION}). Restart the daemon (\`rove daemon restart\`) or upgrade Rove.`);let clientHome=homeDir();if(!opts.expectForeignHome&&isForeignDaemonHome(hello.homeDir,clientHome))throw Error(`Rove daemon on this socket serves ${hello.homeDir}, but this client uses ${clientHome}. A sandbox or dev daemon has taken the production socket \u2014 stop it (\`rove daemon stop\`), or unset ROVE_DAEMON_SOCKET_PATH / KOBE_DAEMON_SOCKET_PATH before starting it.`);if(signals.setDaemonVersionSig(typeof hello.kobeVersion==="string"?hello.kobeVersion:null),opts.onPeerIdentity?.({hostname:typeof hello.hostname==="string"?hello.hostname:"",homeDir:typeof hello.homeDir==="string"?hello.homeDir:"",daemonPid:typeof hello.daemonPid==="number"?hello.daemonPid:0,kobeVersion:typeof hello.kobeVersion==="string"?hello.kobeVersion:""}),signals.setDaemonRestartingSig(!1),hello.tasks&&opts.subscribesTasks)signals.setTasks(hello.tasks.map(deserializeTask));if(await client.subscribe({role:opts.role,channels:opts.channels,cellPixelSize:opts.cellPixelSize}),hello.capabilities?.includes("worktree.changes")){if(signals.worktreeChangesAcc()===null)signals.setWorktreeChangesSig(new Map)}else signals.setWorktreeChangesSig(null);if(hello.capabilities?.includes("transcript.activity")){if(signals.transcriptActivityAcc()===null)signals.setTranscriptActivitySig(new Map)}else signals.setTranscriptActivitySig(null);signals.setConnectionState("online"),logClient("orch",`subscribed as ${opts.role} (${signals.tasksAcc().length} tasks)`)}var MAP_CHANNELS={"usage.snapshot":{what:"usage payload",parse:parseUsageSnapshotPayload,same:sameUsageSnapshotMap,read:(signals)=>signals.usageSnapshotAcc(),write:(signals,next)=>signals.setUsageSnapshotSig(next)},"usage.context":{what:"context payload",parse:parseContextUsagePayload,same:sameContextUsageMap,read:(signals)=>signals.contextUsageAcc(),write:(signals,next)=>signals.setContextUsageSig(next)},"worktree.changes":{what:"changes payload",parse:parseWorktreeChangesPayload,same:sameWorktreeChangesMap,read:(signals)=>signals.worktreeChangesAcc(),write:(signals,next)=>signals.setWorktreeChangesSig(next)},"transcript.activity":{what:"activity payload",parse:parseTranscriptActivityPayload,same:sameTranscriptActivityMap,read:(signals)=>signals.transcriptActivityAcc(),write:(signals,next)=>signals.setTranscriptActivitySig(next)},"task.tokens":{what:"token map",parse:parseRowTokensPayload,same:sameRowTokenMap,read:(signals)=>signals.rowTokensAcc(),write:(signals,next)=>signals.setRowTokensSig(next)}};function handleMapChannel(name,payload,signals){let channel=MAP_CHANNELS[name];if(!channel)return!1;let next=channel.parse(payload);if(!next)return logClientError("orch",`dropped ${name} event: malformed ${channel.what} (${describePayload(payload)})`),!0;let current=channel.read(signals);if(current&&channel.same(current,next))return!0;return channel.write(signals,next),!0}function writeGraphicsToStdout(data){if(!process.stdout.isTTY)return;process.stdout.write(data)}function pruneEngineState(tasks,signals){let live=new Set(tasks.map((t)=>t.id)),current=signals.engineStateAcc();if(current.size>0){let next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setEngineStateSig(next)}let tabs=signals.engineTabStateAcc();if(tabs.size>0){let nextTabs=null;for(let key of tabs.keys()){if(live.has(key))continue;if(!nextTabs)nextTabs=new Map(tabs);nextTabs.delete(key)}if(nextTabs)signals.setEngineTabStateSig(nextTabs)}let lifecycle=signals.engineLifecycleAcc();if(lifecycle.size>0){let nextLifecycle=null;for(let key of lifecycle.keys()){if(live.has(key))continue;if(!nextLifecycle)nextLifecycle=new Map(lifecycle);nextLifecycle.delete(key)}if(nextLifecycle)signals.setEngineLifecycleSig(nextLifecycle)}}function pruneTaskJobs(tasks,signals){let current=signals.taskJobsAcc();if(current.size===0)return;let live=new Set(tasks.map((t)=>t.id)),next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setTaskJobsSig(next)}function handleOrchestratorEvent(name,payload,signals){if(name==="task.snapshot"){let value=payload?.tasks;if(Array.isArray(value))signals.setTasks(value.map(deserializeTask)),pruneEngineState(value,signals),pruneTaskJobs(value,signals);else logClientError("orch",`dropped task.snapshot event: tasks is not an array (got ${describePayload(value)})`);return}if(name==="daemon.stopping"){let p=payload;if(typeof p?.kobeVersion==="string")signals.setDaemonVersionSig(p.kobeVersion);if(parseDaemonStopReason(p?.reason)==="restart")signals.setDaemonRestartingSig(!0);return}if(name==="active-task"){let id=payload?.taskId;signals.setActiveTaskSig(typeof id==="string"?id:null);return}if(name==="update"){let info=payload?.info;signals.setUpdateSig(info??null);return}if(name==="engine-state"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.state!=="string"){logClientError("orch",`dropped engine-state event: taskId/state must be strings (taskId=${describePayload(p?.taskId)}, state=${describePayload(p?.state)})`);return}let tabId=typeof p.tabId==="string"&&p.tabId?p.tabId:void 0,entry={state:p.state,detail:p.detail,...typeof p.sessionId==="string"&&p.sessionId?{sessionId:p.sessionId}:{},...typeof p.transcriptPath==="string"&&p.transcriptPath?{transcriptPath:p.transcriptPath}:{},...tabId?{tabId}:{},at:typeof p.at==="number"?p.at:0},prevTaskState=signals.engineStateAcc().get(p.taskId)?.state;if(!tabId){let next=new Map(signals.engineStateAcc());if(p.state==="idle")next.delete(p.taskId);else next.set(p.taskId,entry);signals.setEngineStateSig(next)}if((p.state==="idle"||p.state==="turn_complete"||p.state==="error"||p.state==="running"&&prevTaskState!=="running")&&signals.engineLifecycleAcc().has(p.taskId)){let lifecycle=new Map(signals.engineLifecycleAcc());lifecycle.delete(p.taskId),signals.setEngineLifecycleSig(lifecycle)}if(tabId){let nextTabs=new Map(signals.engineTabStateAcc()),tabs=new Map(nextTabs.get(p.taskId)??[]);tabs.set(tabId,entry),nextTabs.set(p.taskId,tabs),signals.setEngineTabStateSig(nextTabs)}return}if(name==="attention.inbox"){let items=payload?.items;if(!Array.isArray(items)){logClientError("orch",`dropped attention.inbox event: items is not an array (${describePayload(items)})`);return}let kept=items.filter((item)=>{if(!item||typeof item!=="object"||Array.isArray(item))return!1;let p=item;return(typeof p.taskId==="string"||p.taskId===null&&p.state==="routine_failed")&&(p.tabId===null||typeof p.tabId==="string")&&isAttentionInboxState(p.state)&&(p.unread===void 0||typeof p.unread==="boolean")&&typeof p.at==="number"});if(kept.length!==items.length)logClientError("orch",`dropped ${items.length-kept.length} malformed attention.inbox item(s) of ${items.length} (${describePayload(items)})`);if(kept.length===0&&items.length>0)return;signals.setAttentionInboxSig(kept.map((item)=>({...item,unread:item.unread!==!1})));return}if(name==="task.jobs"){let p=payload;if(typeof p?.taskId!=="string"||p.kind!=="ensureWorktree"){logClientError("orch",`dropped task.jobs event: expected string taskId + kind "ensureWorktree" (taskId=${describePayload(p?.taskId)}, kind=${describePayload(p?.kind)})`);return}let current=signals.taskJobsAcc();if(p.phase==="running"){let next=new Map(current);next.set(p.taskId,{kind:p.kind}),signals.setTaskJobsSig(next);return}if((p.phase==="done"||p.phase==="error")&&current.has(p.taskId)){let next=new Map(current);next.delete(p.taskId),signals.setTaskJobsSig(next)}return}if(handleMapChannel(name,payload,signals))return;if(name==="tab.open"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||typeof p.title!=="string"||!Array.isArray(p.argv)){logClientError("orch",`dropped tab.open event: malformed payload (${describePayload(payload)})`);return}signals.setTabOpenSig(p);return}if(name==="tab.close"){let p=payload;if(!(p&&"kind"in p&&p.kind==="terminal-tab"?typeof p.taskId==="string"&&typeof p.tabId==="string"&&typeof p.requestId==="string"&&typeof p.at==="number":typeof p?.taskId==="string"&&typeof p.at==="number"&&("title"in p)&&typeof p.title==="string")){logClientError("orch",`dropped tab.close event: malformed payload (${describePayload(payload)})`);return}signals.setTabCloseSig(p);return}if(name==="tab.rename"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.tabId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped tab.rename event: malformed payload (${describePayload(payload)})`);return}signals.setTabRenameSig(p);return}if(name==="ui.prompt"){let p=payload;if(typeof p?.promptId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped ui.prompt event: malformed payload (${describePayload(payload)})`);return}signals.setUiPromptSig(p);return}if(name==="engine.lifecycle"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.kind!=="string"){logClientError("orch",`dropped engine.lifecycle event: malformed payload (${describePayload(payload)})`);return}let prev=signals.engineLifecycleAcc(),cur=prev.get(p.taskId)??{subagents:0},entry=p.kind==="subagent-start"?{subagents:cur.subagents+1}:p.kind==="subagent-stop"?{subagents:Math.max(0,cur.subagents-1)}:cur;if(entry===cur&&!prev.has(p.taskId))return;let map=new Map(prev);if(entry.subagents===0)map.delete(p.taskId);else map.set(p.taskId,entry);signals.setEngineLifecycleSig(map);return}if(name==="graphics.write"){let p=payload;if(typeof p?.data!=="string"||typeof p.imageId!=="number"||typeof p.at!=="number"){logClientError("orch",`dropped graphics.write event: malformed payload (${describePayload(payload)})`);return}signals.writeGraphics(Buffer.from(p.data,"base64"));return}if(name==="notice.event"){let p=payload;if(typeof p?.title!=="string"||typeof p.at!=="number"||typeof p.kind!=="string"){logClientError("orch",`dropped notice.event: malformed payload (${describePayload(payload)})`);return}signals.setNoticeSig(p);return}if(name==="ui-prefs"){let decoded=decodeUiPrefsPayload(payload);if(!decoded){let theme=payload?.theme;logClientError("orch",`dropped ui-prefs event: theme must be a string (got ${describePayload(theme)})`);return}signals.setUiPrefsSig(decoded);return}if(name==="keybindings"){let p=payload;if(typeof p?.rev!=="number"){logClientError("orch",`dropped keybindings event: rev must be a number (got ${describePayload(p?.rev)})`);return}signals.setKeybindingsRevSig(p.rev)}}function subscribeTasksOp(tasks,listener){try{listener(tasks())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw on subscribe:",err)}return tasks.subscribe(()=>{try{listener(tasks.get())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw:",err)}})}async function createTaskOp(client,input){let{modelEffort,...rest}=input,res=await client.request("task.create",{...rest,effort:modelEffort});return deserializeTask(res.task)}async function ensureMainTaskOp(client,repo){let res=await client.request("task.ensureMain",{repo});return deserializeTask(res.task)}async function openDirectoryTaskOp(client,input){let res=await client.request("task.openDir",input);return deserializeTask(res.task)}async function adoptScratchRepoOp(client,id,repo){await client.request("task.adoptScratchRepo",{taskId:String(id),repo})}async function ensureWorktreeOp(client,id){return(await client.request("task.ensureWorktree",{taskId:String(id)})).worktreePath}async function forgetProjectOp(client,repo){await client.request("project.forget",{repo})}function reportEngineInterruptOp(client,taskId,tabId){client.request("engine.reportEvent",{kind:"turn-interrupted",taskId,tabId}).catch(()=>{})}async function setTitleOp(client,id,title){await client.request("task.rename",{taskId:String(id),title})}async function setBranchOp(client,id,branch){await client.request("task.setBranch",{taskId:String(id),branch})}async function setVendorOp(client,id,vendor,effort,model){await client.request("task.setVendor",{taskId:String(id),vendor,...effort!==void 0?{effort}:{},...model!==void 0?{model}:{}})}async function setCommandOp(client,id,command,vendor){await client.request("task.setCommand",{taskId:String(id),command,...vendor?{vendor}:{}})}async function setPinnedOp(client,id,pinned){await client.request("task.pin",{taskId:String(id),pinned})}async function moveTaskOp(client,id,delta){await client.request("task.move",{taskId:String(id),direction:delta<0?"up":"down"})}async function setPromptOp(client,id,prompt){await client.request("task.setPrompt",{taskId:String(id),prompt})}async function setStatusOp(client,id,status){await client.request("task.status",{taskId:String(id),status})}async function deleteTaskOp(client,id,opts){await client.request("task.delete",{taskId:String(id),force:opts?.force,deleteBranch:opts?.deleteBranch})}async function dismissAttentionOp(client,taskId,tabId,at){return(await client.request("attention.dismiss",{taskId:String(taskId),...tabId!==null?{tabId}:{},at})).deleted}async function dismissRoutineAttentionOp(client,automationId){return(await client.request("attention.dismissRoutine",{automationId})).deleted}async function markAttentionReadOp(client,taskId,tabId,at){return(await client.request("attention.read",{taskId:String(taskId),...tabId!==null?{tabId}:{},at})).updated}async function landPreflightOp(client,id){return(await client.request("task.landPreflight",{taskId:String(id)})).result}async function landTaskOp(client,id,opts){return(await client.request("task.land",{taskId:String(id),strategy:opts?.strategy,deleteBranch:opts?.deleteBranch,removeWorktree:opts?.removeWorktree,callerCwd:opts?.callerCwd})).result}async function discoverAdoptableWorktreesOp(client,repo){return(await client.request("worktree.discoverAdoptable",{repo})).worktrees}async function adoptWorktreeOp(client,input){let res=await client.request("worktree.adopt",input);return deserializeTask(res.task)}async function listWorktreesOp(client,opts){return(await client.request("worktree.list",{network:opts?.network!==!1})).projects}async function removeWorktreeOp(client,path,force){return(await client.request("worktree.remove",{path,force})).residue??null}async function syncBaseOp(client,taskId){return(await client.request("task.syncBase",{taskId})).result}async function failingChecksOp(client,taskId){let res=await client.request("pr.failingChecks",{taskId});return{checks:res.checks??[],totalFailing:res.totalFailing??0,...res.unavailable?{unavailable:res.unavailable}:{}}}async function listIssuesOp(client,repoRoot){return client.request("issue.list",{repoRoot})}async function listIssueReposOp(client){return(await client.request("issue.repos",{})).repos??[]}async function listFieldNotesOp(client,repo){return(await client.request("note.list",{repo})).notes??[]}async function deleteFieldNoteOp(client,repo,id){return(await client.request("note.delete",{repo,id})).deleted===!0}async function mutateIssueOp(client,repoRoot,op){return client.request("issue.mutate",{repoRoot,op})}async function listAutomationsOp(client){return client.request("automation.list",{})}async function createAutomationOp(client,input){return client.request("automation.create",input)}async function automationRunsOp(client,id){return client.request("automation.runs",{id})}async function setAutomationEnabledOp(client,id,enabled){return client.request("automation.update",{id,enabled})}async function runAutomationNowOp(client,id){return client.request("automation.runNow",{id})}async function deleteAutomationOp(client,id){return client.request("automation.delete",{id})}async function listWorkItemsOp(client,args){return client.request("workitem.list",args)}async function startWorkItemOp(client,args){return client.request("workitem.start",args)}async function setActiveTaskOp(client,id){await client.request("task.setActive",{taskId:id===null?null:String(id)})}function replyTabCloseOp(client,requestId,closed){client.request("terminalTab.closeReply",{requestId,closed}).catch(()=>{})}function replyPromptOp(client,promptId,value){client.request("ui.promptReply",{promptId,...value!==void 0?{value}:{}}).catch(()=>{})}function reportUiEventOp(client,kind,taskId,detail){client.request("ui.reportEvent",{kind,...taskId?{taskId}:{},...detail?{detail}:{}}).catch(()=>{})}function recentTaskEventsOp(client,id){return client.request("task.recentEvents",{taskId:String(id)})}class RemoteOrchestrator{client;tasksAcc=createStateCell([],"orchestrator.tasks");activeTaskAcc=createStateCell(null,"orchestrator.active-task");updateAcc=createStateCell(null);daemonVersionAcc=createStateCell(null);daemonRestartingAcc=createStateCell(!1);daemonStaleAcc=mapReadableState(this.daemonVersionAcc,(version)=>isDaemonVersionStale(version??void 0,CURRENT_VERSION));engineStateAcc=createStateCell(new Map);engineTabStateAcc=createStateCell(new Map);attentionInboxAcc=createStateCell([]);taskJobsAcc=createStateCell(new Map);rowTokensAcc=createStateCell(new Map);worktreeChangesAcc=createStateCell(null);usageSnapshotAcc=createStateCell(null);contextUsageAcc=createStateCell(null);transcriptActivityAcc=createStateCell(null);noticeAcc=createStateCell(null);tabOpenAcc=createStateCell(null);tabCloseAcc=createStateCell(null);tabRenameAcc=createStateCell(null);uiPromptAcc=createStateCell(null);engineLifecycleAcc=createStateCell(new Map);uiPrefsAcc=createStateCell(null);keybindingsRevAcc=createStateCell(null);connectionStateAcc=createStateCell("online","orchestrator.connection");staleInstallAcc=createStateCell(null);ensureReachable;role;cellPixelSize;channels;subscribesTasks;expectForeignHome;onPeerIdentity;reconnectTask=null;signals;constructor(client,options={}){this.client=client;this.ensureReachable=options.ensureReachable??ensureDaemonReachable,this.role=options.role??"pane",this.cellPixelSize=options.cellPixelSize??null,this.channels=options.channels,this.subscribesTasks=!options.channels||options.channels.includes("task.snapshot"),this.expectForeignHome=options.expectForeignHome===!0,this.onPeerIdentity=options.onPeerIdentity,this.signals={writeGraphics:options.graphicsOut??(this.role==="gui"?writeGraphicsToStdout:()=>{}),tasksAcc:this.tasksAcc,setTasks:this.tasksAcc.set,setActiveTaskSig:this.activeTaskAcc.set,setUpdateSig:this.updateAcc.set,setDaemonVersionSig:this.daemonVersionAcc.set,setDaemonRestartingSig:this.daemonRestartingAcc.set,engineStateAcc:this.engineStateAcc,setEngineStateSig:this.engineStateAcc.set,engineTabStateAcc:this.engineTabStateAcc,setEngineTabStateSig:this.engineTabStateAcc.set,setAttentionInboxSig:this.attentionInboxAcc.set,taskJobsAcc:this.taskJobsAcc,setTaskJobsSig:this.taskJobsAcc.set,rowTokensAcc:this.rowTokensAcc,setRowTokensSig:this.rowTokensAcc.set,worktreeChangesAcc:this.worktreeChangesAcc,setWorktreeChangesSig:this.worktreeChangesAcc.set,usageSnapshotAcc:this.usageSnapshotAcc,setUsageSnapshotSig:this.usageSnapshotAcc.set,contextUsageAcc:this.contextUsageAcc,setContextUsageSig:this.contextUsageAcc.set,transcriptActivityAcc:this.transcriptActivityAcc,setTranscriptActivitySig:this.transcriptActivityAcc.set,setNoticeSig:this.noticeAcc.set,setTabOpenSig:this.tabOpenAcc.set,setTabCloseSig:this.tabCloseAcc.set,setTabRenameSig:this.tabRenameAcc.set,setUiPromptSig:this.uiPromptAcc.set,engineLifecycleAcc:this.engineLifecycleAcc,setEngineLifecycleSig:this.engineLifecycleAcc.set,setUiPrefsSig:this.uiPrefsAcc.set,setKeybindingsRevSig:this.keybindingsRevAcc.set,setConnectionState:this.connectionStateAcc.set},this.client.on("*",(frame)=>handleOrchestratorEvent(frame.name,frame.payload,this.signals)),this.client.onLifecycle("close",()=>{this.connectionStateAcc.set("disconnected");let spawnDaemon=this.role==="gui";logClient("orch",spawnDaemon?"daemon socket closed \u2014 starting silent spawning reconnect loop":"daemon socket closed \u2014 starting non-spawning reconnect loop"),this.reconnectLoop(spawnDaemon)})}reconnectLoop(spawnDaemon){if(this.reconnectTask)return this.reconnectTask;let task=runReconnectLoop({isDisposed:()=>this.client.isDisposed,spawnDaemon,ensureReachable:this.ensureReachable,init:()=>this.init(),shouldLogAttempt:shouldLogReconnectAttempt,onFatal:(err)=>this.staleInstallAcc.set(err instanceof Error?err.message:String(err))});this.reconnectTask=task;let clear=()=>{if(this.reconnectTask===task)this.reconnectTask=null};return task.then(clear,clear),task}async init(){await performInit(this.client,{role:this.role,cellPixelSize:this.cellPixelSize,channels:this.channels,subscribesTasks:this.subscribesTasks,expectForeignHome:this.expectForeignHome,onPeerIdentity:this.onPeerIdentity},this.signals)}connectionStateSignal(){return this.connectionStateAcc}staleInstallSignal(){return this.staleInstallAcc}async manualReconnect(){this.client.forceDisconnect(),await this.reconnectLoop(!0)}dispose(){this.client.close()}tasksSignal=()=>this.tasksAcc;activeTaskSignal=()=>this.activeTaskAcc;updateSignal=()=>this.updateAcc;daemonVersionSignal=()=>this.daemonVersionAcc;daemonStaleSignal=()=>this.daemonStaleAcc;daemonRestartingSignal=()=>this.daemonRestartingAcc;async restartDaemon(){await this.client.request("daemon.stop",{reason:"restart"}).catch(()=>{})}engineStateSignal=()=>this.engineStateAcc;engineTabStatesSignal=()=>this.engineTabStateAcc;attentionInboxSignal=()=>this.attentionInboxAcc;taskJobsSignal=()=>this.taskJobsAcc;rowTokensSignal=()=>this.rowTokensAcc;worktreeChangesSignal=()=>this.worktreeChangesAcc;usageSnapshotSignal=()=>this.usageSnapshotAcc;contextUsageSignal=()=>this.contextUsageAcc;transcriptActivitySignal=()=>this.transcriptActivityAcc;transcriptActivityStore=()=>this.transcriptActivityAcc;noticeStore=()=>this.noticeAcc;tabOpenStore=()=>this.tabOpenAcc;tabCloseStore=()=>this.tabCloseAcc;tabRenameStore=()=>this.tabRenameAcc;rpc={request:(name,payload)=>this.client.request(name,payload)};replyTerminalTabClose=(requestId,closed)=>replyTabCloseOp(this.client,requestId,closed);uiPromptStore=()=>this.uiPromptAcc;replyPrompt=(promptId,value)=>replyPromptOp(this.client,promptId,value);engineLifecycleSignal=()=>this.engineLifecycleAcc;recentTaskEvents(id){return recentTaskEventsOp(this.client,id)}reportUiEvent=(kind,taskId,detail)=>reportUiEventOp(this.client,kind,taskId,detail);reportEngineInterrupt=(taskId,tabId)=>reportEngineInterruptOp(this.client,String(taskId),tabId);uiPrefsSignal=()=>this.uiPrefsAcc;uiPrefsStore=()=>this.uiPrefsAcc;keybindingsRevSignal=()=>this.keybindingsRevAcc;keybindingsRevStore=()=>this.keybindingsRevAcc;listTasks=()=>this.tasksAcc();getTask=(id)=>this.tasksAcc().find((task)=>task.id===id);subscribeTasks(listener){return subscribeTasksOp(this.tasksAcc,listener)}createTask=(input)=>createTaskOp(this.client,input);ensureMainTask=(repo)=>ensureMainTaskOp(this.client,repo);openDirectoryTask=(input)=>openDirectoryTaskOp(this.client,input);adoptScratchRepo=(id,repo)=>adoptScratchRepoOp(this.client,id,repo);ensureWorktree=(id)=>ensureWorktreeOp(this.client,id);forgetProject=(repo)=>forgetProjectOp(this.client,repo);setTitle=(id,title)=>setTitleOp(this.client,id,title);setBranch=(id,branch)=>setBranchOp(this.client,id,branch);setVendor=(id,vendor,effort,model)=>setVendorOp(this.client,id,vendor,effort,model);setCommand=(id,command,vendor)=>setCommandOp(this.client,id,command,vendor);setPinned=(id,pinned)=>setPinnedOp(this.client,id,pinned);moveTask=(id,delta)=>moveTaskOp(this.client,id,delta);setStatus=(id,status)=>setStatusOp(this.client,id,status);setPrompt=(id,prompt)=>setPromptOp(this.client,id,prompt);deleteTask=(id,opts)=>deleteTaskOp(this.client,id,opts);dismissAttention=(taskId,tabId,at)=>dismissAttentionOp(this.client,taskId,tabId,at);dismissRoutineAttention=(automationId)=>dismissRoutineAttentionOp(this.client,automationId);markAttentionRead=(taskId,tabId,at)=>markAttentionReadOp(this.client,taskId,tabId,at);landPreflight(id){return landPreflightOp(this.client,id)}landTask(id,opts){return landTaskOp(this.client,id,opts)}discoverAdoptableWorktrees(repo){return discoverAdoptableWorktreesOp(this.client,repo)}adoptWorktree(input){return adoptWorktreeOp(this.client,input)}listWorktrees(opts){return listWorktreesOp(this.client,opts)}listIssues(repoRoot){return listIssuesOp(this.client,repoRoot)}listIssueRepos(){return listIssueReposOp(this.client)}mutateIssue(repoRoot,op){return mutateIssueOp(this.client,repoRoot,op)}listAutomations=()=>listAutomationsOp(this.client);createAutomation=(i)=>createAutomationOp(this.client,i);automationRuns=(id)=>automationRunsOp(this.client,id);setAutomationEnabled=(id,on)=>setAutomationEnabledOp(this.client,id,on);runAutomationNow=(id)=>runAutomationNowOp(this.client,id);deleteAutomation=(id)=>deleteAutomationOp(this.client,id);listWorkItems=(a)=>listWorkItemsOp(this.client,a);listFieldNotes=(repo)=>listFieldNotesOp(this.client,repo);deleteFieldNote=(repo,id)=>deleteFieldNoteOp(this.client,repo,id);failingChecks=(taskId)=>failingChecksOp(this.client,taskId);syncBase=(taskId)=>syncBaseOp(this.client,taskId);startWorkItem=(a)=>startWorkItemOp(this.client,a);removeWorktree(path,force){return removeWorktreeOp(this.client,path,force)}setActiveTask(id){return setActiveTaskOp(this.client,id)}}
3
+ export{liveRowTokens,RemoteOrchestrator};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{LocalExecHost,RemoteExecHost}from"./chunk-2apszxn2.js";import{getKeychainPassword}from"./chunk-g2advs8t.js";import{getRemoteRepoConfig,getRemoteRepos,isRemoteRepoKey}from"./chunk-crt11rmj.js";import{remoteControlSocketPath}from"./chunk-q5jhy3t8.js";function remoteSpecFromConfig(config){let cfgAuth=config.auth,auth=cfgAuth.kind==="key"?{kind:"key",keyPath:cfgAuth.keyPath}:{kind:"password",getPassword:()=>getKeychainPassword(cfgAuth.keychainRef)};return{host:config.host,user:config.user,port:config.port,auth,controlPath:remoteControlSocketPath(config.host,config.user,config.port)}}var remoteHostCache=new Map;function cachedRemoteHost(config){let spec=remoteSpecFromConfig(config),cached=remoteHostCache.get(spec.controlPath);if(cached)return cached;let host=new RemoteExecHost(spec);return remoteHostCache.set(spec.controlPath,host),host}function execHostForRepo(repoKey){let config=getRemoteRepoConfig(repoKey);if(!config)return new LocalExecHost;return cachedRemoteHost(config)}function execHostForWorktreePath(worktreePath){for(let config of Object.values(getRemoteRepos()))if(worktreePath===config.basePath||worktreePath.startsWith(`${config.basePath}/`))return cachedRemoteHost(config);return new LocalExecHost}function remoteKeyForRepo(repo){return repo&&isRemoteRepoKey(repo)?repo:void 0}
2
+ import{LocalExecHost,RemoteExecHost}from"./chunk-2apszxn2.js";import{getKeychainPassword}from"./chunk-g2advs8t.js";import{getRemoteRepoConfig,getRemoteRepos,isRemoteRepoKey}from"./chunk-c8dbw8rz.js";import{remoteControlSocketPath}from"./chunk-q5jhy3t8.js";function remoteSpecFromConfig(config){let cfgAuth=config.auth,auth=cfgAuth.kind==="key"?{kind:"key",keyPath:cfgAuth.keyPath}:{kind:"password",getPassword:()=>getKeychainPassword(cfgAuth.keychainRef)};return{host:config.host,user:config.user,port:config.port,auth,controlPath:remoteControlSocketPath(config.host,config.user,config.port)}}var remoteHostCache=new Map;function cachedRemoteHost(config){let spec=remoteSpecFromConfig(config),cached=remoteHostCache.get(spec.controlPath);if(cached)return cached;let host=new RemoteExecHost(spec);return remoteHostCache.set(spec.controlPath,host),host}function execHostForRepo(repoKey){let config=getRemoteRepoConfig(repoKey);if(!config)return new LocalExecHost;return cachedRemoteHost(config)}function execHostForWorktreePath(worktreePath){for(let config of Object.values(getRemoteRepos()))if(worktreePath===config.basePath||worktreePath.startsWith(`${config.basePath}/`))return cachedRemoteHost(config);return new LocalExecHost}function remoteKeyForRepo(repo){return repo&&isRemoteRepoKey(repo)?repo:void 0}
3
3
  export{execHostForRepo,execHostForWorktreePath,remoteKeyForRepo};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{StaleInstallError,autospawnDaemonEnv,connectIfRunning,connectOrStartDaemon,daemonSpawnReason,ensureDaemonReachable,isStaleInstallError,probeDaemonSocket,resolveKobeSpawn,testDaemonResponds,tryAcquireSpawnLock}from"./chunk-yv44tdjq.js";import"./chunk-c42pwcvw.js";import"./chunk-mjdt28x6.js";import"./chunk-p1zab1sy.js";import"./chunk-hqbmzz4t.js";import"./chunk-3es6spp4.js";import"./chunk-pw6yfj10.js";import"./chunk-vnpqemb0.js";import"./chunk-f10n6063.js";import"./chunk-9prawccj.js";import"./chunk-y8fqdnh3.js";import"./chunk-hq4b3fca.js";import"./chunk-wqfp8d9w.js";export{tryAcquireSpawnLock,testDaemonResponds,resolveKobeSpawn,probeDaemonSocket,isStaleInstallError,ensureDaemonReachable,daemonSpawnReason,connectOrStartDaemon,connectIfRunning,autospawnDaemonEnv,StaleInstallError};
2
+ import{StaleInstallError,autospawnDaemonEnv,connectIfRunning,connectOrStartDaemon,daemonSpawnReason,ensureDaemonReachable,isStaleInstallError,probeDaemonSocket,resolveKobeSpawn,testDaemonResponds,tryAcquireSpawnLock}from"./chunk-5t8cazgm.js";import"./chunk-wenasn1h.js";import"./chunk-vnpqemb0.js";import"./chunk-9prawccj.js";import"./chunk-mjdt28x6.js";import"./chunk-p1zab1sy.js";import"./chunk-hqbmzz4t.js";import"./chunk-3es6spp4.js";import"./chunk-pw6yfj10.js";import"./chunk-f10n6063.js";import"./chunk-y8fqdnh3.js";import"./chunk-hq4b3fca.js";import"./chunk-wqfp8d9w.js";export{tryAcquireSpawnLock,testDaemonResponds,resolveKobeSpawn,probeDaemonSocket,isStaleInstallError,ensureDaemonReachable,daemonSpawnReason,connectOrStartDaemon,connectIfRunning,autospawnDaemonEnv,StaleInstallError};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{detectLanguage}from"./chunk-hape5vwj.js";import{getRepoInitOverride}from"./chunk-crt11rmj.js";import{existsSync}from"fs";import{join as join2}from"path";import{readFileSync}from"fs";import{join}from"path";var REPO_CONFIG_DIRS=[".rove",".kobe"];function repoConfigCandidates(repoDir,filename){return REPO_CONFIG_DIRS.map((dir)=>join(repoDir,dir,filename))}function readFirstNonEmptyRepoFile(repoDir,filename){for(let candidate of repoConfigCandidates(repoDir,filename))if(isNonEmptyRepoFile(candidate))return readFileSync(candidate,"utf8");return}function isNonEmptyRepoFile(absolutePath){try{return readFileSync(absolutePath,"utf8").trim().length>0}catch{return!1}}var LOCKFILE_DEPENDENCY_DIRS=[["bun.lock","node_modules"],["bun.lockb","node_modules"],["package-lock.json","node_modules"],["yarn.lock","node_modules"],["pnpm-lock.yaml","node_modules"],["Cargo.lock","target"],["poetry.lock",".venv"],["uv.lock",".venv"]];function missingDependenciesCoda(worktreePath,language){let missing=new Set;for(let[lockfile,dependencyDir]of LOCKFILE_DEPENDENCY_DIRS){if(!existsSync(join2(worktreePath,lockfile)))continue;if(existsSync(join2(worktreePath,dependencyDir)))continue;missing.add(dependencyDir)}if(missing.size===0)return;let dirs=[...missing].join(", ");if(language==="zh")return`\u8865\u5145\uFF1A\u8FD9\u4E2A worktree \u6CA1\u6709\u88C5\u4F9D\u8D56\uFF08\u4ED3\u5E93\u91CC\u6709 lockfile\uFF0C\u4F46 ${dirs} \u4E0D\u5B58\u5728\uFF09\u3002\u5728\u76F8\u4FE1\u4EFB\u4F55\u6784\u5EFA / \u6D4B\u8BD5\u7ED3\u679C\u4E4B\u524D\uFF0C\u5148\u8DD1\u4E00\u904D\u672C\u4ED3\u5E93\u7684\u5B89\u88C5\u6B65\u9AA4\u2014\u2014\u8FD9\u91CC\u7684\u5931\u8D25\u591A\u534A\u662F\u56E0\u4E3A\u6CA1\u88C5\u4F9D\u8D56\uFF0C\u800C\u4E0D\u662F\u4EE3\u7801\u56DE\u5F52\u3002\u5982\u679C\u8FD9\u4E2A\u4ED3\u5E93\u6BCF\u6B21\u90FD\u9700\u8981\u88C5\uFF0C\u53EF\u4EE5\u8003\u8651\u52A0\u4E00\u4E2A \`.rove/init.sh\`\u3002`;return`PS: this worktree has no installed dependencies (${dirs} missing beside a committed lockfile). Run the repo's install step before trusting build/test results \u2014 a failure here is most likely the missing install, not a regression. If this repo always needs one, consider adding \`.rove/init.sh\`.`}var INIT_SCRIPT_FILENAME="init.sh",INIT_PROMPT_FILENAME="init-prompt.md";function repoFileScript(worktreePath){for(let dir of REPO_CONFIG_DIRS)if(existsSync(join2(worktreePath,dir,INIT_SCRIPT_FILENAME)))return`sh ${dir}/${INIT_SCRIPT_FILENAME}`;return}function repoFilePrompt(worktreePath){return readFirstNonEmptyRepoFile(worktreePath,INIT_PROMPT_FILENAME)}function describeRepoInitSources(repoRoot){let describe=(filename,counts)=>{let taken=!1;return REPO_CONFIG_DIRS.map((dir)=>{let absolute=join2(repoRoot,dir,filename),effective=!taken&&counts(absolute);if(effective)taken=!0;return{rel:`${dir}/${filename}`,present:existsSync(absolute),effective}})};return{script:describe(INIT_SCRIPT_FILENAME,existsSync),prompt:describe(INIT_PROMPT_FILENAME,isNonEmptyRepoFile)}}function resolveRepoInit(repoRoot,worktreePath){let override=repoRoot?getRepoInitOverride(repoRoot):{},initScript=repoFileScript(worktreePath)??override.initScript,initPrompt=repoFilePrompt(worktreePath)??override.initPrompt;return{initScript:initScript&&initScript.trim().length>0?initScript:void 0,initPrompt:initPrompt&&initPrompt.trim().length>0?initPrompt:void 0}}function firstMessageFor(intent,init,worktreePath){if(intent.kind==="none")return;if(intent.kind==="explicit")return{source:"explicit",text:intent.prompt};if(intent.kind==="new-task"){let deps=init.initScript?void 0:missingDependenciesCoda(worktreePath,detectLanguage(intent.prompt)??void 0);return{source:"explicit",text:[intent.prompt,deps].filter(Boolean).join(`
2
+ import{detectLanguage}from"./chunk-hape5vwj.js";import{getRepoInitOverride}from"./chunk-c8dbw8rz.js";import{existsSync}from"fs";import{join as join2}from"path";import{readFileSync}from"fs";import{join}from"path";var REPO_CONFIG_DIRS=[".rove",".kobe"];function repoConfigCandidates(repoDir,filename){return REPO_CONFIG_DIRS.map((dir)=>join(repoDir,dir,filename))}function readFirstNonEmptyRepoFile(repoDir,filename){for(let candidate of repoConfigCandidates(repoDir,filename))if(isNonEmptyRepoFile(candidate))return readFileSync(candidate,"utf8");return}function isNonEmptyRepoFile(absolutePath){try{return readFileSync(absolutePath,"utf8").trim().length>0}catch{return!1}}var LOCKFILE_DEPENDENCY_DIRS=[["bun.lock","node_modules"],["bun.lockb","node_modules"],["package-lock.json","node_modules"],["yarn.lock","node_modules"],["pnpm-lock.yaml","node_modules"],["Cargo.lock","target"],["poetry.lock",".venv"],["uv.lock",".venv"]];function missingDependenciesCoda(worktreePath,language){let missing=new Set;for(let[lockfile,dependencyDir]of LOCKFILE_DEPENDENCY_DIRS){if(!existsSync(join2(worktreePath,lockfile)))continue;if(existsSync(join2(worktreePath,dependencyDir)))continue;missing.add(dependencyDir)}if(missing.size===0)return;let dirs=[...missing].join(", ");if(language==="zh")return`\u8865\u5145\uFF1A\u8FD9\u4E2A worktree \u6CA1\u6709\u88C5\u4F9D\u8D56\uFF08\u4ED3\u5E93\u91CC\u6709 lockfile\uFF0C\u4F46 ${dirs} \u4E0D\u5B58\u5728\uFF09\u3002\u5728\u76F8\u4FE1\u4EFB\u4F55\u6784\u5EFA / \u6D4B\u8BD5\u7ED3\u679C\u4E4B\u524D\uFF0C\u5148\u8DD1\u4E00\u904D\u672C\u4ED3\u5E93\u7684\u5B89\u88C5\u6B65\u9AA4\u2014\u2014\u8FD9\u91CC\u7684\u5931\u8D25\u591A\u534A\u662F\u56E0\u4E3A\u6CA1\u88C5\u4F9D\u8D56\uFF0C\u800C\u4E0D\u662F\u4EE3\u7801\u56DE\u5F52\u3002\u5982\u679C\u8FD9\u4E2A\u4ED3\u5E93\u6BCF\u6B21\u90FD\u9700\u8981\u88C5\uFF0C\u53EF\u4EE5\u8003\u8651\u52A0\u4E00\u4E2A \`.rove/init.sh\`\u3002`;return`PS: this worktree has no installed dependencies (${dirs} missing beside a committed lockfile). Run the repo's install step before trusting build/test results \u2014 a failure here is most likely the missing install, not a regression. If this repo always needs one, consider adding \`.rove/init.sh\`.`}var INIT_SCRIPT_FILENAME="init.sh",INIT_PROMPT_FILENAME="init-prompt.md";function repoFileScript(worktreePath){for(let dir of REPO_CONFIG_DIRS)if(existsSync(join2(worktreePath,dir,INIT_SCRIPT_FILENAME)))return`sh ${dir}/${INIT_SCRIPT_FILENAME}`;return}function repoFilePrompt(worktreePath){return readFirstNonEmptyRepoFile(worktreePath,INIT_PROMPT_FILENAME)}function describeRepoInitSources(repoRoot){let describe=(filename,counts)=>{let taken=!1;return REPO_CONFIG_DIRS.map((dir)=>{let absolute=join2(repoRoot,dir,filename),effective=!taken&&counts(absolute);if(effective)taken=!0;return{rel:`${dir}/${filename}`,present:existsSync(absolute),effective}})};return{script:describe(INIT_SCRIPT_FILENAME,existsSync),prompt:describe(INIT_PROMPT_FILENAME,isNonEmptyRepoFile)}}function resolveRepoInit(repoRoot,worktreePath){let override=repoRoot?getRepoInitOverride(repoRoot):{},initScript=repoFileScript(worktreePath)??override.initScript,initPrompt=repoFilePrompt(worktreePath)??override.initPrompt;return{initScript:initScript&&initScript.trim().length>0?initScript:void 0,initPrompt:initPrompt&&initPrompt.trim().length>0?initPrompt:void 0}}function firstMessageFor(intent,init,worktreePath){if(intent.kind==="none")return;if(intent.kind==="explicit")return{source:"explicit",text:intent.prompt};if(intent.kind==="new-task"){let deps=init.initScript?void 0:missingDependenciesCoda(worktreePath,detectLanguage(intent.prompt)??void 0);return{source:"explicit",text:[intent.prompt,deps].filter(Boolean).join(`
3
3
 
4
4
  `)}}let text=init.initPrompt?.trim();return text?{source:"repo-init",text}:void 0}function resolveEngineLaunchInit(repoRoot,worktreePath,intent={kind:"repo-init"}){let init=resolveRepoInit(repoRoot,worktreePath);return{initScript:init.initScript,firstMessage:firstMessageFor(intent,init,worktreePath)}}
5
- export{readFirstNonEmptyRepoFile,missingDependenciesCoda,INIT_SCRIPT_FILENAME,INIT_PROMPT_FILENAME,describeRepoInitSources,resolveRepoInit,resolveEngineLaunchInit};
5
+ export{readFirstNonEmptyRepoFile,missingDependenciesCoda,describeRepoInitSources,resolveRepoInit,resolveEngineLaunchInit};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{connectIfRunning,connectOrStartDaemon}from"./chunk-yv44tdjq.js";async function openDaemonSession(opts={}){let client=opts.mode==="require-running"?await connectIfRunning():await connectOrStartDaemon();if(!client)return null;return{client,close:()=>client.close()}}async function resolveActiveTaskId(client){let activeId=null,off=client.onChannel("active-task",(payload)=>{activeId=payload.taskId});try{await client.subscribe()}finally{off()}return activeId}
2
+ import{connectIfRunning,connectOrStartDaemon}from"./chunk-5t8cazgm.js";async function openDaemonSession(opts={}){let client=opts.mode==="require-running"?await connectIfRunning():await connectOrStartDaemon();if(!client)return null;return{client,close:()=>client.close()}}async function resolveActiveTaskId(client){let activeId=null,off=client.onChannel("active-task",(payload)=>{activeId=payload.taskId});try{await client.subscribe()}finally{off()}return activeId}
3
3
  export{openDaemonSession,resolveActiveTaskId};
@@ -5,4 +5,4 @@ const lists = {}
5
5
  for (const pid of ${JSON.stringify([...anchors])}) {
6
6
  try { lists[pid] = Array.from(native.getConsoleProcessList(pid)) } catch { lists[pid] = null }
7
7
  }
8
- process.stdout.write(JSON.stringify({ self: process.pid, lists }))`}function parseCohorts(json,anchors){let parsed=JSON.parse(json),self=typeof parsed.self==="number"?parsed.self:-1,out=new Map;for(let anchor of anchors){let list=parsed.lists?.[String(anchor)];out.set(anchor,Array.isArray(list)?list.filter((pid)=>pid>0&&pid!==self):null)}return out}function defaultWinProcessProbe(budgetMs=WIN_PROBE_TIMEOUT_MS){let deadline=Date.now()+budgetMs;return{processList:()=>capture([powershellPath(),"-NoProfile","-NonInteractive","-NoLogo","-Command",WIN_PROCESS_LIST_COMMAND],"Get-CimInstance Win32_Process",deadline),consoleCohorts:async(anchors)=>{let script=agentScript(consoleListAddonPath(),anchors),json=await capture([process.execPath,"-e",script],"console process list",deadline);return parseCohorts(json,anchors)}}}async function winProcessSnapshot(anchors,probe){let rows=parseWinProcessList(await probe.processList());if(rows.length===0)throw new PsProbeUnavailableError("Win32_Process returned no rows");if(anchors.length===0)return serializeProcRows(rows);return serializeProcRows(repairConsoleParentage(rows,await probe.consoleCohorts(anchors)))}export{winProcessSnapshot,repairConsoleParentage,parseWinProcessList,normalizeWindowsArgs,defaultWinProcessProbe,WIN_PROCESS_LIST_COMMAND,WIN_PROBE_TIMEOUT_MS};
8
+ process.stdout.write(JSON.stringify({ self: process.pid, lists }))`}function parseCohorts(json,anchors){let parsed=JSON.parse(json),self=typeof parsed.self==="number"?parsed.self:-1,out=new Map;for(let anchor of anchors){let list=parsed.lists?.[String(anchor)];out.set(anchor,Array.isArray(list)?list.filter((pid)=>pid>0&&pid!==self):null)}return out}function defaultWinProcessProbe(budgetMs=WIN_PROBE_TIMEOUT_MS){let deadline=Date.now()+budgetMs;return{processList:()=>capture([powershellPath(),"-NoProfile","-NonInteractive","-NoLogo","-Command",WIN_PROCESS_LIST_COMMAND],"Get-CimInstance Win32_Process",deadline),consoleCohorts:async(anchors)=>{let script=agentScript(consoleListAddonPath(),anchors),json=await capture([process.execPath,"-e",script],"console process list",deadline);return parseCohorts(json,anchors)}}}async function winProcessSnapshot(anchors,probe){let rows=parseWinProcessList(await probe.processList());if(rows.length===0)throw new PsProbeUnavailableError("Win32_Process returned no rows");if(anchors.length===0)return serializeProcRows(rows);return serializeProcRows(repairConsoleParentage(rows,await probe.consoleCohorts(anchors)))}export{winProcessSnapshot,repairConsoleParentage,parseWinProcessList,normalizeWindowsArgs,defaultWinProcessProbe,WIN_PROBE_TIMEOUT_MS};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ENGINE_NOT_OBSERVED_REASON,ENGINE_START_POLL_MS,ENGINE_START_PROBE_MS,deliverHostedPrompt,deliverToKey,ensurePtyHost,findEngineKey,isTaskKey,killTaskSessions,listSessions,listSessionsOrNull,openPtyHost,outcomeFields,taskKeys}from"./chunk-cs1k9d61.js";import"./chunk-gp72n435.js";import"./chunk-jyghj39f.js";import"./chunk-k74rfmkd.js";import"./chunk-2apszxn2.js";import"./chunk-g2advs8t.js";import"./chunk-878cxvry.js";import"./chunk-rcyasw34.js";import"./chunk-7q67dz4c.js";import"./chunk-ekdh3m31.js";import"./chunk-b99tf0jr.js";import"./chunk-x6c4jega.js";import"./chunk-f7zjggfv.js";import"./chunk-kf8whkc2.js";import"./chunk-hape5vwj.js";import"./chunk-mmdvkep0.js";import"./chunk-pq897z3n.js";import"./chunk-8rk6ecgf.js";import"./chunk-w7zv47mp.js";import"./chunk-khj0apc7.js";import"./chunk-w25b7xxz.js";import"./chunk-jvxh93nz.js";import"./chunk-5t8cazgm.js";import"./chunk-wenasn1h.js";import"./chunk-fczqwtmq.js";import"./chunk-2brn8e1y.js";import"./chunk-nzshm6jy.js";import"./chunk-80jwjzn8.js";import"./chunk-7kysxgbq.js";import"./chunk-4pf41rdt.js";import"./chunk-xy8be792.js";import"./chunk-05jej26n.js";import"./chunk-c8dbw8rz.js";import"./chunk-6cm9pb1f.js";import"./chunk-hq2n27y1.js";import"./chunk-40dgv828.js";import"./chunk-81p6mm0p.js";import"./chunk-vnpqemb0.js";import"./chunk-q5jhy3t8.js";import"./chunk-9prawccj.js";import"./chunk-00ehck55.js";import"./chunk-fxs82dsx.js";import"./chunk-sb0ns0c7.js";import"./chunk-w0tdbrpw.js";import"./chunk-mvz2a6a1.js";import"./chunk-sdyzxayr.js";import"./chunk-pxk2c2vj.js";import"./chunk-mjdt28x6.js";import"./chunk-p1zab1sy.js";import"./chunk-hqbmzz4t.js";import"./chunk-3es6spp4.js";import"./chunk-pw6yfj10.js";import"./chunk-f10n6063.js";import"./chunk-y8fqdnh3.js";import"./chunk-hq4b3fca.js";import"./chunk-wqfp8d9w.js";export{taskKeys,outcomeFields,openPtyHost,listSessionsOrNull,listSessions,killTaskSessions,isTaskKey,findEngineKey,ensurePtyHost,deliverToKey,deliverHostedPrompt,ENGINE_START_PROBE_MS,ENGINE_START_POLL_MS,ENGINE_NOT_OBSERVED_REASON};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{serialized,writeJsonAtomic}from"./chunk-xsrcwcjc.js";import{logDaemonError}from"./chunk-rcyasw34.js";import{ROVE_STATE_DIR_BASENAME,readRoveHomeDirEnv}from"./chunk-hq4b3fca.js";import{readFile}from"fs/promises";import{homedir}from"os";import{join,resolve as resolve2}from"path";import{execFile}from"child_process";import{realpath,stat}from"fs/promises";import{isAbsolute,resolve}from"path";import{promisify}from"util";var execFileAsync=promisify(execFile);async function gitCommonDir(path){let{stdout}=await execFileAsync("git",["-C",path,"rev-parse","--git-common-dir"]),dir=stdout.trim();return realpath(isAbsolute(dir)?dir:resolve(path,dir))}async function gitMainWorktree(path){let{stdout}=await execFileAsync("git",["-C",path,"worktree","list","--porcelain"]),first=stdout.split(/\r?\n/).find((line)=>line.startsWith("worktree "))?.slice(9).trim();return first?await realpath(first):null}async function gitTopLevel(path){let{stdout}=await execFileAsync("git",["-C",path,"rev-parse","--show-toplevel"]);return stdout.trim()}async function resolveRepoRoot(raw){let absolute=resolve(raw);if(!(await stat(absolute).catch(()=>null))?.isDirectory())throw Error("repoRoot does not exist");let[repoRoot,repoKey]=await Promise.all([gitMainWorktree(absolute),gitCommonDir(absolute)]);return{repoRoot,repoKey}}var ISSUE_STATUSES=["open","doing","hold","done"],ISSUE_NOT_FOUND_CODE="ISSUE_NOT_FOUND",ISSUE_STORE_UNREADABLE_CODE="ISSUE_STORE_UNREADABLE";function isGitNotRepositoryError(err){return(err instanceof Error?err.message:String(err)).includes("not a git repository")}function defaultIssuesStorePath(homeDir=readRoveHomeDirEnv()??homedir()){return join(homeDir,ROVE_STATE_DIR_BASENAME,"issues.json")}function isValidStatus(value){return typeof value==="string"&&ISSUE_STATUSES.includes(value)}function normalizeIssue(entry){if(entry===null||typeof entry!=="object"||Array.isArray(entry))return null;let raw=entry;if(typeof raw.id!=="number")return null;return{id:raw.id,title:typeof raw.title==="string"?raw.title:"(untitled)",status:isValidStatus(raw.status)?raw.status:"open",created:typeof raw.created==="string"?raw.created:"",body:typeof raw.body==="string"?raw.body:"",taskId:typeof raw.taskId==="string"?raw.taskId:void 0}}function emptyStore(){return{version:1,repos:{}}}function nextIdFallback(entries){let max=0;for(let entry of entries){let id=Number(entry?.id);if(Number.isFinite(id)&&id>max)max=Math.trunc(id)}return max+1}function todayStamp(){let pinned=process.env.KOBE_ISSUES_TODAY;if(pinned&&/^\d{4}-\d{2}-\d{2}$/.test(pinned))return pinned;let d=new Date,mm=String(d.getMonth()+1).padStart(2,"0"),dd=String(d.getDate()).padStart(2,"0");return`${d.getFullYear()}-${mm}-${dd}`}async function resolveRepo(raw){if(typeof raw!=="string"||raw.length===0)throw Error("repoRoot is required");try{let{repoRoot,repoKey}=await resolveRepoRoot(raw);return{repoRoot:repoRoot??await gitTopLevel(resolve2(raw)),repoKey}}catch(err){if(isGitNotRepositoryError(err))throw Error("repoRoot is not a git repository");throw err}}function unreadableCount(raw){if(raw!==null&&typeof raw==="object"&&!Array.isArray(raw))return Math.max(1,Object.keys(raw).length);return 1}function readRecord(value){let record=value,base={repoRoot:typeof record.repoRoot==="string"?record.repoRoot:"",nextId:typeof record.nextId==="number"?record.nextId:1};if(record.issues!==void 0&&!Array.isArray(record.issues))return{record:{...base,issues:[],unusable:[],unreadable:{raw:value}},dropped:unreadableCount(record.issues)};let entries=Array.isArray(record.issues)?record.issues:[],issues=entries.map(normalizeIssue).filter((issue)=>issue!==null),unusable=entries.filter((entry)=>normalizeIssue(entry)===null);return{record:{repoRoot:base.repoRoot,nextId:typeof record.nextId==="number"?record.nextId:nextIdFallback(entries),issues,unusable},dropped:unusable.length}}async function readStore(path){try{let raw=JSON.parse(await readFile(path,"utf8")),repos={},skipped=new Map;if(raw.repos&&typeof raw.repos==="object")for(let[key,value]of Object.entries(raw.repos)){if(!value||typeof value!=="object")continue;let{record,dropped}=readRecord(value);if(dropped>0){skipped.set(key,dropped);let why=record.unreadable?'"issues" is not an array':"id is not a number";logDaemonError("issues-store-read",Error(`${key}: dropped ${dropped} unreadable issue entr${dropped===1?"y":"ies"} (${why})`))}repos[key]=record}return{file:{version:1,repos},skipped}}catch(err){if(err.code==="ENOENT")return{file:emptyStore(),skipped:new Map};throw Error(`${path}: ${err instanceof Error?err.message:String(err)}`)}}function serializeRecord(record){if(record.unreadable)return record.unreadable.raw;return{repoRoot:record.repoRoot,nextId:record.nextId,issues:[...record.issues,...record.unusable]}}async function writeStore(path,store){let repos={};for(let[key,record]of Object.entries(store.repos))repos[key]=serializeRecord(record);await writeJsonAtomic(path,{version:store.version,repos})}function response(repoRoot,record,skipped=0){return{repoRoot,exists:record!==null,nextId:record?.nextId??1,issues:record?.issues??[],skipped}}class IssuesStore{path;constructor(path=defaultIssuesStorePath()){this.path=path}async list(repo){let{repoRoot,repoKey}=await resolveRepo(repo);return serialized(this.path,async()=>{let{file:store,skipped}=await readStore(this.path),record=store.repos[repoKey]??null;if(record&&!record.unreadable&&record.repoRoot!==repoRoot)record.repoRoot=repoRoot,await writeStore(this.path,store);return response(repoRoot,record,skipped.get(repoKey)??0)})}async repos(){return serialized(this.path,async()=>{let{file}=await readStore(this.path);return Object.values(file.repos).map((record)=>record.repoRoot).filter((root)=>root.length>0)})}async mirrorTaskDone(repo,taskId){let{repoRoot,repoKey}=await resolveRepo(repo);if(!taskId)return null;return serialized(this.path,async()=>{let{file:store,skipped}=await readStore(this.path),record=store.repos[repoKey];if(!record)return null;let issue=record.issues.find((i)=>i.taskId===taskId);if(!issue||issue.status==="done")return null;return issue.status="done",record.repoRoot=repoRoot,await writeStore(this.path,store),response(repoRoot,record,skipped.get(repoKey)??0)})}async unlinkTask(repo,taskId){let{repoRoot,repoKey}=await resolveRepo(repo);if(!taskId)return null;return serialized(this.path,async()=>{let{file:store,skipped}=await readStore(this.path),record=store.repos[repoKey];if(!record)return null;let issue=record.issues.find((i)=>i.taskId===taskId);if(!issue)return null;return issue.taskId=void 0,record.repoRoot=repoRoot,await writeStore(this.path,store),response(repoRoot,record,skipped.get(repoKey)??0)})}async mutate(repo,op){let{repoRoot,repoKey}=await resolveRepo(repo);if(!op||typeof op!=="object"||Array.isArray(op)||typeof op.type!=="string")throw Error("missing op");return serialized(this.path,async()=>{let{file:store,skipped}=await readStore(this.path),record=store.repos[repoKey];if(!record)record={repoRoot,nextId:1,issues:[],unusable:[]},store.repos[repoKey]=record;if(record.unreadable)throw Error(`${ISSUE_STORE_UNREADABLE_CODE}: ${repoRoot}'s record in ${this.path} has a non-array "issues" \u2014 refusing to write over stories this build cannot read`);record.repoRoot=repoRoot;let typed=op;if(typed.type==="create"){if(typeof typed.title!=="string"||typed.title.trim().length===0)throw Error("create requires a non-empty title");if(typed.body!==void 0&&typeof typed.body!=="string")throw Error("body must be a string");record.issues=[{id:record.nextId,title:typed.title,status:"open",created:todayStamp(),body:typeof typed.body==="string"?typed.body:""},...record.issues],record.nextId+=1}else if(typed.type==="setStatus"){if(typeof typed.id!=="number")throw Error("setStatus requires a numeric id");if(!isValidStatus(typed.status))throw Error(`invalid status: must be one of ${ISSUE_STATUSES.join(", ")}`);let issue=record.issues.find((i)=>i.id===typed.id);if(!issue)throw Error(`${ISSUE_NOT_FOUND_CODE}: no issue #${typed.id}`);issue.status=typed.status}else if(typed.type==="update"){if(typeof typed.id!=="number")throw Error("update requires a numeric id");if(typed.title!==void 0&&(typeof typed.title!=="string"||typed.title.trim().length===0))throw Error("title must be a non-empty string");if(typed.body!==void 0&&typeof typed.body!=="string")throw Error("body must be a string");if(typed.taskId!==void 0&&typed.taskId!==null&&(typeof typed.taskId!=="string"||typed.taskId.length===0))throw Error("taskId must be a non-empty string or null");let issue=record.issues.find((i)=>i.id===typed.id);if(!issue)throw Error(`${ISSUE_NOT_FOUND_CODE}: no issue #${typed.id}`);if(typeof typed.title==="string")issue.title=typed.title;if(typeof typed.body==="string")issue.body=typed.body;if(typed.taskId!==void 0)issue.taskId=typed.taskId===null?void 0:typed.taskId}else if(typed.type==="link"){if(typeof typed.id!=="number")throw Error("link requires a numeric id");if(typeof typed.taskId!=="string"||typed.taskId.length===0)throw Error("link requires a non-empty taskId");let issue=record.issues.find((i)=>i.id===typed.id);if(!issue)throw Error(`${ISSUE_NOT_FOUND_CODE}: no issue #${typed.id}`);issue.taskId=typed.taskId}else if(typed.type==="unlink"){if(typeof typed.id!=="number")throw Error("unlink requires a numeric id");let issue=record.issues.find((i)=>i.id===typed.id);if(!issue)throw Error(`${ISSUE_NOT_FOUND_CODE}: no issue #${typed.id}`);issue.taskId=void 0}else if(typed.type==="delete"){if(typeof typed.id!=="number")throw Error("delete requires a numeric id");let nextIssues=record.issues.filter((i)=>i.id!==typed.id);if(nextIssues.length===record.issues.length)throw Error(`${ISSUE_NOT_FOUND_CODE}: no issue #${typed.id}`);record.issues=nextIssues}else throw Error(`unknown op type: ${typed.type}`);return await writeStore(this.path,store),response(repoRoot,record,skipped.get(repoKey)??0)})}}
3
+ export{resolveRepoRoot,ISSUE_STATUSES,defaultIssuesStorePath,IssuesStore};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{engineEntry,identifiableEngineIds}from"./chunk-47j1228v.js";import{recordSpawn}from"./chunk-40dgv828.js";import{loadStateFile}from"./chunk-katrbape.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import{__require}from"./chunk-wqfp8d9w.js";import{basename}from"path";var WRAPPERS=new Set(["node","bun","npx","deno","sh","zsh","bash","env","script"]);function binaryName(token){return basename(token).replace(/\.(exe|js|mjs|cjs)$/,"")}function executableNameFromArgv(argv){for(let token of argv.slice(0,8)){if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))continue;let name=binaryName(token);if(WRAPPERS.has(name))continue;return name||null}return null}function vendorFromArgv(commandLine){let name=executableNameFromArgv(commandLine.trim().split(/\s+/));if(!name)return null;return identifiableEngineIds().find((v)=>{let entry=engineEntry(v);return entry.defaultCommand[0]===name||entry.processNames?.includes(name)===!0})??null}function parsePsSnapshot(text){let rows=[];for(let line of text.split(`
3
- `)){let m=/^\s*(\d+)\s+(\d+)\s+(\S.*)$/.exec(line);if(m)rows.push({pid:Number(m[1]),ppid:Number(m[2]),args:m[3]})}return rows}function childrenIndex(rows){let kids=new Map;for(let row of rows){let list=kids.get(row.ppid);if(list)list.push(row);else kids.set(row.ppid,[row])}return kids}function hasAncestor(rows,pid,ancestorPid){let parents=new Map(rows.map((r)=>[r.pid,r.ppid])),cur=pid;for(let hops=0;hops<=rows.length;hops++){if(cur===ancestorPid)return!0;let next=parents.get(cur);if(next===void 0||next<=1)return!1;cur=next}return!1}function customEngineBinaries(){let state=loadStateFile(),ids=state.customEngineIds,out=new Map;if(!Array.isArray(ids))return out;for(let id of ids){if(typeof id!=="string"||id.trim().length===0)continue;let command=state[`engineCommand.${id}`],argv=typeof command==="string"&&command.trim().length>0?command.trim().split(/\s+/):[id],name=executableNameFromArgv(argv);if(name)out.set(name,id)}return out}function walkDescendants(rows,rootPid,identify){let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;let vendor=identify(row.args);if(vendor)return{vendor,argv:row.args,pid:row.pid};queue.push(...kids.get(row.pid)??[])}return null}function foregroundEngineIn(rows,rootPid){let builtin=walkDescendants(rows,rootPid,vendorFromArgv);if(builtin)return builtin;let custom=customEngineBinaries();if(custom.size===0)return null;return walkDescendants(rows,rootPid,(args)=>custom.get(executableNameFromArgv(args.trim().split(/\s+/))??"")??null)}function engineProcessIn(rows,rootPid,extraLaunch){if(foregroundEngineIn(rows,rootPid))return!0;let expected=extraLaunch?executableNameFromArgv(typeof extraLaunch==="string"?[extraLaunch]:extraLaunch):null;if(!expected)return!1;let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;if(executableNameFromArgv(row.args.trim().split(/\s+/))===expected)return!0;queue.push(...kids.get(row.pid)??[])}return!1}var PS_PROBE_TIMEOUT_MS=5000,bunPsSpawn=()=>{recordSpawn("engine.foregroundWalk",["ps","-A","-o","pid=,ppid=,args="]);let proc=Bun.spawn(["ps","-A","-o","pid=,ppid=,args="],{stdout:"pipe",stderr:"ignore"});return{text:new Response(proc.stdout).text(),kill:()=>proc.kill()}};async function psSnapshotWith(spawn,timeoutMs=PS_PROBE_TIMEOUT_MS){let proc=spawn(),timer;try{let text=await Promise.race([proc.text,new Promise((_resolve,reject)=>{timer=setTimeout(()=>{try{proc.kill()}catch{}reject(new PsProbeUnavailableError(`ps did not answer within ${timeoutMs}ms`))},timeoutMs)})]);if(parsePsSnapshot(text).length===0)throw new PsProbeUnavailableError("ps returned no usable rows");return text}finally{if(timer)clearTimeout(timer)}}var psSnapshot=async(anchors)=>{if(process.platform!=="win32")return psSnapshotWith(bunPsSpawn);let{defaultWinProcessProbe,winProcessSnapshot}=await import("./chunk-hses07jj.js");return winProcessSnapshot(anchors??[],defaultWinProcessProbe())};async function foregroundEngine(rootPid,snapshot=psSnapshot){try{return foregroundEngineIn(parsePsSnapshot(await snapshot([rootPid])),rootPid)}catch{return null}}
2
+ import{engineEntry,identifiableEngineIds}from"./chunk-pq897z3n.js";import{loadStateFile}from"./chunk-6cm9pb1f.js";import{recordSpawn}from"./chunk-40dgv828.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import{__require}from"./chunk-wqfp8d9w.js";import{basename}from"path";var WRAPPERS=new Set(["node","bun","npx","deno","sh","zsh","bash","env","script"]);function binaryName(token){return basename(token).replace(/\.(exe|js|mjs|cjs)$/,"")}function executableNameFromArgv(argv){for(let token of argv.slice(0,8)){if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))continue;let name=binaryName(token);if(WRAPPERS.has(name))continue;return name||null}return null}function vendorFromArgv(commandLine){let name=executableNameFromArgv(commandLine.trim().split(/\s+/));if(!name)return null;return identifiableEngineIds().find((v)=>{let entry=engineEntry(v);return entry.defaultCommand[0]===name||entry.processNames?.includes(name)===!0})??null}function parsePsSnapshot(text){let rows=[];for(let line of text.split(`
3
+ `)){let m=/^\s*(\d+)\s+(\d+)\s+(\S.*)$/.exec(line);if(m)rows.push({pid:Number(m[1]),ppid:Number(m[2]),args:m[3]})}return rows}function childrenIndex(rows){let kids=new Map;for(let row of rows){let list=kids.get(row.ppid);if(list)list.push(row);else kids.set(row.ppid,[row])}return kids}function hasAncestor(rows,pid,ancestorPid){let parents=new Map(rows.map((r)=>[r.pid,r.ppid])),cur=pid;for(let hops=0;hops<=rows.length;hops++){if(cur===ancestorPid)return!0;let next=parents.get(cur);if(next===void 0||next<=1)return!1;cur=next}return!1}function customEngineBinaries(){let state=loadStateFile(),ids=state.customEngineIds,out=new Map;if(!Array.isArray(ids))return out;for(let id of ids){if(typeof id!=="string"||id.trim().length===0)continue;let command=state[`engineCommand.${id}`],argv=typeof command==="string"&&command.trim().length>0?command.trim().split(/\s+/):[id],name=executableNameFromArgv(argv);if(name)out.set(name,id)}return out}function walkDescendants(rows,rootPid,identify){let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;let vendor=identify(row.args);if(vendor)return{vendor,argv:row.args,pid:row.pid};queue.push(...kids.get(row.pid)??[])}return null}function foregroundEngineIn(rows,rootPid){let builtin=walkDescendants(rows,rootPid,vendorFromArgv);if(builtin)return builtin;let custom=customEngineBinaries();if(custom.size===0)return null;return walkDescendants(rows,rootPid,(args)=>custom.get(executableNameFromArgv(args.trim().split(/\s+/))??"")??null)}function engineProcessIn(rows,rootPid,extraLaunch){if(foregroundEngineIn(rows,rootPid))return!0;let expected=extraLaunch?executableNameFromArgv(typeof extraLaunch==="string"?[extraLaunch]:extraLaunch):null;if(!expected)return!1;let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;if(executableNameFromArgv(row.args.trim().split(/\s+/))===expected)return!0;queue.push(...kids.get(row.pid)??[])}return!1}var PS_PROBE_TIMEOUT_MS=5000,bunPsSpawn=()=>{recordSpawn("engine.foregroundWalk",["ps","-A","-o","pid=,ppid=,args="]);let proc=Bun.spawn(["ps","-A","-o","pid=,ppid=,args="],{stdout:"pipe",stderr:"ignore"});return{text:new Response(proc.stdout).text(),kill:()=>proc.kill()}};async function psSnapshotWith(spawn,timeoutMs=PS_PROBE_TIMEOUT_MS){let proc=spawn(),timer;try{let text=await Promise.race([proc.text,new Promise((_resolve,reject)=>{timer=setTimeout(()=>{try{proc.kill()}catch{}reject(new PsProbeUnavailableError(`ps did not answer within ${timeoutMs}ms`))},timeoutMs)})]);if(parsePsSnapshot(text).length===0)throw new PsProbeUnavailableError("ps returned no usable rows");return text}finally{if(timer)clearTimeout(timer)}}var psSnapshot=async(anchors)=>{if(process.platform!=="win32")return psSnapshotWith(bunPsSpawn);let{defaultWinProcessProbe,winProcessSnapshot}=await import("./chunk-kxaqge09.js");return winProcessSnapshot(anchors??[],defaultWinProcessProbe())};async function foregroundEngine(rootPid,snapshot=psSnapshot){try{return foregroundEngineIn(parsePsSnapshot(await snapshot([rootPid])),rootPid)}catch{return null}}
4
4
  export{vendorFromArgv,parsePsSnapshot,hasAncestor,foregroundEngineIn,engineProcessIn,PS_PROBE_TIMEOUT_MS,psSnapshotWith,psSnapshot,foregroundEngine};