@sma1lboy/rove 0.9.272 → 0.9.273-nightly.20261027

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 (92) hide show
  1. package/dist/cli/chunk-06xt2mhb.js +2 -0
  2. package/dist/cli/{chunk-9rtw4k38.js → chunk-0csav0tg.js} +1 -1
  3. package/dist/cli/{chunk-js50sr3w.js → chunk-1pkhwwn4.js} +1 -1
  4. package/dist/cli/chunk-2ssqfhwb.js +2 -0
  5. package/dist/cli/chunk-34tbcjdy.js +2 -0
  6. package/dist/cli/{chunk-pss7gg43.js → chunk-3nqf8gwr.js} +1 -1
  7. package/dist/cli/chunk-4y5hk7gr.js +2 -0
  8. package/dist/cli/{chunk-6b91pz64.js → chunk-58y5geay.js} +2 -2
  9. package/dist/cli/{chunk-32yhdeak.js → chunk-692n3x93.js} +1 -1
  10. package/dist/cli/chunk-72tc0dhk.js +2 -0
  11. package/dist/cli/{chunk-hknt4xza.js → chunk-7hyx5z35.js} +1 -1
  12. package/dist/cli/chunk-7hzgtyke.js +5 -0
  13. package/dist/cli/{chunk-0vq7yqj0.js → chunk-7yn79aye.js} +1 -1
  14. package/dist/cli/{chunk-2kx64z0b.js → chunk-8na3sv2h.js} +1 -1
  15. package/dist/cli/{chunk-sk19nvdj.js → chunk-8z63cvmg.js} +1 -1
  16. package/dist/cli/chunk-9d5zechf.js +2 -0
  17. package/dist/cli/{chunk-9m4gje59.js → chunk-a037vcy5.js} +1 -1
  18. package/dist/cli/{chunk-0j7j051w.js → chunk-a09kjwtd.js} +1 -1
  19. package/dist/cli/{chunk-k0hp75n2.js → chunk-acnmrmxh.js} +1 -1
  20. package/dist/cli/{chunk-9fynr5t1.js → chunk-ag8hyh7c.js} +1 -1
  21. package/dist/cli/chunk-bmq4hxdg.js +2 -0
  22. package/dist/cli/chunk-c2yt6fag.js +4 -0
  23. package/dist/cli/{chunk-e31be3k4.js → chunk-cj82t1v0.js} +1 -1
  24. package/dist/cli/{chunk-hk9p0gjs.js → chunk-fmp4sfxe.js} +1 -1
  25. package/dist/cli/{chunk-zpvwb2z6.js → chunk-fqgvmy2d.js} +1 -1
  26. package/dist/cli/{chunk-ar2zhdhh.js → chunk-fzadtbrm.js} +1 -1
  27. package/dist/cli/chunk-gs01afvb.js +13 -0
  28. package/dist/cli/chunk-h4yec78v.js +11 -0
  29. package/dist/cli/{chunk-ma74dbah.js → chunk-hksrpa1j.js} +3 -3
  30. package/dist/cli/{chunk-p5mtfzn3.js → chunk-hzvbq8mf.js} +1 -1
  31. package/dist/cli/{chunk-xfps1yce.js → chunk-jfn7889p.js} +1 -1
  32. package/dist/cli/{chunk-682xhgvd.js → chunk-jr6c3hce.js} +3 -3
  33. package/dist/cli/{chunk-ncvesyjr.js → chunk-kdg7b8av.js} +2 -2
  34. package/dist/cli/{chunk-62ka1j1s.js → chunk-kfzzk4sk.js} +1 -1
  35. package/dist/cli/{chunk-x564fc4v.js → chunk-kgg1ykdw.js} +1 -1
  36. package/dist/cli/{chunk-yyzpqxt5.js → chunk-krsswcp7.js} +1 -1
  37. package/dist/cli/{chunk-zjq52kfk.js → chunk-kx53jjee.js} +1 -1
  38. package/dist/cli/{chunk-djkmaabe.js → chunk-mmq6922s.js} +2 -2
  39. package/dist/cli/{chunk-pe8affmn.js → chunk-mq0bx7zy.js} +1 -1
  40. package/dist/cli/chunk-nh7a6bhb.js +3 -0
  41. package/dist/cli/{chunk-t4epmfd1.js → chunk-nqck4ghb.js} +1 -1
  42. package/dist/cli/{chunk-r5h3dc1y.js → chunk-p7bzpsgn.js} +1 -1
  43. package/dist/cli/chunk-pm91e38v.js +4 -0
  44. package/dist/cli/chunk-pt00jcaz.js +2 -0
  45. package/dist/cli/{chunk-07daqn0z.js → chunk-qfe1wf5c.js} +1 -1
  46. package/dist/cli/chunk-qpc7ek4z.js +2 -0
  47. package/dist/cli/{chunk-mkb88wzr.js → chunk-r06v0pyn.js} +1 -1
  48. package/dist/cli/{chunk-rwnd0t4w.js → chunk-r3ezk0cs.js} +1 -1
  49. package/dist/cli/chunk-r5j8fycq.js +3 -0
  50. package/dist/cli/{chunk-qdvhg3rg.js → chunk-rngjpf3c.js} +1 -1
  51. package/dist/cli/{chunk-ct896m44.js → chunk-sj4e61x6.js} +1 -1
  52. package/dist/cli/{chunk-nrwyxhtz.js → chunk-ta92gm9s.js} +1 -1
  53. package/dist/cli/{chunk-jeve2yf8.js → chunk-wna3jsp4.js} +2 -2
  54. package/dist/cli/chunk-wsfcca0x.js +3 -0
  55. package/dist/cli/{chunk-27bn9kmy.js → chunk-x06qxj81.js} +1 -1
  56. package/dist/cli/{chunk-eq8kb4kj.js → chunk-x20bs6bs.js} +1 -1
  57. package/dist/cli/{chunk-16x3ftbg.js → chunk-xbgcg6d3.js} +5 -5
  58. package/dist/cli/chunk-xecgzx8c.js +96 -0
  59. package/dist/cli/{chunk-m9qg3yck.js → chunk-xncz4ke1.js} +1 -1
  60. package/dist/cli/{chunk-k8bevbmr.js → chunk-y0wg9ekb.js} +1 -1
  61. package/dist/cli/{chunk-nkd5as36.js → chunk-yk5zs8ec.js} +10 -6
  62. package/dist/cli/{chunk-n2cb06nr.js → chunk-zvxq5xdr.js} +1 -1
  63. package/dist/cli/index.js +3 -3
  64. package/dist/completions/rove.bash +1 -1
  65. package/dist/completions/rove.fish +1 -1
  66. package/dist/completions/rove.zsh +1 -1
  67. package/dist/skills/rove/SKILL.md +2 -2
  68. package/dist/skills/rove/references/api-flags.md +23 -18
  69. package/dist/web/assets/index-oQc8YcHX.js +113 -0
  70. package/dist/web/assets/{index-DfqQoIzt.css → index-sA2EEQJw.css} +1 -1
  71. package/dist/web/index.html +2 -2
  72. package/package.json +1 -1
  73. package/dist/cli/chunk-0ay6bvfg.js +0 -2
  74. package/dist/cli/chunk-3w2vpggj.js +0 -5
  75. package/dist/cli/chunk-4hf2y0k4.js +0 -2
  76. package/dist/cli/chunk-6v5mw6t7.js +0 -3
  77. package/dist/cli/chunk-83pzw53w.js +0 -2
  78. package/dist/cli/chunk-ay9ys27w.js +0 -3
  79. package/dist/cli/chunk-crhbpmfp.js +0 -3
  80. package/dist/cli/chunk-ec08vr9c.js +0 -2
  81. package/dist/cli/chunk-effc77em.js +0 -4
  82. package/dist/cli/chunk-f09ex46c.js +0 -3
  83. package/dist/cli/chunk-gb3zemrx.js +0 -2
  84. package/dist/cli/chunk-kzq2mqjz.js +0 -2
  85. package/dist/cli/chunk-mrdxvf76.js +0 -3
  86. package/dist/cli/chunk-px1gd2zk.js +0 -96
  87. package/dist/cli/chunk-qkbvxa7b.js +0 -2
  88. package/dist/cli/chunk-s4nrmbqh.js +0 -13
  89. package/dist/cli/chunk-s70mf80s.js +0 -11
  90. package/dist/cli/chunk-t19001hn.js +0 -2
  91. package/dist/cli/chunk-v967kt9x.js +0 -2
  92. package/dist/web/assets/index-CJgzqO7A.js +0 -111
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-yk5zs8ec.js";import"./chunk-y0wg9ekb.js";import"./chunk-6vhr65h3.js";import"./chunk-182qa2d6.js";import"./chunk-rtpa8hg3.js";import"./chunk-r3ezk0cs.js";import"./chunk-p6jw0zcd.js";import"./chunk-pm91e38v.js";import"./chunk-17e2tgyg.js";import"./chunk-q9zgj6kw.js";import"./chunk-mmq6922s.js";import"./chunk-7z463zkx.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-1rjq808h.js";import"./chunk-gq36nzg8.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-7drxm3c8.js";import"./chunk-c2yt6fag.js";import"./chunk-gs01afvb.js";import"./chunk-sq6zj3fb.js";import"./chunk-qkehg2c1.js";import"./chunk-zvxq5xdr.js";import"./chunk-sj4e61x6.js";import"./chunk-rngjpf3c.js";import"./chunk-7yn79aye.js";import"./chunk-adv5s59k.js";import"./chunk-fvvb0072.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-783d1ba0.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-yzkhwn31.js";import"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-y1xnjx8x.js";import"./chunk-fqgvmy2d.js";import"./chunk-a037vcy5.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-etfh8f4z.js";import"./chunk-h8t4xg1p.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-2brn8e1y.js";import"./chunk-a09kjwtd.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-4vad6e9t.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
@@ -1,2 +1,2 @@
1
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-n2cb06nr.js";import"./chunk-ct896m44.js";import"./chunk-qdvhg3rg.js";import"./chunk-0vq7yqj0.js";import"./chunk-adv5s59k.js";import"./chunk-fvvb0072.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-783d1ba0.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-yzkhwn31.js";import"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-f09ex46c.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-y1xnjx8x.js";import"./chunk-zpvwb2z6.js";import"./chunk-9m4gje59.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-2brn8e1y.js";import"./chunk-0j7j051w.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.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};
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-zvxq5xdr.js";import"./chunk-sj4e61x6.js";import"./chunk-rngjpf3c.js";import"./chunk-7yn79aye.js";import"./chunk-adv5s59k.js";import"./chunk-fvvb0072.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-783d1ba0.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-yzkhwn31.js";import"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-y1xnjx8x.js";import"./chunk-fqgvmy2d.js";import"./chunk-a037vcy5.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-2brn8e1y.js";import"./chunk-a09kjwtd.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.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};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{CLAUDE_HOOK_EVENT_MAP,claudeSettingsPath}from"./chunk-0j7j051w.js";import{hasRoveActivityHooks}from"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import{installedSkillDirs}from"./chunk-6b91pz64.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{homedir}from"os";var PLUGIN_NAME="rove";function readSettings(path){try{let parsed=JSON.parse(readFileSync(path,"utf8"));return isObject(parsed)?parsed:null}catch{return null}}function isRovePluginEnabled(settingsFilePath=claudeSettingsPath()){let settings=readSettings(settingsFilePath);if(!settings||!isObject(settings.enabledPlugins))return!1;return Object.entries(settings.enabledPlugins).some(([key,on])=>on===!0&&key.split("@")[0]===PLUGIN_NAME)}function detectLegacyInstalls(opts={}){let settingsFilePath=opts.settingsFilePath??claudeSettingsPath(),home=opts.home??homedir(),settings=readSettings(settingsFilePath),legacyHooks=settings!==null&&(hasRoveActivityHooks(settings,CLAUDE_HOOK_EVENT_MAP)||settingsHasWorktreeWatch(settings)),legacySkillDirs=installedSkillDirs(home);return{legacyHooks,legacySkillDirs}}function settingsHasWorktreeWatch(settings){let hooks=isObject(settings.hooks)?settings.hooks:{};return Object.values(hooks).some((groups)=>Array.isArray(groups)&&groups.some((g)=>isObject(g)&&Array.isArray(g.hooks)&&g.hooks.some((h)=>isObject(h)&&typeof h.command==="string"&&h.command.includes("worktree-created")&&!h.command.includes("CLAUDE_PLUGIN_ROOT"))))}function migrationHint(findings,cliName){if(!findings.legacyHooks&&findings.legacySkillDirs.length===0)return null;let lines=[`${cliName}: the Rove Claude Code plugin is enabled, but legacy installs remain:`];if(findings.legacyHooks)lines.push(" \u2022 ~/.claude/settings.json still has the settings-managed Rove hooks (every event fires TWICE).",` Run \`${cliName} hook cleanup\` to remove them (only Rove's own entries are touched).`);for(let dir of findings.legacySkillDirs)lines.push(` \u2022 legacy skill copy at ${dir} (the plugin bundles the skill \u2014 two copies double-register).`," Remove that directory to keep the plugin's copy only.");return lines.push(" Reading this inside a session? Just ask your agent to run the cleanup for you."),`${lines.join(`
2
+ import{CLAUDE_HOOK_EVENT_MAP,claudeSettingsPath}from"./chunk-a09kjwtd.js";import{hasRoveActivityHooks}from"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import{installedSkillDirs}from"./chunk-58y5geay.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{homedir}from"os";var PLUGIN_NAME="rove";function readSettings(path){try{let parsed=JSON.parse(readFileSync(path,"utf8"));return isObject(parsed)?parsed:null}catch{return null}}function isRovePluginEnabled(settingsFilePath=claudeSettingsPath()){let settings=readSettings(settingsFilePath);if(!settings||!isObject(settings.enabledPlugins))return!1;return Object.entries(settings.enabledPlugins).some(([key,on])=>on===!0&&key.split("@")[0]===PLUGIN_NAME)}function detectLegacyInstalls(opts={}){let settingsFilePath=opts.settingsFilePath??claudeSettingsPath(),home=opts.home??homedir(),settings=readSettings(settingsFilePath),legacyHooks=settings!==null&&(hasRoveActivityHooks(settings,CLAUDE_HOOK_EVENT_MAP)||settingsHasWorktreeWatch(settings)),legacySkillDirs=installedSkillDirs(home);return{legacyHooks,legacySkillDirs}}function settingsHasWorktreeWatch(settings){let hooks=isObject(settings.hooks)?settings.hooks:{};return Object.values(hooks).some((groups)=>Array.isArray(groups)&&groups.some((g)=>isObject(g)&&Array.isArray(g.hooks)&&g.hooks.some((h)=>isObject(h)&&typeof h.command==="string"&&h.command.includes("worktree-created")&&!h.command.includes("CLAUDE_PLUGIN_ROOT"))))}function migrationHint(findings,cliName){if(!findings.legacyHooks&&findings.legacySkillDirs.length===0)return null;let lines=[`${cliName}: the Rove Claude Code plugin is enabled, but legacy installs remain:`];if(findings.legacyHooks)lines.push(" \u2022 ~/.claude/settings.json still has the settings-managed Rove hooks (every event fires TWICE).",` Run \`${cliName} hook cleanup\` to remove them (only Rove's own entries are touched).`);for(let dir of findings.legacySkillDirs)lines.push(` \u2022 legacy skill copy at ${dir} (the plugin bundles the skill \u2014 two copies double-register).`," Remove that directory to keep the plugin's copy only.");return lines.push(" Reading this inside a session? Just ask your agent to run the cleanup for you."),`${lines.join(`
3
3
  `)}
4
4
  `}export{migrationHint,isRovePluginEnabled,detectLegacyInstalls};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ensureForwards,startTunnel}from"./chunk-gs01afvb.js";import"./chunk-sq6zj3fb.js";import"./chunk-y1xnjx8x.js";import"./chunk-7kysxgbq.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{startTunnel,ensureForwards};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ApiError,GROUP_MOD,REMOTE_CALLER,VERB_GROUP_IDS,cliCaller,daemonCaller,helpStep,promptMayHaveLanded,requireVerbInstalled,splitDaemonCode,verbInstalled}from"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-yt15y085.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{verbInstalled,splitDaemonCode,requireVerbInstalled,promptMayHaveLanded,helpStep,daemonCaller,cliCaller,VERB_GROUP_IDS,REMOTE_CALLER,GROUP_MOD,ApiError};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,vendorFromArgv}from"./chunk-zpvwb2z6.js";import"./chunk-9m4gje59.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-2brn8e1y.js";import"./chunk-0j7j051w.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{vendorFromArgv,psSnapshotWith,psSnapshot,parsePsSnapshot,hasAncestor,foregroundEngineIn,foregroundEngine,engineProcessIn,PsProbeUnavailableError,PS_PROBE_TIMEOUT_MS};
2
+ import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,vendorFromArgv}from"./chunk-fqgvmy2d.js";import"./chunk-a037vcy5.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-2brn8e1y.js";import"./chunk-a09kjwtd.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{vendorFromArgv,psSnapshotWith,psSnapshot,parsePsSnapshot,hasAncestor,foregroundEngineIn,foregroundEngine,engineProcessIn,PsProbeUnavailableError,PS_PROBE_TIMEOUT_MS};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{MachineFeed,decodeMachines}from"./chunk-mq0bx7zy.js";import"./chunk-nh7a6bhb.js";import"./chunk-phpaypqx.js";import"./chunk-atn06ncf.js";import"./chunk-gs01afvb.js";import"./chunk-sq6zj3fb.js";import"./chunk-y1xnjx8x.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-7kysxgbq.js";import"./chunk-xy8be792.js";import"./chunk-4vad6e9t.js";import"./chunk-40dgv828.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cmp64q4j.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{decodeMachines,MachineFeed};
@@ -1,9 +1,9 @@
1
1
  // @bun
2
- import{getPersistedString,setPersistedString}from"./chunk-rfp0ayra.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{accessSync,existsSync,constants as fsConstants,readFileSync,statSync}from"fs";import{homedir}from"os";import{delimiter,dirname,join,resolve}from"path";import{fileURLToPath}from"url";var ROVE_SKILL_VERSION=86,ROVE_SKILL_REL_PATHS=[".agents/skills/rove/SKILL.md",".claude/skills/rove/SKILL.md"],SKILL_REL_PATHS=ROVE_SKILL_REL_PATHS;function skillInstallCommand(env=process.env){return`${ROVE_PRODUCT_NAME} skill install`}var SKILL_SOURCE_SLUG="Sma1lboy/rove";function bundledSkillDir(){let here=fileURLToPath(import.meta.url);return[resolve(here,"../../../../../.agents/skills/rove"),resolve(here,"../../skills/rove")].find((dir)=>existsSync(join(dir,"SKILL.md")))??null}function npxSkillsArgv(opts={}){let source=opts.source!==void 0?opts.source:bundledSkillDir(),agents=opts.agent===void 0?[]:typeof opts.agent==="string"?[opts.agent]:opts.agent;return["skills","add",source??SKILL_SOURCE_SLUG,"--skill",ROVE_PRODUCT_NAME,...opts.global===!1?[]:["--global"],...agents.flatMap((a)=>["--agent",a])]}function npxSkillsCommand(opts={}){return`npx ${npxSkillsArgv(opts).join(" ")}`}var NPX_MISSING_EXIT=127;function isNpxMissing(){let parts=(process.env.PATH??"").split(delimiter).filter(Boolean);if(parts.length===0)return!1;return!parts.some((dir)=>{try{return accessSync(join(dir,"npx"),fsConstants.X_OK),!0}catch{return!1}})}function npxMissingMessage(){return`${ROVE_PRODUCT_NAME} skill install needs \`npx\` (part of Node.js), which isn't on your PATH.
2
+ import{getPersistedString,setPersistedString}from"./chunk-rfp0ayra.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{accessSync,existsSync,constants as fsConstants,readFileSync,statSync}from"fs";import{homedir}from"os";import{delimiter,dirname,join,resolve}from"path";import{fileURLToPath}from"url";var ROVE_SKILL_VERSION=88,ROVE_SKILL_REL_PATHS=[".agents/skills/rove/SKILL.md",".claude/skills/rove/SKILL.md"],SKILL_REL_PATHS=ROVE_SKILL_REL_PATHS;function skillInstallCommand(env=process.env){return`${ROVE_PRODUCT_NAME} skill install`}var SKILL_SOURCE_SLUG="Sma1lboy/rove";function bundledSkillDir(){let here=fileURLToPath(import.meta.url);return[resolve(here,"../../../../../.agents/skills/rove"),resolve(here,"../../skills/rove")].find((dir)=>existsSync(join(dir,"SKILL.md")))??null}function npxSkillsArgv(opts={}){let source=opts.source!==void 0?opts.source:bundledSkillDir(),agents=opts.agent===void 0?[]:typeof opts.agent==="string"?[opts.agent]:opts.agent;return["skills","add",source??SKILL_SOURCE_SLUG,"--skill",ROVE_PRODUCT_NAME,...opts.global===!1?[]:["--global"],...agents.flatMap((a)=>["--agent",a])]}function npxSkillsCommand(opts={}){return`npx ${npxSkillsArgv(opts).join(" ")}`}var NPX_MISSING_EXIT=127;function isNpxMissing(){let parts=(process.env.PATH??"").split(delimiter).filter(Boolean);if(parts.length===0)return!1;return!parts.some((dir)=>{try{return accessSync(join(dir,"npx"),fsConstants.X_OK),!0}catch{return!1}})}function npxMissingMessage(){return`${ROVE_PRODUCT_NAME} skill install needs \`npx\` (part of Node.js), which isn't on your PATH.
3
3
  Install Node.js (https://nodejs.org) and run it again \u2014 the Rove installer only installs Bun and Rove.`}async function runNpxSkillsInstall(agent,global){if(isNpxMissing())return process.stderr.write(`
4
4
  ${npxMissingMessage()}
5
5
 
6
- `),NPX_MISSING_EXIT;return await Bun.spawn(["npx",...npxSkillsArgv({...agent===void 0?{}:{agent},global})],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}var HINT_SEEN_KEY="skillHintSeen";function markSkillHintSeen(){setPersistedString(HINT_SEEN_KEY,"1")}function roveSkillPaths(opts={}){let home=opts.home??homedir(),cwd=opts.cwd??process.cwd();return[home,cwd].flatMap((root)=>SKILL_REL_PATHS.map((rel)=>join(root,rel)))}function parseSkillVersion(content){let m=content.match(/rove-skill-version:\s*(\d+)/);return m?Number.parseInt(m[1],10):null}function skillVersionAt(path){try{return parseSkillVersion(readFileSync(path,"utf8"))}catch{return null}}function inodeKey(path){try{let stat=statSync(path);return`${stat.dev}:${stat.ino}`}catch{return path}}function distinctSkillFiles(roots,rels){let seen=new Set,out=[];for(let root of roots)for(let rel of rels){let path=join(root,rel);if(!existsSync(path))continue;let key=inodeKey(path);if(seen.has(key))continue;seen.add(key),out.push(path)}return out}function installedSkillDirs(home=homedir()){return distinctSkillFiles([home],SKILL_REL_PATHS).map((path)=>dirname(path))}function roveSkillState(opts={}){let roots=[opts.home??homedir(),opts.cwd??process.cwd()],best=[...distinctSkillFiles(roots,ROVE_SKILL_REL_PATHS).map((path)=>({path,version:skillVersionAt(path)}))].sort((a,b)=>(b.version??-1)-(a.version??-1))[0];if(!best)return{installed:!1,installedVersion:null,currentVersion:ROVE_SKILL_VERSION,stale:!1,path:null};let stale=best.version===null||best.version<ROVE_SKILL_VERSION;return{installed:!0,installedVersion:best.version,currentVersion:ROVE_SKILL_VERSION,stale,path:best.path}}function installedSkillDiffersFromBundled(installedPath){let bundled=bundledSkillDir();if(!bundled)return!1;try{return readFileSync(join(bundled,"SKILL.md"),"utf8")!==readFileSync(installedPath,"utf8")}catch{return!1}}function promptLine(){return new Promise((resolve2)=>{process.stdin.resume(),process.stdin.once("data",(d)=>{process.stdin.pause(),resolve2(String(d))})})}async function maybeHintSkillInstall(io={}){let{isRovePluginEnabled}=await import("./chunk-js50sr3w.js");if(isRovePluginEnabled())return;let cliName=ROVE_PRODUCT_NAME,installCommand=skillInstallCommand(),state=roveSkillState();if(!state.installed){if(getPersistedString(HINT_SEEN_KEY)==="1")return;setPersistedString(HINT_SEEN_KEY,"1"),process.stderr.write(`
6
+ `),NPX_MISSING_EXIT;return await Bun.spawn(["npx",...npxSkillsArgv({...agent===void 0?{}:{agent},global})],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}var HINT_SEEN_KEY="skillHintSeen";function markSkillHintSeen(){setPersistedString(HINT_SEEN_KEY,"1")}function roveSkillPaths(opts={}){let home=opts.home??homedir(),cwd=opts.cwd??process.cwd();return[home,cwd].flatMap((root)=>SKILL_REL_PATHS.map((rel)=>join(root,rel)))}function parseSkillVersion(content){let m=content.match(/rove-skill-version:\s*(\d+)/);return m?Number.parseInt(m[1],10):null}function skillVersionAt(path){try{return parseSkillVersion(readFileSync(path,"utf8"))}catch{return null}}function inodeKey(path){try{let stat=statSync(path);return`${stat.dev}:${stat.ino}`}catch{return path}}function distinctSkillFiles(roots,rels){let seen=new Set,out=[];for(let root of roots)for(let rel of rels){let path=join(root,rel);if(!existsSync(path))continue;let key=inodeKey(path);if(seen.has(key))continue;seen.add(key),out.push(path)}return out}function installedSkillDirs(home=homedir()){return distinctSkillFiles([home],SKILL_REL_PATHS).map((path)=>dirname(path))}function roveSkillState(opts={}){let roots=[opts.home??homedir(),opts.cwd??process.cwd()],best=[...distinctSkillFiles(roots,ROVE_SKILL_REL_PATHS).map((path)=>({path,version:skillVersionAt(path)}))].sort((a,b)=>(b.version??-1)-(a.version??-1))[0];if(!best)return{installed:!1,installedVersion:null,currentVersion:ROVE_SKILL_VERSION,stale:!1,path:null};let stale=best.version===null||best.version<ROVE_SKILL_VERSION;return{installed:!0,installedVersion:best.version,currentVersion:ROVE_SKILL_VERSION,stale,path:best.path}}function installedSkillDiffersFromBundled(installedPath){let bundled=bundledSkillDir();if(!bundled)return!1;try{return readFileSync(join(bundled,"SKILL.md"),"utf8")!==readFileSync(installedPath,"utf8")}catch{return!1}}function promptLine(){return new Promise((resolve2)=>{process.stdin.resume(),process.stdin.once("data",(d)=>{process.stdin.pause(),resolve2(String(d))})})}async function maybeHintSkillInstall(io={}){let{isRovePluginEnabled}=await import("./chunk-1pkhwwn4.js");if(isRovePluginEnabled())return;let cliName=ROVE_PRODUCT_NAME,installCommand=skillInstallCommand(),state=roveSkillState();if(!state.installed){if(getPersistedString(HINT_SEEN_KEY)==="1")return;setPersistedString(HINT_SEEN_KEY,"1"),process.stderr.write(`
7
7
  ${cliName}: the Rove agent skill isn't installed \u2014 install it so your coding agent can drive Rove via \`${cliName} api\`:
8
8
  ${installCommand}
9
9
  (wraps \`${npxSkillsCommand()}\`; check anytime with \`${cliName} doctor\`)
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-62ka1j1s.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-8sggyn8y.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-ncvesyjr.js";import"./chunk-a4hsqj1b.js";import"./chunk-d9e4ssy7.js";import"./chunk-1exwrmjd.js";import"./chunk-k67vbszb.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-rwnd0t4w.js";import"./chunk-7z463zkx.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-1rjq808h.js";import"./chunk-gq36nzg8.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-0vq7yqj0.js";import{resolveNodeBinary}from"./chunk-adv5s59k.js";import"./chunk-fvvb0072.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-zpvwb2z6.js";import"./chunk-9m4gje59.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-2w228s7t.js";import"./chunk-etfh8f4z.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-zsfyj36g.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-2brn8e1y.js";import"./chunk-0j7j051w.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import{readableLegacyIndexPath}from"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import{CURRENT_VERSION,package_default}from"./chunk-4vad6e9t.js";import{roveSkillState,skillInstallCommand}from"./chunk-6b91pz64.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-z1nj22va.js";import{readPidFile}from"./chunk-br8r72bf.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import{t}from"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-eqdbfgq5.js";import{preRenameStateDir}from"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
2
+ import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-kfzzk4sk.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-8sggyn8y.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-kdg7b8av.js";import"./chunk-a4hsqj1b.js";import"./chunk-d9e4ssy7.js";import"./chunk-1exwrmjd.js";import"./chunk-k67vbszb.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-r3ezk0cs.js";import"./chunk-7z463zkx.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-1rjq808h.js";import"./chunk-gq36nzg8.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-7yn79aye.js";import{resolveNodeBinary}from"./chunk-adv5s59k.js";import"./chunk-fvvb0072.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-fqgvmy2d.js";import"./chunk-a037vcy5.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-2w228s7t.js";import"./chunk-etfh8f4z.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-zsfyj36g.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-2brn8e1y.js";import"./chunk-a09kjwtd.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import{readableLegacyIndexPath}from"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import{CURRENT_VERSION,package_default}from"./chunk-4vad6e9t.js";import{roveSkillState,skillInstallCommand}from"./chunk-58y5geay.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-z1nj22va.js";import{readPidFile}from"./chunk-br8r72bf.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import{t}from"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-eqdbfgq5.js";import{preRenameStateDir}from"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
3
3
  `)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids,deps={}){let runProbe=deps.run??run,readEnviron=deps.readEnviron??((pid)=>readFileSync(`/proc/${pid}/environ`,"utf8")),marked=new Set;if(pids.length===0)return{marked,failed:null};if((deps.platform??process.platform)==="linux"){let refused=null;for(let pid of pids)try{if(readEnviron(pid).split("\x00").includes(PTY_MARKER))marked.add(pid)}catch(err){let code=err.code;if(code!=="ENOENT"&&code!=="ESRCH")refused??=`/proc/${pid}/environ: ${code??"unreadable"}`}return{marked,failed:refused}}let result=await runProbe(["ps","eww","-o","pid=,command=","-p",pids.join(",")]);if(result.code!==0)return{marked,failed:`ps eww exited ${result.code}`};let marker=new RegExp(`(^|\\s)${PTY_MARKER}(\\s|$)`);for(let line of result.stdout.split(`
4
4
  `)){let pid=Number.parseInt(line.trim().split(/\s+/)[0]??"",10);if(Number.isFinite(pid)&&marker.test(line))marked.add(pid)}return{marked,failed:null}}async function ownPgid(runProbe){let result=await runProbe(["ps","-o","pgid=","-p",String(process.pid)]),pgid=Number.parseInt(result.stdout.trim(),10);return Number.isFinite(pgid)?pgid:-1}async function collectOrphans(liveSessionPids,deps={}){let runProbe=deps.run??run;if((deps.platform??process.platform)==="win32")return{orphans:[],error:null};let ps=await runProbe(["ps","-A","-o","pid=,ppid=,pgid=,etime=,rss=,command="]);if(ps.code!==0)return{orphans:[],error:`could not read the process table \u2014 ps exited ${ps.code}`};let rows=parsePsRows(ps.stdout),candidates=orphanCandidates(rows,await ownPgid(runProbe),liveSessionPids),{marked,failed}=await markedPids(candidates.map((row)=>row.pid),deps);if(failed)return{orphans:[],error:`could not read process environments \u2014 ${failed}`};return{orphans:candidates.filter((row)=>marked.has(row.pid)),error:null}}function formatMb(rssKb){return`${(rssKb/1024).toFixed(0)} MB`}function orphanDoctorLines(orphans,error,cliName,killing=!1){if(error)return[`orphans: \u2717 ${error}`];if(orphans.length===0)return["orphans: \u2713 none \u2014 no processes left behind by a dead PTY session"];let totalMb=orphans.reduce((sum,row)=>sum+row.rssKb,0)/1024,lines=[`orphans: \u26A0 ${orphans.length} process(es) outlived the PTY session that spawned them (${totalMb.toFixed(0)} MB RSS)`," each is reparented to init, carries Rove's PTY marker, and its process"," group leader is gone \u2014 no live task owns them"];for(let row of[...orphans].sort((a,b)=>b.rssKb-a.rssKb))lines.push(` pid ${row.pid} (group ${row.pgid}) up ${row.etime}, ${formatMb(row.rssKb)}: ${row.command.slice(0,90)}`);if(!killing)lines.push(` \u2192 \`${cliName} doctor --kill-orphans\` ends those process groups (SIGTERM, then SIGKILL)`," read the list first: something you backgrounded from a Rove terminal and then"," closed the tab on looks exactly like a leak, and doctor cannot tell them apart");return lines}var GROUP_EXIT_GRACE_MS=2000,GROUP_POLL_MS=100;function logOrphanKill(pgid,signal,logPath=defaultDaemonLogPath()){try{appendFileSync(logPath,formatDaemonInfo("doctor-kill-orphans",`${signal} process group ${pgid}`))}catch{}}function groupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(err){return err.code!=="ESRCH"}}async function killOrphanGroups(orphans){let groups=[...new Set(orphans.map((row)=>row.pgid))];for(let pgid of groups)try{process.kill(-pgid,"SIGTERM"),logOrphanKill(pgid,"SIGTERM")}catch{}let deadline=Date.now()+GROUP_EXIT_GRACE_MS,survivors=groups.filter(groupAlive);while(survivors.length>0&&Date.now()<deadline)await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),survivors=survivors.filter(groupAlive);for(let pgid of survivors)try{process.kill(-pgid,"SIGKILL"),logOrphanKill(pgid,"SIGKILL")}catch{}return await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),{groups,survivors:survivors.filter(groupAlive)}}function multiplexerLabel(env){if(env.TMUX)return"tmux";if(env.ZELLIJ)return"zellij";if(env.STY)return"screen";return"no"}function terminalEnvLines(env){let show=(v)=>v&&v.length>0?v:"(unset)",program=env.TERM_PROGRAM?`${env.TERM_PROGRAM}${env.TERM_PROGRAM_VERSION?` v${env.TERM_PROGRAM_VERSION}`:""}`:"(unset)";return[`terminal: TERM=${show(env.TERM)} TERM_PROGRAM=${program} COLORTERM=${show(env.COLORTERM)}`,` running inside a multiplexer: ${multiplexerLabel(env)}`]}function parseKittyProbeReply(data){let kitty=data.match(/\x1b\[\?(\d+)u/);if(kitty?.[1]!==void 0)return{kind:"supported",flags:Number.parseInt(kitty[1],10)};if(/\x1b\[\?[\d;]*c/.test(data))return{kind:"unsupported"};return null}function kittyProbeLine(result){switch(result.kind){case"supported":return` kitty keyboard protocol: \u2713 answered (flags=${result.flags})`;case"unsupported":return[" kitty keyboard protocol: \u2717 not supported \u2014 legacy key path"," (ctrl+h/ctrl+j arrive as C0 backspace/linefeed bytes; the"," split chords ctrl+\\ and ctrl+= cannot be encoded at all)"].join(`
5
5
  `);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}async function probeGit(){try{let proc=Bun.spawn(["git","--version"],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),text=(await new Response(proc.stdout).text()).trim();if(await proc.exited===0&&text)return{line:`git: \u2713 ${text}`,found:!0}}catch{}return{line:"git: \u2717 not found on PATH",found:!1}}function binaryLabel(binary){return binary.found?`\u2713 ${binary.path}`:`\u2717 ${binary.error}`}async function probeEngines(){let statuses=await 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=ROVE_PRODUCT_NAME;function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new RoveDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(readFileSync2(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function tailFile(path,count){try{return readFileSync2(path,"utf8").split(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{invokeVerb,runApiSubcommand}from"./chunk-fzadtbrm.js";import{executeVerb,toApiError}from"./chunk-kgg1ykdw.js";import{API_SCHEMA_VERSION,API_VERBS,VERBS,VERB_GROUPS,VerbArgs,apiUsage,buildCountPlan,defaultApiRuntime,deliverPrompt,findVerb,fullSchema,parseAgentsSpec,parseFlags,schemaIndex,validateAgainstSpec,verbHelp,verbSchema}from"./chunk-yk5zs8ec.js";import"./chunk-y0wg9ekb.js";import"./chunk-6vhr65h3.js";import"./chunk-182qa2d6.js";import"./chunk-rtpa8hg3.js";import"./chunk-r3ezk0cs.js";import"./chunk-p6jw0zcd.js";import"./chunk-pm91e38v.js";import"./chunk-17e2tgyg.js";import"./chunk-q9zgj6kw.js";import"./chunk-mmq6922s.js";import"./chunk-7z463zkx.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-1rjq808h.js";import"./chunk-gq36nzg8.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-7drxm3c8.js";import"./chunk-c2yt6fag.js";import"./chunk-gs01afvb.js";import"./chunk-sq6zj3fb.js";import"./chunk-qkehg2c1.js";import"./chunk-zvxq5xdr.js";import"./chunk-sj4e61x6.js";import"./chunk-rngjpf3c.js";import"./chunk-7yn79aye.js";import"./chunk-adv5s59k.js";import"./chunk-fvvb0072.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-783d1ba0.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-yzkhwn31.js";import"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import{ApiError}from"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-y1xnjx8x.js";import"./chunk-fqgvmy2d.js";import"./chunk-a037vcy5.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-etfh8f4z.js";import"./chunk-h8t4xg1p.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-3249q53j.js";import"./chunk-67nb2sdd.js";import"./chunk-7vkvfawc.js";import"./chunk-2brn8e1y.js";import"./chunk-a09kjwtd.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-4vad6e9t.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{verbSchema,verbHelp,validateAgainstSpec,toApiError,schemaIndex,runApiSubcommand,parseFlags,parseAgentsSpec,invokeVerb,fullSchema,findVerb,executeVerb,deliverPrompt,defaultApiRuntime,buildCountPlan,apiUsage,VerbArgs,VERB_GROUPS,VERBS,ApiError,API_VERBS,API_SCHEMA_VERSION};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{NoopHookAdapter,activityHookAdapters,createEngineHookAdapter}from"./chunk-9m4gje59.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-2brn8e1y.js";import"./chunk-0j7j051w.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{createEngineHookAdapter,activityHookAdapters,NoopHookAdapter};
2
+ import{NoopHookAdapter,activityHookAdapters,createEngineHookAdapter}from"./chunk-a037vcy5.js";import"./chunk-aac92ra2.js";import"./chunk-w7zv47mp.js";import"./chunk-2tfnscxk.js";import"./chunk-2brn8e1y.js";import"./chunk-a09kjwtd.js";import"./chunk-dyzvnvjz.js";import"./chunk-7kysxgbq.js";import"./chunk-08gdekk1.js";import"./chunk-2cg3b07h.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{createEngineHookAdapter,activityHookAdapters,NoopHookAdapter};
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{canonPath,normalizeMainRepo,randomDirTaskSuffix,repoWorkingDir,samePrStatus,titleFromRepo}from"./chunk-x20bs6bs.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-c1dz3qg3.js";import{GitWorktreeManager,defaultExecDeps,git,isDirtyOutput,parseDirtyPaths}from"./chunk-kx53jjee.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-q9zgj6kw.js";import{CannotDeleteMainTaskError,DirtyWorktreeError,EmptyBranchDirtyWorktreeError,EmptyBranchError,ExtraRepoNotGitError,GitCommandFailedError,IllegalTransitionError,InvalidWorktreeNameError,LandConflictError,MainCheckoutDirtyError,MissingRefError,NotAGitRepoError,NotALinkedRepoError,REMOTE_PARENT_UNSUPPORTED_CODE,RemoteExtraUnsupportedError,RemoteParentUnsupportedError,ReparentRefusedError,RepoDuplicateError,TaskDeletingError,TaskNotFoundError,TooManyReposError,WorktreeNameTakenError,WorktreeRemoveFailedError,canonicalize,listWorktreeDirNames}from"./chunk-mmq6922s.js";import{detectLanguage}from"./chunk-hpay0ax8.js";import{resolvePreferredVendor}from"./chunk-h8t4xg1p.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{MULTI_REPO_CAP,childrenOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName}from"./chunk-2cg3b07h.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{addSavedRepo,getSavedRepos,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot}from"./chunk-rfp0ayra.js";import{projectRejection,rejectionReason}from"./chunk-7mwvvj46.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{pathIdentity,pathWithin,samePath}from"./chunk-pn5ygqn6.js";var TYPE_PREFIXES=new Set(["feat","feature","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","build","perf","style","revert","release"]),BRAND_TOKENS=new Set(["rove"]);function inferBranchStyle(names){let typed=new Map,bare=0;for(let raw of new Set(names)){let name=raw.trim();if(!name||name==="HEAD")continue;let slash=name.indexOf("/");if(slash===-1){bare+=1;continue}let prefix=name.slice(0,slash);if(TYPE_PREFIXES.has(prefix))typed.set(prefix,(typed.get(prefix)??0)+1)}let typedTotal=0;for(let n of typed.values())typedTotal+=n;if(typedTotal===0||typedTotal<bare)return{kind:"bare"};let best="",bestN=0;for(let[prefix,n]of typed)if(n>bestN||n===bestN&&(best===""||prefix<best))best=prefix,bestN=n;return{kind:"typed",defaultPrefix:best}}function slugTokens(title){return title.toLowerCase().replace(/[^a-z0-9]+/g,"-").split("-").filter((t)=>t.length>0&&!BRAND_TOKENS.has(t))}function capSlug(tokens){let slug="";for(let token of tokens){let candidate=slug?`${slug}-${token}`:token;if(candidate.length>32)return slug||token.slice(0,32);slug=candidate}return slug}function identitySlug(taskId){return`task-${taskId.slice(-6).toLowerCase()}`}function deriveConventionBranch(title,style,taskId){let tokens=slugTokens(title);if(style.kind==="typed"){let first=tokens[0];return`${first!==void 0&&TYPE_PREFIXES.has(first)?tokens.shift():style.defaultPrefix}/${capSlug(tokens)||identitySlug(taskId)}`}return capSlug(tokens)||identitySlug(taskId)}function uniqueBranchName(base,taken,taskId){let dirs=new Set;for(let name of taken)for(let i=name.indexOf("/");i>0;i=name.indexOf("/",i+1))dirs.add(name.slice(0,i));let isFree=(name)=>!taken.has(name)&&!dirs.has(name),segments=base.split("/"),root=segments.slice(0,-1).some((_,i)=>taken.has(segments.slice(0,i+1).join("/")))?segments.join("-"):base;if(isFree(root))return root;for(let n=2;n<=99;n+=1){let candidate=`${root}-${n}`;if(isFree(candidate))return candidate}return`${root}-${taskId.slice(-6).toLowerCase()}`}function planExtraRepos(primary,inputs){if(inputs.length===0)return[];if(1+inputs.length>MULTI_REPO_CAP)throw new TooManyReposError(1+inputs.length,MULTI_REPO_CAP);if(isRemoteRepoKey(primary))throw new RemoteExtraUnsupportedError(primary);let seen=new Set([canonPath(primary)]),names=new Set([repoNameOf(primary)]);return inputs.map((input)=>{if(isRemoteRepoKey(input.repo))throw new RemoteExtraUnsupportedError(input.repo);let{repo}=normalizeMainRepo(input.repo);if(!isGitRepo(repo))throw new ExtraRepoNotGitError(input.repo);if(seen.has(canonPath(repo)))throw new RepoDuplicateError(repo);seen.add(canonPath(repo));let name=uniqueRepoName(repoNameOf(repo),names);names.add(name);let baseRef=input.baseRef?.trim();return{name,repo,branch:"",worktreePath:"",...baseRef?{baseRef}:{}}})}async function rollbackWorktree(worktrees,created){try{await worktrees.remove(created.path,created.fresh?{force:!0,deleteBranch:!0,...created.fresh}:{force:!0})}catch(err){console.error(`[rove] ensureWorktree rollback failed for ${created.path}:`,err)}}async function extrasToMaterialise(worktrees,extras){let missing=[];for(let extra of extras??[])if(!extra.worktreePath||!await worktrees.pathExists(extra.worktreePath))missing.push(extra);return missing}function scaleProgress(onProgress,step,total){return onProgress&&((percent)=>onProgress(Math.floor((step+percent/100)/total*100)))}async function materialiseExtras(opts){let{worktrees,slugs,task}=opts,callerNamed=task.branch!=="",created=[],picked=[],done=new Map,missing=await extrasToMaterialise(worktrees,task.extraRepos);try{for(let[index,extra]of missing.entries()){if(extra.worktreePath)await worktrees.pruneWorktrees(extra.repo);let names=await worktrees.listBranchNames(extra.repo),branch=extra.branch||(callerNamed||!names.includes(opts.branch)?opts.branch:uniqueBranchName(opts.branch,new Set(names),task.id)),slug=await slugs.allocate(extra.repo);picked.push({repo:extra.repo,slug});let info=await worktrees.createForTask({repo:extra.repo,slug,branch,baseRef:extra.baseRef,onProgress:opts.progressFor(index)});created.push({path:info.path,...names.includes(branch)?{}:{fresh:{repo:extra.repo,branch}}}),done.set(extra.name,{...extra,branch,worktreePath:info.path})}}catch(err){for(let wt of created.reverse())await rollbackWorktree(worktrees,wt);for(let{repo,slug}of picked)slugs.cancel(repo,slug);throw err}return{extraRepos:(task.extraRepos??[]).map((e)=>done.get(e.name)??e),created,slugs:picked}}async function createTaskRow(deps,input){if(!input.repo)throw Error("createTask: repo is required");let extraRepos=planExtraRepos(normalizeMainRepo(input.repo).repo,input.extraRepos??[]),repo=(await deps.mainTasks.ensureIfEligible(input.repo,input.projectIntent??"explicit"))?.repo??normalizeMainRepo(input.repo).repo,title=sanitizeTaskTitle(input.title??PLACEHOLDER_TASK_TITLE)||PLACEHOLDER_TASK_TITLE,worktreeName=input.worktreeName?.trim();if(worktreeName)await deps.claimWorktreeName(repo,worktreeName);return await deps.store.create({repo,title,branch:input.branch??"",worktreePath:"",status:"backlog",kind:"task",vendor:input.vendor??DEFAULT_TASK_VENDOR,...input.command?.trim()?{command:input.command.trim()}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},...input.tier?.trim()?{tier:input.tier.trim()}:{},...input.groupId?{groupId:input.groupId}:{},...input.dispatcher?{dispatcher:input.dispatcher}:{},...input.parentTaskId?{parentTaskId:input.parentTaskId}:{},...input.cwdSubpath?{cwdSubpath:input.cwdSubpath}:{},...input.routine?{routine:input.routine}:{},...input.baseRef?.trim()?{baseRef:input.baseRef.trim()}:{},...extraRepos.length>0?{extraRepos}:{},...worktreeName?{worktreeName}:{}})}async function openDirectoryTaskRow(deps,input){if(!input.dir)throw Error("openDirectoryTask: dir is required");let dir=canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:dir,status:"backlog",kind:"dir",...input.scratch?{scratch:!0}:{},...input.noProject?{noProject:!0}:{},...input.routine?{routine:input.routine}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},vendor:input.vendor??resolvePreferredVendor()})}async function adoptScratchRepoRow(deps,id,repo){let task=deps.store.get(id);if(!task||task.kind!=="dir"||task.scratch!==!0)return;let dir=canonPath(repo);await deps.store.update(id,{repo:dir,worktreePath:dir,scratch:!1,title:titleFromRepo(dir)})}function baseRepoCtx(repo,deps){let basePath=deps.remoteBasePath(repo);return{exec:deps.execForRepo(repo),dir:basePath??repo}}async function landGit(exec,dir,args,opts){let r=await exec.run(["git",...args],{cwd:dir,env:opts?.readOnly?READ_ONLY_GIT_ENV:void 0});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}async function isDirty(exec,dir){return isDirtyOutput((await landGit(exec,dir,["status","--porcelain"],{readOnly:!0})).stdout)}async function landPreflight(task,deps=defaultExecDeps){let refuse=(pf,refusal)=>{let refused={...pf,refusal};return{...refused,message:landRefusalError(task,refused).message}},branch=task.branch.trim();if(!branch)throw Error(`landPreflight: task ${task.id} has no branch to land (never materialised)`);let{exec,dir}=baseRepoCtx(task.repo,deps),headOut=await landGit(exec,dir,["symbolic-ref","--short","HEAD"],{readOnly:!0}),landedOn=headOut.stdout.trim();if(headOut.exitCode!==0||!landedOn){let headCommit=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0}),detached=headCommit.exitCode===0&&headCommit.stdout.trim().length>0;return refuse({branch,landedOn:"",baseDir:dir},detached?"DETACHED_HEAD":"UNREADABLE_BASE")}if(landedOn===branch)return refuse({branch,landedOn,baseDir:dir},"SAME_BRANCH");let baseDirty=await isDirty(exec,dir),aheadOut=await landGit(exec,dir,["rev-list","--count",`${landedOn}..${branch}`],{readOnly:!0});if(aheadOut.exitCode!==0){let baseHead=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0});if(baseHead.exitCode!==0||!baseHead.stdout.trim())return refuse({branch,landedOn,baseDirty,baseDir:dir},"UNBORN_BASE");return refuse({branch,landedOn,baseDirty,baseDir:dir},baseDirty?"MAIN_CHECKOUT_DIRTY":"MISSING_REF")}let parsed=Number.parseInt(aheadOut.stdout.trim(),10),base={branch,landedOn,baseDirty,baseDir:dir,...Number.isFinite(parsed)?{ahead:parsed}:{}};if(baseDirty)return refuse(base,"MAIN_CHECKOUT_DIRTY");if(base.ahead!==0)return base;let worktreePath=task.worktreePath.trim();if(worktreePath){let manager=new GitWorktreeManager(deps),dirty=!1;try{dirty=await manager.isDirty(worktreePath)}catch{dirty=!1}if(dirty){let wtExec=deps.execForPath(worktreePath),files=parseDirtyPaths((await landGit(wtExec,worktreePath,["status","--porcelain"],{readOnly:!0})).stdout);return refuse({...base,dirtyFiles:files},"EMPTY_BRANCH_DIRTY_WORKTREE")}}return refuse(base,"EMPTY_BRANCH")}function landRefusalError(task,pf){switch(pf.refusal){case"DETACHED_HEAD":return Error(`landTask: base checkout at ${pf.baseDir} is in detached-HEAD state; check out a branch first`);case"UNREADABLE_BASE":return Error(`landTask: could not read HEAD of the base checkout at ${pf.baseDir} \u2014 is it still a git repo?`);case"UNBORN_BASE":return Error(`landTask: base checkout at ${pf.baseDir} is on '${pf.landedOn}' but has no commits yet, so there is nothing to merge '${pf.branch}' into; make the first commit there (or \`git merge --ff-only ${pf.branch}\`) and land again`);case"SAME_BRANCH":return Error(`landTask: base checkout is already on '${pf.branch}' \u2014 nothing to land onto`);case"MAIN_CHECKOUT_DIRTY":return new MainCheckoutDirtyError(task.repo,pf.baseDir);case"MISSING_REF":return new MissingRefError(pf.branch,pf.landedOn,pf.baseDir);case"EMPTY_BRANCH_DIRTY_WORKTREE":return new EmptyBranchDirtyWorktreeError(pf.branch,pf.landedOn,task.worktreePath.trim(),[...pf.dirtyFiles??[]]);case"EMPTY_BRANCH":return new EmptyBranchError(pf.branch,pf.landedOn)}}async function landTaskWithCleanup(task,opts,deps){if(task.kind==="main")throw Error("landTask: a main task has no branch to land");if(task.kind==="dir")throw Error("landTask: a directory task has no Rove-managed branch to land");let result=await landTask(task,{strategy:opts.strategy});return finishLanded(task,result,opts,deps)}async function finishLanded(task,result,opts,deps){let worktree=opts.removeWorktree===!1?void 0:await removeLandedWorktree(task,opts.callerCwd,deps),branchAnchor=null,branchKept,worktreeGone=!task.worktreePath.trim()||worktree?.removed===!0;if(opts.deleteBranch&&!worktreeGone)branchKept={reason:worktree?.reason??`worktree ${task.worktreePath} was kept, and still has the branch checked out`};else if(opts.deleteBranch){let outcome=await deps.worktrees.deleteBranch(task.repo,result.branch,{force:!0,onAnchor:(record)=>{branchAnchor=record}});if(!outcome.deleted)branchKept={reason:outcome.reason}}return{...result,...worktree?{worktree}:{},...branchAnchor?{branchAnchor}:{},...branchKept?{branchKept}:{}}}async function removeLandedWorktree(task,callerCwd,deps){let worktreePath=task.worktreePath.trim();if(!worktreePath)return{removed:!1,reason:"task has no worktree on disk (never materialised)"};let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(task.repo)))return{removed:!1,reason:"refusing to remove the base checkout"};if(deps.sharesWorktree?.(task))return{removed:!1,reason:`kept ${worktreePath}: other tasks still run in this directory`};if(callerCwd){if(pathWithin(wt,canonicalize(callerCwd))!==null)return{removed:!1,reason:`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`}}if(deps.tearDownSession)try{await deps.tearDownSession(task.id)}catch{}let residue;try{await deps.worktrees.remove(worktreePath,{onResidue:(r)=>{residue=r}})}catch(err){return{removed:!1,reason:errText(err)}}try{await deps.clearWorktreePath(task.id)}catch(err){return{removed:!0,reason:`worktree removed, but clearing the task's worktree path failed: ${errText(err)}`,...residue?{residue}:{}}}return{removed:!0,...residue?{residue}:{}}}function errText(err){return err instanceof Error?err.message:String(err)}async function conflictedFiles(exec,dir){return(await landGit(exec,dir,["diff","--name-only","--diff-filter=U"],{readOnly:!0})).stdout.split(`
3
+ `).map((l)=>l.trim()).filter((l)=>l.length>0)}async function landTask(task,input={},deps=defaultExecDeps){let strategy=input.strategy??"merge",preflight=await landPreflight(task,deps);if(preflight.refusal)throw landRefusalError(task,{...preflight,refusal:preflight.refusal});let{branch,landedOn}=preflight,{exec,dir}=baseRepoCtx(task.repo,deps);if(strategy==="squash"){if((await landGit(exec,dir,["merge","--squash",branch])).exitCode!==0){let files=await conflictedFiles(exec,dir);throw await landGit(exec,dir,["merge","--abort"]).catch(()=>{}),await landGit(exec,dir,["reset","--hard","HEAD"]).catch(()=>{}),new LandConflictError(task.id,branch,files)}let commit=await landGit(exec,dir,["commit","--no-edit","-m",`Land ${branch} (squash)`]);if(commit.exitCode!==0){if((await landGit(exec,dir,["diff","--cached","--quiet"],{readOnly:!0})).exitCode===0)throw await landGit(exec,dir,["reset","--hard","HEAD"]).catch(()=>{}),Error(`landTask: '${branch}' has nothing to land onto '${landedOn}' (already merged or empty)`);throw new GitCommandFailedError(`commit (squash-landing '${branch}' onto '${landedOn}')`,commit.stderr,"the squashed merge is left STAGED in the base checkout \u2014 fix the cause and `git commit` it, or `git reset --hard HEAD` to discard")}}else{let before=(await landGit(exec,dir,["rev-parse","HEAD"],{readOnly:!0})).stdout.trim(),merge=await landGit(exec,dir,["merge","--no-ff","-m",`Land ${branch}`,branch]);if(merge.exitCode!==0){let files=await conflictedFiles(exec,dir);if(await landGit(exec,dir,["merge","--abort"]).catch(()=>{}),files.length===0)throw new GitCommandFailedError(`merge --no-ff (landing '${branch}' onto '${landedOn}')`,merge.stderr,"the merge was aborted, so the base checkout is unchanged");throw new LandConflictError(task.id,branch,files)}let after=(await landGit(exec,dir,["rev-parse","HEAD"],{readOnly:!0})).stdout.trim();if(before===after)throw Error(`landTask: '${branch}' has nothing to land onto '${landedOn}' (already merged or empty)`)}let shaOut=await landGit(exec,dir,["rev-parse","--short","HEAD"],{readOnly:!0});return{branch,strategy,landedOn,commit:shaOut.stdout.trim()}}function viewOf(task,repo){let{baseRef:_primaryBase,...rest}=task;return{...rest,repo:repo.repo,branch:repo.branch,worktreePath:repo.worktreePath,...repo.baseRef?{baseRef:repo.baseRef}:{}}}function codeOf(message){return/^([A-Z][A-Z0-9_]{2,}): /.exec(message)?.[1]}async function contentLanded(view,landedOn,branch,deps){let{exec,dir}=baseRepoCtx(view.repo,deps),merged=await landGit(exec,dir,["merge-tree","--write-tree",landedOn,branch],{readOnly:!0});if(merged.exitCode!==0)return!1;let base=await landGit(exec,dir,["rev-parse",`${landedOn}^{tree}`],{readOnly:!0}),tree=merged.stdout.split(`
4
+ `)[0]?.trim();return base.exitCode===0&&!!tree&&tree===base.stdout.trim()}async function probeOne(task,repo,deps){let view=viewOf(task,repo);if(!repo.branch.trim()){let row={name:repo.name,status:"skipped",branch:"",landedOn:"",baseDir:repo.repo,message:"never materialised \u2014 nothing to land"};return{repo,view,row}}let pf=await landPreflight(view,deps);if(pf.refusal==="MISSING_REF"&&!repo.worktreePath.trim()){let row={...pf,name:repo.name,status:"skipped",message:`branch '${pf.branch}' is gone and the worktree was already removed \u2014 landed earlier`};return{repo,view,row}}if(!pf.refusal&&pf.ahead!==0&&await contentLanded(view,pf.landedOn,pf.branch,deps)){let row={...pf,name:repo.name,status:"skipped",refusal:"EMPTY_BRANCH",message:`its changes are already on ${pf.landedOn} \u2014 landed earlier`};return{repo,view,row}}let status=!pf.refusal?"ready":pf.refusal==="EMPTY_BRANCH"?"skipped":"refused";return{repo,view,row:{...pf,name:repo.name,status}}}async function probeAll(task,only,deps){let probed=[];for(let repo of pickRepos(task,only))probed.push(await probeOne(task,repo,deps));return probed}async function landPreflightAll(task,only,deps=defaultExecDeps){let rows=(await probeAll(task,only,deps)).map((p)=>p.row),head=rows.find((r)=>r.status==="refused")??rows.find((r)=>r.status==="ready")??rows[0];if(!head)throw Error("landPreflight: task has no repos");let{name:_name,status:_status,...top}=head,nothingToLand=rows.every((r)=>r.status==="skipped");return{...top,...nothingToLand&&!top.refusal?{refusal:"EMPTY_BRANCH"}:{},repos:rows}}function pendingRow(p){let{row}=p;if(row.status==="skipped"){let reason=row.refusal==="EMPTY_BRANCH"&&row.ahead===0?`nothing ahead of ${row.landedOn} \u2014 already landed or untouched`:row.message;return{name:row.name,status:"skipped",branch:row.branch,landedOn:row.landedOn,...reason?{error:reason}:{}}}return{name:row.name,status:"pending",branch:row.branch,landedOn:row.landedOn,...row.ahead===void 0?{}:{ahead:row.ahead}}}function summarise(strategy,results,stopped){let lead=results.find((r)=>r.status==="landed")??results.find((r)=>r.status==="refused")??results[0];return{branch:lead?.branch??"",strategy,landedOn:lead?.landedOn??"",commit:lead?.commit??"",...lead?.worktree?{worktree:lead.worktree}:{},...lead?.branchAnchor?{branchAnchor:lead.branchAnchor}:{},...lead?.branchKept?{branchKept:lead.branchKept}:{},repos:results,...stopped?{stopped}:{}}}async function landTaskAll(task,opts,deps,only){let strategy=opts.strategy??"merge",probed=await probeAll(task,only,defaultExecDeps),results=probed.map(pendingRow),refused=probed.findIndex((p)=>p.row.status==="refused");if(refused>=0){let{row}=probed[refused],code=row.refusal??"REFUSED",message=row.message??code;return results[refused]={...results[refused],name:row.name,status:"refused",code,error:message},summarise(strategy,results,{repo:row.name,code,message})}if(!probed.some((p)=>p.row.status==="ready")){let first=probed.find((p)=>p.row.refusal);if(first?.row.refusal)throw landRefusalError(first.view,{...first.row,refusal:first.row.refusal});throw Error("landTask: task has no branch to land (never materialised)")}let stopped;for(let[i,p]of probed.entries()){if(p.row.status!=="ready"||stopped)continue;try{let merged=await landTask(p.view,{strategy});results[i]={name:p.repo.name,status:"landed",branch:merged.branch,landedOn:merged.landedOn,commit:merged.commit,...p.row.ahead===void 0?{}:{ahead:p.row.ahead}}}catch(err){let message=errorMessage(err),conflict=err instanceof LandConflictError,code=conflict?"LAND_CONFLICT":codeOf(message)??"LAND_FAILED";results[i]={name:p.repo.name,status:conflict?"conflict":"failed",branch:p.row.branch,landedOn:p.row.landedOn,code,error:message},stopped={repo:p.repo.name,code,message}}}if(stopped)return summarise(strategy,results,stopped);let selected=new Set(probed.map((p)=>p.repo.name)),othersOpen=only!==void 0&&pickRepos(task).some((r)=>!selected.has(r.name)&&r.worktreePath.trim());for(let[i,p]of probed.entries()){let row=results[i];if(!p.repo.branch.trim()||row.status!=="landed"&&row.status!=="skipped")continue;if(row.status==="skipped"&&p.row.refusal==="MISSING_REF")continue;if(p.repo.primary&&othersOpen){results[i]={...row,worktree:{removed:!1,reason:"kept until every repo has landed: other repos of this task still have worktrees"},...opts.deleteBranch?{branchKept:{reason:"kept until every repo has landed: other repos of this task still have worktrees"}}:{}};continue}let repoDeps={worktrees:deps.worktrees,tearDownSession:p.repo.primary?deps.tearDownSession:void 0,clearWorktreePath:(id)=>deps.clearRepoWorktreePath(id,p.repo.name),sharesWorktree:()=>deps.sharesRepoWorktree(task,p.repo)},done=await finishLanded(p.view,{branch:p.row.branch,strategy,landedOn:p.row.landedOn,commit:row.commit??""},opts,repoDeps);results[i]={...row,...done.worktree&&p.view.worktreePath?{worktree:done.worktree}:{},...done.branchAnchor?{branchAnchor:done.branchAnchor}:{},...done.branchKept?{branchKept:done.branchKept}:{}}}return summarise(strategy,results,void 0)}class MainTaskCoordinator{store;forgetWorktree;locks=new Map;constructor(store,forgetWorktree){this.store=store;this.forgetWorktree=forgetWorktree}async ensure(repo){let task=await this.ensureIfEligible(repo,"explicit");if(task)return task;let{repo:normalizedRepo}=normalizeMainRepo(repo),rejected=projectRejection(normalizedRepo,isGitRepo,"explicit")??"notGitRepo";throw Error(`cannot add ${normalizedRepo} as a project: ${rejectionReason(rejected)}`)}async ensureIfEligible(repo,intent="derived"){let{repo:normalizedRepo,key}=normalizeMainRepo(repo),onThisRoot=(task)=>normalizeMainRepo(task.repo).key===key,existing=this.store.list().find((task)=>task.kind==="main"&&onThisRoot(task));if(existing)return existing;if(projectRejection(normalizedRepo,isGitRepo,intent))return null;let inflight=this.locks.get(key);if(inflight)return inflight;let promise=(async()=>{addSavedRepo(normalizedRepo,{intent:"explicit"});let adoptable=this.store.list().find((task)=>task.kind==="dir"&&task.scratch!==!0&&task.noProject!==!0&&!task.sharesWorkspaceOf&&onThisRoot(task));if(adoptable)return await this.store.update(adoptable.id,this.mainShape(normalizedRepo));return await this.store.create({...this.mainShape(normalizedRepo),status:"backlog",vendor:resolvePreferredVendor(normalizedRepo)})})();this.locks.set(key,promise);try{return await promise}finally{this.locks.delete(key)}}mainShape(normalizedRepo){return{kind:"main",title:titleFromRepo(normalizedRepo),repo:normalizedRepo,branch:"",worktreePath:repoWorkingDir(normalizedRepo)}}async forget(repo){if(!repo)throw Error("forgetProject: repo is required");let key=normalizeMainRepo(repo).key;for(let saved of getSavedRepos())if(normalizeMainRepo(saved).key===key)removeSavedRepo(saved);for(let task of this.store.list()){if(task.kind!=="main")continue;if(normalizeMainRepo(task.repo).key!==key)continue;await this.store.remove(task.id),this.forgetWorktree(task.id);for(let dependent of this.store.list()){if(dependent.parentTaskId!==task.id&&dependent.sharesWorkspaceOf!==task.id)continue;await this.store.update(dependent.id,{...dependent.parentTaskId===task.id?{parentTaskId:void 0}:{},...dependent.sharesWorkspaceOf===task.id?{sharesWorkspaceOf:void 0}:{}})}}}}import{isAbsolute,relative,resolve,sep}from"path";import{lstatSync,readdirSync,realpathSync}from"fs";import{join}from"path";function scanLinkedRepos(workspaceDir){let workspace,names;try{workspace=realpathSync(workspaceDir),names=readdirSync(workspaceDir)}catch{return[]}let out=[];for(let name of names.sort()){let entry=join(workspaceDir,name);try{if(!lstatSync(entry).isSymbolicLink())continue;let target=realpathSync(entry);if(pathWithin(workspace,target)!==null)continue;if(isGitRepo(target)&&samePath(resolveRepoRoot(target),target))out.push({name,path:target})}catch{}}return out}function sharedChildRow(parent,workspace,fields){let command=fields.command?.trim();return{repo:parent.repo,branch:parent.kind==="task"?parent.branch:"",worktreePath:workspace,status:"backlog",kind:parent.kind==="task"?"task":"dir",title:fields.title,vendor:fields.vendor,...command?{command}:{},...fields.dispatcher?{dispatcher:fields.dispatcher}:{},...parent.kind==="task"&&parent.baseRef?{baseRef:parent.baseRef}:{},...parent.cwdSubpath?{cwdSubpath:parent.cwdSubpath}:{},...fields.prompt?{prompt:fields.prompt}:{},parentTaskId:toTaskId(fields.parentTaskId),sharesWorkspaceOf:toTaskId(parent.sharesWorkspaceOf??parent.id)}}async function spawnChildTaskRow(deps,input){let found=deps.store.get(input.parentTaskId);if(!found)throw new TaskNotFoundError(input.parentTaskId);if(found.deletion)throw new TaskDeletingError(String(found.id));if(isRemoteRepoKey(found.repo))throw new RemoteParentUnsupportedError(String(found.id));if(input.isolateIn&&!input.worktree)throw Error("INVALID_SPAWN: isolateIn needs a worktree child");let workspace=found.kind==="task"?await deps.ensureWorktree(found.id):found.worktreePath,parent=deps.store.get(found.id)??found,cwd=taskCwd({worktreePath:workspace,cwdSubpath:parent.cwdSubpath}),links=scanLinkedRepos(cwd),inherit=!input.vendor&&!input.command,common={parentTaskId:lineageRootId(deps.store.list(),parent.id),title:sanitizeTaskTitle(input.title??PLACEHOLDER_TASK_TITLE)||PLACEHOLDER_TASK_TITLE,vendor:input.vendor??parent.vendor,command:input.command??(inherit?parent.command:void 0),dispatcher:input.dispatcher,prompt:input.prompt};if(!input.worktree)return{task:await deps.store.create(sharedChildRow(parent,workspace,common)),parentDirty:await isDirty2(deps,cwd),sharedLinks:links.map((l)=>l.name)};let source=input.isolateIn?requireLink(links,input.isolateIn,cwd):void 0,sourceDir=source?.path??cwd;if(!source&&!isGitRepo(sourceDir))throw new NotAGitRepoError(sourceDir);let top=source?sourceDir:gitOut(sourceDir,["rev-parse","--show-toplevel"]),sub=relative(canonPath(top),canonPath(sourceDir)),cwdSubpath=sub&&!sub.split(sep).includes("..")&&!isAbsolute(sub)?sub:void 0,baseRef=input.baseRef?.trim()||gitOut(sourceDir,["rev-parse","HEAD"]),repo=source||parent.kind==="dir"?resolveMainRepoRoot(sourceDir):parent.repo,parentDirty=await isDirty2(deps,sourceDir),child=await deps.createTask({repo,title:common.title,baseRef,vendor:common.vendor,command:common.command,dispatcher:common.dispatcher,parentTaskId:toTaskId(common.parentTaskId),cwdSubpath,projectIntent:"derived"});try{await deps.ensureWorktree(child.id)}catch(err){let partial=deps.store.get(child.id);if(partial?.worktreePath)await deps.worktrees.remove(partial.worktreePath,{force:!0,deleteBranch:!0,repo:partial.repo,branch:partial.branch}).catch((cleanup)=>console.error(`[rove] spawn rollback failed for ${partial.worktreePath}:`,cleanup));throw await deps.store.remove(child.id),err}if(input.prompt)await deps.store.update(child.id,{prompt:input.prompt});return{task:deps.store.get(child.id)??child,parentDirty,sharedLinks:source?[]:links.map((l)=>l.name)}}function requireLink(links,isolateIn,cwd){let name=isAbsolute(isolateIn)||isolateIn.includes("/")?relative(cwd,resolve(cwd,isolateIn)):isolateIn,link=links.find((l)=>l.name===name);if(!link)throw new NotALinkedRepoError(isolateIn,links.map((l)=>l.name));return link}function gitOut(cwd,args){return git(args,{cwd,readOnly:!0}).stdout.trim()}async function isDirty2(deps,dir){try{return(await deps.worktrees.dirtyPaths(dir)).length>0}catch{return!1}}async function createMigratedChildRow(deps,input){let parent=deps.store.get(input.parentTaskId);if(!parent)throw new TaskNotFoundError(input.parentTaskId);if(parent.deletion)throw new TaskDeletingError(String(parent.id));let inherit=!input.vendor&&!input.command,row=sharedChildRow(parent,parent.worktreePath,{parentTaskId:lineageRootId(deps.store.list(),parent.id),title:sanitizeTaskTitle(input.title)||PLACEHOLDER_TASK_TITLE,vendor:input.vendor??parent.vendor,command:input.command??(inherit?parent.command:void 0)});return await deps.store.create({...row,...input.ptyAlias?{ptyAlias:input.ptyAlias}:{}})}async function setPtyAliasRow(deps,id,alias){let task=deps.store.get(id);if(!task)throw new TaskNotFoundError(id);if(alias===null&&!task.ptyAlias)return;await deps.store.update(id,{ptyAlias:alias??void 0})}function promotableDirTasks(deps){let claimed=new Set(deps.tasks.filter((task)=>task.kind==="main").map((task)=>pathIdentity(task.repo))),seen=new Set,out=[];for(let task of deps.tasks){if(task.kind!=="dir"||task.scratch===!0||task.noProject===!0||task.sharesWorkspaceOf)continue;let path=task.repo,key=pathIdentity(path);if(!path||claimed.has(key)||seen.has(key))continue;if(!deps.isRepoRoot(path))continue;seen.add(key),out.push(task)}return out}function isLeaving(task){return task.deletion?.phase==="queued"||task.deletion?.phase==="running"}class TaskDeletionCoordinator{store;worktrees;forgetTask;onSalvage;onResidue;onBranchKept;pathLocks=new Map;constructor(store,worktrees,forgetTask,onSalvage,onResidue,onBranchKept){this.store=store;this.worktrees=worktrees;this.forgetTask=forgetTask;this.onSalvage=onSalvage;this.onResidue=onResidue;this.onBranchKept=onBranchKept}targets(id,opts){return opts?.cascade?subtreeIds(this.store.list(),String(id)):[String(id)]}async prepare(id,opts){let task=this.store.get(id);if(!task)return!1;if(task.kind==="main")throw new CannotDeleteMainTaskError;if(isLeaving(task))return!0;let keys=this.targets(task.id,opts).flatMap((targetId)=>{let target=this.store.get(targetId);return target&&target.kind!=="dir"?taskWorktreePaths(target).map(canonPath):[]});return this.withPathLocks([...new Set(keys)].sort(),()=>this.prepareLocked(task.id,opts))}async prepareLocked(id,opts){let task=this.store.get(id);if(!task||isLeaving(task))return task!==void 0;let force=opts?.force===!0,doomed=this.targets(task.id,opts).map((targetId)=>this.store.get(targetId)).filter((t)=>t!==void 0&&t.kind!=="main"&&!isLeaving(t)),leaving=new Set(doomed.map((t)=>String(t.id))),survivors=this.store.list().filter((t)=>!leaving.has(String(t.id))&&!isLeaving(t)),gated=new Set;for(let target of doomed){if(force||target.kind==="dir"||!target.worktreePath)continue;let primaryKey=canonPath(target.worktreePath);if(survivors.some((s)=>s.worktreePath&&canonPath(s.worktreePath)===primaryKey))continue;let repos=taskRepos(target).filter((r)=>r.worktreePath),found=[];for(let r of repos){let key=canonPath(r.worktreePath);if(gated.has(key))continue;gated.add(key);let finding=await this.probeDirty(r.worktreePath);if(finding)found.push({repo:r.name,...finding})}let[head,...rest]=found;if(head)throw new DirtyWorktreeError(target.id,head.ignored,head.dirty,repos.length>1?head.repo:void 0,rest)}for(let target of doomed)await this.store.update(target.id,{deletion:{phase:"queued",force,deleteBranch:opts?.deleteBranch===!0||target.deleteBranchPending===!0,requestedAt:new Date().toISOString()}});if(await this.transferOwnership(leaving),!opts?.cascade)await this.promoteChildren(task);return!0}async begin(id){let task=this.store.get(id);if(!task||!task.deletion||task.deletion.phase==="error")return!1;if(task.deletion.phase!=="running")await this.store.update(task.id,{deletion:{...task.deletion,phase:"running"}});return!0}async finish(id){let task=this.store.get(id);if(!task?.deletion||task.deletion.phase!=="running")return;let deletion=task.deletion,ownsDirectory=Boolean(task.worktreePath)&&task.kind!=="dir",extras=task.kind==="dir"?[]:(task.extraRepos??[]).filter((x)=>x.worktreePath),key=ownsDirectory?canonPath(task.worktreePath):null,keys=[...key?[key]:[],...extras.map((x)=>canonPath(x.worktreePath))];await this.withPathLocks([...new Set(keys)].sort(),async()=>{let shared=key!==null&&this.store.list().some((t)=>t.id!==task.id&&t.worktreePath&&canonPath(t.worktreePath)===key),removing;try{if(ownsDirectory&&!shared){if(extras.length>0)removing=taskRepos(task)[0]?.name;await this.removeWorktree(task,deletion,{path:task.worktreePath,repo:task.repo,branch:task.branch})}else if(ownsDirectory&&deletion.deleteBranch)await this.handBranchDeleteOn(task,key);for(let extra of extras){removing=extra.name,await this.removeWorktree(task,deletion,{path:extra.worktreePath,repo:extra.repo,branch:extra.branch});let current=this.store.get(task.id)?.extraRepos??[];await this.store.update(task.id,{extraRepos:current.map((x)=>x.name===extra.name?{...x,worktreePath:""}:x)})}}catch(cause){let failure=new WorktreeRemoveFailedError(task.id,removing?Error(`${removing}: ${errorMessage(cause)}`,{cause}):cause);throw await this.store.update(task.id,{deletion:{...deletion,phase:"error",error:errorMessage(failure)}}),failure}await this.store.remove(task.id),this.forgetTask(task.id)})}async deleteNow(id,opts){let targets=this.targets(id,opts);if(!await this.prepare(id,opts))return;let failure;for(let target of targets)try{if(await this.begin(target))await this.finish(target)}catch(err){failure??=err}if(failure)throw failure}async probeDirty(path){let dirty=[],ignored=[],probed=!0;try{dirty=await this.worktrees.dirtyPaths(path)}catch{probed=!1}if(probed&&dirty.length===0)ignored=await this.worktrees.ignoredWork(path);return dirty.length>0||ignored==="unknown"||ignored.length>0?{ignored,dirty}:null}async removeWorktree(task,deletion,target){await this.worktrees.remove(target.path,{force:deletion.force,deleteBranch:deletion.deleteBranch===!0,repo:target.repo,branch:target.branch,onSalvage:(record)=>{if(record)this.onSalvage?.(task.id,record,target.repo)},onResidue:(residue)=>this.onResidue?.(task.id,residue),onBranchKept:(kept)=>this.onBranchKept?.(task.id,kept)})}async handBranchDeleteOn(leaving,key){let holder=this.store.list().find((t)=>t.id!==leaving.id&&t.worktreePath&&canonPath(t.worktreePath)===key);if(holder&&isLeaving(holder))await this.store.update(holder.id,{deletion:{...holder.deletion,deleteBranch:!0}});else if(holder)await this.store.update(holder.id,{deleteBranchPending:!0});this.onBranchKept?.(leaving.id,{branch:leaving.branch,reason:"another task still uses this branch"})}async transferOwnership(leaving){for(let ownerId of leaving){let remaining=this.store.list().filter((t)=>t.sharesWorkspaceOf===ownerId&&!leaving.has(String(t.id))&&!isLeaving(t)),[heir,...rest]=remaining;if(!heir)continue;let extraRepos=this.store.get(ownerId)?.extraRepos;if(await this.store.update(heir.id,{sharesWorkspaceOf:void 0,...extraRepos?{extraRepos}:{}}),extraRepos)await this.store.update(ownerId,{extraRepos:void 0});for(let sharer of rest)await this.store.update(sharer.id,{sharesWorkspaceOf:heir.id})}}async promoteChildren(deleted){let ungrouped=deleted.kind==="dir"&&(deleted.scratch===!0||deleted.noProject===!0);for(let child of this.store.list().filter((t)=>t.parentTaskId===deleted.id)){let keep=ungrouped&&child.kind==="dir"?{noProject:!0}:{};await this.store.update(child.id,{parentTaskId:deleted.parentTaskId,...keep})}}async withPathLocks(keys,fn){let[first,...rest]=keys;if(first===void 0)return fn();return this.withPathLock(first,()=>this.withPathLocks(rest,fn))}async withPathLock(key,fn){if(key===null)return fn();let previous=this.pathLocks.get(key)??Promise.resolve(),release,turn=new Promise((resolve2)=>{release=resolve2}),tail=previous.then(()=>turn);this.pathLocks.set(key,tail),await previous;try{return await fn()}finally{if(release(),this.pathLocks.get(key)===tail)this.pathLocks.delete(key)}}}class TaskEditor{store;worktrees;constructor(store,worktrees){this.store=store,this.worktrees=worktrees}requireTask(id){let task=this.store.get(id);if(!task)throw new TaskNotFoundError(String(id));return task}async setTitle(id,title){let trimmed=sanitizeTaskTitle(title);if(!trimmed)throw Error("setTitle: title is required (empty or whitespace-only rejected)");let task=this.requireTask(id);if(task.title===trimmed&&task.scratch!==!0)return;await this.store.update(task.id,{title:trimmed,...task.scratch===!0?{scratch:!1}:{}}),await this.followBranchToTitle(task,trimmed)}async followBranchToTitle(taskBefore,newTitle){if(taskBefore.kind==="main"||!taskBefore.worktreePath)return;if(!isPlaceholderDerivedBranch(taskBefore.branch,taskBefore.id))return;try{let names=await this.worktrees.listBranchNames(taskBefore.repo),base=deriveConventionBranch(newTitle,inferBranchStyle(names),taskBefore.id);if(base===taskBefore.branch)return;if(await this.worktrees.branchHasUpstream(taskBefore.worktreePath,taskBefore.branch))return;let taken=new Set(names.filter((n)=>n!==taskBefore.branch)),nextBranch=uniqueBranchName(base,taken,taskBefore.id);await this.setBranch(taskBefore.id,nextBranch)}catch(err){console.error(`[rove] follow-branch-to-title failed for ${taskBefore.id}:`,err)}}async setBranch(id,branch){let trimmed=branch.trim();if(!trimmed)throw Error("setBranch: branch is required (empty or whitespace-only rejected)");let task=this.requireTask(id);if(task.kind==="main")throw Error("setBranch: a main task tracks the repo's own branch; rename it with git directly");if(task.kind==="dir")throw Error("setBranch: a directory task tracks its own checkout; rename branches with git directly");if(task.branch===trimmed)return;let extras=(task.extraRepos??[]).filter((x)=>x.worktreePath&&x.branch===task.branch),renamed=[];try{if(task.worktreePath)await this.worktrees.renameBranch(task.worktreePath,task.branch,trimmed),renamed.push({path:task.worktreePath,from:task.branch});for(let extra of extras)await this.worktrees.renameBranch(extra.worktreePath,extra.branch,trimmed),renamed.push({path:extra.worktreePath,from:extra.branch})}catch(err){for(let done of renamed.reverse())await this.worktrees.renameBranch(done.path,trimmed,done.from).catch(()=>{});throw err}if(await this.store.update(task.id,{branch:trimmed,...task.extraRepos?{extraRepos:task.extraRepos.map((x)=>extras.includes(x)?{...x,branch:trimmed}:x)}:{}}),!task.worktreePath)return;for(let holder of this.store.list()){if(holder.id===task.id||holder.kind!=="task"||holder.branch!==task.branch)continue;if(holder.worktreePath&&samePath(holder.worktreePath,task.worktreePath))await this.store.update(holder.id,{branch:trimmed})}}async observeLanguage(id,text){let observed=detectLanguage(text);if(!observed)return;let task=this.requireTask(id);if(task.observedLanguage===observed)return;await this.store.update(task.id,{observedLanguage:observed})}async setVendor(id,vendor,effort,model){let task=this.requireTask(id),switching=task.vendor!==vendor,effortArg=effort??(switching?"":void 0),modelArg=model??(switching?"":void 0),nextEffort=effortArg?.trim()?effortArg.trim():void 0,effortChanges=effortArg!==void 0&&task.modelEffort!==nextEffort,nextModel=modelArg?.trim()?modelArg.trim():void 0,modelChanges=modelArg!==void 0&&task.model!==nextModel;if(!switching&&!effortChanges&&!modelChanges)return;await this.store.update(task.id,{vendor,...effortArg!==void 0?{modelEffort:nextEffort}:{},...modelArg!==void 0?{model:nextModel}:{}})}async setCommand(id,command,vendor){let trimmed=command.trim();if(!trimmed)throw Error("setCommand: command is required (empty or whitespace-only rejected)");let task=this.requireTask(id),switching=vendor!==void 0&&task.vendor!==vendor;if(task.command===trimmed&&!switching)return;await this.store.update(task.id,{command:trimmed,...switching?{vendor,model:void 0,modelEffort:void 0}:{}})}async setPinned(id,pinned){let task=this.requireTask(id);if(task.kind==="main")return;let next=pinned??!task.pinned;if((task.pinned??!1)===next)return;await this.store.update(task.id,{pinned:next})}async setParent(id,parentId,replyTab){let task=this.requireTask(id);if(task.deletion)throw new TaskDeletingError(String(task.id));if(task.kind==="main")throw new ReparentRefusedError("TASK_NOT_MOVABLE",`${task.id} is a project's main task \u2014 it is the project`);if(task.routine)throw new ReparentRefusedError("TASK_NOT_MOVABLE",`${task.id} is a routine session; the sidebar keeps those in the routine fold`);if(isRemoteRepoKey(task.repo))throw new ReparentRefusedError(REMOTE_PARENT_UNSUPPORTED_CODE,`task ${task.id} lives on a remote project \u2014 re-parent it from that machine's rove`);let tasks=this.store.list();if(parentId===null){let oldParent=task.parentTaskId,dispatchedFromOldTree=oldParent!==void 0&&task.dispatcher!==void 0&&subtreeIds(tasks,oldParent).includes(task.dispatcher.taskId);return await this.store.update(task.id,{parentTaskId:void 0,...dispatchedFromOldTree?{dispatcher:void 0}:{}}),{parentTaskId:null,dispatcher:(dispatchedFromOldTree?void 0:task.dispatcher)??null,moved:[]}}if(parentId===task.id)throw new ReparentRefusedError("PARENT_IS_SELF",`${task.id} cannot be its own parent`);let parent=this.store.get(parentId);if(!parent)throw new ReparentRefusedError("PARENT_NOT_FOUND",`no task ${parentId} on this machine \u2014 a parent must live beside its child`);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(isRemoteRepoKey(parent.repo))throw new ReparentRefusedError(REMOTE_PARENT_UNSUPPORTED_CODE,`task ${parent.id} lives on a remote project \u2014 re-parent under it from that machine's rove`);if(subtreeIds(tasks,task.id).includes(parent.id))throw new ReparentRefusedError("PARENT_CYCLE",`${parent.id} is already a descendant of ${task.id}`);let root=lineageRootId(tasks,parent.id),dispatcher=task.dispatcher?.taskId===parent.id&&replyTab===void 0?task.dispatcher:{taskId:parent.id,tabId:replyTab??"tab-1"};await this.store.update(task.id,{parentTaskId:toTaskId(root),dispatcher});let moved=childrenOf(tasks,task.id).map((child)=>child.id);for(let child of moved)await this.store.update(child,{parentTaskId:toTaskId(root)});return{parentTaskId:root,dispatcher,moved}}async setArchived(id,archived){let task=this.requireTask(id);if(task.kind==="main")throw Error("a project's main checkout cannot be archived");if((task.archived??!1)===archived)return;await this.store.update(task.id,{archived:archived||void 0})}async setRequireReport(id,required){let task=this.requireTask(id);if((task.requireReport??!1)===required)return;await this.store.update(task.id,{requireReport:required||void 0})}async moveTask(id,delta){let task=this.requireTask(id);await this.store.move(task.id,delta,this.movePartition(task))}async moveTaskToTop(id){let task=this.requireTask(id);await this.store.moveToFront(task.id,this.movePartition(task))}movePartition(task){let isMain=task.kind==="main";return this.store.list().filter((t)=>isMain?(t.kind??"task")==="main":(t.kind??"task")!=="main"&&samePath(t.repo,task.repo)&&(t.pinned??!1)===(task.pinned??!1)).map((t)=>String(t.id))}async setStatus(id,status){let task=this.requireTask(id);if(task.status===status)return;if(task.status==="done"&&status==="error"||task.status==="error"&&status==="done")throw new IllegalTransitionError(task.status,status,task.id);await this.store.update(task.id,{status})}async setWorkerReport(id,report){let task=this.requireTask(id),next={...task.report,...report,at:new Date().toISOString()};await this.store.update(task.id,{report:next})}async setPRStatus(id,prStatus,repoName){let task=this.requireTask(id),extra=repoName?task.extraRepos?.find((x)=>x.name===repoName):void 0;if(repoName&&!extra)return;let current=extra?extra.prStatus:task.prStatus;if((current?.lastError??null)===(prStatus?.lastError??null)&&samePrStatus(current,prStatus??void 0))return;if(!extra){await this.store.update(task.id,{prStatus:prStatus??void 0});return}let latest=this.store.get(task.id)?.extraRepos??[];await this.store.update(task.id,{extraRepos:latest.map((x)=>x.name===repoName?{...x,prStatus:prStatus??void 0}:x)})}async setQuotaResume(id,state){let task=this.requireTask(id);if((task.quotaResume?.resumeAt??null)===(state?.resumeAt??null))return;await this.store.update(task.id,{quotaResume:state??void 0})}async setLinkedWorkItem(id,item){let task=this.requireTask(id);if((task.linkedWorkItem?.url??null)===(item?.url??null))return;await this.store.update(task.id,{linkedWorkItem:item??void 0})}async setPrompt(id,prompt){if(prompt.trim().length===0)throw Error("setPrompt: prompt is required (empty or whitespace-only rejected)");let task=this.requireTask(id);if(task.prompt===prompt)return;await this.store.update(task.id,{prompt})}}import{basename}from"path";var ANIMAL_NAMES=["aardvark","addax","adder","agouti","albatross","alpaca","anaconda","anchovy","anglerfish","anole","anteater","antelope","ape","argali","armadillo","avocet","axolotl","baboon","badger","banteng","barracuda","basilisk","bass","bat","beagle","bear","beaver","bee","beetle","beluga","betta","bison","blackbird","blenny","bluebird","bluegill","boar","bobcat","bonito","bovid","buffalo","bullfrog","bunting","bushbuck","butterfly","buzzard","caiman","camel","canary","capybara","caracal","cardinal","caribou","carp","cassowary","caterpillar","catfish","chameleon","chamois","char","cheetah","chickadee","chimp","chinchilla","chipmunk","chough","cicada","civet","clam","clownfish","cobra","cockatoo","condor","coot","copperhead","coral","cormorant","cougar","coyote","crab","crane","crawfish","crayfish","cricket","crocodile","crow","cuckoo","curlew","cuttlefish","deer","dikdik","dingo","dolphin","donkey","dormouse","dotterel","dove","dragonfly","dromedary","duck","dugong","dunlin","eagle","echidna","eel","egret","eider","eland","elephant","elk","emu","ermine","falcon","fawn","ferret","finch","firefly","flamingo","flounder","fox","frog","gadwall","gannet","gaur","gazelle","gecko","gemsbok","gerbil","gharial","gibbon","gnu","goat","goby","godwit","goldfish","goose","gopher","goral","gorilla","goshawk","grackle","grasshopper","grayling","grebe","grouse","guanaco","guillemot","guineafowl","guppy","halibut","hammerhead","hamster","hare","harrier","hartebeest","hawk","hedgehog","heron","herring","hippo","hornbill","hornet","horse","hummingbird","hyena","ibex","ibis","iguana","impala","indri","jacana","jackal","jaguar","jay","jellyfish","jerboa","junco","kakapo","kangaroo","kestrel","killdeer","kingfisher","kinglet","kite","kiwi","koala","kookaburra","krait","krill","kudu","ladybug","lamprey","langur","lapwing","lark","lemming","lemur","leopard","limpet","lion","lionfish","lizard","llama","lobster","locust","loon","lorikeet","loris","lynx","macaque","macaw","mackerel","magpie","mallard","mamba","mammoth","manatee","mandrill","manta","mantis","marlin","marmoset","marmot","marten","meerkat","merganser","mink","minnow","mole","mongoose","monitor","monkey","moose","moth","mouflon","mouse","mudpuppy","mule","muntjac","musk","muskox","muskrat","mussel","mustang","narwhal","newt","nightingale","numbat","nuthatch","nyala","ocelot","octopus","okapi","opossum","orangutan","orca","oriole","oryx","osprey","ostrich","otter","owl","oyster","oystercatcher","paca","panda","pangolin","panther","parakeet","parrot","parrotfish","partridge","peafowl","pelican","penguin","perch","petrel","pheasant","pigeon","pika","pike","pintail","pipefish","platypus","plover","pollock","pony","porcupine","porpoise","possum","ptarmigan","puffin","puma","pupfish","python","quail","quetzal","quokka","quoll","rabbit","raccoon","rail","rat","rattler","raven","ray","redpoll","reindeer","remora","rhino","roadrunner","robin","rook","sable","sailfish","salamander","salmon","sandpiper","sardine","scallop","scaup","scorpion","seahorse","seal","serval","shark","shearwater","shrew","shrike","shrimp","siskin","sitatunga","skate","skink","skua","skunk","sloth","smelt","snail","snipe","solenodon","sparrow","spider","springbok","squid","squirrel","starfish","starling","stilt","stingray","stoat","stork","sunbird","sunfish","swallow","swan","swift","swordfish","tahr","takin","tamarin","tanager","tapir","tarantula","tarpon","tarsier","teal","tenrec","terrapin","tern","tetra","thrasher","thrush","tiger","toad","tortoise","toucan","treecreeper","treefrog","trout","tuatara","tuna","turkey","turtle","urchin","urial","vicuna","viper","vole","vulture","wagtail","wallaby","walleye","walrus","warbler","warthog","waterbuck","weasel","wildebeest","wolf","wolverine","wombat","woodcock","woodpecker","wrasse","wren","yak","zebra","zebu","zorilla"];class SlugAllocator{activeSlugs;random;pool;pendingByRepo=new Map;chain=Promise.resolve();constructor(activeSlugs,options={}){this.activeSlugs=activeSlugs;if(this.random=options.random??Math.random,this.pool=options.pool??ANIMAL_NAMES,this.pool.length===0)throw Error("SlugAllocator: animal pool cannot be empty")}async allocate(repo){let previous=this.chain,release;this.chain=new Promise((resolve2)=>{release=resolve2}),await previous;try{return await this.pickLocked(repo)}finally{release()}}async claim(repo,slug){let previous=this.chain,release;this.chain=new Promise((resolve2)=>{release=resolve2}),await previous;try{if((await this.occupiedSlugs(repo)).has(slug))throw new WorktreeNameTakenError(slug);return this.addPending(repo,slug),slug}finally{release()}}commit(repo,slug){this.deletePending(repo,slug)}cancel(repo,slug){this.deletePending(repo,slug)}async pickLocked(repo){let occupied=await this.occupiedSlugs(repo),candidates=this.pool.filter((n)=>!occupied.has(n));if(candidates.length>0){let pick=candidates[Math.floor(this.random()*candidates.length)];return this.addPending(repo,pick),pick}let base=this.pool[Math.floor(this.random()*this.pool.length)];for(let v=2;;v++){let candidate=`${base}-v${v}`;if(!occupied.has(candidate))return this.addPending(repo,candidate),candidate}}async occupiedSlugs(repo){let set=new Set(this.pendingByRepo.get(repo)??[]);for(let slug of this.activeSlugs(repo))if(slug)set.add(slug);for(let dir of await listWorktreeDirNames(repo))set.add(dir);return set}addPending(repo,slug){let pending=this.pendingByRepo.get(repo);if(!pending)pending=new Set,this.pendingByRepo.set(repo,pending);pending.add(slug)}deletePending(repo,slug){let pending=this.pendingByRepo.get(repo);if(!pending)return;if(pending.delete(slug),pending.size===0)this.pendingByRepo.delete(repo)}}var WORKTREE_NAME_RE=/^[A-Za-z0-9_][A-Za-z0-9._-]*$/;class WorktreeCoordinator{store;worktrees;canonPath;ensureProject;slugs;worktreeLocks=new Map;adoptLocks=new Map;reservedBranches=new Set;constructor(store,worktrees,canonPath2,ensureProject){this.store=store,this.worktrees=worktrees,this.canonPath=canonPath2,this.ensureProject=ensureProject,this.slugs=new SlugAllocator((repo)=>this.store.list().filter((t)=>t.kind!=="main").flatMap((t)=>[...samePath(t.repo,repo)?[t.worktreePath]:[],...(t.extraRepos??[]).filter((x)=>samePath(x.repo,repo)).map((x)=>x.worktreePath)]).map((path)=>path.match(/([^/\\]+)[/\\]*$/)?.[1]??"").filter((s)=>s.length>0))}async claimWorktreeName(repo,name){if(!WORKTREE_NAME_RE.test(name))throw new InvalidWorktreeNameError(name);return await this.slugs.claim(repo,name)}forget(id){this.worktreeLocks.delete(id)}async ensure(task,onProgress){let inflight=this.worktreeLocks.get(task.id);if(inflight)return inflight;let work=this.createWorktree(task,onProgress);this.worktreeLocks.set(task.id,work);try{return await work}finally{this.worktreeLocks.delete(task.id)}}async createWorktree(task,onProgress){let extrasMissing=await extrasToMaterialise(this.worktrees,task.extraRepos);if(task.worktreePath&&extrasMissing.length===0)return task.worktreePath;let total=(task.worktreePath?0:1)+extrasMissing.length,primary=task.worktreePath?void 0:await this.createPrimary(task,scaleProgress(onProgress,0,total)),branch=primary?.branch??task.branch,undoPrimary=async()=>{if(!primary)return;await rollbackWorktree(this.worktrees,{path:primary.path,...primary.fresh?{fresh:{repo:task.repo,branch}}:{}}),this.slugs.cancel(task.repo,primary.slug)},extras;try{if(extrasMissing.length>0)extras=await materialiseExtras({worktrees:this.worktrees,slugs:this.slugs,task,branch,progressFor:(i)=>scaleProgress(onProgress,(primary?1:0)+i,total)})}catch(err){throw await undoPrimary(),err}try{await this.store.update(task.id,{...primary?{worktreePath:primary.path,branch}:{},...extras?{extraRepos:extras.extraRepos}:{}})}catch(err){for(let wt of[...extras?.created??[]].reverse())await rollbackWorktree(this.worktrees,wt);for(let{repo,slug}of extras?.slugs??[])this.slugs.cancel(repo,slug);throw await undoPrimary(),err}if(primary)this.slugs.commit(task.repo,primary.slug);for(let{repo,slug}of extras?.slugs??[])this.slugs.commit(repo,slug);return primary?.path??task.worktreePath}async createPrimary(task,onProgress){let slug=task.worktreeName||await this.slugs.allocate(task.repo),branch=task.branch||await this.deriveAutoBranch(task),baseRef=task.baseRef;try{let fresh=!(await this.worktrees.listBranchNames(task.repo)).includes(branch);return{path:(await this.worktrees.createForTask({repo:task.repo,slug,branch,baseRef,onProgress})).path,branch,slug,fresh}}catch(err){throw this.slugs.cancel(task.repo,slug),err}finally{this.reservedBranches.delete(branch)}}async deriveAutoBranch(task){let names=await this.worktrees.listBranchNames(task.repo),base=deriveConventionBranch(task.title,inferBranchStyle(names),task.id),taken=new Set([...names,...this.reservedBranches]),branch=uniqueBranchName(base,taken,task.id);return this.reservedBranches.add(branch),branch}async discoverAdoptable(repo){let all=await this.worktrees.listAll(repo),linked=new Set(this.store.list().flatMap((t)=>taskWorktreePaths(t)).map((p)=>this.canonPath(p)));return all.filter((wt)=>!linked.has(this.canonPath(wt.path)))}async adopt(input){let target=this.canonPath(input.worktreePath),inflight=this.adoptLocks.get(target);if(inflight)return inflight;let work=this.adoptLocked(input,target);this.adoptLocks.set(target,work);try{return await work}finally{this.adoptLocks.delete(target)}}async adoptLocked(input,target){let holders=this.store.list().filter((t)=>taskWorktreePaths(t).some((p)=>this.canonPath(p)===target)),existing=holders.find((t)=>!t.sharesWorkspaceOf)??holders[0];if(existing){if(input.ifExists==="return")return existing;throw Error(`adoptWorktree: ${input.worktreePath} is already adopted as a task`)}let match=(await this.worktrees.listAdoptablePaths(input.repo)).find((wt)=>this.canonPath(wt.path)===target);if(!match)throw Error(`adoptWorktree: ${input.worktreePath} is not an adoptable git worktree of ${input.repo} (unknown, detached, or the main checkout)`);let branch=input.branch?.trim()||match.branch,title=(input.title??basename(match.path)).trim()||PLACEHOLDER_TASK_TITLE;return await this.ensureProject(input.repo),this.store.create({repo:input.repo,title,branch,worktreePath:match.path,status:"backlog",kind:"task",vendor:input.vendor??DEFAULT_TASK_VENDOR})}}class Orchestrator{store;worktrees;worktreeCoordinator;editor;deletions;tasksAcc;activeTaskAcc;unsubscribeStore;mainTasks;tearDownSession;constructor(deps){this.store=deps.store,this.worktrees=deps.worktrees,this.tearDownSession=deps.tearDownSession,this.worktreeCoordinator=new WorktreeCoordinator(this.store,this.worktrees,canonPath,(repo)=>this.mainTasks.ensureIfEligible(repo)),this.mainTasks=new MainTaskCoordinator(this.store,(id)=>this.worktreeCoordinator.forget(id)),this.editor=new TaskEditor(this.store,this.worktrees),this.deletions=new TaskDeletionCoordinator(this.store,this.worktrees,(id)=>this.worktreeCoordinator.forget(id),deps.onSalvage,deps.onWorktreeResidue,deps.onBranchKept),this.tasksAcc=createStateCell(this.store.list());let persistedFocus=readLastActiveTaskId();this.activeTaskAcc=createStateCell(persistedFocus&&this.store.get(persistedFocus)?persistedFocus:null),this.unsubscribeStore=this.store.subscribe((snapshot)=>{this.tasksAcc.set(snapshot.slice())})}async init(){try{let promotable=promotableDirTasks({tasks:this.store.list(),isRepoRoot:(path)=>isGitRepo(path)&&samePath(resolveRepoRoot(path),path)});for(let task of promotable)await this.mainTasks.ensureIfEligible(task.repo,"explicit")}catch{}}activeTaskSignal(){return this.activeTaskAcc}async setActiveTask(id){let next=id===null?null:String(id);if(next&&this.store.get(next)?.deletion)throw new TaskDeletingError(next);if(this.activeTaskAcc.set(next),next&&this.store.get(next))writeLastActiveTaskId(next)}tasksSignal(){return this.tasksAcc}subscribeTasks(listener){return this.store.subscribe(listener)}dispose(){this.unsubscribeStore()}listTasks(){return this.store.list()}getTask(id){return this.store.get(id)}createTask=(input)=>createTaskRow({store:this.store,mainTasks:this.mainTasks,claimWorktreeName:(repo,name)=>this.worktreeCoordinator.claimWorktreeName(repo,name)},input);openDirectoryTask=(input)=>openDirectoryTaskRow({store:this.store},input);adoptScratchRepo=(id,repo)=>adoptScratchRepoRow({store:this.store},id,repo);spawnChildTask=(input)=>spawnChildTaskRow({store:this.store,worktrees:this.worktrees,createTask:this.createTask,ensureWorktree:(id)=>this.ensureWorktree(id)},input);createMigratedChild=(input)=>createMigratedChildRow({store:this.store},input);setPtyAlias=(id,alias)=>setPtyAliasRow({store:this.store},String(id),alias);async ensureMainTask(repo){return await this.mainTasks.ensure(repo)}async ensureWorktree(id,opts){let task=this.requireTask(id);if(task.deletion)throw new TaskDeletingError(String(task.id));if(task.kind==="main")return repoWorkingDir(task.repo);if(task.kind==="dir")return task.worktreePath;let owner=task.sharesWorkspaceOf?this.store.get(task.sharesWorkspaceOf):void 0;if(owner){let path=await this.ensureWorktree(owner.id,opts);if(path!==task.worktreePath||owner.branch!==task.branch)await this.store.update(task.id,{worktreePath:path,branch:owner.branch});return path}if(task.worktreePath){if(await this.worktrees.pathExists(task.worktreePath))return task.extraRepos?.length?this.worktreeCoordinator.ensure(task,opts?.onProgress):task.worktreePath;return await this.worktrees.pruneWorktrees(task.repo),await this.store.update(task.id,{worktreePath:""}),this.worktreeCoordinator.ensure({...task,worktreePath:""},opts?.onProgress)}return this.worktreeCoordinator.ensure(task,opts?.onProgress)}async clearWorktreePath(id){let task=this.store.get(id);if(!task||!task.worktreePath)return;if(task.kind==="main"||task.kind==="dir")return;let gone=canonPath(task.worktreePath);for(let holder of this.store.list()){if(holder.kind!=="task"||!holder.worktreePath||canonPath(holder.worktreePath)!==gone)continue;await this.store.update(holder.id,{worktreePath:""}),this.worktreeCoordinator.forget(holder.id)}}setTitle=(id,title)=>this.editor.setTitle(id,title);setBranch=(id,branch)=>this.editor.setBranch(id,branch);observeLanguage=(id,text)=>this.editor.observeLanguage(id,text);setVendor=(id,vendor,effort,model)=>this.editor.setVendor(id,vendor,effort,model);setCommand=(id,command,vendor)=>this.editor.setCommand(id,command,vendor);setPinned=(id,pinned)=>this.editor.setPinned(id,pinned);setParent=(id,parentId,replyTab)=>this.editor.setParent(id,parentId,replyTab);setArchived=(id,archived)=>this.editor.setArchived(id,archived);setRequireReport=(id,required)=>this.editor.setRequireReport(id,required);moveTask=(id,delta)=>this.editor.moveTask(id,delta);moveTaskToTop=(id)=>this.editor.moveTaskToTop(id);setStatus=(id,status)=>this.editor.setStatus(id,status);setWorkerReport=(id,report)=>this.editor.setWorkerReport(id,report);setPRStatus=(id,prStatus,repoName)=>this.editor.setPRStatus(id,prStatus,repoName);setLinkedWorkItem=(id,item)=>this.editor.setLinkedWorkItem(id,item);setQuotaResume=(id,state)=>this.editor.setQuotaResume(id,state);setPrompt=(id,prompt)=>this.editor.setPrompt(id,prompt);async deleteTask(id,opts){await this.deletions.deleteNow(id,opts)}async prepareTaskDeletion(id,opts){return this.deletions.prepare(id,opts)}async beginTaskDeletion(id){return this.deletions.begin(id)}async finishTaskDeletion(id){return this.deletions.finish(id)}async landPreflight(id,repo){let task=this.requireTask(id);if(task.kind==="main")throw Error("landTask: a main task has no branch to land");if(task.kind==="dir")throw Error("landTask: a directory task has no Rove-managed branch to land");if(task.deletion)throw new TaskDeletingError(String(task.id));return pickRepos(task,repo),task.extraRepos?.length?landPreflightAll(task,repo):landPreflight(task)}async landTask(id,opts){let task=this.requireTask(id);if(task.deletion)throw new TaskDeletingError(String(task.id));pickRepos(task,opts?.repo);let sharing=(landed,path)=>this.store.list().some((t)=>t.id!==landed.id&&(t.worktreePath&&canonPath(t.worktreePath)===canonPath(path)||t.sharesWorkspaceOf===landed.id));if(task.extraRepos?.length)return landTaskAll(task,opts??{},{worktrees:this.worktrees,tearDownSession:this.tearDownSession,clearRepoWorktreePath:(tid,name)=>this.clearRepoWorktreePath(tid,name),sharesRepoWorktree:(landed,repo)=>sharing(landed,repo.worktreePath)},opts?.repo);return landTaskWithCleanup(task,opts??{},{worktrees:this.worktrees,clearWorktreePath:(tid)=>this.clearWorktreePath(tid),tearDownSession:this.tearDownSession,sharesWorktree:(landed)=>sharing(landed,landed.worktreePath)})}async clearRepoWorktreePath(id,repoName){let task=this.store.get(id);if(!task?.extraRepos?.some((x)=>x.name===repoName))return this.clearWorktreePath(id);await this.store.update(task.id,{extraRepos:task.extraRepos.map((x)=>x.name===repoName?{...x,worktreePath:""}:x)})}async forgetProject(repo){await this.mainTasks.forget(repo)}async discoverAdoptableWorktrees(repo){if(!repo)throw Error("discoverAdoptableWorktrees: repo is required");return this.worktreeCoordinator.discoverAdoptable(repo)}async adoptWorktree(input){if(!input.repo)throw Error("adoptWorktree: repo is required");if(!input.worktreePath)throw Error("adoptWorktree: worktreePath is required");return this.worktreeCoordinator.adopt(input)}requireTask(id){let task=this.store.get(id);if(!task)throw new TaskNotFoundError(String(id));return task}}
5
+ export{Orchestrator};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{vendorFromArgv}from"./chunk-zpvwb2z6.js";import{engineEntry}from"./chunk-9m4gje59.js";import{isContribEngine}from"./chunk-aac92ra2.js";import{roveCliInvocation}from"./chunk-dyzvnvjz.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{getCustomEngineIds,getPersistedString}from"./chunk-rfp0ayra.js";function engineCommandKey(vendor){return`engineCommand.${vendor}`}function engineNameKey(vendor){return`engineName.${vendor}`}function engineDisplayName(vendor){return getPersistedString(engineNameKey(vendor))?.trim()||engineEntry(vendor).displayName}function humanizeSlug(id){return id.split(/[-_]+/).filter((word)=>word.length>0).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")}function engineRenamedFrom(vendor,override){let name=override.trim(),base=engineEntry(vendor).displayName;if(!name||name===base||name===humanizeSlug(vendor))return;return base}function defaultEngineCommand(vendor){return engineEntry(coerceVendorId(vendor)).defaultCommand}function parseEngineCommand(command){let out=[],token="",hasToken=!1,quote=null;for(let ch of command){if(quote){if(ch===quote)quote=null;else token+=ch;continue}if(ch==='"'||ch==="'"){quote=ch,hasToken=!0;continue}if(/\s/.test(ch)){if(hasToken)out.push(token),token="",hasToken=!1;continue}token+=ch,hasToken=!0}if(hasToken)out.push(token);return out}function interactiveEngineCommand(vendor,effort,model){let v=coerceVendorId(vendor),override=getPersistedString(engineCommandKey(v))?.trim(),base=(()=>{if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(v)})();return withEngineTerminalTitle(withEngineModel(withEngineEffort(base,v,effort),v,model),v)}function withEngineTerminalTitle(argv,vendor){let args=engineEntry(coerceVendorId(vendor)).terminalTitle?.launchArgs;return args&&args.length>0?[...argv,...args]:argv}function withEngineEffort(argv,vendor,effort){let trimmed=effort?.trim();if(!trimmed)return argv;let entry=engineEntry(coerceVendorId(vendor));if(!entry.effortLevels?.includes(trimmed))return argv;return entry.effortArgv?.(argv,trimmed)??argv}function withEngineModel(argv,vendor,model){let trimmed=model?.trim();if(!trimmed)return argv;return engineEntry(coerceVendorId(vendor)).modelArgv?.(argv,trimmed)??argv}function roveApiInvocation(){let quote=(a)=>/^[A-Za-z0-9_/.:=-]+$/.test(a)?a:`'${a.replace(/'/g,"'\\''")}'`;try{return[...roveCliInvocation(),"api"].map(quote).join(" ")}catch{return"rove api"}}import{randomUUID}from"crypto";function hasFlag(argv,flag){return argv.some((a)=>a===flag||a.startsWith(`${flag}=`))}function controlsOwnSession(identity,argv){return(identity?.sessionControlFlags??[]).some((flag)=>hasFlag(argv,flag))}function pinSessionArgv(identity,argv,sessionId){if(!identity?.pinFlag)return argv;if(controlsOwnSession(identity,argv))return argv;return[...argv,identity.pinFlag,sessionId]}function acceptsPinnedSession(identity,argv){return!!identity?.pinFlag&&!controlsOwnSession(identity,argv)}function resumeSessionArgv(identity,base,sessionId){if(!sessionId||!identity?.resumeArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.resumeArgv(base,sessionId)}function pickUnclaimedSessionId(ids,claimed){for(let i=ids.length-1;i>=0;i--){let id=ids[i];if(id&&!claimed.has(id))return id}return null}function forkSessionArgvFor(identity,base,sourceId,newId){if(!sourceId||!identity?.forkArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.forkArgv(base,sourceId,newId)}function acceptsSessionFork(identity){return!!identity?.forkArgv}var GENERIC_PROTOCOL="generic",ENGINE_PROTOCOLS=BUILTIN_VENDORS;function engineProtocolKey(id){return`engineProtocol.${id}`}function getEngineProtocol(id){if(isBuiltinVendor(id)||isContribEngine(id))return id;let raw=getPersistedString(engineProtocolKey(id))?.trim();return raw&&ENGINE_PROTOCOLS.includes(raw)?raw:void 0}function isPresetId(id){return isBuiltinVendor(id)||isContribEngine(id)||getCustomEngineIds().includes(id)}function listPresetIds(){return[...BUILTIN_VENDORS,...getCustomEngineIds()]}function describePreset(id){let command=getPersistedString(engineCommandKey(id))?.trim()||defaultEngineCommand(id).join(" ");return{id,name:engineDisplayName(id),command,protocol:getEngineProtocol(id)??GENERIC_PROTOCOL,builtin:isBuiltinVendor(id)}}function listEnginePresets(){return listPresetIds().map(describePreset)}function resolveCommandProtocol(command){let trimmed=command?.trim();if(!trimmed)return GENERIC_PROTOCOL;if(isPresetId(trimmed))return getEngineProtocol(trimmed)??GENERIC_PROTOCOL;let fromArgv=vendorFromArgv(trimmed);if(fromArgv)return fromArgv;let argv0=parseEngineCommand(trimmed)[0];if(argv0)for(let id of getCustomEngineIds()){let preset=getPersistedString(engineCommandKey(id))?.trim();if(preset&&parseEngineCommand(preset)[0]===argv0)return getEngineProtocol(id)??GENERIC_PROTOCOL}return GENERIC_PROTOCOL}function engineLaunchArgv(spec){let command=spec.command?.trim();if(!command)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);let vendor=(isPresetId(command)?getEngineProtocol(command):void 0)??resolveCommandProtocol(command),base=isPresetId(command)?presetBaseArgv(command):(()=>{let argv=parseEngineCommand(command);return argv.length>0?argv:null})();if(!base)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);return withEngineTerminalTitle(withEngineModel(withEngineEffort(base,vendor,spec.effort),vendor,spec.model),vendor)}function presetBaseArgv(id){let override=getPersistedString(engineCommandKey(id))?.trim();if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(id)}function sessionProtocol(vendor){let id=vendor?.trim();if(!id)return"claude";return getEngineProtocol(id)??id}function protocolEntry(vendor){return engineEntry(sessionProtocol(vendor))}function withPinnedSessionId(argv,vendor,newId=randomUUID){let identity=engineEntry(sessionProtocol(vendor)).sessionIdentity;if(!acceptsPinnedSession(identity,argv))return{argv,sessionId:null};let sessionId=newId();return{argv:pinSessionArgv(identity,argv,sessionId),sessionId}}function engineResumeArgv(base,vendor,sessionId){return resumeSessionArgv(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sessionId)}function engineCanFork(vendor){return acceptsSessionFork(engineEntry(sessionProtocol(vendor)).sessionIdentity)}function engineForkArgv(base,vendor,sourceId,newId){return forkSessionArgvFor(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sourceId,newId)}var ID_RE=/^tab-(\d+)$/;function tabOrdinalOf(id){let match=ID_RE.exec(id);return match?Number(match[1]):null}var sameValue=(a,b)=>a===b||JSON.stringify(a)===JSON.stringify(b);function insertAfter(tabs,row,after){if(after===null)return[row,...tabs];let i=after===void 0?-1:tabs.findIndex((t)=>t.id===after);return i<0?[...tabs,row]:[...tabs.slice(0,i+1),row,...tabs.slice(i+1)]}function applyTabOps(current,ops,tombstones=new Set){let state=current,changed=!1,opened=[],set=(next)=>{state=next,changed=!0};for(let op of ops)switch(op.op){case"seed":{if(state===null||state.tabs.length===0){let floor=Math.max(op.state.nextOrdinal,maxOrdinal(op.state)+1,state?.nextOrdinal??0);set({...op.state,nextOrdinal:floor})}break}case"forget":{if(state!==null)set(null);break}case"open":{let base=state??{tabs:[],nextOrdinal:1},wanted=op.row.id;if(wanted!==void 0&&(base.tabs.some((t)=>t.id===wanted)||tombstones.has(wanted))){opened.push(null);break}let ordinal=wanted!==void 0?tabOrdinalOf(wanted)??op.row.ordinal??base.nextOrdinal:base.nextOrdinal,id=wanted??`tab-${ordinal}`,row={...op.row,id,ordinal};set({...base,tabs:insertAfter(base.tabs,row,op.after),nextOrdinal:Math.max(base.nextOrdinal,ordinal+1)}),opened.push(id);break}case"patch":{if(!state)break;let i=state.tabs.findIndex((t)=>t.id===op.id),row=state.tabs[i];if(!row)break;let next={...row},rowChanged=!1;for(let[key,value]of Object.entries(op.set??{})){if(key==="id"||key==="ordinal"||sameValue(next[key],value))continue;next[key]=value,rowChanged=!0}for(let key of op.unset??[]){if(key==="id"||key==="ordinal"||key==="kind"||!(key in next))continue;delete next[key],rowChanged=!0}if(!rowChanged)break;let tabs=[...state.tabs];tabs[i]=next,set({...state,tabs});break}case"close":{if(!state||!state.tabs.some((t)=>t.id===op.id))break;tombstones.add(op.id);let tabs=state.tabs.filter((t)=>t.id!==op.id),reopen=tabs.length===0&&op.reopenAs!==void 0?{reopenAs:op.reopenAs}:{},{activeId,...rest}=state;set({...rest,tabs,...activeId!==void 0&&activeId!==op.id?{activeId}:{},...reopen});break}case"order":{if(!state)break;let byId=new Map(state.tabs.map((t)=>[t.id,t])),tabs=[...op.ids.flatMap((id)=>{let row=byId.get(id);if(!row)return[];return byId.delete(id),[row]}),...state.tabs.filter((t)=>byId.has(t.id))];if(tabs.every((t,i)=>t===state?.tabs[i]))break;set({...state,tabs});break}case"focus":{if(!state||state.activeId===op.id||!state.tabs.some((t)=>t.id===op.id))break;set({...state,activeId:op.id});break}case"meta":{if(!state||sameValue(state.reopenAs,op.reopenAs))break;let{reopenAs:_drop,...rest}=state;set(op.reopenAs===void 0?rest:{...rest,reopenAs:op.reopenAs});break}}return{state,changed,opened}}function maxOrdinal(state){return state.tabs.reduce((max,tab)=>Math.max(max,tab.ordinal),0)}function reserveOrdinals(state,count){let base=state??{tabs:[],nextOrdinal:1},from=Math.max(base.nextOrdinal,maxOrdinal(base)+1);return{state:{...base,nextOrdinal:from+count},from}}function releaseOrdinals(state,from,to){if(!state||state.nextOrdinal!==to||from>=to)return state;let floor=Math.max(from,maxOrdinal(state)+1);return floor<state.nextOrdinal?{...state,nextOrdinal:floor}:state}function diffTabs(prev,next){if(prev===null)return[{op:"seed",state:next}];let ops=[],prevById=new Map(prev.tabs.map((t)=>[t.id,t])),nextIds=new Set(next.tabs.map((t)=>t.id));for(let row of prev.tabs){let reopen=next.tabs.length===0&&next.reopenAs!==void 0?{reopenAs:next.reopenAs}:{};if(!nextIds.has(row.id))ops.push({op:"close",id:row.id,...reopen})}next.tabs.forEach((row,i)=>{let before=prevById.get(row.id);if(!before){ops.push({op:"open",row,after:i===0?null:next.tabs[i-1]?.id??null});return}if(before===row)return;let set={},unset=[];for(let[key,value]of Object.entries(row))if(key!=="id"&&key!=="ordinal"&&!sameValue(before[key],value))set[key]=value;for(let key of Object.keys(before))if(!(key in row))unset.push(key);if(Object.keys(set).length>0||unset.length>0)ops.push({op:"patch",id:row.id,...Object.keys(set).length>0?{set}:{},...unset.length>0?{unset}:{}})});let kept=next.tabs.filter((t)=>prevById.has(t.id)).map((t)=>t.id),prevKept=prev.tabs.filter((t)=>nextIds.has(t.id)).map((t)=>t.id);if(kept.some((id,i)=>id!==prevKept[i]))ops.push({op:"order",ids:next.tabs.map((t)=>t.id)});if(!sameValue(prev.reopenAs,next.reopenAs)&&next.tabs.length>0)ops.push({op:"meta",reopenAs:next.reopenAs});return ops}
2
+ import{vendorFromArgv}from"./chunk-fqgvmy2d.js";import{engineEntry}from"./chunk-a037vcy5.js";import{isContribEngine}from"./chunk-aac92ra2.js";import{roveCliInvocation}from"./chunk-dyzvnvjz.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{getCustomEngineIds,getPersistedString}from"./chunk-rfp0ayra.js";function engineCommandKey(vendor){return`engineCommand.${vendor}`}function engineNameKey(vendor){return`engineName.${vendor}`}function engineDisplayName(vendor){return getPersistedString(engineNameKey(vendor))?.trim()||engineEntry(vendor).displayName}function humanizeSlug(id){return id.split(/[-_]+/).filter((word)=>word.length>0).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")}function engineRenamedFrom(vendor,override){let name=override.trim(),base=engineEntry(vendor).displayName;if(!name||name===base||name===humanizeSlug(vendor))return;return base}function defaultEngineCommand(vendor){return engineEntry(coerceVendorId(vendor)).defaultCommand}function parseEngineCommand(command){let out=[],token="",hasToken=!1,quote=null;for(let ch of command){if(quote){if(ch===quote)quote=null;else token+=ch;continue}if(ch==='"'||ch==="'"){quote=ch,hasToken=!0;continue}if(/\s/.test(ch)){if(hasToken)out.push(token),token="",hasToken=!1;continue}token+=ch,hasToken=!0}if(hasToken)out.push(token);return out}function interactiveEngineCommand(vendor,effort,model){let v=coerceVendorId(vendor),override=getPersistedString(engineCommandKey(v))?.trim(),base=(()=>{if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(v)})();return withEngineTerminalTitle(withEngineModel(withEngineEffort(base,v,effort),v,model),v)}function withEngineTerminalTitle(argv,vendor){let args=engineEntry(coerceVendorId(vendor)).terminalTitle?.launchArgs;return args&&args.length>0?[...argv,...args]:argv}function withEngineEffort(argv,vendor,effort){let trimmed=effort?.trim();if(!trimmed)return argv;let entry=engineEntry(coerceVendorId(vendor));if(!entry.effortLevels?.includes(trimmed))return argv;return entry.effortArgv?.(argv,trimmed)??argv}function withEngineModel(argv,vendor,model){let trimmed=model?.trim();if(!trimmed)return argv;return engineEntry(coerceVendorId(vendor)).modelArgv?.(argv,trimmed)??argv}function roveApiInvocation(){let quote=(a)=>/^[A-Za-z0-9_/.:=-]+$/.test(a)?a:`'${a.replace(/'/g,"'\\''")}'`;try{return[...roveCliInvocation(),"api"].map(quote).join(" ")}catch{return"rove api"}}import{randomUUID}from"crypto";function hasFlag(argv,flag){return argv.some((a)=>a===flag||a.startsWith(`${flag}=`))}function controlsOwnSession(identity,argv){return(identity?.sessionControlFlags??[]).some((flag)=>hasFlag(argv,flag))}function pinSessionArgv(identity,argv,sessionId){if(!identity?.pinFlag)return argv;if(controlsOwnSession(identity,argv))return argv;return[...argv,identity.pinFlag,sessionId]}function acceptsPinnedSession(identity,argv){return!!identity?.pinFlag&&!controlsOwnSession(identity,argv)}function resumeSessionArgv(identity,base,sessionId){if(!sessionId||!identity?.resumeArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.resumeArgv(base,sessionId)}function pickUnclaimedSessionId(ids,claimed){for(let i=ids.length-1;i>=0;i--){let id=ids[i];if(id&&!claimed.has(id))return id}return null}function forkSessionArgvFor(identity,base,sourceId,newId){if(!sourceId||!identity?.forkArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.forkArgv(base,sourceId,newId)}function acceptsSessionFork(identity){return!!identity?.forkArgv}var GENERIC_PROTOCOL="generic",ENGINE_PROTOCOLS=BUILTIN_VENDORS;function engineProtocolKey(id){return`engineProtocol.${id}`}function getEngineProtocol(id){if(isBuiltinVendor(id)||isContribEngine(id))return id;let raw=getPersistedString(engineProtocolKey(id))?.trim();return raw&&ENGINE_PROTOCOLS.includes(raw)?raw:void 0}function isPresetId(id){return isBuiltinVendor(id)||isContribEngine(id)||getCustomEngineIds().includes(id)}function listPresetIds(){return[...BUILTIN_VENDORS,...getCustomEngineIds()]}function describePreset(id){let command=getPersistedString(engineCommandKey(id))?.trim()||defaultEngineCommand(id).join(" ");return{id,name:engineDisplayName(id),command,protocol:getEngineProtocol(id)??GENERIC_PROTOCOL,builtin:isBuiltinVendor(id)}}function listEnginePresets(){return listPresetIds().map(describePreset)}function resolveCommandProtocol(command){let trimmed=command?.trim();if(!trimmed)return GENERIC_PROTOCOL;if(isPresetId(trimmed))return getEngineProtocol(trimmed)??GENERIC_PROTOCOL;let fromArgv=vendorFromArgv(trimmed);if(fromArgv)return fromArgv;let argv0=parseEngineCommand(trimmed)[0];if(argv0)for(let id of getCustomEngineIds()){let preset=getPersistedString(engineCommandKey(id))?.trim();if(preset&&parseEngineCommand(preset)[0]===argv0)return getEngineProtocol(id)??GENERIC_PROTOCOL}return GENERIC_PROTOCOL}function engineLaunchArgv(spec){let command=spec.command?.trim();if(!command)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);let vendor=(isPresetId(command)?getEngineProtocol(command):void 0)??resolveCommandProtocol(command),base=isPresetId(command)?presetBaseArgv(command):(()=>{let argv=parseEngineCommand(command);return argv.length>0?argv:null})();if(!base)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);return withEngineTerminalTitle(withEngineModel(withEngineEffort(base,vendor,spec.effort),vendor,spec.model),vendor)}function presetBaseArgv(id){let override=getPersistedString(engineCommandKey(id))?.trim();if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(id)}function sessionProtocol(vendor){let id=vendor?.trim();if(!id)return"claude";return getEngineProtocol(id)??id}function protocolEntry(vendor){return engineEntry(sessionProtocol(vendor))}function withPinnedSessionId(argv,vendor,newId=randomUUID){let identity=engineEntry(sessionProtocol(vendor)).sessionIdentity;if(!acceptsPinnedSession(identity,argv))return{argv,sessionId:null};let sessionId=newId();return{argv:pinSessionArgv(identity,argv,sessionId),sessionId}}function engineResumeArgv(base,vendor,sessionId){return resumeSessionArgv(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sessionId)}function engineCanFork(vendor){return acceptsSessionFork(engineEntry(sessionProtocol(vendor)).sessionIdentity)}function engineForkArgv(base,vendor,sourceId,newId){return forkSessionArgvFor(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sourceId,newId)}var ID_RE=/^tab-(\d+)$/;function tabOrdinalOf(id){let match=ID_RE.exec(id);return match?Number(match[1]):null}var sameValue=(a,b)=>a===b||JSON.stringify(a)===JSON.stringify(b);function insertAfter(tabs,row,after){if(after===null)return[row,...tabs];let i=after===void 0?-1:tabs.findIndex((t)=>t.id===after);return i<0?[...tabs,row]:[...tabs.slice(0,i+1),row,...tabs.slice(i+1)]}function applyTabOps(current,ops,tombstones=new Set){let state=current,changed=!1,opened=[],set=(next)=>{state=next,changed=!0};for(let op of ops)switch(op.op){case"seed":{if(state===null||state.tabs.length===0){let floor=Math.max(op.state.nextOrdinal,maxOrdinal(op.state)+1,state?.nextOrdinal??0);set({...op.state,nextOrdinal:floor})}break}case"forget":{if(state!==null)set(null);break}case"open":{let base=state??{tabs:[],nextOrdinal:1},wanted=op.row.id;if(wanted!==void 0&&(base.tabs.some((t)=>t.id===wanted)||tombstones.has(wanted))){opened.push(null);break}let ordinal=wanted!==void 0?tabOrdinalOf(wanted)??op.row.ordinal??base.nextOrdinal:base.nextOrdinal,id=wanted??`tab-${ordinal}`,row={...op.row,id,ordinal};set({...base,tabs:insertAfter(base.tabs,row,op.after),nextOrdinal:Math.max(base.nextOrdinal,ordinal+1)}),opened.push(id);break}case"patch":{if(!state)break;let i=state.tabs.findIndex((t)=>t.id===op.id),row=state.tabs[i];if(!row)break;let next={...row},rowChanged=!1;for(let[key,value]of Object.entries(op.set??{})){if(key==="id"||key==="ordinal"||sameValue(next[key],value))continue;next[key]=value,rowChanged=!0}for(let key of op.unset??[]){if(key==="id"||key==="ordinal"||key==="kind"||!(key in next))continue;delete next[key],rowChanged=!0}if(!rowChanged)break;let tabs=[...state.tabs];tabs[i]=next,set({...state,tabs});break}case"close":{if(!state||!state.tabs.some((t)=>t.id===op.id))break;tombstones.add(op.id);let tabs=state.tabs.filter((t)=>t.id!==op.id),reopen=tabs.length===0&&op.reopenAs!==void 0?{reopenAs:op.reopenAs}:{},{activeId,...rest}=state;set({...rest,tabs,...activeId!==void 0&&activeId!==op.id?{activeId}:{},...reopen});break}case"order":{if(!state)break;let byId=new Map(state.tabs.map((t)=>[t.id,t])),tabs=[...op.ids.flatMap((id)=>{let row=byId.get(id);if(!row)return[];return byId.delete(id),[row]}),...state.tabs.filter((t)=>byId.has(t.id))];if(tabs.every((t,i)=>t===state?.tabs[i]))break;set({...state,tabs});break}case"focus":{if(!state||state.activeId===op.id||!state.tabs.some((t)=>t.id===op.id))break;set({...state,activeId:op.id});break}case"meta":{if(!state||sameValue(state.reopenAs,op.reopenAs))break;let{reopenAs:_drop,...rest}=state;set(op.reopenAs===void 0?rest:{...rest,reopenAs:op.reopenAs});break}}return{state,changed,opened}}function maxOrdinal(state){return state.tabs.reduce((max,tab)=>Math.max(max,tab.ordinal),0)}function reserveOrdinals(state,count){let base=state??{tabs:[],nextOrdinal:1},from=Math.max(base.nextOrdinal,maxOrdinal(base)+1);return{state:{...base,nextOrdinal:from+count},from}}function releaseOrdinals(state,from,to){if(!state||state.nextOrdinal!==to||from>=to)return state;let floor=Math.max(from,maxOrdinal(state)+1);return floor<state.nextOrdinal?{...state,nextOrdinal:floor}:state}function diffTabs(prev,next){if(prev===null)return[{op:"seed",state:next}];let ops=[],prevById=new Map(prev.tabs.map((t)=>[t.id,t])),nextIds=new Set(next.tabs.map((t)=>t.id));for(let row of prev.tabs){let reopen=next.tabs.length===0&&next.reopenAs!==void 0?{reopenAs:next.reopenAs}:{};if(!nextIds.has(row.id))ops.push({op:"close",id:row.id,...reopen})}next.tabs.forEach((row,i)=>{let before=prevById.get(row.id);if(!before){ops.push({op:"open",row,after:i===0?null:next.tabs[i-1]?.id??null});return}if(before===row)return;let set={},unset=[];for(let[key,value]of Object.entries(row))if(key!=="id"&&key!=="ordinal"&&!sameValue(before[key],value))set[key]=value;for(let key of Object.keys(before))if(!(key in row))unset.push(key);if(Object.keys(set).length>0||unset.length>0)ops.push({op:"patch",id:row.id,...Object.keys(set).length>0?{set}:{},...unset.length>0?{unset}:{}})});let kept=next.tabs.filter((t)=>prevById.has(t.id)).map((t)=>t.id),prevKept=prev.tabs.filter((t)=>nextIds.has(t.id)).map((t)=>t.id);if(kept.some((id,i)=>id!==prevKept[i]))ops.push({op:"order",ids:next.tabs.map((t)=>t.id)});if(!sameValue(prev.reopenAs,next.reopenAs)&&next.tabs.length>0)ops.push({op:"meta",reopenAs:next.reopenAs});return ops}
3
3
  export{engineCommandKey,engineNameKey,engineDisplayName,humanizeSlug,engineRenamedFrom,defaultEngineCommand,interactiveEngineCommand,roveApiInvocation,pickUnclaimedSessionId,GENERIC_PROTOCOL,ENGINE_PROTOCOLS,engineProtocolKey,getEngineProtocol,listPresetIds,describePreset,listEnginePresets,resolveCommandProtocol,engineLaunchArgv,sessionProtocol,protocolEntry,withPinnedSessionId,engineResumeArgv,engineCanFork,engineForkArgv,applyTabOps,reserveOrdinals,releaseOrdinals,diffTabs};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-p5mtfzn3.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
2
+ import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-hzvbq8mf.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
3
3
  export{runChannelCli,startChatChannels};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{join}from"path";function webRoot(){return[join(import.meta.dir,"..","web"),join(import.meta.dir,"..","..","..","rove-web","dist")].find((dir)=>existsSync(join(dir,"index.html")))??null}async function runWebSubcommand(args){let root=webRoot();if(!root)console.error(`${ROVE_PRODUCT_NAME} --web: the browser client is not in this build. From a checkout, run \`bun --filter rove-web build\` first; the npm package ships it in dist/web.`),process.exit(2);let{runBridge}=await import("./chunk-px1gd2zk.js");await runBridge(args,{name:`${ROVE_PRODUCT_NAME} --web`,web:{root}})}export{runWebSubcommand};
2
+ import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{join}from"path";function webRoot(){return[join(import.meta.dir,"..","web"),join(import.meta.dir,"..","..","..","rove-web","dist")].find((dir)=>existsSync(join(dir,"index.html")))??null}async function runWebSubcommand(args){let root=webRoot();if(!root)console.error(`${ROVE_PRODUCT_NAME} --web: the browser client is not in this build. From a checkout, run \`bun --filter rove-web build\` first; the npm package ships it in dist/web.`),process.exit(2);let{runBridge}=await import("./chunk-xecgzx8c.js");await runBridge(args,{name:`${ROVE_PRODUCT_NAME} --web`,web:{root}})}export{runWebSubcommand};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{AUTO_MACHINE,LOCAL_MACHINE,forwardVerb,invokeRouted,machineDaemonSocket,machinePtySocket,machineTasks,pickMachine,repoHosts,repoWanted,requireMachine,routeTarget}from"./chunk-c2yt6fag.js";import"./chunk-gs01afvb.js";import"./chunk-sq6zj3fb.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-y1xnjx8x.js";import"./chunk-2brn8e1y.js";import"./chunk-7kysxgbq.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{routeTarget,requireMachine,repoWanted,repoHosts,pickMachine,machineTasks,machinePtySocket,machineDaemonSocket,invokeRouted,forwardVerb,LOCAL_MACHINE,AUTO_MACHINE};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{CONTRIB_ENGINE_IDS,contribEngineEntry,detectBobAccount,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectKimiAccount,isContribEngine,mergeFlatHooks,parseFlatHooks,pluginEngineIds}from"./chunk-aac92ra2.js";import{TomlError,parse}from"./chunk-w7zv47mp.js";import{spawnCapture}from"./chunk-2tfnscxk.js";import{ClaudeHookAdapter}from"./chunk-0j7j051w.js";import{GATED_TOOL_VERBS,JsonHookAdapter,ROVE_HOOK_VERSION,bobDbPath,bobTrustPath,claudeGlobalConfigPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isJsonlLineWithinBound,readFirstLineBounded,readSharedConfigSync,readTextFileBounded,readTextFileIfRegular,roveHookArgs,roveHookInvocation,updateSharedJsonSync,vendorAgentDir,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-dyzvnvjz.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import{samePath}from"./chunk-pn5ygqn6.js";import{__require}from"./chunk-91sykzqq.js";var BOB_SCREEN_MANIFEST={rules:[{state:"blocked",any:["complete sign-in in your browser"]},{state:"blocked",all:["do you trust this folder?"],any:["trust folder","don't trust"]},{state:"blocked",all:["approve once"],any:["reject","always allow"]},{state:"working",any:["enter to steer","tab to queue"]},{state:"idle",lineRegex:["^\\s*\\w[\\w ]* mode( \xB7|\\s*$)"]}]};import{homedir}from"os";var TRUSTED="TRUST_FOLDER";function trustBobWorktree(worktreePath,home=homedir()){updateSharedJsonSync(bobTrustPath(home),(raw)=>{if(raw===void 0)return{};try{return JSON.parse(raw)}catch{return{}}},(doc)=>{let folders=doc.folders&&typeof doc.folders==="object"&&!Array.isArray(doc.folders)?doc.folders:{};if(folders[worktreePath]===TRUSTED)return;let merged={...doc,version:doc.version??1,folders:{...folders,[worktreePath]:TRUSTED}};return`${JSON.stringify(merged,null,2)}
2
+ import{CONTRIB_ENGINE_IDS,contribEngineEntry,detectBobAccount,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectKimiAccount,isContribEngine,mergeFlatHooks,parseFlatHooks,pluginEngineIds}from"./chunk-aac92ra2.js";import{TomlError,parse}from"./chunk-w7zv47mp.js";import{spawnCapture}from"./chunk-2tfnscxk.js";import{ClaudeHookAdapter}from"./chunk-a09kjwtd.js";import{GATED_TOOL_VERBS,JsonHookAdapter,ROVE_HOOK_VERSION,bobDbPath,bobTrustPath,claudeGlobalConfigPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isJsonlLineWithinBound,readFirstLineBounded,readSharedConfigSync,readTextFileBounded,readTextFileIfRegular,roveHookArgs,roveHookInvocation,updateSharedJsonSync,vendorAgentDir,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-dyzvnvjz.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import{samePath}from"./chunk-pn5ygqn6.js";import{__require}from"./chunk-91sykzqq.js";var BOB_SCREEN_MANIFEST={rules:[{state:"blocked",any:["complete sign-in in your browser"]},{state:"blocked",all:["do you trust this folder?"],any:["trust folder","don't trust"]},{state:"blocked",all:["approve once"],any:["reject","always allow"]},{state:"working",any:["enter to steer","tab to queue"]},{state:"idle",lineRegex:["^\\s*\\w[\\w ]* mode( \xB7|\\s*$)"]}]};import{homedir}from"os";var TRUSTED="TRUST_FOLDER";function trustBobWorktree(worktreePath,home=homedir()){updateSharedJsonSync(bobTrustPath(home),(raw)=>{if(raw===void 0)return{};try{return JSON.parse(raw)}catch{return{}}},(doc)=>{let folders=doc.folders&&typeof doc.folders==="object"&&!Array.isArray(doc.folders)?doc.folders:{};if(folders[worktreePath]===TRUSTED)return;let merged={...doc,version:doc.version??1,folders:{...folders,[worktreePath]:TRUSTED}};return`${JSON.stringify(merged,null,2)}
3
3
  `})}var claudeCapabilities={interruptSequence:"\x1B"},claudeIdentity={shortName:"Claude"};import{homedir as homedir2,userInfo}from"os";import path from"path";var OAUTH_USAGE_URL="https://api.anthropic.com/api/oauth/usage",OAUTH_BETA_HEADER="oauth-2025-04-20",OAUTH_USER_AGENT="claude-cli/2.1.198 (external, cli)",USAGE_TIMEOUT_MS=1e4,KEYCHAIN_SERVICE="Claude Code-credentials";function parseResetsAtMs(value){if(value==null)return null;let numeric=typeof value==="number"?value:/^\d+(?:\.\d+)?$/.test(value.trim())?Number(value):null;if(numeric!=null){if(!Number.isFinite(numeric)||numeric<=0)return null;return numeric<1000000000000?numeric*1000:numeric}let parsed=Date.parse(String(value));return Number.isNaN(parsed)?null:parsed}var clampPercent=(value)=>Math.min(100,Math.max(0,Math.round(value)));function windowLabel(kind,scopeModel){if(kind==="weekly_scoped"&&scopeModel)return scopeModel;return kind.startsWith("weekly")||kind.startsWith("seven_day")?"7d":"5h"}function usageFromClaudePayload(payload,capturedAt){let windows=[];if(payload.limits?.length)for(let limit of payload.limits){if(typeof limit.kind!=="string"||typeof limit.percent!=="number")continue;windows.push({kind:limit.kind,label:windowLabel(limit.kind,limit.scope?.model?.display_name),percent:clampPercent(limit.percent),resetsAt:parseResetsAtMs(limit.resets_at)})}else{if(typeof payload.five_hour?.utilization==="number")windows.push({kind:"session",label:"5h",percent:clampPercent(payload.five_hour.utilization),resetsAt:parseResetsAtMs(payload.five_hour.resets_at)});if(typeof payload.seven_day?.utilization==="number")windows.push({kind:"weekly_all",label:"7d",percent:clampPercent(payload.seven_day.utilization),resetsAt:parseResetsAtMs(payload.seven_day.resets_at)})}return{windows,capturedAt}}function parseCredentials(raw){try{let oauth=JSON.parse(raw)?.claudeAiOauth;if(!oauth||typeof oauth.accessToken!=="string"||!oauth.accessToken)return null;return{accessToken:oauth.accessToken,...typeof oauth.expiresAt==="number"&&Number.isFinite(oauth.expiresAt)?{expiresAt:oauth.expiresAt}:{}}}catch{return null}}var isFresh=(c)=>c.expiresAt===void 0||c.expiresAt>Date.now();async function readFileCredentials(dir){try{return parseCredentials(await readTextFileBounded(path.join(dir,".credentials.json")))}catch{return null}}async function readKeychainCredentials(){if(process.platform!=="darwin")return null;let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),3000);try{let result=await spawnCapture("security",["find-generic-password","-a",userInfo().username,"-w","-s",KEYCHAIN_SERVICE],{cwd:homedir2(),signal:controller.signal});return result.status===0?parseCredentials(result.stdout.trim()):null}finally{clearTimeout(timeout)}}async function readAccessToken(){let configDir=process.env.CLAUDE_CONFIG_DIR?.trim();if(configDir){let fromFile=await readFileCredentials(configDir);return fromFile&&isFresh(fromFile)?fromFile.accessToken:null}return[await readKeychainCredentials(),await readFileCredentials(vendorConfigHome("claude"))].find((c)=>c!=null&&isFresh(c))?.accessToken??null}async function fetchClaudeQuotaUsage(now=Date.now){let token=await readAccessToken().catch(()=>null);if(!token)return null;let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),USAGE_TIMEOUT_MS);try{let response=await fetch(OAUTH_USAGE_URL,{headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json","User-Agent":OAUTH_USER_AGENT,"anthropic-beta":OAUTH_BETA_HEADER},signal:controller.signal});if(!response.ok)return null;return usageFromClaudePayload(await response.json(),now())}catch{return null}finally{clearTimeout(timeout)}}function trustClaudeWorktree(worktreePath,home){let deps=vendorWriteHomeDeps(home);updateSharedJsonSync(claudeGlobalConfigPath(deps.env,deps.home()),(raw)=>{if(raw===void 0)return{};let doc=JSON.parse(raw);if(!isObject(doc))throw Error("Claude trust config must be a JSON object");return doc},(doc)=>{if(doc.projects!==void 0&&!isObject(doc.projects))throw Error("Claude trust projects must be an object");let projects={...doc.projects},existing=Object.hasOwn(projects,worktreePath)?projects[worktreePath]:{};if(!isObject(existing))throw Error("Claude trust project must be an object");if(existing.hasTrustDialogAccepted===!0)return;return projects[worktreePath]={...existing,hasTrustDialogAccepted:!0,hasCompletedProjectOnboarding:!0},JSON.stringify({...doc,projects},null,2)})}function isSyntheticClaudeRecord(record){return record.isMeta===!0||record.isCompactSummary===!0}function isClaudeCommandBreadcrumb(blocks){if(blocks.length===0)return!1;for(let b of blocks){if(b.type!=="text")return!1;let t=b.text.trim();if(!t.startsWith("<command-name>")&&!t.startsWith("<command-message>")&&!t.startsWith("<local-command"))return!1}return!0}function opensTurn(content){if(typeof content==="string")return content.trim().length>0;if(!Array.isArray(content))return!1;return content.some((b)=>!isObject(b)||b.type!=="tool_result")}function num(v){return typeof v==="number"&&Number.isFinite(v)?v:0}function readUsage(v){if(!isObject(v))return;return{input_tokens:num(v.input_tokens),output_tokens:num(v.output_tokens),cache_read_input_tokens:num(v.cache_read_input_tokens),cache_creation_input_tokens:num(v.cache_creation_input_tokens)}}function finish(draft){if(!draft.id)return null;let totals={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};for(let u of draft.usageByMessage.values())totals.input_tokens+=u.input_tokens,totals.output_tokens+=u.output_tokens,totals.cache_read_input_tokens+=u.cache_read_input_tokens,totals.cache_creation_input_tokens+=u.cache_creation_input_tokens;return{id:draft.id,sessionId:draft.sessionId,...draft.model?{model:draft.model}:{},startedAt:draft.startedAt,endedAt:draft.endedAt,...draft.usageByMessage.size>0?{usage:totals}:{}}}function parseClaudeTurns(raw,fallbackSessionId=""){let out=[],draft=null;for(let line of raw.split(`
4
4
  `)){let trimmed=line.trim();if(!trimmed||!isJsonlLineWithinBound(trimmed))continue;let record;try{record=JSON.parse(trimmed)}catch{continue}if(!isObject(record)||isSyntheticClaudeRecord(record))continue;let inner=isObject(record.message)?record.message:record,at=typeof record.timestamp==="string"?Date.parse(record.timestamp):Number.NaN;if(!Number.isFinite(at))continue;let sessionId=typeof record.sessionId==="string"?record.sessionId:fallbackSessionId;if(inner.role==="user"){if(!opensTurn(inner.content))continue;if(draft){let done=finish(draft);if(done)out.push(done)}draft={id:"",sessionId,startedAt:at,endedAt:at,usageByMessage:new Map};continue}if(inner.role!=="assistant"||!draft)continue;if(draft.endedAt=at,typeof inner.model==="string")draft.model=inner.model;let messageId=typeof inner.id==="string"?inner.id:"";if(messageId)draft.id=messageId;let usage=readUsage(inner.usage);if(usage&&messageId)draft.usageByMessage.set(messageId,usage)}if(draft){let done=finish(draft);if(done)out.push(done)}return out}async function readClaudeTurns(transcriptPath){try{let raw=await readTextFileBounded(transcriptPath);return parseClaudeTurns(raw)}catch{return[]}}var HEX_RE=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;function parseHex(value){let match=HEX_RE.exec(value);if(!match)return[0,0,0];return[Number.parseInt(match[1],16),Number.parseInt(match[2],16),Number.parseInt(match[3],16)]}function luminance([red,green,blue]){return(red*0.2126+green*0.7152+blue*0.0722)/255}function blend(from,to,amount){return[Math.round(from[0]+(to[0]-from[0])*amount),Math.round(from[1]+(to[1]-from[1])*amount),Math.round(from[2]+(to[2]-from[2])*amount)]}function codexUserMessageBackground(background){return luminance(background)>0.5?blend(background,[0,0,0],0.04):blend(background,[255,255,255],0.12)}function transcriptRewrite(palette){let foreground=parseHex(palette.foreground),background=parseHex(palette.background),backgroundIsLight=luminance(background)>0.5;return{matchBackground:codexUserMessageBackground(background),foreground:backgroundIsLight?foreground:background,background:backgroundIsLight?background:foreground}}var codexTerminalPresentation={alternateScreenStyleRewrites:(palette)=>[transcriptRewrite(palette)]};var codexCapabilities={preparePromptSubmission:(prompt)=>{return/^[\/!]/.test(prompt.trimStart())?prompt:`${prompt} `},beforePromptSubmit:"\x1B[F",terminalPresentation:codexTerminalPresentation,interruptSequence:"\x1B"},codexIdentity={shortName:"Codex"};import{join}from"path";var EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"Stop",verb:"turn-complete"},{event:"SessionEnd",verb:"session-end"},{event:"PreCompact",verb:"pre-compact"},{event:"PostCompact",verb:"post-compact"},{event:"SubagentStart",verb:"subagent-start"},{event:"SubagentStop",verb:"subagent-stop"},{event:"PreToolUse",verb:"tool-pre"},{event:"PostToolUse",verb:"tool-post"}],ROVE_CODEX_HOOK_EVENTS=EVENT_MAP.map((e)=>e.event);function codexHooksPath(){return join(vendorConfigHome("codex"),"hooks.json")}class CodexHookAdapter extends JsonHookAdapter{vendor="codex";setupCommand="/hooks";eventMap=EVENT_MAP;globalSettingsPath(){return codexHooksPath()}activityDetailFromPayload(kind,payload){if(kind==="tool-pre"||kind==="tool-post")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{}}};if(kind==="pre-compact"||kind==="post-compact")return{compact:{trigger:payload.trigger==="manual"?"manual":"auto"}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}}import{createHash}from"crypto";function createAppendParseCache(opts){let maxFiles=opts.maxFiles??8,cache=new Map;function remember(filePath,entry){if(cache.delete(filePath),cache.set(filePath,entry),cache.size>maxFiles){let oldest=cache.keys().next().value;if(oldest!==void 0)cache.delete(oldest)}}return function(filePath,raw,ctx){let stableLength=raw.lastIndexOf(`
5
5
  `)+1,entry=cache.get(filePath),verifiedLength=Math.min(entry?.prefixLength??0,stableLength),hash=createHash("sha256").update(raw.slice(0,verifiedLength)),unchanged=entry!==void 0&&Object.is(entry.context,ctx)&&entry.prefixLength<=stableLength&&hash.copy().digest("hex")===entry.prefixHash,prefixState;if(unchanged)prefixState=entry.prefixLength<stableLength?opts.parseChunk(raw.slice(entry.prefixLength,stableLength),entry.state,ctx):entry.state;else prefixState=opts.parseChunk(raw.slice(0,stableLength),opts.initial(ctx),ctx);if(!unchanged||entry.prefixLength!==stableLength||entry.state!==prefixState)remember(filePath,{context:ctx,prefixLength:stableLength,prefixHash:hash.update(raw.slice(verifiedLength,stableLength)).digest("hex"),state:prefixState});let tail=raw.slice(stableLength);return tail.trim().length>0?opts.parseChunk(tail,prefixState,ctx):prefixState}}var sortedMessages=new WeakMap;function sortByTimestamp(messages){let hit=sortedMessages.get(messages);if(hit)return hit;let sorted=[...messages].sort((a,b)=>a.timestamp<b.timestamp?-1:a.timestamp>b.timestamp?1:0);return sortedMessages.set(messages,sorted),sorted}function normalizeCodexContent(raw){if(typeof raw==="string")return raw.length>0?[{type:"text",text:raw}]:[];if(!Array.isArray(raw))return[];let blocks=[];for(let item of raw){if(typeof item==="string"){if(item.length>0)blocks.push({type:"text",text:item});continue}if(!isObject(item))continue;let t=typeof item.type==="string"?item.type:void 0;if(t==="input_text"||t==="output_text"){let text=typeof item.text==="string"?item.text:"";if(text.length>0)blocks.push({type:"text",text});continue}if(t)blocks.push({type:"text",text:`[codex: ${t}]`})}return blocks}function isSyntheticCodexUserRow(blocks){if(blocks.length===0)return!1;for(let b of blocks){if(b.type!=="text")return!1;let t=(b.text??"").trim();if(!isTagEnvelope(t)&&!isInstructionsEnvelope(t))return!1}return!0}var ENVELOPE_TAGS=["environment_context","recommended_plugins","user_instructions"];function isTagEnvelope(text){return ENVELOPE_TAGS.some((tag)=>text.startsWith(`<${tag}>`)&&text.endsWith(`</${tag}>`))}function isInstructionsEnvelope(text){return text.startsWith("# AGENTS.md instructions")&&text.includes("<INSTRUCTIONS>")}function codexUsageToSnapshot(usage,opts={}){let totalInput=numberOr(usage.input_tokens,0),cachedInput=numberOr(usage.cached_input_tokens,0),output=numberOr(usage.output_tokens,0),nonCachedInput=Math.max(0,totalInput-cachedInput);if(totalInput<=0&&output<=0&&cachedInput<=0)return;return{input_tokens:nonCachedInput,output_tokens:output,...cachedInput>0?{cache_read_input_tokens:cachedInput}:{},...validPositive(opts.contextWindowTokens)?{context_window_tokens:opts.contextWindowTokens}:{}}}function numberOr(v,fallback){return typeof v==="number"&&Number.isFinite(v)?v:fallback}function validPositive(v){return typeof v==="number"&&Number.isFinite(v)&&v>0}var emptyState={messages:[],latestUsage:void 0,latestUsageTimestampMs:null},cache=createAppendParseCache({initial:()=>emptyState,parseChunk:foldRolloutChunk});function parseRolloutRaw(filePath,raw,sessionId){let state=cache(filePath,raw,sessionId);return{messages:sortByTimestamp(state.messages),...state.latestUsage?{usageMetrics:state.latestUsage}:{}}}function foldRolloutChunk(chunk,prev,sessionId){let updatedMessages,writableMessages=()=>{return updatedMessages??=[...prev.messages],updatedMessages},latestUsage=prev.latestUsage,latestUsageTimestampMs=prev.latestUsageTimestampMs;for(let line of chunk.split(`
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{JsonHookAdapter,editJsonSettings,removeRoveHooks,vendorConfigHome}from"./chunk-dyzvnvjz.js";import{isObject}from"./chunk-7ghwdjdc.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{join}from"path";var CLAUDE_HOOK_EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"Stop",verb:"turn-complete"},{event:"StopFailure",verb:"turn-failed"},{event:"Notification",matcher:"permission_prompt",verb:"awaiting-input"},{event:"Notification",matcher:"elicitation_dialog",verb:"awaiting-input"},{event:"SessionEnd",verb:"session-end"},{event:"PreCompact",verb:"pre-compact"},{event:"PostCompact",verb:"post-compact"},{event:"SubagentStart",verb:"subagent-start"},{event:"SubagentStop",verb:"subagent-stop"},{event:"PreToolUse",verb:"tool-pre"},{event:"PostToolUse",verb:"tool-post"},{event:"PostToolUseFailure",verb:"tool-failed"}],ROVE_HOOK_EVENTS=[...new Set(CLAUDE_HOOK_EVENT_MAP.map((e)=>e.event))];function failureFromErrorType(errorType){if(typeof errorType!=="string")return"other";if(errorType==="rate_limit"||errorType==="overloaded")return"rate_limit";if(errorType==="billing_error")return"billing";return"other"}function claudeSettingsPath(){return join(vendorConfigHome("claude"),"settings.json")}var WORKTREE_SYNC_VERB="worktree-created";function mergeWorktreeSyncHook(current,command){let{hooks:rawHooks,...restSettings}=current,{WorktreeCreate,...otherHooks}=isObject(rawHooks)?rawHooks:{},prior=Array.isArray(WorktreeCreate)?WorktreeCreate:[],kept=removeRoveHooks(prior,[WORKTREE_SYNC_VERB]);if(command!==null)kept.push({hooks:[{type:"command",command}]});let nextHooks={...otherHooks};if(kept.length>0)nextHooks.WorktreeCreate=kept;return Object.keys(nextHooks).length>0?{...restSettings,hooks:nextHooks}:{...restSettings}}class ClaudeHookAdapter extends JsonHookAdapter{vendor="claude";eventMap=CLAUDE_HOOK_EVENT_MAP;globalSettingsPath(){return claudeSettingsPath()}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return{failure:failureFromErrorType(payload.error_type)};if(kind==="awaiting-input")return{waiting:payload.notification_type==="elicitation_dialog"?"input":"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{},...typeof payload.tool_use_id==="string"?{id:payload.tool_use_id}:{}}};if(kind==="pre-compact"||kind==="post-compact")return{compact:{trigger:payload.trigger==="manual"?"manual":"auto"}};if(kind==="subagent-start"||kind==="subagent-stop")return{subagent:{...typeof payload.agent_type==="string"?{type:payload.agent_type}:{},...typeof payload.agent_id==="string"?{id:payload.agent_id}:{}}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}isUnattendedSession(env){return env.CLAUDE_CODE_SESSION_ATTENDED==="0"}async externallyManagedHooks(){let{isRovePluginEnabled,detectLegacyInstalls,migrationHint}=await import("./chunk-js50sr3w.js");if(!isRovePluginEnabled())return;let notice=migrationHint(detectLegacyInstalls(),ROVE_PRODUCT_NAME);return notice?{notice}:{}}supportsWorktreeSync(){return!0}async removeWorktreeSyncHook(settingsFilePath){await editJsonSettings(settingsFilePath,(cur)=>mergeWorktreeSyncHook(cur,null))}}
2
+ import{JsonHookAdapter,editJsonSettings,removeRoveHooks,vendorConfigHome}from"./chunk-dyzvnvjz.js";import{isObject}from"./chunk-7ghwdjdc.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{join}from"path";var CLAUDE_HOOK_EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"Stop",verb:"turn-complete"},{event:"StopFailure",verb:"turn-failed"},{event:"Notification",matcher:"permission_prompt",verb:"awaiting-input"},{event:"Notification",matcher:"elicitation_dialog",verb:"awaiting-input"},{event:"SessionEnd",verb:"session-end"},{event:"PreCompact",verb:"pre-compact"},{event:"PostCompact",verb:"post-compact"},{event:"SubagentStart",verb:"subagent-start"},{event:"SubagentStop",verb:"subagent-stop"},{event:"PreToolUse",verb:"tool-pre"},{event:"PostToolUse",verb:"tool-post"},{event:"PostToolUseFailure",verb:"tool-failed"}],ROVE_HOOK_EVENTS=[...new Set(CLAUDE_HOOK_EVENT_MAP.map((e)=>e.event))];function failureFromErrorType(errorType){if(typeof errorType!=="string")return"other";if(errorType==="rate_limit"||errorType==="overloaded")return"rate_limit";if(errorType==="billing_error")return"billing";return"other"}function claudeSettingsPath(){return join(vendorConfigHome("claude"),"settings.json")}var WORKTREE_SYNC_VERB="worktree-created";function mergeWorktreeSyncHook(current,command){let{hooks:rawHooks,...restSettings}=current,{WorktreeCreate,...otherHooks}=isObject(rawHooks)?rawHooks:{},prior=Array.isArray(WorktreeCreate)?WorktreeCreate:[],kept=removeRoveHooks(prior,[WORKTREE_SYNC_VERB]);if(command!==null)kept.push({hooks:[{type:"command",command}]});let nextHooks={...otherHooks};if(kept.length>0)nextHooks.WorktreeCreate=kept;return Object.keys(nextHooks).length>0?{...restSettings,hooks:nextHooks}:{...restSettings}}class ClaudeHookAdapter extends JsonHookAdapter{vendor="claude";eventMap=CLAUDE_HOOK_EVENT_MAP;globalSettingsPath(){return claudeSettingsPath()}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return{failure:failureFromErrorType(payload.error_type)};if(kind==="awaiting-input")return{waiting:payload.notification_type==="elicitation_dialog"?"input":"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{},...typeof payload.tool_use_id==="string"?{id:payload.tool_use_id}:{}}};if(kind==="pre-compact"||kind==="post-compact")return{compact:{trigger:payload.trigger==="manual"?"manual":"auto"}};if(kind==="subagent-start"||kind==="subagent-stop")return{subagent:{...typeof payload.agent_type==="string"?{type:payload.agent_type}:{},...typeof payload.agent_id==="string"?{id:payload.agent_id}:{}}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}isUnattendedSession(env){return env.CLAUDE_CODE_SESSION_ATTENDED==="0"}async externallyManagedHooks(){let{isRovePluginEnabled,detectLegacyInstalls,migrationHint}=await import("./chunk-1pkhwwn4.js");if(!isRovePluginEnabled())return;let notice=migrationHint(detectLegacyInstalls(),ROVE_PRODUCT_NAME);return notice?{notice}:{}}supportsWorktreeSync(){return!0}async removeWorktreeSyncHook(settingsFilePath){await editJsonSettings(settingsFilePath,(cur)=>mergeWorktreeSyncHook(cur,null))}}
3
3
  export{CLAUDE_HOOK_EVENT_MAP,claudeSettingsPath,ClaudeHookAdapter};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{LAST_RUN_VERSION_KEY}from"./chunk-xdzd6v4r.js";import{isShellKind,shippedCompletionsPath}from"./chunk-0rrmz6k6.js";import{isNpxMissing,markSkillHintSeen,npxSkillsArgv,npxSkillsCommand}from"./chunk-6b91pz64.js";import{loadStateFile,patchStateFile}from"./chunk-32j6y5d1.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{t}from"./chunk-bj6sa371.js";import{spawnSync}from"child_process";import{appendFileSync,existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{basename,join}from"path";var WELCOMED_KEY="welcomed",PENDING_SKILL_KEY="welcomePendingSkillInstall";function shouldWelcome(state){if(state[WELCOMED_KEY]===!0)return!1;return typeof state[LAST_RUN_VERSION_KEY]!=="string"}function takeWelcome(){if(!shouldWelcome(loadStateFile()))return null;try{patchStateFile({[WELCOMED_KEY]:!0})}catch{}return{shell:detectShell()}}var PENDING_COMPLETIONS_KEY="welcomePendingCompletions";function detectShell(env=process.env){let shell=basename(env.SHELL??"");return shell==="zsh"||shell==="bash"||shell==="fish"?shell:null}function completionHook(shell,cli,shipped){if(shipped===null)return legacyCompletionHook(shell,cli);return shell==="fish"?`test -f "${shipped}"; and source "${shipped}"`:`[ -f "${shipped}" ] && source "${shipped}"`}function legacyCompletionHook(shell,cli){return shell==="fish"?`${cli} completions fish | source`:`command -v ${cli} >/dev/null && source <(${cli} completions ${shell})`}function shippedScriptFor(shell,cli){let path=shippedCompletionsPath(shell,cli);return existsSync(path)?path:null}function installCompletions(shell,home=homedir(),cli=ROVE_PRODUCT_NAME,shipped=shippedScriptFor(shell,cli)){let hook=completionHook(shell,cli,shipped);if(shell==="fish"){let dir=join(home,".config","fish","completions"),path=join(dir,`${cli}.fish`);return mkdirSync(dir,{recursive:!0}),writeFileSync(path,`${hook}
2
+ import{LAST_RUN_VERSION_KEY}from"./chunk-xdzd6v4r.js";import{isShellKind,shippedCompletionsPath}from"./chunk-0rrmz6k6.js";import{isNpxMissing,markSkillHintSeen,npxSkillsArgv,npxSkillsCommand}from"./chunk-58y5geay.js";import{loadStateFile,patchStateFile}from"./chunk-32j6y5d1.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{t}from"./chunk-bj6sa371.js";import{spawnSync}from"child_process";import{appendFileSync,existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{basename,join}from"path";var WELCOMED_KEY="welcomed",PENDING_SKILL_KEY="welcomePendingSkillInstall";function shouldWelcome(state){if(state[WELCOMED_KEY]===!0)return!1;return typeof state[LAST_RUN_VERSION_KEY]!=="string"}function takeWelcome(){if(!shouldWelcome(loadStateFile()))return null;try{patchStateFile({[WELCOMED_KEY]:!0})}catch{}return{shell:detectShell()}}var PENDING_COMPLETIONS_KEY="welcomePendingCompletions";function detectShell(env=process.env){let shell=basename(env.SHELL??"");return shell==="zsh"||shell==="bash"||shell==="fish"?shell:null}function completionHook(shell,cli,shipped){if(shipped===null)return legacyCompletionHook(shell,cli);return shell==="fish"?`test -f "${shipped}"; and source "${shipped}"`:`[ -f "${shipped}" ] && source "${shipped}"`}function legacyCompletionHook(shell,cli){return shell==="fish"?`${cli} completions fish | source`:`command -v ${cli} >/dev/null && source <(${cli} completions ${shell})`}function shippedScriptFor(shell,cli){let path=shippedCompletionsPath(shell,cli);return existsSync(path)?path:null}function installCompletions(shell,home=homedir(),cli=ROVE_PRODUCT_NAME,shipped=shippedScriptFor(shell,cli)){let hook=completionHook(shell,cli,shipped);if(shell==="fish"){let dir=join(home,".config","fish","completions"),path=join(dir,`${cli}.fish`);return mkdirSync(dir,{recursive:!0}),writeFileSync(path,`${hook}
3
3
  `),{path,installed:!0}}let rc=join(home,shell==="zsh"?".zshrc":".bashrc"),existing=existsSync(rc)?readFileSync(rc,"utf8"):"";if(existing.includes(hook))return{path:rc,installed:!1};let legacy=legacyCompletionHook(shell,cli);if(existing.includes(legacy))return writeFileSync(rc,existing.replace(legacy,hook)),{path:rc,installed:!0};if(existing.includes(`${cli} completions`))return{path:rc,installed:!1};return appendFileSync(rc,`
4
4
  # ${cli} completions
5
5
  ${hook}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{detectShell,installCompletions,recordWelcomeChoices,runPendingWelcomeInstalls,settleWelcomeInstall}from"./chunk-k0hp75n2.js";import"./chunk-xdzd6v4r.js";import"./chunk-0rrmz6k6.js";import"./chunk-tjj9bt7n.js";import"./chunk-4vad6e9t.js";import"./chunk-6b91pz64.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{settleWelcomeInstall,runPendingWelcomeInstalls,recordWelcomeChoices,installCompletions,detectShell};
2
+ import{detectShell,installCompletions,recordWelcomeChoices,runPendingWelcomeInstalls,settleWelcomeInstall}from"./chunk-acnmrmxh.js";import"./chunk-xdzd6v4r.js";import"./chunk-0rrmz6k6.js";import"./chunk-tjj9bt7n.js";import"./chunk-4vad6e9t.js";import"./chunk-58y5geay.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-bj6sa371.js";import"./chunk-1ffqacz9.js";import"./chunk-cmp64q4j.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{settleWelcomeInstall,runPendingWelcomeInstalls,recordWelcomeChoices,installCompletions,detectShell};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{machineTasks}from"./chunk-c2yt6fag.js";import{dedupeMachines,listMachines}from"./chunk-gs01afvb.js";import"./chunk-sq6zj3fb.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-y1xnjx8x.js";import"./chunk-2brn8e1y.js";import"./chunk-7kysxgbq.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-z1nj22va.js";import"./chunk-br8r72bf.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cynqvjk8.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";async function mergeTaskList(local){let machines=dedupeMachines(listMachines());if(machines.length===0)return local;let tasks=(local.tasks??[]).map((task)=>({...task,origin:{machineId:"local",hostLabel:"local"}}));for(let entry of machines){let remote=await machineTasks(entry);if(!remote)continue;let hostLabel=entry.alias;for(let task of remote)tasks.push({...task,origin:{machineId:entry.alias,hostLabel}})}return{tasks}}export{mergeTaskList};