@sma1lboy/rove 0.9.252 → 0.9.254

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 (186) hide show
  1. package/dist/cli/{chunk-r0etyq15.js → chunk-08ycv55d.js} +1 -1
  2. package/dist/cli/chunk-0g1me47p.js +2 -0
  3. package/dist/cli/{chunk-cvrtapqt.js → chunk-13msr643.js} +1 -1
  4. package/dist/cli/chunk-18dpws0y.js +2 -0
  5. package/dist/cli/{chunk-gaf6n1ea.js → chunk-1e6jbj70.js} +1 -1
  6. package/dist/cli/{chunk-07jq0271.js → chunk-1mpheecn.js} +1 -1
  7. package/dist/cli/{chunk-57wm48dh.js → chunk-1yzg4hzy.js} +1 -1
  8. package/dist/cli/{chunk-md094j05.js → chunk-278sc87n.js} +1 -1
  9. package/dist/cli/{chunk-q854fweb.js → chunk-3jnw3ftt.js} +1 -1
  10. package/dist/cli/chunk-3r8v2gza.js +2 -0
  11. package/dist/cli/{chunk-34468esa.js → chunk-4mxn5jg6.js} +1 -1
  12. package/dist/cli/{chunk-2ks86x2d.js → chunk-4myck788.js} +1 -1
  13. package/dist/cli/{chunk-sgegp9x9.js → chunk-4zhmbqt3.js} +1 -1
  14. package/dist/cli/chunk-5a6b4kv9.js +4 -0
  15. package/dist/cli/{chunk-5hhr44fc.js → chunk-5b7pd8j5.js} +1 -1
  16. package/dist/cli/chunk-5d0vb6v9.js +2 -0
  17. package/dist/cli/{chunk-9e21z4gn.js → chunk-5fhrns31.js} +1 -1
  18. package/dist/cli/{chunk-m3bz62v4.js → chunk-5j6z32fh.js} +1 -1
  19. package/dist/cli/chunk-5s4g1bkx.js +2 -0
  20. package/dist/cli/{chunk-q2fnt7gm.js → chunk-68gxqtse.js} +1 -1
  21. package/dist/cli/chunk-68pcd00x.js +2 -0
  22. package/dist/cli/chunk-6d5csfp4.js +2 -0
  23. package/dist/cli/{chunk-pgmv2hwf.js → chunk-6g5wvt5m.js} +2 -2
  24. package/dist/cli/{chunk-36pkmg07.js → chunk-6wxnkz3c.js} +10 -10
  25. package/dist/cli/{chunk-jn7vr075.js → chunk-6zvh002j.js} +1 -1
  26. package/dist/cli/{chunk-axmpjma9.js → chunk-7cd1epfw.js} +1 -1
  27. package/dist/cli/chunk-7ghwdjdc.js +3 -0
  28. package/dist/cli/chunk-7wga6bet.js +8 -0
  29. package/dist/cli/{chunk-jwnhthx9.js → chunk-7zpkyrxy.js} +1 -1
  30. package/dist/cli/{chunk-npb9xz3y.js → chunk-80zzjcvp.js} +1 -1
  31. package/dist/cli/{chunk-namxa4wy.js → chunk-8bd054vx.js} +1 -1
  32. package/dist/cli/{chunk-s5k3g5ra.js → chunk-9dendh71.js} +1 -1
  33. package/dist/cli/chunk-9g0vz9dk.js +209 -0
  34. package/dist/cli/chunk-9vd6fv1k.js +3 -0
  35. package/dist/cli/{chunk-tntdcyra.js → chunk-afwh7as3.js} +1 -1
  36. package/dist/cli/{chunk-9sta3ak4.js → chunk-ant4k6dm.js} +1 -1
  37. package/dist/cli/chunk-avz72132.js +3 -0
  38. package/dist/cli/chunk-ax7wzcam.js +2 -0
  39. package/dist/cli/{chunk-zk5qkkb1.js → chunk-axxf5dkq.js} +1 -1
  40. package/dist/cli/{chunk-a7kq09ke.js → chunk-b31cte10.js} +1 -1
  41. package/dist/cli/{chunk-fktvtdkb.js → chunk-bphs6am4.js} +1 -1
  42. package/dist/cli/chunk-cjxvb9vg.js +2 -0
  43. package/dist/cli/chunk-cm923k09.js +52 -0
  44. package/dist/cli/{chunk-6a4xqzqf.js → chunk-d48g9zzm.js} +3 -3
  45. package/dist/cli/{chunk-zzzm2cfx.js → chunk-d4mvprvq.js} +2 -2
  46. package/dist/cli/{chunk-952aedqm.js → chunk-ddc4t38t.js} +1 -1
  47. package/dist/cli/{chunk-resmnaxq.js → chunk-dehnv06q.js} +1 -1
  48. package/dist/cli/{chunk-y1cb8pj5.js → chunk-dqprpnd6.js} +1 -1
  49. package/dist/cli/chunk-dx72asyw.js +2 -0
  50. package/dist/cli/{chunk-e8pv3b92.js → chunk-e5vnptx5.js} +1 -1
  51. package/dist/cli/chunk-edsm15ht.js +4 -0
  52. package/dist/cli/{chunk-2rfyjb3y.js → chunk-ef7ckm5b.js} +1 -1
  53. package/dist/cli/{chunk-s2t9acrv.js → chunk-f6836h0n.js} +1 -1
  54. package/dist/cli/{chunk-s5a5dyab.js → chunk-fnsch8kr.js} +2 -2
  55. package/dist/cli/chunk-ft6ftksv.js +2 -0
  56. package/dist/cli/{chunk-trjve2xz.js → chunk-fwt0t2h7.js} +1 -1
  57. package/dist/cli/{chunk-ra40m849.js → chunk-gb3qb83h.js} +1 -1
  58. package/dist/cli/chunk-ghyz3fd7.js +4 -0
  59. package/dist/cli/chunk-gqpka00s.js +30 -0
  60. package/dist/cli/{chunk-4ays3krf.js → chunk-hqp8b49k.js} +2 -2
  61. package/dist/cli/{chunk-h3q3r1py.js → chunk-hzzq6pdb.js} +1 -1
  62. package/dist/cli/{chunk-x8pk5cyf.js → chunk-j19gkhzh.js} +1 -1
  63. package/dist/cli/{chunk-b67pjyyg.js → chunk-j26zqrnq.js} +1 -1
  64. package/dist/cli/{chunk-24dryfqb.js → chunk-j7831wcj.js} +1 -1
  65. package/dist/cli/{chunk-t3v57v42.js → chunk-j84zbw79.js} +2 -2
  66. package/dist/cli/chunk-j9c9tdfg.js +2 -0
  67. package/dist/cli/{chunk-zcadc92x.js → chunk-jetsx9zr.js} +1 -1
  68. package/dist/cli/{chunk-5q08srg6.js → chunk-jtpjdmb6.js} +1 -1
  69. package/dist/cli/chunk-jwtqe209.js +2 -0
  70. package/dist/cli/{chunk-w2sp489k.js → chunk-k3wzznqw.js} +1 -1
  71. package/dist/cli/chunk-k7ke95vy.js +5 -0
  72. package/dist/cli/chunk-k9ahks28.js +41 -0
  73. package/dist/cli/{chunk-nz9nmp4v.js → chunk-kwd59v51.js} +1 -1
  74. package/dist/cli/{chunk-j6t7xvm3.js → chunk-m0cbndc2.js} +1 -1
  75. package/dist/cli/{chunk-a7m7w6d1.js → chunk-m6qv5rsv.js} +1 -1
  76. package/dist/cli/{chunk-4e1wcgw7.js → chunk-mpdfhvgs.js} +3 -3
  77. package/dist/cli/chunk-mxkm0snt.js +2 -0
  78. package/dist/cli/chunk-n3wdy4z4.js +2 -0
  79. package/dist/cli/{chunk-tfqrc2v1.js → chunk-n5xj11ps.js} +3 -3
  80. package/dist/cli/{chunk-kda565xs.js → chunk-p5902z3e.js} +1 -1
  81. package/dist/cli/chunk-pahcf9td.js +3 -0
  82. package/dist/cli/{chunk-rc8baevh.js → chunk-pkq8n3gs.js} +2 -2
  83. package/dist/cli/{chunk-2bxts9pp.js → chunk-pvah9q79.js} +1 -1
  84. package/dist/cli/chunk-pyv2ywxr.js +3 -0
  85. package/dist/cli/chunk-qb6ktr8a.js +2 -0
  86. package/dist/cli/{chunk-mw0ysrpd.js → chunk-qk5f6p3e.js} +1 -1
  87. package/dist/cli/{chunk-rxge7bh5.js → chunk-qkd4eweb.js} +1 -1
  88. package/dist/cli/{chunk-h7y9v8k1.js → chunk-r4bn0mtb.js} +1 -1
  89. package/dist/cli/{chunk-ayhkcv0w.js → chunk-r7q7s63y.js} +2 -2
  90. package/dist/cli/{chunk-cbd6y9at.js → chunk-rf4z7b6g.js} +1 -1
  91. package/dist/cli/{chunk-25867jnk.js → chunk-rn97jntv.js} +1 -1
  92. package/dist/cli/{chunk-1tebqkdv.js → chunk-rnxk3587.js} +1 -1
  93. package/dist/cli/chunk-s96qnht3.js +2 -0
  94. package/dist/cli/chunk-sma961wh.js +3 -0
  95. package/dist/cli/{chunk-p2jeq98m.js → chunk-stcvcsfm.js} +1 -1
  96. package/dist/cli/{chunk-qh4y4e27.js → chunk-sxhjvr0w.js} +1 -1
  97. package/dist/cli/{chunk-0gxa04rx.js → chunk-sxt12set.js} +1 -1
  98. package/dist/cli/chunk-tbq3t259.js +2 -0
  99. package/dist/cli/{chunk-jp31bpgp.js → chunk-tewt7vre.js} +1 -1
  100. package/dist/cli/{chunk-1v8y9xtk.js → chunk-tmz0wzq8.js} +1 -1
  101. package/dist/cli/{chunk-zb5d61xa.js → chunk-tnft1xw4.js} +1 -1
  102. package/dist/cli/{chunk-032g0ahy.js → chunk-tq6pq1ws.js} +1 -1
  103. package/dist/cli/{chunk-x0rvg54z.js → chunk-v0jvt60f.js} +1 -1
  104. package/dist/cli/{chunk-qyfmfpjg.js → chunk-v7prawj1.js} +1 -1
  105. package/dist/cli/chunk-v8s0s21v.js +2 -0
  106. package/dist/cli/{chunk-t5qayy7m.js → chunk-v9dcyjmj.js} +1 -1
  107. package/dist/cli/chunk-v9fgdd90.js +3 -0
  108. package/dist/cli/chunk-vfwbgx85.js +2 -0
  109. package/dist/cli/{chunk-a1wjg2cv.js → chunk-vvw1njx5.js} +1 -1
  110. package/dist/cli/chunk-vzn94t0z.js +6 -0
  111. package/dist/cli/{chunk-vgknea9y.js → chunk-wbtebbrv.js} +1 -1
  112. package/dist/cli/{chunk-meyfwc50.js → chunk-wkk63qck.js} +1 -1
  113. package/dist/cli/chunk-wn2w5ar9.js +2 -0
  114. package/dist/cli/{chunk-2s762g8n.js → chunk-wsv6tw1b.js} +1 -1
  115. package/dist/cli/{chunk-2n1n70f2.js → chunk-x40h0f1w.js} +1 -1
  116. package/dist/cli/{chunk-0y4qgnby.js → chunk-x5ymh8ev.js} +1 -1
  117. package/dist/cli/{chunk-568q390y.js → chunk-x7r75e3p.js} +2 -2
  118. package/dist/cli/{chunk-7h7270rz.js → chunk-x7ryv67y.js} +2 -2
  119. package/dist/cli/{chunk-phpt1d3e.js → chunk-x951qvk5.js} +1 -1
  120. package/dist/cli/{chunk-ebhbtvhd.js → chunk-xdhs40fx.js} +1 -1
  121. package/dist/cli/chunk-xg6zg6kz.js +2 -0
  122. package/dist/cli/{chunk-21ek142k.js → chunk-xkr7fwvb.js} +1 -1
  123. package/dist/cli/{chunk-nqtvthqg.js → chunk-xpxxgzw9.js} +1 -1
  124. package/dist/cli/{chunk-7j00hbq5.js → chunk-y330t2bt.js} +2 -2
  125. package/dist/cli/{chunk-hq9tbzqa.js → chunk-y55zpren.js} +1 -1
  126. package/dist/cli/chunk-yebn33mf.js +2 -0
  127. package/dist/cli/chunk-ykdpg0zd.js +15 -0
  128. package/dist/cli/{chunk-qstjfseh.js → chunk-yshp8cmx.js} +1 -1
  129. package/dist/cli/chunk-z3zaa155.js +3 -0
  130. package/dist/cli/{chunk-npwzmmv9.js → chunk-z7zm8h1q.js} +2 -2
  131. package/dist/cli/index.js +8 -8
  132. package/dist/cli/pty-host-node.mjs +3 -0
  133. package/dist/cli/rove-run.js +1 -1
  134. package/dist/cli/rove.js +1 -1
  135. package/dist/completions/rove.bash +1 -1
  136. package/dist/completions/rove.fish +1 -1
  137. package/dist/completions/rove.zsh +1 -1
  138. package/dist/skills/rove/SKILL.md +61 -2
  139. package/dist/skills/rove/references/api-flags.md +75 -29
  140. package/dist/web/assets/{index-DHlgMx7L.js → index-BydepNFM.js} +3 -3
  141. package/dist/web/index.html +1 -1
  142. package/dist/web-ui/assets/{harness-BHiciz5A.js → harness-dYkQBfYz.js} +3 -3
  143. package/dist/web-ui/assets/{index-BkxJISAI.js → index-ByMdqeTv.js} +2 -2
  144. package/dist/web-ui/index.html +1 -1
  145. package/package.json +3 -3
  146. package/dist/cli/chunk-17pg88dq.js +0 -22
  147. package/dist/cli/chunk-1zwp3ase.js +0 -2
  148. package/dist/cli/chunk-2bp01vf2.js +0 -2
  149. package/dist/cli/chunk-2g2w5vvn.js +0 -2
  150. package/dist/cli/chunk-564jgrb3.js +0 -2
  151. package/dist/cli/chunk-5qxp7xx3.js +0 -2
  152. package/dist/cli/chunk-6f01fsje.js +0 -2
  153. package/dist/cli/chunk-7zxf47xb.js +0 -2
  154. package/dist/cli/chunk-8e0nmegv.js +0 -2
  155. package/dist/cli/chunk-9dregrj6.js +0 -5
  156. package/dist/cli/chunk-9h940gnr.js +0 -2
  157. package/dist/cli/chunk-9mcpqrx8.js +0 -2
  158. package/dist/cli/chunk-bhm24ne6.js +0 -9
  159. package/dist/cli/chunk-c0ksxg3z.js +0 -3
  160. package/dist/cli/chunk-cb1dg7nz.js +0 -2
  161. package/dist/cli/chunk-ccn7pq03.js +0 -5
  162. package/dist/cli/chunk-cpv1rpc7.js +0 -2
  163. package/dist/cli/chunk-csdttpme.js +0 -52
  164. package/dist/cli/chunk-fz0xfw86.js +0 -2
  165. package/dist/cli/chunk-h89ghyex.js +0 -2
  166. package/dist/cli/chunk-jnj2kk2h.js +0 -3
  167. package/dist/cli/chunk-kqv7t8jk.js +0 -8
  168. package/dist/cli/chunk-kx0wzjj4.js +0 -2
  169. package/dist/cli/chunk-m2t2n474.js +0 -6
  170. package/dist/cli/chunk-n2xemv4a.js +0 -2
  171. package/dist/cli/chunk-n92fz0hn.js +0 -2
  172. package/dist/cli/chunk-nj53wrzz.js +0 -2
  173. package/dist/cli/chunk-pdvyfz3n.js +0 -3
  174. package/dist/cli/chunk-pj3gnkfr.js +0 -3
  175. package/dist/cli/chunk-q3xt0mqt.js +0 -3
  176. package/dist/cli/chunk-qzsahxd9.js +0 -3
  177. package/dist/cli/chunk-r2c5nbcq.js +0 -4
  178. package/dist/cli/chunk-rf0jrh3q.js +0 -2
  179. package/dist/cli/chunk-rj7fwa30.js +0 -2
  180. package/dist/cli/chunk-sbn5pbz9.js +0 -2
  181. package/dist/cli/chunk-va0n5rwm.js +0 -39
  182. package/dist/cli/chunk-va5am5n6.js +0 -2
  183. package/dist/cli/chunk-vd8qqev9.js +0 -4
  184. package/dist/cli/chunk-vwpcv7j1.js +0 -4
  185. package/dist/cli/chunk-yknavm97.js +0 -3
  186. package/dist/cli/chunk-yt24rrvx.js +0 -2
@@ -0,0 +1,209 @@
1
+ // @bun
2
+ import{errorMessage}from"./chunk-2brn8e1y.js";import{JsonHookAdapter,ROVE_HOOK_VERSION,bobAuthSecretsPath,claudeGlobalConfigPath,codexAuthPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isRoveHook,kimiCredentialsPath,readTextFileSyncBounded,roveHookArgs,roveHookInvocation,updateSharedJson}from"./chunk-k7ke95vy.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{isObject}from"./chunk-7ghwdjdc.js";import{getCustomEngineIds,getDisabledEngineIds}from"./chunk-xkr7fwvb.js";import{__require}from"./chunk-91sykzqq.js";var GEMINI={rules:[{state:"blocked",any:["\u2502 apply this change","\u2502 allow execution","waiting for user confirmation"]},{state:"blocked",all:["do you want to proceed"],any:["yes"]},{state:"working",any:["esc to cancel"]}]},OPENCODE={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"]},{state:"working",any:["esc interrupt","esc to interrupt","ctrl+c to interrupt","esc again to interrupt"]},{state:"idle",any:["enter send"]}]},CURSOR={rules:[{state:"blocked",any:["press any key to log in"]},{state:"blocked",all:["proceed (y)"]},{state:"blocked",any:["run this command?","waiting for approval","skip (esc or n)","(y) (enter)"]},{state:"working",any:["esc to cancel","ctrl+c to stop"]}]},GROK={rules:[{state:"blocked",any:["\u26A0 action required","ctrl+o:yolo"]},{state:"blocked",all:["\u2503"],lineRegex:["^\\s*\u2503\\s+\\S+\\s+\\(\u25CB\\)"]},{state:"working",any:["[stop]"],lineRegex:["^\\s*[\\u2800-\\u28FF]"]}]},DROID={rules:[{state:"blocked",all:["enter to select","esc to cancel"],any:["> yes, allow","> no, cancel"]},{state:"blocked",all:["enter select","esc cancel"]},{state:"working",any:["esc to stop"]}]},AMP={rules:[{state:"blocked",any:["waiting for approval","run this command?","allow editing file:","allow creating file:","confirm tool call"]},{state:"working",lineRegex:["^\\s*\u2570\\s+\\S+\\s+(thinking|streaming|running tools|waiting)\\s+\u2500"]}]},CLINE={rules:[{state:"blocked",any:["let cline use this tool"]},{state:"blocked",all:["execute command?","yes"],any:["[act mode]","[plan mode]"]},{state:"blocked",all:["use this tool?","yes"],any:["[act mode]","[plan mode]"]}]},KIRO={rules:[{state:"blocked",all:["requires approval"],any:["yes, single permission","trust, always allow","no (tab to edit)","esc to close"]},{state:"blocked",all:["pending from subagents","tool approval"],any:["approve all pending","configure individually","exit (cancel subagents)"]},{state:"working",any:["kiro is working"]},{state:"working",all:["esc to cancel"],lineRegex:["^\\s*[\u25D4\u25D1\u25D5\u25CF]\\s+[A-Za-z]"]}]},MAKI={rules:[{state:"blocked",all:["permission required","y allow","n deny"]},{state:"blocked",all:["permission required"],any:["confirm allow","confirm deny"]},{state:"blocked",all:["permission required","enter deny","esc cancel"]},{state:"blocked",all:["plan complete","enter confirm"],any:["space toggle parallel","edit plan"]},{state:"working",bottomLines:1,lineRegex:["^( [\\u2800-\\u28FF]){1,2} \\[(BUILD|PLAN|BASH)\\]"]},{state:"idle",bottomLines:1,lineRegex:["^ \\[(BUILD|PLAN|BASH)\\]"]}]},ANTIGRAVITY={rules:[{state:"blocked",all:["requesting permission for:","do you want to proceed?"]},{state:"blocked",all:["requesting permission for:","tab amend","edit command"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]+\\s+[A-Za-z]+\\w*ing\\b"]},{state:"working",bottomLines:5,lineRegex:["\xB7\\s*[1-9][0-9]*\\s+task"]}]},DEVIN={rules:[{state:"blocked",bottomLines:8,all:["do you trust the authors of this directory?","yes, trust "]},{state:"blocked",bottomLines:8,all:["approve once","select","confirm","esc cancel"]},{state:"working",bottomLines:8,all:["running tools","esc to interrupt"]},{state:"working",bottomLines:6,all:["guide devin while it works"]},{state:"working",bottomLines:8,all:["reading shell ","timeout:"]},{state:"idle",bottomLines:8,all:["ask devin to build","features, fix bugs","your code"],lineRegex:["^\\s*\u276D Ask Devin to build"]},{state:"idle",bottomLines:6,all:["context:"],lineRegex:["^\\s*\u276D"]}]},QODERCLI={rules:[{state:"blocked",all:["waiting for user confirmation"],any:["yes","no","allow","reject"]},{state:"blocked",all:["awaiting approval"],any:["allow","reject"]},{state:"blocked",any:["permission required","allow once or always?","asking user","enter your response","review your answers:","shell awaiting input"]},{state:"working",any:["(esc to cancel,"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]\\s+.*[A-Za-z]"]}]},HERMES={rules:[{state:"blocked",bottomLines:14,any:["dangerous","approval","allow once","hermes needs your","type your answer","approve once","start a new session","keep going"],lineRegex:["enter\\s+(?:to\\s+)?(?:confirm|send)","press enter","\u2191/\u2193\\s+(?:to\\s+)?select","show full command","type 1/2/3","y/n quick","other \\(type"]},{state:"blocked",bottomLines:14,any:["sudo password","skill setup"]},{state:"blocked",bottomLines:14,all:["\uD83D\uDD11","for "]},{state:"working",bottomLines:5,any:["msg=interrupt","ctrl+c to interrupt","ctrl+c cancel"]}]},KILO={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"],lineRegex:["\u2191\u2193\\s*select","\u21C6\\s*tab"]},{state:"working",any:["esc interrupt"]}]},MASTRACODE={rules:[]};import{existsSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";function parseFlatHooks(raw){if(raw===void 0)return{ok:!0,doc:{}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{ok:!1,reason:`not valid JSON (${err instanceof Error?err.message:String(err)})`}}if(!isObject(parsed))return{ok:!1,reason:"top level is not a JSON object"};if(parsed.hooks===void 0)return{ok:!0,doc:parsed};if(!isObject(parsed.hooks))return{ok:!1,reason:'"hooks" is not an object'};for(let[event,entries]of Object.entries(parsed.hooks))if(!Array.isArray(entries))return{ok:!1,reason:`"hooks.${event}" is not an array`};return{ok:!0,doc:parsed}}function mergeFlatHooks(format,current,install,inv=roveHookInvocation()){let verbs=format.eventMap.map((spec)=>spec.verb),{hooks:rawHooks,...rest}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},quoting=hookCommandQuoting();for(let{event,verb}of format.eventMap){let kept=(Array.isArray(hooks[event])?hooks[event]:[]).filter((entry)=>!isRoveHook(entry,verbs));if(install){let command=quoteShellArgv([...inv,"hook",verb,...roveHookArgs(format.vendor)],quoting);kept.push(format.withType?{type:"command",command}:{command})}if(kept.length>0)hooks[event]=kept;else delete hooks[event]}return{version:1,...rest,hooks}}var CURSOR_HOOK_EVENT_MAP=[{event:"sessionStart",verb:"session-start"}],CURSOR_FORMAT={vendor:"cursor",eventMap:CURSOR_HOOK_EVENT_MAP};function cursorHooksPath(home=homedir()){let override=process.env.CURSOR_CONFIG_DIR?.trim();return join(override||join(home,".cursor"),"hooks.json")}function parseCursorHooks(raw){return parseFlatHooks(raw)}function mergeCursorHooks(current,install,inv=roveHookInvocation()){return mergeFlatHooks(CURSOR_FORMAT,current,install,inv)}class CursorHookAdapter{vendor="cursor";supportsHooks(){return!0}globalSettingsPath(){return cursorHooksPath()}activityDetailFromPayload(){return}cwdFromPayload(payload){let roots=payload.workspace_roots;return Array.isArray(roots)?firstString(...roots):void 0}sessionFromPayload(payload){let sessionId=firstString(payload.session_id,payload.conversation_id);if(!sessionId)return;let transcriptPath=firstString(payload.transcript_path);return{sessionId,...transcriptPath?{transcriptPath}:{}}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync(dirname(settingsFilePath)))return{ok:!0};let outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!0),parseCursorHooks);if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] cursor: skipped ${outcome.file}: ${outcome.reason}
3
+ `);return outcome}async removeActivityHooks(settingsFilePath){if(!existsSync(settingsFilePath))return;await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!1),parseCursorHooks)}hookConfigRefusal(raw){let parsed=parseCursorHooks(raw);return parsed.ok?void 0:parsed.reason}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}function firstString(...values){for(let value of values)if(typeof value==="string"&&value)return value;return}import{homedir as homedir2}from"os";import{join as join2}from"path";import{existsSync as existsSync2}from"fs";import{dirname as dirname2}from"path";function sessionStartOnly(matcher){return[{event:"SessionStart",verb:"session-start",...matcher?{matcher}:{}}]}class SessionStartHookAdapter extends JsonHookAdapter{installGuardDir(settingsFilePath){return dirname2(settingsFilePath)}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync2(this.installGuardDir(settingsFilePath)))return{ok:!0};return super.installActivityHooks(settingsFilePath,opts)}async removeActivityHooks(settingsFilePath){if(!existsSync2(settingsFilePath))return;await super.removeActivityHooks(settingsFilePath)}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}}var DEVIN_HOOK_EVENT_MAP=sessionStartOnly();function devinSettingsPath(home=homedir2()){let xdg=process.env.XDG_CONFIG_HOME?.trim();return join2(xdg||join2(home,".config"),"devin","config.json")}class DevinHookAdapter extends SessionStartHookAdapter{vendor="devin";eventMap=DEVIN_HOOK_EVENT_MAP;globalSettingsPath(){return devinSettingsPath()}}import{homedir as homedir3}from"os";import{join as join3}from"path";var DROID_HOOK_EVENT_MAP=sessionStartOnly();function droidSettingsPath(home=homedir3()){return join3(home,".factory","settings.json")}class DroidHookAdapter extends SessionStartHookAdapter{vendor="droid";eventMap=DROID_HOOK_EVENT_MAP;globalSettingsPath(){return droidSettingsPath()}}import{homedir as homedir4}from"os";import{dirname as dirname3,join as join4}from"path";var GROK_HOOK_EVENT_MAP=sessionStartOnly();function grokConfigDir(home=homedir4()){return process.env.GROK_HOME?.trim()||join4(home,".grok")}function grokHooksPath(home=homedir4()){return join4(grokConfigDir(home),"hooks","rove.json")}class GrokHookAdapter extends SessionStartHookAdapter{vendor="grok";eventMap=GROK_HOOK_EVENT_MAP;globalSettingsPath(){return grokHooksPath()}installGuardDir(settingsFilePath){return dirname3(dirname3(settingsFilePath))}sessionFromPayload(payload){let sessionId=firstString2(payload.session_id,payload.sessionId);if(!sessionId)return;let transcriptPath=firstString2(payload.transcript_path,payload.transcriptPath);return{sessionId,...transcriptPath?{transcriptPath}:{}}}}function firstString2(...values){for(let value of values)if(typeof value==="string"&&value)return value;return}import{existsSync as existsSync3}from"fs";import{mkdir,readFile,rm,writeFile}from"fs/promises";import{homedir as homedir5}from"os";import path from"path";var HERMES_PLUGIN_NAME="rove-agent-state";function indentOf(line){if(!line.trim()||line.trim().startsWith("#"))return;let match=/^ */.exec(line),indent=match?match[0].length:0;return line[indent]==="\t"?void 0:indent}function keyAt(line,indent){if(indentOf(line)!==indent)return;return/^ *(["']?)([A-Za-z0-9_.-]+)\1:(?:\s|$)/.exec(line)?.[2]}function inlineValue(line){return(/^ *(["']?)[A-Za-z0-9_.-]+\1:(.*)$/.exec(line)?.[2]??"").trim()}function listItemAt(line,indent){if(indentOf(line)!==indent)return;let match=/^ *- *(.*)$/.exec(line);if(!match)return;return match[1].trim().replace(/^["']|["']$/g,"")}function join5(lines,trailingNewline){return lines.join(`
4
+ `)+(trailingNewline?`
5
+ `:"")}function setHermesPluginEnabled(content,enabled){let trailingNewline=content.endsWith(`
6
+ `)||content==="",lines=content.length>0?content.replace(/\n$/,"").split(`
7
+ `):[],pluginsIndex=lines.findIndex((line)=>keyAt(line,0)==="plugins");if(pluginsIndex<0){if(!enabled)return{ok:!0,content};let head=content.replace(/\n+$/,""),block=`plugins:
8
+ enabled:
9
+ - rove-agent-state
10
+ `;return{ok:!0,content:head?`${head}
11
+ ${block}`:block}}if(inlineValue(lines[pluginsIndex]??"")!=="")return{ok:!1,reason:'"plugins" is written inline; Rove only edits a block mapping'};let pluginsEnd=lines.length;for(let i=pluginsIndex+1;i<lines.length;i++)if(indentOf(lines[i]??"")===0){pluginsEnd=i;break}let enabledIndex=lines.slice(pluginsIndex+1,pluginsEnd).findIndex((line)=>keyAt(line,2)==="enabled");if(enabledIndex<0)return{ok:!1,reason:'"plugins" has no "enabled" key that Rove can add to'};let enabledAt=pluginsIndex+1+enabledIndex,enabledValue=inlineValue(lines[enabledAt]??"");if(enabledValue==="[]"){if(!enabled)return{ok:!0,content};let next2=[...lines];return next2.splice(enabledAt,1," enabled:"," - rove-agent-state"),{ok:!0,content:join5(next2,trailingNewline)}}if(enabledValue!=="")return{ok:!1,reason:'"plugins.enabled" is written inline; Rove only edits a block list'};let listEnd=pluginsEnd;for(let i=enabledAt+1;i<pluginsEnd;i++){let line=lines[i]??"",indent=indentOf(line);if(indent!==void 0&&indent<=2&&listItemAt(line,indent)===void 0){listEnd=i;break}}let itemIndent=(()=>{for(let i=enabledAt+1;i<listEnd;i++){let indent=indentOf(lines[i]??"");if(indent!==void 0&&listItemAt(lines[i]??"",indent)!==void 0)return indent}return 4})(),existing=-1;for(let i=enabledAt+1;i<listEnd;i++)if(listItemAt(lines[i]??"",itemIndent)==="rove-agent-state"){existing=i;break}if(enabled){if(existing>=0)return{ok:!0,content};let next2=[...lines];return next2.splice(enabledAt+1,0,`${" ".repeat(itemIndent)}- rove-agent-state`),{ok:!0,content:join5(next2,trailingNewline)}}if(existing<0)return{ok:!0,content};let next=[...lines];return next.splice(existing,1),{ok:!0,content:join5(next,trailingNewline)}}var HERMES_PLUGIN_MANIFEST=`name: rove-agent-state
12
+ version: "1.0"
13
+ description: Report Hermes Agent session identity to Rove
14
+ `;function renderHermesPluginSource(opts){let{vendor,invocation}=opts;return`"""Rove activity hook \u2014 GENERATED, installed and rewritten by Rove on every
15
+ launch (${vendor}). Local edits are overwritten; to stop reporting, delete this
16
+ directory or turn Rove's global hooks off.
17
+
18
+ ROVE_HOOK_VERSION=${ROVE_HOOK_VERSION}
19
+
20
+ It subscribes to ${vendor}'s session hooks and shells out to
21
+ \`${invocation.join(" ")} hook session-start --engine ${vendor}\`. Best-effort by
22
+ construction: the report is fire-and-forget and every failure is swallowed \u2014 a
23
+ badge must never break a turn.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import os
30
+ import subprocess
31
+
32
+ _ENGINE = ${JSON.stringify(vendor)}
33
+ _INVOCATION = ${JSON.stringify(invocation)}
34
+ _HOOK_VERSION = ${JSON.stringify(String(ROVE_HOOK_VERSION))}
35
+
36
+ # Hermes fires these hooks for batch and API entry points too; only a session
37
+ # with a terminal behind it is the one Rove's pane is about.
38
+ _INTERACTIVE_PLATFORMS = {"cli", "tui", "desktop", "acp"}
39
+
40
+
41
+ def _emit(session_id: str) -> None:
42
+ payload = {"session_id": session_id, "cwd": os.getcwd()}
43
+ argv = list(_INVOCATION) + [
44
+ "hook",
45
+ "session-start",
46
+ "--engine",
47
+ _ENGINE,
48
+ "--hook-version",
49
+ _HOOK_VERSION,
50
+ "--payload",
51
+ json.dumps(payload),
52
+ ]
53
+ try:
54
+ subprocess.Popen(
55
+ argv,
56
+ stdin=subprocess.DEVNULL,
57
+ stdout=subprocess.DEVNULL,
58
+ stderr=subprocess.DEVNULL,
59
+ )
60
+ except Exception:
61
+ pass
62
+
63
+
64
+ def _report(**kwargs) -> None:
65
+ if kwargs.get("platform") not in _INTERACTIVE_PLATFORMS:
66
+ return
67
+ session_id = kwargs.get("session_id")
68
+ if not isinstance(session_id, str) or not session_id:
69
+ return
70
+ _emit(session_id)
71
+
72
+
73
+ def register(ctx):
74
+ # Only the two session edges. Hermes also exposes \`pre_llm_call\`, which
75
+ # would re-report the same identity once per model request \u2014 a process
76
+ # spawn per call to say what session start already said.
77
+ ctx.register_hook("on_session_start", _report)
78
+ ctx.register_hook("on_session_reset", _report)
79
+ `}function hermesConfigDir(home=homedir5()){return path.join(home,".hermes")}function hermesConfigPath(home=homedir5()){return path.join(hermesConfigDir(home),"config.yaml")}class HermesHookAdapter{vendor="hermes";supportsHooks(){return!0}globalSettingsPath(){return hermesConfigPath()}activityDetailFromPayload(){return}sessionFromPayload(payload){let sessionId=typeof payload.session_id==="string"?payload.session_id:void 0;return sessionId?{sessionId}:void 0}async installActivityHooks(settingsFilePath,opts={}){let configDir=path.dirname(settingsFilePath);if(!existsSync3(configDir))return{ok:!0};let pluginDir=path.join(configDir,"plugins",HERMES_PLUGIN_NAME);await writeIfChanged(path.join(pluginDir,"plugin.yaml"),HERMES_PLUGIN_MANIFEST),await writeIfChanged(path.join(pluginDir,"__init__.py"),renderHermesPluginSource({vendor:this.vendor,invocation:roveHookInvocation()}));let outcome=await this.editConfig(settingsFilePath,!0);if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] hermes: skipped ${outcome.file}: ${outcome.reason}
80
+ `);return outcome}async removeActivityHooks(settingsFilePath){if(existsSync3(settingsFilePath))await this.editConfig(settingsFilePath,!1);try{await rm(path.join(path.dirname(settingsFilePath),"plugins",HERMES_PLUGIN_NAME),{recursive:!0,force:!0})}catch{}}hookConfigRefusal(raw){let edit=setHermesPluginEnabled(raw,!0);return edit.ok?void 0:edit.reason}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}async editConfig(file,enabled){let rejected;try{await updateSharedJson(file,(raw)=>({raw:raw??""}),(doc)=>{let raw=String(doc.raw??""),edit=setHermesPluginEnabled(raw,enabled);if(!edit.ok){rejected=edit.reason;return}return edit.content===raw?void 0:edit.content})}catch(err){return{ok:!1,file,reason:err instanceof Error?err.message:String(err)}}if(rejected!==void 0)return{ok:!1,file,reason:rejected};return{ok:!0}}}async function writeIfChanged(file,content){try{if(await readFile(file,"utf8").catch(()=>{return})===content)return;await mkdir(path.dirname(file),{recursive:!0}),await writeFile(file,content)}catch{}}import{existsSync as existsSync4}from"fs";import{homedir as homedir6}from"os";import{dirname as dirname4,join as join6}from"path";var MASTRACODE_HOOK_EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"AgentStart",verb:"turn-start"},{event:"PermissionRequest",verb:"awaiting-input"},{event:"PermissionResult",verb:"turn-start"},{event:"Interrupt",verb:"turn-interrupted"},{event:"AgentEnd",verb:"turn-complete"},{event:"Stop",verb:"turn-complete"}],MASTRACODE_FORMAT={vendor:"mastracode",eventMap:MASTRACODE_HOOK_EVENT_MAP,withType:!0};function mastracodeHooksPath(home=homedir6()){return join6(home,".mastracode","hooks.json")}function mergeMastracodeHooks(current,install,inv=roveHookInvocation()){return mergeFlatHooks(MASTRACODE_FORMAT,current,install,inv)}class MastracodeHookAdapter{vendor="mastracode";supportsHooks(){return!0}globalSettingsPath(){return mastracodeHooksPath()}activityDetailFromPayload(kind){return kind==="awaiting-input"?{waiting:"permission"}:void 0}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync4(dirname4(settingsFilePath)))return{ok:!0};let outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeMastracodeHooks(cur,!0),parseMastracodeHooks);if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] mastracode: skipped ${outcome.file}: ${outcome.reason}
81
+ `);return outcome}async removeActivityHooks(settingsFilePath){if(!existsSync4(settingsFilePath))return;await editJsonSettings(settingsFilePath,(cur)=>mergeMastracodeHooks(cur,!1),parseMastracodeHooks)}hookConfigRefusal(raw){let parsed=parseMastracodeHooks(raw);return parsed.ok?void 0:parsed.reason}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}function parseMastracodeHooks(raw){return parseFlatHooks(raw)}import{existsSync as existsSync5}from"fs";import{mkdir as mkdir2,readFile as readFile2,rm as rm2,writeFile as writeFile2}from"fs/promises";import{homedir as homedir7}from"os";import path2 from"path";function renderOpencodePluginSource(opts){let{vendor,invocation}=opts;return`/**
82
+ * Rove activity hook \u2014 GENERATED, installed and rewritten by Rove on every
83
+ * launch (${vendor}). Local edits are overwritten; to stop reporting, delete
84
+ * this file or turn Rove's global hooks off. Add your own plugins beside it.
85
+ *
86
+ * ROVE_HOOK_VERSION=${ROVE_HOOK_VERSION}
87
+ *
88
+ * It subscribes to ${vendor}'s session lifecycle and shells out to
89
+ * \`${invocation.join(" ")} hook <verb> --engine ${vendor}\`. Best-effort by
90
+ * construction: every report is fire-and-forget and every failure is
91
+ * swallowed \u2014 a badge must never break a turn.
92
+ */
93
+
94
+ import { spawn } from "node:child_process"
95
+
96
+ const ENGINE = ${JSON.stringify(vendor)}
97
+ const INVOCATION = ${JSON.stringify(invocation)}
98
+ const HOOK_VERSION = ${JSON.stringify(String(ROVE_HOOK_VERSION))}
99
+
100
+ /** A running turn, by whichever name this build of the CLI reports. */
101
+ const WORKING_STATUS = new Set(["active", "busy", "pending", "retry", "running", "streaming", "working"])
102
+
103
+ function text(value) {
104
+ return typeof value === "string" && value.length > 0 ? value : undefined
105
+ }
106
+
107
+ /**
108
+ * Sub-agent sessions. Their lifecycle edges must not replace the pane's root
109
+ * session id, and their completions must not light the "turn done" lamp while
110
+ * the user's own turn is still running.
111
+ */
112
+ const childSessions = new Set()
113
+
114
+ /** A child session's events that still say something about the ROOT turn:
115
+ * a nested agent blocked on a human blocks the whole task. */
116
+ const CHILD_VERBS = new Map([
117
+ ["permission.asked", "awaiting-input"],
118
+ ["question.asked", "awaiting-input"],
119
+ ["permission.replied", "turn-start"],
120
+ ["question.replied", "turn-start"],
121
+ ["question.rejected", "turn-start"],
122
+ ])
123
+
124
+ function emit(cwd, verb, sessionID, extra) {
125
+ try {
126
+ const payload = Object.assign({}, extra)
127
+ if (cwd) payload.cwd = cwd
128
+ if (sessionID) payload.session_id = sessionID
129
+ const args = INVOCATION.slice(1).concat([
130
+ "hook",
131
+ verb,
132
+ "--engine",
133
+ ENGINE,
134
+ "--hook-version",
135
+ HOOK_VERSION,
136
+ "--payload",
137
+ JSON.stringify(payload),
138
+ ])
139
+ const child = spawn(INVOCATION[0], args, { stdio: "ignore", detached: false })
140
+ child.on("error", () => {})
141
+ } catch {
142
+ /* never let observability break the engine */
143
+ }
144
+ }
145
+
146
+ export const RoveAgentState = async (input) => {
147
+ const cwd = text(input && input.directory) || text(input && input.worktree)
148
+
149
+ return {
150
+ "chat.message": async ({ sessionID }) => {
151
+ if (sessionID && childSessions.has(sessionID)) return
152
+ emit(cwd, "turn-start", sessionID)
153
+ },
154
+ event: async ({ event }) => {
155
+ const type = event && event.type
156
+ const properties = (event && event.properties) || {}
157
+ const info = properties.info
158
+ // session.created carries the new Session as \`info\`, not a \`sessionID\`.
159
+ const sessionID = text(properties.sessionID) || (type === "session.created" ? text(info && info.id) : undefined)
160
+
161
+ if (info && info.id && info.parentID) childSessions.add(info.id)
162
+ if (sessionID && childSessions.has(sessionID)) {
163
+ const verb = CHILD_VERBS.get(type)
164
+ // No session id: a sub-agent's identity must never become the pane's.
165
+ if (verb) emit(cwd, verb, undefined)
166
+ return
167
+ }
168
+
169
+ switch (type) {
170
+ case "session.created":
171
+ if (sessionID) emit(cwd, "session-start", sessionID)
172
+ break
173
+ case "session.status": {
174
+ const status = properties.status
175
+ const kind = typeof status === "string" ? status : status && status.type
176
+ const lowered = typeof kind === "string" ? kind.toLowerCase() : undefined
177
+ if (lowered === "idle") emit(cwd, "turn-complete", sessionID)
178
+ else if (lowered && WORKING_STATUS.has(lowered)) emit(cwd, "turn-start", sessionID)
179
+ break
180
+ }
181
+ case "permission.replied":
182
+ case "question.replied":
183
+ case "question.rejected":
184
+ emit(cwd, "turn-start", sessionID)
185
+ break
186
+ case "permission.asked":
187
+ emit(cwd, "awaiting-input", sessionID, { waiting: "permission" })
188
+ break
189
+ case "question.asked":
190
+ emit(cwd, "awaiting-input", sessionID, { waiting: "input" })
191
+ break
192
+ case "session.error":
193
+ emit(cwd, "turn-failed", sessionID, { error_message: text(properties.error?.data?.message) || text(properties.error?.name) })
194
+ break
195
+ case "session.idle":
196
+ emit(cwd, "turn-complete", sessionID)
197
+ break
198
+ case "session.compacted":
199
+ emit(cwd, "post-compact", sessionID)
200
+ break
201
+ default:
202
+ break
203
+ }
204
+ },
205
+ }
206
+ }
207
+ `}var ACTIVITY_PLUGIN_FILE="rove-agent-state.js",FAMILY_DIRS={opencode:{configDir:"opencode",pluginDir:"plugins"},kilo:{configDir:"kilo",pluginDir:"plugin"}};function opencodeFamilyConfigDir(vendor,home=homedir7()){return path2.join(home,".config",FAMILY_DIRS[vendor].configDir)}function opencodeFamilyPluginPath(vendor,home=homedir7()){return path2.join(opencodeFamilyConfigDir(vendor,home),FAMILY_DIRS[vendor].pluginDir,ACTIVITY_PLUGIN_FILE)}function opencodeFailureDetail(payload){let raw=typeof payload.error_message==="string"?payload.error_message:"",message=raw.toLowerCase(),note=raw?raw.slice(0,200):void 0;return{failure:(()=>{if(/insufficient|credit|billing|payment required|\b402\b|quota exceeded|out of credits/.test(message))return"billing";if(/rate.?limit|too many requests|\b429\b|overloaded|capacity/.test(message))return"rate_limit";return"other"})(),...note?{note}:{}}}class OpencodeFamilyHookAdapter{family;vendor;constructor(family){this.family=family;this.vendor=family}supportsHooks(){return!0}globalSettingsPath(){return opencodeFamilyPluginPath(this.family)}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return opencodeFailureDetail(payload);if(kind==="awaiting-input")return{waiting:payload.waiting==="input"?"input":"permission"};return}sessionFromPayload(payload){let sessionId=typeof payload.session_id==="string"?payload.session_id:void 0;return sessionId?{sessionId}:void 0}async installActivityHooks(settingsFilePath){let configDir=path2.dirname(path2.dirname(settingsFilePath));if(!existsSync5(configDir))return{ok:!0};let source=renderOpencodePluginSource({vendor:this.family,invocation:roveHookInvocation()});return await writeIfChanged2(settingsFilePath,source),{ok:!0}}async removeActivityHooks(settingsFilePath){try{await rm2(settingsFilePath,{force:!0})}catch{}}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}async function writeIfChanged2(file,content){try{if(await readFile2(file,"utf8").catch(()=>{return})===content)return;await mkdir2(path2.dirname(file),{recursive:!0}),await writeFile2(file,content)}catch{}}import{homedir as homedir8}from"os";import{join as join7}from"path";var QODERCLI_HOOK_EVENT_MAP=sessionStartOnly("*");function qodercliSettingsPath(home=homedir8()){let override=process.env.QODERCLI_CONFIG_DIR?.trim();return join7(override||join7(home,".qoder"),"settings.json")}class QodercliHookAdapter extends SessionStartHookAdapter{vendor="qodercli";eventMap=QODERCLI_HOOK_EVENT_MAP;globalSettingsPath(){return qodercliSettingsPath()}}var pluginEngines=new Map;function registerPluginEngine(id,spec){if(Object.hasOwn(CONTRIB_ENGINES,id))return!1;return pluginEngines.set(id,spec),!0}function clearPluginEngines(){pluginEngines.clear()}function pluginEngineIds(){return[...pluginEngines.keys()]}var CONTRIB_ENGINES={gemini:{displayName:"Gemini CLI",defaultCommand:["gemini"],screenManifest:GEMINI},opencode:{displayName:"OpenCode",defaultCommand:["opencode"],screenManifest:OPENCODE,firstMessageDelivery:"paste",createHookAdapter:()=>new OpencodeFamilyHookAdapter("opencode")},cursor:{displayName:"Cursor Agent",defaultCommand:["cursor-agent"],screenManifest:CURSOR,createHookAdapter:()=>new CursorHookAdapter},grok:{displayName:"Grok CLI",defaultCommand:["grok"],screenManifest:GROK,createHookAdapter:()=>new GrokHookAdapter},droid:{displayName:"Droid",defaultCommand:["droid"],screenManifest:DROID,createHookAdapter:()=>new DroidHookAdapter},amp:{displayName:"Amp",defaultCommand:["amp"],screenManifest:AMP},devin:{displayName:"Devin",defaultCommand:["devin"],processNames:["devin-cli"],screenManifest:DEVIN,createHookAdapter:()=>new DevinHookAdapter},qodercli:{displayName:"Qoder CLI",defaultCommand:["qodercli"],processNames:["qoder","qoderclicn","qodercn"],screenManifest:QODERCLI,createHookAdapter:()=>new QodercliHookAdapter},cline:{displayName:"Cline",defaultCommand:["cline"],screenManifest:CLINE},kiro:{displayName:"Kiro CLI",defaultCommand:["kiro-cli"],processNames:["kiro"],screenManifest:KIRO},maki:{displayName:"Maki",defaultCommand:["maki"],screenManifest:MAKI},antigravity:{displayName:"Antigravity",defaultCommand:["agy"],processNames:["antigravity","antigravity-cli"],screenManifest:ANTIGRAVITY},hermes:{displayName:"Hermes Agent",defaultCommand:["hermes"],processNames:["hermes-agent"],screenManifest:HERMES,createHookAdapter:()=>new HermesHookAdapter},kilo:{displayName:"Kilo",defaultCommand:["kilo"],processNames:["kilo-code"],screenManifest:KILO,firstMessageDelivery:"paste",createHookAdapter:()=>new OpencodeFamilyHookAdapter("kilo")},mastracode:{displayName:"MastraCode",defaultCommand:["mastracode"],processNames:["mastra-code"],screenManifest:MASTRACODE,createHookAdapter:()=>new MastracodeHookAdapter}};function isContribEngine(id){return Object.hasOwn(CONTRIB_ENGINES,id)||pluginEngines.has(id)}var CONTRIB_ENGINE_IDS=Object.keys(CONTRIB_ENGINES);function contribEngineEntry(id,base){let spec=CONTRIB_ENGINES[id]??pluginEngines.get(id);if(!spec)return base;return{...base,displayName:spec.displayName,defaultCommand:spec.defaultCommand,...spec.processNames?{processNames:spec.processNames}:{},screenManifest:spec.screenManifest,...spec.identity?{identity:spec.identity}:{},...spec.firstMessageDelivery?{firstMessageDelivery:spec.firstMessageDelivery}:{},...spec.createHookAdapter?{createHookAdapter:spec.createHookAdapter}:{}}}import{homedir as homedir10}from"os";import{spawnSync}from"child_process";import{existsSync as existsSync6,statSync}from"fs";import{homedir as homedir9}from"os";import path3 from"path";var defaultBinaryDeps={fileExists(p){try{return statSync(p).isFile()}catch{return!1}},env(name){return process.env[name]},home(){return homedir9()},which(name){let cmd=process.platform==="win32"?"where":"which",out=spawnSync(cmd,[name],{encoding:"utf8"});if(out.status!==0)return;let first=out.stdout.split(`
208
+ `).map((l)=>l.trim()).filter(Boolean)[0];if(!first)return;if(first.startsWith(`${name}:`)&&first.includes("aliased to")){let aliasTarget=first.split("aliased to")[1]?.trim();return aliasTarget&&existsSync6(aliasTarget)?aliasTarget:void 0}return first},readdir(p){try{return __require("fs").readdirSync(p)}catch{return[]}}};class BinaryNotFoundError extends Error{checkedPaths;constructor(label,hint,checkedPaths){super(`${label} not found. Checked: ${checkedPaths.join(", ")}. ${hint}`);this.name="BinaryNotFoundError",this.checkedPaths=checkedPaths}}function npmStyleDirs({deps,home},locations=["system","nvm","windowsNpm","npmGlobal","local","bun","bin"]){return locations.flatMap((location)=>{switch(location){case"system":return["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"];case"homebrew":return["/opt/homebrew/bin","/usr/local/bin"];case"nvm":{let bin=deps.env("NVM_BIN");return bin?[bin]:[]}case"windowsNpm":{if((deps.platform?.()??process.platform)!=="win32")return[];let appData=deps.env("APPDATA"),localAppData=deps.env("LOCALAPPDATA");return[...localAppData?[path3.join(localAppData,"npm")]:[],...appData?[path3.join(appData,"npm")]:[],path3.join(home,"AppData/Roaming/npm")]}case"npmGlobal":return[path3.join(home,".npm-global/bin")];case"local":return[path3.join(home,".local/bin")];case"yarn":return[path3.join(home,".yarn/bin")];case"bun":return[path3.join(home,".bun/bin")];case"bin":return[path3.join(home,"bin")]}})}function npmStyleBinaryCandidates(ctx,name){let names=(ctx.deps.platform?.()??process.platform)==="win32"?[`${name}.exe`,`${name}.cmd`,name]:[name];return npmStyleDirs(ctx).flatMap((dir)=>names.map((n)=>path3.join(dir,n)))}function createBinaryFinder(spec){return async function(deps=defaultBinaryDeps){let checked=[],whichResult=deps.which(spec.name);if(whichResult){if(checked.push(`which:${whichResult}`),deps.fileExists(whichResult))return whichResult}for(let candidate of spec.candidates({deps,home:deps.home()}))if(checked.push(candidate),deps.fileExists(candidate))return candidate;throw spec.notFound(checked)}}class BobBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("IBM Bob Shell binary","Ensure 'bob' is on PATH (for example `curl -fsSL https://bob.ibm.com/download/bobshell.sh | bash`).",checkedPaths);this.name="BobBinaryNotFoundError"}}var findBobBinary=createBinaryFinder({name:"bob",candidates:(ctx)=>npmStyleBinaryCandidates(ctx,"bob"),notFound:(checked)=>new BobBinaryNotFoundError(checked)});import path4 from"path";class ClaudeBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Claude Code binary","Ensure 'claude' is on PATH, or install at ~/.claude/local/claude.",checkedPaths);this.name="ClaudeBinaryNotFoundError"}}var findClaudeBinary=createBinaryFinder({name:"claude",candidates({deps,home}){let out=[path4.join(home,".claude","local","claude")];out.push(...npmStyleDirs({deps,home},["nvm"]).map((dir)=>path4.join(dir,"claude")));let nvmRoot=path4.join(home,".nvm","versions","node"),versions=(deps.readdir?.(nvmRoot)??[]).sort((a,b)=>b.localeCompare(a,void 0,{numeric:!0}));for(let v of versions)out.push(path4.join(nvmRoot,v,"bin","claude"));return out.push(...npmStyleDirs({deps,home},["system","local","npmGlobal","yarn","bun","bin"]).map((dir)=>path4.join(dir,"claude"))),out},notFound:(checked)=>new ClaudeBinaryNotFoundError(checked)});import path5 from"path";class CodexBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Codex CLI binary","Ensure 'codex' is on PATH (e.g. `brew install codex` or the official installer).",checkedPaths);this.name="CodexBinaryNotFoundError"}}var findCodexBinary=createBinaryFinder({name:"codex",candidates({deps,home}){return npmStyleDirs({deps,home},["system","nvm","local","bun","bin"]).map((dir)=>path5.join(dir,"codex"))},notFound:(checked)=>new CodexBinaryNotFoundError(checked)});class CopilotBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("GitHub Copilot CLI binary","Ensure 'copilot' is on PATH (for example `npm install -g @github/copilot` or `brew install copilot-cli`).",checkedPaths);this.name="CopilotBinaryNotFoundError"}}var findCopilotBinary=createBinaryFinder({name:"copilot",candidates:(ctx)=>npmStyleBinaryCandidates(ctx,"copilot"),notFound:(checked)=>new CopilotBinaryNotFoundError(checked)});import path6 from"path";class KimiBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Kimi Code CLI binary","Ensure 'kimi' is on PATH or installed at ~/.kimi-code/bin/kimi.",checkedPaths);this.name="KimiBinaryNotFoundError"}}var findKimiBinary=createBinaryFinder({name:"kimi",candidates:(ctx)=>[path6.join(ctx.home,".kimi-code/bin"),...npmStyleDirs(ctx,["local","bin","homebrew"])].map((dir)=>path6.join(dir,"kimi")),notFound:(checked)=>new KimiBinaryNotFoundError(checked)});import path7 from"path";class PiFamilyBinaryNotFoundError extends BinaryNotFoundError{constructor(name,checkedPaths){super(`${name} CLI binary`,`Ensure '${name}' is on PATH (e.g. \`brew install ${name}\`, or \`npm i -g ${name==="omp"?"@oh-my-pi/pi-coding-agent":"@earendil-works/pi-coding-agent"}\`).`,checkedPaths);this.name="PiFamilyBinaryNotFoundError"}}function candidatesFor(name,ctx){let{home}=ctx,out=npmStyleDirs(ctx,["system","local","bun","bin"]).map((dir)=>path7.join(dir,name)),packageName=name==="omp"?"@oh-my-pi/pi-coding-agent":"@earendil-works/pi-coding-agent";for(let prefix of[path7.join(home,".npm-global"),"/usr/local","/opt/homebrew"])out.push(path7.join(prefix,"bin",name)),out.push(path7.join(prefix,"lib/node_modules",packageName,"dist","cli.js"));return out}var findPiBinary=createBinaryFinder({name:"pi",candidates:(ctx)=>candidatesFor("pi",ctx),notFound:(checked)=>new PiFamilyBinaryNotFoundError("pi",checked)}),findOmpBinary=createBinaryFinder({name:"omp",candidates:(ctx)=>candidatesFor("omp",ctx),notFound:(checked)=>new PiFamilyBinaryNotFoundError("omp",checked)});var defaultDeps={readFile(p){return readTextFileSyncBounded(p)},env(name){return process.env[name]},home(){return homedir10()},findClaudeBinary(){return findClaudeBinary()},findCodexBinary(){return findCodexBinary()},findBobBinary(){return findBobBinary()},findCopilotBinary(){return findCopilotBinary()},findKimiBinary(){return findKimiBinary()},findPiBinary(){return findPiBinary()},findOmpBinary(){return findOmpBinary()}};function decodeJwtPayload(jwt){let parts=jwt.split(".");if(parts.length!==3)return null;let payload=parts[1];if(!payload)return null;let b64=payload.replace(/-/g,"+").replace(/_/g,"/"),padded=b64+"=".repeat((4-b64.length%4)%4);try{let json=Buffer.from(padded,"base64").toString("utf8"),obj=JSON.parse(json);return typeof obj==="object"&&obj!==null?obj:null}catch{return null}}async function probeBinary(probe){try{return{found:!0,path:await probe()}}catch(err){if(err instanceof BinaryNotFoundError)return{found:!1,error:"not found on PATH"};return{found:!1,error:errorMessage(err)}}}var cachedDefaultVendors=null;async function probeAvailableVendors(deps){return(await Promise.all([["claude",()=>deps.findClaudeBinary()],["codex",()=>deps.findCodexBinary()],["copilot",()=>deps.findCopilotBinary()],["kimi",()=>deps.findKimiBinary()],["pi",()=>deps.findPiBinary()],["omp",()=>deps.findOmpBinary()]].map(async([vendor,probe])=>(await probeBinary(probe)).found?vendor:null))).filter((v)=>v!==null)}function detectAvailableVendors(deps=defaultDeps){if(deps!==defaultDeps)return probeAvailableVendors(deps);if(cachedDefaultVendors)return cachedDefaultVendors;let pending=probeAvailableVendors(deps).catch((err)=>{throw cachedDefaultVendors=null,err});return cachedDefaultVendors=pending,pending}function resetAvailableVendorsCache(){cachedDefaultVendors=null,cachedContribEngines=null}async function installedEngineIds(deps=defaultDeps){let builtins=await detectAvailableVendors(deps),contrib=await detectContribEngines();return[...new Set([...builtins,...getCustomEngineIds(),...contrib])]}async function availableEngineIds(deps=defaultDeps){let disabled=new Set(getDisabledEngineIds());return(await installedEngineIds(deps)).filter((id)=>!disabled.has(id))}var cachedContribEngines=null;function detectContribEngines(){if(cachedContribEngines)return cachedContribEngines;let which=globalThis.Bun?.which;return cachedContribEngines=Promise.resolve([...which?CONTRIB_ENGINE_IDS.filter((id)=>{let bin=CONTRIB_ENGINES[id]?.defaultCommand[0];return bin?which(bin)!==null:!1}):[],...pluginEngineIds()]),cachedContribEngines}async function detectClaudeAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findClaudeBinary()),configPath=claudeGlobalConfigPath(deps.env,deps.home()),raw;try{raw=deps.readFile(configPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${configPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${configPath}: ${errorMessage(err)}`}}let oauth=parsed?.oauthAccount;if(!oauth||typeof oauth!=="object")return{binary,account:{kind:"none"}};let o=oauth,email=typeof o.emailAddress==="string"?o.emailAddress:void 0;if(!email)return{binary,account:{kind:"none"}};return{binary,account:{kind:"oauth",email,organization:typeof o.organizationName==="string"?o.organizationName:void 0,displayName:typeof o.displayName==="string"?o.displayName:void 0,billingType:typeof o.billingType==="string"?o.billingType:void 0}}}async function detectCodexAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findCodexBinary()),authPath=codexAuthPath(deps.env,deps.home()),raw;try{raw=deps.readFile(authPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${authPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${authPath}: ${errorMessage(err)}`}}let obj=parsed??{},tokens=obj.tokens,idToken=typeof tokens?.id_token==="string"?tokens.id_token:void 0;if(idToken){let payload=decodeJwtPayload(idToken);if(!payload)return{binary,account:{kind:"none"},accountError:"codex id_token: malformed JWT"};let email=typeof payload.email==="string"?payload.email:void 0,authClaimRaw=payload["https://api.openai.com/auth"],authClaim=isObject(authClaimRaw)?authClaimRaw:void 0,plan=typeof authClaim?.chatgpt_plan_type==="string"?authClaim.chatgpt_plan_type:void 0;if(email)return{binary,account:{kind:"chatgpt",email,plan}};return{binary,account:{kind:"none"},accountError:"codex id_token: no email claim"}}let apiKey=obj.OPENAI_API_KEY;if(typeof apiKey==="string"&&apiKey.length>0)return{binary,account:{kind:"apikey"}};return{binary,account:{kind:"none"}}}async function detectCopilotAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findCopilotBinary());for(let source of["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"])if(deps.env(source)?.trim())return{binary,account:{kind:"token",source}};let configPath=copilotConfigPath(deps.env,deps.home()),raw;try{raw=deps.readFile(configPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${configPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${configPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};if(hasStringDeep(parsed,["github_token","oauth_token","access_token","token","selectedUser","currentUser","user"]))return{binary,account:{kind:"oauth"}};return{binary,account:{kind:"none"}}}async function detectBobAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findBobBinary()),secretsPath=bobAuthSecretsPath(deps.home()),raw;try{raw=deps.readFile(secretsPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${secretsPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${secretsPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};let signedIn=Object.entries(parsed).some(([key,value])=>key.startsWith("bob.auth.tokens-")&&typeof value==="string"&&value.length>0);return{binary,account:signedIn?{kind:"oauth"}:{kind:"none"}}}async function detectKimiAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findKimiBinary()),credPath=kimiCredentialsPath(deps.env,deps.home()),raw;try{raw=deps.readFile(credPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${credPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${credPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};let token=parsed.access_token;if(typeof token==="string"&&token.length>0)return{binary,account:{kind:"oauth"}};return{binary,account:{kind:"none"}}}function hasStringDeep(value,interestingKeys,depth=0){if(depth>4||!isObject(value))return!1;for(let[key,entry]of Object.entries(value)){if(interestingKeys.includes(key)&&typeof entry==="string"&&entry.length>0)return!0;if(isObject(entry)&&hasStringDeep(entry,interestingKeys,depth+1))return!0}return!1}
209
+ export{parseFlatHooks,mergeFlatHooks,registerPluginEngine,clearPluginEngines,pluginEngineIds,isContribEngine,CONTRIB_ENGINE_IDS,contribEngineEntry,resetAvailableVendorsCache,installedEngineIds,availableEngineIds,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectBobAccount,detectKimiAccount};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{errorMessage}from"./chunk-2brn8e1y.js";import{isObject}from"./chunk-7ghwdjdc.js";import{loadStateFile}from"./chunk-axxf5dkq.js";import{isDev,keybindingsConfigPath}from"./chunk-prqeddy7.js";import{createStateCell}from"./chunk-cmp64q4j.js";function hasReachableBinding(snapshot,predicate){for(let i=snapshot.length-1;i>=0;i--){let cfg=snapshot[i]?.config();if(!cfg||cfg.enabled===!1)continue;if(cfg.bindings.some(predicate))return!0;if(cfg.modal)return!1}return!1}var prefixReachable=(snapshot)=>hasReachableBinding(snapshot,(binding)=>binding.prefix===!0),inputPassthroughReachable=(snapshot)=>hasReachableBinding(snapshot,(binding)=>binding.passthrough===!0);function scanReachability(snapshot){let directIds=new Set,prefixIds=new Set,prefixReachable2=!1,inputPassthrough=!1,yieldedDirectIds=new Set,prefixOptions=[],seenPrefixKeys=new Set;for(let i=snapshot.length-1;i>=0;i--){let cfg=snapshot[i]?.config();if(!cfg||cfg.enabled===!1)continue;for(let binding of cfg.bindings){if(binding.passthrough)inputPassthrough=!0;if(binding.prefix===!0){if(prefixReachable2=!0,binding.id)prefixIds.add(binding.id);if(!seenPrefixKeys.has(binding.key))seenPrefixKeys.add(binding.key),prefixOptions.push({stroke:binding.key,action:binding.id??binding.key})}else if(binding.id){if(directIds.add(binding.id),binding.yieldToPassthrough)yieldedDirectIds.add(binding.id)}}if(cfg.modal)break}if(inputPassthrough)for(let id of yieldedDirectIds)directIds.delete(id);return{prefixReachable:prefixReachable2,inputPassthrough,prefixOptions,directIds,prefixIds}}function bindingReachability(snapshot){let{directIds,prefixIds,inputPassthrough}=scanReachability(snapshot);return{direct:directIds,prefix:prefixIds,inputPassthrough}}var PREFIX_HUD_TTL_MS=4000,PREFIX_GUIDE_DELAY_MS=180;var MAX_ENTRIES=3,realClock={now:()=>Date.now(),schedule:(fn,ms)=>{let timer=setTimeout(fn,ms);return()=>clearTimeout(timer)}},clock=realClock;function prefixHudClock(){return clock}var cell=createStateCell({guide:null,entries:[]}),nextEntryId=1,prefixHudState=cell;function prefixHudSetArmed(armed,options=[],armedAt=null){cell.update((current)=>{if(!armed)return current.guide?.kind==="prefix"?{...current,guide:null}:current;return{...current,guide:{kind:"prefix",armedAt:armedAt??clock.now(),options}}})}function prefixHudShowDirect(options){cell.update((current)=>({...current,guide:{kind:"direct",options}}))}function prefixHudHideDirect(){cell.update((current)=>current.guide?.kind==="direct"?{...current,guide:null}:current)}function prefixHudPush(entry){cell.update((current)=>({...current,guide:null,entries:[...current.entries,{...entry,id:nextEntryId++}].slice(-MAX_ENTRIES)}))}function matchKey(evt){let base=[],name=evt.name;if(name)base.push(name);if(name==="return")base.push("enter");if(name==="enter")base.push("return");if(name==="backspace"&&evt.raw==="\b"&&!evt.meta&&!evt.option)base.push("ctrl+h");if(name==="linefeed"&&!evt.meta&&!evt.option)base.push("ctrl+j");let mods=[];if(evt.ctrl)mods.push("ctrl");if(evt.meta||evt.super)mods.push("cmd");if(evt.option)mods.push("alt");let bareShiftChar=evt.shift&&name!==void 0&&name.length===1&&mods.length===0;if(evt.shift&&name&&name.length>1)mods.push("shift");if(mods.length===0){if(bareShiftChar)return[...base.map((n)=>`shift+${n}`),...base];return base}let prefix=`${mods.join("+")}+`,prefixed=base.map((n)=>prefix+n);if(evt.shift&&name!==void 0&&name.length===1&&evt.source==="kitty")return[...base.map((n)=>`${mods.join("+")}+shift+${n}`),...prefixed];return prefixed}var KITTY_MODIFIER_KEY_NAMES=["leftshift","leftctrl","leftalt","leftsuper","lefthyper","leftmeta","rightshift","rightctrl","rightalt","rightsuper","righthyper","rightmeta","iso_level3_shift","iso_level5_shift"],KITTY_MODIFIER_KEYS=new Set(KITTY_MODIFIER_KEY_NAMES);function isKittyModifierKeyName(name){return name!==void 0&&KITTY_MODIFIER_KEYS.has(name)}function isKittyModifierKeyEvent(event){return isKittyModifierKeyName(event.name)}function isCtrlModifierKeyName(name){return name==="leftctrl"||name==="rightctrl"}function prefixAction(run){return{run}}function insertRegistration(stack,reg){if(reg.modalOwner!==void 0){let firstMember=stack.findIndex((r)=>r.modalMember===reg.modalOwner);if(firstMember>=0){stack.splice(firstMember,0,reg);return}}stack.push(reg)}var dispatching=!1,DEFAULT_PREFIX_CONFIGURATION={key:"ctrl+a",timeoutMs:5000},prefixConfiguration={...DEFAULT_PREFIX_CONFIGURATION},prefixArmedAt=null,prefixArmedKey="",prefixArmedOnPassthrough=!1,prefixArmedOptions=[],prefixTimer=null;function configurePrefix(next){prefixConfiguration={...next},resetPrefixState()}function resetPrefixConfiguration(){prefixConfiguration={...DEFAULT_PREFIX_CONFIGURATION},resetPrefixState()}function currentPrefixConfiguration(){return prefixConfiguration}function prefixFirstStrokes(config=prefixConfiguration){if(config.key===null)return[];return[config.key,...config.extraKeys??[]]}function resetPrefixState(){if(prefixTimer!==null)clearTimeout(prefixTimer);prefixTimer=null,prefixArmedAt=null,prefixArmedOnPassthrough=!1,prefixArmedOptions=[],prefixHudSetArmed(!1)}function armPrefix(now,options,inputPassthrough,armedKey=prefixConfiguration.key??""){resetPrefixState(),prefixArmedAt=now,prefixArmedKey=armedKey,prefixArmedOnPassthrough=inputPassthrough,prefixArmedOptions=options.slice(),prefixTimer=setTimeout(resetPrefixState,prefixConfiguration.timeoutMs),prefixHudSetArmed(!0,options,now)}function armPrefixNow(snapshot,now=Date.now()){if(prefixConfiguration.key===null)return!1;let reach=scanReachability(snapshot);if(!reach.prefixReachable)return!1;return armPrefix(now,reach.prefixOptions,reach.inputPassthrough),!0}function invokeArmedPrefixAction(bindingStack,actionId,stroke,now=Date.now()){if(dispatching||prefixArmedAt===null)return!1;let snapshot=bindingStack.slice(),armedPrefixKey=prefixArmedKey,validOption=prefixArmedOptions.some((option)=>option.action===actionId&&option.stroke===stroke),expired=now-prefixArmedAt>prefixConfiguration.timeoutMs,crossedBoundary=inputPassthroughReachable(snapshot)!==prefixArmedOnPassthrough;if(!validOption||expired||crossedBoundary)return resetPrefixState(),!1;let hit=null;for(let i=snapshot.length-1;i>=0;i--){let reg=snapshot[i];if(!reg)continue;let cfg=reg.config();if(cfg.enabled===!1)continue;let candidate=cfg.bindings.find((binding)=>binding.prefix===!0&&binding.key===stroke);if(candidate){if(candidate.id===actionId)hit=candidate;break}if(cfg.modal)break}if(!hit?.action)return resetPrefixState(),!1;resetPrefixState(),dispatching=!0;try{return hit.action.run(),prefixHudPush({prefixKey:armedPrefixKey,stroke,action:actionId,at:now}),!0}finally{dispatching=!1}}var shadowWarned=new Set;function warnShadowedMatch(snapshot,hitIndex,candidates,prefix){for(let j=hitIndex-1;j>=0;j--){let cfg=snapshot[j]?.config();if(!cfg||cfg.enabled===!1)continue;let shadowed=cfg.bindings.find((b)=>Boolean(b.prefix)===prefix&&candidates.includes(b.key));if(shadowed){if(!shadowWarned.has(shadowed.key))shadowWarned.add(shadowed.key),console.error(`[rove keymap] "${shadowed.key}" matched two ENABLED bindings \u2014 the lower one is shadowed by LIFO order. Gate one of them off (see tui-react/lib/keymap.ts header).`);return}if(cfg.modal)return}}function dispatchMode(snapshot,evt,candidates,prefix,runCmd){for(let i=snapshot.length-1;i>=0;i--){let reg=snapshot[i];if(!reg)continue;let cfg=reg.config();if(cfg.enabled===!1)continue;let hit;for(let candidate of candidates)if(hit=cfg.bindings.find((binding)=>Boolean(binding.prefix)===prefix&&binding.key===candidate),hit)break;if(hit){if(hit.yieldToPassthrough&&inputPassthroughReachable(snapshot))continue;if(!cfg.modal&&isDev())warnShadowedMatch(snapshot,i,candidates,prefix);return runCmd(()=>hit.cmd(evt,hit.slot)),hit}if(cfg.modal)return null}return null}function dispatchKeyEvent(bindingStack,evt,now=Date.now(),opts){if(evt.defaultPrevented||dispatching)return!1;if(isKittyModifierKeyName(evt.name))return evt.preventDefault(),!0;let snapshot=bindingStack.slice(),candidates=matchKey(evt),runCmd=opts?.flushSync??((fn)=>fn());dispatching=!0;try{if(prefixArmedAt!==null&&inputPassthroughReachable(snapshot)!==prefixArmedOnPassthrough)resetPrefixState();if(prefixArmedAt!==null){let armedPrefixKey=prefixArmedKey,expired=now-prefixArmedAt>prefixConfiguration.timeoutMs;if(prefixArmedAt=null,expired)resetPrefixState();else{if(candidates.includes("escape"))return resetPrefixState(),evt.preventDefault(),!0;resetPrefixState();let hit=dispatchMode(snapshot,evt,candidates,!0,runCmd);return prefixHudPush({prefixKey:armedPrefixKey,stroke:candidates[0]??"",action:hit?hit.id??hit.key:null,at:now}),evt.preventDefault(),!0}}let firstStroke=prefixFirstStrokes().find((key)=>candidates.includes(key));if(firstStroke!==void 0){if(prefixReachable(snapshot)){let reach=scanReachability(snapshot);return armPrefix(now,reach.prefixOptions,reach.inputPassthrough,firstStroke),evt.preventDefault(),!0}}let direct=dispatchMode(snapshot,evt,candidates,!1,runCmd);if(direct){if(direct.id&&direct.key.includes("+")&&!direct.key.startsWith("shift+"))prefixHudPush({prefixKey:"",stroke:direct.key,action:direct.id??direct.key,at:now});return evt.preventDefault(),!0}return!1}finally{dispatching=!1}}import{existsSync,readFileSync}from"fs";var cached=null;function resetKeybindingsFileCache(){cached=null}function resolveConfigFile(){let canonical=keybindingsConfigPath();if(existsSync(canonical))return{canonical,found:canonical};let yml=canonical.replace(/\.yaml$/,".yml");if(existsSync(yml))return{canonical,found:yml};return{canonical,found:null}}function readKeybindingsFile(){if(cached)return cached;let{canonical,found}=resolveConfigFile();if(!found)return cached={path:canonical,exists:!1,doc:null,warnings:[]},cached;let warnings=[],doc=null;try{let text=readFileSync(found,"utf8");doc=Bun.YAML.parse(text)}catch(err){let msg=errorMessage(err);warnings.push(`could not read/parse ${found}: ${msg}`)}return cached={path:canonical,exists:!0,doc,warnings},cached}var MOD_ALIASES={ctrl:"ctrl",control:"ctrl",ctl:"ctrl",cmd:"cmd",command:"cmd",meta:"cmd",super:"cmd",win:"cmd",alt:"alt",option:"alt",opt:"alt",shift:"shift"},KEY_ALIASES={esc:"escape",spacebar:"space",pgup:"pageup",pgdn:"pagedown",pgdown:"pagedown"},KNOWN_NAMED_KEYS=new Set(["up","down","left","right","pageup","pagedown","home","end","insert","delete","backspace","tab","space","escape","enter","return",...Array.from({length:12},(_,i)=>`f${i+1}`)]),MOD_ORDER=["ctrl","cmd","alt","shift"];function normalizeChord(raw){let rawTrimmed=raw.trim(),upperLetterKey=rawTrimmed.length===1&&rawTrimmed>="A"&&rawTrimmed<="Z",trimmed=raw.trim().toLowerCase();if(!trimmed)return{error:"empty chord"};let parts=trimmed.split("+"),key=parts.pop()??"";if(key===""&&parts.length>0&&parts[parts.length-1]==="")key="+",parts.pop();if(!key)return{error:`"${raw}": no key after the modifiers`};let mods=new Set;for(let part of parts){let mod=MOD_ALIASES[part];if(!mod)return{error:`"${raw}": unknown modifier "${part}" (use ctrl / cmd / alt / shift)`};mods.add(mod)}if(key=KEY_ALIASES[key]??key,upperLetterKey)mods.add("shift");if(mods.has("shift")&&mods.size>1&&key.length===1)return{error:`"${raw}": shift with other modifiers on a single character can never match \u2014 legacy terminals send the same byte with and without shift`};let prefix=MOD_ORDER.filter((m)=>mods.has(m)).join("+"),chord=prefix?`${prefix}+${key}`:key;if(key.length>1&&!KNOWN_NAMED_KEYS.has(key))return{chord,warning:`"${raw}": unrecognized key name "${key}" \u2014 the chord may never fire`};return{chord}}function platformSectionNames(platform){if(platform==="darwin")return["darwin","macos","mac"];if(platform==="win32")return["win32","windows"];return[platform]}function extractBindingsMap(section){if(!isObject(section))return null;let nested=section.bindings;if(isObject(nested))return nested;return section}function extractKeybindingOverrides(doc,platform){let warnings=[];if(doc===null||doc===void 0)return{entries:[],prefixEntries:[],warnings};if(!isObject(doc))return{entries:[],prefixEntries:[],warnings:["config root must be a YAML mapping (e.g. a top-level `bindings:` key)"]};let merged=new Map,prefixMerged=new Map,layers=[];if(doc.bindings!==void 0)if(isObject(doc.bindings))layers.push(doc.bindings);else warnings.push("`bindings:` must be a mapping of id \u2192 chord(s)");for(let name of platformSectionNames(platform)){let section=doc[name];if(section===void 0)continue;let map=extractBindingsMap(section);if(map)layers.push(map);else warnings.push(`\`${name}:\` must be a mapping (or contain a \`bindings:\` mapping)`)}for(let layer of layers)for(let[id,value]of Object.entries(layer)){let modeValues=isObject(value)&&(("direct"in value)||("prefix"in value))?[[merged,value.direct],[prefixMerged,value.prefix]]:[[merged,value]];for(let[target,modeValue]of modeValues){if(modeValue===void 0)continue;if(modeValue===null||modeValue===!1||Array.isArray(modeValue)&&modeValue.length===0){target.set(id,[]);continue}let rawChords=typeof modeValue==="string"?[modeValue]:Array.isArray(modeValue)?modeValue:null;if(!rawChords){warnings.push(`${id}: expected a chord string, a list of chords, or null \u2014 got ${typeof modeValue}`);continue}let chords=[],anyError=!1;for(let rawChord of rawChords){if(typeof rawChord!=="string"){warnings.push(`${id}: chord entries must be strings`),anyError=!0;continue}let result=normalizeChord(rawChord);if("error"in result){warnings.push(`${id}: ${result.error}`),anyError=!0;continue}if(result.warning)warnings.push(`${id}: ${result.warning}`);if(!chords.includes(result.chord))chords.push(result.chord)}if(chords.length===0&&anyError){warnings.push(`${id}: no valid chords \u2014 keeping the default`);continue}target.set(id,chords)}}return{entries:Array.from(merged,([id,keys])=>({id,keys})),prefixEntries:Array.from(prefixMerged,([id,keys])=>({id,keys})),warnings}}var FIXED_BINDING_IDS={"diff.review.cursor":"diff-review cursor is a fixed raw binding (j/k), not keymap-driven","diff.review.range":"diff-review range anchor is a fixed raw binding (v), not keymap-driven","diff.review.note":"diff-review note is a fixed raw binding (c), not keymap-driven","diff.review.send":"diff-review send is a fixed raw binding (s), not keymap-driven","diff.review.drop":"diff-review drop-note is a fixed raw binding (x), not keymap-driven","diff.review.reload":"preview reload is a fixed raw binding (r), not keymap-driven"};function pairContract(first,second){let layout=`alternating [${first}, ${second}] pairs`;return{layout,validateCount:(count)=>count>=2&&count%2===0?null:`needs ${layout} (an even number of chords \u2014 got ${count})`}}var SLOT_CONTRACTS={"sidebar.goto":pairContract("top (double-tap)","bottom"),"sidebar.nav":pairContract("down","up"),"files.nav":pairContract("down","up"),"sidebar.search.nav":pairContract("down","up"),"files.hierarchy":pairContract("collapse","expand"),"files.tab":pairContract("previous tab","next tab"),"app.quit":{layout:"[quit confirm, hard exit] (second chord optional)",validateCount:(count)=>count<=2?null:`needs [quit confirm, hard exit] (1 or 2 chords \u2014 got ${count})`}},NO_BARE_LETTER_SCOPES=new Set(["global","workspace","terminal"]);function scopesOverlap(a,b){return a===b||a==="global"||b==="global"}function applyKeymapOverrides(keymap,entries,fixedIds=FIXED_BINDING_IDS){let warnings=[],applied=[];for(let entry of entries){let row=keymap.find((b)=>b.id===entry.id);if(!row){warnings.push(`${entry.id}: unknown binding id (press F1 in Rove for the full list)`);continue}let fixedReason=fixedIds[entry.id];if(fixedReason){warnings.push(`${entry.id}: not customizable \u2014 ${fixedReason}`);continue}if(row.keys.length===0&&row.prefixKeys===void 0){warnings.push(`${entry.id}: not customizable \u2014 the key is handled outside the keymap (doc-only row)`);continue}let contract=SLOT_CONTRACTS[entry.id];if(contract&&entry.keys.length>0){let problem=contract.validateCount(entry.keys.length);if(problem){warnings.push(`${entry.id}: ${problem} \u2014 keeping the default`);continue}}let keys=entry.keys.filter((chord)=>{if((chord.length===1||chord.startsWith("shift+")&&chord.length===7)&&NO_BARE_LETTER_SCOPES.has(row.scope))return warnings.push(`${entry.id}: "${chord}" dropped \u2014 a bare character on a ${row.scope}-scope binding would steal typed input (add a modifier)`),!1;return!0});if(keys.length===0&&entry.keys.length>0){warnings.push(`${entry.id}: no chords survived validation \u2014 keeping the default`);continue}if(contract&&keys.length!==entry.keys.length){warnings.push(`${entry.id}: a dropped chord would shift the slot layout (${contract.layout}) \u2014 keeping the default`);continue}let defaultKeys=row.keys,mutable=row;if(mutable.keys=keys,row.hint)if(keys.length===0)mutable.hint=void 0;else row.hint.keys=keys.join("/");applied.push({id:entry.id,keys,defaultKeys})}for(let change of applied)for(let chord of change.keys){let owner=keymap.find((b)=>b.id===change.id);if(!owner)continue;for(let other of keymap){if(other.id===change.id)continue;if(!other.keys.includes(chord))continue;if(!scopesOverlap(owner.scope,other.scope))continue;warnings.push(`${change.id}: "${chord}" also fires ${other.id} (${other.scope} scope) \u2014 last registration wins; consider a different chord`)}}return{applied,warnings}}var PLATFORM_SECTIONS={darwin:["darwin","macos","mac"],linux:["linux"],win32:["win32","windows"]},VALUE_RE=/^(pane|action):\s*([A-Za-z0-9][A-Za-z0-9._:-]*\.[A-Za-z0-9][A-Za-z0-9_:-]*)$/;function sectionOf(doc,key){if(typeof doc!=="object"||doc===null)return null;let section=doc[key];if(typeof section!=="object"||section===null||Array.isArray(section))return null;return section}function collect(section,into,warnings){for(let[rawChord,rawValue]of Object.entries(section)){if(typeof rawValue!=="string"){warnings.push(`plugins: ${rawChord}: value must be a "pane:<id>" or "action:<id>" string`);continue}let match=rawValue.trim().match(VALUE_RE);if(!match){warnings.push(`plugins: ${rawChord}: \`${rawValue}\` is not pane:<plugin-id>.<local-id> or action:<...>`);continue}let chord=normalizeChord(rawChord);if("error"in chord){warnings.push(`plugins: ${rawChord}: ${chord.error}`);continue}if(chord.warning)warnings.push(`plugins: ${rawChord}: ${chord.warning}`);into.set(chord.chord,{chord:chord.chord,kind:match[1],target:match[2].trim()})}}function extractPluginKeybindings(doc,platform){let warnings=[],byChord=new Map,base=sectionOf(doc,"plugins");if(base)collect(base,byChord,warnings);for(let alias of PLATFORM_SECTIONS[platform]??[]){let overlaySection=sectionOf(doc,alias),overlay=overlaySection?sectionOf(overlaySection,"plugins"):null;if(overlay)collect(overlay,byChord,warnings)}return{entries:[...byChord.values()],warnings}}function platformKeys(platform){if(platform==="darwin")return["darwin","macos","mac"];if(platform==="win32")return["win32","windows"];return[platform]}function collectEntries(source,warnings){let out=new Map;if(source===void 0)return out;if(!isObject(source))return warnings.push("prefix.bindings must be a mapping of binding id to chord(s)"),out;for(let[id,raw]of Object.entries(source)){if(raw===null||Array.isArray(raw)&&raw.length===0){out.set(id,[]);continue}let rawKeys=typeof raw==="string"?[raw]:Array.isArray(raw)?raw:null;if(!rawKeys||rawKeys.some((key)=>typeof key!=="string")){warnings.push(`prefix.bindings.${id} must be a chord string, a string list, null, or []`);continue}let keys=[],anyError=!1;for(let rawKey of rawKeys){let normalized=normalizeChord(rawKey);if("error"in normalized){warnings.push(`prefix.bindings.${id}: ${normalized.error}`),anyError=!0;continue}if(!keys.includes(normalized.chord))keys.push(normalized.chord);if(normalized.warning)warnings.push(`prefix.bindings.${id}: ${normalized.warning}`)}if(keys.length===0&&anyError){warnings.push(`prefix.bindings.${id}: no valid chords \u2014 keeping the default`);continue}out.set(id,keys)}return out}function prefixChord(raw,warnings){let normalized=normalizeChord(raw);if("error"in normalized)warnings.push(`prefix.key: ${normalized.error}`);else if(!normalized.chord.includes("+"))warnings.push("prefix.key must include a modifier");else return normalized.chord;return null}function mergePrefixKey(raw,configuration,warnings){if(raw===null||Array.isArray(raw)&&raw.length===0){configuration.key=null,configuration.extraKeys=void 0;return}let rawKeys=typeof raw==="string"?[raw]:Array.isArray(raw)?raw:null;if(!rawKeys||rawKeys.some((key)=>typeof key!=="string")){warnings.push("prefix.key must be a modifier chord, a list of them, or null");return}let keys=[];for(let rawKey of rawKeys){let chord=prefixChord(rawKey,warnings);if(chord!==null&&!keys.includes(chord))keys.push(chord)}let[primary,...extra]=keys;if(primary===void 0)return;if(configuration.key=primary,extra.length>0)configuration.extraKeys=extra;else configuration.extraKeys=void 0}function mergePrefixBlock(raw,configuration,entries,warnings){if(raw===void 0)return;if(!isObject(raw)){warnings.push("prefix must be a mapping");return}if("key"in raw)mergePrefixKey(raw.key,configuration,warnings);if("timeoutMs"in raw)if(typeof raw.timeoutMs!=="number"||!Number.isInteger(raw.timeoutMs)||raw.timeoutMs<100||raw.timeoutMs>1e4)warnings.push("prefix.timeoutMs must be an integer from 100 to 10000");else configuration.timeoutMs=raw.timeoutMs;for(let[id,keys]of collectEntries(raw.bindings,warnings))entries.set(id,keys)}function extractPrefixKeybindings(doc,platform){let configuration={},warnings=[],entries=new Map;if(!isObject(doc)){if(doc!==null&&doc!==void 0)warnings.push("keybindings document must be a mapping");return{configuration,entries:[],warnings}}mergePrefixBlock(doc.prefix,configuration,entries,warnings);for(let key of platformKeys(platform)){let overlay=doc[key];if(isObject(overlay))mergePrefixBlock(overlay.prefix,configuration,entries,warnings)}return{configuration,entries:[...entries].map(([id,keys])=>({id,keys})),warnings}}function applyPrefixKeymapOverrides(keymap,entries){let applied=[],warnings=[];for(let entry of entries){let row=keymap.find((candidate)=>candidate.id===entry.id);if(!row){warnings.push(`${entry.id}: unknown binding id`);continue}let mutable=row,defaultKeys=[...row.prefixKeys??[]];mutable.prefixKeys=[...entry.keys],applied.push({id:entry.id,keys:[...entry.keys],defaultKeys})}return{applied,warnings}}function resolveUserKeybindings(file,keymap,platform){if(!file.exists)return{report:{path:file.path,exists:!1,applied:[],plugins:[],warnings:[]},prefix:{...DEFAULT_PREFIX_CONFIGURATION}};let warnings=[...file.warnings],extracted=extractKeybindingOverrides(file.doc,platform);warnings.push(...extracted.warnings);let prefix=extractPrefixKeybindings(file.doc,platform);warnings.push(...prefix.warnings);let prefixConfiguration2={...DEFAULT_PREFIX_CONFIGURATION,...prefix.configuration},result=applyKeymapOverrides(keymap,extracted.entries);warnings.push(...result.warnings);let applied=[...result.applied],customPrefix=prefix.configuration.key===void 0?[]:prefixFirstStrokes(prefixConfiguration2);for(let prefixKey of customPrefix){let directOwner=keymap.find((row)=>row.keys.includes(prefixKey));if(directOwner)warnings.push(`prefix.key "${prefixKey}" collides with direct binding ${directOwner.id}`)}let prefixResult=applyPrefixKeymapOverrides(keymap,[...extracted.prefixEntries,...prefix.entries]);warnings.push(...prefixResult.warnings),applied.push(...prefixResult.applied);let plugins=extractPluginKeybindings(file.doc,platform);warnings.push(...plugins.warnings);for(let p of plugins.entries){let owner=keymap.find((row)=>row.keys.includes(p.chord));if(owner)warnings.push(`plugins: ${p.chord} shadows ${owner.id}`)}return{report:{path:file.path,exists:!0,applied,plugins:plugins.entries,warnings},prefix:prefixConfiguration2}}var CHAT_BINDINGS=[{id:"chat.tab.new",scope:"workspace",keys:["ctrl+t"],category:"Workspace",description:"New chat tab",hint:{keys:"ctrl+t"},presentation:"onePress"},{id:"chat.tab.chooseEngine",scope:"workspace",keys:["ctrl+e"],category:"Workspace",description:"New conversation \u2014 engine/shell picker with destination + context toggles",hint:{keys:"ctrl+e"},presentation:"onePress"},{id:"chat.tab.fork",scope:"workspace",keys:[],prefixKeys:["c"],category:"Workspace",description:"Fork this chat into a new tab (same Task directory, keeps the conversation)",hint:{keys:"ctrl+a c"}},{id:"chat.fork.new",scope:"workspace",keys:[],prefixKeys:["f"],category:"Workspace",description:"Quick-fork: create child task seeded with current repo/branch/model",hint:{keys:"ctrl+a f"}},{id:"chat.tab.close",scope:"workspace",keys:["ctrl+w"],prefixKeys:["w"],category:"Workspace",description:"Close chat tab",hint:{keys:"ctrl+w"},presentation:"onePress"},{id:"workspace.reopenSession",scope:"workspace",keys:["return"],category:"Workspace",description:"Reopen a session in a task whose tabs are all closed",hint:{keys:"enter"},presentation:"onePress"},{id:"chat.tab.rename",scope:"workspace",keys:["f2"],category:"Workspace",description:"Rename active chat tab",hint:{keys:"f2"},presentation:"onePress"},{id:"chat.tab.cycle-next",scope:"workspace",keys:["ctrl+]"],category:"Workspace",description:"Next chat tab",hint:{keys:"ctrl+]"},presentation:"onePress"},{id:"chat.tab.cycle-prev",scope:"workspace",keys:["ctrl+["],category:"Workspace",description:"Previous chat tab",hint:{keys:"ctrl+["},presentation:"onePress"},{id:"chat.tab.goto",scope:"workspace",keys:["1","2","3","4","5","6","7","8","9"].map((digit)=>`ctrl+${digit}`),category:"Workspace",description:"Go to chat tab N",hint:{keys:"ctrl+1-9"},presentation:"onePress"},{id:"workspace.split.right",scope:"workspace",keys:["ctrl+\\"],category:"Workspace",description:"Split right",hint:{keys:"ctrl+\\"},presentation:"onePress"},{id:"workspace.split.down",scope:"workspace",keys:["ctrl+="],category:"Workspace",description:"Split down",hint:{keys:"ctrl+="},presentation:"onePress"},{id:"workspace.split.focus-next",scope:"workspace",keys:["f3"],category:"Workspace",description:"Focus next split",hint:{keys:"f3"},presentation:"onePress"},{id:"workspace.split.close",scope:"workspace",keys:["ctrl+w"],prefixKeys:["w"],category:"Workspace",description:"Close active split (tab when unsplit)",hint:{keys:"ctrl+w"},presentation:"onePress"},{id:"workspace.split.rename",scope:"workspace",keys:["f2"],category:"Workspace",description:"Rename active split (tab when unsplit)",hint:{keys:"f2"},presentation:"onePress"}];var FILES_BINDINGS=[{id:"files.nav",scope:"files",keys:["j","k","down","up"],category:"Files",description:"Move cursor up/down",hint:{keys:"j/k"}},{id:"files.hierarchy",scope:"files",keys:["h","l","left","right"],category:"Files",description:"Collapse / expand tree level",hint:{keys:"h/l"}},{id:"files.open",scope:"files",keys:["return"],category:"Files",description:"Open file in configured editor (diff when supported)",hint:{keys:"enter"}},{id:"files.tab",scope:"files",keys:["[","]"],category:"Files",description:"Switch tab (cycle All / Changes)",hint:{keys:"[/]"}},{id:"files.refresh",scope:"files",keys:["r"],category:"Files",description:"Refresh",hint:{keys:"r"}},{id:"files.scope",scope:"files",keys:["b"],category:"Files",description:"Toggle Changes scope (working \u2194 branch vs base)",hint:{keys:"b"}},{id:"files.diff",scope:"files",keys:["d"],category:"Files",description:"Open read-only diff in a workspace tab",hint:{keys:"d"}},{id:"files.diffAll",scope:"files",keys:["shift+d"],category:"Files",description:"Open the whole worktree's diff in one workspace tab",hint:{keys:"D"}},{id:"files.openExternal",scope:"files",keys:["o"],category:"Files",description:"Open file in system default app (audio / video / pdf preview)",hint:{keys:"o"}},{id:"files.mention",scope:"files",keys:["a"],category:"Files",description:"Inject @<path> mention into the engine pane",hint:{keys:"a"}},{id:"files.createPR",scope:"global",keys:[],prefixKeys:["p","shift+p"],category:"Files",description:"Ask the agent to create a PR from the current task"},{id:"files.fixChecks",scope:"global",keys:[],prefixKeys:["k"],category:"Files",description:"Ask the agent to fix the failing PR checks"},{id:"files.syncBase",scope:"global",keys:[],prefixKeys:["u"],category:"Files",description:"Merge the base branch into this task's worktree"},{id:"diff.review.cursor",scope:"workspace",keys:[],category:"Diff review",description:"Move the line cursor over the diff",hint:{keys:"j/k"}},{id:"diff.review.range",scope:"workspace",keys:[],category:"Diff review",description:"Toggle range anchor at the cursor",hint:{keys:"v"}},{id:"diff.review.note",scope:"workspace",keys:[],category:"Diff review",description:"Add a review note at the cursor",hint:{keys:"c"}},{id:"diff.review.send",scope:"workspace",keys:[],category:"Diff review",description:"Send all unsent review notes to the engine",hint:{keys:"s"}},{id:"diff.review.drop",scope:"workspace",keys:[],category:"Diff review",description:"Drop the review note the cursor sits inside",hint:{keys:"x"}},{id:"diff.review.reload",scope:"workspace",keys:[],category:"Diff review",description:"Reload the previewed file from disk",hint:{keys:"r"}}];var INBOX_BINDINGS=[{id:"inbox.show",scope:"global",keys:[],prefixKeys:["i"],category:"Global",description:"Open Inbox"},{id:"inbox.nav",scope:"inbox",keys:["j","k","down","up"],category:"Inbox",description:"Move cursor up/down",hint:{keys:"j/k"}},{id:"inbox.open",scope:"inbox",keys:["return"],category:"Inbox",description:"Open the selected Task and Terminal Tab",hint:{keys:"enter"}},{id:"inbox.delete",scope:"inbox",keys:["d"],category:"Inbox",description:"Remove the selected Inbox item",hint:{keys:"d"}}];var SIDEBAR_BINDINGS=[{id:"sidebar.nav",scope:"sidebar",keys:["j","k","down","up"],category:"Sidebar",description:"Move cursor up/down",hint:{keys:"j/k"}},{id:"sidebar.select",scope:"sidebar",keys:["return"],category:"Sidebar",description:"Open the selected task",hint:{keys:"enter"}},{id:"sidebar.tree.open",scope:"sidebar",keys:["l","space"],category:"Sidebar",description:"Open the row under the cursor (a tab row enters its chat)",hint:{keys:"l"}},{id:"sidebar.goto",scope:"sidebar",keys:["g","shift+g"],category:"Sidebar",description:"Top / bottom of list (gg or shift-G)"},{id:"sidebar.rename",scope:"sidebar",keys:["r"],category:"Sidebar",description:"Rename task",hint:{keys:"r"}},{id:"sidebar.localMerge",scope:"sidebar",keys:["shift+m"],category:"Sidebar",description:"Reorder row (Shift+M, then j/k)",hint:{keys:"M"}},{id:"sidebar.pin",scope:"sidebar",keys:["shift+p"],category:"Sidebar",description:"Pin / unpin task at top (Shift+P)",hint:{keys:"P"}},{id:"sidebar.sort",scope:"sidebar",keys:["t"],category:"Sidebar",description:"Cycle task sort (default \u2192 recent \u2192 attention \u2192 name)",hint:{keys:"t"}},{id:"sidebar.delete",scope:"sidebar",keys:["d"],category:"Sidebar",description:"Delete task (with confirm)",hint:{keys:"d"}},{id:"sidebar.search.enter",scope:"sidebar",keys:["/"],category:"Sidebar",description:"Search tasks (fuzzy filter)",hint:{keys:"/"}},{id:"sidebar.search.nav",scope:"sidebar",keys:["down","up"],category:"Sidebar",description:"Move highlight in search results"},{id:"sidebar.search.submit",scope:"sidebar",keys:["return"],category:"Sidebar",description:"Select search match and exit search"},{id:"sidebar.search.cancel",scope:"sidebar",keys:["escape"],category:"Sidebar",description:"Cancel search (restore prior selection)"},{id:"tasks.openWorktree",scope:"sidebar",keys:["o"],category:"Tasks pane",description:"Open selected Task directory in your editor",hint:{keys:"o"}},{id:"tasks.renameBranch",scope:"sidebar",keys:["b"],category:"Tasks pane",description:"Rename the selected task's git branch",hint:{keys:"b"}},{id:"tasks.cycleEngine",scope:"sidebar",keys:["v"],category:"Tasks pane",description:"Cycle engine vendor \u2014 applies on reopen",hint:{keys:"v"}},{id:"tasks.update",scope:"sidebar",keys:["u"],category:"Tasks pane",description:"Open the update page \u2014 version check + release notes",hint:{keys:"u"}},{id:"tasks.focusEngine",scope:"sidebar",keys:["right"],category:"Tasks pane",description:"Focus the engine pane of the current window",hint:{keys:"\u2192"}}];var RoveKeymap=[{id:"palette.open",scope:"global",keys:[],prefixKeys:["/"],category:"Global",description:"Search commands"},{id:"help.open",scope:"global",keys:["f1"],category:"Global",description:"Show keybindings help",hint:{keys:"F1"},presentation:"onePress"},{id:"task.new",scope:"sidebar",keys:["n"],category:"Sidebar",description:"New task",hint:{keys:"n"}},{id:"task.new.global",scope:"global",keys:[],prefixKeys:["n"],category:"Global",description:"New task"},{id:"task.openEditor",scope:"global",keys:[],prefixKeys:["o"],category:"Global",description:"Open active Task directory in editor"},{id:"task.moveMode",scope:"global",keys:[],prefixKeys:["m"],category:"Global",description:"Reorder sidebar rows (then j/k)"},{id:"settings.open",scope:"global",keys:[],prefixKeys:[","],category:"Global",description:"Open settings"},{id:"app.refresh",scope:"global",keys:[],prefixKeys:["r"],category:"Global",description:"Refresh Rove onto the installed build (after an update)"},{id:"settings.open.sidebar",scope:"sidebar",keys:["s"],category:"Sidebar",description:"Open settings",hint:{keys:"s"}},{id:"worktrees.open.sidebar",scope:"sidebar",keys:["x"],category:"Sidebar",description:"Open worktrees",hint:{keys:"x"}},{id:"kanban.open",scope:"global",keys:[],prefixKeys:["1"],category:"Global",description:"Open kanban (issues board)"},{id:"automations.open",scope:"global",keys:[],prefixKeys:["2"],category:"Global",description:"Open routines (scheduled tasks)"},{id:"workItems.open",scope:"global",keys:[],prefixKeys:["3"],category:"Global",description:"Open GitHub issues (external tracker)"},{id:"app.quit",scope:"sidebar",keys:["q","ctrl+q"],category:"Sidebar",description:"Quit (with confirm)",hint:{keys:"q"}},{id:"focus.sidebar",scope:"workspace",keys:["ctrl+q"],category:"Workspace",description:"Back to sidebar (tasks)",hint:{keys:"ctrl+q"},presentation:"onePress"},{id:"focus.previous",scope:"global",keys:[],prefixKeys:["h"],category:"Navigation",description:"Focus previous pane (files \u2192 workspace \u2192 sidebar)"},{id:"focus.next",scope:"global",keys:["f4"],prefixKeys:["l"],category:"Navigation",description:"Focus next pane (sidebar \u2192 workspace \u2192 files)",hint:{keys:"f4"},presentation:"onePress"},{id:"attention.next",scope:"global",keys:["f7"],category:"Navigation",description:"Jump to the next available Inbox item",hint:{keys:"f7"},presentation:"onePress"},{id:"workspace.zenToggle",scope:"global",keys:[],prefixKeys:["z"],category:"Navigation",description:"Toggle zen mode (hide the files column)"},{id:"view.redraw",scope:"global",keys:[],prefixKeys:["r"],category:"Global",description:"Redraw the screen"},...SIDEBAR_BINDINGS,...CHAT_BINDINGS,...FILES_BINDINGS,...INBOX_BINDINGS,{id:"terminal.scroll-up",scope:"terminal",keys:["ctrl+pageup"],category:"Terminal",description:"Scroll scrollback up",hint:{keys:"ctrl+pgup"}},{id:"terminal.scroll-down",scope:"terminal",keys:["ctrl+pagedown"],category:"Terminal",description:"Scroll scrollback down"},{id:"terminal.reset",scope:"terminal",keys:["f5"],category:"Terminal",description:"Reset terminal \u2014 kill the current shell and respawn",hint:{keys:"f5"},presentation:"onePress"},{id:"terminal.search",scope:"terminal",keys:[],prefixKeys:["/"],category:"Terminal",description:"Search the scrollback"},{id:"terminal.search.older",scope:"terminal",keys:["up","return"],category:"Terminal",description:"Scrollback search: walk to the older match"},{id:"terminal.search.newer",scope:"terminal",keys:["down"],category:"Terminal",description:"Scrollback search: walk to the newer match"},{id:"terminal.search.cancel",scope:"terminal",keys:["escape"],category:"Terminal",description:"Close scrollback search (restore prior scroll position)"}];var SOUND_VOLUME_KEY="notifications.sound.volume",DEFAULT_SOUND_VOLUME=0.4,SOUND_VOLUME_STEPS=[0.1,0.25,0.4,0.6,0.8,1];function normalizeSoundVolume(value){let n=typeof value==="number"?value:typeof value==="string"?Number.parseFloat(value.trim()):Number.NaN;if(!Number.isFinite(n))return DEFAULT_SOUND_VOLUME;return Math.min(1,Math.max(0,n))}function nextSoundVolume(volume){let current=normalizeSoundVolume(volume),above=SOUND_VOLUME_STEPS.findIndex((step)=>step>current+0.000000001);return SOUND_VOLUME_STEPS[above<0?0:above]}function persistedSoundVolume(){return normalizeSoundVolume(loadStateFile()[SOUND_VOLUME_KEY])}
3
+ export{resetKeybindingsFileCache,readKeybindingsFile,inputPassthroughReachable,bindingReachability,isKittyModifierKeyEvent,isCtrlModifierKeyName,PREFIX_HUD_TTL_MS,PREFIX_GUIDE_DELAY_MS,prefixHudClock,prefixHudState,prefixHudShowDirect,prefixHudHideDirect,prefixAction,insertRegistration,DEFAULT_PREFIX_CONFIGURATION,configurePrefix,resetPrefixConfiguration,currentPrefixConfiguration,prefixFirstStrokes,resetPrefixState,armPrefixNow,invokeArmedPrefixAction,dispatchKeyEvent,FIXED_BINDING_IDS,resolveUserKeybindings,RoveKeymap,SOUND_VOLUME_KEY,DEFAULT_SOUND_VOLUME,SOUND_VOLUME_STEPS,normalizeSoundVolume,nextSoundVolume,persistedSoundVolume};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{addRemoteRepo,addSavedRepo,backfillSavedReposFromProjects,getCustomEngineIds,getDisabledEngineIds,getPersistedString,getPersistedValue,getRemoteRepoConfig,getRemoteRepos,getRepoInitOverride,getSavedRepos,isGitRepo,isRemoteProjectsEnabled,isRemoteRepoKey,isValidBranchName,normalizeSavedRepos,remoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,setPersistedString,setRepoInitOverride,statePath}from"./chunk-21ek142k.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-zk5qkkb1.js";import"./chunk-mw0ysrpd.js";import"./chunk-a7kq09ke.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-npwzmmv9.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{statePath,setRepoInitOverride,setPersistedString,resolveRepoRoot,resolveMainRepoRoot,removeSavedRepo,remoteRepoKey,normalizeSavedRepos,isValidBranchName,isRemoteRepoKey,isRemoteProjectsEnabled,isGitRepo,getSavedRepos,getRepoInitOverride,getRemoteRepos,getRemoteRepoConfig,getPersistedValue,getPersistedString,getDisabledEngineIds,getCustomEngineIds,backfillSavedReposFromProjects,addSavedRepo,addRemoteRepo};
2
+ import{addRemoteRepo,addSavedRepo,backfillSavedReposFromProjects,getCustomEngineIds,getDisabledEngineIds,getPersistedString,getPersistedValue,getRemoteRepoConfig,getRemoteRepos,getRepoInitOverride,getSavedRepos,isGitRepo,isRemoteProjectsEnabled,isRemoteRepoKey,isValidBranchName,normalizeSavedRepos,remoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,setPersistedString,setRepoInitOverride,statePath}from"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{statePath,setRepoInitOverride,setPersistedString,resolveRepoRoot,resolveMainRepoRoot,removeSavedRepo,remoteRepoKey,normalizeSavedRepos,isValidBranchName,isRemoteRepoKey,isRemoteProjectsEnabled,isGitRepo,getSavedRepos,getRepoInitOverride,getRemoteRepos,getRemoteRepoConfig,getPersistedValue,getPersistedString,getDisabledEngineIds,getCustomEngineIds,backfillSavedReposFromProjects,addSavedRepo,addRemoteRepo};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{stopDaemonProcess}from"./chunk-gaf6n1ea.js";import{spawnDetachedDaemon}from"./chunk-7j00hbq5.js";import{isProcessAlive,readPidFile}from"./chunk-a7kq09ke.js";import{DAEMON_PROTOCOL_VERSION,RoveDaemonClient}from"./chunk-s5a5dyab.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-npwzmmv9.js";import{ROVE_PRODUCT_NAME}from"./chunk-nc46gddg.js";import{closeSync,existsSync,mkdirSync,openSync,statSync,unlinkSync}from"fs";import{dirname,resolve}from"path";import{fileURLToPath}from"url";var DAEMON_START_ARGS=["daemon","start"],DAEMON_HELLO_TIMEOUT_MS=3000,BUSY_DAEMON_GRACE_MS=15000;function insideEngineSession(env=process.env){return typeof env.ROVE_TASK_ID==="string"&&env.ROVE_TASK_ID!==""}function autospawnDaemonEnv(env=process.env,reason="autospawn"){let{ROVE_TASK_ID:_task,ROVE_TAB_ID:_tab,ROVE_TUI:_tui,ROVE_TERMINAL_PTY:_pty,ROVE_TASK_ID:_roveTask,ROVE_TAB_ID:_roveTab,ROVE_TUI:_roveTui,ROVE_TERMINAL_PTY:_rovePty,...rest}=env;return{...rest,ROVE_DAEMON_AUTOSPAWNED:"1",ROVE_DAEMON_SPAWN_REASON:reason}}function daemonSpawnReason(env=process.env){let raw=env.ROVE_DAEMON_SPAWN_REASON;if(raw==="explicit-restart"||raw==="autospawn")return raw;return env.ROVE_DAEMON_AUTOSPAWNED==="1"?"autospawn":"manual"}var SPAWN_LOCK_STALE_MS=40000,SPAWN_LOCK_WAIT_MS=30000;function tryAcquireSpawnLock(lockPath,staleMs=SPAWN_LOCK_STALE_MS){let create=()=>{return mkdirSync(dirname(lockPath),{recursive:!0}),closeSync(openSync(lockPath,"wx")),!0};try{return create()}catch{try{if(Date.now()-statSync(lockPath).mtimeMs<=staleMs)return!1;return unlinkSync(lockPath),create()}catch{return!1}}}async function ensureDaemonReachable(resolveSpawn=resolveRoveSpawn,spawnReason="autospawn"){let socketPath=defaultDaemonSocketPath(),state=await probeDaemonSocket(socketPath);if(state==="alive")return socketPath;if(state==="wedged"&&insideEngineSession())throw Error(`rove: daemon at ${socketPath} is not answering hello (busy or wedged); not restarting it from inside an engine session \u2014 retry, or run \`rove daemon restart\` from a regular shell`);let lockPath=`${defaultDaemonPidPath()}.spawn-lock`;if(!tryAcquireSpawnLock(lockPath)){let deadline=Date.now()+SPAWN_LOCK_WAIT_MS;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,150))}throw Error(`rove: another process is starting the daemon but it never became reachable at ${socketPath}; check ${defaultDaemonLogPath()} or run \`rove doctor\``)}try{if(await probeDaemonSocket(socketPath)==="alive")return socketPath;let livePid=await readPidFile(defaultDaemonPidPath());if(livePid!==null&&livePid!==process.pid&&isProcessAlive(livePid)){let deadline2=Date.now()+BUSY_DAEMON_GRACE_MS;while(Date.now()<deadline2){if(await new Promise((resolveTimer)=>setTimeout(resolveTimer,250)),await testDaemonResponds(socketPath))return socketPath;if(!isProcessAlive(livePid))break}}let[command,...args]=resolveSpawn(DAEMON_START_ARGS);await stopDaemonProcess(socketPath,defaultDaemonPidPath()).catch(()=>{}),spawnDetachedDaemon(command,args,autospawnDaemonEnv(process.env,spawnReason),defaultDaemonLogPath());let deadline=Date.now()+5000;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,100))}throw Error(`rove: daemon did not start (or stayed wedged) at ${socketPath}; check ${defaultDaemonLogPath()} or run \`rove doctor\``)}finally{try{unlinkSync(lockPath)}catch{}}}async function connectOrStartDaemon(spawnReason="autospawn"){let socketPath=await ensureDaemonReachable(resolveRoveSpawn,spawnReason),client=new RoveDaemonClient(socketPath);return await client.connect(),client}async function connectIfRunning(){let socketPath=defaultDaemonSocketPath();if(!await testDaemonResponds(socketPath))return null;let client=new RoveDaemonClient(socketPath);return await client.connect(),client}async function probeDaemonSocket(socketPath,timeoutMs=DAEMON_HELLO_TIMEOUT_MS){let probe=new RoveDaemonClient(socketPath);try{await probe.connect()}catch{return probe.close(),"absent"}let droppedByPeer=!1,offClose=probe.onLifecycle("close",()=>{droppedByPeer=!0}),replied=probe.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION}).then(()=>!0).catch(()=>!0),timer,timedOut=new Promise((resolve2)=>{timer=setTimeout(()=>resolve2(!1),timeoutMs)}),settled=await Promise.race([replied,timedOut]);if(timer)clearTimeout(timer);if(offClose(),probe.close(),droppedByPeer)return"absent";return settled?"alive":"wedged"}async function testDaemonResponds(socketPath,timeoutMs=DAEMON_HELLO_TIMEOUT_MS){return await probeDaemonSocket(socketPath,timeoutMs)==="alive"}class StaleInstallError extends Error{candidates;constructor(cliName,dir,candidates){super(`${cliName}: this process is running from an install that no longer exists on disk \u2014 no ${cliName} entry near ${dir} (checked ${candidates.join(", ")}). Reinstall (\`npm install -g @sma1lboy/rove\`) and relaunch Rove.`);this.name="StaleInstallError",this.candidates=candidates}}function isStaleInstallError(err){return err instanceof Error&&err.name==="StaleInstallError"}function resolveRoveSpawn(subcommand,env=process.env,moduleFile=fileURLToPath(import.meta.url)){let here=moduleFile;if(here.startsWith("/$bunfs")||here.startsWith("B:\\~BUN"))return[process.execPath,...subcommand];let dir=dirname(here),cliName=ROVE_PRODUCT_NAME,candidates=[resolve(dir,`../cli/${cliName}.ts`),resolve(dir,`../../../rove/src/cli/${cliName}.ts`),resolve(dir,`../cli/${cliName}.js`),resolve(dir,"../cli/index.ts"),resolve(dir,"../../../rove/src/cli/index.ts"),resolve(dir,"../cli/index.js")],entry=candidates.find((candidate)=>existsSync(candidate));if(entry)return[process.execPath,entry,...subcommand];throw new StaleInstallError(cliName,dir,candidates)}
2
+ import{stopDaemonProcess}from"./chunk-1e6jbj70.js";import{spawnDetachedDaemon}from"./chunk-y330t2bt.js";import{isProcessAlive,readPidFile}from"./chunk-b31cte10.js";import{DAEMON_PROTOCOL_VERSION,RoveDaemonClient}from"./chunk-fnsch8kr.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-z7zm8h1q.js";import{ROVE_PRODUCT_NAME}from"./chunk-nc46gddg.js";import{closeSync,existsSync,mkdirSync,openSync,statSync,unlinkSync}from"fs";import{dirname,resolve}from"path";import{fileURLToPath}from"url";var DAEMON_START_ARGS=["daemon","start"],DAEMON_HELLO_TIMEOUT_MS=3000,BUSY_DAEMON_GRACE_MS=15000;function insideEngineSession(env=process.env){return typeof env.ROVE_TASK_ID==="string"&&env.ROVE_TASK_ID!==""}function autospawnDaemonEnv(env=process.env,reason="autospawn"){let{ROVE_TASK_ID:_task,ROVE_TAB_ID:_tab,ROVE_TUI:_tui,ROVE_TERMINAL_PTY:_pty,ROVE_TASK_ID:_roveTask,ROVE_TAB_ID:_roveTab,ROVE_TUI:_roveTui,ROVE_TERMINAL_PTY:_rovePty,...rest}=env;return{...rest,ROVE_DAEMON_AUTOSPAWNED:"1",ROVE_DAEMON_SPAWN_REASON:reason}}function daemonSpawnReason(env=process.env){let raw=env.ROVE_DAEMON_SPAWN_REASON;if(raw==="explicit-restart"||raw==="autospawn")return raw;return env.ROVE_DAEMON_AUTOSPAWNED==="1"?"autospawn":"manual"}var SPAWN_LOCK_STALE_MS=40000,SPAWN_LOCK_WAIT_MS=30000;function tryAcquireSpawnLock(lockPath,staleMs=SPAWN_LOCK_STALE_MS){let create=()=>{return mkdirSync(dirname(lockPath),{recursive:!0}),closeSync(openSync(lockPath,"wx")),!0};try{return create()}catch{try{if(Date.now()-statSync(lockPath).mtimeMs<=staleMs)return!1;return unlinkSync(lockPath),create()}catch{return!1}}}async function ensureDaemonReachable(resolveSpawn=resolveRoveSpawn,spawnReason="autospawn"){let socketPath=defaultDaemonSocketPath(),state=await probeDaemonSocket(socketPath);if(state==="alive")return socketPath;if(state==="wedged"&&insideEngineSession())throw Error(`rove: daemon at ${socketPath} is not answering hello (busy or wedged); not restarting it from inside an engine session \u2014 retry, or run \`rove daemon restart\` from a regular shell`);let lockPath=`${defaultDaemonPidPath()}.spawn-lock`;if(!tryAcquireSpawnLock(lockPath)){let deadline=Date.now()+SPAWN_LOCK_WAIT_MS;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,150))}throw Error(`rove: another process is starting the daemon but it never became reachable at ${socketPath}; check ${defaultDaemonLogPath()} or run \`rove doctor\``)}try{if(await probeDaemonSocket(socketPath)==="alive")return socketPath;let livePid=await readPidFile(defaultDaemonPidPath());if(livePid!==null&&livePid!==process.pid&&isProcessAlive(livePid)){let deadline2=Date.now()+BUSY_DAEMON_GRACE_MS;while(Date.now()<deadline2){if(await new Promise((resolveTimer)=>setTimeout(resolveTimer,250)),await testDaemonResponds(socketPath))return socketPath;if(!isProcessAlive(livePid))break}}let[command,...args]=resolveSpawn(DAEMON_START_ARGS);await stopDaemonProcess(socketPath,defaultDaemonPidPath()).catch(()=>{}),spawnDetachedDaemon(command,args,autospawnDaemonEnv(process.env,spawnReason),defaultDaemonLogPath());let deadline=Date.now()+5000;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,100))}throw Error(`rove: daemon did not start (or stayed wedged) at ${socketPath}; check ${defaultDaemonLogPath()} or run \`rove doctor\``)}finally{try{unlinkSync(lockPath)}catch{}}}async function connectOrStartDaemon(spawnReason="autospawn"){let socketPath=await ensureDaemonReachable(resolveRoveSpawn,spawnReason),client=new RoveDaemonClient(socketPath);return await client.connect(),client}async function connectIfRunning(){let socketPath=defaultDaemonSocketPath();if(!await testDaemonResponds(socketPath))return null;let client=new RoveDaemonClient(socketPath);return await client.connect(),client}async function probeDaemonSocket(socketPath,timeoutMs=DAEMON_HELLO_TIMEOUT_MS){let probe=new RoveDaemonClient(socketPath);try{await probe.connect()}catch{return probe.close(),"absent"}let droppedByPeer=!1,offClose=probe.onLifecycle("close",()=>{droppedByPeer=!0}),replied=probe.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION}).then(()=>!0).catch(()=>!0),timer,timedOut=new Promise((resolve2)=>{timer=setTimeout(()=>resolve2(!1),timeoutMs)}),settled=await Promise.race([replied,timedOut]);if(timer)clearTimeout(timer);if(offClose(),probe.close(),droppedByPeer)return"absent";return settled?"alive":"wedged"}async function testDaemonResponds(socketPath,timeoutMs=DAEMON_HELLO_TIMEOUT_MS){return await probeDaemonSocket(socketPath,timeoutMs)==="alive"}class StaleInstallError extends Error{candidates;constructor(cliName,dir,candidates){super(`${cliName}: this process is running from an install that no longer exists on disk \u2014 no ${cliName} entry near ${dir} (checked ${candidates.join(", ")}). Reinstall (\`npm install -g @sma1lboy/rove\`) and relaunch Rove.`);this.name="StaleInstallError",this.candidates=candidates}}function isStaleInstallError(err){return err instanceof Error&&err.name==="StaleInstallError"}function resolveRoveSpawn(subcommand,env=process.env,moduleFile=fileURLToPath(import.meta.url)){let here=moduleFile;if(here.startsWith("/$bunfs")||here.startsWith("B:\\~BUN"))return[process.execPath,...subcommand];let dir=dirname(here),cliName=ROVE_PRODUCT_NAME,candidates=[resolve(dir,`../cli/${cliName}.ts`),resolve(dir,`../../../rove/src/cli/${cliName}.ts`),resolve(dir,`../cli/${cliName}.js`),resolve(dir,"../cli/index.ts"),resolve(dir,"../../../rove/src/cli/index.ts"),resolve(dir,"../cli/index.js")],entry=candidates.find((candidate)=>existsSync(candidate));if(entry)return[process.execPath,entry,...subcommand];throw new StaleInstallError(cliName,dir,candidates)}
3
3
  export{autospawnDaemonEnv,daemonSpawnReason,tryAcquireSpawnLock,ensureDaemonReachable,connectOrStartDaemon,connectIfRunning,probeDaemonSocket,testDaemonResponds,StaleInstallError,isStaleInstallError,resolveRoveSpawn};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{toTaskId}from"./chunk-xy8be792.js";import{coerceVendorId}from"./chunk-h2m7em1e.js";import{DAEMON_MIGRATION_MARKER}from"./chunk-tdhk4dz8.js";import{LockfileError,acquire}from"./chunk-qk5f6p3e.js";import{logClient}from"./chunk-y55zpren.js";import{defaultClientLogPath}from"./chunk-z7zm8h1q.js";import{existsSync}from"fs";import{copyFile,readFile}from"fs/promises";import{dirname,join}from"path";function coerceTask(value){if(!value||typeof value!=="object")return null;let v=value;if(typeof v.id!=="string"||typeof v.title!=="string"||typeof v.repo!=="string"||typeof v.branch!=="string"||typeof v.worktreePath!=="string"||typeof v.status!=="string"||typeof v.createdAt!=="string"||typeof v.updatedAt!=="string")return null;if(!isTaskStatus(v.status))return null;let kind=v.kind==="main"?"main":v.kind==="dir"?"dir":"task",scratch=kind==="dir"&&v.scratch===!0,healedStatus=kind==="main"&&(v.status==="in_progress"||v.status==="done")?"backlog":v.status,deletion=coerceDeletion(v.deletion),quotaResume=coerceQuotaResume(v.quotaResume),linkedWorkItem=coerceLinkedWorkItem(v.linkedWorkItem),dispatcher=coerceDispatcher(v.dispatcher),routine=coerceRoutine(v.routine),report=coerceWorkerReport(v.report);return{id:toTaskId(v.id),title:v.title,repo:v.repo,branch:v.branch,worktreePath:v.worktreePath,status:healedStatus,pinned:typeof v.pinned==="boolean"?v.pinned:!1,kind,...scratch?{scratch:!0}:{},...routine?{routine}:{},vendor:coerceVendorId(typeof v.vendor==="string"?v.vendor:void 0),...typeof v.command==="string"&&v.command.trim().length>0?{command:v.command}:{},prStatus:coercePRStatus(v.prStatus),...typeof v.modelEffort==="string"&&v.modelEffort.length>0?{modelEffort:v.modelEffort}:{},...typeof v.model==="string"&&v.model.length>0?{model:v.model}:{},...typeof v.tier==="string"&&v.tier.length>0?{tier:v.tier}:{},...typeof v.groupId==="string"&&v.groupId.length>0?{groupId:v.groupId}:{},...v.observedLanguage==="zh"||v.observedLanguage==="en"?{observedLanguage:v.observedLanguage}:{},...deletion?{deletion}:{},...quotaResume?{quotaResume}:{},...linkedWorkItem?{linkedWorkItem}:{},...dispatcher?{dispatcher}:{},...typeof v.prompt==="string"&&v.prompt.length>0?{prompt:v.prompt}:{},...typeof v.baseRef==="string"&&v.baseRef.trim().length>0?{baseRef:v.baseRef}:{},...typeof v.worktreeName==="string"&&v.worktreeName.trim().length>0?{worktreeName:v.worktreeName}:{},...report?{report}:{},...v.requireReport===!0?{requireReport:!0}:{},createdAt:v.createdAt,updatedAt:v.updatedAt}}function coerceWorkerReport(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;return{at:v.at,...typeof v.branch==="string"&&v.branch.length>0?{branch:v.branch}:{},...typeof v.pr==="number"&&Number.isFinite(v.pr)?{pr:v.pr}:{},...typeof v.summary==="string"&&v.summary.length>0?{summary:v.summary}:{}}}function coerceDispatcher(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.taskId!=="string"||v.taskId.length===0)return;if(typeof v.tabId!=="string"||v.tabId.length===0)return;return{taskId:v.taskId,tabId:v.tabId}}function coerceRoutine(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.automationId!=="string"||v.automationId.length===0)return;return{automationId:v.automationId}}function coerceQuotaResume(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.resumeAt!=="string"||v.resumeAt.length===0)return;if(typeof v.requestedAt!=="string"||v.requestedAt.length===0)return;return{resumeAt:v.resumeAt,requestedAt:v.requestedAt}}function coerceLinkedWorkItem(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.provider!=="github")return;if(v.type!=="issue"&&v.type!=="pr")return;if(typeof v.number!=="number"||!Number.isFinite(v.number))return;if(typeof v.title!=="string"||typeof v.url!=="string"||v.url.length===0)return;return{provider:v.provider,type:v.type,number:v.number,title:v.title,url:v.url}}function coerceDeletion(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.phase!=="queued"&&v.phase!=="running"&&v.phase!=="error"||typeof v.force!=="boolean"||typeof v.requestedAt!=="string"||v.requestedAt.length===0||v.error!==void 0&&typeof v.error!=="string")return;return{phase:v.phase,force:v.force,...typeof v.deleteBranch==="boolean"?{deleteBranch:v.deleteBranch}:{},requestedAt:v.requestedAt,...typeof v.error==="string"?{error:v.error}:{}}}function coercePRStatus(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(!isPRProviderId(v.provider)||!isPRLifecycleState(v.lifecycle)||!isPRCheckState(v.checkState))return;return{provider:v.provider,lifecycle:v.lifecycle,checkState:v.checkState,...typeof v.number==="number"&&Number.isFinite(v.number)?{number:v.number}:{},...typeof v.url==="string"?{url:v.url}:{},...typeof v.title==="string"?{title:v.title}:{},...typeof v.baseRef==="string"?{baseRef:v.baseRef}:{},...typeof v.reviewDecision==="string"?{reviewDecision:v.reviewDecision}:{},...typeof v.mergeable==="string"?{mergeable:v.mergeable}:{},...typeof v.lastCheckedAt==="string"?{lastCheckedAt:v.lastCheckedAt}:{},...typeof v.lastError==="string"?{lastError:v.lastError}:{}}}function isPRProviderId(v){return v==="github"||v==="gitlab"||v==="bitbucket"||v==="unknown"}function isPRLifecycleState(v){return v==="creating"||v==="open"||v==="ready_to_merge"||v==="merged"||v==="closed"||v==="unknown"}function isPRCheckState(v){return v==="none"||v==="pending"||v==="passing"||v==="failing"||v==="unknown"}function isTaskStatus(s){return s==="backlog"||s==="in_progress"||s==="in_review"||s==="done"||s==="canceled"||s==="error"}var sleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),LOCK_RETRY_DELAY_MS=25,LOCK_MAX_WAIT_MS=5000;async function acquireWithRetry(lockPath){let deadline=Date.now()+LOCK_MAX_WAIT_MS;for(;;)try{return await acquire(lockPath)}catch(err){if(!(err instanceof LockfileError)||Date.now()>=deadline)throw err;await sleep(LOCK_RETRY_DELAY_MS)}}var CURRENT_VERSION=3;async function backupCorruptManifest(path,now=()=>new Date){let backupPath=`${path}.corrupt-${now().toISOString().replaceAll(":","-")}`;try{return await copyFile(path,backupPath),backupPath}catch{return null}}var SUPPORTED_VERSIONS=new Set([1,2,3]);function warnManifestRecovery(message,manifestPath){console.warn(message),logClient("tasks-index",message,manifestPath?defaultClientLogPath(dirname(dirname(manifestPath))):void 0)}async function recoverUnsupportedVersion(parsed,sourcePath){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return!1;let version=parsed.version;if(version===void 0||SUPPORTED_VERSIONS.has(version))return!1;let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} has unsupported version=${String(version)}; recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),!0}function normalizeIndex(parsed,source){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return warnManifestRecovery(`[rove] tasks.json at ${source} is not an object; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let obj=parsed,version=obj.version;if(version!==void 0&&!SUPPORTED_VERSIONS.has(version))return warnManifestRecovery(`[rove] tasks.json at ${source} has unsupported version=${String(version)}; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let rawTasks=Array.isArray(obj.tasks)?obj.tasks:[],tasks=[];for(let entry of rawTasks){let task=coerceTask(entry);if(task)tasks.push(task);else console.warn(`[rove] dropping malformed task entry from ${source}: ${JSON.stringify(entry)}`)}return{version:CURRENT_VERSION,tasks}}var TOMBSTONE_TTL_MS=2592000000;function readableLegacyIndexPath(canonicalPath,legacyPath){return existsSync(join(dirname(canonicalPath),DAEMON_MIGRATION_MARKER))?void 0:legacyPath}async function readDiskIndex(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(sourcePath,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath);if(!legacy)return{tasks:[],removed:[]};sourcePath=legacy;try{raw=await readFile(sourcePath,"utf8")}catch(legacyErr){if(legacyErr.code==="ENOENT")return{tasks:[],removed:[]};throw legacyErr}}let parsed;try{parsed=JSON.parse(raw)}catch{return await backupCorruptManifest(sourcePath),{tasks:[],removed:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{tasks:[],removed:[]};return{tasks:normalizeIndex(parsed,sourcePath).tasks,removed:coerceTombstones(parsed)}}function coerceTombstones(parsed){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return[];let raw=parsed.removed;if(!Array.isArray(raw))return[];let out=[];for(let entry of raw){if(!entry||typeof entry!=="object")continue;let v=entry;if(typeof v.id==="string"&&v.id.length>0&&typeof v.at==="string")out.push({id:v.id,at:v.at})}return out}function mergeTasksWithDisk(cacheTasks,diskTasks,dirty,removed,diskRemoved=[],now=Date.now()){let tombstones=new Map;for(let t of diskRemoved){let at=Date.parse(t.at);if(!Number.isFinite(at)||now-at>TOMBSTONE_TTL_MS)continue;tombstones.set(t.id,t.at)}for(let[id,at]of removed)tombstones.set(id,at);let diskById=new Map(diskTasks.map((t)=>[t.id,t])),result=[],included=new Set;for(let task of cacheTasks){if(tombstones.has(task.id))continue;if(dirty.has(task.id))result.push(task);else{let onDisk=diskById.get(task.id);if(onDisk===void 0)continue;result.push(onDisk)}included.add(task.id)}for(let task of diskTasks){if(included.has(task.id)||tombstones.has(task.id))continue;result.push(task),included.add(task.id)}return{tasks:result,removed:[...tombstones].map(([id,at])=>({id,at}))}}async function recoverIndexFromDisk(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(path,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath),legacyRaw;if(legacy)try{legacyRaw=await readFile(legacy,"utf8"),sourcePath=legacy}catch(legacyErr){if(legacyErr.code!=="ENOENT")throw legacyErr}if(legacyRaw===void 0)return{version:CURRENT_VERSION,tasks:[]};raw=legacyRaw}let parsed;try{parsed=JSON.parse(raw)}catch(err){let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} is corrupted (${err.message}); recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),{version:CURRENT_VERSION,tasks:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{version:CURRENT_VERSION,tasks:[]};return normalizeIndex(parsed,sourcePath)}
3
+ export{acquireWithRetry,readableLegacyIndexPath,readDiskIndex,mergeTasksWithDisk,recoverIndexFromDisk};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{defaultClientLogPath,defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultDeliveriesPath,defaultDeliveryLockDir,defaultPtyExitsPath,defaultPtyFreezeDir,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath,defaultWebTokenPath,fitSocketPath,isWindowsPipePath,resolveDaemonHomeDir,shortHomeTag,windowsPipePath}from"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{windowsPipePath,shortHomeTag,resolveDaemonHomeDir,isWindowsPipePath,fitSocketPath,defaultWebTokenPath,defaultPtyHostSocketPath,defaultPtyHostPidPath,defaultPtyHostLogPath,defaultPtyFreezeDir,defaultPtyExitsPath,defaultDeliveryLockDir,defaultDeliveriesPath,defaultDaemonSocketPath,defaultDaemonPidPath,defaultDaemonLogPath,defaultClientLogPath};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{acquireSync,releaseSync}from"./chunk-mw0ysrpd.js";import{kvStatePath}from"./chunk-prqeddy7.js";import{mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import{dirname}from"path";var corruptWarned=!1;function readSavedRepos(state){let raw=state.savedRepos;if(!Array.isArray(raw))return[];return raw.filter((entry)=>typeof entry==="string")}function loadStateFile(){return readStateFile(!1)}function readStateFile(ownsLock){let path=kvStatePath(),text;try{text=readFileSync(path,"utf8")}catch{return{}}try{let parsed=JSON.parse(text);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed))return parsed}catch{}if(!ownsLock){let lockPath=`${path}.lock`,token;try{token=acquireSync(lockPath,0)}catch{return{}}try{return readStateFile(!0)}finally{releaseSync(lockPath,token)}}try{if(renameSync(path,`${path}.corrupt-${Date.now()}`),!corruptWarned)corruptWarned=!0,console.error(`[rove] ${path} is corrupted; backed up and starting fresh.`)}catch{}return{}}function readStateFileStrict(){let path=kvStatePath(),text;try{text=readFileSync(path,"utf8")}catch(err){if(err.code==="ENOENT")return{};throw err}let parsed=JSON.parse(text);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`${path} is not a JSON object`);return parsed}function writeStateFile(state){let path=kvStatePath();mkdirSync(dirname(path),{recursive:!0});let nonce=Math.random().toString(36).slice(2),tmp=`${path}.${process.pid}.${nonce}.tmp`;writeFileSync(tmp,JSON.stringify(state),{encoding:"utf8",mode:384}),renameSync(tmp,path)}function updateStateFile(mutate,readMode="recover"){let lockPath=`${kvStatePath()}.lock`,token=acquireSync(lockPath);try{let state=readMode==="strict"?readStateFileStrict():readStateFile(!0);if(mutate(state)!==!1)writeStateFile(state);return state}finally{releaseSync(lockPath,token)}}function patchStateFile(patch,readMode="recover"){return updateStateFile((state)=>{for(let[key,value]of Object.entries(patch))if(value===void 0)delete state[key];else state[key]=value;return},readMode)}function getPersistedBool(key,defaultValue){let value=loadStateFile()[key];return typeof value==="boolean"?value:defaultValue}function setPersistedBool(key,value){patchStateFile({[key]:value})}function replaceStateFile(snapshot){updateStateFile((state)=>{for(let key of Object.keys(state))delete state[key];Object.assign(state,snapshot);return})}
2
+ import{acquireSync,releaseSync}from"./chunk-qk5f6p3e.js";import{kvStatePath}from"./chunk-prqeddy7.js";import{mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import{dirname}from"path";var corruptWarned=!1;function readSavedRepos(state){let raw=state.savedRepos;if(!Array.isArray(raw))return[];return raw.filter((entry)=>typeof entry==="string")}function loadStateFile(){return readStateFile(!1)}function readStateFile(ownsLock){let path=kvStatePath(),text;try{text=readFileSync(path,"utf8")}catch{return{}}try{let parsed=JSON.parse(text);if(parsed&&typeof parsed==="object"&&!Array.isArray(parsed))return parsed}catch{}if(!ownsLock){let lockPath=`${path}.lock`,token;try{token=acquireSync(lockPath,0)}catch{return{}}try{return readStateFile(!0)}finally{releaseSync(lockPath,token)}}try{if(renameSync(path,`${path}.corrupt-${Date.now()}`),!corruptWarned)corruptWarned=!0,console.error(`[rove] ${path} is corrupted; backed up and starting fresh.`)}catch{}return{}}function readStateFileStrict(){let path=kvStatePath(),text;try{text=readFileSync(path,"utf8")}catch(err){if(err.code==="ENOENT")return{};throw err}let parsed=JSON.parse(text);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw Error(`${path} is not a JSON object`);return parsed}function writeStateFile(state){let path=kvStatePath();mkdirSync(dirname(path),{recursive:!0});let nonce=Math.random().toString(36).slice(2),tmp=`${path}.${process.pid}.${nonce}.tmp`;writeFileSync(tmp,JSON.stringify(state),{encoding:"utf8",mode:384}),renameSync(tmp,path)}function updateStateFile(mutate,readMode="recover"){let lockPath=`${kvStatePath()}.lock`,token=acquireSync(lockPath);try{let state=readMode==="strict"?readStateFileStrict():readStateFile(!0);if(mutate(state)!==!1)writeStateFile(state);return state}finally{releaseSync(lockPath,token)}}function patchStateFile(patch,readMode="recover"){return updateStateFile((state)=>{for(let[key,value]of Object.entries(patch))if(value===void 0)delete state[key];else state[key]=value;return},readMode)}function getPersistedBool(key,defaultValue){let value=loadStateFile()[key];return typeof value==="boolean"?value:defaultValue}function setPersistedBool(key,value){patchStateFile({[key]:value})}function replaceStateFile(snapshot){updateStateFile((state)=>{for(let key of Object.keys(state))delete state[key];Object.assign(state,snapshot);return})}
3
3
  export{readSavedRepos,loadStateFile,readStateFileStrict,updateStateFile,patchStateFile,getPersistedBool,setPersistedBool,replaceStateFile};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{tightenFilePermissions}from"./chunk-yt15y085.js";import{isWindowsPipePath}from"./chunk-npwzmmv9.js";import{readFile,stat,unlink}from"fs/promises";var DEFAULT_SOCKET_WATCH_MS=5000;async function listenOnUnixSocket(server,socketPath){if(await new Promise((resolve,reject)=>{let evented=server;evented.once("error",reject),server.listen(socketPath,()=>{evented.removeListener("error",reject),resolve()})}),!isWindowsPipePath(socketPath))await tightenFilePermissions(socketPath)}function isProcessAlive(pid){if(!Number.isInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(err){return err.code!=="ESRCH"}}async function readPidFile(pidPath){try{let raw=await readFile(pidPath,"utf8"),pid=Number(raw.trim());return Number.isInteger(pid)&&pid>1?pid:null}catch{return null}}function createSocketOwnershipGuard(options){let watchMs=options.watchMs??DEFAULT_SOCKET_WATCH_MS,stamp=null,lost=!1,timer=null,currentStamp=async()=>{try{let s=await stat(options.socketPath);return{dev:s.dev,ino:s.ino}}catch(err){return err.code==="ENOENT"?null:"error"}},stopTimer=()=>{if(timer)clearInterval(timer);timer=null},verify=async()=>{if(stamp===null||lost)return;let now=await currentStamp();if(now==="error")return;if(now===null||now.dev!==stamp.dev||now.ino!==stamp.ino)lost=!0},check=async()=>{if(stamp===null||lost)return;if(await verify(),!lost)return;stopTimer(),options.onLost()};return{async arm(){let now=await currentStamp();if(now===null||now==="error")return;if(stamp=now,watchMs>0)timer=setInterval(()=>void check(),watchMs),timer.unref?.()},async release(server){if(stopTimer(),await verify(),stamp===null||lost){server.unref();return}await new Promise((resolve)=>server.close(()=>resolve())),await unlink(options.socketPath).catch(()=>{}),await unlink(options.pidPath).catch(()=>{})}}}
2
+ import{tightenFilePermissions}from"./chunk-yt15y085.js";import{isWindowsPipePath}from"./chunk-z7zm8h1q.js";import{readFile,stat,unlink}from"fs/promises";var DEFAULT_SOCKET_WATCH_MS=5000;async function listenOnUnixSocket(server,socketPath){if(await new Promise((resolve,reject)=>{let evented=server;evented.once("error",reject),server.listen(socketPath,()=>{evented.removeListener("error",reject),resolve()})}),!isWindowsPipePath(socketPath))await tightenFilePermissions(socketPath)}function isProcessAlive(pid){if(!Number.isInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch(err){return err.code!=="ESRCH"}}async function readPidFile(pidPath){try{let raw=await readFile(pidPath,"utf8"),pid=Number(raw.trim());return Number.isInteger(pid)&&pid>1?pid:null}catch{return null}}function createSocketOwnershipGuard(options){let watchMs=options.watchMs??DEFAULT_SOCKET_WATCH_MS,stamp=null,lost=!1,timer=null,currentStamp=async()=>{try{let s=await stat(options.socketPath);return{dev:s.dev,ino:s.ino}}catch(err){return err.code==="ENOENT"?null:"error"}},stopTimer=()=>{if(timer)clearInterval(timer);timer=null},verify=async()=>{if(stamp===null||lost)return;let now=await currentStamp();if(now==="error")return;if(now===null||now.dev!==stamp.dev||now.ino!==stamp.ino)lost=!0},check=async()=>{if(stamp===null||lost)return;if(await verify(),!lost)return;stopTimer(),options.onLost()};return{async arm(){let now=await currentStamp();if(now===null||now==="error")return;if(stamp=now,watchMs>0)timer=setInterval(()=>void check(),watchMs),timer.unref?.()},async release(server){if(stopTimer(),await verify(),stamp===null||lost){server.unref();return}await new Promise((resolve)=>server.close(()=>resolve())),await unlink(options.socketPath).catch(()=>{}),await unlink(options.pidPath).catch(()=>{})}}}
3
3
  export{listenOnUnixSocket,isProcessAlive,readPidFile,createSocketOwnershipGuard};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{describeRepoInitSources,missingDependenciesCoda,resolveEngineLaunchInit,resolveRepoInit}from"./chunk-r0etyq15.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-21ek142k.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-zk5qkkb1.js";import"./chunk-mw0ysrpd.js";import"./chunk-a7kq09ke.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-npwzmmv9.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{resolveRepoInit,resolveEngineLaunchInit,missingDependenciesCoda,describeRepoInitSources};
2
+ import{describeRepoInitSources,missingDependenciesCoda,resolveEngineLaunchInit,resolveRepoInit}from"./chunk-08ycv55d.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{resolveRepoInit,resolveEngineLaunchInit,missingDependenciesCoda,describeRepoInitSources};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Orchestrator}from"./chunk-pkq8n3gs.js";import"./chunk-tmz0wzq8.js";import"./chunk-68gxqtse.js";import"./chunk-f6836h0n.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-cbc1h345.js";import"./chunk-1mpheecn.js";import"./chunk-41x1hrqe.js";import"./chunk-dehnv06q.js";import"./chunk-sak1tphp.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-2tfnscxk.js";import"./chunk-m6qv5rsv.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-b7xjhgts.js";import"./chunk-2brn8e1y.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cmp64q4j.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{PLACEHOLDER_TASK_TITLE,Orchestrator};