@sma1lboy/rove 0.9.283 → 0.9.284-next.136

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 (162) hide show
  1. package/dist/cli/{chunk-tay29xzx.js → chunk-0hc53k74.js} +1 -1
  2. package/dist/cli/{chunk-ve2jj5qv.js → chunk-0ppfr3vm.js} +1 -1
  3. package/dist/cli/{chunk-nf1gqqv8.js → chunk-0xh1e21e.js} +1 -1
  4. package/dist/cli/{chunk-4gjj2ed9.js → chunk-11nf15ht.js} +1 -1
  5. package/dist/cli/chunk-11wyec8z.js +2 -0
  6. package/dist/cli/{chunk-mt0mh96t.js → chunk-1e0v0ycz.js} +2 -2
  7. package/dist/cli/{chunk-0sy3bez6.js → chunk-1k7f137x.js} +1 -1
  8. package/dist/cli/{chunk-p4aqy3sm.js → chunk-1rs3dmwz.js} +1 -1
  9. package/dist/cli/{chunk-p5pebhe6.js → chunk-2xtk4ch2.js} +2 -2
  10. package/dist/cli/{chunk-37pwx1a7.js → chunk-36f8xr65.js} +1 -1
  11. package/dist/cli/{chunk-x5swq8ar.js → chunk-3a12v30f.js} +1 -1
  12. package/dist/cli/{chunk-28mm4k8b.js → chunk-3j3ms4fx.js} +1 -1
  13. package/dist/cli/{chunk-afhnm3e4.js → chunk-46c20c2s.js} +1 -1
  14. package/dist/cli/{chunk-b1zg5jnk.js → chunk-4khwsrwk.js} +1 -1
  15. package/dist/cli/{chunk-hcrpbx9x.js → chunk-4qg325ww.js} +2 -2
  16. package/dist/cli/{chunk-trw076nv.js → chunk-4qy2mvd5.js} +1 -1
  17. package/dist/cli/{chunk-0r1jf8m9.js → chunk-55ajzrj6.js} +1 -1
  18. package/dist/cli/{chunk-c69xdgfz.js → chunk-5c2syc7e.js} +2 -2
  19. package/dist/cli/{chunk-r4bwm4zh.js → chunk-5jpfg8kz.js} +1 -1
  20. package/dist/cli/{chunk-8ac8k0ba.js → chunk-5smmarfy.js} +1 -1
  21. package/dist/cli/{chunk-mcbxrpwg.js → chunk-6b3s6fqq.js} +1 -1
  22. package/dist/cli/{chunk-q2r4qavc.js → chunk-6nsjckc5.js} +1 -1
  23. package/dist/cli/{chunk-131bpjms.js → chunk-6tg9h05d.js} +1 -1
  24. package/dist/cli/{chunk-d9fx9282.js → chunk-6z1a05bz.js} +1 -1
  25. package/dist/cli/{chunk-bxg7y1qk.js → chunk-7vt1bf35.js} +5 -5
  26. package/dist/cli/{chunk-kd8j15cg.js → chunk-87rkqyr3.js} +1 -1
  27. package/dist/cli/{chunk-94t488yj.js → chunk-8d4v27ez.js} +1 -1
  28. package/dist/cli/{chunk-cacct9gd.js → chunk-9wd57t3j.js} +1 -1
  29. package/dist/cli/chunk-9xax0901.js +2 -0
  30. package/dist/cli/{chunk-4zmhzb28.js → chunk-9y17mj2r.js} +1 -1
  31. package/dist/cli/{chunk-s7ttzm9a.js → chunk-9y803nx4.js} +1 -1
  32. package/dist/cli/{chunk-g2yf429k.js → chunk-a7pygqgw.js} +1 -1
  33. package/dist/cli/chunk-a9867184.js +2 -0
  34. package/dist/cli/{chunk-9q43btkf.js → chunk-acqqhrjb.js} +1 -1
  35. package/dist/cli/{chunk-nzf76wa4.js → chunk-adr12wp8.js} +2 -2
  36. package/dist/cli/{chunk-1c6yk07x.js → chunk-af5a4v8t.js} +1 -1
  37. package/dist/cli/{chunk-69f84j0j.js → chunk-ah04qzfd.js} +1 -1
  38. package/dist/cli/chunk-bg2ypp04.js +3 -0
  39. package/dist/cli/chunk-bjhx1nav.js +2 -0
  40. package/dist/cli/{chunk-fd3gswsr.js → chunk-bxqdxv63.js} +1 -1
  41. package/dist/cli/{chunk-1gxnd3qq.js → chunk-ca5fmepn.js} +1 -1
  42. package/dist/cli/chunk-chzxsqth.js +2 -0
  43. package/dist/cli/chunk-d79vm3bt.js +20 -0
  44. package/dist/cli/chunk-dcnyp3qq.js +62 -0
  45. package/dist/cli/{chunk-tckyb2xt.js → chunk-dcw40f11.js} +1 -1
  46. package/dist/cli/chunk-dgjnak3n.js +2 -0
  47. package/dist/cli/chunk-dp0m6jrg.js +2 -0
  48. package/dist/cli/{chunk-gr0ffx3f.js → chunk-dxwjx5d1.js} +1 -1
  49. package/dist/cli/chunk-e0z123ad.js +2 -0
  50. package/dist/cli/{chunk-qnv8ggxh.js → chunk-e1c6909n.js} +1 -1
  51. package/dist/cli/{chunk-yz859e8t.js → chunk-e23n32hv.js} +1 -1
  52. package/dist/cli/{chunk-5mhf43dx.js → chunk-e5crm07d.js} +1 -1
  53. package/dist/cli/{chunk-dce6ytw0.js → chunk-ebb8z47a.js} +1 -1
  54. package/dist/cli/{chunk-60kx1j7x.js → chunk-ee9nm38f.js} +6 -7
  55. package/dist/cli/{chunk-xs6w6ekc.js → chunk-ejytsv0b.js} +2 -2
  56. package/dist/cli/{chunk-1masf4pj.js → chunk-em75b155.js} +1 -1
  57. package/dist/cli/{chunk-jfbfasx0.js → chunk-f050r8jy.js} +1 -1
  58. package/dist/cli/chunk-f535feph.js +2 -0
  59. package/dist/cli/{chunk-62z7016x.js → chunk-f6qne8f1.js} +1 -1
  60. package/dist/cli/{chunk-mejxvvzb.js → chunk-fq8sbarx.js} +1 -1
  61. package/dist/cli/chunk-fsqgs1p1.js +2 -0
  62. package/dist/cli/{chunk-xdqj48wx.js → chunk-fxqgvjtt.js} +1 -1
  63. package/dist/cli/chunk-g1er3ctd.js +2 -0
  64. package/dist/cli/{chunk-qnpkhvrn.js → chunk-g2f96z6s.js} +1 -1
  65. package/dist/cli/{chunk-ar3mt81z.js → chunk-gca19v0w.js} +1 -1
  66. package/dist/cli/{chunk-an97ga8b.js → chunk-ghww7w7x.js} +1 -1
  67. package/dist/cli/chunk-gpq30qgy.js +2 -0
  68. package/dist/cli/chunk-gqqtkwkq.js +2 -0
  69. package/dist/cli/{chunk-dxacz9ba.js → chunk-gvzr7jxt.js} +1 -1
  70. package/dist/cli/{chunk-gfdd2jbp.js → chunk-h37tqrdb.js} +1 -1
  71. package/dist/cli/{chunk-8ttn73cv.js → chunk-hk0zbk3t.js} +1 -1
  72. package/dist/cli/chunk-hp2p26w1.js +2 -0
  73. package/dist/cli/{chunk-jadjn49m.js → chunk-j1rsp5pc.js} +1 -1
  74. package/dist/cli/{chunk-2r1fgng9.js → chunk-jrzh4yv6.js} +1 -1
  75. package/dist/cli/{chunk-sttpyf2b.js → chunk-jy0kms4j.js} +1 -1
  76. package/dist/cli/chunk-jzsngv31.js +3 -0
  77. package/dist/cli/{chunk-xj8bma5k.js → chunk-k2p7at32.js} +1 -1
  78. package/dist/cli/chunk-m3rjakc6.js +2 -0
  79. package/dist/cli/{chunk-mhft316g.js → chunk-m9gvs19s.js} +1 -1
  80. package/dist/cli/chunk-ma00xdy2.js +2 -0
  81. package/dist/cli/{chunk-pmwk2etg.js → chunk-mdfm45fx.js} +1 -1
  82. package/dist/cli/chunk-nkfqg6e2.js +2 -0
  83. package/dist/cli/{chunk-paashxkd.js → chunk-ntqg38ke.js} +1 -1
  84. package/dist/cli/{chunk-jkssty8x.js → chunk-p1pbtfa5.js} +1 -1
  85. package/dist/cli/chunk-pk2w9dtp.js +2 -0
  86. package/dist/cli/{chunk-abate6bw.js → chunk-qap0g8v4.js} +1 -1
  87. package/dist/cli/chunk-qknyztxj.js +2 -0
  88. package/dist/cli/{chunk-ee8917py.js → chunk-qq1q07tz.js} +1 -1
  89. package/dist/cli/{chunk-8y10pmkf.js → chunk-qq2mjph2.js} +1 -1
  90. package/dist/cli/{chunk-cye56q32.js → chunk-r02sre5z.js} +3 -3
  91. package/dist/cli/{chunk-991x8tw6.js → chunk-r1r83d2r.js} +1 -1
  92. package/dist/cli/chunk-ratr5ew6.js +2 -0
  93. package/dist/cli/{chunk-5a6rkz1s.js → chunk-rg38rkr1.js} +1 -1
  94. package/dist/cli/{chunk-gygdyf0s.js → chunk-rja9tf6j.js} +1 -1
  95. package/dist/cli/{chunk-7mwvvj46.js → chunk-rz8319pe.js} +1 -1
  96. package/dist/cli/{chunk-bbq6wc47.js → chunk-s62qg37a.js} +1 -1
  97. package/dist/cli/{chunk-wcq8k0j6.js → chunk-sdcb3ttr.js} +1 -1
  98. package/dist/cli/chunk-sdqvrj4w.js +2 -0
  99. package/dist/cli/{chunk-bwxmrwb1.js → chunk-t183jy5m.js} +1 -1
  100. package/dist/cli/{chunk-g6jregtt.js → chunk-t8j9csw2.js} +3 -3
  101. package/dist/cli/{chunk-hptxcj03.js → chunk-txy0xkks.js} +2 -2
  102. package/dist/cli/chunk-v765ej4f.js +2 -0
  103. package/dist/cli/{chunk-90dkv2mn.js → chunk-w1evhnvr.js} +1 -1
  104. package/dist/cli/{chunk-v883qbhk.js → chunk-w6me6vm2.js} +1 -1
  105. package/dist/cli/{chunk-d9x7zeh7.js → chunk-w7sb3jmd.js} +1 -1
  106. package/dist/cli/chunk-w8a3gsvw.js +2 -0
  107. package/dist/cli/{chunk-q89yrevw.js → chunk-wgyfwry1.js} +1 -1
  108. package/dist/cli/{chunk-3wsjbxd7.js → chunk-wxb38172.js} +1 -1
  109. package/dist/cli/{chunk-ks5g5ee2.js → chunk-x02jmqj1.js} +1 -1
  110. package/dist/cli/{chunk-53pn0a9z.js → chunk-x1d70j6f.js} +1 -1
  111. package/dist/cli/chunk-x652sy0y.js +2 -0
  112. package/dist/cli/{chunk-r0qhywyp.js → chunk-x6k5tgzz.js} +1 -1
  113. package/dist/cli/{chunk-f9x0n7kr.js → chunk-xenhysr0.js} +1 -1
  114. package/dist/cli/{chunk-fx2e7z2s.js → chunk-xhzbynky.js} +1 -1
  115. package/dist/cli/{chunk-gq7s8vp3.js → chunk-xtbjzbyn.js} +1 -1
  116. package/dist/cli/{chunk-kfr8dm31.js → chunk-y343681c.js} +1 -1
  117. package/dist/cli/chunk-y8b2p44q.js +1 -1
  118. package/dist/cli/chunk-yb75pw36.js +2 -0
  119. package/dist/cli/{chunk-5jbfscxy.js → chunk-ycqt3445.js} +1 -1
  120. package/dist/cli/{chunk-1kxnpa9w.js → chunk-yeysn5x1.js} +3 -3
  121. package/dist/cli/{chunk-mdebknyq.js → chunk-yjeh02k3.js} +1 -1
  122. package/dist/cli/{chunk-tpc0002n.js → chunk-yv77a1p9.js} +1 -1
  123. package/dist/cli/{chunk-22emnsn5.js → chunk-z46zwmyq.js} +1 -1
  124. package/dist/cli/{chunk-ee5a0pka.js → chunk-z6t0rmg1.js} +6 -4
  125. package/dist/cli/index.js +7 -7
  126. package/dist/cli/rove-run.js +1 -1
  127. package/dist/cli/rove.js +6 -6
  128. package/dist/skills/rove/SKILL.md +40 -20
  129. package/dist/skills/rove/references/api-flags.md +15 -11
  130. package/dist/web/assets/{index-Cd9SayTz.js → index-CJt_9NpJ.js} +4 -4
  131. package/dist/web/assets/{term-mount-aQMkgSR7.js → term-mount-BhfGkya5.js} +1 -1
  132. package/dist/web/index.html +1 -1
  133. package/package.json +2 -1
  134. package/dist/cli/chunk-0jdvy6hk.js +0 -2
  135. package/dist/cli/chunk-2vkxtms5.js +0 -20
  136. package/dist/cli/chunk-335g4j0y.js +0 -2
  137. package/dist/cli/chunk-5yfffvqe.js +0 -2
  138. package/dist/cli/chunk-7zh7adny.js +0 -2
  139. package/dist/cli/chunk-81q3t424.js +0 -2
  140. package/dist/cli/chunk-8h94w236.js +0 -2
  141. package/dist/cli/chunk-cxef4y2s.js +0 -2
  142. package/dist/cli/chunk-dxwmnww0.js +0 -2
  143. package/dist/cli/chunk-e3jddh9d.js +0 -2
  144. package/dist/cli/chunk-g5sx5knm.js +0 -2
  145. package/dist/cli/chunk-k5arcpfm.js +0 -2
  146. package/dist/cli/chunk-k5pd6q0r.js +0 -2
  147. package/dist/cli/chunk-mkb5mmmw.js +0 -2
  148. package/dist/cli/chunk-nka82csc.js +0 -2
  149. package/dist/cli/chunk-nn130cde.js +0 -2
  150. package/dist/cli/chunk-np319fys.js +0 -2
  151. package/dist/cli/chunk-pzy7fe5e.js +0 -3
  152. package/dist/cli/chunk-q23gw6np.js +0 -2
  153. package/dist/cli/chunk-s61xd58f.js +0 -2
  154. package/dist/cli/chunk-s88gxrtj.js +0 -2
  155. package/dist/cli/chunk-sfrsqpvn.js +0 -2
  156. package/dist/cli/chunk-tjh04p1x.js +0 -2
  157. package/dist/cli/chunk-w1rgfjkp.js +0 -2
  158. package/dist/cli/chunk-x1jxxmtc.js +0 -3
  159. package/dist/cli/chunk-y57tnbwp.js +0 -2
  160. package/dist/cli/chunk-z16wb344.js +0 -2
  161. package/dist/cli/chunk-z3hfz52n.js +0 -2
  162. package/dist/cli/chunk-zw9w8wbk.js +0 -63
@@ -1,7 +1,7 @@
1
1
  // @bun
2
- import{expandTilde}from"./chunk-2r1fgng9.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{SUBCOMMAND_VERBS}from"./chunk-nbcm8d58.js";import"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{resolve}from"path";var CLI_NAME=ROVE_PRODUCT_NAME,REPO_USAGE=[`Usage: ${CLI_NAME} repo <show|set|unset> [path] [options]`,"","Manage a repo's per-user init override (state.json fallback for repos","that don't ship .rove/init.sh / .rove/init-prompt.md).","","Commands:"," show [path] Print the override + repo convention files"," set [path] <options> Set the init script and/or first prompt"," unset [path] [--init-script] [--init-prompt] Clear one or both (default: both)","","Set options (later wins; *-file reads from disk):"," --init-script <text> Inline shell to run before the engine"," --init-script-file <path> Read the init script from a file"," --init-prompt <text> Inline first prompt for the engine"," --init-prompt-file <path> Read the first prompt from a file",""," path defaults to the current directory (resolved to its git toplevel).",""].join(`
2
+ import{SUBCOMMAND_VERBS}from"./chunk-nbcm8d58.js";import{expandTilde}from"./chunk-jrzh4yv6.js";import{errorMessage}from"./chunk-2brn8e1y.js";import"./chunk-pn5ygqn6.js";import"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{resolve}from"path";var CLI_NAME=ROVE_PRODUCT_NAME,REPO_USAGE=[`Usage: ${CLI_NAME} repo <show|set|unset> [path] [options]`,"","Manage a repo's per-user init override (state.json fallback for repos","that don't ship .rove/init.sh / .rove/init-prompt.md).","","Commands:"," show [path] Print the override + repo convention files"," set [path] <options> Set the init script and/or first prompt"," unset [path] [--init-script] [--init-prompt] Clear one or both (default: both)","","Set options (later wins; *-file reads from disk):"," --init-script <text> Inline shell to run before the engine"," --init-script-file <path> Read the init script from a file"," --init-prompt <text> Inline first prompt for the engine"," --init-prompt-file <path> Read the first prompt from a file",""," path defaults to the current directory (resolved to its git toplevel).",""].join(`
3
3
  `);function usageError(message){process.stderr.write(`${CLI_NAME} repo: ${message}
4
4
 
5
5
  ${REPO_USAGE}
6
6
  `),process.exit(2)}function readArgFile(path){try{return readFileSync(resolve(process.cwd(),expandTilde(path)),"utf8")}catch(err){usageError(`cannot read ${path}: ${errorMessage(err)}`)}}function parseRepoArgs(args){let out={};for(let i=0;i<args.length;i++){let a=args[i],need=()=>{let v=args[++i];if(v===void 0)usageError(`${a} requires a value`);return v};if(a==="--init-script")out.initScript=need();else if(a==="--init-script-file")out.initScript=readArgFile(need());else if(a==="--init-prompt")out.initPrompt=need();else if(a==="--init-prompt-file")out.initPrompt=readArgFile(need());else if(a.startsWith("-"))usageError(`unknown flag "${a}"`);else if(out.path===void 0)out.path=a;else usageError(`unexpected argument "${a}"`)}return out}function parseUnsetArgs(args){let path,clearScript=!1,clearPrompt=!1;for(let a of args)if(a==="--init-script")clearScript=!0;else if(a==="--init-prompt")clearPrompt=!0;else if(a.startsWith("-"))usageError(`unknown flag "${a}"`);else if(path===void 0)path=a;else usageError(`unexpected argument "${a}"`);if(!clearScript&&!clearPrompt)clearScript=!0,clearPrompt=!0;return{path,clearScript,clearPrompt}}async function runRepoSubcommand(args){let[verb,...rest]=args;if(verb===void 0||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${REPO_USAGE}
7
- `);return}if(!SUBCOMMAND_VERBS.repo.includes(verb))usageError(`unknown verb "${verb}"`);let{getRepoInitOverride,setRepoInitOverride,resolveRepoRoot}=await import("./chunk-an97ga8b.js");if(verb==="show"){let[pathArg]=rest.filter((a)=>!a.startsWith("-")),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(pathArg??"."))),override=getRepoInitOverride(repo),{describeRepoInitSources}=await import("./chunk-z3hfz52n.js"),sources=describeRepoInitSources(repo);console.log(`repo: ${repo}`);for(let group of[sources.script,sources.prompt])group.forEach((source,index)=>{console.log(` ${`${source.rel}:`.padEnd(22)}${describeSource(group,index)}`)});console.log(` override initScript: ${override.initScript?quotePreview(override.initScript):"(unset)"}`),console.log(` override initPrompt: ${override.initPrompt?quotePreview(override.initPrompt):"(unset)"}`);return}if(verb==="set"){let flags=parseRepoArgs(rest);if(flags.initScript===void 0&&flags.initPrompt===void 0)usageError("set needs at least one of --init-script(-file) / --init-prompt(-file)");let repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(flags.path??"."))),next=setRepoInitOverride(repo,{...flags.initScript!==void 0?{initScript:flags.initScript}:{},...flags.initPrompt!==void 0?{initPrompt:flags.initPrompt}:{}});console.log(`updated override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}if(verb==="unset"){let{path,clearScript,clearPrompt}=parseUnsetArgs(rest),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(path??"."))),next=setRepoInitOverride(repo,{...clearScript?{initScript:""}:{},...clearPrompt?{initPrompt:""}:{}});console.log(`cleared override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}usageError(`unknown verb "${verb}"`)}function describeSource(group,index){let source=group[index];if(!source)return"absent";if(source.effective)return"present (wins)";if(!source.present)return"absent";return group.slice(0,index).some((earlier)=>earlier.effective)?"present (shadowed)":"present but empty (ignored)"}function quotePreview(value){let oneLine=value.replace(/\s+/g," ").trim();return oneLine.length>60?`"${oneLine.slice(0,57)}\u2026"`:`"${oneLine}"`}export{runRepoSubcommand};
7
+ `);return}if(!SUBCOMMAND_VERBS.repo.includes(verb))usageError(`unknown verb "${verb}"`);let{getRepoInitOverride,setRepoInitOverride,resolveRepoRoot}=await import("./chunk-ghww7w7x.js");if(verb==="show"){let[pathArg]=rest.filter((a)=>!a.startsWith("-")),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(pathArg??"."))),override=getRepoInitOverride(repo),{describeRepoInitSources}=await import("./chunk-pk2w9dtp.js"),sources=describeRepoInitSources(repo);console.log(`repo: ${repo}`);for(let group of[sources.script,sources.prompt])group.forEach((source,index)=>{console.log(` ${`${source.rel}:`.padEnd(22)}${describeSource(group,index)}`)});console.log(` override initScript: ${override.initScript?quotePreview(override.initScript):"(unset)"}`),console.log(` override initPrompt: ${override.initPrompt?quotePreview(override.initPrompt):"(unset)"}`);return}if(verb==="set"){let flags=parseRepoArgs(rest);if(flags.initScript===void 0&&flags.initPrompt===void 0)usageError("set needs at least one of --init-script(-file) / --init-prompt(-file)");let repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(flags.path??"."))),next=setRepoInitOverride(repo,{...flags.initScript!==void 0?{initScript:flags.initScript}:{},...flags.initPrompt!==void 0?{initPrompt:flags.initPrompt}:{}});console.log(`updated override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}if(verb==="unset"){let{path,clearScript,clearPrompt}=parseUnsetArgs(rest),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(path??"."))),next=setRepoInitOverride(repo,{...clearScript?{initScript:""}:{},...clearPrompt?{initPrompt:""}:{}});console.log(`cleared override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}usageError(`unknown verb "${verb}"`)}function describeSource(group,index){let source=group[index];if(!source)return"absent";if(source.effective)return"present (wins)";if(!source.present)return"absent";return group.slice(0,index).some((earlier)=>earlier.effective)?"present (shadowed)":"present but empty (ignored)"}function quotePreview(value){let oneLine=value.replace(/\s+/g," ").trim();return oneLine.length>60?`"${oneLine.slice(0,57)}\u2026"`:`"${oneLine}"`}export{runRepoSubcommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{dedupeMachines,discoverMachine,ensureForwards,learnedFrom,listMachines,localDaemonSocketPath,localPtySocketPath,updateMachine}from"./chunk-pmwk2etg.js";import{DISPATCH_PROMPT_HEAD_CHARS,normalizeRemoteUrl,resolvePtyOwner}from"./chunk-vp29jgbt.js";import{taskEngineArgv}from"./chunk-xj8bma5k.js";import{roveApiInvocation}from"./chunk-c69xdgfz.js";import{ApiError}from"./chunk-r5j8fycq.js";import{ptyScopeFor}from"./chunk-g9ba25q5.js";import{connectIfRunning}from"./chunk-5mhf43dx.js";import{getSavedRepos,isRemoteRepoKey}from"./chunk-gygdyf0s.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";import{RoveDaemonClient}from"./chunk-8y10pmkf.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{hostname}from"os";async function ptyScopeOf(daemon,task){let listed=await daemon.request("task.list",{}).catch(()=>({tasks:[]})),scope=ptyScopeFor(listed.tasks,task.id);return task.ptyAlias?{...scope,alias:task.ptyAlias}:scope}async function recordSend(daemon,sent){let self=await ownSession(daemon).catch(()=>null);await daemon.request("dispatch.record",{taskId:sent.taskId,...sent.tabId?{tabId:sent.tabId}:{},promptHead:sent.prompt.slice(0,DISPATCH_PROMPT_HEAD_CHARS),delivered:sent.delivered,...sent.deliveryId?{deliveryId:sent.deliveryId}:{},...self?{fromTaskId:self.taskId,fromTabId:self.tabId}:{}}).catch(()=>{})}var selfSessionOnce,identityWarning=null;async function realProbe(){let[{openPtyHost,listSessions},{psSnapshot}]=await Promise.all([import("./chunk-k5pd6q0r.js"),import("./chunk-81q3t424.js")]);return{sessions:async()=>{let host=await openPtyHost();if(!host)return[];try{return await listSessions(host.rpc)}finally{host.close()}},ps:psSnapshot,pid:process.pid}}async function verifiedSelfSession(env=process.env,probe){if(!probe&&selfSessionOnce)return selfSessionOnce;let run=resolveSelfSession(env,probe);return selfSessionOnce=run,run}async function resolveSelfSession(env,probe){let taskId=env.ROVE_TASK_ID;if(!taskId)return null;let tabId=env.ROVE_TAB_ID||"tab-1";try{let p=probe??await realProbe(),key=`${taskId}::${tabId}`,session=(await p.sessions()).find((s)=>s.key===key&&s.alive);if(session?.pid){let{hasAncestor,parsePsSnapshot}=await import("./chunk-81q3t424.js");if(hasAncestor(parsePsSnapshot(await p.ps([session.pid,p.pid])),p.pid,session.pid))return identityWarning=null,{taskId,tabId}}}catch{}return identityWarning=`$ROVE_TASK_ID/$ROVE_TASK_ID names task ${taskId} ${tabId}, but this process is not running inside that tab (an inherited env, not an identity) \u2014 dispatcher/peer provenance omitted`,null}function takeIdentityWarning(){let warning=identityWarning;return identityWarning=null,warning}async function ownSession(daemon,env=process.env,probe){let self=await verifiedSelfSession(env,probe);if(!self)return null;let listed=await daemon.request("task.list",{}).catch(()=>({tasks:[]}));return{...self,taskId:resolvePtyOwner(listed.tasks,self.taskId,self.tabId)}}async function dispatcherEnvPayload(daemon,env=process.env,probe){let self=await ownSession(daemon,env,probe);if(!self)return{};return{dispatcherTaskId:self.taskId,dispatcherTabId:self.tabId}}async function readOwnDispatcher(daemon){let self=await ownSession(daemon);if(!self)return null;try{return(await daemon.request("task.get",{taskId:self.taskId})).task.dispatcher??null}catch{return null}}async function resolveDispatcherTab(runtime,daemon,dispatcher){let task=await daemon.request("task.get",{taskId:dispatcher.taskId}).then((res)=>res.task).catch(()=>null),{tabs,running}=await runtime.taskTabs(dispatcher.taskId,void 0,task?await ptyScopeOf(daemon,task):void 0);if(tabs.some((t)=>t.id===dispatcher.tabId&&t.alive))return dispatcher.tabId;if(running)return;throw new ApiError(`dispatcher tab ${dispatcher.tabId} on task ${dispatcher.taskId} is dead and the task has no live engine tab \u2014 the reply has nowhere to land`,"DISPATCHER_UNREACHABLE",{dispatcher,hint:`address an alive target explicitly with --task-id/--tab (see \`${ROVE_PRODUCT_NAME} api pty-list\`), or notify the user with \`${ROVE_PRODUCT_NAME} api notify\``,nextCommandArgs:["api","pty-list"]})}async function replyTabOf(runtime,daemon,taskId){let self=await ownSession(daemon);if(self?.taskId===taskId)return self.tabId;let task=await daemon.request("task.get",{taskId}).then((res)=>res.task).catch(()=>null);if(!task)return;let{tabs}=await runtime.taskTabs(taskId,taskEngineArgv(task),await ptyScopeOf(daemon,task));return tabs.find((t)=>t.kind==="engine"&&t.alive===!0&&t.engineAlive!==!1)?.id}async function withPeerProvenance(daemon,targetTaskId,prompt){let self=await ownSession(daemon),senderId=self?.taskId;if(!self||!senderId||senderId===targetTaskId)return prompt;let label=senderId;try{let res=await daemon.request("task.get",{taskId:senderId});label=res.task.title||res.task.branch||senderId}catch{}let api=roveApiInvocation(),replyTarget=`--task-id ${senderId} --tab ${self.tabId}`;return`[ROVE PEER] from "${label}" (task ${senderId} \u2014 Rove agent skill /rove, read it once per session; reply only if it changes what I do next: \`${api} send ${replyTarget} --prompt "<text>"\`)
2
+ import{dedupeMachines,discoverMachine,ensureForwards,learnedFrom,listMachines,localDaemonSocketPath,localPtySocketPath,updateMachine}from"./chunk-mdfm45fx.js";import{DISPATCH_PROMPT_HEAD_CHARS,normalizeRemoteUrl,resolvePtyOwner}from"./chunk-vp29jgbt.js";import{taskEngineArgv}from"./chunk-k2p7at32.js";import{roveApiInvocation}from"./chunk-5c2syc7e.js";import{ApiError}from"./chunk-r5j8fycq.js";import{ptyScopeFor}from"./chunk-g9ba25q5.js";import{connectIfRunning}from"./chunk-e5crm07d.js";import{RoveDaemonClient}from"./chunk-qq2mjph2.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{getSavedRepos,isRemoteRepoKey}from"./chunk-rja9tf6j.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{hostname}from"os";async function ptyScopeOf(daemon,task){let listed=await daemon.request("task.list",{}).catch(()=>({tasks:[]})),scope=ptyScopeFor(listed.tasks,task.id);return task.ptyAlias?{...scope,alias:task.ptyAlias}:scope}async function recordSend(daemon,sent){let self=await ownSession(daemon).catch(()=>null);await daemon.request("dispatch.record",{taskId:sent.taskId,...sent.tabId?{tabId:sent.tabId}:{},promptHead:sent.prompt.slice(0,DISPATCH_PROMPT_HEAD_CHARS),delivered:sent.delivered,...sent.deliveryId?{deliveryId:sent.deliveryId}:{},...self?{fromTaskId:self.taskId,fromTabId:self.tabId}:{}}).catch(()=>{})}var selfSessionOnce,identityWarning=null;async function realProbe(){let[{openPtyHost,listSessions},{psSnapshot}]=await Promise.all([import("./chunk-w8a3gsvw.js"),import("./chunk-gpq30qgy.js")]);return{sessions:async()=>{let host=await openPtyHost();if(!host)return[];try{return await listSessions(host.rpc)}finally{host.close()}},ps:psSnapshot,pid:process.pid}}async function verifiedSelfSession(env=process.env,probe){if(!probe&&selfSessionOnce)return selfSessionOnce;let run=resolveSelfSession(env,probe);return selfSessionOnce=run,run}async function resolveSelfSession(env,probe){let taskId=env.ROVE_TASK_ID;if(!taskId)return null;let tabId=env.ROVE_TAB_ID||"tab-1";try{let p=probe??await realProbe(),key=`${taskId}::${tabId}`,session=(await p.sessions()).find((s)=>s.key===key&&s.alive);if(session?.pid){let{hasAncestor,parsePsSnapshot}=await import("./chunk-gpq30qgy.js");if(hasAncestor(parsePsSnapshot(await p.ps([session.pid,p.pid])),p.pid,session.pid))return identityWarning=null,{taskId,tabId}}}catch{}return identityWarning=`$ROVE_TASK_ID/$ROVE_TASK_ID names task ${taskId} ${tabId}, but this process is not running inside that tab (an inherited env, not an identity) \u2014 dispatcher/peer provenance omitted`,null}function takeIdentityWarning(){let warning=identityWarning;return identityWarning=null,warning}async function ownSession(daemon,env=process.env,probe){let self=await verifiedSelfSession(env,probe);if(!self)return null;let listed=await daemon.request("task.list",{}).catch(()=>({tasks:[]}));return{...self,taskId:resolvePtyOwner(listed.tasks,self.taskId,self.tabId)}}async function dispatcherEnvPayload(daemon,env=process.env,probe){let self=await ownSession(daemon,env,probe);if(!self)return{};return{dispatcherTaskId:self.taskId,dispatcherTabId:self.tabId}}async function readOwnDispatcher(daemon){let self=await ownSession(daemon);if(!self)return null;try{return(await daemon.request("task.get",{taskId:self.taskId})).task.dispatcher??null}catch{return null}}async function resolveDispatcherTab(runtime,daemon,dispatcher){let task=await daemon.request("task.get",{taskId:dispatcher.taskId}).then((res)=>res.task).catch(()=>null),{tabs,running}=await runtime.taskTabs(dispatcher.taskId,void 0,task?await ptyScopeOf(daemon,task):void 0);if(tabs.some((t)=>t.id===dispatcher.tabId&&t.alive))return dispatcher.tabId;if(running)return;throw new ApiError(`dispatcher tab ${dispatcher.tabId} on task ${dispatcher.taskId} is dead and the task has no live engine tab \u2014 the reply has nowhere to land`,"DISPATCHER_UNREACHABLE",{dispatcher,hint:`address an alive target explicitly with --task-id/--tab (see \`${ROVE_PRODUCT_NAME} api pty-list\`), or notify the user with \`${ROVE_PRODUCT_NAME} api notify\``,nextCommandArgs:["api","pty-list"]})}async function replyTabOf(runtime,daemon,taskId){let self=await ownSession(daemon);if(self?.taskId===taskId)return self.tabId;let task=await daemon.request("task.get",{taskId}).then((res)=>res.task).catch(()=>null);if(!task)return;let{tabs}=await runtime.taskTabs(taskId,taskEngineArgv(task),await ptyScopeOf(daemon,task));return tabs.find((t)=>t.kind==="engine"&&t.alive===!0&&t.engineAlive!==!1)?.id}async function withPeerProvenance(daemon,targetTaskId,prompt){let self=await ownSession(daemon),senderId=self?.taskId;if(!self||!senderId||senderId===targetTaskId)return prompt;let label=senderId;try{let res=await daemon.request("task.get",{taskId:senderId});label=res.task.title||res.task.branch||senderId}catch{}let api=roveApiInvocation(),replyTarget=`--task-id ${senderId} --tab ${self.tabId}`;return`[ROVE PEER] from "${label}" (task ${senderId} \u2014 Rove agent skill /rove, read it once per session; reply only if it changes what I do next: \`${api} send ${replyTarget} --prompt "<text>"\`)
3
3
 
4
4
  ${prompt}`}import{spawnSync}from"child_process";import{existsSync}from"fs";import{join}from"path";function git(cwd,args){let res=spawnSync("git",["-C",cwd,...args],{encoding:"utf8",timeout:5000});return res.status===0?res.stdout.trim():null}function repoIdentity(path){if(!existsSync(path)||git(path,["rev-parse","--git-dir"])===null)return null;let origin=git(path,["remote","get-url","origin"]),root=git(path,["rev-list","--max-parents=0","HEAD"])?.split(`
5
5
  `).filter(Boolean).sort()[0];return{...origin?{origin:normalizeRemoteUrl(origin)}:{},...root?{root}:{}}}function isLocalCheckout(path){return existsSync(join(path,".git"))||existsSync(path)&&git(path,["rev-parse","--git-dir"])!==null}function unpushedCommits(path,ref){if(git(path,["rev-parse","--verify","--quiet",`${ref}^{commit}`])===null)return null;let ahead=git(path,["rev-list","--count",`${ref}@{upstream}..${ref}`]);if(ahead!==null)return Number.parseInt(ahead,10)||0;let lone=git(path,["rev-list","--count",ref,"--not","--remotes"]);return lone===null?null:Number.parseInt(lone,10)||0}import{spawnSync as spawnSync2}from"child_process";import{existsSync as existsSync2,mkdirSync}from"fs";import{homedir}from"os";import{dirname,isAbsolute,join as join2,resolve}from"path";var URL_LIKE=/^[a-z][a-z0-9+.-]*:\/\//i,SCP_LIKE=/^[^@/\s]+@[^:/\s]+:[^\s]+$/,SEGMENT=/^[A-Za-z0-9_.-]+$/;function parseRepoRef(raw,cwd=process.cwd(),exists=existsSync2){let value=raw.trim(),asPath={kind:"path",path:value};if(value===""||isRemoteRepoKey(value))return asPath;if(URL_LIKE.test(value)||SCP_LIKE.test(value))return{kind:"id",id:normalizeRemoteUrl(value),cloneUrl:value};if(isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value)||/^[~.\\]/.test(value))return asPath;if(exists(resolve(cwd,value)))return asPath;let parts=value.replace(/\.git$/i,"").split("/");if(!parts.every((p)=>SEGMENT.test(p)))return asPath;if(parts.length===2){let id=`github.com/${parts.join("/")}`.toLowerCase();return{kind:"id",id,cloneUrl:`https://${id}.git`}}if(parts.length>=3&&parts[0]?.includes(".")){let id=parts.join("/").toLowerCase();return{kind:"id",id,cloneUrl:`https://${id}.git`}}return asPath}function repoIdOf(identity){if(!identity)return null;if(identity.origin)return identity.origin;return identity.root?`root:${identity.root}`:null}function findCheckouts(want,candidates){let out=[];for(let c of candidates){let sameRoot=Boolean(want.root&&c.identity.root===want.root),sameOrigin=Boolean(want.origin&&c.identity.origin===want.origin);if(!sameRoot&&!sameOrigin)continue;let fork=sameRoot&&!sameOrigin&&Boolean(want.origin&&c.identity.origin);out.push({path:c.path,via:sameRoot?"root":"origin",fork})}return out}function pickCheckout(matches,opts){let usable=matches.filter((m)=>opts.allowFork||!m.fork);if(usable.length===0){let fork=matches.find((m)=>m.fork)?.path;return fork?{path:null,fork}:{path:null}}let primary=usable.find((m)=>m.path===opts.primary);if(primary)return{path:primary.path};if(usable.length>1&&opts.isClean){let clean=usable.find((m)=>opts.isClean?.(m.path));if(clean)return{path:clean.path}}return{path:usable[0]?.path??null}}function isCleanCheckout(path){let res=spawnSync2("git",["-C",path,"status","--porcelain","--untracked-files=no"],{encoding:"utf8",timeout:5000});return res.status===0&&res.stdout.trim()===""}var REPO_PRIMARY_KEY="repoPrimary";function primaryCheckouts(state=loadStateFile()){let raw=state[REPO_PRIMARY_KEY],out={};if(raw&&typeof raw==="object"){for(let[id,path]of Object.entries(raw))if(typeof path==="string")out[id]=path}return out}function setPrimaryCheckout(id,path){updateStateFile((state)=>{let next=primaryCheckouts(state);if(path===null)Reflect.deleteProperty(next,id);else next[id]=path;return state[REPO_PRIMARY_KEY]=next,!0})}function cloneDirFor(id,home=homedir()){return join2(home,".rove","repos",...id.split("/"))}function cloneRepo(ref,home){let dir=cloneDirFor(ref.id,home);if(repoIdentity(dir))return dir;mkdirSync(dirname(dir),{recursive:!0});let res=spawnSync2("git",["clone",ref.cloneUrl,dir],{encoding:"utf8",timeout:600000,env:{...process.env,GIT_TERMINAL_PROMPT:"0"}});if(res.status!==0)throw Error((res.stderr||res.stdout||"git clone failed").trim());return dir}var LOCAL_MACHINE="local";async function machineDaemonSocket(entry){let socketPath=localDaemonSocketPath(entry.alias);if(await answers(socketPath))return socketPath;if(!entry.sockets||!await forward(entry,entry.sockets))return null;if(await answers(socketPath))return socketPath;let found=await discoverMachine(entry.alias,entry);if(!found.ok)return null;let learned=learnedFrom(found);return updateMachine(entry.alias,learned),await forward({...entry,...learned},learned.sockets)&&await answers(socketPath)?socketPath:null}function forward(entry,sockets){return ensureForwards({alias:entry.alias,config:{...entry,sockets},remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty})}async function answers(socketPath){let client=new RoveDaemonClient(socketPath);try{return await client.request("hello",{}),!0}catch{return!1}finally{client.close()}}async function machineTasks(entry){let socketPath=await machineDaemonSocket(entry);if(!socketPath)return null;let client=new RoveDaemonClient(socketPath);try{return(await client.request("task.list")).tasks??[]}catch{return null}finally{client.close()}}function requireMachine(alias){let entry=listMachines().find((m)=>m.alias===alias);if(entry)return entry;throw new ApiError(`no machine named "${alias}"`,"UNKNOWN_MACHINE",{hint:"list the registered machines and retry with one of their aliases, or register it first",nextCommandArgs:["machine","list"]})}var AUTO_MACHINE="auto",busy=(tasks)=>tasks.filter((task)=>task.status==="in_progress").length;async function pickMachine(localTasks,readTasks=machineTasks,machines=dedupeMachines(listMachines()),hosts){let[local,...remote]=await Promise.all([localTasks().catch(()=>[]),...machines.map((entry)=>readTasks(entry))]),loads={[LOCAL_MACHINE]:busy(local)};machines.forEach((entry,i)=>{let tasks=remote[i];if(tasks)loads[entry.alias]=busy(tasks)});let pool=[null,...machines.filter((entry)=>loads[entry.alias]!==void 0)],skipped;if(hosts){let ok=await Promise.all(pool.map((entry)=>hosts(entry).catch(()=>!1)));if(ok.some(Boolean))skipped=pool.filter((_,i)=>!ok[i]).map((entry)=>entry?.alias??LOCAL_MACHINE),pool=pool.filter((_,i)=>ok[i])}let best=null,bestLoad=Number.POSITIVE_INFINITY;for(let entry of pool){let load=loads[entry?.alias??LOCAL_MACHINE]??0;if(load<bestLoad)best=entry,bestLoad=load}return{entry:best,loads,...skipped?{skipped}:{}}}function repoWanted(repo){if(typeof repo!=="string")return null;let ref=parseRepoRef(repo);if(ref.kind==="id")return{origin:ref.id};return isLocalCheckout(ref.path)?repoIdentity(ref.path):null}function repoHosts(params){if(flagOn(params.clone))return;let want=repoWanted(params.repo);if(!want||!want.origin&&!want.root)return;return async(entry)=>{if(entry===null){if(typeof params.repo==="string"&&parseRepoRef(params.repo).kind==="path")return!0;return getSavedRepos().some((path)=>findCheckouts(want,[{path,identity:repoIdentity(path)??{}}]).length)}let socket=await machineDaemonSocket(entry);if(!socket)return!1;let client=new RoveDaemonClient(socket);try{let res=await client.request("api.invoke",{verb:"repo-match",params:{...want.origin?{origin:want.origin}:{},...want.root?{root:want.root}:{}},forwarded:!0,from:hostname()});return res.ok&&Boolean(res.result.repo)}finally{client.close()}}}async function routeTarget(args){if(args.machine===AUTO_MACHINE){let hosts=args.params?repoHosts(args.params):void 0;return(await pickMachine(args.localTasks??(async()=>[]),machineTasks,void 0,hosts)).entry}if(args.machine!==void 0&&args.machine!==LOCAL_MACHINE)return requireMachine(args.machine);if(args.machine===LOCAL_MACHINE||!args.taskId)return null;let machines=dedupeMachines(listMachines());if(machines.length===0||await args.isLocalTask(args.taskId))return null;for(let entry of machines)if((await machineTasks(entry))?.some((task)=>task.id===args.taskId))return entry;return null}async function forwardVerb(entry,verb,params,socketPath){let target=socketPath??await machineDaemonSocket(entry);if(!target)return offline(entry.alias);let client=new RoveDaemonClient(target);try{let repo=await translateRepo(client,entry.alias,params);if(repo.failure)return repo.failure;if(verb==="land"&&params["dry-run"]===void 0){let published=await client.request("api.invoke",{verb:"publish",params:{"task-id":params["task-id"]},forwarded:!0,from:hostname()});if(published.ok||published.error.code!=="UNKNOWN_VERB")return published}let envelope=await client.request("api.invoke",{verb,params:repo.params,forwarded:!0,from:hostname()});return await recordHere(verb,params,envelope),envelope}catch(err){let message=errorMessage(err);if(/unknown daemon request:/i.test(message))return tooOld(entry.alias);return failure("MACHINE_UNREACHABLE",`machine "${entry.alias}": ${message}`,{hint:"check the machine is up and reachable over ssh, then retry",nextCommandArgs:["machine","list"]})}finally{client.close()}}async function recordHere(verb,params,envelope){if(verb!=="send"&&verb!=="dispatch"||!envelope.ok||typeof params.prompt!=="string")return;let sent=envelope.result,taskId=typeof sent.childTaskId==="string"?sent.childTaskId:sent.taskId;if(typeof taskId!=="string")return;let tabId=typeof sent.tabId==="string"?sent.tabId:typeof sent.session==="string"?sent.session.split("::")[1]:void 0,local=await connectIfRunning().catch(()=>null);if(!local)return;try{await recordSend(local,{taskId,...tabId?{tabId}:{},prompt:params.prompt,delivered:sent.delivered===!0})}finally{local.close()}}async function translateRepo(client,alias,params){let repo=params.repo;if(typeof repo!=="string")return{params};let ref=parseRepoRef(repo),local=ref.kind==="path"&&isLocalCheckout(ref.path);if(ref.kind==="path"&&!local)return{params};let identity=ref.kind==="id"?{origin:ref.id}:repoIdentity(repo);if(!identity?.origin&&!identity?.root)return{params};let allowFork=flagOn(params["allow-fork"]),ask=await client.request("api.invoke",{verb:"repo-match",params:{...identity.origin?{origin:identity.origin}:{},...identity.root?{root:identity.root}:{},...allowFork?{"allow-fork":!0}:{}},forwarded:!0,from:hostname()});if(!ask.ok)return ask.error.code==="UNKNOWN_VERB"?{params}:{failure:ask};let answer=ask.result,found=answer.repo;if(found){let base=params["base-branch"],unpushed=local&&typeof base==="string"?unpushedCommits(repo,base):null;if(typeof base==="string"&&unpushed)return{failure:failure("UNPUSHED_BASE",`${base} has ${unpushed} commit${unpushed===1?"":"s"} no remote has; ${alias} cannot base a task on it`,{hint:`push it first (\`git -C ${repo} push -u origin ${base}\`), then dispatch again`})};return{params:{...params,repo:found}}}if(answer.fork)return{failure:failure("FORK_MATCH",`machine "${alias}" only has ${answer.fork}, a fork of ${identity.origin??repo} (same history, other origin)`,{hint:"pass --allow-fork to use it, or --clone with the repo id to fetch the repo itself there"})};if(flagOn(params.clone)&&identity.origin)return{params:{...params,repo:ref.kind==="id"?repo:identity.origin}};return{failure:failure("NO_REMOTE_CHECKOUT",`machine "${alias}" has no checkout of ${identity.origin??repo}`,{hint:identity.origin?`pass --clone to clone it on ${alias}, or --repo with ${alias}'s own path`:`clone it on ${alias} (and open it there once so Rove knows it), or pass --repo with ${alias}'s own path`})}}var flagOn=(value)=>value===!0||value==="true";function offline(alias){return failure("MACHINE_UNREACHABLE",`machine "${alias}" did not answer`,{hint:`check \`ssh ${alias} true\` works without a prompt, then retry`,nextCommandArgs:["machine","list"]})}function tooOld(alias){return failure("MACHINE_VERSION_SKEW",`machine "${alias}" runs a Rove too old to accept forwarded verbs`,{hint:`upgrade Rove on ${alias} (\`rove update\` there), then retry`})}function failure(code,message,data){return{apiVersion:ROVE_API_VERSION,ok:!1,error:{message,code,...data}}}async function invokeRouted(args){if(args.forwarded)return args.runHere();let taskId=args.params["task-id"],target;try{target=await routeTarget({machine:args.machine,taskId:typeof taskId==="string"?taskId:void 0,isLocalTask:args.isLocalTask,...args.localTasks?{localTasks:args.localTasks}:{},params:args.params})}catch(err){if(!(err instanceof ApiError))throw err;return failure(err.code,err.message,err.data??{})}return target?forwardVerb(target,args.verb,args.params):args.runHere()}async function machinePtySocket(alias){let entry=requireMachine(alias);if(!await machineDaemonSocket(entry))throw new ApiError(`machine "${alias}" did not answer`,"MACHINE_UNREACHABLE");return localPtySocketPath(alias)}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{getCustomEngineIds,getDisabledEngineIds}from"./chunk-gygdyf0s.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{JsonHookAdapter,ROVE_HOOK_VERSION,bobAuthSecretsPath,claudeGlobalConfigPath,codexAuthPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isRoveHook,kimiCredentialsPath,readTextFileSyncBounded,roveHookArgs,roveHookInvocation,skillsDirUnder,updateSharedJson,xdgConfigHome}from"./chunk-ks5g5ee2.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{isObject}from"./chunk-7ghwdjdc.js";import{__require}from"./chunk-91sykzqq.js";import{homedir as homedir9}from"os";import{join as join8}from"path";var GEMINI={rules:[{state:"blocked",any:["\u2502 apply this change","\u2502 allow execution","waiting for user confirmation"]},{state:"blocked",all:["do you want to proceed"],any:["yes"]},{state:"working",any:["esc to cancel"]}]},OPENCODE={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"]},{state:"working",any:["esc interrupt","esc to interrupt","ctrl+c to interrupt","esc again to interrupt"]},{state:"idle",any:["enter send"]}]},CURSOR={rules:[{state:"blocked",any:["press any key to log in"]},{state:"blocked",all:["proceed (y)"]},{state:"blocked",any:["run this command?","waiting for approval","skip (esc or n)","(y) (enter)"]},{state:"working",any:["esc to cancel","ctrl+c to stop"]}]},GROK={rules:[{state:"blocked",any:["\u26A0 action required","ctrl+o:yolo"]},{state:"blocked",all:["\u2503"],lineRegex:["^\\s*\u2503\\s+\\S+\\s+\\(\u25CB\\)"]},{state:"working",any:["[stop]"],lineRegex:["^\\s*[\\u2800-\\u28FF]"]}]},DROID={rules:[{state:"blocked",all:["enter to select","esc to cancel"],any:["> yes, allow","> no, cancel"]},{state:"blocked",all:["enter select","esc cancel"]},{state:"working",any:["esc to stop"]}]},AMP={rules:[{state:"blocked",any:["waiting for approval","run this command?","allow editing file:","allow creating file:","confirm tool call"]},{state:"working",lineRegex:["^\\s*\u2570\\s+\\S+\\s+(thinking|streaming|running tools|waiting)\\s+\u2500"]}]},CLINE={rules:[{state:"blocked",any:["let cline use this tool"]},{state:"blocked",all:["execute command?","yes"],any:["[act mode]","[plan mode]"]},{state:"blocked",all:["use this tool?","yes"],any:["[act mode]","[plan mode]"]}]},KIRO={rules:[{state:"blocked",all:["requires approval"],any:["yes, single permission","trust, always allow","no (tab to edit)","esc to close"]},{state:"blocked",all:["pending from subagents","tool approval"],any:["approve all pending","configure individually","exit (cancel subagents)"]},{state:"working",any:["kiro is working"]},{state:"working",all:["esc to cancel"],lineRegex:["^\\s*[\u25D4\u25D1\u25D5\u25CF]\\s+[A-Za-z]"]}]},MAKI={rules:[{state:"blocked",all:["permission required","y allow","n deny"]},{state:"blocked",all:["permission required"],any:["confirm allow","confirm deny"]},{state:"blocked",all:["permission required","enter deny","esc cancel"]},{state:"blocked",all:["plan complete","enter confirm"],any:["space toggle parallel","edit plan"]},{state:"working",bottomLines:1,lineRegex:["^( [\\u2800-\\u28FF]){1,2} \\[(BUILD|PLAN|BASH)\\]"]},{state:"idle",bottomLines:1,lineRegex:["^ \\[(BUILD|PLAN|BASH)\\]"]}]},ANTIGRAVITY={rules:[{state:"blocked",all:["requesting permission for:","do you want to proceed?"]},{state:"blocked",all:["requesting permission for:","tab amend","edit command"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]+\\s+[A-Za-z]+\\w*ing\\b"]},{state:"working",bottomLines:5,lineRegex:["\xB7\\s*[1-9][0-9]*\\s+task"]}]},DEVIN={rules:[{state:"blocked",bottomLines:8,all:["do you trust the authors of this directory?","yes, trust "]},{state:"blocked",bottomLines:8,all:["approve once","select","confirm","esc cancel"]},{state:"working",bottomLines:8,all:["running tools","esc to interrupt"]},{state:"working",bottomLines:6,all:["guide devin while it works"]},{state:"working",bottomLines:8,all:["reading shell ","timeout:"]},{state:"idle",bottomLines:8,all:["ask devin to build","features, fix bugs","your code"],lineRegex:["^\\s*\u276D Ask Devin to build"]},{state:"idle",bottomLines:6,all:["context:"],lineRegex:["^\\s*\u276D"]}]},QODERCLI={rules:[{state:"blocked",all:["waiting for user confirmation"],any:["yes","no","allow","reject"]},{state:"blocked",all:["awaiting approval"],any:["allow","reject"]},{state:"blocked",any:["permission required","allow once or always?","asking user","enter your response","review your answers:","shell awaiting input"]},{state:"working",any:["(esc to cancel,"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]\\s+.*[A-Za-z]"]}]},HERMES={rules:[{state:"blocked",bottomLines:14,any:["dangerous","approval","allow once","hermes needs your","type your answer","approve once","start a new session","keep going"],lineRegex:["enter\\s+(?:to\\s+)?(?:confirm|send)","press enter","\u2191/\u2193\\s+(?:to\\s+)?select","show full command","type 1/2/3","y/n quick","other \\(type"]},{state:"blocked",bottomLines:14,any:["sudo password","skill setup"]},{state:"blocked",bottomLines:14,all:["\uD83D\uDD11","for "]},{state:"working",bottomLines:5,any:["msg=interrupt","ctrl+c to interrupt","ctrl+c cancel"]}]},KILO={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"],lineRegex:["\u2191\u2193\\s*select","\u21C6\\s*tab"]},{state:"working",any:["esc interrupt"]}]},MASTRACODE={rules:[]};import{existsSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";function parseFlatHooks(raw){if(raw===void 0)return{ok:!0,doc:{}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{ok:!1,reason:`not valid JSON (${err instanceof Error?err.message:String(err)})`}}if(!isObject(parsed))return{ok:!1,reason:"top level is not a JSON object"};if(parsed.hooks===void 0)return{ok:!0,doc:parsed};if(!isObject(parsed.hooks))return{ok:!1,reason:'"hooks" is not an object'};for(let[event,entries]of Object.entries(parsed.hooks))if(!Array.isArray(entries))return{ok:!1,reason:`"hooks.${event}" is not an array`};return{ok:!0,doc:parsed}}function mergeFlatHooks(format,current,install,inv=roveHookInvocation()){let verbs=format.eventMap.map((spec)=>spec.verb),{hooks:rawHooks,...rest}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},quoting=hookCommandQuoting();for(let{event,verb}of format.eventMap){let kept=(Array.isArray(hooks[event])?hooks[event]:[]).filter((entry)=>!isRoveHook(entry,verbs));if(install){let command=quoteShellArgv([...inv,"hook",verb,...roveHookArgs(format.vendor)],quoting);kept.push(format.withType?{type:"command",command}:{command})}if(kept.length>0)hooks[event]=kept;else delete hooks[event]}return{version:1,...rest,hooks}}var CURSOR_HOOK_EVENT_MAP=[{event:"sessionStart",verb:"session-start"}],CURSOR_FORMAT={vendor:"cursor",eventMap:CURSOR_HOOK_EVENT_MAP};function cursorHooksPath(home=homedir()){let override=process.env.CURSOR_CONFIG_DIR?.trim();return join(override||join(home,".cursor"),"hooks.json")}function parseCursorHooks(raw){return parseFlatHooks(raw)}function mergeCursorHooks(current,install,inv=roveHookInvocation()){return mergeFlatHooks(CURSOR_FORMAT,current,install,inv)}class CursorHookAdapter{vendor="cursor";supportsHooks(){return!0}globalSettingsPath(){return cursorHooksPath()}activityDetailFromPayload(){return}cwdFromPayload(payload){let roots=payload.workspace_roots;return Array.isArray(roots)?firstString(...roots):void 0}sessionFromPayload(payload){let sessionId=firstString(payload.session_id,payload.conversation_id);if(!sessionId)return;let transcriptPath=firstString(payload.transcript_path);return{sessionId,...transcriptPath?{transcriptPath}:{}}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync(dirname(settingsFilePath)))return{ok:!0};let outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!0),parseCursorHooks);if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] cursor: skipped ${outcome.file}: ${outcome.reason}
2
+ import{getCustomEngineIds,getDisabledEngineIds}from"./chunk-rja9tf6j.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{JsonHookAdapter,ROVE_HOOK_VERSION,bobAuthSecretsPath,claudeGlobalConfigPath,codexAuthPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isRoveHook,kimiCredentialsPath,readTextFileSyncBounded,roveHookArgs,roveHookInvocation,skillsDirUnder,updateSharedJson,xdgConfigHome}from"./chunk-x02jmqj1.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{isObject}from"./chunk-7ghwdjdc.js";import{__require}from"./chunk-91sykzqq.js";import{homedir as homedir9}from"os";import{join as join8}from"path";var GEMINI={rules:[{state:"blocked",any:["\u2502 apply this change","\u2502 allow execution","waiting for user confirmation"]},{state:"blocked",all:["do you want to proceed"],any:["yes"]},{state:"working",any:["esc to cancel"]}]},OPENCODE={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"]},{state:"working",any:["esc interrupt","esc to interrupt","ctrl+c to interrupt","esc again to interrupt"]},{state:"idle",any:["enter send"]}]},CURSOR={rules:[{state:"blocked",any:["press any key to log in"]},{state:"blocked",all:["proceed (y)"]},{state:"blocked",any:["run this command?","waiting for approval","skip (esc or n)","(y) (enter)"]},{state:"working",any:["esc to cancel","ctrl+c to stop"]}]},GROK={rules:[{state:"blocked",any:["\u26A0 action required","ctrl+o:yolo"]},{state:"blocked",all:["\u2503"],lineRegex:["^\\s*\u2503\\s+\\S+\\s+\\(\u25CB\\)"]},{state:"working",any:["[stop]"],lineRegex:["^\\s*[\\u2800-\\u28FF]"]}]},DROID={rules:[{state:"blocked",all:["enter to select","esc to cancel"],any:["> yes, allow","> no, cancel"]},{state:"blocked",all:["enter select","esc cancel"]},{state:"working",any:["esc to stop"]}]},AMP={rules:[{state:"blocked",any:["waiting for approval","run this command?","allow editing file:","allow creating file:","confirm tool call"]},{state:"working",lineRegex:["^\\s*\u2570\\s+\\S+\\s+(thinking|streaming|running tools|waiting)\\s+\u2500"]}]},CLINE={rules:[{state:"blocked",any:["let cline use this tool"]},{state:"blocked",all:["execute command?","yes"],any:["[act mode]","[plan mode]"]},{state:"blocked",all:["use this tool?","yes"],any:["[act mode]","[plan mode]"]}]},KIRO={rules:[{state:"blocked",all:["requires approval"],any:["yes, single permission","trust, always allow","no (tab to edit)","esc to close"]},{state:"blocked",all:["pending from subagents","tool approval"],any:["approve all pending","configure individually","exit (cancel subagents)"]},{state:"working",any:["kiro is working"]},{state:"working",all:["esc to cancel"],lineRegex:["^\\s*[\u25D4\u25D1\u25D5\u25CF]\\s+[A-Za-z]"]}]},MAKI={rules:[{state:"blocked",all:["permission required","y allow","n deny"]},{state:"blocked",all:["permission required"],any:["confirm allow","confirm deny"]},{state:"blocked",all:["permission required","enter deny","esc cancel"]},{state:"blocked",all:["plan complete","enter confirm"],any:["space toggle parallel","edit plan"]},{state:"working",bottomLines:1,lineRegex:["^( [\\u2800-\\u28FF]){1,2} \\[(BUILD|PLAN|BASH)\\]"]},{state:"idle",bottomLines:1,lineRegex:["^ \\[(BUILD|PLAN|BASH)\\]"]}]},ANTIGRAVITY={rules:[{state:"blocked",all:["requesting permission for:","do you want to proceed?"]},{state:"blocked",all:["requesting permission for:","tab amend","edit command"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]+\\s+[A-Za-z]+\\w*ing\\b"]},{state:"working",bottomLines:5,lineRegex:["\xB7\\s*[1-9][0-9]*\\s+task"]}]},DEVIN={rules:[{state:"blocked",bottomLines:8,all:["do you trust the authors of this directory?","yes, trust "]},{state:"blocked",bottomLines:8,all:["approve once","select","confirm","esc cancel"]},{state:"working",bottomLines:8,all:["running tools","esc to interrupt"]},{state:"working",bottomLines:6,all:["guide devin while it works"]},{state:"working",bottomLines:8,all:["reading shell ","timeout:"]},{state:"idle",bottomLines:8,all:["ask devin to build","features, fix bugs","your code"],lineRegex:["^\\s*\u276D Ask Devin to build"]},{state:"idle",bottomLines:6,all:["context:"],lineRegex:["^\\s*\u276D"]}]},QODERCLI={rules:[{state:"blocked",all:["waiting for user confirmation"],any:["yes","no","allow","reject"]},{state:"blocked",all:["awaiting approval"],any:["allow","reject"]},{state:"blocked",any:["permission required","allow once or always?","asking user","enter your response","review your answers:","shell awaiting input"]},{state:"working",any:["(esc to cancel,"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]\\s+.*[A-Za-z]"]}]},HERMES={rules:[{state:"blocked",bottomLines:14,any:["dangerous","approval","allow once","hermes needs your","type your answer","approve once","start a new session","keep going"],lineRegex:["enter\\s+(?:to\\s+)?(?:confirm|send)","press enter","\u2191/\u2193\\s+(?:to\\s+)?select","show full command","type 1/2/3","y/n quick","other \\(type"]},{state:"blocked",bottomLines:14,any:["sudo password","skill setup"]},{state:"blocked",bottomLines:14,all:["\uD83D\uDD11","for "]},{state:"working",bottomLines:5,any:["msg=interrupt","ctrl+c to interrupt","ctrl+c cancel"]}]},KILO={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"],lineRegex:["\u2191\u2193\\s*select","\u21C6\\s*tab"]},{state:"working",any:["esc interrupt"]}]},MASTRACODE={rules:[]};import{existsSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";function parseFlatHooks(raw){if(raw===void 0)return{ok:!0,doc:{}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{ok:!1,reason:`not valid JSON (${err instanceof Error?err.message:String(err)})`}}if(!isObject(parsed))return{ok:!1,reason:"top level is not a JSON object"};if(parsed.hooks===void 0)return{ok:!0,doc:parsed};if(!isObject(parsed.hooks))return{ok:!1,reason:'"hooks" is not an object'};for(let[event,entries]of Object.entries(parsed.hooks))if(!Array.isArray(entries))return{ok:!1,reason:`"hooks.${event}" is not an array`};return{ok:!0,doc:parsed}}function mergeFlatHooks(format,current,install,inv=roveHookInvocation()){let verbs=format.eventMap.map((spec)=>spec.verb),{hooks:rawHooks,...rest}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},quoting=hookCommandQuoting();for(let{event,verb}of format.eventMap){let kept=(Array.isArray(hooks[event])?hooks[event]:[]).filter((entry)=>!isRoveHook(entry,verbs));if(install){let command=quoteShellArgv([...inv,"hook",verb,...roveHookArgs(format.vendor)],quoting);kept.push(format.withType?{type:"command",command}:{command})}if(kept.length>0)hooks[event]=kept;else delete hooks[event]}return{version:1,...rest,hooks}}var CURSOR_HOOK_EVENT_MAP=[{event:"sessionStart",verb:"session-start"}],CURSOR_FORMAT={vendor:"cursor",eventMap:CURSOR_HOOK_EVENT_MAP};function cursorHooksPath(home=homedir()){let override=process.env.CURSOR_CONFIG_DIR?.trim();return join(override||join(home,".cursor"),"hooks.json")}function parseCursorHooks(raw){return parseFlatHooks(raw)}function mergeCursorHooks(current,install,inv=roveHookInvocation()){return mergeFlatHooks(CURSOR_FORMAT,current,install,inv)}class CursorHookAdapter{vendor="cursor";supportsHooks(){return!0}globalSettingsPath(){return cursorHooksPath()}activityDetailFromPayload(){return}cwdFromPayload(payload){let roots=payload.workspace_roots;return Array.isArray(roots)?firstString(...roots):void 0}sessionFromPayload(payload){let sessionId=firstString(payload.session_id,payload.conversation_id);if(!sessionId)return;let transcriptPath=firstString(payload.transcript_path);return{sessionId,...transcriptPath?{transcriptPath}:{}}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync(dirname(settingsFilePath)))return{ok:!0};let outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!0),parseCursorHooks);if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] cursor: skipped ${outcome.file}: ${outcome.reason}
3
3
  `);return outcome}async removeActivityHooks(settingsFilePath){if(!existsSync(settingsFilePath))return;await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!1),parseCursorHooks)}hookConfigRefusal(raw){let parsed=parseCursorHooks(raw);return parsed.ok?void 0:parsed.reason}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}function firstString(...values){for(let value of values)if(typeof value==="string"&&value)return value;return}import{homedir as homedir2}from"os";import{join as join2}from"path";import{existsSync as existsSync2}from"fs";import{dirname as dirname2}from"path";function sessionStartOnly(matcher){return[{event:"SessionStart",verb:"session-start",...matcher?{matcher}:{}}]}class SessionStartHookAdapter extends JsonHookAdapter{installGuardDir(settingsFilePath){return dirname2(settingsFilePath)}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync2(this.installGuardDir(settingsFilePath)))return{ok:!0};return super.installActivityHooks(settingsFilePath,opts)}async removeActivityHooks(settingsFilePath){if(!existsSync2(settingsFilePath))return;await super.removeActivityHooks(settingsFilePath)}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}:{}}}}var DEVIN_HOOK_EVENT_MAP=sessionStartOnly();function devinSettingsPath(home=homedir2()){let xdg=process.env.XDG_CONFIG_HOME?.trim();return join2(xdg||join2(home,".config"),"devin","config.json")}class DevinHookAdapter extends SessionStartHookAdapter{vendor="devin";eventMap=DEVIN_HOOK_EVENT_MAP;globalSettingsPath(){return devinSettingsPath()}}import{homedir as homedir3}from"os";import{join as join3}from"path";var DROID_HOOK_EVENT_MAP=sessionStartOnly();function droidSettingsPath(home=homedir3()){return join3(home,".factory","settings.json")}class DroidHookAdapter extends SessionStartHookAdapter{vendor="droid";eventMap=DROID_HOOK_EVENT_MAP;globalSettingsPath(){return droidSettingsPath()}}import{homedir as homedir4}from"os";import{dirname as dirname3,join as join4}from"path";var GROK_HOOK_EVENT_MAP=sessionStartOnly();function grokConfigDir(home=homedir4()){return process.env.GROK_HOME?.trim()||join4(home,".grok")}function grokHooksPath(home=homedir4()){return join4(grokConfigDir(home),"hooks","rove.json")}class GrokHookAdapter extends SessionStartHookAdapter{vendor="grok";eventMap=GROK_HOOK_EVENT_MAP;globalSettingsPath(){return grokHooksPath()}installGuardDir(settingsFilePath){return dirname3(dirname3(settingsFilePath))}sessionFromPayload(payload){let sessionId=firstString2(payload.session_id,payload.sessionId);if(!sessionId)return;let transcriptPath=firstString2(payload.transcript_path,payload.transcriptPath);return{sessionId,...transcriptPath?{transcriptPath}:{}}}}function firstString2(...values){for(let value of values)if(typeof value==="string"&&value)return value;return}import{existsSync as existsSync3}from"fs";import{rm}from"fs/promises";import{homedir as homedir5}from"os";import path2 from"path";import{mkdir,readFile,writeFile}from"fs/promises";import path from"path";async function writeIfChanged(file,content){try{if(await readFile(file,"utf8").catch(()=>{return})===content)return;await mkdir(path.dirname(file),{recursive:!0}),await writeFile(file,content)}catch{}}var HERMES_PLUGIN_NAME="rove-agent-state";function indentOf(line){if(!line.trim()||line.trim().startsWith("#"))return;let match=/^ */.exec(line),indent=match?match[0].length:0;return line[indent]==="\t"?void 0:indent}function keyAt(line,indent){if(indentOf(line)!==indent)return;return/^ *(["']?)([A-Za-z0-9_.-]+)\1:(?:\s|$)/.exec(line)?.[2]}function inlineValue(line){return(/^ *(["']?)[A-Za-z0-9_.-]+\1:(.*)$/.exec(line)?.[2]??"").trim()}function listItemAt(line,indent){if(indentOf(line)!==indent)return;let match=/^ *- *(.*)$/.exec(line);if(!match)return;return match[1].trim().replace(/^["']|["']$/g,"")}function join5(lines,trailingNewline){return lines.join(`
4
4
  `)+(trailingNewline?`
5
5
  `:"")}function setHermesPluginEnabled(content,enabled){let trailingNewline=content.endsWith(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{invokeVerb,runApiSubcommand}from"./chunk-adr12wp8.js";import{executeVerb,toApiError}from"./chunk-yjeh02k3.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-7vt1bf35.js";import"./chunk-46c20c2s.js";import"./chunk-j1rsp5pc.js";import"./chunk-ca5fmepn.js";import"./chunk-wgyfwry1.js";import"./chunk-fxqgvjtt.js";import"./chunk-9wd57t3j.js";import"./chunk-pm91e38v.js";import"./chunk-2xsxcdp6.js";import"./chunk-17e2tgyg.js";import"./chunk-qq1q07tz.js";import"./chunk-q8ffd1pc.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-1k7f137x.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-fq8sbarx.js";import"./chunk-em75b155.js";import"./chunk-mdfm45fx.js";import"./chunk-vp29jgbt.js";import"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import"./chunk-qkehg2c1.js";import"./chunk-hk0zbk3t.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-bg2ypp04.js";import"./chunk-3a12v30f.js";import"./chunk-87rkqyr3.js";import"./chunk-h37tqrdb.js";import"./chunk-w77s2df8.js";import"./chunk-mqfvzdpr.js";import"./chunk-k1m1c0yc.js";import"./chunk-rxqdw6s5.js";import"./chunk-8ng1756g.js";import"./chunk-kxp04jnp.js";import"./chunk-k2p7at32.js";import"./chunk-z6t0rmg1.js";import"./chunk-5c2syc7e.js";import{ApiError}from"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-g9ba25q5.js";import"./chunk-ntqg38ke.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-mdc7b01e.js";import"./chunk-tn9gtf18.js";import"./chunk-z46zwmyq.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-e5crm07d.js";import"./chunk-gca19v0w.js";import"./chunk-9y803nx4.js";import"./chunk-qq2mjph2.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-jrzh4yv6.js";import"./chunk-4wq1jsve.js";import"./chunk-af60qacx.js";import"./chunk-cmp64q4j.js";import"./chunk-ebb8z47a.js";import"./chunk-6nsjckc5.js";import"./chunk-2tfnscxk.js";import"./chunk-f050r8jy.js";import"./chunk-w7zv47mp.js";import"./chunk-rja9tf6j.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-rz8319pe.js";import"./chunk-32j6y5d1.js";import"./chunk-0ppfr3vm.js";import"./chunk-x02jmqj1.js";import"./chunk-7kysxgbq.js";import"./chunk-f6qne8f1.js";import"./chunk-jzsngv31.js";import"./chunk-0g4wc808.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.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,3 +1,3 @@
1
1
  // @bun
2
- import{MAX_NOTES,MULTI_REPO_CAP,REPO_NAME_RE,SESSION_PR_CAP,canonicalPrUrl,coerceTodos,isWorkspaceBackendId}from"./chunk-x1jxxmtc.js";import{toTaskId}from"./chunk-xy8be792.js";import{coerceVendorId}from"./chunk-h2m7em1e.js";import{DAEMON_MIGRATION_MARKER}from"./chunk-8t7qbr1e.js";import{LockfileError,acquire}from"./chunk-bejhca6z.js";import{logClient}from"./chunk-0g4wc808.js";import{pathSyntax,samePath}from"./chunk-pn5ygqn6.js";import{defaultClientLogPath}from"./chunk-eqdbfgq5.js";import{existsSync}from"fs";import{copyFile,readFile}from"fs/promises";import{dirname,join}from"path";var AUTO_FIX_MAX=3,AT_REST={idle:!0,turn_complete:!0};function autoFixDecision(input){let{state,pr,engine}=input;if(!state||!pr)return{do:"skip"};if(pr.lifecycle!=="open"&&pr.lifecycle!=="ready_to_merge")return{do:"skip"};if(pr.checkState==="passing")return state.attempts>0||state.stopped||state.lastSha?{do:"reset"}:{do:"skip"};if(pr.checkState!=="failing"||!pr.headSha)return{do:"skip"};if(pr.headSha===state.lastSha)return{do:"skip"};if(state.stopped)return{do:"skip"};if(state.attempts>=3)return{do:"stop"};return AT_REST[engine??""]?{do:"fire"}:{do:"wait"}}function coerceAutoFix(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value,attempts=typeof v.attempts==="number"&&Number.isInteger(v.attempts)&&v.attempts>=0?v.attempts:0;return{attempts:Math.min(attempts,3),...typeof v.lastSha==="string"&&v.lastSha.length>0?{lastSha:v.lastSha}:{},...v.stopped===!0?{stopped:!0}:{}}}function coerceTask(value){if(!value||typeof value!=="object")return null;let v=value;if(typeof v.id!=="string"||typeof v.title!=="string"||typeof v.repo!=="string"||typeof v.branch!=="string"||typeof v.worktreePath!=="string"||typeof v.status!=="string"||typeof v.createdAt!=="string"||typeof v.updatedAt!=="string")return null;if(!isTaskStatus(v.status))return null;let kind=v.kind==="main"?"main":v.kind==="dir"?"dir":"task",scratch=kind==="dir"&&v.scratch===!0,noProject=kind==="dir"&&v.noProject===!0,healedStatus=kind==="main"&&(v.status==="in_progress"||v.status==="done")?"backlog":v.status,deletion=coerceDeletion(v.deletion),quotaResume=coerceQuotaResume(v.quotaResume),scheduledStart=coerceScheduledStart(v.scheduledStart),linkedWorkItem=coerceLinkedWorkItem(v.linkedWorkItem),dispatcher=coerceDispatcher(v.dispatcher),lineage=coerceLineage(v,kind),routine=coerceRoutine(v.routine),extraRepos=coerceExtraRepos(v.extraRepos,v.repo),workspace=coerceWorkspace(v.workspace),sessionPrs=coerceSessionPrs(v.sessionPrs),todos=coerceTodos(v.todos),autoFixCi=coerceAutoFix(v.autoFixCi),report=coerceWorkerReport(v.report);return{id:toTaskId(v.id),title:v.title,repo:v.repo,branch:v.branch,worktreePath:v.worktreePath,status:healedStatus,pinned:typeof v.pinned==="boolean"?v.pinned:!1,...v.kept===!0?{kept:!0}:{},...typeof v.notes==="string"&&v.notes.length>0?{notes:v.notes.slice(0,MAX_NOTES)}:{},...todos?{todos}:{},...autoFixCi?{autoFixCi}:{},kind,...scratch?{scratch:!0}:{},...noProject?{noProject:!0}:{},...routine?{routine}:{},vendor:coerceVendorId(typeof v.vendor==="string"?v.vendor:void 0),...typeof v.command==="string"&&v.command.trim().length>0?{command:v.command}:{},prStatus:coercePRStatus(v.prStatus),...typeof v.modelEffort==="string"&&v.modelEffort.length>0?{modelEffort:v.modelEffort}:{},...typeof v.model==="string"&&v.model.length>0?{model:v.model}:{},...typeof v.tier==="string"&&v.tier.length>0?{tier:v.tier}:{},...typeof v.groupId==="string"&&v.groupId.length>0?{groupId:v.groupId}:{},...v.observedLanguage==="zh"||v.observedLanguage==="en"?{observedLanguage:v.observedLanguage}:{},...deletion?{deletion}:{},...quotaResume?{quotaResume}:{},...scheduledStart?{scheduledStart}:{},...linkedWorkItem?{linkedWorkItem}:{},...dispatcher?{dispatcher}:{},...lineage,...v.deleteBranchPending===!0?{deleteBranchPending:!0}:{},...typeof v.prompt==="string"&&v.prompt.length>0?{prompt:v.prompt}:{},...typeof v.baseRef==="string"&&v.baseRef.trim().length>0?{baseRef:v.baseRef}:{},...typeof v.worktreeName==="string"&&v.worktreeName.trim().length>0?{worktreeName:v.worktreeName}:{},...typeof v.gitRepo==="string"&&v.gitRepo.trim().length>0?{gitRepo:v.gitRepo}:{},...extraRepos?{extraRepos}:{},...workspace?{workspace}:{},...sessionPrs?{sessionPrs}:{},...report?{report}:{},...v.requireReport===!0?{requireReport:!0}:{},...v.worktreeOnly===!0?{worktreeOnly:!0}:{},...v.archived===!0?{archived:!0}:{},createdAt:v.createdAt,updatedAt:v.updatedAt}}function coerceWorkspace(value){if(!value||typeof value!=="object")return;let w=value;if(!isWorkspaceBackendId(w.backend))return;return{backend:w.backend,...typeof w.ref==="string"&&w.ref.length>0?{ref:w.ref}:{}}}function coerceExtraRepos(value,primary){if(!Array.isArray(value))return;let out=[];for(let entry of value){if(out.length>=MULTI_REPO_CAP-1)break;if(!entry||typeof entry!=="object")continue;let e=entry;if(typeof e.name!=="string"||!REPO_NAME_RE.test(e.name))continue;if(typeof e.repo!=="string"||!pathSyntax(e.repo).isAbsolute(e.repo))continue;let repo=e.repo;if(samePath(repo,primary)||out.some((o)=>o.name===e.name||samePath(o.repo,repo)))continue;out.push({name:e.name,repo,branch:typeof e.branch==="string"?e.branch:"",worktreePath:typeof e.worktreePath==="string"?e.worktreePath:"",...typeof e.baseRef==="string"&&e.baseRef.trim().length>0?{baseRef:e.baseRef}:{},...coercePRStatus(e.prStatus)?{prStatus:coercePRStatus(e.prStatus)}:{}})}return out.length>0?out:void 0}function coerceSessionPrs(value){if(!Array.isArray(value))return;let out=[];for(let entry of value){if(!entry||typeof entry!=="object")continue;let e=entry,url=typeof e.url==="string"?canonicalPrUrl(e.url):void 0;if(!url||typeof e.addedAt!=="string"||out.some((o)=>o.url===url))continue;let status=coercePRStatus(e.status);out.push({url,addedAt:e.addedAt,...status?{status}:{}})}return out.length>0?out.slice(-SESSION_PR_CAP):void 0}function coerceWorkerReport(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;return{at:v.at,...typeof v.branch==="string"&&v.branch.length>0?{branch:v.branch}:{},...typeof v.pr==="number"&&Number.isFinite(v.pr)?{pr:v.pr}:{},...typeof v.summary==="string"&&v.summary.length>0?{summary:v.summary}:{}}}function coerceDispatcher(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.taskId!=="string"||v.taskId.length===0)return;if(typeof v.tabId!=="string"||v.tabId.length===0)return;return{taskId:v.taskId,tabId:v.tabId}}function coerceTaskRef(value,selfId){return typeof value==="string"&&value.length>0&&value!==selfId?value:void 0}function coerceCwdSubpath(value){if(typeof value!=="string"||value.length===0)return;if(/^[/\\]|^[a-z]:/i.test(value))return;return value.split(/[/\\]/).includes("..")?void 0:value}function coerceLineage(v,kind){let selfId=v.id,parentTaskId=coerceTaskRef(v.parentTaskId,selfId),sharesWorkspaceOf=kind==="main"?void 0:coerceTaskRef(v.sharesWorkspaceOf,selfId),cwdSubpath=coerceCwdSubpath(v.cwdSubpath),ptyAlias=coerceDispatcher(v.ptyAlias);return{...parentTaskId?{parentTaskId:toTaskId(parentTaskId)}:{},...sharesWorkspaceOf?{sharesWorkspaceOf:toTaskId(sharesWorkspaceOf)}:{},...cwdSubpath?{cwdSubpath}:{},...ptyAlias?{ptyAlias}:{}}}function coerceRoutine(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.automationId!=="string"||v.automationId.length===0)return;return{automationId:v.automationId}}function coerceQuotaResume(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.resumeAt!=="string"||v.resumeAt.length===0)return;if(typeof v.requestedAt!=="string"||v.requestedAt.length===0)return;return{resumeAt:v.resumeAt,requestedAt:v.requestedAt}}function coerceScheduledStart(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;if(typeof v.prompt!=="string"||v.prompt.length===0)return;return{at:v.at,prompt:v.prompt}}function coerceLinkedWorkItem(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.provider!=="github")return;if(v.type!=="issue"&&v.type!=="pr")return;if(typeof v.number!=="number"||!Number.isFinite(v.number))return;if(typeof v.title!=="string"||typeof v.url!=="string"||v.url.length===0)return;return{provider:v.provider,type:v.type,number:v.number,title:v.title,url:v.url}}function coerceDeletion(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.phase!=="queued"&&v.phase!=="running"&&v.phase!=="error"||typeof v.force!=="boolean"||typeof v.requestedAt!=="string"||v.requestedAt.length===0||v.error!==void 0&&typeof v.error!=="string")return;return{phase:v.phase,force:v.force,...typeof v.deleteBranch==="boolean"?{deleteBranch:v.deleteBranch}:{},requestedAt:v.requestedAt,...typeof v.error==="string"?{error:v.error}:{}}}function coercePRStatus(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(!isPRProviderId(v.provider)||!isPRLifecycleState(v.lifecycle)||!isPRCheckState(v.checkState))return;return{provider:v.provider,lifecycle:v.lifecycle,checkState:v.checkState,...typeof v.number==="number"&&Number.isFinite(v.number)?{number:v.number}:{},...typeof v.url==="string"?{url:v.url}:{},...typeof v.title==="string"?{title:v.title}:{},...typeof v.additions==="number"&&Number.isFinite(v.additions)?{additions:v.additions}:{},...typeof v.deletions==="number"&&Number.isFinite(v.deletions)?{deletions:v.deletions}:{},...typeof v.baseRef==="string"?{baseRef:v.baseRef}:{},...typeof v.reviewDecision==="string"?{reviewDecision:v.reviewDecision}:{},...typeof v.mergeable==="string"?{mergeable:v.mergeable}:{},...typeof v.headSha==="string"?{headSha:v.headSha}:{},...typeof v.lastCheckedAt==="string"?{lastCheckedAt:v.lastCheckedAt}:{},...typeof v.lastError==="string"?{lastError:v.lastError}:{}}}function isPRProviderId(v){return v==="github"||v==="gitlab"||v==="bitbucket"||v==="unknown"}function isPRLifecycleState(v){return v==="creating"||v==="open"||v==="ready_to_merge"||v==="merged"||v==="closed"||v==="unknown"}function isPRCheckState(v){return v==="none"||v==="pending"||v==="passing"||v==="failing"||v==="unknown"}function isTaskStatus(s){return s==="backlog"||s==="in_progress"||s==="in_review"||s==="done"||s==="canceled"||s==="error"}var sleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),LOCK_RETRY_DELAY_MS=25,LOCK_MAX_WAIT_MS=5000;async function acquireWithRetry(lockPath){let deadline=Date.now()+LOCK_MAX_WAIT_MS;for(;;)try{return await acquire(lockPath)}catch(err){if(!(err instanceof LockfileError)||Date.now()>=deadline)throw err;await sleep(LOCK_RETRY_DELAY_MS)}}var CURRENT_VERSION=3;async function backupCorruptManifest(path,now=()=>new Date){let backupPath=`${path}.corrupt-${now().toISOString().replaceAll(":","-")}`;try{return await copyFile(path,backupPath),backupPath}catch{return null}}var SUPPORTED_VERSIONS=new Set([1,2,3]);function warnManifestRecovery(message,manifestPath){console.warn(message),logClient("tasks-index",message,manifestPath?defaultClientLogPath(dirname(dirname(manifestPath))):void 0)}async function recoverUnsupportedVersion(parsed,sourcePath){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return!1;let version=parsed.version;if(version===void 0||SUPPORTED_VERSIONS.has(version))return!1;let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} has unsupported version=${String(version)}; recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),!0}function normalizeIndex(parsed,source){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return warnManifestRecovery(`[rove] tasks.json at ${source} is not an object; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let obj=parsed,version=obj.version;if(version!==void 0&&!SUPPORTED_VERSIONS.has(version))return warnManifestRecovery(`[rove] tasks.json at ${source} has unsupported version=${String(version)}; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let rawTasks=Array.isArray(obj.tasks)?obj.tasks:[],tasks=[];for(let entry of rawTasks){let task=coerceTask(entry);if(task)tasks.push(task);else console.warn(`[rove] dropping malformed task entry from ${source}: ${JSON.stringify(entry)}`)}return{version:CURRENT_VERSION,tasks}}var TOMBSTONE_TTL_MS=2592000000;function readableLegacyIndexPath(canonicalPath,legacyPath){return existsSync(join(dirname(canonicalPath),DAEMON_MIGRATION_MARKER))?void 0:legacyPath}async function readDiskIndex(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(sourcePath,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath);if(!legacy)return{tasks:[],removed:[]};sourcePath=legacy;try{raw=await readFile(sourcePath,"utf8")}catch(legacyErr){if(legacyErr.code==="ENOENT")return{tasks:[],removed:[]};throw legacyErr}}let parsed;try{parsed=JSON.parse(raw)}catch{return await backupCorruptManifest(sourcePath),{tasks:[],removed:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{tasks:[],removed:[]};return{tasks:normalizeIndex(parsed,sourcePath).tasks,removed:coerceTombstones(parsed)}}function coerceTombstones(parsed){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return[];let raw=parsed.removed;if(!Array.isArray(raw))return[];let out=[];for(let entry of raw){if(!entry||typeof entry!=="object")continue;let v=entry;if(typeof v.id==="string"&&v.id.length>0&&typeof v.at==="string")out.push({id:v.id,at:v.at})}return out}function mergeTasksWithDisk(cacheTasks,diskTasks,dirty,removed,diskRemoved=[],now=Date.now()){let tombstones=new Map;for(let t of diskRemoved){let at=Date.parse(t.at);if(!Number.isFinite(at)||now-at>TOMBSTONE_TTL_MS)continue;tombstones.set(t.id,t.at)}for(let[id,at]of removed)tombstones.set(id,at);let diskById=new Map(diskTasks.map((t)=>[t.id,t])),result=[],included=new Set;for(let task of cacheTasks){if(tombstones.has(task.id))continue;if(dirty.has(task.id))result.push(task);else{let onDisk=diskById.get(task.id);if(onDisk===void 0)continue;result.push(onDisk)}included.add(task.id)}for(let task of diskTasks){if(included.has(task.id)||tombstones.has(task.id))continue;result.push(task),included.add(task.id)}return{tasks:result,removed:[...tombstones].map(([id,at])=>({id,at}))}}async function recoverIndexFromDisk(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(path,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath),legacyRaw;if(legacy)try{legacyRaw=await readFile(legacy,"utf8"),sourcePath=legacy}catch(legacyErr){if(legacyErr.code!=="ENOENT")throw legacyErr}if(legacyRaw===void 0)return{version:CURRENT_VERSION,tasks:[]};raw=legacyRaw}let parsed;try{parsed=JSON.parse(raw)}catch(err){let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} is corrupted (${err.message}); recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),{version:CURRENT_VERSION,tasks:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{version:CURRENT_VERSION,tasks:[]};return normalizeIndex(parsed,sourcePath)}
2
+ import{MAX_NOTES,MULTI_REPO_CAP,REPO_NAME_RE,SESSION_PR_CAP,canonicalPrUrl,coerceTodos,isWorkspaceBackendId}from"./chunk-jzsngv31.js";import{logClient}from"./chunk-0g4wc808.js";import{toTaskId}from"./chunk-xy8be792.js";import{coerceVendorId}from"./chunk-h2m7em1e.js";import{pathSyntax,samePath}from"./chunk-pn5ygqn6.js";import{DAEMON_MIGRATION_MARKER}from"./chunk-8t7qbr1e.js";import{LockfileError,acquire}from"./chunk-bejhca6z.js";import{defaultClientLogPath}from"./chunk-eqdbfgq5.js";import{existsSync}from"fs";import{copyFile,readFile}from"fs/promises";import{dirname,join}from"path";var AUTO_FIX_MAX=3,AT_REST={idle:!0,turn_complete:!0};function autoFixDecision(input){let{state,pr,engine}=input;if(!state||!pr)return{do:"skip"};if(pr.lifecycle!=="open"&&pr.lifecycle!=="ready_to_merge")return{do:"skip"};if(pr.checkState==="passing")return state.attempts>0||state.stopped||state.lastSha?{do:"reset"}:{do:"skip"};if(pr.checkState!=="failing"||!pr.headSha)return{do:"skip"};if(pr.headSha===state.lastSha)return{do:"skip"};if(state.stopped)return{do:"skip"};if(state.attempts>=3)return{do:"stop"};return AT_REST[engine??""]?{do:"fire"}:{do:"wait"}}function coerceAutoFix(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value,attempts=typeof v.attempts==="number"&&Number.isInteger(v.attempts)&&v.attempts>=0?v.attempts:0;return{attempts:Math.min(attempts,3),...typeof v.lastSha==="string"&&v.lastSha.length>0?{lastSha:v.lastSha}:{},...v.stopped===!0?{stopped:!0}:{}}}function coerceTask(value){if(!value||typeof value!=="object")return null;let v=value;if(typeof v.id!=="string"||typeof v.title!=="string"||typeof v.repo!=="string"||typeof v.branch!=="string"||typeof v.worktreePath!=="string"||typeof v.status!=="string"||typeof v.createdAt!=="string"||typeof v.updatedAt!=="string")return null;if(!isTaskStatus(v.status))return null;let kind=v.kind==="main"?"main":v.kind==="dir"?"dir":"task",scratch=kind==="dir"&&v.scratch===!0,noProject=kind==="dir"&&v.noProject===!0,healedStatus=kind==="main"&&(v.status==="in_progress"||v.status==="done")?"backlog":v.status,deletion=coerceDeletion(v.deletion),quotaResume=coerceQuotaResume(v.quotaResume),scheduledStart=coerceScheduledStart(v.scheduledStart),linkedWorkItem=coerceLinkedWorkItem(v.linkedWorkItem),dispatcher=coerceDispatcher(v.dispatcher),lineage=coerceLineage(v,kind),routine=coerceRoutine(v.routine),extraRepos=coerceExtraRepos(v.extraRepos,v.repo),workspace=coerceWorkspace(v.workspace),sessionPrs=coerceSessionPrs(v.sessionPrs),todos=coerceTodos(v.todos),autoFixCi=coerceAutoFix(v.autoFixCi),report=coerceWorkerReport(v.report);return{id:toTaskId(v.id),title:v.title,repo:v.repo,branch:v.branch,worktreePath:v.worktreePath,status:healedStatus,pinned:typeof v.pinned==="boolean"?v.pinned:!1,...v.kept===!0?{kept:!0}:{},...typeof v.notes==="string"&&v.notes.length>0?{notes:v.notes.slice(0,MAX_NOTES)}:{},...todos?{todos}:{},...autoFixCi?{autoFixCi}:{},kind,...scratch?{scratch:!0}:{},...noProject?{noProject:!0}:{},...routine?{routine}:{},vendor:coerceVendorId(typeof v.vendor==="string"?v.vendor:void 0),...typeof v.command==="string"&&v.command.trim().length>0?{command:v.command}:{},prStatus:coercePRStatus(v.prStatus),...typeof v.modelEffort==="string"&&v.modelEffort.length>0?{modelEffort:v.modelEffort}:{},...typeof v.model==="string"&&v.model.length>0?{model:v.model}:{},...typeof v.tier==="string"&&v.tier.length>0?{tier:v.tier}:{},...typeof v.groupId==="string"&&v.groupId.length>0?{groupId:v.groupId}:{},...v.observedLanguage==="zh"||v.observedLanguage==="en"?{observedLanguage:v.observedLanguage}:{},...deletion?{deletion}:{},...quotaResume?{quotaResume}:{},...scheduledStart?{scheduledStart}:{},...linkedWorkItem?{linkedWorkItem}:{},...dispatcher?{dispatcher}:{},...lineage,...v.deleteBranchPending===!0?{deleteBranchPending:!0}:{},...typeof v.prompt==="string"&&v.prompt.length>0?{prompt:v.prompt}:{},...typeof v.baseRef==="string"&&v.baseRef.trim().length>0?{baseRef:v.baseRef}:{},...typeof v.worktreeName==="string"&&v.worktreeName.trim().length>0?{worktreeName:v.worktreeName}:{},...typeof v.gitRepo==="string"&&v.gitRepo.trim().length>0?{gitRepo:v.gitRepo}:{},...extraRepos?{extraRepos}:{},...workspace?{workspace}:{},...sessionPrs?{sessionPrs}:{},...report?{report}:{},...v.requireReport===!0?{requireReport:!0}:{},...v.worktreeOnly===!0?{worktreeOnly:!0}:{},...v.archived===!0?{archived:!0}:{},createdAt:v.createdAt,updatedAt:v.updatedAt}}function coerceWorkspace(value){if(!value||typeof value!=="object")return;let w=value;if(!isWorkspaceBackendId(w.backend))return;return{backend:w.backend,...typeof w.ref==="string"&&w.ref.length>0?{ref:w.ref}:{}}}function coerceExtraRepos(value,primary){if(!Array.isArray(value))return;let out=[];for(let entry of value){if(out.length>=MULTI_REPO_CAP-1)break;if(!entry||typeof entry!=="object")continue;let e=entry;if(typeof e.name!=="string"||!REPO_NAME_RE.test(e.name))continue;if(typeof e.repo!=="string"||!pathSyntax(e.repo).isAbsolute(e.repo))continue;let repo=e.repo;if(samePath(repo,primary)||out.some((o)=>o.name===e.name||samePath(o.repo,repo)))continue;out.push({name:e.name,repo,branch:typeof e.branch==="string"?e.branch:"",worktreePath:typeof e.worktreePath==="string"?e.worktreePath:"",...typeof e.baseRef==="string"&&e.baseRef.trim().length>0?{baseRef:e.baseRef}:{},...coercePRStatus(e.prStatus)?{prStatus:coercePRStatus(e.prStatus)}:{}})}return out.length>0?out:void 0}function coerceSessionPrs(value){if(!Array.isArray(value))return;let out=[];for(let entry of value){if(!entry||typeof entry!=="object")continue;let e=entry,url=typeof e.url==="string"?canonicalPrUrl(e.url):void 0;if(!url||typeof e.addedAt!=="string"||out.some((o)=>o.url===url))continue;let status=coercePRStatus(e.status);out.push({url,addedAt:e.addedAt,...status?{status}:{}})}return out.length>0?out.slice(-SESSION_PR_CAP):void 0}function coerceWorkerReport(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;return{at:v.at,...typeof v.branch==="string"&&v.branch.length>0?{branch:v.branch}:{},...typeof v.pr==="number"&&Number.isFinite(v.pr)?{pr:v.pr}:{},...typeof v.summary==="string"&&v.summary.length>0?{summary:v.summary}:{}}}function coerceDispatcher(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.taskId!=="string"||v.taskId.length===0)return;if(typeof v.tabId!=="string"||v.tabId.length===0)return;return{taskId:v.taskId,tabId:v.tabId}}function coerceTaskRef(value,selfId){return typeof value==="string"&&value.length>0&&value!==selfId?value:void 0}function coerceCwdSubpath(value){if(typeof value!=="string"||value.length===0)return;if(/^[/\\]|^[a-z]:/i.test(value))return;return value.split(/[/\\]/).includes("..")?void 0:value}function coerceLineage(v,kind){let selfId=v.id,parentTaskId=coerceTaskRef(v.parentTaskId,selfId),sharesWorkspaceOf=kind==="main"?void 0:coerceTaskRef(v.sharesWorkspaceOf,selfId),cwdSubpath=coerceCwdSubpath(v.cwdSubpath),ptyAlias=coerceDispatcher(v.ptyAlias);return{...parentTaskId?{parentTaskId:toTaskId(parentTaskId)}:{},...sharesWorkspaceOf?{sharesWorkspaceOf:toTaskId(sharesWorkspaceOf)}:{},...cwdSubpath?{cwdSubpath}:{},...ptyAlias?{ptyAlias}:{}}}function coerceRoutine(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.automationId!=="string"||v.automationId.length===0)return;return{automationId:v.automationId}}function coerceQuotaResume(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.resumeAt!=="string"||v.resumeAt.length===0)return;if(typeof v.requestedAt!=="string"||v.requestedAt.length===0)return;return{resumeAt:v.resumeAt,requestedAt:v.requestedAt}}function coerceScheduledStart(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;if(typeof v.prompt!=="string"||v.prompt.length===0)return;return{at:v.at,prompt:v.prompt}}function coerceLinkedWorkItem(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.provider!=="github")return;if(v.type!=="issue"&&v.type!=="pr")return;if(typeof v.number!=="number"||!Number.isFinite(v.number))return;if(typeof v.title!=="string"||typeof v.url!=="string"||v.url.length===0)return;return{provider:v.provider,type:v.type,number:v.number,title:v.title,url:v.url}}function coerceDeletion(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.phase!=="queued"&&v.phase!=="running"&&v.phase!=="error"||typeof v.force!=="boolean"||typeof v.requestedAt!=="string"||v.requestedAt.length===0||v.error!==void 0&&typeof v.error!=="string")return;return{phase:v.phase,force:v.force,...typeof v.deleteBranch==="boolean"?{deleteBranch:v.deleteBranch}:{},requestedAt:v.requestedAt,...typeof v.error==="string"?{error:v.error}:{}}}function coercePRStatus(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(!isPRProviderId(v.provider)||!isPRLifecycleState(v.lifecycle)||!isPRCheckState(v.checkState))return;return{provider:v.provider,lifecycle:v.lifecycle,checkState:v.checkState,...typeof v.number==="number"&&Number.isFinite(v.number)?{number:v.number}:{},...typeof v.url==="string"?{url:v.url}:{},...typeof v.title==="string"?{title:v.title}:{},...typeof v.additions==="number"&&Number.isFinite(v.additions)?{additions:v.additions}:{},...typeof v.deletions==="number"&&Number.isFinite(v.deletions)?{deletions:v.deletions}:{},...typeof v.baseRef==="string"?{baseRef:v.baseRef}:{},...typeof v.reviewDecision==="string"?{reviewDecision:v.reviewDecision}:{},...typeof v.mergeable==="string"?{mergeable:v.mergeable}:{},...typeof v.headSha==="string"?{headSha:v.headSha}:{},...typeof v.lastCheckedAt==="string"?{lastCheckedAt:v.lastCheckedAt}:{},...typeof v.lastError==="string"?{lastError:v.lastError}:{}}}function isPRProviderId(v){return v==="github"||v==="gitlab"||v==="bitbucket"||v==="unknown"}function isPRLifecycleState(v){return v==="creating"||v==="open"||v==="ready_to_merge"||v==="merged"||v==="closed"||v==="unknown"}function isPRCheckState(v){return v==="none"||v==="pending"||v==="passing"||v==="failing"||v==="unknown"}function isTaskStatus(s){return s==="backlog"||s==="in_progress"||s==="in_review"||s==="done"||s==="canceled"||s==="error"}var sleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),LOCK_RETRY_DELAY_MS=25,LOCK_MAX_WAIT_MS=5000;async function acquireWithRetry(lockPath){let deadline=Date.now()+LOCK_MAX_WAIT_MS;for(;;)try{return await acquire(lockPath)}catch(err){if(!(err instanceof LockfileError)||Date.now()>=deadline)throw err;await sleep(LOCK_RETRY_DELAY_MS)}}var CURRENT_VERSION=3;async function backupCorruptManifest(path,now=()=>new Date){let backupPath=`${path}.corrupt-${now().toISOString().replaceAll(":","-")}`;try{return await copyFile(path,backupPath),backupPath}catch{return null}}var SUPPORTED_VERSIONS=new Set([1,2,3]);function warnManifestRecovery(message,manifestPath){console.warn(message),logClient("tasks-index",message,manifestPath?defaultClientLogPath(dirname(dirname(manifestPath))):void 0)}async function recoverUnsupportedVersion(parsed,sourcePath){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return!1;let version=parsed.version;if(version===void 0||SUPPORTED_VERSIONS.has(version))return!1;let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} has unsupported version=${String(version)}; recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),!0}function normalizeIndex(parsed,source){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return warnManifestRecovery(`[rove] tasks.json at ${source} is not an object; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let obj=parsed,version=obj.version;if(version!==void 0&&!SUPPORTED_VERSIONS.has(version))return warnManifestRecovery(`[rove] tasks.json at ${source} has unsupported version=${String(version)}; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let rawTasks=Array.isArray(obj.tasks)?obj.tasks:[],tasks=[];for(let entry of rawTasks){let task=coerceTask(entry);if(task)tasks.push(task);else console.warn(`[rove] dropping malformed task entry from ${source}: ${JSON.stringify(entry)}`)}return{version:CURRENT_VERSION,tasks}}var TOMBSTONE_TTL_MS=2592000000;function readableLegacyIndexPath(canonicalPath,legacyPath){return existsSync(join(dirname(canonicalPath),DAEMON_MIGRATION_MARKER))?void 0:legacyPath}async function readDiskIndex(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(sourcePath,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath);if(!legacy)return{tasks:[],removed:[]};sourcePath=legacy;try{raw=await readFile(sourcePath,"utf8")}catch(legacyErr){if(legacyErr.code==="ENOENT")return{tasks:[],removed:[]};throw legacyErr}}let parsed;try{parsed=JSON.parse(raw)}catch{return await backupCorruptManifest(sourcePath),{tasks:[],removed:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{tasks:[],removed:[]};return{tasks:normalizeIndex(parsed,sourcePath).tasks,removed:coerceTombstones(parsed)}}function coerceTombstones(parsed){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return[];let raw=parsed.removed;if(!Array.isArray(raw))return[];let out=[];for(let entry of raw){if(!entry||typeof entry!=="object")continue;let v=entry;if(typeof v.id==="string"&&v.id.length>0&&typeof v.at==="string")out.push({id:v.id,at:v.at})}return out}function mergeTasksWithDisk(cacheTasks,diskTasks,dirty,removed,diskRemoved=[],now=Date.now()){let tombstones=new Map;for(let t of diskRemoved){let at=Date.parse(t.at);if(!Number.isFinite(at)||now-at>TOMBSTONE_TTL_MS)continue;tombstones.set(t.id,t.at)}for(let[id,at]of removed)tombstones.set(id,at);let diskById=new Map(diskTasks.map((t)=>[t.id,t])),result=[],included=new Set;for(let task of cacheTasks){if(tombstones.has(task.id))continue;if(dirty.has(task.id))result.push(task);else{let onDisk=diskById.get(task.id);if(onDisk===void 0)continue;result.push(onDisk)}included.add(task.id)}for(let task of diskTasks){if(included.has(task.id)||tombstones.has(task.id))continue;result.push(task),included.add(task.id)}return{tasks:result,removed:[...tombstones].map(([id,at])=>({id,at}))}}async function recoverIndexFromDisk(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(path,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath),legacyRaw;if(legacy)try{legacyRaw=await readFile(legacy,"utf8"),sourcePath=legacy}catch(legacyErr){if(legacyErr.code!=="ENOENT")throw legacyErr}if(legacyRaw===void 0)return{version:CURRENT_VERSION,tasks:[]};raw=legacyRaw}let parsed;try{parsed=JSON.parse(raw)}catch(err){let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} is corrupted (${err.message}); recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),{version:CURRENT_VERSION,tasks:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{version:CURRENT_VERSION,tasks:[]};return normalizeIndex(parsed,sourcePath)}
3
3
  export{AUTO_FIX_MAX,autoFixDecision,acquireWithRetry,readableLegacyIndexPath,readDiskIndex,mergeTasksWithDisk,recoverIndexFromDisk};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{getGlobalDefaultVendor}from"./chunk-8ttn73cv.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-pzy7fe5e.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{spawnSync}from"child_process";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
2
+ import{getGlobalDefaultVendor}from"./chunk-hk0zbk3t.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-bg2ypp04.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{spawnSync}from"child_process";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
3
3
  `)}function normalizeText(value,label){let trimmed=value.trim();if(!trimmed)throw Error(`${label} is required`);return trimmed}function issueCreateArgv(slug,title,kind){return["issue","create","-R",slug,"--title",title,"--label",KIND_LABEL[kind],"--body-file","-"]}function newIssueUrl(slug,title,body,kind){let prefilled=body.length>MAX_PREFILL_BODY?`${body.slice(0,MAX_PREFILL_BODY)}
4
4
 
5
5
  [truncated]`:body,query=new URLSearchParams({title,body:prefilled,labels:KIND_LABEL[kind]});return`https://github.com/${slug}/issues/new?${query.toString()}`}var ISSUE_URL=/https:\/\/\S+\/issues\/(\d+)/;function submitFeedback(input,deps={}){let title=normalizeText(input.title,"feedback title"),kind=input.kind??DEFAULT_FEEDBACK_KIND,body=`${normalizeText(input.body,"feedback body")}
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{connectIfRunning}from"./chunk-e5crm07d.js";import"./chunk-gca19v0w.js";import"./chunk-9y803nx4.js";import"./chunk-qq2mjph2.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";async function openLocalOrchestrator(){let{TaskIndexStore}=await import("./chunk-v765ej4f.js"),{GitWorktreeManager}=await import("./chunk-e0z123ad.js"),{Orchestrator}=await import("./chunk-ma00xdy2.js"),store=new TaskIndexStore;return await store.load(),new Orchestrator({store,worktrees:new GitWorktreeManager})}async function withDaemonOrLocal(bridge){let client=await connectIfRunning();if(client)try{return await bridge.daemon(client)}finally{client.close()}let orch=await openLocalOrchestrator();return bridge.local(orch)}export{withDaemonOrLocal,openLocalOrchestrator};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{interactiveEngineCommand,listPresetIds}from"./chunk-c69xdgfz.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{engineEntry}from"./chunk-q2r4qavc.js";import{installedEngineIds}from"./chunk-jfbfasx0.js";import{spawn,spawnSync}from"child_process";import{statSync}from"fs";import path from"path";function whichOnPath(bin){let bunWhich=globalThis.Bun?.which;if(bunWhich)return bunWhich(bin);let out=spawnSync(process.platform==="win32"?"where":"which",[bin],{encoding:"utf8"});if(out.status!==0)return null;return out.stdout.split(`
2
+ import{interactiveEngineCommand,listPresetIds}from"./chunk-5c2syc7e.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{engineEntry}from"./chunk-6nsjckc5.js";import{installedEngineIds}from"./chunk-f050r8jy.js";import{spawn,spawnSync}from"child_process";import{statSync}from"fs";import path from"path";function whichOnPath(bin){let bunWhich=globalThis.Bun?.which;if(bunWhich)return bunWhich(bin);let out=spawnSync(process.platform==="win32"?"where":"which",[bin],{encoding:"utf8"});if(out.status!==0)return null;return out.stdout.split(`
3
3
  `).map((l)=>l.trim()).find(Boolean)??null}var LOGIN_PROBE_MS=5000,MARK="__rove_which__";function whichInLoginShell(bin){return new Promise((resolve)=>{let out="",child;try{let quoted=`'${bin.replaceAll("'","'\\''")}'`;child=spawn(resolveSessionShell(),["-ilc",`printf '\\n${MARK}%s\\n' "$(command -v ${quoted})"`],{stdio:["ignore","pipe","ignore"]})}catch{return resolve(null)}let timer=setTimeout(()=>child.kill("SIGKILL"),LOGIN_PROBE_MS);child.stdout?.on("data",(b)=>{out+=b.toString()}),child.on("error",()=>{clearTimeout(timer),resolve(null)}),child.on("close",()=>{clearTimeout(timer);let line=out.split(`
4
4
  `).find((l)=>l.startsWith(MARK));resolve(line?.slice(MARK.length).trim()||null)})})}var defaultDeps={which:(bin)=>whichOnPath(bin)??(process.platform==="win32"?null:whichInLoginShell(bin)),command:(vendor)=>interactiveEngineCommand(vendor)};async function probeLaunchBinary(argv,which){let bin=argv[0]?.trim();if(!bin)return{found:!1,error:"no launch command"};if(bin.includes(path.sep)||bin.startsWith(".")){try{if(statSync(bin).isFile())return{found:!0,path:bin}}catch{}return{found:!1,error:`not found at ${bin}`}}let found=await which(bin);return found?{found:!0,path:found}:{found:!1,error:"not found on PATH"}}async function detectEngineStatus(vendor,over={}){let deps={...defaultDeps,...over},detector=engineEntry(vendor).detectAccount;if(!detector)return{vendor,binary:await probeLaunchBinary(deps.command(vendor),deps.which),account:null};let status=await detector(deps.accountDeps),binary=status.binary.found?status.binary:await probeLaunchBinary(deps.command(vendor),deps.which);return{vendor,binary,account:status.account,accountError:status.accountError}}function detectEngineStatuses(vendors,over={}){return Promise.all(vendors.map((v)=>detectEngineStatus(v,over)))}function describeAccount(account){if(account===null)return"login not detectable";switch(account.kind){case"oauth":return"email"in account?`logged in (${account.email}${account.organization?`, ${account.organization}`:""})`:"logged in";case"chatgpt":return`logged in (${account.email}${account.plan?`, ${account.plan}`:""})`;case"apikey":return"API key";case"token":return`token (${account.source})`;default:return"no account"}}function engineUsable(status){return status.binary.found&&status.account?.kind!=="none"}async function probeableEngineIds(){return[...new Set([...listPresetIds(),...await installedEngineIds()])]}function summarizeEngines(statuses){let usable=[],signedOut=[];for(let status of statuses)if(engineUsable(status))usable.push(status.vendor);else if(status.binary.found)signedOut.push(status.vendor);return{usable,signedOut}}
5
5
  export{detectEngineStatus,detectEngineStatuses,describeAccount,probeableEngineIds,summarizeEngines};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{openDaemonSession,resolveActiveTaskId}from"./chunk-ca5fmepn.js";import"./chunk-e5crm07d.js";import"./chunk-gca19v0w.js";import"./chunk-9y803nx4.js";import"./chunk-qq2mjph2.js";import"./chunk-96kvwzj8.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{resolveActiveTaskId,openDaemonSession};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{pathRejection,projectRejection,rejectionReason}from"./chunk-7mwvvj46.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{rejectionReason,projectRejection,pathRejection};
2
+ import{pathRejection,projectRejection,rejectionReason}from"./chunk-rz8319pe.js";import"./chunk-pn5ygqn6.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{rejectionReason,projectRejection,pathRejection};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{PTY_STOP_REFUSED,RoveDaemonClient}from"./chunk-8y10pmkf.js";import{isProcessAlive,readPidFile}from"./chunk-br8r72bf.js";import{unlink}from"fs/promises";async function stopDaemonProcess(socketPath,pidPath,opts={}){let oldPid=await readPidFile(pidPath),targetPid=oldPid!==null&&oldPid!==process.pid?oldPid:null,wasAlive=targetPid!==null&&isProcessAlive(targetPid),method=wasAlive?"graceful":"absent",client=new RoveDaemonClient(socketPath),refusal=client.request("daemon.stop",{reason:opts.reason??"stop",...opts.force?{force:!0}:{}}).then(()=>!1,(err)=>err instanceof Error&&err.name===PTY_STOP_REFUSED),{promise:stopTimeout,resolve:timedOut}=Promise.withResolvers();setTimeout(()=>timedOut(!1),2000);let refused=await Promise.race([refusal,stopTimeout]);if(client.close(),refused)return{pid:oldPid,method:"refused"};if(wasAlive&&targetPid!==null){let deadline=Date.now()+5000,escalated=!1;while(Date.now()<deadline){try{process.kill(targetPid,0)}catch{break}if(!escalated&&Date.now()-(deadline-5000)>2000){try{process.kill(targetPid,"SIGTERM")}catch{}method="sigterm",escalated=!0}await new Promise((resolve)=>setTimeout(resolve,50))}try{process.kill(targetPid,0),process.kill(targetPid,"SIGKILL"),method="sigkill",await new Promise((resolve)=>setTimeout(resolve,100))}catch{}}let survivor=await readPidFile(pidPath);if(survivor!==null&&survivor!==process.pid&&isProcessAlive(survivor))return{pid:oldPid,method};return await unlink(socketPath).catch(()=>{}),await unlink(pidPath).catch(()=>{}),{pid:oldPid,method}}
2
+ import{PTY_STOP_REFUSED,RoveDaemonClient}from"./chunk-qq2mjph2.js";import{isProcessAlive,readPidFile}from"./chunk-br8r72bf.js";import{unlink}from"fs/promises";async function stopDaemonProcess(socketPath,pidPath,opts={}){let oldPid=await readPidFile(pidPath),targetPid=oldPid!==null&&oldPid!==process.pid?oldPid:null,wasAlive=targetPid!==null&&isProcessAlive(targetPid),method=wasAlive?"graceful":"absent",client=new RoveDaemonClient(socketPath),refusal=client.request("daemon.stop",{reason:opts.reason??"stop",...opts.force?{force:!0}:{}}).then(()=>!1,(err)=>err instanceof Error&&err.name===PTY_STOP_REFUSED),{promise:stopTimeout,resolve:timedOut}=Promise.withResolvers();setTimeout(()=>timedOut(!1),2000);let refused=await Promise.race([refusal,stopTimeout]);if(client.close(),refused)return{pid:oldPid,method:"refused"};if(wasAlive&&targetPid!==null){let deadline=Date.now()+5000,escalated=!1;while(Date.now()<deadline){try{process.kill(targetPid,0)}catch{break}if(!escalated&&Date.now()-(deadline-5000)>2000){try{process.kill(targetPid,"SIGTERM")}catch{}method="sigterm",escalated=!0}await new Promise((resolve)=>setTimeout(resolve,50))}try{process.kill(targetPid,0),process.kill(targetPid,"SIGKILL"),method="sigkill",await new Promise((resolve)=>setTimeout(resolve,100))}catch{}}let survivor=await readPidFile(pidPath);if(survivor!==null&&survivor!==process.pid&&isProcessAlive(survivor))return{pid:oldPid,method};return await unlink(socketPath).catch(()=>{}),await unlink(pidPath).catch(()=>{}),{pid:oldPid,method}}
3
3
  export{stopDaemonProcess};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{addRemoteRepo,addSavedRepo,backfillSavedReposFromProjects,getCustomEngineIds,getDisabledEngineIds,getPersistedString,getPersistedValue,getRemoteRepoConfig,getRemoteRepos,getRepoInitOverride,getSavedRepos,inspectRepo,isGitRepo,isRemoteProjectsEnabled,isRemoteRepoKey,isValidBranchName,normalizeSavedRepos,remoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,setPersistedString,setRepoInitOverride,statePath}from"./chunk-gygdyf0s.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{statePath,setRepoInitOverride,setPersistedString,resolveRepoRoot,resolveMainRepoRoot,removeSavedRepo,remoteRepoKey,normalizeSavedRepos,isValidBranchName,isRemoteRepoKey,isRemoteProjectsEnabled,isGitRepo,inspectRepo,getSavedRepos,getRepoInitOverride,getRemoteRepos,getRemoteRepoConfig,getPersistedValue,getPersistedString,getDisabledEngineIds,getCustomEngineIds,backfillSavedReposFromProjects,addSavedRepo,addRemoteRepo};
2
+ import{addRemoteRepo,addSavedRepo,backfillSavedReposFromProjects,getCustomEngineIds,getDisabledEngineIds,getPersistedString,getPersistedValue,getRemoteRepoConfig,getRemoteRepos,getRepoInitOverride,getSavedRepos,inspectRepo,isGitRepo,isRemoteProjectsEnabled,isRemoteRepoKey,isValidBranchName,normalizeSavedRepos,remoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,setPersistedString,setRepoInitOverride,statePath}from"./chunk-rja9tf6j.js";import"./chunk-40dgv828.js";import"./chunk-rz8319pe.js";import"./chunk-32j6y5d1.js";import"./chunk-pn5ygqn6.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{statePath,setRepoInitOverride,setPersistedString,resolveRepoRoot,resolveMainRepoRoot,removeSavedRepo,remoteRepoKey,normalizeSavedRepos,isValidBranchName,isRemoteRepoKey,isRemoteProjectsEnabled,isGitRepo,inspectRepo,getSavedRepos,getRepoInitOverride,getRemoteRepos,getRemoteRepoConfig,getPersistedValue,getPersistedString,getDisabledEngineIds,getCustomEngineIds,backfillSavedReposFromProjects,addSavedRepo,addRemoteRepo};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,shareInflight,vendorFromArgv}from"./chunk-ebb8z47a.js";import"./chunk-6nsjckc5.js";import"./chunk-2tfnscxk.js";import"./chunk-f050r8jy.js";import"./chunk-w7zv47mp.js";import"./chunk-rja9tf6j.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-rz8319pe.js";import"./chunk-32j6y5d1.js";import"./chunk-0ppfr3vm.js";import"./chunk-x02jmqj1.js";import"./chunk-7kysxgbq.js";import"./chunk-f6qne8f1.js";import"./chunk-jzsngv31.js";import"./chunk-0g4wc808.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{vendorFromArgv,shareInflight,psSnapshotWith,psSnapshot,parsePsSnapshot,hasAncestor,foregroundEngineIn,foregroundEngine,engineProcessIn,PsProbeUnavailableError,PS_PROBE_TIMEOUT_MS};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{installSkillNow,refreshSkillStatus,skillMissing,startSkillStatus}from"./chunk-8d4v27ez.js";import"./chunk-9y17mj2r.js";import"./chunk-cmp64q4j.js";import"./chunk-6nsjckc5.js";import"./chunk-2tfnscxk.js";import"./chunk-f050r8jy.js";import"./chunk-w7zv47mp.js";import"./chunk-rja9tf6j.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-rz8319pe.js";import"./chunk-32j6y5d1.js";import"./chunk-0ppfr3vm.js";import"./chunk-x02jmqj1.js";import"./chunk-7kysxgbq.js";import"./chunk-f6qne8f1.js";import"./chunk-jzsngv31.js";import"./chunk-0g4wc808.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{startSkillStatus,skillMissing,refreshSkillStatus,installSkillNow};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-pzy7fe5e.js";import{loadStateFile,patchStateFile}from"./chunk-32j6y5d1.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=ROVE_PRODUCT_NAME,lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-bg2ypp04.js";import{loadStateFile,patchStateFile}from"./chunk-32j6y5d1.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=ROVE_PRODUCT_NAME,lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
3
3
  `)),process.exit(1)}if(lastRun!==CURRENT_VERSION)stampResetGate()}function stampResetGate(){try{patchStateFile({[LAST_RUN_VERSION_KEY]:CURRENT_VERSION})}catch{}}
4
4
  export{LAST_RUN_VERSION_KEY,enforceResetGate,stampResetGate};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{FREEZE_TTL_MS}from"./chunk-w77s2df8.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import{isUnderKey}from"./chunk-g9ba25q5.js";import{probeDaemonSocket,resolveRoveSpawn,testDaemonResponds}from"./chunk-5mhf43dx.js";import{stopDaemonProcess}from"./chunk-ar3mt81z.js";import{spawnDetachedDaemon,windowsPowershellPath}from"./chunk-s7ttzm9a.js";import{RoveDaemonClient}from"./chunk-8y10pmkf.js";import{isProcessAlive,readPidFile}from"./chunk-br8r72bf.js";import{defaultPtyFreezeDir,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-eqdbfgq5.js";import{spawn}from"child_process";import{existsSync}from"fs";import{readdir,rename,rm,stat}from"fs/promises";import{basename,delimiter,dirname,join,resolve}from"path";import{fileURLToPath}from"url";var PTY_HOST_START_ARGS=["pty-host"],PTY_HOST_NODE_BUNDLE="pty-host-node.mjs",PTY_HOST_NODE_DEV_CACHE="../../.cache/pty-host-node.mjs",PTY_HOST_NODE_ENTRY="../daemon/pty-host-node-entry.ts";function resolveNodeBinary(env=process.env,exists=existsSync,platform=process.platform){let dirs=(env.PATH??env.Path??"").split(delimiter).filter((dir)=>dir.length>0),suffixes=platform==="win32"?(env.PATHEXT??".EXE;.CMD;.BAT").split(";").filter((ext)=>ext.length>0):[""];for(let dir of dirs)for(let suffix of suffixes){let candidate=join(dir,`node${suffix}`);if(exists(candidate))return candidate}return null}async function bundleWithBun(entry,outFile,io){let{build,rename:move,discard}=io??{build:(config)=>Bun.build(config),rename,discard:(path)=>rm(path,{force:!0})},staging=`${outFile}.${process.pid}.tmp`,built=await build({entrypoints:[entry],outdir:dirname(staging),target:"node",format:"esm",naming:basename(staging),external:["node-pty"]});if(!built.success)return await discard(staging).catch(()=>{}),built;return await move(staging,outFile),built}async function resolveNodePtyHostSpawn(deps={}){let platform=deps.platform??process.platform;if(platform!=="win32")return null;let here=deps.moduleDir??dirname(fileURLToPath(import.meta.url)),exists=deps.exists??existsSync,bundle=deps.bundle??bundleWithBun,node=resolveNodeBinary(deps.env??process.env,exists,platform);if(!node)throw Error("Rove: the Windows PTY host runs under node, but no node was found on PATH. "+"Install Node.js (https://nodejs.org) and restart Rove \u2014 engine and terminal sessions cannot start without it.");let packaged=resolve(here,PTY_HOST_NODE_BUNDLE);if(exists(packaged))return[node,packaged];let entry=resolve(here,PTY_HOST_NODE_ENTRY);if(!exists(entry))throw Error(`Rove: no Windows PTY host found (looked for ${packaged} and ${entry})`);let cache=resolve(here,PTY_HOST_NODE_DEV_CACHE),built=await bundle(entry,cache);if(!built.success)throw Error(`Rove: could not build the Windows PTY host \u2014 ${built.logs.map(String).join("; ")}`);return[node,cache]}var BUSY_PTY_HOST_GRACE_MS=15000,CHILD_PROBE_TIMEOUT_MS=5000;function childProbeCommand(deps={}){let env=deps.env??process.env;if((deps.platform??process.platform)!=="win32")return["ps","-A","-o","ppid="];return[windowsPowershellPath(env,deps.exists??existsSync),"-NoProfile","-NonInteractive","-Command","[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance -ClassName Win32_Process -Property ParentProcessId | Select-Object -ExpandProperty ParentProcessId"]}function runChildProbe(command,timeoutMs){return new Promise((done,fail)=>{let proc=spawn(command[0]??"",command.slice(1),{stdio:["ignore","pipe","ignore"]}),out="",finish=(err)=>{clearTimeout(timer);try{proc.kill()}catch{}if(err)fail(err);else done(out)},timer=setTimeout(()=>finish(Error(`did not answer within ${timeoutMs}ms`)),timeoutMs);proc.stdout?.on("data",(chunk)=>{out+=String(chunk)}),proc.on("error",(err)=>finish(err)),proc.on("close",(code,signal)=>finish(code===0&&signal===null?null:Error(`exited with ${signal??`code ${code}`}`)))})}async function liveChildCount(pid,deps={}){let timeoutMs=deps.timeoutMs??CHILD_PROBE_TIMEOUT_MS,command=childProbeCommand(deps),run=deps.run??runChildProbe,text;try{text=await run(command,timeoutMs)}catch{return null}let rows=text.split(`
2
+ import{FREEZE_TTL_MS}from"./chunk-w77s2df8.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import{isUnderKey}from"./chunk-g9ba25q5.js";import{probeDaemonSocket,resolveRoveSpawn,testDaemonResponds}from"./chunk-e5crm07d.js";import{stopDaemonProcess}from"./chunk-gca19v0w.js";import{spawnDetachedDaemon,windowsPowershellPath}from"./chunk-9y803nx4.js";import{RoveDaemonClient}from"./chunk-qq2mjph2.js";import{isProcessAlive,readPidFile}from"./chunk-br8r72bf.js";import{defaultPtyFreezeDir,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-eqdbfgq5.js";import{spawn}from"child_process";import{existsSync}from"fs";import{readdir,rename,rm,stat}from"fs/promises";import{basename,delimiter,dirname,join,resolve}from"path";import{fileURLToPath}from"url";var PTY_HOST_START_ARGS=["pty-host"],PTY_HOST_NODE_BUNDLE="pty-host-node.mjs",PTY_HOST_NODE_DEV_CACHE="../../.cache/pty-host-node.mjs",PTY_HOST_NODE_ENTRY="../daemon/pty-host-node-entry.ts";function resolveNodeBinary(env=process.env,exists=existsSync,platform=process.platform){let dirs=(env.PATH??env.Path??"").split(delimiter).filter((dir)=>dir.length>0),suffixes=platform==="win32"?(env.PATHEXT??".EXE;.CMD;.BAT").split(";").filter((ext)=>ext.length>0):[""];for(let dir of dirs)for(let suffix of suffixes){let candidate=join(dir,`node${suffix}`);if(exists(candidate))return candidate}return null}async function bundleWithBun(entry,outFile,io){let{build,rename:move,discard}=io??{build:(config)=>Bun.build(config),rename,discard:(path)=>rm(path,{force:!0})},staging=`${outFile}.${process.pid}.tmp`,built=await build({entrypoints:[entry],outdir:dirname(staging),target:"node",format:"esm",naming:basename(staging),external:["node-pty"]});if(!built.success)return await discard(staging).catch(()=>{}),built;return await move(staging,outFile),built}async function resolveNodePtyHostSpawn(deps={}){let platform=deps.platform??process.platform;if(platform!=="win32")return null;let here=deps.moduleDir??dirname(fileURLToPath(import.meta.url)),exists=deps.exists??existsSync,bundle=deps.bundle??bundleWithBun,node=resolveNodeBinary(deps.env??process.env,exists,platform);if(!node)throw Error("Rove: the Windows PTY host runs under node, but no node was found on PATH. "+"Install Node.js (https://nodejs.org) and restart Rove \u2014 engine and terminal sessions cannot start without it.");let packaged=resolve(here,PTY_HOST_NODE_BUNDLE);if(exists(packaged))return[node,packaged];let entry=resolve(here,PTY_HOST_NODE_ENTRY);if(!exists(entry))throw Error(`Rove: no Windows PTY host found (looked for ${packaged} and ${entry})`);let cache=resolve(here,PTY_HOST_NODE_DEV_CACHE),built=await bundle(entry,cache);if(!built.success)throw Error(`Rove: could not build the Windows PTY host \u2014 ${built.logs.map(String).join("; ")}`);return[node,cache]}var BUSY_PTY_HOST_GRACE_MS=15000,CHILD_PROBE_TIMEOUT_MS=5000;function childProbeCommand(deps={}){let env=deps.env??process.env;if((deps.platform??process.platform)!=="win32")return["ps","-A","-o","ppid="];return[windowsPowershellPath(env,deps.exists??existsSync),"-NoProfile","-NonInteractive","-Command","[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; Get-CimInstance -ClassName Win32_Process -Property ParentProcessId | Select-Object -ExpandProperty ParentProcessId"]}function runChildProbe(command,timeoutMs){return new Promise((done,fail)=>{let proc=spawn(command[0]??"",command.slice(1),{stdio:["ignore","pipe","ignore"]}),out="",finish=(err)=>{clearTimeout(timer);try{proc.kill()}catch{}if(err)fail(err);else done(out)},timer=setTimeout(()=>finish(Error(`did not answer within ${timeoutMs}ms`)),timeoutMs);proc.stdout?.on("data",(chunk)=>{out+=String(chunk)}),proc.on("error",(err)=>finish(err)),proc.on("close",(code,signal)=>finish(code===0&&signal===null?null:Error(`exited with ${signal??`code ${code}`}`)))})}async function liveChildCount(pid,deps={}){let timeoutMs=deps.timeoutMs??CHILD_PROBE_TIMEOUT_MS,command=childProbeCommand(deps),run=deps.run??runChildProbe,text;try{text=await run(command,timeoutMs)}catch{return null}let rows=text.split(`
3
3
  `).map((row)=>row.trim()).filter((row)=>row.length>0);if(rows.length===0||rows.some((row)=>!/^\d+$/.test(row)))return null;return rows.filter((row)=>Number(row)===pid).length}async function ensurePtyHostReachable(){let socketPath=defaultPtyHostSocketPath(),firstProbe=await probeDaemonSocket(socketPath);if(firstProbe==="alive")return socketPath;let recordedPid=await readPidFile(defaultPtyHostPidPath()),hostPid=recordedPid!==null&&recordedPid!==process.pid&&isProcessAlive(recordedPid)?recordedPid:null;if(hostPid!==null||firstProbe==="wedged"){let deadline2=Date.now()+BUSY_PTY_HOST_GRACE_MS,state=firstProbe;while(Date.now()<deadline2){if(await new Promise((resolveTimer)=>setTimeout(resolveTimer,250)),state=await probeDaemonSocket(socketPath),state==="alive")return socketPath;if(hostPid===null?state==="absent":!isProcessAlive(hostPid))break}if(hostPid===null&&state==="wedged")throw Error(`rove: the pty host at ${socketPath} accepts connections but is not answering, and no live pid is recorded for it, so Rove cannot tell whether it still holds live sessions \u2014 refusing to restart it, which would kill every engine running in them. Inspect it with \`rove api pty-list\`, run \`rove reset\` to end every session and start fresh, or stop its process yourself once you have accepted losing those sessions.`);if(hostPid!==null&&isProcessAlive(hostPid)){let sessions=await liveChildCount(hostPid);if(sessions===null)throw Error(`rove: the pty host (pid ${hostPid}) is not answering and Rove could not read this machine's process table, so it cannot tell whether the host still holds live sessions \u2014 refusing to restart it, which would kill every engine running in them. Inspect it with \`rove api pty-list\`, or kill ${hostPid} yourself once you have accepted losing those sessions.`);if(sessions>0)throw Error(`rove: the pty host (pid ${hostPid}) is not answering but still holds ${sessions} live session(s) \u2014 refusing to restart it, which would kill every engine running in them. Inspect it with \`rove api pty-list\`, or kill ${hostPid} yourself once you have accepted losing those sessions.`)}}if((await stopDaemonProcess(socketPath,defaultPtyHostPidPath()).catch(()=>{return}))?.method==="refused")throw Error(`rove: the pty host at ${socketPath} still holds live sessions and declined to stop \u2014 not replacing it, which would kill every engine running in them. Inspect it with \`rove api pty-list\`, or run \`rove reset\` to end them and start fresh.`);let[command,...args]=await resolveNodePtyHostSpawn()??resolveRoveSpawn(PTY_HOST_START_ARGS);spawnDetachedDaemon(command??"",args,process.env,defaultPtyHostLogPath());let deadline=Date.now()+5000;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,100))}throw Error(`rove: pty host did not start (or stayed wedged) at ${socketPath}; check ${defaultPtyHostLogPath()} or run \`rove doctor\``)}async function sweepPtyHostSessions(liveTaskIds,homeDir,aliasedKeys=()=>[]){let client=new RoveDaemonClient(defaultPtyHostSocketPath(homeDir));try{await client.connect();let{sessions}=await client.request("pty.list"),current;for(let session of sessions){if(!current){let ids=liveTaskIds();if(ids===null)return;current={tasks:new Set(ids),aliased:aliasedKeys()}}if(current.tasks.has(session.key.split("::")[0]??session.key))continue;if(current.aliased.some((base)=>isUnderKey(session.key,base)))continue;if(!session.generation){logDaemonInfo("pty-sweep",`skipped ${session.key}: host has no session generation; restart it when sessions can be interrupted`);continue}await client.request("pty.kill",{key:session.key,expectedGeneration:session.generation}),current=void 0}}catch{}finally{client.close()}}async function listPtyHostSessions(homeDir){let client=new RoveDaemonClient(defaultPtyHostSocketPath(homeDir));try{await client.connect();let result=await client.request("pty.list");return Array.isArray(result.sessions)?result.sessions:null}catch(err){if(err instanceof Error&&"code"in err&&(err.code==="ENOENT"||err.code==="ECONNREFUSED")){let pid=await readPidFile(defaultPtyHostPidPath(homeDir));return pid!==null&&isProcessAlive(pid)?null:[]}return null}finally{client.close()}}async function hasFrozenPtySessions(homeDir){let dir=defaultPtyFreezeDir(homeDir);try{for(let name of await readdir(dir)){if(!name.endsWith(".json"))continue;let mtimeMs=await stat(join(dir,name)).then((st)=>st.mtimeMs).catch(()=>0);if(Date.now()-mtimeMs<=FREEZE_TTL_MS)return!0}}catch{}return!1}async function ptyHostHasLiveSessions(homeDir){let sessions=await listPtyHostSessions(homeDir);if(!sessions||sessions.some((s)=>typeof s.alive!=="boolean"))return null;return sessions.some((s)=>s.alive)}
4
4
  export{resolveNodeBinary,bundleWithBun,resolveNodePtyHostSpawn,childProbeCommand,runChildProbe,liveChildCount,ensurePtyHostReachable,sweepPtyHostSessions,listPtyHostSessions,hasFrozenPtySessions,ptyHostHasLiveSessions};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{getCustomEngineIds,getDisabledEngineIds,getPersistedString,setPersistedString}from"./chunk-gygdyf0s.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";var REPO_KEY_PREFIX="lastActiveVendor.";function validVendor(value,customIds){let v=value?.trim();if(!v)return;if(getDisabledEngineIds().includes(v))return;if(isBuiltinVendor(v)||customIds.includes(v))return v;return}function firstEnabledVendor(){let disabled=new Set(getDisabledEngineIds());return[...BUILTIN_VENDORS,...getCustomEngineIds()].find((id)=>!disabled.has(id))??DEFAULT_TASK_VENDOR}function getRepoLastActiveVendor(repo){return validVendor(getPersistedString(REPO_KEY_PREFIX+repo),getCustomEngineIds())}function setRepoLastActiveVendor(repo,vendor){setPersistedString(REPO_KEY_PREFIX+repo,vendor)}function getGlobalDefaultVendor(){let customIds=getCustomEngineIds();return validVendor(getPersistedString("defaultVendor"),customIds)??validVendor(getPersistedString("lastSelectedVendor"),customIds)}function setGlobalDefaultVendor(vendor){setPersistedString("defaultVendor",vendor)}function resolvePreferredVendor(repo){return(repo?getRepoLastActiveVendor(repo):void 0)??getGlobalDefaultVendor()??firstEnabledVendor()}
2
+ import{getCustomEngineIds,getDisabledEngineIds,getPersistedString,setPersistedString}from"./chunk-rja9tf6j.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";var REPO_KEY_PREFIX="lastActiveVendor.";function validVendor(value,customIds){let v=value?.trim();if(!v)return;if(getDisabledEngineIds().includes(v))return;if(isBuiltinVendor(v)||customIds.includes(v))return v;return}function firstEnabledVendor(){let disabled=new Set(getDisabledEngineIds());return[...BUILTIN_VENDORS,...getCustomEngineIds()].find((id)=>!disabled.has(id))??DEFAULT_TASK_VENDOR}function getRepoLastActiveVendor(repo){return validVendor(getPersistedString(REPO_KEY_PREFIX+repo),getCustomEngineIds())}function setRepoLastActiveVendor(repo,vendor){setPersistedString(REPO_KEY_PREFIX+repo,vendor)}function getGlobalDefaultVendor(){let customIds=getCustomEngineIds();return validVendor(getPersistedString("defaultVendor"),customIds)??validVendor(getPersistedString("lastSelectedVendor"),customIds)}function setGlobalDefaultVendor(vendor){setPersistedString("defaultVendor",vendor)}function resolvePreferredVendor(repo){return(repo?getRepoLastActiveVendor(repo):void 0)??getGlobalDefaultVendor()??firstEnabledVendor()}
3
3
  export{getRepoLastActiveVendor,setRepoLastActiveVendor,getGlobalDefaultVendor,setGlobalDefaultVendor,resolvePreferredVendor};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{execHostForRepo,execHostForWorktreePath,localSpawnCwd,remoteKeyForRepo,remoteSpecFromConfig,worktreeUsable}from"./chunk-z46zwmyq.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-rja9tf6j.js";import"./chunk-40dgv828.js";import"./chunk-rz8319pe.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-eqdbfgq5.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{worktreeUsable,remoteSpecFromConfig,remoteKeyForRepo,localSpawnCwd,execHostForWorktreePath,execHostForRepo};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{loadPluginRegistry,readPluginManifest}from"./chunk-0sy3bez6.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-jfbfasx0.js";import{getCustomEngineIds}from"./chunk-gygdyf0s.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
2
+ import{loadPluginRegistry,readPluginManifest}from"./chunk-1k7f137x.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-f050r8jy.js";import{getCustomEngineIds}from"./chunk-rja9tf6j.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
3
3
  export{loadPluginEngines,reloadPluginEngines,ensurePluginEnginesLoaded,registeredEngineIds};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{homeDir}from"./chunk-z1nj22va.js";import{pathWithin}from"./chunk-pn5ygqn6.js";import{homedir as osHomedir}from"os";import{join}from"path";function tildify(path,home=osHomedir()){let suffix=pathWithin(home,path);return suffix===null?path:suffix?`~/${suffix}`:"~"}function expandTilde(path){if(path==="~")return homeDir();if(path.startsWith("~/")||process.platform==="win32"&&path.startsWith("~\\"))return join(homeDir(),path.slice(2));return path}
2
+ import{pathWithin}from"./chunk-pn5ygqn6.js";import{homeDir}from"./chunk-z1nj22va.js";import{homedir as osHomedir}from"os";import{join}from"path";function tildify(path,home=osHomedir()){let suffix=pathWithin(home,path);return suffix===null?path:suffix?`~/${suffix}`:"~"}function expandTilde(path){if(path==="~")return homeDir();if(path.startsWith("~/")||process.platform==="win32"&&path.startsWith("~\\"))return join(homeDir(),path.slice(2));return path}
3
3
  export{tildify,expandTilde};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-pzy7fe5e.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-bg2ypp04.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{pathSyntax}from"./chunk-pn5ygqn6.js";var WORKSPACE_BACKEND_IDS=["git-worktree","borrowed","cow-clone","layerfs"];function isWorkspaceBackendId(value){return typeof value==="string"&&WORKSPACE_BACKEND_IDS.includes(value)}var GIT_WORKTREE={fork:"committed",checkpoint:!0,cheapClone:!1,ownsBranch:!0,ownsDirectory:!0,interactive:!0},WORKSPACE_CAPABILITIES={"git-worktree":GIT_WORKTREE,borrowed:{fork:"committed",checkpoint:!1,cheapClone:!1,ownsBranch:!1,ownsDirectory:!1,interactive:!0},"cow-clone":{...GIT_WORKTREE,fork:"with-uncommitted",cheapClone:!0},layerfs:{...GIT_WORKTREE,cheapClone:!0,ownsBranch:!1,interactive:!1}};function workspaceBackendId(task){if(task.workspace)return task.workspace.backend;return task.kind==="main"||task.kind==="dir"?"borrowed":"git-worktree"}function workspaceCapabilities(task){return WORKSPACE_CAPABILITIES[workspaceBackendId(task)]}function childrenOf(tasks,id){return tasks.filter((task)=>task.parentTaskId===id)}function workspaceOwnerId(task){return task.sharesWorkspaceOf??task.id}function isSharedChild(task){return task.sharesWorkspaceOf!==void 0}function lineageRootId(tasks,id){let byId=new Map(tasks.map((task)=>[task.id,task])),seen=new Set,current=id;for(;;){seen.add(current);let up=byId.get(current)?.parentTaskId;if(!up||seen.has(up)||!byId.has(up))return current;current=up}}function subtreeIds(tasks,id){let out=[],seen=new Set,visit=(current)=>{if(seen.has(current))return;seen.add(current);for(let child of childrenOf(tasks,current))visit(child.id);out.push(current)};return visit(id),out}function taskCwd(task){let root=task.worktreePath??"";if(!root||!task.cwdSubpath)return root;return pathSyntax(root).join(root,task.cwdSubpath)}function gitRepoOf(task){return task.gitRepo||task.repo}var MULTI_REPO_CAP=8,REPO_NAME_RE=/^[A-Za-z0-9_][A-Za-z0-9._-]*$/;function repoNameOf(repoPath){return pathSyntax(repoPath).basename(repoPath).replace(/[^A-Za-z0-9._-]/g,"-").replace(/^[.-]+/,"")||"repo"}function uniqueRepoName(name,taken){if(!taken.has(name))return name;for(let n=2;;n++)if(!taken.has(`${name}-${n}`))return`${name}-${n}`}function taskRepos(task,tasks){let extras=(task.sharesWorkspaceOf&&tasks?.find((t)=>t.id===task.sharesWorkspaceOf)||task).extraRepos??[],primaryRepo=gitRepoOf(task);return[{name:uniqueRepoName(repoNameOf(primaryRepo),new Set(extras.map((e)=>e.name))),repo:primaryRepo,branch:task.branch,worktreePath:task.worktreePath??"",...task.baseRef?{baseRef:task.baseRef}:{},...task.prStatus?{prStatus:task.prStatus}:{},primary:!0},...extras.map((e)=>({name:e.name,repo:e.repo,branch:e.branch,worktreePath:e.worktreePath,...e.baseRef?{baseRef:e.baseRef}:{},...e.prStatus?{prStatus:e.prStatus}:{},primary:!1}))]}function taskWorktreePaths(task,tasks){return taskRepos(task,tasks).map((r)=>r.worktreePath).filter((p)=>p.length>0)}function prRank(pr){if(pr.checkState==="failing")return 0;if(pr.checkState==="pending")return 1;return pr.lifecycle==="merged"?3:2}function rollupPr(task){let worst;for(let pr of[task.prStatus,...(task.extraRepos??[]).map((e)=>e.prStatus)])if(pr&&(!worst||prRank(pr)<prRank(worst)))worst=pr;return worst}function pickRepos(task,only){let all=taskRepos(task);if(!only)return all;let picked=all.filter((r)=>r.name===only);if(picked.length===0)throw Error(`UNKNOWN_REPO: no repo named '${only}' in this task (repos: ${all.map((r)=>r.name).join(", ")})`);return picked}var SESSION_PR_CAP=20,GITHUB_PR_URL=/^https?:\/\/(?:www\.)?github\.com\/([\w.-]+)\/([\w.-]+)\/pull\/(\d+)(?:[/?#].*)?$/i;function canonicalPrUrl(input){let m=GITHUB_PR_URL.exec(input.trim());if(!m)return;let[,owner,repo,number]=m;return`https://github.com/${owner}/${repo}/pull/${Number(number)}`}var MAX_NOTES=20000;class TodoRefusedError extends Error{code;constructor(code,message){super(message);this.code=code;this.name="TodoRefusedError"}}function cleanText(raw){let text=raw.replace(/\s+/g," ").trim();if(text.length===0)throw new TodoRefusedError("TODO_EMPTY","a todo needs some text");if(text.length>500)throw new TodoRefusedError("TODO_TOO_LONG","a todo is at most 500 characters");return text}function nextId(todos){return`t${todos.reduce((max,todo)=>Math.max(max,Number(todo.id.slice(1))||0),0)+1}`}function applyTodoOps(todos,ops){let list=[...todos],find=(id)=>{let at=list.findIndex((todo)=>todo.id===id);if(at<0)throw new TodoRefusedError("TODO_NOT_FOUND",`no todo ${id}`);return at};for(let op of ops)if(op.op==="add"){if(list.length>=100)throw new TodoRefusedError("TODO_LIMIT","a task holds at most 100 todos");list.push({id:nextId(list),text:cleanText(op.text),done:!1})}else if(op.op==="check"){let at=find(op.id);list[at]={...list[at],done:op.done}}else if(op.op==="edit"){let at=find(op.id);list[at]={...list[at],text:cleanText(op.text)}}else list.splice(find(op.id),1);return list}function checkNotes(notes){if(notes.length>20000)throw new TodoRefusedError("NOTES_TOO_LONG","notes are at most 20000 characters");return notes}function coerceTodos(value){if(!Array.isArray(value))return;let out=[];for(let item of value.slice(0,100)){let v=item;if(typeof v?.id==="string"&&/^t\d+$/.test(v.id)&&typeof v.text==="string"&&v.text.trim().length>0)out.push({id:v.id,text:v.text.slice(0,500),done:v.done===!0})}return out.length>0?out:void 0}function todoCount(todos){if(!todos||todos.length===0)return null;return{done:todos.filter((todo)=>todo.done).length,total:todos.length}}function parseTodoOps(value){if(!Array.isArray(value))throw new TodoRefusedError("TODO_EMPTY","ops must be a list");return value.map((raw)=>{let v=raw,id=typeof v?.id==="string"?v.id:"",text=typeof v?.text==="string"?v.text:"";if(v?.op==="add")return{op:"add",text};if(v?.op==="edit")return{op:"edit",id,text};if(v?.op==="remove")return{op:"remove",id};if(v?.op==="check"&&typeof v.done==="boolean")return{op:"check",id,done:v.done};throw new TodoRefusedError("TODO_EMPTY","each op is add, check, edit or remove")})}
3
+ export{isWorkspaceBackendId,WORKSPACE_CAPABILITIES,workspaceBackendId,workspaceCapabilities,SESSION_PR_CAP,canonicalPrUrl,MAX_NOTES,TodoRefusedError,applyTodoOps,checkNotes,coerceTodos,todoCount,parseTodoOps,childrenOf,workspaceOwnerId,isSharedChild,lineageRootId,subtreeIds,taskCwd,gitRepoOf,MULTI_REPO_CAP,REPO_NAME_RE,repoNameOf,uniqueRepoName,taskRepos,taskWorktreePaths,rollupPr,pickRepos};