@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,3 +1,3 @@
1
1
  // @bun
2
- import{buildEngineSessionLaunch,sniffProtocolFromTitle,trustEngineWorktree}from"./chunk-ee5a0pka.js";import{diffTabs,engineForkArgv,engineLaunchArgv,engineResumeArgv,withPinnedSessionId}from"./chunk-c69xdgfz.js";import{terminalTabsKey}from"./chunk-mdc7b01e.js";import{engineEntry,engineStatusPrefixes,isEnginePlaceholderTitle,stripEngineStatusPrefix}from"./chunk-q2r4qavc.js";import{tildify}from"./chunk-2r1fgng9.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{t}from"./chunk-4wq1jsve.js";import{pathSyntax}from"./chunk-pn5ygqn6.js";function engineTabArgv(tab,base,live,fallbackVendor){if(tab.forkFrom&&!tab.spawned&&!live){let forked=tab.vendor?engineForkArgv(base,tab.vendor,tab.forkFrom,tab.sessionId??null):null;if(forked)return forked}if(!tab.sessionId)return base;let vendor=tab.vendor??fallbackVendor;if(tab.spawned&&!live)return engineResumeArgv(base,vendor,tab.sessionId)??base;return withPinnedSessionId(base,vendor,()=>tab.sessionId).argv}function engineTabSpawnFor(state,tab,base,opts){let{live,shell,prompt}=opts,firstEngine=state.tabs.find((t2)=>t2.kind==="engine"),fresh=!tab.spawned&&!live,tabPrompt=fresh?tab.initialPrompt?.trim():void 0,wantsPrompt=!!prompt&&tab.id===firstEngine?.id&&fresh,isFreshFirstEngine=tab.id===firstEngine?.id&&fresh,promptIntent=tabPrompt?{kind:"explicit",prompt:tabPrompt}:wantsPrompt?{kind:"new-task",prompt}:isFreshFirstEngine?{kind:"repo-init"}:{kind:"none"},ref=tab.ptyTask;trustEngineWorktree(tab.vendor??opts.task.vendor,ref?.worktree??opts.worktreePath);let launch=buildEngineSessionLaunch({task:ref?{...opts.task,id:ref.id,kind:"task"}:opts.task,worktreePath:ref?.worktree??opts.worktreePath,shell,argv:engineTabArgv(tab,base,live,opts.task.vendor),promptIntent,protocolGates:opts.protocolGates,inlineImages:opts.inlineImages,tabId:ref?ref.tabId??"tab-1":tab.id});return{command:launch.command,...launch.firstMessage?{firstMessage:launch.firstMessage,engineBin:base[0]}:{}}}function tabExitAction(tab,deadOnAttach,resumeTried){if(tab.kind==="engine"&&deadOnAttach&&!!tab.sessionId&&tab.spawned&&!resumeTried)return"resume";return"close"}import*as fs from"fs";import*as os from"os";function pathLeaf(p){return p.slice(lastSeparator(p)+1)}function lastSeparator(p){return pathSyntax(p).sep==="\\"||process.platform==="win32"&&!p.startsWith("/")?Math.max(p.lastIndexOf("/"),p.lastIndexOf("\\")):p.lastIndexOf("/")}function expandHome(p){if(p==="~")return os.homedir();if(p.startsWith("~/")||process.platform==="win32"&&p.startsWith("~\\"))return os.homedir()+p.slice(1);return p}function stripTrailingSlash(p){let root=pathSyntax(p).parse(p).root,end=p.length;while(end>root.length&&lastSeparator(p.slice(0,end))===end-1)end--;return p.slice(0,end)}function splitPathForDirSuggest(value){if(!value)return{base:"",filter:""};let expanded=expandHome(value==="~"?"~/":value),lastSlash=lastSeparator(expanded);if(lastSlash===-1)return{base:"",filter:expanded};return{base:expanded.slice(0,lastSlash+1),filter:expanded.slice(lastSlash+1)}}function listSubdirs(base){if(!base)return[];try{let entries=fs.readdirSync(base,{withFileTypes:!0}),out=[];for(let e of entries)if(e.isDirectory())out.push(e.name);return out.sort((a,b)=>a.localeCompare(b))}catch{return[]}}function filterSubdirs(all,filter){let f=filter.toLowerCase(),visible=f.startsWith(".")?all:all.filter((n)=>!n.startsWith("."));if(!f)return visible;return visible.filter((n)=>n.toLowerCase().startsWith(f))}function joinDrill(typedValue,baseExpanded,name){let out=`${baseExpanded+name}/`;if(typedValue.startsWith("~")){let short=tildify(out);if(short.startsWith("~"))return short==="~"?"~/":`${short}/`}return out}function joinPicked(typedValue,baseExpanded,name){let out=baseExpanded+name;if(typedValue.startsWith("~"))return tildify(out);return out}function depth(node){return node.kind==="leaf"?0:1+Math.max(...node.children.map(depth))}function siblingCount(root,id,orientation){let find=(node)=>{if(node.kind==="leaf")return null;if(node.orientation===orientation&&node.children.some((c)=>c.kind==="leaf"&&c.id===id))return node.children.length;for(let child of node.children){let n=find(child);if(n!==null)return n}return null};return find(root)??1}function splitFits(state,orientation,activeSize){let extent=orientation==="row"?activeSize.cols:activeSize.rows,min=orientation==="row"?20:6,n=siblingCount(state.root,state.activeLeafId,orientation);return Math.floor(extent*n/(n+1))-1>=min}function initialSplit(content){return{root:{kind:"leaf",id:"leaf-1",content},activeLeafId:"leaf-1",nextOrdinal:2}}function leaves(node){return node.kind==="leaf"?[node]:node.children.flatMap(leaves)}function splitActive(state,orientation,content,activeSize){if(activeSize&&!splitFits(state,orientation,activeSize))return state;let leaf={kind:"leaf",id:`leaf-${state.nextOrdinal}`,content},insert=(node)=>{if(node.kind==="leaf"){if(node.id!==state.activeLeafId)return node;return{kind:"group",orientation,children:[node,leaf]}}if(node.orientation===orientation){let i=node.children.findIndex((c)=>c.kind==="leaf"&&c.id===state.activeLeafId);if(i>=0){let children=[...node.children.slice(0,i+1),leaf,...node.children.slice(i+1)];return{...node,children}}}return{...node,children:node.children.map(insert)}},root=insert(state.root);if(!activeSize&&depth(root)>4)return state;return{root,activeLeafId:leaf.id,nextOrdinal:state.nextOrdinal+1}}function removeLeaf(state,id){let all=leaves(state.root);if(all.length<=1)return null;let prune=(node)=>{if(node.kind==="leaf")return node.id===id?null:node;let children=node.children.map(prune).filter((c)=>c!==null);if(children.length===0)return null;if(children.length===1)return children[0];return{...node,children}},root=prune(state.root);if(root===null)return null;if(leaves(root).length===all.length)return state;let order=all.map((l)=>l.id),removedIdx=order.indexOf(id),fallback=order[removedIdx>0?removedIdx-1:removedIdx+1],activeLeafId=state.activeLeafId===id?fallback:state.activeLeafId;return{...state,root,activeLeafId}}function renameLeaf(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,walk=(node)=>node.kind==="leaf"?node.id===id?{...node,title:next}:node:{...node,children:node.children.map(walk)};if(!leaves(state.root).some((l)=>l.id===id))return state;return{...state,root:walk(state.root)}}function cycleLeaf(state,delta){let order=leaves(state.root).map((l)=>l.id);if(order.length<=1)return state;let i=order.indexOf(state.activeLeafId),next=order[(i+delta+order.length)%order.length];return{...state,activeLeafId:next}}function hasEngineLeaf(tree){return!tree||leaves(tree.root).some((l)=>l.id==="leaf-1")}function isTabSplit(tree){return tree?leaves(tree.root).length>1:!1}function collapseSplit(next){let ls=leaves(next.root);return ls.length===1&&ls[0]?.id==="leaf-1"?null:next}function splitLeafPtyKey(tabKey,leafId){return leafId==="leaf-1"?tabKey:`${tabKey}::${leafId}`}var SHELL_LEAF_NAME="shell";function splitLeafNames(leafList,tabCommand,engineTitle,liveTitles){let basename=(argv)=>{let head=(argv??tabCommand)[0]??"",name=pathLeaf(head);return name.length>0?name:"?"},seen=new Map,out=new Map;for(let leaf of leafList){if(leaf.title){out.set(leaf.id,leaf.title);continue}let name=leaf.content===null?engineTitle||liveTitles?.get(leaf.id)||basename(leaf.content):liveTitles?.get(leaf.id)||SHELL_LEAF_NAME,n=(seen.get(name)??0)+1;seen.set(name,n),out.set(leaf.id,n===1?name:`${name} ${n}`)}return out}function meaningfulAutoTitle(autoTitle){let trimmed=(autoTitle??"").trim();if(trimmed.length<3)return null;if(/^[\d\s\p{P}\p{S}]+$/u.test(trimmed))return null;return trimmed}function stableRecordedTitle(raw,vendor){let recorded=raw?.trim();if(!recorded)return null;let cleaned=stripEngineStatusPrefix(recorded,vendor);if(cleaned===recorded&&isEngineDecoration(recorded,vendor))return null;if(isEnginePlaceholderTitle(cleaned,vendor))return null;return cleaned||null}function isEngineDecoration(text,vendor){let glyphs=new Set(engineStatusPrefixes(vendor));return[...text].every((ch)=>ch.trim().length===0||glyphs.has(ch))}function tabTitleStable(tab,taskVendor,liveVendor,liveTitle){if(liveVendor===null&&tab.kind==="engine")return tabTitle({...tab,kind:"command",lastTitle:null},taskVendor);let source=liveTitle?.trim()||tab.lastTitle,vendor=liveVendor??tab.liveVendor??sniffProtocolFromTitle(source)??(tab.kind==="engine"?tab.vendor??taskVendor:void 0)??void 0,named=vendor?stableRecordedTitle(source,vendor):source??null;if(!vendor||engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return tabTitle({...tab,...vendor?{kind:"engine",vendor}:{},lastTitle:named},taskVendor);return tabTitle({...tab,kind:"engine",vendor,lastTitle:named},taskVendor)}function conversationTitle(tab,taskVendor,liveTitle){let renamed=tab.title?.trim();if(renamed)return renamed;let source=liveTitle?.trim()||tab.lastTitle,vendor=titleVendor(tab,taskVendor,source),named=stableRecordedTitle(source,vendor);if(!named)return null;let entry=engineEntry(vendor),generic=[entry.displayName,entry.defaultCommand[0]].map((name)=>name?.toLowerCase()),lowered=named.toLowerCase();return generic.includes(lowered)||generic.includes(lowered.replace(/ (code|cli)$/,""))?null:named}function titleVendor(tab,taskVendor,title){return tab.liveVendor??sniffProtocolFromTitle(title)??(tab.kind==="engine"?tab.vendor:void 0)??taskVendor}function tabTitle(tab,taskVendor,liveName){if(tab.title)return tab.title;let ls=tab.splitTree?leaves(tab.splitTree.root):[];if(ls.length>1)return t("terminal.tab.groupTitle",{n:tab.ordinal});let sole=ls.length===1?ls[0]:void 0;if(sole&&sole.id!=="leaf-1")return sole.title??`${liveName??SHELL_LEAF_NAME} ${tab.ordinal}`;let vendor=titleVendor(tab,taskVendor,liveName||tab.lastTitle);if(liveName&&!isEnginePlaceholderTitle(liveName,vendor))return`${liveName} ${tab.ordinal}`;if(tab.lastTitle&&!isEnginePlaceholderTitle(tab.lastTitle,vendor))return`${tab.lastTitle} ${tab.ordinal}`;let auto=meaningfulAutoTitle(tab.autoTitle);if(auto)return auto;return`${tab.kind==="engine"?engineEntry(tab.vendor??taskVendor).defaultCommand[0]??SHELL_LEAF_NAME:SHELL_LEAF_NAME} ${tab.ordinal}`}function visibleNativeStatus(tab,taskVendor,vendor,liveName){if(!vendor||!liveName)return!1;if(engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return!1;return tabTitle(tab,taskVendor,liveName)===`${liveName} ${tab.ordinal}`}function initialTabs(){return{tabs:[{kind:"engine",id:"tab-1",title:null,ordinal:1}],activeId:"tab-1",nextOrdinal:2}}function reopenHintFor(closed){if(closed?.kind==="command")return{kind:"command"};if(closed?.kind==="engine"&&closed.vendor)return{kind:"engine",vendor:closed.vendor};return{kind:"engine"}}function reopenTabs(state,shell,engine){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,next=state.nextOrdinal+1;if(!engine&&state.reopenAs?.kind==="command")return{tabs:[{kind:"command",id,title:null,ordinal,command:[shell]}],activeId:id,nextOrdinal:next};let vendor=state.reopenAs?.kind==="engine"?state.reopenAs.vendor:void 0;return{tabs:[{kind:"engine",id,title:null,ordinal,...engine??(vendor?{vendor}:{})}],activeId:id,nextOrdinal:next}}function initialShellTabs(shell){return{tabs:[{kind:"command",id:"tab-1",title:null,ordinal:1,command:[shell]}],activeId:"tab-1",nextOrdinal:2}}function rehydrateTabs(persisted,shell,opts={}){let tabs=persisted.tabs.map((t2)=>t2.kind==="command"?{...t2,command:shell,purpose:void 0}:t2);if(tabs.length===0)return opts.allowEmpty?persisted:initialTabs();let activeId=tabs.some((t2)=>t2.id===persisted.activeId)?persisted.activeId:tabs[0].id,maxOrdinal=tabs.reduce((max,t2)=>Math.max(max,t2.ordinal),0);return{tabs,activeId,nextOrdinal:Math.max(persisted.nextOrdinal,maxOrdinal+1)}}function recycleTabs(state,prev){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,pinned=prev.kind==="engine"?prev:void 0;return{tabs:[{kind:"engine",id,ordinal,title:prev.title,autoTitle:prev.autoTitle,...pinned?.vendor?{vendor:pinned.vendor}:{},...pinned?.engineCommand?{engineCommand:pinned.engineCommand}:{}}],activeId:id,nextOrdinal:ordinal+1}}var SHELL_SAFE_ARG=/^[A-Za-z0-9@%+=:,./_-]+$/;function shellCommandLine(argv){return argv.map((a)=>SHELL_SAFE_ARG.test(a)?a:`'${a.replaceAll("'","'\\''")}'`).join(" ")}function shellIdentityInput(taskId,tabId,extraEnv=[]){let task=shellCommandLine([taskId]),tab=shellCommandLine([tabId]),extra=extraEnv.map(([name,value])=>` ${name}=${shellCommandLine([value])}`).join("");return` export ROVE_TASK_ID=${task} ROVE_TAB_ID=${tab}${extra} && clear\r`}function insertAfterActive(state,tab){let i=state.tabs.findIndex((t2)=>t2.id===state.activeId);return{tabs:[...state.tabs.slice(0,i+1),tab,...state.tabs.slice(i+1)],activeId:tab.id,nextOrdinal:state.nextOrdinal+1}}function addTab(state,vendor){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"engine",id:`tab-${ordinal}`,title:null,ordinal,vendor})}function openCommandTab(state,command,label){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command})}function findEditorTab(state){return state.tabs.find((tab)=>tab.kind==="command"&&tab.purpose==="editor")}function openEditorTab(state,command,label){let existing=findEditorTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command,purpose:"editor"})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,command,splitTree:null}:tab);return{...state,tabs,activeId:existing.id}}function findContentTab(state){return state.tabs.find((tab)=>tab.kind==="content")}function openContentTab(state,relPath,label,base){let existing=findContentTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"content",id:`tab-${ordinal}`,title:label,ordinal,relPath,base})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,relPath,base}:tab);return{...state,tabs,activeId:existing.id}}function closeTab(state,id,opts={}){if(state.tabs.length<=1&&!opts.allowEmpty)return{state,closedId:null};let i=state.tabs.findIndex((t2)=>t2.id===id);if(i<0)return{state,closedId:null};let tabs=state.tabs.filter((t2)=>t2.id!==id);if(state.activeId!==id)return{state:{...state,tabs},closedId:id};if(tabs.length===0)return{state:{...state,tabs,activeId:id,reopenAs:reopenHintFor(state.tabs[i])},closedId:id};let next=tabs[Math.max(0,i-1)];return{state:{...state,tabs,activeId:(next??tabs[0]).id},closedId:id}}function closeActiveTab(state){return closeTab(state,state.activeId)}function renameActiveTab(state,title){return setTabTitle(state,state.activeId,title)}function setTabTitle(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.title??null)===next)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,title:next}:t2);return{...state,tabs}}function setTabSessionId(state,id,sessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,sessionId}:t2);return{...state,tabs}}function setTabForkFrom(state,id,sourceSessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,forkFrom:sourceSessionId}:t2);return{...state,tabs}}function setTabEngineCommand(state,id,command){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,engineCommand:command}:t2);return{...state,tabs}}function setTabInitialPrompt(state,id,prompt){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,initialPrompt:prompt}:t2);return{...state,tabs}}function setTabLastTitle(state,id,lastTitle){if(lastTitle.length===0)return state;let current=state.tabs.find((t2)=>t2.id===id);if(!current||current.lastTitle===lastTitle)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,lastTitle}:t2);return{...state,tabs}}function setTabLiveVendor(state,id,liveVendor){let current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.liveVendor??null)===liveVendor)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,liveVendor}:t2);return{...state,tabs}}function setTabAutoTitle(state,id,autoTitle){let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,autoTitle}:t2);return{...state,tabs}}function setTabSpawned(state,id,spawned){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"&&!t2.spawned!==!spawned?{...t2,spawned}:t2);return{...state,tabs}}function cycleTab(state,delta){let n=state.tabs.length;if(n<=1)return state;let i=state.tabs.findIndex((t2)=>t2.id===state.activeId),next=state.tabs[(i+delta+n)%n];return{...state,activeId:next.id}}function gotoTab(state,index){let target=state.tabs[index];return target&&target.id!==state.activeId?{...state,activeId:target.id}:state}function moveTab(state,id,delta){let i=state.tabs.findIndex((t2)=>t2.id===id),j=i+delta;if(i<0||j<0||j>=state.tabs.length)return state;let tabs=[...state.tabs],a=tabs[i];return tabs[i]=tabs[j],tabs[j]=a,{...state,tabs}}function selectTab(state,id){if(state.activeId===id||!state.tabs.some((t2)=>t2.id===id))return state;return{...state,activeId:id}}function setTabSplit(state,id,tree){if(!state.tabs.some((t2)=>t2.id===id))return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,splitTree:tree}:t2);return{...state,tabs}}function tabPtyKey(taskId,tabId){return`${taskId}::${tabId}`}function tabPtyKeyFor(taskId,tab){if(tab.kind==="engine"&&tab.ptyTask)return tabPtyKey(tab.ptyTask.id,tab.ptyTask.tabId??"tab-1");return tabPtyKey(taskId,tab.id)}function tabCwdFor(tab,taskWorktree){if(tab.kind==="engine"&&tab.ptyTask)return tab.ptyTask.worktree;return taskWorktree}function wireNode(node){if(node.kind==="leaf")return{kind:"leaf",id:node.id,title:node.title??null,own:node.content===null};return{kind:"group",orientation:node.orientation,children:node.children.map(wireNode)}}function wireSplit(tree){return tree?{root:wireNode(tree.root),activeLeafId:tree.activeLeafId}:null}function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function asTabsState(state){if(!state||!Array.isArray(state.tabs))return;return{...state,activeId:state.activeId??state.tabs[0]?.id??""}}var asShared=(state)=>state;async function applyTabOps(client,taskId,ops){let reply=await client.request("tabs.apply",{taskId,ops});return{state:asTabsState(reply?.state),opened:reply?.opened??[]}}async function readDaemonTabs(client,taskId){return asTabsState((await client.request("tabs.get",{taskId}))?.state)}async function editTabs(client,taskId,edit){let before=await readDaemonTabs(client,taskId);if(!before)return;let next=edit(before);if(next===before)return;let ops=diffTabs(asShared(before),asShared(next));if(ops.length>0)await applyTabOps(client,taskId,ops)}async function closeTabsSnapshot(client,taskId,tabId){let closing;return await editTabs(client,taskId,(state)=>{if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return state;let{state:next,closedId}=closeTab({...state,activeId:tabId},tabId,{allowEmpty:!0});if(!closedId)closing=void 0;return closedId?next:state}),closing}async function renameTabsSnapshot(client,taskId,tabId,title){let found=!1;return await editTabs(client,taskId,(state)=>{return found=state.tabs.some((tab)=>tab.id===tabId),found?setTabTitle(state,tabId,title):state}),found}async function patchTabSplit(client,taskId,tabId,tree){let{state}=await applyTabOps(client,taskId,[{op:"patch",id:tabId,set:{splitTree:tree??null}}]);return state?.tabs.find((t2)=>t2.id===tabId)}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t2)=>t2.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),liveTitles=new Map(rows0.filter((s)=>s.alive&&s.title?.trim()).map((s)=>[s.key,s.title])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t2)=>{let key=tabPtyKeyFor(taskId,t2),isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t2.id,kind:t2.kind,title:t2.title??null,vendor:t2.vendor??null,liveVendor:walked!==void 0?walked:t2.liveVendor??null,lastTitle:t2.lastTitle??null,liveTitle:liveTitles.get(key)??null,autoTitle:t2.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null,...t2.splitTree?{split:wireSplit(t2.splitTree)}:{},...t2.kind==="engine"&&t2.ptyTask?{viewOf:t2.ptyTask.id}:{}}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0)){let key=`${taskId}::${tabId}`,engineIsAlive=engineAliveOf(key,!0,engineAlive);rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,liveTitle:liveTitles.get(key)??null,autoTitle:null,alive:!0,engineAlive:engineIsAlive,exit:engineIsAlive===!1?engineExit(key):null,unregistered:!0})}return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}async function publishCliTabSnapshot(client,taskId,sessionId){if(!taskId)return;try{let seeded=initialTabs(),state=sessionId?{...seeded,tabs:seeded.tabs.map((t2)=>t2.kind==="engine"?{...t2,sessionId,spawned:!0}:t2)}:seeded;await applyTabOps(client,taskId,[{op:"seed",state:asShared(state)}])}catch{}}async function markCliTabSession(client,taskId,tabId,sessionId){try{if((await readDaemonTabs(client,taskId))?.tabs.find((t2)=>t2.id===tabId)?.kind!=="engine")return;let set={...sessionId?{sessionId}:{},spawned:!0};return(await applyTabOps(client,taskId,[{op:"patch",id:tabId,set}])).state}catch{return}}async function allocateTab(client,taskId,row){let{state,opened}=await applyTabOps(client,taskId,[{op:"seed",state:asShared(initialTabs())},{op:"open",row}]),id=opened[0],tab=id?state?.tabs.find((t2)=>t2.id===id):void 0;if(!tab)throw Error(`the daemon opened no tab for ${taskId}`);return tab}async function seedCanonicalTab(client,taskId){let{state}=await applyTabOps(client,taskId,[{op:"seed",state:asShared(initialTabs())}]),tab=state?.tabs.find((t2)=>t2.id==="tab-1");if(!tab)throw Error(`the daemon holds no tab-1 for ${taskId}`);return tab}async function seedShellHome(client,taskId,shell){let{state}=await applyTabOps(client,taskId,[{op:"seed",state:asShared(initialShellTabs(shell))}]),tab=state?.tabs.find((t2)=>t2.id==="tab-1");if(tab?.kind!=="command")throw Error(`${taskId} already has tabs: its tab-1 is not a shell`);return tab}
2
+ import{buildEngineSessionLaunch,sniffProtocolFromTitle,trustEngineWorktree}from"./chunk-z6t0rmg1.js";import{diffTabs,engineForkArgv,engineLaunchArgv,engineResumeArgv,withPinnedSessionId}from"./chunk-5c2syc7e.js";import{terminalTabsKey}from"./chunk-mdc7b01e.js";import{tildify}from"./chunk-jrzh4yv6.js";import{t}from"./chunk-4wq1jsve.js";import{engineEntry,engineStatusPrefixes,isEnginePlaceholderTitle,stripEngineStatusPrefix}from"./chunk-6nsjckc5.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{pathSyntax}from"./chunk-pn5ygqn6.js";function engineTabArgv(tab,base,live,fallbackVendor){if(tab.forkFrom&&!tab.spawned&&!live){let forked=tab.vendor?engineForkArgv(base,tab.vendor,tab.forkFrom,tab.sessionId??null):null;if(forked)return forked}if(!tab.sessionId)return base;let vendor=tab.vendor??fallbackVendor;if(tab.spawned&&!live)return engineResumeArgv(base,vendor,tab.sessionId)??base;return withPinnedSessionId(base,vendor,()=>tab.sessionId).argv}function engineTabSpawnFor(state,tab,base,opts){let{live,shell,prompt}=opts,firstEngine=state.tabs.find((t2)=>t2.kind==="engine"),fresh=!tab.spawned&&!live,tabPrompt=fresh?tab.initialPrompt?.trim():void 0,wantsPrompt=!!prompt&&tab.id===firstEngine?.id&&fresh,isFreshFirstEngine=tab.id===firstEngine?.id&&fresh,promptIntent=tabPrompt?{kind:"explicit",prompt:tabPrompt}:wantsPrompt?{kind:"new-task",prompt}:isFreshFirstEngine?{kind:"repo-init"}:{kind:"none"},ref=tab.ptyTask;trustEngineWorktree(tab.vendor??opts.task.vendor,ref?.worktree??opts.worktreePath);let launch=buildEngineSessionLaunch({task:ref?{...opts.task,id:ref.id,kind:"task"}:opts.task,worktreePath:ref?.worktree??opts.worktreePath,shell,argv:engineTabArgv(tab,base,live,opts.task.vendor),promptIntent,protocolGates:opts.protocolGates,inlineImages:opts.inlineImages,tabId:ref?ref.tabId??"tab-1":tab.id});return{command:launch.command,...launch.firstMessage?{firstMessage:launch.firstMessage,engineBin:base[0]}:{}}}function tabExitAction(tab,deadOnAttach,resumeTried){if(tab.kind==="engine"&&deadOnAttach&&!!tab.sessionId&&tab.spawned&&!resumeTried)return"resume";return"close"}import*as fs from"fs";import*as os from"os";function pathLeaf(p){return p.slice(lastSeparator(p)+1)}function lastSeparator(p){return pathSyntax(p).sep==="\\"||process.platform==="win32"&&!p.startsWith("/")?Math.max(p.lastIndexOf("/"),p.lastIndexOf("\\")):p.lastIndexOf("/")}function expandHome(p){if(p==="~")return os.homedir();if(p.startsWith("~/")||process.platform==="win32"&&p.startsWith("~\\"))return os.homedir()+p.slice(1);return p}function stripTrailingSlash(p){let root=pathSyntax(p).parse(p).root,end=p.length;while(end>root.length&&lastSeparator(p.slice(0,end))===end-1)end--;return p.slice(0,end)}function splitPathForDirSuggest(value){if(!value)return{base:"",filter:""};let expanded=expandHome(value==="~"?"~/":value),lastSlash=lastSeparator(expanded);if(lastSlash===-1)return{base:"",filter:expanded};return{base:expanded.slice(0,lastSlash+1),filter:expanded.slice(lastSlash+1)}}function listSubdirs(base){if(!base)return[];try{let entries=fs.readdirSync(base,{withFileTypes:!0}),out=[];for(let e of entries)if(e.isDirectory())out.push(e.name);return out.sort((a,b)=>a.localeCompare(b))}catch{return[]}}function filterSubdirs(all,filter){let f=filter.toLowerCase(),visible=f.startsWith(".")?all:all.filter((n)=>!n.startsWith("."));if(!f)return visible;return visible.filter((n)=>n.toLowerCase().startsWith(f))}function joinDrill(typedValue,baseExpanded,name){let out=`${baseExpanded+name}/`;if(typedValue.startsWith("~")){let short=tildify(out);if(short.startsWith("~"))return short==="~"?"~/":`${short}/`}return out}function joinPicked(typedValue,baseExpanded,name){let out=baseExpanded+name;if(typedValue.startsWith("~"))return tildify(out);return out}function depth(node){return node.kind==="leaf"?0:1+Math.max(...node.children.map(depth))}function siblingCount(root,id,orientation){let find=(node)=>{if(node.kind==="leaf")return null;if(node.orientation===orientation&&node.children.some((c)=>c.kind==="leaf"&&c.id===id))return node.children.length;for(let child of node.children){let n=find(child);if(n!==null)return n}return null};return find(root)??1}function splitFits(state,orientation,activeSize){let extent=orientation==="row"?activeSize.cols:activeSize.rows,min=orientation==="row"?20:6,n=siblingCount(state.root,state.activeLeafId,orientation);return Math.floor(extent*n/(n+1))-1>=min}function initialSplit(content){return{root:{kind:"leaf",id:"leaf-1",content},activeLeafId:"leaf-1",nextOrdinal:2}}function leaves(node){return node.kind==="leaf"?[node]:node.children.flatMap(leaves)}function splitActive(state,orientation,content,activeSize){if(activeSize&&!splitFits(state,orientation,activeSize))return state;let leaf={kind:"leaf",id:`leaf-${state.nextOrdinal}`,content},insert=(node)=>{if(node.kind==="leaf"){if(node.id!==state.activeLeafId)return node;return{kind:"group",orientation,children:[node,leaf]}}if(node.orientation===orientation){let i=node.children.findIndex((c)=>c.kind==="leaf"&&c.id===state.activeLeafId);if(i>=0){let children=[...node.children.slice(0,i+1),leaf,...node.children.slice(i+1)];return{...node,children}}}return{...node,children:node.children.map(insert)}},root=insert(state.root);if(!activeSize&&depth(root)>4)return state;return{root,activeLeafId:leaf.id,nextOrdinal:state.nextOrdinal+1}}function removeLeaf(state,id){let all=leaves(state.root);if(all.length<=1)return null;let prune=(node)=>{if(node.kind==="leaf")return node.id===id?null:node;let children=node.children.map(prune).filter((c)=>c!==null);if(children.length===0)return null;if(children.length===1)return children[0];return{...node,children}},root=prune(state.root);if(root===null)return null;if(leaves(root).length===all.length)return state;let order=all.map((l)=>l.id),removedIdx=order.indexOf(id),fallback=order[removedIdx>0?removedIdx-1:removedIdx+1],activeLeafId=state.activeLeafId===id?fallback:state.activeLeafId;return{...state,root,activeLeafId}}function renameLeaf(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,walk=(node)=>node.kind==="leaf"?node.id===id?{...node,title:next}:node:{...node,children:node.children.map(walk)};if(!leaves(state.root).some((l)=>l.id===id))return state;return{...state,root:walk(state.root)}}function cycleLeaf(state,delta){let order=leaves(state.root).map((l)=>l.id);if(order.length<=1)return state;let i=order.indexOf(state.activeLeafId),next=order[(i+delta+order.length)%order.length];return{...state,activeLeafId:next}}function hasEngineLeaf(tree){return!tree||leaves(tree.root).some((l)=>l.id==="leaf-1")}function isTabSplit(tree){return tree?leaves(tree.root).length>1:!1}function collapseSplit(next){let ls=leaves(next.root);return ls.length===1&&ls[0]?.id==="leaf-1"?null:next}function splitLeafPtyKey(tabKey,leafId){return leafId==="leaf-1"?tabKey:`${tabKey}::${leafId}`}var SHELL_LEAF_NAME="shell";function splitLeafNames(leafList,tabCommand,engineTitle,liveTitles){let basename=(argv)=>{let head=(argv??tabCommand)[0]??"",name=pathLeaf(head);return name.length>0?name:"?"},seen=new Map,out=new Map;for(let leaf of leafList){if(leaf.title){out.set(leaf.id,leaf.title);continue}let name=leaf.content===null?engineTitle||liveTitles?.get(leaf.id)||basename(leaf.content):liveTitles?.get(leaf.id)||SHELL_LEAF_NAME,n=(seen.get(name)??0)+1;seen.set(name,n),out.set(leaf.id,n===1?name:`${name} ${n}`)}return out}function meaningfulAutoTitle(autoTitle){let trimmed=(autoTitle??"").trim();if(trimmed.length<3)return null;if(/^[\d\s\p{P}\p{S}]+$/u.test(trimmed))return null;return trimmed}function stableRecordedTitle(raw,vendor){let recorded=raw?.trim();if(!recorded)return null;let cleaned=stripEngineStatusPrefix(recorded,vendor);if(cleaned===recorded&&isEngineDecoration(recorded,vendor))return null;if(isEnginePlaceholderTitle(cleaned,vendor))return null;return cleaned||null}function isEngineDecoration(text,vendor){let glyphs=new Set(engineStatusPrefixes(vendor));return[...text].every((ch)=>ch.trim().length===0||glyphs.has(ch))}function tabTitleStable(tab,taskVendor,liveVendor,liveTitle){if(liveVendor===null&&tab.kind==="engine")return tabTitle({...tab,kind:"command",lastTitle:null},taskVendor);let source=liveTitle?.trim()||tab.lastTitle,vendor=liveVendor??tab.liveVendor??sniffProtocolFromTitle(source)??(tab.kind==="engine"?tab.vendor??taskVendor:void 0)??void 0,named=vendor?stableRecordedTitle(source,vendor):source??null;if(!vendor||engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return tabTitle({...tab,...vendor?{kind:"engine",vendor}:{},lastTitle:named},taskVendor);return tabTitle({...tab,kind:"engine",vendor,lastTitle:named},taskVendor)}function conversationTitle(tab,taskVendor,liveTitle){let renamed=tab.title?.trim();if(renamed)return renamed;let source=liveTitle?.trim()||tab.lastTitle,vendor=titleVendor(tab,taskVendor,source),named=stableRecordedTitle(source,vendor);if(!named)return null;let entry=engineEntry(vendor),generic=[entry.displayName,entry.defaultCommand[0]].map((name)=>name?.toLowerCase()),lowered=named.toLowerCase();return generic.includes(lowered)||generic.includes(lowered.replace(/ (code|cli)$/,""))?null:named}function titleVendor(tab,taskVendor,title){return tab.liveVendor??sniffProtocolFromTitle(title)??(tab.kind==="engine"?tab.vendor:void 0)??taskVendor}function tabTitle(tab,taskVendor,liveName){if(tab.title)return tab.title;let ls=tab.splitTree?leaves(tab.splitTree.root):[];if(ls.length>1)return t("terminal.tab.groupTitle",{n:tab.ordinal});let sole=ls.length===1?ls[0]:void 0;if(sole&&sole.id!=="leaf-1")return sole.title??`${liveName??SHELL_LEAF_NAME} ${tab.ordinal}`;let vendor=titleVendor(tab,taskVendor,liveName||tab.lastTitle);if(liveName&&!isEnginePlaceholderTitle(liveName,vendor))return`${liveName} ${tab.ordinal}`;if(tab.lastTitle&&!isEnginePlaceholderTitle(tab.lastTitle,vendor))return`${tab.lastTitle} ${tab.ordinal}`;let auto=meaningfulAutoTitle(tab.autoTitle);if(auto)return auto;return`${tab.kind==="engine"?engineEntry(tab.vendor??taskVendor).defaultCommand[0]??SHELL_LEAF_NAME:SHELL_LEAF_NAME} ${tab.ordinal}`}function visibleNativeStatus(tab,taskVendor,vendor,liveName){if(!vendor||!liveName)return!1;if(engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return!1;return tabTitle(tab,taskVendor,liveName)===`${liveName} ${tab.ordinal}`}function initialTabs(){return{tabs:[{kind:"engine",id:"tab-1",title:null,ordinal:1}],activeId:"tab-1",nextOrdinal:2}}function reopenHintFor(closed){if(closed?.kind==="command")return{kind:"command"};if(closed?.kind==="engine"&&closed.vendor)return{kind:"engine",vendor:closed.vendor};return{kind:"engine"}}function reopenTabs(state,shell,engine){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,next=state.nextOrdinal+1;if(!engine&&state.reopenAs?.kind==="command")return{tabs:[{kind:"command",id,title:null,ordinal,command:[shell]}],activeId:id,nextOrdinal:next};let vendor=state.reopenAs?.kind==="engine"?state.reopenAs.vendor:void 0;return{tabs:[{kind:"engine",id,title:null,ordinal,...engine??(vendor?{vendor}:{})}],activeId:id,nextOrdinal:next}}function initialShellTabs(shell){return{tabs:[{kind:"command",id:"tab-1",title:null,ordinal:1,command:[shell]}],activeId:"tab-1",nextOrdinal:2}}function rehydrateTabs(persisted,shell,opts={}){let tabs=persisted.tabs.map((t2)=>t2.kind==="command"?{...t2,command:shell,purpose:void 0}:t2);if(tabs.length===0)return opts.allowEmpty?persisted:initialTabs();let activeId=tabs.some((t2)=>t2.id===persisted.activeId)?persisted.activeId:tabs[0].id,maxOrdinal=tabs.reduce((max,t2)=>Math.max(max,t2.ordinal),0);return{tabs,activeId,nextOrdinal:Math.max(persisted.nextOrdinal,maxOrdinal+1)}}function recycleTabs(state,prev){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,pinned=prev.kind==="engine"?prev:void 0;return{tabs:[{kind:"engine",id,ordinal,title:prev.title,autoTitle:prev.autoTitle,...pinned?.vendor?{vendor:pinned.vendor}:{},...pinned?.engineCommand?{engineCommand:pinned.engineCommand}:{}}],activeId:id,nextOrdinal:ordinal+1}}var SHELL_SAFE_ARG=/^[A-Za-z0-9@%+=:,./_-]+$/;function shellCommandLine(argv){return argv.map((a)=>SHELL_SAFE_ARG.test(a)?a:`'${a.replaceAll("'","'\\''")}'`).join(" ")}function shellIdentityInput(taskId,tabId,extraEnv=[]){let task=shellCommandLine([taskId]),tab=shellCommandLine([tabId]),extra=extraEnv.map(([name,value])=>` ${name}=${shellCommandLine([value])}`).join("");return` export ROVE_TASK_ID=${task} ROVE_TAB_ID=${tab}${extra} && clear\r`}function insertAfterActive(state,tab){let i=state.tabs.findIndex((t2)=>t2.id===state.activeId);return{tabs:[...state.tabs.slice(0,i+1),tab,...state.tabs.slice(i+1)],activeId:tab.id,nextOrdinal:state.nextOrdinal+1}}function addTab(state,vendor){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"engine",id:`tab-${ordinal}`,title:null,ordinal,vendor})}function openCommandTab(state,command,label){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command})}function findEditorTab(state){return state.tabs.find((tab)=>tab.kind==="command"&&tab.purpose==="editor")}function openEditorTab(state,command,label){let existing=findEditorTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command,purpose:"editor"})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,command,splitTree:null}:tab);return{...state,tabs,activeId:existing.id}}function findContentTab(state){return state.tabs.find((tab)=>tab.kind==="content")}function openContentTab(state,relPath,label,base){let existing=findContentTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"content",id:`tab-${ordinal}`,title:label,ordinal,relPath,base})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,relPath,base}:tab);return{...state,tabs,activeId:existing.id}}function closeTab(state,id,opts={}){if(state.tabs.length<=1&&!opts.allowEmpty)return{state,closedId:null};let i=state.tabs.findIndex((t2)=>t2.id===id);if(i<0)return{state,closedId:null};let tabs=state.tabs.filter((t2)=>t2.id!==id);if(state.activeId!==id)return{state:{...state,tabs},closedId:id};if(tabs.length===0)return{state:{...state,tabs,activeId:id,reopenAs:reopenHintFor(state.tabs[i])},closedId:id};let next=tabs[Math.max(0,i-1)];return{state:{...state,tabs,activeId:(next??tabs[0]).id},closedId:id}}function closeActiveTab(state){return closeTab(state,state.activeId)}function renameActiveTab(state,title){return setTabTitle(state,state.activeId,title)}function setTabTitle(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.title??null)===next)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,title:next}:t2);return{...state,tabs}}function setTabSessionId(state,id,sessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,sessionId}:t2);return{...state,tabs}}function setTabForkFrom(state,id,sourceSessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,forkFrom:sourceSessionId}:t2);return{...state,tabs}}function setTabEngineCommand(state,id,command){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,engineCommand:command}:t2);return{...state,tabs}}function setTabInitialPrompt(state,id,prompt){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,initialPrompt:prompt}:t2);return{...state,tabs}}function setTabLastTitle(state,id,lastTitle){if(lastTitle.length===0)return state;let current=state.tabs.find((t2)=>t2.id===id);if(!current||current.lastTitle===lastTitle)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,lastTitle}:t2);return{...state,tabs}}function setTabLiveVendor(state,id,liveVendor){let current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.liveVendor??null)===liveVendor)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,liveVendor}:t2);return{...state,tabs}}function setTabAutoTitle(state,id,autoTitle){let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,autoTitle}:t2);return{...state,tabs}}function setTabSpawned(state,id,spawned){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"&&!t2.spawned!==!spawned?{...t2,spawned}:t2);return{...state,tabs}}function cycleTab(state,delta){let n=state.tabs.length;if(n<=1)return state;let i=state.tabs.findIndex((t2)=>t2.id===state.activeId),next=state.tabs[(i+delta+n)%n];return{...state,activeId:next.id}}function gotoTab(state,index){let target=state.tabs[index];return target&&target.id!==state.activeId?{...state,activeId:target.id}:state}function moveTab(state,id,delta){let i=state.tabs.findIndex((t2)=>t2.id===id),j=i+delta;if(i<0||j<0||j>=state.tabs.length)return state;let tabs=[...state.tabs],a=tabs[i];return tabs[i]=tabs[j],tabs[j]=a,{...state,tabs}}function selectTab(state,id){if(state.activeId===id||!state.tabs.some((t2)=>t2.id===id))return state;return{...state,activeId:id}}function setTabSplit(state,id,tree){if(!state.tabs.some((t2)=>t2.id===id))return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,splitTree:tree}:t2);return{...state,tabs}}function tabPtyKey(taskId,tabId){return`${taskId}::${tabId}`}function tabPtyKeyFor(taskId,tab){if(tab.kind==="engine"&&tab.ptyTask)return tabPtyKey(tab.ptyTask.id,tab.ptyTask.tabId??"tab-1");return tabPtyKey(taskId,tab.id)}function tabCwdFor(tab,taskWorktree){if(tab.kind==="engine"&&tab.ptyTask)return tab.ptyTask.worktree;return taskWorktree}function wireNode(node){if(node.kind==="leaf")return{kind:"leaf",id:node.id,title:node.title??null,own:node.content===null};return{kind:"group",orientation:node.orientation,children:node.children.map(wireNode)}}function wireSplit(tree){return tree?{root:wireNode(tree.root),activeLeafId:tree.activeLeafId}:null}function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function asTabsState(state){if(!state||!Array.isArray(state.tabs))return;return{...state,activeId:state.activeId??state.tabs[0]?.id??""}}var asShared=(state)=>state;async function applyTabOps(client,taskId,ops){let reply=await client.request("tabs.apply",{taskId,ops});return{state:asTabsState(reply?.state),opened:reply?.opened??[]}}async function readDaemonTabs(client,taskId){return asTabsState((await client.request("tabs.get",{taskId}))?.state)}async function editTabs(client,taskId,edit){let before=await readDaemonTabs(client,taskId);if(!before)return;let next=edit(before);if(next===before)return;let ops=diffTabs(asShared(before),asShared(next));if(ops.length>0)await applyTabOps(client,taskId,ops)}async function closeTabsSnapshot(client,taskId,tabId){let closing;return await editTabs(client,taskId,(state)=>{if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return state;let{state:next,closedId}=closeTab({...state,activeId:tabId},tabId,{allowEmpty:!0});if(!closedId)closing=void 0;return closedId?next:state}),closing}async function renameTabsSnapshot(client,taskId,tabId,title){let found=!1;return await editTabs(client,taskId,(state)=>{return found=state.tabs.some((tab)=>tab.id===tabId),found?setTabTitle(state,tabId,title):state}),found}async function patchTabSplit(client,taskId,tabId,tree){let{state}=await applyTabOps(client,taskId,[{op:"patch",id:tabId,set:{splitTree:tree??null}}]);return state?.tabs.find((t2)=>t2.id===tabId)}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t2)=>t2.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),liveTitles=new Map(rows0.filter((s)=>s.alive&&s.title?.trim()).map((s)=>[s.key,s.title])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t2)=>{let key=tabPtyKeyFor(taskId,t2),isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t2.id,kind:t2.kind,title:t2.title??null,vendor:t2.vendor??null,liveVendor:walked!==void 0?walked:t2.liveVendor??null,lastTitle:t2.lastTitle??null,liveTitle:liveTitles.get(key)??null,autoTitle:t2.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null,...t2.splitTree?{split:wireSplit(t2.splitTree)}:{},...t2.kind==="engine"&&t2.ptyTask?{viewOf:t2.ptyTask.id}:{}}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0)){let key=`${taskId}::${tabId}`,engineIsAlive=engineAliveOf(key,!0,engineAlive);rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,liveTitle:liveTitles.get(key)??null,autoTitle:null,alive:!0,engineAlive:engineIsAlive,exit:engineIsAlive===!1?engineExit(key):null,unregistered:!0})}return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}async function publishCliTabSnapshot(client,taskId,sessionId){if(!taskId)return;try{let seeded=initialTabs(),state=sessionId?{...seeded,tabs:seeded.tabs.map((t2)=>t2.kind==="engine"?{...t2,sessionId,spawned:!0}:t2)}:seeded;await applyTabOps(client,taskId,[{op:"seed",state:asShared(state)}])}catch{}}async function markCliTabSession(client,taskId,tabId,sessionId){try{if((await readDaemonTabs(client,taskId))?.tabs.find((t2)=>t2.id===tabId)?.kind!=="engine")return;let set={...sessionId?{sessionId}:{},spawned:!0};return(await applyTabOps(client,taskId,[{op:"patch",id:tabId,set}])).state}catch{return}}async function allocateTab(client,taskId,row){let{state,opened}=await applyTabOps(client,taskId,[{op:"seed",state:asShared(initialTabs())},{op:"open",row}]),id=opened[0],tab=id?state?.tabs.find((t2)=>t2.id===id):void 0;if(!tab)throw Error(`the daemon opened no tab for ${taskId}`);return tab}async function seedCanonicalTab(client,taskId){let{state}=await applyTabOps(client,taskId,[{op:"seed",state:asShared(initialTabs())}]),tab=state?.tabs.find((t2)=>t2.id==="tab-1");if(!tab)throw Error(`the daemon holds no tab-1 for ${taskId}`);return tab}async function seedShellHome(client,taskId,shell){let{state}=await applyTabOps(client,taskId,[{op:"seed",state:asShared(initialShellTabs(shell))}]),tab=state?.tabs.find((t2)=>t2.id==="tab-1");if(tab?.kind!=="command")throw Error(`${taskId} already has tabs: its tab-1 is not a shell`);return tab}
3
3
  export{pathLeaf,expandHome,stripTrailingSlash,splitPathForDirSuggest,listSubdirs,filterSubdirs,joinDrill,joinPicked,initialSplit,leaves,splitActive,removeLeaf,renameLeaf,cycleLeaf,hasEngineLeaf,isTabSplit,collapseSplit,splitLeafPtyKey,splitLeafNames,tabTitleStable,conversationTitle,tabTitle,visibleNativeStatus,initialTabs,reopenTabs,initialShellTabs,rehydrateTabs,recycleTabs,engineTabArgv,engineTabSpawnFor,tabExitAction,shellIdentityInput,addTab,openCommandTab,findEditorTab,openEditorTab,openContentTab,closeTab,closeActiveTab,renameActiveTab,setTabTitle,setTabSessionId,setTabForkFrom,setTabEngineCommand,setTabInitialPrompt,setTabLastTitle,setTabLiveVendor,setTabAutoTitle,setTabSpawned,cycleTab,gotoTab,moveTab,selectTab,setTabSplit,tabPtyKey,tabPtyKeyFor,tabCwdFor,wireSplit,taskEngineArgv,readTabsSnapshot,applyTabOps,readDaemonTabs,closeTabsSnapshot,renameTabsSnapshot,patchTabSplit,unregisteredTabIds,joinTaskTabs,publishCliTabSnapshot,markCliTabSession,allocateTab,seedCanonicalTab,seedShellHome};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{publishRoveTerminalTitle}from"./chunk-3aqhytyy.js";import{ensureGlobalRoveHooks}from"./chunk-1rs3dmwz.js";import{LAST_RUN_VERSION_KEY,enforceResetGate}from"./chunk-gvzr7jxt.js";import"./chunk-17e2tgyg.js";import"./chunk-2bgmby1d.js";import"./chunk-1k7f137x.js";import{CURRENT_VERSION,compareSemver}from"./chunk-bg2ypp04.js";import{detectShell}from"./chunk-bxqdxv63.js";import"./chunk-e4fp3w22.js";import"./chunk-nbcm8d58.js";import"./chunk-j1z9kgyd.js";import"./chunk-e5crm07d.js";import"./chunk-gca19v0w.js";import"./chunk-9y803nx4.js";import"./chunk-qq2mjph2.js";import"./chunk-96kvwzj8.js";import"./chunk-zsfyj36g.js";import"./chunk-4wq1jsve.js";import"./chunk-af60qacx.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{loadStateFile,patchStateFile}from"./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{__require}from"./chunk-91sykzqq.js";var WELCOMED_KEY="welcomed";function shouldWelcome(state){if(state[WELCOMED_KEY]===!0)return!1;return typeof state[LAST_RUN_VERSION_KEY]!=="string"}function takeWelcome(){if(!shouldWelcome(loadStateFile()))return null;try{patchStateFile({[WELCOMED_KEY]:!0})}catch{}return{shell:detectShell()}}var WHATS_NEW_SEEN_KEY="app.whatsNewSeenVersion";function whatsNewFromVersion(state,current=CURRENT_VERSION){let stamped=state[WHATS_NEW_SEEN_KEY]??state[LAST_RUN_VERSION_KEY];if(typeof stamped!=="string"||stamped.length===0)return null;return compareSemver(current,stamped)>0?stamped:null}function takeWhatsNew(){let from=whatsNewFromVersion(loadStateFile());try{patchStateFile({[WHATS_NEW_SEEN_KEY]:CURRENT_VERSION})}catch{}return from}async function startTui(){let whatsNewFrom=takeWhatsNew(),welcome=takeWelcome();enforceResetGate(),publishRoveTerminalTitle(),await ensureGlobalRoveHooks();let{loadPluginEngines}=await import("./chunk-9xax0901.js");loadPluginEngines();let{startSkillStatus}=await import("./chunk-gqqtkwkq.js");startSkillStatus();let{startWorkspaceHost}=await import("./chunk-ee9nm38f.js");await startWorkspaceHost({whatsNewFrom,welcome})}export{startTui};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-9q43btkf.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
2
+ import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-acqqhrjb.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
3
3
  export{runChannelCli,startChatChannels};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Orchestrator}from"./chunk-e23n32hv.js";import"./chunk-e1c6909n.js";import"./chunk-c1dz3qg3.js";import"./chunk-p1pbtfa5.js";import"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-2xsxcdp6.js";import"./chunk-qq1q07tz.js";import"./chunk-gq36nzg8.js";import"./chunk-hk0zbk3t.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-xmwp6je4.js";import"./chunk-6xppe9bj.js";import"./chunk-mqfvzdpr.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-z46zwmyq.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-cmp64q4j.js";import"./chunk-2tfnscxk.js";import"./chunk-rja9tf6j.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-rz8319pe.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-jzsngv31.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.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{PLACEHOLDER_TASK_TITLE,Orchestrator};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{PreambleStripper}from"./chunk-sq6zj3fb.js";import{shQuote}from"./chunk-y1xnjx8x.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";import{RoveDaemonClient}from"./chunk-8y10pmkf.js";import{homeDir}from"./chunk-z1nj22va.js";import{logClientError}from"./chunk-0g4wc808.js";import{shortHomeTag}from"./chunk-eqdbfgq5.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-f8gg8cqh.js";import{spawn as spawn3}from"child_process";import{mkdirSync as mkdirSync3,rmSync as rmSync2}from"fs";import{connect as netConnect}from"net";import{tmpdir}from"os";import{join}from"path";var LOCAL_MACHINE_ID="local",ALIAS_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function isValidMachineAlias(alias){return alias!==LOCAL_MACHINE_ID&&alias.length<=64&&ALIAS_RE.test(alias)}function parseSshTarget(target){let trimmed=target.trim();if(!trimmed)return null;let at=trimmed.lastIndexOf("@"),user=at>=0?trimmed.slice(0,at):void 0,rest=at>=0?trimmed.slice(at+1):trimmed;if(at>=0&&!user)return null;let bracketed=/^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(rest),portMatch=bracketed?null:/^([^:]*):(\d{1,5})$/.exec(rest),host=bracketed?bracketed[1]??"":portMatch?portMatch[1]??"":rest,rawPort=bracketed?bracketed[2]:portMatch?.[2],port=rawPort?Number(rawPort):void 0;if(!host||/\s/.test(host))return null;if(port!==void 0&&(port<1||port>65535))return null;return{host,...user?{user}:{},...port?{port}:{}}}function defaultMachineAlias(args){let source=!args.typedUser&&args.port===void 0&&!isIpLiteral(args.typedHost)?args.typedHost:args.remoteHostname||args.typedHost;return sanitizeAlias(source)}function isIpLiteral(host){return host.includes(":")||/^\d{1,3}(\.\d{1,3}){3}$/.test(host)}function sanitizeAlias(raw){return(raw.split(".")[0]??raw).replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)}function sshTargetOf(config){return config.user?`${config.user}@${config.host}`:config.host}function readMachines(state){let raw=state.machines;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function listMachines(){let machines=readMachines(loadStateFile());return Object.entries(machines).map(([alias,config])=>({alias,...config}))}function getMachine(alias){return readMachines(loadStateFile())[alias]??null}function addMachine(alias,config){let added=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};added=machines[alias]===void 0,machines[alias]={...config,addedAt:config.addedAt??machines[alias]?.addedAt??new Date().toISOString()},state.machines=machines;return}),{added}}function updateMachine(alias,patch){updateStateFile((state)=>{let machines={...readMachines(state)},existing=machines[alias];if(!existing)return!1;machines[alias]={...existing,...patch},state.machines=machines;return})}function setMachineIdentity(alias,identity){updateMachine(alias,{identity})}function removeMachine(alias){let removed=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};if(removed=machines[alias]!==void 0,!removed)return!1;delete machines[alias],state.machines=machines;return}),removed}function dedupeMachines(entries){let kept=[],seen=[];for(let entry of entries){let identity=entry.identity;if(identity){if(seen.some((other)=>sameMachine(other,identity)))continue;seen.push(identity)}kept.push(entry)}return kept}function sameMachine(a,b){return a.hostname===b.hostname&&a.homeDir===b.homeDir&&a.daemonPid===b.daemonPid}function duplicateAliasOf(machines,self,identity){for(let[alias,config]of Object.entries(machines)){if(alias===self)continue;let other=config.identity;if(!other)continue;if(other.hostname===identity.hostname&&other.homeDir===identity.homeDir&&other.daemonPid===identity.daemonPid)return alias}return null}var CONTROL_PERSIST_SECONDS=300;function machineSocketDir(alias,home=homeDir()){let natural=join(home,".rove","machines",alias);if(Buffer.byteLength(join(natural,"daemon.sock"),"utf8")<=SOCKET_PATH_LIMIT)return natural;return join(tmpdir(),`rove-m-${shortHomeTag(home)}-${shortHomeTag(alias)}`)}var SOCKET_PATH_LIMIT=100;function localDaemonSocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"daemon.sock")}function localPtySocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"pty.sock")}function controlPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"cm")}function machineSshArgs(alias,config,opts={}){let argv=["ssh"];if(opts.batch!==!1)argv.push("-o","BatchMode=yes");if(opts.mux!==!1&&process.platform!=="win32")argv.push("-o","ControlMaster=auto","-o",`ControlPath=${controlPath(alias,opts.home)}`,"-o",`ControlPersist=${CONTROL_PERSIST_SECONDS}`);if(argv.push("-o","StrictHostKeyChecking=accept-new"),config.port)argv.push("-p",String(config.port));if(config.auth.kind==="key"&&config.auth.keyPath)argv.push("-i",config.auth.keyPath);return argv.push(sshTargetOf(config)),argv}import{spawn as spawn2}from"child_process";import{mkdirSync as mkdirSync2,rmSync}from"fs";import{createServer}from"net";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";function isWindowsPath(path){return/^[A-Za-z]:[\\/]/.test(path)||/^\\\\[.?]\\/.test(path)}function isWindowsMachine(config){if(config.sockets&&(isWindowsPath(config.sockets.daemon)||isWindowsPath(config.sockets.pty)))return!0;return config.roveBin!==void 0&&isWindowsPath(config.roveBin)}function psQuote(value){return`'${value.replaceAll("'","''")}'`}function powershellCommand(script){return`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function windowsRoveCommand(roveBin,args){return powershellCommand(`& ${psQuote(roveBin)} ${args.map(psQuote).join(" ")}; exit $LASTEXITCODE`)}var WINDOWS_LOCATE_SCRIPT=['$dirs = @("$env:APPDATA\\npm", "$env:USERPROFILE\\.bun\\bin", "$env:LOCALAPPDATA\\pnpm", $env:NVM_SYMLINK)',"$dirs += [Environment]::GetEnvironmentVariable('Path', 'User') -split ';'","foreach ($d in $dirs) { if (-not $d) { continue }",` foreach ($n in 'rove.cmd', 'rove.exe') { $p = Join-Path $d $n; if (Test-Path -LiteralPath $p) { "ROVE_BIN=$p"; exit 0 } } }`,"exit 1"].join(`
2
+ import{PreambleStripper}from"./chunk-sq6zj3fb.js";import{shQuote}from"./chunk-y1xnjx8x.js";import{RoveDaemonClient}from"./chunk-qq2mjph2.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";import{logClientError}from"./chunk-0g4wc808.js";import{shortHomeTag}from"./chunk-eqdbfgq5.js";import{homeDir}from"./chunk-z1nj22va.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-f8gg8cqh.js";import{spawn as spawn3}from"child_process";import{mkdirSync as mkdirSync3,rmSync as rmSync2}from"fs";import{connect as netConnect}from"net";import{tmpdir}from"os";import{join}from"path";var LOCAL_MACHINE_ID="local",ALIAS_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function isValidMachineAlias(alias){return alias!==LOCAL_MACHINE_ID&&alias.length<=64&&ALIAS_RE.test(alias)}function parseSshTarget(target){let trimmed=target.trim();if(!trimmed)return null;let at=trimmed.lastIndexOf("@"),user=at>=0?trimmed.slice(0,at):void 0,rest=at>=0?trimmed.slice(at+1):trimmed;if(at>=0&&!user)return null;let bracketed=/^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(rest),portMatch=bracketed?null:/^([^:]*):(\d{1,5})$/.exec(rest),host=bracketed?bracketed[1]??"":portMatch?portMatch[1]??"":rest,rawPort=bracketed?bracketed[2]:portMatch?.[2],port=rawPort?Number(rawPort):void 0;if(!host||/\s/.test(host))return null;if(port!==void 0&&(port<1||port>65535))return null;return{host,...user?{user}:{},...port?{port}:{}}}function defaultMachineAlias(args){let source=!args.typedUser&&args.port===void 0&&!isIpLiteral(args.typedHost)?args.typedHost:args.remoteHostname||args.typedHost;return sanitizeAlias(source)}function isIpLiteral(host){return host.includes(":")||/^\d{1,3}(\.\d{1,3}){3}$/.test(host)}function sanitizeAlias(raw){return(raw.split(".")[0]??raw).replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)}function sshTargetOf(config){return config.user?`${config.user}@${config.host}`:config.host}function readMachines(state){let raw=state.machines;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function listMachines(){let machines=readMachines(loadStateFile());return Object.entries(machines).map(([alias,config])=>({alias,...config}))}function getMachine(alias){return readMachines(loadStateFile())[alias]??null}function addMachine(alias,config){let added=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};added=machines[alias]===void 0,machines[alias]={...config,addedAt:config.addedAt??machines[alias]?.addedAt??new Date().toISOString()},state.machines=machines;return}),{added}}function updateMachine(alias,patch){updateStateFile((state)=>{let machines={...readMachines(state)},existing=machines[alias];if(!existing)return!1;machines[alias]={...existing,...patch},state.machines=machines;return})}function setMachineIdentity(alias,identity){updateMachine(alias,{identity})}function removeMachine(alias){let removed=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};if(removed=machines[alias]!==void 0,!removed)return!1;delete machines[alias],state.machines=machines;return}),removed}function dedupeMachines(entries){let kept=[],seen=[];for(let entry of entries){let identity=entry.identity;if(identity){if(seen.some((other)=>sameMachine(other,identity)))continue;seen.push(identity)}kept.push(entry)}return kept}function sameMachine(a,b){return a.hostname===b.hostname&&a.homeDir===b.homeDir&&a.daemonPid===b.daemonPid}function duplicateAliasOf(machines,self,identity){for(let[alias,config]of Object.entries(machines)){if(alias===self)continue;let other=config.identity;if(!other)continue;if(other.hostname===identity.hostname&&other.homeDir===identity.homeDir&&other.daemonPid===identity.daemonPid)return alias}return null}var CONTROL_PERSIST_SECONDS=300;function machineSocketDir(alias,home=homeDir()){let natural=join(home,".rove","machines",alias);if(Buffer.byteLength(join(natural,"daemon.sock"),"utf8")<=SOCKET_PATH_LIMIT)return natural;return join(tmpdir(),`rove-m-${shortHomeTag(home)}-${shortHomeTag(alias)}`)}var SOCKET_PATH_LIMIT=100;function localDaemonSocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"daemon.sock")}function localPtySocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"pty.sock")}function controlPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"cm")}function machineSshArgs(alias,config,opts={}){let argv=["ssh"];if(opts.batch!==!1)argv.push("-o","BatchMode=yes");if(opts.mux!==!1&&process.platform!=="win32")argv.push("-o","ControlMaster=auto","-o",`ControlPath=${controlPath(alias,opts.home)}`,"-o",`ControlPersist=${CONTROL_PERSIST_SECONDS}`);if(argv.push("-o","StrictHostKeyChecking=accept-new"),config.port)argv.push("-p",String(config.port));if(config.auth.kind==="key"&&config.auth.keyPath)argv.push("-i",config.auth.keyPath);return argv.push(sshTargetOf(config)),argv}import{spawn as spawn2}from"child_process";import{mkdirSync as mkdirSync2,rmSync}from"fs";import{createServer}from"net";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";function isWindowsPath(path){return/^[A-Za-z]:[\\/]/.test(path)||/^\\\\[.?]\\/.test(path)}function isWindowsMachine(config){if(config.sockets&&(isWindowsPath(config.sockets.daemon)||isWindowsPath(config.sockets.pty)))return!0;return config.roveBin!==void 0&&isWindowsPath(config.roveBin)}function psQuote(value){return`'${value.replaceAll("'","''")}'`}function powershellCommand(script){return`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function windowsRoveCommand(roveBin,args){return powershellCommand(`& ${psQuote(roveBin)} ${args.map(psQuote).join(" ")}; exit $LASTEXITCODE`)}var WINDOWS_LOCATE_SCRIPT=['$dirs = @("$env:APPDATA\\npm", "$env:USERPROFILE\\.bun\\bin", "$env:LOCALAPPDATA\\pnpm", $env:NVM_SYMLINK)',"$dirs += [Environment]::GetEnvironmentVariable('Path', 'User') -split ';'","foreach ($d in $dirs) { if (-not $d) { continue }",` foreach ($n in 'rove.cmd', 'rove.exe') { $p = Join-Path $d $n; if (Test-Path -LiteralPath $p) { "ROVE_BIN=$p"; exit 0 } } }`,"exit 1"].join(`
3
3
  `),WINDOWS_LOCATE_ROVE=powershellCommand(WINDOWS_LOCATE_SCRIPT),WINDOWS_ROVE_MISSING=/'(?:[^'\r\n]*[\\/])?rove(?:\.cmd|\.exe|\.ps1)?' is not recognized as (?:an internal or external command|(?:the|a) name of a cmdlet)/i,WINDOWS_SCRIPTS_DISABLED=/rove\.ps1 cannot be loaded because running scripts is disabled/i;function windowsNoRoveMessage(alias,output){if(WINDOWS_SCRIPTS_DISABLED.test(output))return[`${alias}'s ssh sessions run Windows PowerShell, whose execution policy refuses npm's rove.ps1, and no rove.cmd was found to use instead.`,`On ${alias}, either allow scripts for your user: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`,'or make ssh use PowerShell 7 (elevated): New-ItemProperty -Path HKLM:\\SOFTWARE\\OpenSSH -Name DefaultShell -Value "$env:ProgramFiles\\PowerShell\\7\\pwsh.exe" -PropertyType String -Force'].join(`
4
4
  `);return[`Rove is not on the PATH of ssh sessions on ${alias} (Windows), nor in %APPDATA%\\npm, ~\\.bun\\bin or the user PATH.`,"Install it there in a PowerShell: npm install -g @sma1lboy/rove",`If it is installed elsewhere, add that folder to your user PATH on ${alias}, then restart sshd (elevated: Restart-Service sshd) so new sessions see it.`].join(`
5
5
  `)}var WINDOWS_SSHD_BANNER=/remote software version OpenSSH_for_Windows/i,WINDOWS_SSHD_STEPS=["Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0","Set-Service sshd -StartupType Automatic; Start-Service sshd","if (-not (Get-NetFirewallRule -Name OpenSSH-Server-In-TCP -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name OpenSSH-Server-In-TCP -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 }"];function windowsAuthorizeKeySteps(publicKey){let key=psQuote(publicKey.trim());return["# Administrator account (elevated PowerShell):",`Add-Content -Path "$env:ProgramData\\ssh\\administrators_authorized_keys" -Value ${key}`,'icacls.exe "$env:ProgramData\\ssh\\administrators_authorized_keys" /inheritance:r /grant "*S-1-5-32-544:F" /grant "SYSTEM:F"',"# Standard account (normal PowerShell):",`New-Item -ItemType Directory -Force "$HOME\\.ssh" | Out-Null; Add-Content -Path "$HOME\\.ssh\\authorized_keys" -Value ${key}`]}var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target,windows=!1){if(windows&&(kind==="refused"||kind==="timeout"))return[`${target} (Windows) ${kind==="refused"?"refused the connection: its OpenSSH Server is not running":"did not answer on the ssh port: its OpenSSH Server is off, or the firewall drops it"}.`,"In an elevated PowerShell there:",...WINDOWS_SSHD_STEPS.map((step)=>` ${step}`)].join(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{AUTO_MACHINE,LOCAL_MACHINE,forwardVerb,invokeRouted,machineDaemonSocket,machinePtySocket,machineTasks,pickMachine,repoHosts,repoWanted,requireMachine,routeTarget}from"./chunk-em75b155.js";import"./chunk-mdfm45fx.js";import"./chunk-vp29jgbt.js";import"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import"./chunk-k2p7at32.js";import"./chunk-z6t0rmg1.js";import"./chunk-5c2syc7e.js";import"./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-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{routeTarget,requireMachine,repoWanted,repoHosts,pickMachine,machineTasks,machinePtySocket,machineDaemonSocket,invokeRouted,forwardVerb,LOCAL_MACHINE,AUTO_MACHINE};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{detectLanguage}from"./chunk-hpay0ax8.js";import{REPO_CONFIG_DIRS,isNonEmptyRepoFile,readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{getRepoInitOverride}from"./chunk-gygdyf0s.js";import{existsSync}from"fs";import{join}from"path";var LOCKFILE_DEPENDENCY_DIRS=[["bun.lock","node_modules"],["bun.lockb","node_modules"],["package-lock.json","node_modules"],["yarn.lock","node_modules"],["pnpm-lock.yaml","node_modules"],["Cargo.lock","target"],["poetry.lock",".venv"],["uv.lock",".venv"]];function missingDependenciesCoda(worktreePath,language){let missing=new Set;for(let[lockfile,dependencyDir]of LOCKFILE_DEPENDENCY_DIRS){if(!existsSync(join(worktreePath,lockfile)))continue;if(existsSync(join(worktreePath,dependencyDir)))continue;missing.add(dependencyDir)}if(missing.size===0)return;let dirs=[...missing].join(", ");if(language==="zh")return`\u8865\u5145\uFF1A\u8FD9\u4E2A worktree \u6CA1\u6709\u88C5\u4F9D\u8D56\uFF08\u4ED3\u5E93\u91CC\u6709 lockfile\uFF0C\u4F46 ${dirs} \u4E0D\u5B58\u5728\uFF09\u3002\u5728\u76F8\u4FE1\u4EFB\u4F55\u6784\u5EFA / \u6D4B\u8BD5\u7ED3\u679C\u4E4B\u524D\uFF0C\u5148\u8DD1\u4E00\u904D\u672C\u4ED3\u5E93\u7684\u5B89\u88C5\u6B65\u9AA4\u2014\u2014\u8FD9\u91CC\u7684\u5931\u8D25\u591A\u534A\u662F\u56E0\u4E3A\u6CA1\u88C5\u4F9D\u8D56\uFF0C\u800C\u4E0D\u662F\u4EE3\u7801\u56DE\u5F52\u3002\u5982\u679C\u8FD9\u4E2A\u4ED3\u5E93\u6BCF\u6B21\u90FD\u9700\u8981\u88C5\uFF0C\u53EF\u4EE5\u8003\u8651\u52A0\u4E00\u4E2A \`.rove/init.sh\`\u3002`;return`PS: this worktree has no installed dependencies (${dirs} missing beside a committed lockfile). Run the repo's install step before trusting build/test results \u2014 a failure here is most likely the missing install, not a regression. If this repo always needs one, consider adding \`.rove/init.sh\`.`}var INIT_SCRIPT_FILENAME="init.sh",INIT_PROMPT_FILENAME="init-prompt.md";function repoFileScript(worktreePath){for(let dir of REPO_CONFIG_DIRS)if(existsSync(join(worktreePath,dir,INIT_SCRIPT_FILENAME)))return`sh ${dir}/${INIT_SCRIPT_FILENAME}`;return}function repoFilePrompt(worktreePath){return readFirstNonEmptyRepoFile(worktreePath,INIT_PROMPT_FILENAME)}function describeRepoInitSources(repoRoot){let describe=(filename,counts)=>{let taken=!1;return REPO_CONFIG_DIRS.map((dir)=>{let absolute=join(repoRoot,dir,filename),effective=!taken&&counts(absolute);if(effective)taken=!0;return{rel:`${dir}/${filename}`,present:existsSync(absolute),effective}})};return{script:describe(INIT_SCRIPT_FILENAME,existsSync),prompt:describe(INIT_PROMPT_FILENAME,isNonEmptyRepoFile)}}function resolveRepoInit(repoRoot,worktreePath){let override=repoRoot?getRepoInitOverride(repoRoot):{},initScript=repoFileScript(worktreePath)??override.initScript,initPrompt=repoFilePrompt(worktreePath)??override.initPrompt;return{initScript:initScript&&initScript.trim().length>0?initScript:void 0,initPrompt:initPrompt&&initPrompt.trim().length>0?initPrompt:void 0}}function firstMessageFor(intent,init,worktreePath){if(intent.kind==="none")return;if(intent.kind==="explicit")return{source:"explicit",text:intent.prompt};if(intent.kind==="new-task"){let deps=init.initScript?void 0:missingDependenciesCoda(worktreePath,detectLanguage(intent.prompt)??void 0);return{source:"explicit",text:[intent.prompt,deps].filter(Boolean).join(`
2
+ import{detectLanguage}from"./chunk-hpay0ax8.js";import{REPO_CONFIG_DIRS,isNonEmptyRepoFile,readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{getRepoInitOverride}from"./chunk-rja9tf6j.js";import{existsSync}from"fs";import{join}from"path";var LOCKFILE_DEPENDENCY_DIRS=[["bun.lock","node_modules"],["bun.lockb","node_modules"],["package-lock.json","node_modules"],["yarn.lock","node_modules"],["pnpm-lock.yaml","node_modules"],["Cargo.lock","target"],["poetry.lock",".venv"],["uv.lock",".venv"]];function missingDependenciesCoda(worktreePath,language){let missing=new Set;for(let[lockfile,dependencyDir]of LOCKFILE_DEPENDENCY_DIRS){if(!existsSync(join(worktreePath,lockfile)))continue;if(existsSync(join(worktreePath,dependencyDir)))continue;missing.add(dependencyDir)}if(missing.size===0)return;let dirs=[...missing].join(", ");if(language==="zh")return`\u8865\u5145\uFF1A\u8FD9\u4E2A worktree \u6CA1\u6709\u88C5\u4F9D\u8D56\uFF08\u4ED3\u5E93\u91CC\u6709 lockfile\uFF0C\u4F46 ${dirs} \u4E0D\u5B58\u5728\uFF09\u3002\u5728\u76F8\u4FE1\u4EFB\u4F55\u6784\u5EFA / \u6D4B\u8BD5\u7ED3\u679C\u4E4B\u524D\uFF0C\u5148\u8DD1\u4E00\u904D\u672C\u4ED3\u5E93\u7684\u5B89\u88C5\u6B65\u9AA4\u2014\u2014\u8FD9\u91CC\u7684\u5931\u8D25\u591A\u534A\u662F\u56E0\u4E3A\u6CA1\u88C5\u4F9D\u8D56\uFF0C\u800C\u4E0D\u662F\u4EE3\u7801\u56DE\u5F52\u3002\u5982\u679C\u8FD9\u4E2A\u4ED3\u5E93\u6BCF\u6B21\u90FD\u9700\u8981\u88C5\uFF0C\u53EF\u4EE5\u8003\u8651\u52A0\u4E00\u4E2A \`.rove/init.sh\`\u3002`;return`PS: this worktree has no installed dependencies (${dirs} missing beside a committed lockfile). Run the repo's install step before trusting build/test results \u2014 a failure here is most likely the missing install, not a regression. If this repo always needs one, consider adding \`.rove/init.sh\`.`}var INIT_SCRIPT_FILENAME="init.sh",INIT_PROMPT_FILENAME="init-prompt.md";function repoFileScript(worktreePath){for(let dir of REPO_CONFIG_DIRS)if(existsSync(join(worktreePath,dir,INIT_SCRIPT_FILENAME)))return`sh ${dir}/${INIT_SCRIPT_FILENAME}`;return}function repoFilePrompt(worktreePath){return readFirstNonEmptyRepoFile(worktreePath,INIT_PROMPT_FILENAME)}function describeRepoInitSources(repoRoot){let describe=(filename,counts)=>{let taken=!1;return REPO_CONFIG_DIRS.map((dir)=>{let absolute=join(repoRoot,dir,filename),effective=!taken&&counts(absolute);if(effective)taken=!0;return{rel:`${dir}/${filename}`,present:existsSync(absolute),effective}})};return{script:describe(INIT_SCRIPT_FILENAME,existsSync),prompt:describe(INIT_PROMPT_FILENAME,isNonEmptyRepoFile)}}function resolveRepoInit(repoRoot,worktreePath){let override=repoRoot?getRepoInitOverride(repoRoot):{},initScript=repoFileScript(worktreePath)??override.initScript,initPrompt=repoFilePrompt(worktreePath)??override.initPrompt;return{initScript:initScript&&initScript.trim().length>0?initScript:void 0,initPrompt:initPrompt&&initPrompt.trim().length>0?initPrompt:void 0}}function firstMessageFor(intent,init,worktreePath){if(intent.kind==="none")return;if(intent.kind==="explicit")return{source:"explicit",text:intent.prompt};if(intent.kind==="new-task"){let deps=init.initScript?void 0:missingDependenciesCoda(worktreePath,detectLanguage(intent.prompt)??void 0);return{source:"explicit",text:[intent.prompt,deps].filter(Boolean).join(`
3
3
 
4
4
  `)}}let text=init.initPrompt?.trim();return text?{source:"repo-init",text}:void 0}function resolveEngineLaunchInit(repoRoot,worktreePath,intent={kind:"repo-init"}){let init=resolveRepoInit(repoRoot,worktreePath);return{initScript:init.initScript,firstMessage:firstMessageFor(intent,init,worktreePath)}}
5
5
  export{missingDependenciesCoda,describeRepoInitSources,resolveRepoInit,resolveEngineLaunchInit};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-ee8917py.js";import{readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-22emnsn5.js";import{getRemoteRepoConfig}from"./chunk-gygdyf0s.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{smallIgnoredPaths}from"./chunk-xmwp6je4.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import path4 from"path";function parseDirtyPaths(stdout){return parsePorcelainRows(stdout).filter((row)=>(row.x+row.y).trim().length>0).map((row)=>row.path).filter((p)=>p.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var METER_RE=/(\d{1,3})% \(\d+\/\d+\)/g;function checkoutProgressReader(onPercent){let tail="",last=-1;return(chunk)=>{let text=tail+chunk,end=Math.max(text.lastIndexOf("\r"),text.lastIndexOf(`
2
+ import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-qq1q07tz.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{smallIgnoredPaths}from"./chunk-xmwp6je4.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-z46zwmyq.js";import{getRemoteRepoConfig}from"./chunk-rja9tf6j.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import path4 from"path";function parseDirtyPaths(stdout){return parsePorcelainRows(stdout).filter((row)=>(row.x+row.y).trim().length>0).map((row)=>row.path).filter((p)=>p.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var METER_RE=/(\d{1,3})% \(\d+\/\d+\)/g;function checkoutProgressReader(onPercent){let tail="",last=-1;return(chunk)=>{let text=tail+chunk,end=Math.max(text.lastIndexOf("\r"),text.lastIndexOf(`
3
3
  `));if(end<0){tail=text;return}tail=text.slice(end+1);let percent=-1;for(let match of text.slice(0,end).matchAll(METER_RE))percent=Number(match[1]);if(percent<0||percent>100||percent===last)return;last=percent,onPercent(percent)}}class CheckpointError extends Error{code;constructor(code,reason){super(`${code}: ${reason}`);this.code=code;this.name="CheckpointError"}}function checkpointRef(taskId,n){return`refs/rove/checkpoints/${taskId}/${n}`}var FALLBACK_IDENTITY={GIT_AUTHOR_NAME:"Rove",GIT_AUTHOR_EMAIL:"rove@localhost",GIT_COMMITTER_NAME:"Rove",GIT_COMMITTER_EMAIL:"rove@localhost"};function parseSubject(subject){let parts=subject.trim().split(/\s+/).slice(3),at=parts.pop()??"";return parts[0]?{at,tabId:parts[0]}:{at}}async function listCheckpoints(deps,exec,cwd,taskId){let prefix=`refs/rove/checkpoints/${taskId}/`,out=await deps.runGit(exec,["for-each-ref","--format=%(refname)%09%(objectname)%09%(tree)%09%(subject)",prefix],{cwd,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return[];let records=[];for(let line of out.stdout.split(`
4
4
  `)){let[ref,commit,tree,subject=""]=line.split("\t"),n=Number(ref?.slice(prefix.length));if(!ref||!commit||!tree||!Number.isInteger(n))continue;records.push({n,ref,commit,tree,...parseSubject(subject)})}return records.sort((a,b)=>a.n-b.n)}async function gitlinkPaths(exec,deps,cwd,tree){let out=await deps.runGit(exec,["ls-tree","-r",tree],{cwd,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return[];return out.stdout.split(`
5
5
  `).filter((line)=>line.startsWith("160000 ")).map((line)=>line.slice(line.indexOf("\t")+1)).filter((p)=>p.length>0)}async function withTempIndex(deps,exec,cwd,body){let name=`rove-ckpt-index-${process.pid}-${Math.random().toString(36).slice(2,8)}`,indexPath=(await deps.runGit(exec,["rev-parse","--git-path",name],{cwd,allowFail:!0,readOnly:!0})).stdout.trim();if(!indexPath)throw new CheckpointError("CHECKPOINT_FAILED",`${cwd} is not a git work tree`);try{return await body((args,extraEnv)=>deps.runGit(exec,args,{cwd,allowFail:!0,env:{GIT_INDEX_FILE:indexPath,...extraEnv}}),indexPath)}finally{await exec.run(["rm","-f",indexPath],{cwd}).catch(()=>{return})}}async function snapshotTree(deps,exec,cwd,head){let tree=await withTempIndex(deps,exec,cwd,async(gitIdx,indexPath)=>{let real=(await deps.runGit(exec,["rev-parse","--git-path","index"],{cwd,allowFail:!0,readOnly:!0})).stdout.trim();if(!(real!==""&&(await exec.run(["cp","-p",real,indexPath],{cwd}).catch(()=>{return}))?.exitCode===0)&&head&&(await gitIdx(["read-tree",head])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","read-tree failed");if((await gitIdx(["add","-A"])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","git add -A failed");let written=(await gitIdx(["write-tree"])).stdout.trim();if(!written)throw new CheckpointError("CHECKPOINT_FAILED","write-tree failed");return written});return{tree,uncaptured:await gitlinkPaths(exec,deps,cwd,tree)}}async function headCommit(deps,exec,cwd){let out=await deps.runGit(exec,["rev-parse","--verify","-q","HEAD"],{cwd,allowFail:!0,readOnly:!0});return out.exitCode===0?out.stdout.trim():""}async function takeCheckpoint(deps,exec,worktreePath,taskId,opts={}){let head=await headCommit(deps,exec,worktreePath),{tree,uncaptured}=await snapshotTree(deps,exec,worktreePath,head),existing=await listCheckpoints(deps,exec,worktreePath,taskId),latest=existing[existing.length-1];if(latest&&latest.tree===tree)return{created:!1,checkpoint:latest};let at=(opts.now??new Date).toISOString(),hasIdentity=(await deps.runGit(exec,["var","GIT_COMMITTER_IDENT"],{cwd:worktreePath,allowFail:!0,readOnly:!0})).exitCode===0;for(let n=(latest?.n??0)+1,attempt=0;attempt<5;n++,attempt++){let message=["rove checkpoint",n,opts.tabId,at].filter((p)=>p!==void 0&&p!=="").join(" "),commitArgs=head?["commit-tree",tree,"-p",head,"-m",message]:["commit-tree",tree,"-m",message],commit=await deps.runGit(exec,commitArgs,{cwd:worktreePath,allowFail:!0,...hasIdentity?{}:{env:FALLBACK_IDENTITY}}),sha=commit.stdout.trim();if(commit.exitCode!==0||!sha)throw new CheckpointError("CHECKPOINT_FAILED",`commit-tree failed: ${commit.stderr.trim()}`);let ref=checkpointRef(taskId,n);if((await deps.runGit(exec,["update-ref",ref,sha,""],{cwd:worktreePath,allowFail:!0})).exitCode===0)return await pruneCheckpoints(deps,exec,worktreePath,taskId).catch(()=>{return}),{created:!0,checkpoint:{n,ref,commit:sha,tree,at,...opts.tabId?{tabId:opts.tabId}:{}},uncaptured}}throw new CheckpointError("CHECKPOINT_FAILED",`could not allocate a checkpoint number for ${taskId}`)}async function deleteRefs(deps,exec,cwd,refs){for(let ref of refs)await deps.runGit(exec,["update-ref","-d",ref],{cwd,allowFail:!0})}async function pruneCheckpoints(deps,exec,cwd,taskId,keep=100){let all=await listCheckpoints(deps,exec,cwd,taskId),doomed=all.slice(0,Math.max(0,all.length-keep));return await deleteRefs(deps,exec,cwd,doomed.map((c)=>c.ref)),doomed.length}async function deleteTaskCheckpoints(deps,exec,cwd,taskId){let all=await listCheckpoints(deps,exec,cwd,taskId);return await deleteRefs(deps,exec,cwd,all.map((c)=>c.ref)),all.length}async function moveTaskCheckpoints(deps,exec,cwd,fromId,toId){let moved=0;for(let c of await listCheckpoints(deps,exec,cwd,fromId)){if((await deps.runGit(exec,["update-ref",checkpointRef(toId,c.n),c.commit,""],{cwd,allowFail:!0})).exitCode!==0)continue;await deleteRefs(deps,exec,cwd,[c.ref]),moved++}return moved}async function rewindTo(deps,exec,worktreePath,taskId,n,opts={}){let target=(await listCheckpoints(deps,exec,worktreePath,taskId)).find((c)=>c.n===n);if(!target)throw new CheckpointError("CHECKPOINT_NOT_FOUND",`task ${taskId} has no checkpoint ${n}`);let taken=await takeCheckpoint(deps,exec,worktreePath,taskId,{now:opts.now}),undo=taken.checkpoint,uncaptured=taken.created?taken.uncaptured:[];await withTempIndex(deps,exec,worktreePath,async(gitIdx)=>{if((await gitIdx(["read-tree",undo.tree])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","read-tree (current) failed");let res=await gitIdx(["read-tree","--reset","-u",target.tree]);if(res.exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED",`read-tree failed: ${res.stderr.trim()}`)});let head=await headCommit(deps,exec,worktreePath);return await deps.runGit(exec,head?["reset","-q"]:["read-tree","--empty"],{cwd:worktreePath,allowFail:!0}),{target,undo,uncaptured}}import fs from"fs/promises";import path from"path";var WORKTREE_CLONE_IGNORED_KEY="worktree.cloneIgnored",DEFAULT_CLONE_DIRS=["node_modules",".venv","target",".build"];function isCloneIgnoredEnabled(){return loadStateFile()[WORKTREE_CLONE_IGNORED_KEY]!==!1}function parseCloneDirs(text){return text.split(/\r?\n/).map((line)=>line.replace(/#.*$/,"").trim()).filter((e)=>e.length>0&&e!=="."&&e!==".."&&!/[/\\]/.test(e)&&!e.startsWith("-"))}function resolveCloneDirs(worktreePath){let file=readFirstNonEmptyRepoFile(worktreePath,"clone-dirs");return file===void 0?DEFAULT_CLONE_DIRS:parseCloneDirs(file)}var CLONEFILEAT_PERL='my $r = syscall(462, -2, $ARGV[0], -2, $ARGV[1], 0); if ($r != 0) { print STDERR "clonefileat: $!\\n"; exit 1 }';function defaultCloneDeps(exec){return{platform:process.platform,statDev:async(p)=>(await fs.stat(p)).dev,isApfs:async(p)=>{let r=await exec.run(["/bin/df","-T","apfs",p]);return r.exitCode===0&&r.stdout.trim().split(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{describeRepoInitSources,missingDependenciesCoda,resolveEngineLaunchInit,resolveRepoInit}from"./chunk-ntqg38ke.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./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{resolveRepoInit,resolveEngineLaunchInit,missingDependenciesCoda,describeRepoInitSources};
@@ -6,6 +6,6 @@ ${EXPORT_USAGE}
6
6
  `),process.exit(2)}function parseFormat(args){let format="json";for(let i=0;i<args.length;i++){let a=args[i];if(a==="--json")format="json";else if(a==="--csv")format="csv";else if(a==="--format"){let v=args[++i];if(v===void 0)usageError("--format requires a value (json, csv, or table)");format=coerceFormat(v)}else if(a.startsWith("--format="))format=coerceFormat(a.slice(9));else usageError(`unexpected argument "${a}"`)}return format}function coerceFormat(value){if(value==="json"||value==="csv"||value==="table")return value;usageError(`unknown format "${value}" (expected json, csv, or table)`)}function csvCell(value){if(/[",\r\n]/.test(value))return`"${value.replace(/"/g,'""')}"`;return value}function renderCsv(rows){let lines=[COLUMNS.join(",")];for(let row of rows)lines.push(COLUMNS.map((c)=>csvCell(row[c])).join(","));return lines.join(`
7
7
  `)}function padCell(cell,width){return cell+" ".repeat(Math.max(0,width-displayWidth(cell)))}function renderTable(rows){let widths={};for(let c of COLUMNS)widths[c]=Math.max(displayWidth(c),...rows.map((r)=>displayWidth(r[c])));let line=(cells)=>COLUMNS.map((c)=>padCell(cells[c],widths[c])).join(" ").trimEnd(),header={};for(let c of COLUMNS)header[c]=c;return[line(header),...rows.map(line)].join(`
8
8
  `)}function renderExport(tasks,format){let rows=tasks.map(toRow);if(format==="json")return JSON.stringify(rows,null,2);if(format==="csv")return renderCsv(rows);return renderTable(rows)}async function runExportSubcommand(args){if(args.includes("--help")||args.includes("-h")||args.includes("help")){process.stdout.write(`${EXPORT_USAGE}
9
- `);return}let format=parseFormat(args),{TaskIndexStore}=await import("./chunk-8h94w236.js"),store=new TaskIndexStore;await store.load();let tasks=store.list();if(tasks.length===0&&format==="table"){process.stdout.write(`no tasks
9
+ `);return}let format=parseFormat(args),{TaskIndexStore}=await import("./chunk-v765ej4f.js"),store=new TaskIndexStore;await store.load();let tasks=store.list();if(tasks.length===0&&format==="table"){process.stdout.write(`no tasks
10
10
  `);return}process.stdout.write(`${renderExport(tasks,format)}
11
11
  `)}export{runExportSubcommand,renderExport};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{isPathLikeArg,runOpenDirectory}from"./chunk-1e0v0ycz.js";import"./chunk-jrzh4yv6.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{runOpenDirectory,isPathLikeArg};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,defaultLocalWorktreesRoot,legacyLocalWorktreesRoot,managedWorktreeRootsFor,normalizeWorktreeBase,worktreeRootFor}from"./chunk-gq36nzg8.js";import{execHostForRepo}from"./chunk-22emnsn5.js";import{getRemoteRepoConfig,isRemoteRepoKey}from"./chunk-gygdyf0s.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{pathWithin}from"./chunk-pn5ygqn6.js";class IllegalTransitionError extends Error{from;to;taskId;constructor(from,to,taskId){super(`illegal transition for task ${taskId}: ${from} -> ${to}`);this.from=from;this.to=to;this.taskId=taskId;this.name="IllegalTransitionError"}}class TaskNotFoundError extends Error{constructor(taskId){super(`task not found: ${taskId}`);this.name="TaskNotFoundError"}}class CannotDeleteMainTaskError extends Error{constructor(){super("cannot delete a main task; remove the repo from saved repos instead");this.name="CannotDeleteMainTaskError"}}var DIRTY_WORKTREE_CODE="DIRTY_WORKTREE";function describeDirtyWorktreeWork(ignored,dirty=[]){if(dirty.length>0)return`uncommitted or untracked changes: ${namePaths(dirty)}`;return ignored==="unknown"?"gitignored work this check could not read (git status --ignored failed) \u2014 nothing here can confirm it is empty":ignored.length>0?`gitignored work git status cannot see: ${ignored.join(", ")}`:"uncommitted or untracked changes"}var DIRTY_PATHS_SHOWN=10;function namePaths(paths){let shown=paths.slice(0,DIRTY_PATHS_SHOWN).join(", "),more=paths.length-DIRTY_PATHS_SHOWN;return more>0?`${shown} (+${more} more)`:shown}function dirtyRefusalReason(err){let message=errorMessage(err),at=message.indexOf(DIRTY_WORKTREE_CODE);if(at<0)return null;return message.slice(at+DIRTY_WORKTREE_CODE.length).replace(/^:\s*/,"")}class DirtyWorktreeError extends Error{taskId;ignored;dirty;repo;also;constructor(taskId,ignored=[],dirty=[],repo,also=[]){let where=repo?` (${repo})`:"",rest=also.map((f)=>`; also ${f.repo}: ${describeDirtyWorktreeWork(f.ignored,f.dirty)}`).join("");super(`${DIRTY_WORKTREE_CODE}: task ${taskId} worktree${where} has ${describeDirtyWorktreeWork(ignored,dirty)}${rest}`);this.taskId=taskId;this.ignored=ignored;this.dirty=dirty;this.repo=repo;this.also=also;this.name="DirtyWorktreeError"}}class WorktreeRemoveFailedError extends Error{taskId;cause;constructor(taskId,cause){super(`failed to remove worktree for task ${taskId}: ${errorMessage(cause)}`);this.taskId=taskId;this.cause=cause;this.name="WorktreeRemoveFailedError"}}var TASK_DELETING_CODE="TASK_DELETING";class TaskDeletingError extends Error{taskId;constructor(taskId){super(`${TASK_DELETING_CODE}: task ${taskId} is being deleted`);this.taskId=taskId;this.name="TaskDeletingError"}}var MAIN_CHECKOUT_DIRTY_CODE="MAIN_CHECKOUT_DIRTY";class MainCheckoutDirtyError extends Error{repo;dir;constructor(repo,dir){super(`${MAIN_CHECKOUT_DIRTY_CODE}: base checkout at ${dir} has uncommitted changes; commit them before landing (never git stash \u2014 the stash stack is shared by every worktree of this repo)`);this.repo=repo;this.dir=dir;this.name="MainCheckoutDirtyError"}}var EMPTY_BRANCH_CODE="EMPTY_BRANCH";class EmptyBranchError extends Error{branch;landedOn;constructor(branch,landedOn){super(`${EMPTY_BRANCH_CODE}: '${branch}' has no commits ahead of '${landedOn}' \u2014 landing it would be a no-op (the worker may not have delivered anything)`);this.branch=branch;this.landedOn=landedOn;this.name="EmptyBranchError"}}var EMPTY_BRANCH_DIRTY_WORKTREE_CODE="EMPTY_BRANCH_DIRTY_WORKTREE";class EmptyBranchDirtyWorktreeError extends Error{branch;landedOn;worktreePath;files;constructor(branch,landedOn,worktreePath,files){let list=files.length>0?files.join(", "):"(none reported)";super(`${EMPTY_BRANCH_DIRTY_WORKTREE_CODE}: '${branch}' has no commits ahead of '${landedOn}' but its worktree ${worktreePath} has uncommitted changes (${list}) \u2014 commit them in the worktree first, then land again`);this.branch=branch;this.landedOn=landedOn;this.worktreePath=worktreePath;this.files=files;this.name="EmptyBranchDirtyWorktreeError"}}var MISSING_REF_CODE="MISSING_REF";class MissingRefError extends Error{branch;landedOn;dir;constructor(branch,landedOn,dir){super(`${MISSING_REF_CODE}: '${branch}' does not resolve in the base repo at ${dir} (comparing against '${landedOn}') \u2014 the branch was renamed or deleted outside Rove; re-point the task with \`rove api update --branch\` or recreate the branch`);this.branch=branch;this.landedOn=landedOn;this.dir=dir;this.name="MissingRefError"}}var LAND_CONFLICT_CODE="LAND_CONFLICT";class LandConflictError extends Error{taskId;branch;files;constructor(taskId,branch,files){let list=files.length>0?files.join(", "):"(none reported)";super(`${LAND_CONFLICT_CODE}: merging '${branch}' hit conflicts, merge aborted \u2014 conflicted files: ${list}`);this.taskId=taskId;this.branch=branch;this.files=files;this.name="LandConflictError"}}var GIT_COMMAND_FAILED_CODE="GIT_COMMAND_FAILED";class GitCommandFailedError extends Error{command;stderr;constructor(command,stderr,hint){let detail=stderr.trim()||"(git printed nothing on stderr)";super(`${GIT_COMMAND_FAILED_CODE}: \`git ${command}\` failed \u2014 ${detail}${hint?`; ${hint}`:""}`);this.command=command;this.stderr=stderr;this.name="GitCommandFailedError"}}var WORKTREE_NAME_TAKEN_CODE="WORKTREE_NAME_TAKEN";class WorktreeNameTakenError extends Error{worktreeName;constructor(worktreeName){super(`${WORKTREE_NAME_TAKEN_CODE}: worktree name '${worktreeName}' is already in use in this repo \u2014 pick another, or omit --worktree-name for a generated one`);this.worktreeName=worktreeName;this.name="WorktreeNameTakenError"}}var INVALID_WORKTREE_NAME_CODE="INVALID_WORKTREE_NAME";class InvalidWorktreeNameError extends Error{worktreeName;constructor(worktreeName){super(`${INVALID_WORKTREE_NAME_CODE}: worktree name '${worktreeName}' must be a single path segment of letters, digits, '.', '_' or '-' (no '/', no '..', not starting with '.')`);this.worktreeName=worktreeName;this.name="InvalidWorktreeNameError"}}var NOT_A_GIT_REPO_CODE="NOT_A_GIT_REPO";class NotAGitRepoError extends Error{dir;constructor(dir){super(`${NOT_A_GIT_REPO_CODE}: ${dir} is not inside a git repository, so a child cannot get its own worktree \u2014 pass --no-worktree to share the directory`);this.dir=dir;this.name="NotAGitRepoError"}}var NOT_A_LINKED_REPO_CODE="NOT_A_LINKED_REPO";class NotALinkedRepoError extends Error{link;available;constructor(link,available){super(`${NOT_A_LINKED_REPO_CODE}: '${link}' is not a top-level symlink to a git checkout in the parent workspace (linked repos: ${available.length>0?available.join(", "):"none"})`);this.link=link;this.available=available;this.name="NotALinkedRepoError"}}var REMOTE_PARENT_UNSUPPORTED_CODE="REMOTE_PARENT_UNSUPPORTED";class RemoteParentUnsupportedError extends Error{taskId;constructor(taskId){super(`${REMOTE_PARENT_UNSUPPORTED_CODE}: task ${taskId} lives on a remote project \u2014 add the child from that machine's rove`);this.taskId=taskId;this.name="RemoteParentUnsupportedError"}}class ReparentRefusedError extends Error{code;constructor(code,detail){super(`${code}: ${detail}`);this.code=code;this.name="ReparentRefusedError"}}class MoveRefusedError extends Error{code;constructor(code,detail){super(`${code}: ${detail}`);this.code=code;this.name="MoveRefusedError"}}var TOO_MANY_REPOS_CODE="TOO_MANY_REPOS";class TooManyReposError extends Error{constructor(count,cap){super(`${TOO_MANY_REPOS_CODE}: ${count} repos exceed the cap of ${cap} per task (the first is the primary)`);this.name="TooManyReposError"}}var REPO_DUPLICATE_CODE="REPO_DUPLICATE";class RepoDuplicateError extends Error{repo;constructor(repo){super(`${REPO_DUPLICATE_CODE}: ${repo} is listed more than once (a subdirectory resolves to its repo root)`);this.repo=repo;this.name="RepoDuplicateError"}}var REMOTE_EXTRA_UNSUPPORTED_CODE="REMOTE_EXTRA_UNSUPPORTED";class RemoteExtraUnsupportedError extends Error{repo;constructor(repo){super(`${REMOTE_EXTRA_UNSUPPORTED_CODE}: ${repo} is a remote project \u2014 a task spanning several repos must keep all of them local`);this.repo=repo;this.name="RemoteExtraUnsupportedError"}}class ExtraRepoNotGitError extends Error{repo;constructor(repo){super(`${NOT_A_GIT_REPO_CODE}: ${repo} is not a git repository \u2014 every repo of a task needs one to cut its worktree and branch from`);this.repo=repo;this.name="ExtraRepoNotGitError"}}var FORK_UNSUPPORTED_CODE="FORK_UNSUPPORTED";class ForkUnsupportedError extends Error{constructor(reason){super(`${FORK_UNSUPPORTED_CODE}: ${reason}`);this.name="ForkUnsupportedError"}}import fs from"fs";import path from"path";var WORKTREE_BASE_CUSTOM_KEY="worktree.basePath.custom",PROJECT_SIBLING_BASE=`${PROJECT_DIR_TOKEN}/..`;function worktreeBaseKindOf(raw){let trimmed=raw.trim();if(!trimmed)return"default";if(trimmed.replace(/\/+$/,"")===PROJECT_SIBLING_BASE)return"nextToProject";return"custom"}function getWorktreeBaseOverride(projectDir){let value=loadStateFile()[WORKTREE_BASE_KEY];return normalizeWorktreeBase(typeof value==="string"?value:null,projectDir)}function worktreeRootFor2(repo){return worktreeRootFor(repo,getWorktreeBaseOverride(repo))}function managedWorktreeRootsFor2(repo){return managedWorktreeRootsFor(repo,getWorktreeBaseOverride(repo))}function worktreePathFor(repo,slug){if(!slug||/[/\\\0]/.test(slug))throw Error(`worktreePathFor: invalid slug: ${JSON.stringify(slug)}`);return path.join(worktreeRootFor2(repo),slug)}async function listWorktreeDirNames(repo){if(isRemoteRepoKey(repo)){let basePath=getRemoteRepoConfig(repo)?.basePath;if(!basePath)return[];let names2=new Set,host=execHostForRepo(repo),entries=await Promise.all(remoteManagedWorktreeRootsFor(basePath).map((root)=>host.readdir(root)));for(let list of entries)for(let name of list)names2.add(name);return[...names2]}let names=new Set;for(let root of managedWorktreeRootsFor2(repo))try{for(let e of fs.readdirSync(root,{withFileTypes:!0}))if(e.isDirectory())names.add(e.name)}catch{}return[...names]}function managedWorktreeRootForPath(repo,candidate){if(!path.isAbsolute(repo)||!path.isAbsolute(candidate))return null;let target=canonicalize(candidate);for(let rootPath of managedWorktreeRootsFor2(repo)){let root=canonicalize(rootPath),rel=pathWithin(root,target);if(rel!==null&&rel!=="")return rootPath}return null}function isRoveManagedPath(repo,candidate){return managedWorktreeRootForPath(repo,candidate)!==null}function isUnderManagedWorktreesRoot(candidate,projectDir){if(!path.isAbsolute(candidate))return!1;let target=canonicalize(candidate),roots=[getWorktreeBaseOverride(projectDir)??"",defaultLocalWorktreesRoot(),legacyLocalWorktreesRoot()];for(let rootPath of roots){if(!rootPath)continue;let root=canonicalize(rootPath),rel=pathWithin(root,target);if(rel===null)continue;if(rel.split("/").filter(Boolean).length===2)return!0}return!1}function remoteWorktreeRootFor(basePath){return`${stripTrailingSlash(basePath)}/.rove/worktrees`}function remoteManagedWorktreeRootsFor(basePath){let base=stripTrailingSlash(basePath);return[`${base}/.rove/worktrees`,`${base}/.rove/worktrees`]}function remoteWorktreePathFor(basePath,slug){if(!slug||/[/\\\0]/.test(slug))throw Error(`remoteWorktreePathFor: invalid slug: ${JSON.stringify(slug)}`);return`${remoteWorktreeRootFor(basePath)}/${slug}`}function remoteManagedRootForPath(basePath,candidate){for(let root of remoteManagedWorktreeRootsFor(basePath))if(candidate===root||candidate.startsWith(`${root}/`))return root;return null}function stripTrailingSlash(p){return p.length>1&&p.endsWith("/")?p.replace(/\/+$/,""):p}function requireAbsolute(name,value){if(!value||!path.isAbsolute(value))throw Error(`${name} must be an absolute path, got: ${JSON.stringify(value)}`)}function canonicalize(p){try{return fs.realpathSync(p)}catch{return path.resolve(p)}}
2
+ import{PROJECT_DIR_TOKEN,WORKTREE_BASE_KEY,defaultLocalWorktreesRoot,legacyLocalWorktreesRoot,managedWorktreeRootsFor,normalizeWorktreeBase,worktreeRootFor}from"./chunk-gq36nzg8.js";import{execHostForRepo}from"./chunk-z46zwmyq.js";import{getRemoteRepoConfig,isRemoteRepoKey}from"./chunk-rja9tf6j.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{pathWithin}from"./chunk-pn5ygqn6.js";class IllegalTransitionError extends Error{from;to;taskId;constructor(from,to,taskId){super(`illegal transition for task ${taskId}: ${from} -> ${to}`);this.from=from;this.to=to;this.taskId=taskId;this.name="IllegalTransitionError"}}class TaskNotFoundError extends Error{constructor(taskId){super(`task not found: ${taskId}`);this.name="TaskNotFoundError"}}class CannotDeleteMainTaskError extends Error{constructor(){super("cannot delete a main task; remove the repo from saved repos instead");this.name="CannotDeleteMainTaskError"}}var DIRTY_WORKTREE_CODE="DIRTY_WORKTREE";function describeDirtyWorktreeWork(ignored,dirty=[]){if(dirty.length>0)return`uncommitted or untracked changes: ${namePaths(dirty)}`;return ignored==="unknown"?"gitignored work this check could not read (git status --ignored failed) \u2014 nothing here can confirm it is empty":ignored.length>0?`gitignored work git status cannot see: ${ignored.join(", ")}`:"uncommitted or untracked changes"}var DIRTY_PATHS_SHOWN=10;function namePaths(paths){let shown=paths.slice(0,DIRTY_PATHS_SHOWN).join(", "),more=paths.length-DIRTY_PATHS_SHOWN;return more>0?`${shown} (+${more} more)`:shown}function dirtyRefusalReason(err){let message=errorMessage(err),at=message.indexOf(DIRTY_WORKTREE_CODE);if(at<0)return null;return message.slice(at+DIRTY_WORKTREE_CODE.length).replace(/^:\s*/,"")}class DirtyWorktreeError extends Error{taskId;ignored;dirty;repo;also;constructor(taskId,ignored=[],dirty=[],repo,also=[]){let where=repo?` (${repo})`:"",rest=also.map((f)=>`; also ${f.repo}: ${describeDirtyWorktreeWork(f.ignored,f.dirty)}`).join("");super(`${DIRTY_WORKTREE_CODE}: task ${taskId} worktree${where} has ${describeDirtyWorktreeWork(ignored,dirty)}${rest}`);this.taskId=taskId;this.ignored=ignored;this.dirty=dirty;this.repo=repo;this.also=also;this.name="DirtyWorktreeError"}}class WorktreeRemoveFailedError extends Error{taskId;cause;constructor(taskId,cause){super(`failed to remove worktree for task ${taskId}: ${errorMessage(cause)}`);this.taskId=taskId;this.cause=cause;this.name="WorktreeRemoveFailedError"}}var TASK_DELETING_CODE="TASK_DELETING";class TaskDeletingError extends Error{taskId;constructor(taskId){super(`${TASK_DELETING_CODE}: task ${taskId} is being deleted`);this.taskId=taskId;this.name="TaskDeletingError"}}var MAIN_CHECKOUT_DIRTY_CODE="MAIN_CHECKOUT_DIRTY";class MainCheckoutDirtyError extends Error{repo;dir;constructor(repo,dir){super(`${MAIN_CHECKOUT_DIRTY_CODE}: base checkout at ${dir} has uncommitted changes; commit them before landing (never git stash \u2014 the stash stack is shared by every worktree of this repo)`);this.repo=repo;this.dir=dir;this.name="MainCheckoutDirtyError"}}var EMPTY_BRANCH_CODE="EMPTY_BRANCH";class EmptyBranchError extends Error{branch;landedOn;constructor(branch,landedOn){super(`${EMPTY_BRANCH_CODE}: '${branch}' has no commits ahead of '${landedOn}' \u2014 landing it would be a no-op (the worker may not have delivered anything)`);this.branch=branch;this.landedOn=landedOn;this.name="EmptyBranchError"}}var EMPTY_BRANCH_DIRTY_WORKTREE_CODE="EMPTY_BRANCH_DIRTY_WORKTREE";class EmptyBranchDirtyWorktreeError extends Error{branch;landedOn;worktreePath;files;constructor(branch,landedOn,worktreePath,files){let list=files.length>0?files.join(", "):"(none reported)";super(`${EMPTY_BRANCH_DIRTY_WORKTREE_CODE}: '${branch}' has no commits ahead of '${landedOn}' but its worktree ${worktreePath} has uncommitted changes (${list}) \u2014 commit them in the worktree first, then land again`);this.branch=branch;this.landedOn=landedOn;this.worktreePath=worktreePath;this.files=files;this.name="EmptyBranchDirtyWorktreeError"}}var MISSING_REF_CODE="MISSING_REF";class MissingRefError extends Error{branch;landedOn;dir;constructor(branch,landedOn,dir){super(`${MISSING_REF_CODE}: '${branch}' does not resolve in the base repo at ${dir} (comparing against '${landedOn}') \u2014 the branch was renamed or deleted outside Rove; re-point the task with \`rove api update --branch\` or recreate the branch`);this.branch=branch;this.landedOn=landedOn;this.dir=dir;this.name="MissingRefError"}}var LAND_CONFLICT_CODE="LAND_CONFLICT";class LandConflictError extends Error{taskId;branch;files;constructor(taskId,branch,files){let list=files.length>0?files.join(", "):"(none reported)";super(`${LAND_CONFLICT_CODE}: merging '${branch}' hit conflicts, merge aborted \u2014 conflicted files: ${list}`);this.taskId=taskId;this.branch=branch;this.files=files;this.name="LandConflictError"}}var GIT_COMMAND_FAILED_CODE="GIT_COMMAND_FAILED";class GitCommandFailedError extends Error{command;stderr;constructor(command,stderr,hint){let detail=stderr.trim()||"(git printed nothing on stderr)";super(`${GIT_COMMAND_FAILED_CODE}: \`git ${command}\` failed \u2014 ${detail}${hint?`; ${hint}`:""}`);this.command=command;this.stderr=stderr;this.name="GitCommandFailedError"}}var WORKTREE_NAME_TAKEN_CODE="WORKTREE_NAME_TAKEN";class WorktreeNameTakenError extends Error{worktreeName;constructor(worktreeName){super(`${WORKTREE_NAME_TAKEN_CODE}: worktree name '${worktreeName}' is already in use in this repo \u2014 pick another, or omit --worktree-name for a generated one`);this.worktreeName=worktreeName;this.name="WorktreeNameTakenError"}}var INVALID_WORKTREE_NAME_CODE="INVALID_WORKTREE_NAME";class InvalidWorktreeNameError extends Error{worktreeName;constructor(worktreeName){super(`${INVALID_WORKTREE_NAME_CODE}: worktree name '${worktreeName}' must be a single path segment of letters, digits, '.', '_' or '-' (no '/', no '..', not starting with '.')`);this.worktreeName=worktreeName;this.name="InvalidWorktreeNameError"}}var NOT_A_GIT_REPO_CODE="NOT_A_GIT_REPO";class NotAGitRepoError extends Error{dir;constructor(dir){super(`${NOT_A_GIT_REPO_CODE}: ${dir} is not inside a git repository, so a child cannot get its own worktree \u2014 pass --no-worktree to share the directory`);this.dir=dir;this.name="NotAGitRepoError"}}var NOT_A_LINKED_REPO_CODE="NOT_A_LINKED_REPO";class NotALinkedRepoError extends Error{link;available;constructor(link,available){super(`${NOT_A_LINKED_REPO_CODE}: '${link}' is not a top-level symlink to a git checkout in the parent workspace (linked repos: ${available.length>0?available.join(", "):"none"})`);this.link=link;this.available=available;this.name="NotALinkedRepoError"}}var REMOTE_PARENT_UNSUPPORTED_CODE="REMOTE_PARENT_UNSUPPORTED";class RemoteParentUnsupportedError extends Error{taskId;constructor(taskId){super(`${REMOTE_PARENT_UNSUPPORTED_CODE}: task ${taskId} lives on a remote project \u2014 add the child from that machine's rove`);this.taskId=taskId;this.name="RemoteParentUnsupportedError"}}class ReparentRefusedError extends Error{code;constructor(code,detail){super(`${code}: ${detail}`);this.code=code;this.name="ReparentRefusedError"}}class MoveRefusedError extends Error{code;constructor(code,detail){super(`${code}: ${detail}`);this.code=code;this.name="MoveRefusedError"}}var TOO_MANY_REPOS_CODE="TOO_MANY_REPOS";class TooManyReposError extends Error{constructor(count,cap){super(`${TOO_MANY_REPOS_CODE}: ${count} repos exceed the cap of ${cap} per task (the first is the primary)`);this.name="TooManyReposError"}}var REPO_DUPLICATE_CODE="REPO_DUPLICATE";class RepoDuplicateError extends Error{repo;constructor(repo){super(`${REPO_DUPLICATE_CODE}: ${repo} is listed more than once (a subdirectory resolves to its repo root)`);this.repo=repo;this.name="RepoDuplicateError"}}var REMOTE_EXTRA_UNSUPPORTED_CODE="REMOTE_EXTRA_UNSUPPORTED";class RemoteExtraUnsupportedError extends Error{repo;constructor(repo){super(`${REMOTE_EXTRA_UNSUPPORTED_CODE}: ${repo} is a remote project \u2014 a task spanning several repos must keep all of them local`);this.repo=repo;this.name="RemoteExtraUnsupportedError"}}class ExtraRepoNotGitError extends Error{repo;constructor(repo){super(`${NOT_A_GIT_REPO_CODE}: ${repo} is not a git repository \u2014 every repo of a task needs one to cut its worktree and branch from`);this.repo=repo;this.name="ExtraRepoNotGitError"}}var FORK_UNSUPPORTED_CODE="FORK_UNSUPPORTED";class ForkUnsupportedError extends Error{constructor(reason){super(`${FORK_UNSUPPORTED_CODE}: ${reason}`);this.name="ForkUnsupportedError"}}import fs from"fs";import path from"path";var WORKTREE_BASE_CUSTOM_KEY="worktree.basePath.custom",PROJECT_SIBLING_BASE=`${PROJECT_DIR_TOKEN}/..`;function worktreeBaseKindOf(raw){let trimmed=raw.trim();if(!trimmed)return"default";if(trimmed.replace(/\/+$/,"")===PROJECT_SIBLING_BASE)return"nextToProject";return"custom"}function getWorktreeBaseOverride(projectDir){let value=loadStateFile()[WORKTREE_BASE_KEY];return normalizeWorktreeBase(typeof value==="string"?value:null,projectDir)}function worktreeRootFor2(repo){return worktreeRootFor(repo,getWorktreeBaseOverride(repo))}function managedWorktreeRootsFor2(repo){return managedWorktreeRootsFor(repo,getWorktreeBaseOverride(repo))}function worktreePathFor(repo,slug){if(!slug||/[/\\\0]/.test(slug))throw Error(`worktreePathFor: invalid slug: ${JSON.stringify(slug)}`);return path.join(worktreeRootFor2(repo),slug)}async function listWorktreeDirNames(repo){if(isRemoteRepoKey(repo)){let basePath=getRemoteRepoConfig(repo)?.basePath;if(!basePath)return[];let names2=new Set,host=execHostForRepo(repo),entries=await Promise.all(remoteManagedWorktreeRootsFor(basePath).map((root)=>host.readdir(root)));for(let list of entries)for(let name of list)names2.add(name);return[...names2]}let names=new Set;for(let root of managedWorktreeRootsFor2(repo))try{for(let e of fs.readdirSync(root,{withFileTypes:!0}))if(e.isDirectory())names.add(e.name)}catch{}return[...names]}function managedWorktreeRootForPath(repo,candidate){if(!path.isAbsolute(repo)||!path.isAbsolute(candidate))return null;let target=canonicalize(candidate);for(let rootPath of managedWorktreeRootsFor2(repo)){let root=canonicalize(rootPath),rel=pathWithin(root,target);if(rel!==null&&rel!=="")return rootPath}return null}function isRoveManagedPath(repo,candidate){return managedWorktreeRootForPath(repo,candidate)!==null}function isUnderManagedWorktreesRoot(candidate,projectDir){if(!path.isAbsolute(candidate))return!1;let target=canonicalize(candidate),roots=[getWorktreeBaseOverride(projectDir)??"",defaultLocalWorktreesRoot(),legacyLocalWorktreesRoot()];for(let rootPath of roots){if(!rootPath)continue;let root=canonicalize(rootPath),rel=pathWithin(root,target);if(rel===null)continue;if(rel.split("/").filter(Boolean).length===2)return!0}return!1}function remoteWorktreeRootFor(basePath){return`${stripTrailingSlash(basePath)}/.rove/worktrees`}function remoteManagedWorktreeRootsFor(basePath){let base=stripTrailingSlash(basePath);return[`${base}/.rove/worktrees`,`${base}/.rove/worktrees`]}function remoteWorktreePathFor(basePath,slug){if(!slug||/[/\\\0]/.test(slug))throw Error(`remoteWorktreePathFor: invalid slug: ${JSON.stringify(slug)}`);return`${remoteWorktreeRootFor(basePath)}/${slug}`}function remoteManagedRootForPath(basePath,candidate){for(let root of remoteManagedWorktreeRootsFor(basePath))if(candidate===root||candidate.startsWith(`${root}/`))return root;return null}function stripTrailingSlash(p){return p.length>1&&p.endsWith("/")?p.replace(/\/+$/,""):p}function requireAbsolute(name,value){if(!value||!path.isAbsolute(value))throw Error(`${name} must be an absolute path, got: ${JSON.stringify(value)}`)}function canonicalize(p){try{return fs.realpathSync(p)}catch{return path.resolve(p)}}
3
3
  export{IllegalTransitionError,TaskNotFoundError,CannotDeleteMainTaskError,DIRTY_WORKTREE_CODE,describeDirtyWorktreeWork,dirtyRefusalReason,DirtyWorktreeError,WorktreeRemoveFailedError,TASK_DELETING_CODE,TaskDeletingError,MainCheckoutDirtyError,EmptyBranchError,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,EmptyBranchDirtyWorktreeError,MissingRefError,LandConflictError,GitCommandFailedError,WorktreeNameTakenError,InvalidWorktreeNameError,NotAGitRepoError,NotALinkedRepoError,REMOTE_PARENT_UNSUPPORTED_CODE,RemoteParentUnsupportedError,ReparentRefusedError,MoveRefusedError,TooManyReposError,RepoDuplicateError,RemoteExtraUnsupportedError,ExtraRepoNotGitError,FORK_UNSUPPORTED_CODE,ForkUnsupportedError,WORKTREE_BASE_CUSTOM_KEY,PROJECT_SIBLING_BASE,worktreeBaseKindOf,worktreePathFor,listWorktreeDirNames,managedWorktreeRootForPath,isRoveManagedPath,isUnderManagedWorktreesRoot,remoteWorktreePathFor,remoteManagedRootForPath,requireAbsolute,canonicalize};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{DAEMON_CHANNELS}from"./chunk-96kvwzj8.js";import{logClientError}from"./chunk-0g4wc808.js";import{samePath}from"./chunk-pn5ygqn6.js";import{preRenameRuntimePaths}from"./chunk-f8gg8cqh.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{connect}from"net";import{StringDecoder}from"string_decoder";function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"||status==="script_failed"}var ROUTINE_RESPONSE_MAX_CHARS=32000,ROUTINE_RESPONSE_WINDOW_MS=7200000;function routineRunResponseState(run,nowMs){if(run.response)return"responded";if(run.status!=="dispatched"&&run.status!=="revived")return null;if(run.deliveryStatus==="missing")return"missing";if(run.deliveryStatus==="awaiting")return"awaiting";return nowMs-Date.parse(run.at)>ROUTINE_RESPONSE_WINDOW_MS?"missing":"awaiting"}var GATE_QUESTION_MAX=500,GATE_CONTEXT_MAX=4000,GATE_OPTIONS_MAX=6;function gateInboxKey(gateId){return`\x00gate\x00${gateId}`}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","dead","routine_failed","report_missing","decision_needed"];function isRoutineInboxState(state){return state==="routine_failed"}function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(isRoutineInboxState(item.state)&&item.detail?.routine)return`\x00${item.state}\x00${item.detail.routine.automationId}`;if(item.state==="report_missing"&&item.detail?.delivery)return`\x00delivery\x00${item.detail.delivery.id}`;if(item.state==="decision_needed"&&item.detail?.gate)return gateInboxKey(item.detail.gate.id);return`${item.taskId}\x00${item.tabId??""}`}var DELIVERY_OUTCOMES=["done","partial","blocked","failed"],DELIVERY_SUMMARY_MAX_CHARS=32000,DELIVERY_EVIDENCE_MAX_ITEMS=50,DELIVERY_EVIDENCE_MAX_CHARS=2000,DELIVERY_NEXT_MAX_CHARS=4000,DELIVERY_PROMPT_HEAD_CHARS=200,MAX_DELIVERIES_PER_TASK=50,DELIVERY_STALL_MS=600000;function deliveryFooter(deliveryId,api){return`[ROVE] When this turn ends, report: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026]`}var SKIP_REASONS=["task-missing","awaiting-owner","report-missing","quota","engine-error","engine-dead","awaiting-permission","busy"],SHOULD_RUN_SKIP_EXIT_CODE=3;function parseSkipVerdict(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(raw.run!==!1||!SKIP_REASONS.includes(raw.reason))return;let text=(v)=>typeof v==="string"&&v.length>0?v:void 0;return{run:!1,reason:raw.reason,...text(raw.detail)?{detail:raw.detail}:{},...text(raw.until)?{until:raw.until}:{},...Array.isArray(raw.gateIds)?{gateIds:raw.gateIds.filter((g)=>typeof g==="string")}:{}}}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var DAEMON_PROTOCOL_VERSION=5,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;return!samePath(daemonHome,clientHome)}var BLOCKING_RPCS=new Set(["api.invoke","ui.prompt","task.land","workitem.start","automation.runNow","task.startScheduledNow","task.resumeQuota","pr.rerunFailedChecks","pr.reviewComments","task.ensureWorktree","task.spawn","task.ensureMain","task.moveToProject","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove","task.checkpoint","task.rewind","task.exportBranch"]),PTY_STOP_REFUSED="PtyStopRefused";function frameToLine(frame){return`${JSON.stringify(frame)}
2
+ import{DAEMON_CHANNELS}from"./chunk-96kvwzj8.js";import{logClientError}from"./chunk-0g4wc808.js";import{samePath}from"./chunk-pn5ygqn6.js";import{preRenameRuntimePaths}from"./chunk-f8gg8cqh.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{connect}from"net";import{StringDecoder}from"string_decoder";function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"||status==="script_failed"}var ROUTINE_RESPONSE_MAX_CHARS=32000,ROUTINE_RESPONSE_WINDOW_MS=7200000;function routineRunResponseState(run,nowMs){if(run.response)return"responded";if(run.status!=="dispatched"&&run.status!=="revived")return null;if(run.deliveryStatus==="quiet")return null;if(run.deliveryStatus==="missing")return"missing";if(run.deliveryStatus==="awaiting")return"awaiting";return nowMs-Date.parse(run.at)>ROUTINE_RESPONSE_WINDOW_MS?"missing":"awaiting"}var GATE_QUESTION_MAX=500,GATE_CONTEXT_MAX=4000,GATE_OPTIONS_MAX=6;function gateInboxKey(gateId){return`\x00gate\x00${gateId}`}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","dead","routine_failed","report_missing","decision_needed"];function isRoutineInboxState(state){return state==="routine_failed"}function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(isRoutineInboxState(item.state)&&item.detail?.routine)return`\x00${item.state}\x00${item.detail.routine.automationId}`;if(item.state==="report_missing"&&item.detail?.delivery)return`\x00delivery\x00${item.detail.delivery.id}`;if(item.state==="decision_needed"&&item.detail?.gate)return gateInboxKey(item.detail.gate.id);return`${item.taskId}\x00${item.tabId??""}`}var DELIVERY_OUTCOMES=["done","partial","blocked","failed"],DELIVERY_SUMMARY_MAX_CHARS=32000,DELIVERY_EVIDENCE_MAX_ITEMS=50,DELIVERY_EVIDENCE_MAX_CHARS=2000,DELIVERY_NEXT_MAX_CHARS=4000,DELIVERY_PROMPT_HEAD_CHARS=200,MAX_DELIVERIES_PER_TASK=50,DELIVERY_STALL_MS=600000;function deliveryFooter(deliveryId,api){return`[ROVE] When this turn ends, report: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026]`}var SKIP_REASONS=["task-missing","awaiting-owner","report-missing","quota","engine-error","engine-dead","awaiting-permission","busy"],SHOULD_RUN_SKIP_EXIT_CODE=3;function parseSkipVerdict(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(raw.run!==!1||!SKIP_REASONS.includes(raw.reason))return;let text=(v)=>typeof v==="string"&&v.length>0?v:void 0;return{run:!1,reason:raw.reason,...text(raw.detail)?{detail:raw.detail}:{},...text(raw.until)?{until:raw.until}:{},...Array.isArray(raw.gateIds)?{gateIds:raw.gateIds.filter((g)=>typeof g==="string")}:{}}}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var DAEMON_PROTOCOL_VERSION=5,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;return!samePath(daemonHome,clientHome)}var BLOCKING_RPCS=new Set(["api.invoke","ui.prompt","task.land","workitem.start","automation.runNow","task.startScheduledNow","task.resumeQuota","pr.rerunFailedChecks","pr.reviewComments","task.ensureWorktree","task.spawn","task.ensureMain","task.moveToProject","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove","task.checkpoint","task.rewind","task.exportBranch"]),PTY_STOP_REFUSED="PtyStopRefused";function frameToLine(frame){return`${JSON.stringify(frame)}
3
3
  `}class RpcTimeoutError extends Error{constructor(name,timeoutMs){super(`daemon rpc "${name}" timed out after ${timeoutMs}ms (daemon wedged?)`);this.name="RpcTimeoutError"}}function rpcTimeoutMs(){let raw=readRoveEnv("RPC_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 20000}class ConnectTimeoutError extends Error{constructor(socketPath,timeoutMs){super(`connecting to ${socketPath} timed out after ${timeoutMs}ms \u2014 nothing accepted the connection (daemon or PTY host not listening at that address)`);this.name="ConnectTimeoutError"}}function connectTimeoutMs(){let raw=readRoveEnv("CONNECT_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 5000}class RoveDaemonClient{socketPath;socket=null;buffer="";nextId=1;pending=new Map;handlers=new Map;lifecycleHandlers=new Map;connecting=null;disposed=!1;taskListInflight=null;constructor(socketPath){this.socketPath=socketPath}connect(){if(this.socket)return Promise.resolve();if(this.disposed)return Promise.reject(Error("daemon client disposed"));if(this.connecting)return this.connecting;let p=this.openSocketWithFallback();this.connecting=p;let cleanup=()=>{if(this.connecting===p)this.connecting=null};return p.then(cleanup,cleanup),p}get isDisposed(){return this.disposed}close(){this.disposed=!0,this.socket?.end(),this.socket=null,this.failPending()}forceDisconnect(){let socket=this.socket;if(!socket)return;this.socket=null,socket.destroy(),this.failPending()}failPending(){if(this.pending.size===0)return;let err=Error("daemon connection closed");for(let pending of this.pending.values()){if(pending.timer)clearTimeout(pending.timer);pending.reject(err)}this.pending.clear()}on(name,handler){let set=this.handlers.get(name);if(!set)set=new Set,this.handlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.handlers.delete(name)}}onChannel(channel,handler){return this.on(channel,(frame)=>handler(frame.payload))}subscribe(opts={}){let payload={};if(opts.channels)payload.channels=opts.channels;if(opts.role)payload.role=opts.role;if(opts.cellPixelSize)payload.cellPixelWidth=opts.cellPixelSize.width,payload.cellPixelHeight=opts.cellPixelSize.height;return this.request("subscribe",payload)}onLifecycle(name,handler){let set=this.lifecycleHandlers.get(name);if(!set)set=new Set,this.lifecycleHandlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.lifecycleHandlers.delete(name)}}request(name,payload){if(name!=="task.list")return this.taskListInflight=null,this.send(name,payload);if(!this.taskListInflight){let p=this.send(name,payload);this.taskListInflight=p;let clear=()=>{if(this.taskListInflight===p)this.taskListInflight=null};p.then(clear,clear)}return this.taskListInflight}async send(name,payload){await this.connect();let socket=this.socket;if(!socket)throw Error("daemon connection is not open");let id=String(this.nextId++),promise=new Promise((resolve,reject)=>{let entry={resolve:(value)=>resolve(value),reject},timeoutMs=rpcTimeoutMs();if(timeoutMs>0&&!BLOCKING_RPCS.has(name))entry.timer=setTimeout(()=>this.onRequestTimeout(id,name,timeoutMs),timeoutMs);this.pending.set(id,entry)});return socket.write(frameToLine({type:"request",id,name,payload})),promise}onRequestTimeout(id,name,timeoutMs){let pending=this.pending.get(id);if(!pending)return;this.pending.delete(id),pending.reject(new RpcTimeoutError(name,timeoutMs)),this.forceDisconnect(),this.emitLifecycle("close")}async openSocketWithFallback(){try{await this.openSocket(this.socketPath);return}catch(err){if(!(err instanceof Error)||!("code"in err)||!["ENOENT","ECONNREFUSED"].includes(String(err.code)))throw err;for(let path of preRenameRuntimePaths(this.socketPath)){if(this.disposed)throw err;try{await this.openSocket(path);return}catch{}}throw err}}openSocket(path){return new Promise((resolve,reject)=>{let socket=connect(path);this.socket=socket;let timeoutMs=connectTimeoutMs(),timer;if(timeoutMs>0)timer=setTimeout(()=>{if(socket.off("connect",onConnect),socket.off("error",onError),socket.destroy(),this.socket===socket)this.socket=null;reject(new ConnectTimeoutError(this.socketPath,timeoutMs))},timeoutMs);let onConnect=()=>{if(timer)clearTimeout(timer);socket.off("error",onError),socket.on("error",()=>socket.destroy()),resolve()},onError=(err)=>{if(timer)clearTimeout(timer);if(socket.off("connect",onConnect),this.socket===socket)this.socket=null;reject(err)};socket.once("connect",onConnect),socket.once("error",onError);let decoder=new StringDecoder("utf8");this.buffer="",socket.on("data",(chunk)=>this.onData(decoder.write(chunk))),socket.on("close",()=>this.onSocketClose(socket))})}onSocketClose(which){if(this.socket!==which)return;this.socket=null,this.failPending(),this.emitLifecycle("close")}emitLifecycle(name){for(let handler of this.lifecycleHandlers.get(name)??[])try{handler()}catch(err){console.error(`[rove] lifecycle handler for "${name}" threw:`,err)}}onData(chunk){this.buffer+=chunk;let nl=this.buffer.indexOf(`
4
4
  `);while(nl!==-1){let line=this.buffer.slice(0,nl);if(this.buffer=this.buffer.slice(nl+1),line.trim().length>0)this.onLine(line);nl=this.buffer.indexOf(`
5
5
  `)}}onLine(line){let frame;try{frame=JSON.parse(line)}catch(err){logClientError("client-frame",err);return}if(frame.type==="event"){this.emit(frame);return}if(frame.type!=="response")return;let pending=this.pending.get(frame.id);if(!pending)return;if(this.pending.delete(frame.id),pending.timer)clearTimeout(pending.timer);if(frame.error){let err=Error(frame.error.message);if(frame.error.name)err.name=frame.error.name;if(frame.error.data!==void 0)err.data=frame.error.data;pending.reject(err)}else pending.resolve(frame.payload)}emit(frame){for(let handler of this.handlers.get(frame.name)??[])try{handler(frame)}catch(err){logClientError("client-event",err)}for(let handler of this.handlers.get("*")??[])try{handler(frame)}catch(err){logClientError("client-event",err)}}}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{defaultFixRuntime}from"./chunk-vbyjsx29.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-5a6rkz1s.js";import"./chunk-bxg7y1qk.js";import"./chunk-afhnm3e4.js";import"./chunk-jadjn49m.js";import"./chunk-1gxnd3qq.js";import"./chunk-q89yrevw.js";import"./chunk-xdqj48wx.js";import"./chunk-cacct9gd.js";import"./chunk-pm91e38v.js";import"./chunk-2xsxcdp6.js";import"./chunk-17e2tgyg.js";import"./chunk-ee8917py.js";import"./chunk-q8ffd1pc.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-0sy3bez6.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-mejxvvzb.js";import{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-1masf4pj.js";import{addMachine,defaultMachineAlias,discoverMachine,duplicateAliasOf,getMachine,isValidMachineAlias,isWindowsMachine,learnedFrom,listMachines,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,remoteRove,removeMachine,sanitizeAlias,setMachineIdentity,sshServerIsWindows,sshTargetOf,updateMachine,windowsAuthorizeKeySteps}from"./chunk-pmwk2etg.js";import"./chunk-vp29jgbt.js";import"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import"./chunk-qkehg2c1.js";import"./chunk-x5swq8ar.js";import"./chunk-kd8j15cg.js";import"./chunk-gfdd2jbp.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-xj8bma5k.js";import"./chunk-ee5a0pka.js";import"./chunk-c69xdgfz.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-g9ba25q5.js";import"./chunk-paashxkd.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-mdc7b01e.js";import"./chunk-tn9gtf18.js";import"./chunk-22emnsn5.js";import"./chunk-sak1tphp.js";import{shQuote}from"./chunk-y1xnjx8x.js";import"./chunk-5mhf43dx.js";import"./chunk-ar3mt81z.js";import"./chunk-s7ttzm9a.js";import"./chunk-dce6ytw0.js";import"./chunk-q2r4qavc.js";import"./chunk-2tfnscxk.js";import"./chunk-jfbfasx0.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-8ttn73cv.js";import"./chunk-gygdyf0s.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-40dgv828.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION}from"./chunk-pzy7fe5e.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import{SUBCOMMAND_VERBS}from"./chunk-nbcm8d58.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import"./chunk-4wq1jsve.js";import"./chunk-af60qacx.js";import"./chunk-cmp64q4j.js";import"./chunk-8y10pmkf.js";import"./chunk-96kvwzj8.js";import"./chunk-ve2jj5qv.js";import"./chunk-ks5g5ee2.js";import"./chunk-7kysxgbq.js";import"./chunk-62z7016x.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import{homeDir}from"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{spawn}from"child_process";import{appendFileSync,chmodSync,existsSync,mkdirSync}from"fs";import{homedir}from"os";import{dirname}from"path";function parseSshG(stdout,home=homedir()){let values=new Map;for(let line of stdout.split(`
2
+ import{defaultFixRuntime}from"./chunk-vbyjsx29.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-rg38rkr1.js";import"./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{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-em75b155.js";import{addMachine,defaultMachineAlias,discoverMachine,duplicateAliasOf,getMachine,isValidMachineAlias,isWindowsMachine,learnedFrom,listMachines,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,remoteRove,removeMachine,sanitizeAlias,setMachineIdentity,sshServerIsWindows,sshTargetOf,updateMachine,windowsAuthorizeKeySteps}from"./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{CURRENT_VERSION}from"./chunk-bg2ypp04.js";import{SUBCOMMAND_VERBS}from"./chunk-nbcm8d58.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"./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{shQuote}from"./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{argvHasFlag}from"./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{loadStateFile}from"./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{homeDir}from"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{spawn}from"child_process";import{appendFileSync,chmodSync,existsSync,mkdirSync}from"fs";import{homedir}from"os";import{dirname}from"path";function parseSshG(stdout,home=homedir()){let values=new Map;for(let line of stdout.split(`
3
3
  `)){let space=line.indexOf(" ");if(space>0)values.set(line.slice(0,space).toLowerCase(),line.slice(space+1).trim())}let hostname=values.get("hostname")??"",port=Number(values.get("port")??"22")||22,files=(key)=>(values.get(key)??"").split(/\s+/).filter((f)=>f&&f!=="none").map((f)=>f.startsWith("~/")?`${home}${f.slice(1)}`:f),alias=values.get("hostkeyalias"),proxy=(key)=>{let v=values.get(key);return v!==void 0&&v!=="none"};return{knownHostsName:alias&&alias!=="none"?alias:port===22?hostname:`[${hostname}]:${port}`,hostname,port,userKnownHosts:files("userknownhostsfile"),globalKnownHosts:files("globalknownhostsfile"),proxied:proxy("proxyjump")||proxy("proxycommand")}}async function checkHostKey(config){let target=sshTargetOf(config),resolved=await run(["ssh","-G",...config.port?["-p",String(config.port)]:[],target]);if(resolved.code!==0)return{state:"skipped",reason:"ssh -G failed"};let destination=parseSshG(resolved.stdout);if(!destination.hostname)return{state:"skipped",reason:"ssh -G named no host"};if(destination.proxied)return{state:"skipped",reason:"reached through a proxy"};for(let file of[...destination.userKnownHosts,...destination.globalKnownHosts]){if(!existsSync(file))continue;if((await run(["ssh-keygen","-F",destination.knownHostsName,"-f",file])).code===0)return{state:"known"}}let keys=(await run(["ssh-keyscan","-T","5","-p",String(destination.port),destination.hostname])).stdout.split(`
4
4
  `).filter((line)=>line.trim()&&!line.startsWith("#"));if(keys.length===0)return{state:"skipped",reason:"the host offered no key"};let named=keys.map((line)=>line.replace(/^\S+/,destination.knownHostsName)),fingerprints=(await run(["ssh-keygen","-l","-f","-"],`${named.join(`
5
5
  `)}
@@ -39,12 +39,12 @@ ${MACHINE_USAGE}
39
39
  `),process.exit(1)}function flagValue(argv,name){for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg===void 0)continue;if(arg.startsWith(`--${name}=`))return arg.slice(name.length+3);if(arg!==`--${name}`)continue;let value=argv[i+1];if(value===void 0||value.startsWith("--"))usageError(`--${name} needs a value`);return value}return}async function runMachineSubcommand(argv){let[verb,...rest]=argv;if(!verb||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${MACHINE_USAGE}
40
40
  `);return}if(!SUBCOMMAND_VERBS.machine.includes(verb))usageError(`unknown verb "${verb}"`);if(verb==="list")return list();if(verb==="add")return await add(rest);if(verb==="doctor")return await doctor(rest);if(verb==="remove")return remove(rest);if(verb==="tunnel")return tunnel(rest);if(verb==="inbound")return inbound(rest);if(verb==="primary")return machinePrimary(rest,usageError);usageError(`unknown verb "${verb}"`)}async function add(argv){let target=positionalOf(argv);if(!target)usageError("add needs an ssh target, e.g. `machine add narwhal`");let parsed=parseSshTarget(target);if(!parsed)usageError(`"${target}" is not a valid ssh target ([user@]host[:port])`);let portFlag=flagValue(argv,"port"),port=portFlag?Number(portFlag):parsed.port;if(port!==void 0&&(!Number.isInteger(port)||port<1||port>65535))usageError("--port must be 1-65535");let identity=flagValue(argv,"identity"),requested=flagValue(argv,"alias");if(requested&&!isValidMachineAlias(requested))usageError(`--alias must be letters/digits/._- and cannot be "local" (got "${requested}")`);let probeAlias=requested??sanitizeAlias(parsed.host),config={host:parsed.host,...parsed.user?{user:parsed.user}:{},...port?{port}:{},auth:identity?{kind:"key",keyPath:identity}:{kind:"key"}};await confirmHostKey(config),process.stderr.write(`${CLI_NAME} machine: contacting ${sshTargetOf(config)}\u2026
41
41
  `);let established=await establishMachine(probeAlias,config,setupRuntime(argv));if(!established.ok)fail("nothing was saved");let{found,config:settled}=established,alias=requested??defaultMachineAlias({typedHost:parsed.host,typedUser:parsed.user,port,remoteHostname:found.status.hostname});if(!isValidMachineAlias(alias))fail(`could not derive a usable alias from "${found.status.hostname}" \u2014 pass --alias`);let identityTriple={hostname:found.status.hostname,homeDir:found.status.homeDir,daemonPid:found.status.daemonPid},duplicate=duplicateAliasOf(readMachines(loadStateFile()),alias,identityTriple),learned=learnedFrom(found),sockets=learned.sockets;if(found.roveBin)process.stderr.write(`${CLI_NAME} machine: rove is not on ${alias}'s non-interactive PATH; using ${found.roveBin}
42
- `);addMachine(alias,{...settled,...learned,identity:identityTriple}),setMachineIdentity(alias,identityTriple);let{ensureForwards}=await import("./chunk-s88gxrtj.js"),up=await ensureForwards({alias,config:{...settled,...learned},remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(process.stdout.write(`${CLI_NAME} machine: ${alias} \u2192 ${sshTargetOf(settled)} (rove ${found.status.roveVersion||"?"} on ${found.status.hostname||"?"})
42
+ `);addMachine(alias,{...settled,...learned,identity:identityTriple}),setMachineIdentity(alias,identityTriple);let{ensureForwards}=await import("./chunk-a9867184.js"),up=await ensureForwards({alias,config:{...settled,...learned},remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(process.stdout.write(`${CLI_NAME} machine: ${alias} \u2192 ${sshTargetOf(settled)} (rove ${found.status.roveVersion||"?"} on ${found.status.hostname||"?"})
43
43
  `),!up)process.stderr.write(`${CLI_NAME} machine: registered, but could not forward ${alias}'s socket yet \u2014 it will show as offline until the connection comes up
44
44
  `);if(duplicate)process.stdout.write(`${CLI_NAME} machine: ${alias} is the same machine as ${duplicate} (hostname/homeDir/pid match) \u2014 the sidebar shows one row
45
45
  `)}function setupRuntime(argv){let yes=argv.includes("--yes"),fixRuntime=defaultFixRuntime();return{confirm:fixRuntime.confirm,exec:fixRuntime.exec,out:(line)=>process.stderr.write(`${line}
46
46
  `),ask:!yes,planOnly:!yes&&process.stdin.isTTY!==!0}}async function doctor(argv){let alias=positionalOf(argv),entries=listMachines().filter((m)=>!alias||m.alias===alias);if(alias&&entries.length===0)fail(`no machine named "${alias}" (see \`${CLI_NAME} machine list\`)`);if(entries.length===0){process.stdout.write(`No machines registered. Add one with \`${CLI_NAME} machine add <ssh-target>\`.
47
- `);return}let rt=setupRuntime(argv),{ensureForwards}=await import("./chunk-s88gxrtj.js"),failed=0;for(let{alias:name,...config}of entries){process.stderr.write(`${CLI_NAME} machine: checking ${name} (${sshTargetOf(config)})\u2026
47
+ `);return}let rt=setupRuntime(argv),{ensureForwards}=await import("./chunk-a9867184.js"),failed=0;for(let{alias:name,...config}of entries){process.stderr.write(`${CLI_NAME} machine: checking ${name} (${sshTargetOf(config)})\u2026
48
48
  `);let established=await establishMachine(name,config,rt);if(!established.ok){failed++,process.stdout.write(`${name} \u2717 ${established.failure.code}
49
49
  `);continue}let{found}=established,learned=learnedFrom(found),sockets=learned.sockets,settled={...established.config,...learned};updateMachine(name,settled);let up=await ensureForwards({alias:name,config:settled,remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty}),version=found.status.roveVersion||"?",skew=version!==CURRENT_VERSION?` (this machine runs ${CURRENT_VERSION})`:"";process.stdout.write(`${name} ${up?"\u2713":"\u2717 socket not forwarded"} rove ${version}${skew} on ${found.status.hostname||"?"}
50
50
  `);for(let note of await doctorNotes(name,settled,found))process.stdout.write(` ${note}
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{failureHint}from"./chunk-9rsmxcd2.js";import{errorMessage}from"./chunk-2brn8e1y.js";import"./chunk-4wq1jsve.js";import"./chunk-af60qacx.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";function debugEnabled(env){return env.ROVE_DEBUG==="1"||env.ROVE_DEBUG==="1"}function failureSubject(cliName,argv){let verb=argv[2];return verb&&!verb.startsWith("-")&&!verb.includes("/")?`${cliName} ${verb}`:cliName}function summarizeCliGitError(message,cwd){if(!/not a git repository/i.test(message))return null;return`${cwd} is not a git repository \u2014 run this inside one, or pass a repo path.`}function formatCliFailure(err,opts){let subject=failureSubject(opts.cliName,opts.argv);if(debugEnabled(opts.env))return`${subject}: ${String(err instanceof Error?err.stack??err:err)}
2
+ import{failureHint}from"./chunk-9rsmxcd2.js";import"./chunk-4wq1jsve.js";import"./chunk-af60qacx.js";import"./chunk-cmp64q4j.js";import{errorMessage}from"./chunk-2brn8e1y.js";import"./chunk-91sykzqq.js";function debugEnabled(env){return env.ROVE_DEBUG==="1"||env.ROVE_DEBUG==="1"}function failureSubject(cliName,argv){let verb=argv[2];return verb&&!verb.startsWith("-")&&!verb.includes("/")?`${cliName} ${verb}`:cliName}function summarizeCliGitError(message,cwd){if(!/not a git repository/i.test(message))return null;return`${cwd} is not a git repository \u2014 run this inside one, or pass a repo path.`}function formatCliFailure(err,opts){let subject=failureSubject(opts.cliName,opts.argv);if(debugEnabled(opts.env))return`${subject}: ${String(err instanceof Error?err.stack??err:err)}
3
3
  ${failureHint(err,opts.cliName)}`;let raw=errorMessage(err),git=summarizeCliGitError(raw,opts.cwd);return`${subject}: ${git??`${raw}
4
4
  ${failureHint(err,opts.cliName)}`}`}export{summarizeCliGitError,formatCliFailure,failureSubject};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-yjeh02k3.js";import"./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"./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{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{findVerb}from"./chunk-bxg7y1qk.js";import{VERB_GROUP_IDS}from"./chunk-r5j8fycq.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
2
+ import{findVerb}from"./chunk-7vt1bf35.js";import{VERB_GROUP_IDS}from"./chunk-r5j8fycq.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
3
3
  export{INBOUND_KEY,INBOUND_CLASSES,inboundClassOf,deniedClasses,inboundRefusal,setInbound};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{recordSpawn}from"./chunk-40dgv828.js";import{projectRejection}from"./chunk-7mwvvj46.js";import{getPersistedBool,loadStateFile,patchStateFile,readSavedRepos,updateStateFile}from"./chunk-32j6y5d1.js";import{kvStatePath}from"./chunk-z1nj22va.js";import{pathIdentity,samePath}from"./chunk-pn5ygqn6.js";import{execFile,spawnSync}from"child_process";import{realpathSync}from"fs";import{promisify}from"util";function isRemoteRepoKey(key){return key.startsWith("ssh://")}function isRemoteProjectsEnabled(){return getPersistedBool("experimental.remoteProjects",!1)}function remoteRepoKey(host,user,port,basePath){let authority=port?`${user}@${host}:${port}`:`${user}@${host}`,base=(basePath??"").trim().replace(/\/+$/,"");if(!base)return`ssh://${authority}`;return`ssh://${authority}${base.startsWith("/")?base:`/${base}`}`}function readRemoteRepos(state){let raw=state.remoteRepos;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function getRemoteRepoConfig(key){return readRemoteRepos(loadStateFile())[key]??null}function getRemoteRepos(){return readRemoteRepos(loadStateFile())}function addRemoteRepo(config){let key=remoteRepoKey(config.host,config.user,config.port,config.basePath),added=!1;return updateStateFile((state)=>{let repos={...readRemoteRepos(state)},legacyKey=remoteRepoKey(config.host,config.user,config.port);if(key!==legacyKey&&repos[legacyKey]?.basePath===config.basePath)key=legacyKey;repos[key]=config,state.remoteRepos=repos;let saved=readSavedRepos(state);if(added=!saved.includes(key),added)state.savedRepos=[...saved,key];return}),{key,added}}var run=promisify(execFile);function resolveRepoRoot(absPath){if(isRemoteRepoKey(absPath))return absPath;recordSpawn("repos.resolveRepoRoot",["git","rev-parse","--show-toplevel"],absPath);let r=spawnSync("git",["rev-parse","--show-toplevel"],{cwd:absPath,encoding:"utf8",shell:!1});if(r.status!==0)return absPath;let top=(r.stdout??"").trim();if(!top)return absPath;try{if(realpathSync(absPath)===realpathSync(top))return absPath}catch{}return top}function isGitRepo(absPath){if(isRemoteRepoKey(absPath))return!1;recordSpawn("repos.isGitRepo",["git","rev-parse","--is-inside-work-tree"],absPath);let r=spawnSync("git",["rev-parse","--is-inside-work-tree"],{cwd:absPath,encoding:"utf8",shell:!1});return r.status===0&&(r.stdout??"").trim()==="true"}function isValidBranchName(branch){return spawnSync("git",["check-ref-format","--branch",branch],{encoding:"utf8",shell:!1}).status===0}function resolveMainRepoRoot(absPath){if(isRemoteRepoKey(absPath))return absPath;recordSpawn("repos.resolveMainRepoRoot",["git","worktree","list","--porcelain"],absPath);let r=spawnSync("git",["worktree","list","--porcelain"],{cwd:absPath,encoding:"utf8",shell:!1});if(r.status!==0)return resolveRepoRoot(absPath);return(r.stdout??"").split(/\r?\n/).find((line)=>line.startsWith("worktree "))?.slice(9).trim()||resolveRepoRoot(absPath)}async function inspectRepo(absPath){if(isRemoteRepoKey(absPath))return{root:absPath,usable:!0};recordSpawn("repos.inspectRepo",["git","worktree","list","--porcelain"],absPath);let stdout="",ok=!0;try{stdout=(await run("git",["worktree","list","--porcelain"],{cwd:absPath,encoding:"utf8"})).stdout}catch{ok=!1}let first=stdout.split(/\r?\n/).find((line)=>line.startsWith("worktree "))?.slice(9).trim(),usable=ok&&!/^bare$/m.test(stdout);return{root:usable&&first||absPath,usable}}function statePath(){return kvStatePath()}function getSavedRepos(){return readSavedRepos(loadStateFile())}function getPersistedString(key){let value=loadStateFile()[key];return typeof value==="string"?value:void 0}function getPersistedValue(key){return loadStateFile()[key]}function setPersistedString(key,value){patchStateFile({[key]:value})}function getCustomEngineIds(){let raw=loadStateFile().customEngineIds;if(!Array.isArray(raw))return[];return raw.filter((s)=>typeof s==="string"&&s.trim().length>0)}function getDisabledEngineIds(){let raw=loadStateFile().disabledEngineIds;if(!Array.isArray(raw))return[];return raw.filter((s)=>typeof s==="string"&&s.trim().length>0)}function addSavedRepo(absPath,opts={}){let normalized=resolveMainRepoRoot(absPath),rejected=opts.skipGate?null:projectRejection(normalized,isGitRepo,opts.intent??"explicit");if(rejected)return{added:!1,path:normalized,total:getSavedRepos().length,rejected};let result={added:!1,path:normalized,total:0};return updateStateFile((state)=>{let cur=readSavedRepos(state);if(cur.some((repo)=>samePath(repo,normalized)))return result={added:!1,path:normalized,total:cur.length},!1;state.savedRepos=[...cur,normalized],result={added:!0,path:normalized,total:cur.length+1};return}),result}function backfillSavedReposFromProjects(mainRepos){let added=[];for(let repo of mainRepos)if(addSavedRepo(repo,{intent:"explicit"}).added)added.push(repo);return added}function normalizeSavedRepos(){let cur=getSavedRepos(),seen=new Set,next=[],changed=!1;for(let p of cur){let top=resolveMainRepoRoot(p);if(top!==p)changed=!0;if(seen.has(pathIdentity(top))){changed=!0;continue}seen.add(pathIdentity(top)),next.push(top)}if(!changed)return;patchStateFile({savedRepos:next})}function readRepoConfigs(state){let raw=state.repoConfigs;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function samePathResolved(left,right){if(samePath(left,right))return!0;try{return realpathSync(left)===realpathSync(right)}catch{return!1}}function coerceOverride(entry){if(!entry||typeof entry!=="object")return{};let e=entry;return{initScript:typeof e.initScript==="string"&&e.initScript.length>0?e.initScript:void 0,initPrompt:typeof e.initPrompt==="string"&&e.initPrompt.length>0?e.initPrompt:void 0}}function getRepoInitOverride(repoRoot){let configs=readRepoConfigs(loadStateFile()),keys=Object.keys(configs);if(keys.length===0)return{};let direct=keys.find((key2)=>samePathResolved(key2,repoRoot));if(direct)return coerceOverride(configs[direct]);let normalized=resolveRepoRoot(repoRoot),key=keys.find((key2)=>samePathResolved(key2,normalized))??normalized;return coerceOverride(configs[key])}function setRepoInitOverride(repoRoot,patch){let resolved=resolveRepoRoot(repoRoot),next={};return updateStateFile((state)=>{let configs={...readRepoConfigs(state)},normalized=Object.keys(configs).find((key)=>samePathResolved(key,resolved))??resolved,cur=coerceOverride(configs[normalized]),nextScript=patch.initScript===void 0?cur.initScript:patch.initScript||void 0,nextPrompt=patch.initPrompt===void 0?cur.initPrompt:patch.initPrompt||void 0;if(next={...nextScript?{initScript:nextScript}:{},...nextPrompt?{initPrompt:nextPrompt}:{}},!next.initScript&&!next.initPrompt){let{[normalized]:_dropped,...rest}=configs;state.repoConfigs=rest}else configs[normalized]=next,state.repoConfigs=configs;return}),next}function removeSavedRepo(absPath){let result={removed:!1,path:absPath,total:0};return updateStateFile((state)=>{let cur=readSavedRepos(state);if(!cur.some((repo)=>samePath(repo,absPath)))return result={removed:!1,path:absPath,total:cur.length},!1;let remaining=cur.filter((p)=>!samePath(p,absPath));if(state.savedRepos=remaining,isRemoteRepoKey(absPath)){let remotes=readRemoteRepos(state);if(absPath in remotes){let next={...remotes};delete next[absPath],state.remoteRepos=next}}result={removed:!0,path:absPath,total:remaining.length};return}),result}
2
+ import{recordSpawn}from"./chunk-40dgv828.js";import{projectRejection}from"./chunk-rz8319pe.js";import{getPersistedBool,loadStateFile,patchStateFile,readSavedRepos,updateStateFile}from"./chunk-32j6y5d1.js";import{pathIdentity,samePath}from"./chunk-pn5ygqn6.js";import{kvStatePath}from"./chunk-z1nj22va.js";import{execFile,spawnSync}from"child_process";import{realpathSync}from"fs";import{promisify}from"util";function isRemoteRepoKey(key){return key.startsWith("ssh://")}function isRemoteProjectsEnabled(){return getPersistedBool("experimental.remoteProjects",!1)}function remoteRepoKey(host,user,port,basePath){let authority=port?`${user}@${host}:${port}`:`${user}@${host}`,base=(basePath??"").trim().replace(/\/+$/,"");if(!base)return`ssh://${authority}`;return`ssh://${authority}${base.startsWith("/")?base:`/${base}`}`}function readRemoteRepos(state){let raw=state.remoteRepos;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function getRemoteRepoConfig(key){return readRemoteRepos(loadStateFile())[key]??null}function getRemoteRepos(){return readRemoteRepos(loadStateFile())}function addRemoteRepo(config){let key=remoteRepoKey(config.host,config.user,config.port,config.basePath),added=!1;return updateStateFile((state)=>{let repos={...readRemoteRepos(state)},legacyKey=remoteRepoKey(config.host,config.user,config.port);if(key!==legacyKey&&repos[legacyKey]?.basePath===config.basePath)key=legacyKey;repos[key]=config,state.remoteRepos=repos;let saved=readSavedRepos(state);if(added=!saved.includes(key),added)state.savedRepos=[...saved,key];return}),{key,added}}var run=promisify(execFile);function resolveRepoRoot(absPath){if(isRemoteRepoKey(absPath))return absPath;recordSpawn("repos.resolveRepoRoot",["git","rev-parse","--show-toplevel"],absPath);let r=spawnSync("git",["rev-parse","--show-toplevel"],{cwd:absPath,encoding:"utf8",shell:!1});if(r.status!==0)return absPath;let top=(r.stdout??"").trim();if(!top)return absPath;try{if(realpathSync(absPath)===realpathSync(top))return absPath}catch{}return top}function isGitRepo(absPath){if(isRemoteRepoKey(absPath))return!1;recordSpawn("repos.isGitRepo",["git","rev-parse","--is-inside-work-tree"],absPath);let r=spawnSync("git",["rev-parse","--is-inside-work-tree"],{cwd:absPath,encoding:"utf8",shell:!1});return r.status===0&&(r.stdout??"").trim()==="true"}function isValidBranchName(branch){return spawnSync("git",["check-ref-format","--branch",branch],{encoding:"utf8",shell:!1}).status===0}function resolveMainRepoRoot(absPath){if(isRemoteRepoKey(absPath))return absPath;recordSpawn("repos.resolveMainRepoRoot",["git","worktree","list","--porcelain"],absPath);let r=spawnSync("git",["worktree","list","--porcelain"],{cwd:absPath,encoding:"utf8",shell:!1});if(r.status!==0)return resolveRepoRoot(absPath);return(r.stdout??"").split(/\r?\n/).find((line)=>line.startsWith("worktree "))?.slice(9).trim()||resolveRepoRoot(absPath)}async function inspectRepo(absPath){if(isRemoteRepoKey(absPath))return{root:absPath,usable:!0};recordSpawn("repos.inspectRepo",["git","worktree","list","--porcelain"],absPath);let stdout="",ok=!0;try{stdout=(await run("git",["worktree","list","--porcelain"],{cwd:absPath,encoding:"utf8"})).stdout}catch{ok=!1}let first=stdout.split(/\r?\n/).find((line)=>line.startsWith("worktree "))?.slice(9).trim(),usable=ok&&!/^bare$/m.test(stdout);return{root:usable&&first||absPath,usable}}function statePath(){return kvStatePath()}function getSavedRepos(){return readSavedRepos(loadStateFile())}function getPersistedString(key){let value=loadStateFile()[key];return typeof value==="string"?value:void 0}function getPersistedValue(key){return loadStateFile()[key]}function setPersistedString(key,value){patchStateFile({[key]:value})}function getCustomEngineIds(){let raw=loadStateFile().customEngineIds;if(!Array.isArray(raw))return[];return raw.filter((s)=>typeof s==="string"&&s.trim().length>0)}function getDisabledEngineIds(){let raw=loadStateFile().disabledEngineIds;if(!Array.isArray(raw))return[];return raw.filter((s)=>typeof s==="string"&&s.trim().length>0)}function addSavedRepo(absPath,opts={}){let normalized=resolveMainRepoRoot(absPath),rejected=opts.skipGate?null:projectRejection(normalized,isGitRepo,opts.intent??"explicit");if(rejected)return{added:!1,path:normalized,total:getSavedRepos().length,rejected};let result={added:!1,path:normalized,total:0};return updateStateFile((state)=>{let cur=readSavedRepos(state);if(cur.some((repo)=>samePath(repo,normalized)))return result={added:!1,path:normalized,total:cur.length},!1;state.savedRepos=[...cur,normalized],result={added:!0,path:normalized,total:cur.length+1};return}),result}function backfillSavedReposFromProjects(mainRepos){let added=[];for(let repo of mainRepos)if(addSavedRepo(repo,{intent:"explicit"}).added)added.push(repo);return added}function normalizeSavedRepos(){let cur=getSavedRepos(),seen=new Set,next=[],changed=!1;for(let p of cur){let top=resolveMainRepoRoot(p);if(top!==p)changed=!0;if(seen.has(pathIdentity(top))){changed=!0;continue}seen.add(pathIdentity(top)),next.push(top)}if(!changed)return;patchStateFile({savedRepos:next})}function readRepoConfigs(state){let raw=state.repoConfigs;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function samePathResolved(left,right){if(samePath(left,right))return!0;try{return realpathSync(left)===realpathSync(right)}catch{return!1}}function coerceOverride(entry){if(!entry||typeof entry!=="object")return{};let e=entry;return{initScript:typeof e.initScript==="string"&&e.initScript.length>0?e.initScript:void 0,initPrompt:typeof e.initPrompt==="string"&&e.initPrompt.length>0?e.initPrompt:void 0}}function getRepoInitOverride(repoRoot){let configs=readRepoConfigs(loadStateFile()),keys=Object.keys(configs);if(keys.length===0)return{};let direct=keys.find((key2)=>samePathResolved(key2,repoRoot));if(direct)return coerceOverride(configs[direct]);let normalized=resolveRepoRoot(repoRoot),key=keys.find((key2)=>samePathResolved(key2,normalized))??normalized;return coerceOverride(configs[key])}function setRepoInitOverride(repoRoot,patch){let resolved=resolveRepoRoot(repoRoot),next={};return updateStateFile((state)=>{let configs={...readRepoConfigs(state)},normalized=Object.keys(configs).find((key)=>samePathResolved(key,resolved))??resolved,cur=coerceOverride(configs[normalized]),nextScript=patch.initScript===void 0?cur.initScript:patch.initScript||void 0,nextPrompt=patch.initPrompt===void 0?cur.initPrompt:patch.initPrompt||void 0;if(next={...nextScript?{initScript:nextScript}:{},...nextPrompt?{initPrompt:nextPrompt}:{}},!next.initScript&&!next.initPrompt){let{[normalized]:_dropped,...rest}=configs;state.repoConfigs=rest}else configs[normalized]=next,state.repoConfigs=configs;return}),next}function removeSavedRepo(absPath){let result={removed:!1,path:absPath,total:0};return updateStateFile((state)=>{let cur=readSavedRepos(state);if(!cur.some((repo)=>samePath(repo,absPath)))return result={removed:!1,path:absPath,total:cur.length},!1;let remaining=cur.filter((p)=>!samePath(p,absPath));if(state.savedRepos=remaining,isRemoteRepoKey(absPath)){let remotes=readRemoteRepos(state);if(absPath in remotes){let next={...remotes};delete next[absPath],state.remoteRepos=next}}result={removed:!0,path:absPath,total:remaining.length};return}),result}
3
3
  export{isRemoteRepoKey,isRemoteProjectsEnabled,remoteRepoKey,getRemoteRepoConfig,getRemoteRepos,addRemoteRepo,resolveRepoRoot,isGitRepo,isValidBranchName,resolveMainRepoRoot,inspectRepo,statePath,getSavedRepos,getPersistedString,getPersistedValue,setPersistedString,getCustomEngineIds,getDisabledEngineIds,addSavedRepo,backfillSavedReposFromProjects,normalizeSavedRepos,getRepoInitOverride,setRepoInitOverride,removeSavedRepo};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{homeDir,legacyRoveStateDir,roveStateDir}from"./chunk-z1nj22va.js";import{pathSyntax,pathWithin}from"./chunk-pn5ygqn6.js";import{tmpdir}from"os";import{join}from"path";var THROWAWAY_SEGMENTS=new Set([".dev-sandbox",".scratch"]);function isRemoteKey(key){return key.startsWith("ssh://")}function isInside(candidate,root){return pathWithin(root,candidate)!==null}function roveInternalRoots(){return[roveStateDir(),legacyRoveStateDir(),join(homeDir(),".config","rove")]}function pathRejection(absPath,intent="derived"){let raw=absPath.trim();if(!raw)return"notAbsolute";if(isRemoteKey(raw))return null;let syntax=pathSyntax(raw);if(!syntax.isAbsolute(raw))return"notAbsolute";if(syntax.normalize(raw).split(syntax.sep).some((s)=>THROWAWAY_SEGMENTS.has(s)))return"insideSandbox";for(let root of roveInternalRoots())if(isInside(raw,root))return"roveInternal";if(intent==="derived"&&(isInside(raw,tmpdir())||isInside(raw,"/tmp")||isInside(raw,"/private/tmp")))return"temporary";return null}function projectRejection(absPath,isRepo,intent="derived"){let shape=pathRejection(absPath,intent);if(shape)return shape;let raw=absPath.trim();if(isRemoteKey(raw))return null;if(isRepo&&!isRepo(raw))return"notGitRepo";return null}function rejectionReason(rejection){switch(rejection){case"notAbsolute":return"not an absolute path";case"notGitRepo":return"not a git repository";case"temporary":return"inside a temporary directory";case"roveInternal":return"inside Rove's own state directory";case"insideSandbox":return"inside a sandbox or scratch directory"}}
2
+ import{pathSyntax,pathWithin}from"./chunk-pn5ygqn6.js";import{homeDir,legacyRoveStateDir,roveStateDir}from"./chunk-z1nj22va.js";import{tmpdir}from"os";import{join}from"path";var THROWAWAY_SEGMENTS=new Set([".dev-sandbox",".scratch"]);function isRemoteKey(key){return key.startsWith("ssh://")}function isInside(candidate,root){return pathWithin(root,candidate)!==null}function roveInternalRoots(){return[roveStateDir(),legacyRoveStateDir(),join(homeDir(),".config","rove")]}function pathRejection(absPath,intent="derived"){let raw=absPath.trim();if(!raw)return"notAbsolute";if(isRemoteKey(raw))return null;let syntax=pathSyntax(raw);if(!syntax.isAbsolute(raw))return"notAbsolute";if(syntax.normalize(raw).split(syntax.sep).some((s)=>THROWAWAY_SEGMENTS.has(s)))return"insideSandbox";for(let root of roveInternalRoots())if(isInside(raw,root))return"roveInternal";if(intent==="derived"&&(isInside(raw,tmpdir())||isInside(raw,"/tmp")||isInside(raw,"/private/tmp")))return"temporary";return null}function projectRejection(absPath,isRepo,intent="derived"){let shape=pathRejection(absPath,intent);if(shape)return shape;let raw=absPath.trim();if(isRemoteKey(raw))return null;if(isRepo&&!isRepo(raw))return"notGitRepo";return null}function rejectionReason(rejection){switch(rejection){case"notAbsolute":return"not an absolute path";case"notGitRepo":return"not a git repository";case"temporary":return"inside a temporary directory";case"roveInternal":return"inside Rove's own state directory";case"insideSandbox":return"inside a sandbox or scratch directory"}}
3
3
  export{pathRejection,projectRejection,rejectionReason};