@sma1lboy/rove 0.9.310-next.576 → 0.9.310-next.578

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 (125) hide show
  1. package/dist/cli/{chunk-np8p2080.js → chunk-03xmw1mv.js} +1 -1
  2. package/dist/cli/chunk-0jskz95t.js +2 -0
  3. package/dist/cli/{chunk-seg8143s.js → chunk-0xhgwjmx.js} +1 -1
  4. package/dist/cli/chunk-12yy593m.js +3 -0
  5. package/dist/cli/{chunk-wv0471pd.js → chunk-1bpmn0xt.js} +1 -1
  6. package/dist/cli/chunk-1cye0btk.js +3 -0
  7. package/dist/cli/{chunk-785c8xtm.js → chunk-1jp3vdzc.js} +1 -1
  8. package/dist/cli/{chunk-11dtgrr8.js → chunk-1wf54d5g.js} +1 -1
  9. package/dist/cli/chunk-2dhwra79.js +2 -0
  10. package/dist/cli/{chunk-cemc0hsn.js → chunk-2h4n5nns.js} +1 -1
  11. package/dist/cli/{chunk-16rp8nn7.js → chunk-336z42rb.js} +1 -1
  12. package/dist/cli/{chunk-z7jd560f.js → chunk-36kzy6a8.js} +1 -1
  13. package/dist/cli/{chunk-1ajd27b1.js → chunk-3d168p3v.js} +1 -1
  14. package/dist/cli/{chunk-c4kr46da.js → chunk-3eqhtvm1.js} +1 -1
  15. package/dist/cli/{chunk-w95nbs2v.js → chunk-4k84q913.js} +1 -1
  16. package/dist/cli/{chunk-fxjkrbj7.js → chunk-57rv7bn2.js} +1 -1
  17. package/dist/cli/{chunk-47r438mg.js → chunk-5bqcp71x.js} +1 -1
  18. package/dist/cli/{chunk-0ha5ne2c.js → chunk-5z9d1bdy.js} +1 -1
  19. package/dist/cli/{chunk-jgj05ar6.js → chunk-5zn86aed.js} +1 -1
  20. package/dist/cli/{chunk-p55es0nf.js → chunk-6bxdexbq.js} +1 -1
  21. package/dist/cli/{chunk-62b9mm81.js → chunk-6n9wzp5t.js} +1 -1
  22. package/dist/cli/{chunk-hpgeyq7e.js → chunk-6wypjhy8.js} +1 -1
  23. package/dist/cli/{chunk-evf15cs5.js → chunk-7cm66y22.js} +2 -2
  24. package/dist/cli/{chunk-k2fb370k.js → chunk-7ewphe3a.js} +1 -1
  25. package/dist/cli/{chunk-ag4bgs6x.js → chunk-7hnsdaj9.js} +1 -1
  26. package/dist/cli/{chunk-kn7vqxfv.js → chunk-7yh6k6sf.js} +1 -1
  27. package/dist/cli/chunk-8045zyyy.js +2 -0
  28. package/dist/cli/chunk-85cqv9te.js +2 -0
  29. package/dist/cli/{chunk-6926g5q3.js → chunk-88590vqy.js} +1 -1
  30. package/dist/cli/{chunk-vh82t8c3.js → chunk-8rr7mv60.js} +1 -1
  31. package/dist/cli/{chunk-6dnxy1cr.js → chunk-97nfzddk.js} +1 -1
  32. package/dist/cli/{chunk-c1va68mx.js → chunk-9c06ccvf.js} +6 -6
  33. package/dist/cli/{chunk-vpk5m2z6.js → chunk-9c723k0b.js} +1 -1
  34. package/dist/cli/{chunk-dfap5t5n.js → chunk-9g1a80xf.js} +1 -1
  35. package/dist/cli/chunk-9marhcac.js +2 -0
  36. package/dist/cli/{chunk-57atdjmz.js → chunk-9sq4jh9k.js} +1 -1
  37. package/dist/cli/{chunk-j5bf5vac.js → chunk-a0htfj15.js} +4 -4
  38. package/dist/cli/{chunk-2q20kf2r.js → chunk-a1kp5arm.js} +1 -1
  39. package/dist/cli/{chunk-12s0srrp.js → chunk-anttfbrv.js} +1 -1
  40. package/dist/cli/chunk-awerm3vq.js +3 -0
  41. package/dist/cli/{chunk-8675zams.js → chunk-ba24d86x.js} +2 -2
  42. package/dist/cli/{chunk-jc0a959d.js → chunk-bhfmnj61.js} +1 -1
  43. package/dist/cli/{chunk-rzgt8znt.js → chunk-bmnmhva5.js} +1 -1
  44. package/dist/cli/{chunk-cbzdrs5q.js → chunk-bmt3fwpx.js} +1 -1
  45. package/dist/cli/{chunk-719g5sdr.js → chunk-c1wz9mja.js} +1 -1
  46. package/dist/cli/{chunk-f1rkchnb.js → chunk-c8m9b7mt.js} +1 -1
  47. package/dist/cli/{chunk-8bv7ea27.js → chunk-dm8dew4k.js} +9 -9
  48. package/dist/cli/{chunk-mytwyyej.js → chunk-e33eejqa.js} +1 -1
  49. package/dist/cli/{chunk-0k3r20n2.js → chunk-ea2dtx41.js} +1 -1
  50. package/dist/cli/{chunk-x9pyz29j.js → chunk-eemkpbmm.js} +2 -2
  51. package/dist/cli/{chunk-r4vwq5wv.js → chunk-fczxyfgn.js} +1 -1
  52. package/dist/cli/{chunk-5rxef858.js → chunk-fj7nj0vy.js} +1 -1
  53. package/dist/cli/chunk-fqdx10w8.js +3 -0
  54. package/dist/cli/{chunk-0697addz.js → chunk-fwfd7s00.js} +1 -1
  55. package/dist/cli/{chunk-2mjky7c1.js → chunk-fx2jcsqg.js} +1 -1
  56. package/dist/cli/{chunk-xb8x99se.js → chunk-g2n9z1ed.js} +1 -1
  57. package/dist/cli/{chunk-qbd69xdf.js → chunk-gbcyjs7c.js} +1 -1
  58. package/dist/cli/{chunk-cex17awh.js → chunk-geac4b8s.js} +1 -1
  59. package/dist/cli/{chunk-t4zxjveq.js → chunk-ghfqyrbr.js} +1 -1
  60. package/dist/cli/{chunk-k5eg5yyz.js → chunk-gt4wtnv0.js} +1 -1
  61. package/dist/cli/{chunk-q04f1v0q.js → chunk-h407rq50.js} +1 -1
  62. package/dist/cli/{chunk-68avd0fp.js → chunk-hb4rfryf.js} +3 -2
  63. package/dist/cli/{chunk-t4gdpxey.js → chunk-hckdnyhz.js} +2 -2
  64. package/dist/cli/chunk-hdea2ss8.js +3 -0
  65. package/dist/cli/{chunk-sp7marmf.js → chunk-j8byht57.js} +1 -1
  66. package/dist/cli/{chunk-h45zwz97.js → chunk-jnbjf6t4.js} +2 -2
  67. package/dist/cli/{chunk-8ka3rkq0.js → chunk-jw8fp9fk.js} +1 -1
  68. package/dist/cli/{chunk-v8ms64g1.js → chunk-kr7jw1s4.js} +1 -1
  69. package/dist/cli/{chunk-58gz8k9a.js → chunk-ksqstg9v.js} +1 -1
  70. package/dist/cli/{chunk-1wsx4qrz.js → chunk-m8zppjrn.js} +1 -1
  71. package/dist/cli/{chunk-7dy9dtnd.js → chunk-n5at7bsq.js} +1 -1
  72. package/dist/cli/chunk-n9v5x83q.js +8 -0
  73. package/dist/cli/{chunk-b43gbrar.js → chunk-nbfxhvby.js} +1 -1
  74. package/dist/cli/{chunk-rabsnprp.js → chunk-nt29jven.js} +1 -1
  75. package/dist/cli/{chunk-xmwrg55j.js → chunk-pk67ddfn.js} +1 -1
  76. package/dist/cli/{chunk-tsmybvy0.js → chunk-ps4srps8.js} +1 -1
  77. package/dist/cli/{chunk-x729vdm1.js → chunk-q1tm27sa.js} +1 -1
  78. package/dist/cli/{chunk-xdmamqy7.js → chunk-q5agazsv.js} +1 -1
  79. package/dist/cli/{chunk-57gqbn7j.js → chunk-qgewm52d.js} +1 -1
  80. package/dist/cli/{chunk-tdzdrnse.js → chunk-qpemynnh.js} +1 -1
  81. package/dist/cli/{chunk-z2vgeqbx.js → chunk-qq2arpfc.js} +1 -1
  82. package/dist/cli/{chunk-dn2xnk1r.js → chunk-qxkw8jf3.js} +1 -1
  83. package/dist/cli/{chunk-g8w7rhdn.js → chunk-r7djnsc6.js} +1 -1
  84. package/dist/cli/{chunk-37tn3t78.js → chunk-rhns2ryg.js} +1 -1
  85. package/dist/cli/{chunk-sy81vcaz.js → chunk-s2b2nfeb.js} +1 -1
  86. package/dist/cli/{chunk-4yjj71gy.js → chunk-sadhbjbv.js} +1 -1
  87. package/dist/cli/{chunk-sqb58cas.js → chunk-snzvrmzv.js} +1 -1
  88. package/dist/cli/{chunk-t4jnss0g.js → chunk-t262wrra.js} +2 -2
  89. package/dist/cli/chunk-tsxrab2f.js +2 -0
  90. package/dist/cli/{chunk-cfb6mvz5.js → chunk-vk8t0x7q.js} +1 -1
  91. package/dist/cli/{chunk-ryfvgfan.js → chunk-vrcn6zhe.js} +1 -1
  92. package/dist/cli/{chunk-tyq1tvdh.js → chunk-w2cf7bgt.js} +1 -1
  93. package/dist/cli/{chunk-c0af07nt.js → chunk-w9fdfcnc.js} +1 -1
  94. package/dist/cli/chunk-wxrbpxzx.js +3 -0
  95. package/dist/cli/{chunk-7ab1mvwq.js → chunk-xqa97kez.js} +1 -1
  96. package/dist/cli/{chunk-8j69a8dk.js → chunk-xzxzycng.js} +1 -1
  97. package/dist/cli/{chunk-wzvantp2.js → chunk-ykmfwmb3.js} +1 -1
  98. package/dist/cli/{chunk-zjteszk4.js → chunk-ytkkzf1x.js} +1 -1
  99. package/dist/cli/{chunk-141k131d.js → chunk-zmxmmt9e.js} +1 -1
  100. package/dist/cli/{chunk-c0xxw2hd.js → chunk-zp78250b.js} +1 -1
  101. package/dist/cli/{chunk-bn8nrqde.js → chunk-zvnzy679.js} +1 -1
  102. package/dist/cli/{chunk-9k3360sv.js → chunk-zwb8jycx.js} +6 -6
  103. package/dist/cli/index.js +3 -3
  104. package/dist/cli/rove.js +1 -1
  105. package/dist/skills/rove/SKILL.md +6 -3
  106. package/dist/skills/rove/references/api-flags.md +6 -1
  107. package/dist/web/assets/{index-BxUzG7oh.js → index-4CEnphOo.js} +3 -3
  108. package/dist/web/assets/{term-mount-Bcpe_vHC.js → term-mount-CxcHHCla.js} +1 -1
  109. package/dist/web/index.html +1 -1
  110. package/dist/web/relay-client/assets/{index-CGKsaV-C.js → index-DmPkYEMp.js} +1 -1
  111. package/dist/web/relay-client/index.html +1 -1
  112. package/package.json +1 -1
  113. package/dist/cli/chunk-2rjm2p4k.js +0 -2
  114. package/dist/cli/chunk-3xjenrkd.js +0 -2
  115. package/dist/cli/chunk-3zz0zksx.js +0 -4
  116. package/dist/cli/chunk-412zrrg1.js +0 -2
  117. package/dist/cli/chunk-484edssp.js +0 -3
  118. package/dist/cli/chunk-6xqqjvht.js +0 -2
  119. package/dist/cli/chunk-7ewmprex.js +0 -8
  120. package/dist/cli/chunk-aena2jzj.js +0 -3
  121. package/dist/cli/chunk-axycrfkq.js +0 -3
  122. package/dist/cli/chunk-eqz170td.js +0 -2
  123. package/dist/cli/chunk-m74qxqw0.js +0 -3
  124. package/dist/cli/chunk-wbjzydbg.js +0 -3
  125. package/dist/cli/chunk-xz52we91.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{CURRENT_VERSION}from"./chunk-tdzdrnse.js";import{ensureMcpForwards,machineMcp}from"./chunk-6qwjd3da.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import{flagValue}from"./chunk-78y80xe8.js";import"./chunk-nks2q6d9.js";import{quoteShellArg}from"./chunk-ptyqj15s.js";import"./chunk-pn5ygqn6.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir));else if(args[0]==="mcp-hook"){let ws=readRemoteWorkspace(dir);if(ws)ensureMcpForwards(ws.machine,machineMcp(ws.machine))}}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}var ROVE_COMMAND=/^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*\/)?rove(?:\s|$)/;function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command)||ROVE_COMMAND.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
2
+ import{CURRENT_VERSION}from"./chunk-qpemynnh.js";import{ensureMcpForwards,machineMcp}from"./chunk-6qwjd3da.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import{flagValue}from"./chunk-78y80xe8.js";import"./chunk-nks2q6d9.js";import{quoteShellArg}from"./chunk-ptyqj15s.js";import"./chunk-pn5ygqn6.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir));else if(args[0]==="mcp-hook"){let ws=readRemoteWorkspace(dir);if(ws)ensureMcpForwards(ws.machine,machineMcp(ws.machine))}}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}var ROVE_COMMAND=/^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*\/)?rove(?:\s|$)/;function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command)||ROVE_COMMAND.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
3
3
  `);if(lines.length<=count+1)return text;return`${lines.slice(0,count).join(`
4
4
  `)}
5
5
  [cut at line ${from+count-1}; pass offset to read on]`}if(name==="write"){if(typeof a.content!=="string")throw Error("content is required");return write(a.content),`wrote ${path}`}if(name==="edit"){let{old_string:from,new_string:to}=a;if(typeof from!=="string"||typeof to!=="string"||!from)throw Error("old_string and new_string are required");let text=must(run(`cat -- ${file}`)),hits=text.split(from).length-1;if(hits===0)throw Error(`old_string not found in ${path}`);if(hits>1&&a.replace_all!==!0)throw Error(`old_string occurs ${hits} times in ${path}; add context to make it unique, or pass replace_all`);return write(text.split(from).join(to)),`edited ${path} (${hits} replacement${hits===1?"":"s"})`}throw Error(`unknown tool: ${name}`)}function mcpReply(run,msg){if(msg.id===void 0||!msg.method)return null;let result=(value)=>({jsonrpc:"2.0",id:msg.id,result:value});if(msg.method==="initialize")return result({protocolVersion:typeof msg.params?.protocolVersion==="string"?msg.params.protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rove-workspace",version:CURRENT_VERSION}});if(msg.method==="ping")return result({});if(msg.method==="tools/list")return result({tools:TOOLS});if(msg.method==="tools/call"){let args=msg.params?.arguments??{};try{let text=callWorkspaceTool(run,String(msg.params?.name??""),args);return result({content:[{type:"text",text}]})}catch(err){return result({content:[{type:"text",text:err instanceof Error?err.message:String(err)}],isError:!0})}}return{jsonrpc:"2.0",id:msg.id,error:{code:-32601,message:`method not found: ${msg.method}`}}}async function serveMcp(rx){let run=runThrough(rx);for await(let line of createInterface({input:process.stdin})){if(!line.trim())continue;let msg;try{msg=JSON.parse(line)}catch{continue}let reply=mcpReply(run,msg);if(reply)process.stdout.write(`${JSON.stringify(reply)}
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{DAEMON_UNREACHABLE_MESSAGE,argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,isDaemonUnreachable,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-pk67ddfn.js";import"./chunk-9c06ccvf.js";import"./chunk-6n9wzp5t.js";import"./chunk-9sq4jh9k.js";import"./chunk-73a9kk03.js";import"./chunk-336z42rb.js";import"./chunk-ggnk6hg8.js";import"./chunk-sns4xm7n.js";import"./chunk-hawwvad6.js";import"./chunk-7cm66y22.js";import"./chunk-zcywdm3y.js";import"./chunk-4kepb278.js";import"./chunk-fqdx10w8.js";import"./chunk-awerm3vq.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-hdea2ss8.js";import"./chunk-5mhvjytn.js";import"./chunk-jpc5yh8e.js";import"./chunk-w9fdfcnc.js";import"./chunk-q1tm27sa.js";import"./chunk-g2tqea7f.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-5swzs64n.js";import"./chunk-mdx18vtz.js";import"./chunk-1jp3vdzc.js";import"./chunk-vk8t0x7q.js";import"./chunk-y0e28qha.js";import"./chunk-gx0hxf04.js";import"./chunk-7eqzs28e.js";import"./chunk-5x9zmxbm.js";import"./chunk-f1csqde7.js";import"./chunk-m1jbthc5.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-qpemynnh.js";import"./chunk-grbrh92f.js";import"./chunk-kr7jw1s4.js";import"./chunk-7b2x6nkj.js";import"./chunk-jw8fp9fk.js";import"./chunk-6bxdexbq.js";import"./chunk-2caxfsms.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-wmrmwncn.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-9c723k0b.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-vnp1k7ek.js";import"./chunk-c9c6yczz.js";import"./chunk-cw6xz64t.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-fj7nj0vy.js";import"./chunk-s2b2nfeb.js";import"./chunk-zvnzy679.js";import"./chunk-6qwjd3da.js";import"./chunk-f60hmm20.js";import"./chunk-03ab55aq.js";import"./chunk-w7zv47mp.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-78y80xe8.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import"./chunk-wx77yjhc.js";import"./chunk-nks2q6d9.js";import"./chunk-fczxyfgn.js";import"./chunk-nbfxhvby.js";import"./chunk-n5at7bsq.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-q5agazsv.js";import"./chunk-1cye0btk.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";export{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,isDaemonUnreachable,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams,DAEMON_UNREACHABLE_MESSAGE};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{PLUGIN_MANIFEST_FILENAMES,currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginManifestPath,savePluginRegistry,supportsPlatform,upsertPluginEntry}from"./chunk-jpc5yh8e.js";import{pluginCheckoutDir,pluginConfigDir,pluginStateDir,pluginsRootDir}from"./chunk-ws2q07kb.js";import{CURRENT_VERSION,compareSemver}from"./chunk-tdzdrnse.js";import{spawn}from"child_process";import{cpSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync}from"fs";import{mkdtempSync}from"fs";import{basename,join,resolve}from"path";import{createInterface}from"readline/promises";var GITHUB_SPEC_RE=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)(\/.+)?$/;class PluginCliError extends Error{}function fail(message){throw new PluginCliError(message)}function readManifestAt(root){let path=pluginManifestPath(root);if(!path)fail(`no ${PLUGIN_MANIFEST_FILENAMES.join(" or ")} found at ${root}`);let source=readFileSync(path,"utf8");return{...parsePluginManifest(source,basename(path)),manifestPath:path,manifestSource:source}}function checkVersionGate(parsed){let min=parsed.manifest.minRoveVersion;if(compareSemver(CURRENT_VERSION,min)<0)fail(`plugin requires Rove >= ${min} (this is ${CURRENT_VERSION}); update Rove first`)}function commandLines(parsed){let m=parsed.manifest,lines=[];for(let c of m.build)lines.push(`build: ${c.command.join(" ")}`);for(let c of m.startup)lines.push(`startup: ${c.command.join(" ")}`);for(let a of m.actions)lines.push(`action ${a.id}: ${a.command.join(" ")}`);for(let e of m.events)lines.push(`on ${e.on}: ${e.command.join(" ")}`);for(let e of m.engines)if(e.modelsCommand)lines.push(`engine ${e.id} models: ${e.modelsCommand.join(" ")}`);return lines}var CAPTURE_TAIL_BYTES=4096;function run(cmd,args,opts){return new Promise((resolve2)=>{let child=spawn(cmd,args,{cwd:opts.cwd,stdio:opts.inherit?["ignore","inherit","inherit"]:["ignore","pipe","pipe"]}),output="",collect=(chunk)=>{output=`${output}${String(chunk)}`.slice(-CAPTURE_TAIL_BYTES)};child.stdout?.on("data",collect),child.stderr?.on("data",collect),child.on("error",(err)=>resolve2({code:null,output:`${output}${err.message}`})),child.on("close",(code)=>resolve2({code,output}))})}function outputTail(output){let trimmed=output.trim();return trimmed?`: ${trimmed.split(`
2
+ import{PLUGIN_MANIFEST_FILENAMES,currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginManifestPath,savePluginRegistry,supportsPlatform,upsertPluginEntry}from"./chunk-jpc5yh8e.js";import{pluginCheckoutDir,pluginConfigDir,pluginStateDir,pluginsRootDir}from"./chunk-ws2q07kb.js";import{CURRENT_VERSION,compareSemver}from"./chunk-qpemynnh.js";import{spawn}from"child_process";import{cpSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync}from"fs";import{mkdtempSync}from"fs";import{basename,join,resolve}from"path";import{createInterface}from"readline/promises";var GITHUB_SPEC_RE=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)(\/.+)?$/;class PluginCliError extends Error{}function fail(message){throw new PluginCliError(message)}function readManifestAt(root){let path=pluginManifestPath(root);if(!path)fail(`no ${PLUGIN_MANIFEST_FILENAMES.join(" or ")} found at ${root}`);let source=readFileSync(path,"utf8");return{...parsePluginManifest(source,basename(path)),manifestPath:path,manifestSource:source}}function checkVersionGate(parsed){let min=parsed.manifest.minRoveVersion;if(compareSemver(CURRENT_VERSION,min)<0)fail(`plugin requires Rove >= ${min} (this is ${CURRENT_VERSION}); update Rove first`)}function commandLines(parsed){let m=parsed.manifest,lines=[];for(let c of m.build)lines.push(`build: ${c.command.join(" ")}`);for(let c of m.startup)lines.push(`startup: ${c.command.join(" ")}`);for(let a of m.actions)lines.push(`action ${a.id}: ${a.command.join(" ")}`);for(let e of m.events)lines.push(`on ${e.on}: ${e.command.join(" ")}`);for(let e of m.engines)if(e.modelsCommand)lines.push(`engine ${e.id} models: ${e.modelsCommand.join(" ")}`);return lines}var CAPTURE_TAIL_BYTES=4096;function run(cmd,args,opts){return new Promise((resolve2)=>{let child=spawn(cmd,args,{cwd:opts.cwd,stdio:opts.inherit?["ignore","inherit","inherit"]:["ignore","pipe","pipe"]}),output="",collect=(chunk)=>{output=`${output}${String(chunk)}`.slice(-CAPTURE_TAIL_BYTES)};child.stdout?.on("data",collect),child.stderr?.on("data",collect),child.on("error",(err)=>resolve2({code:null,output:`${output}${err.message}`})),child.on("close",(code)=>resolve2({code,output}))})}function outputTail(output){let trimmed=output.trim();return trimmed?`: ${trimmed.split(`
3
3
  `).slice(-3).join(" / ")}`:""}async function git(args,opts){let{code,output}=await run("git",args,opts);if(code!==0)fail(`git ${args[0]} failed${outputTail(output)}`)}async function runBuildCommands(parsed,root,opts){let platform=currentPluginPlatform();for(let[i,step]of parsed.manifest.build.entries()){if(!supportsPlatform(step,parsed.manifest,platform))continue;let[cmd,...args]=step.command;if(opts.inherit)console.log(`build[${i}]: ${step.command.join(" ")}`);let{code,output}=await run(cmd,args,{cwd:root,inherit:opts.inherit});if(code!==0)fail(`build[${i}] failed (exit ${code??"spawn error"}); plugin not registered${outputTail(output)}`)}}function makeStagingDir(){let root=pluginsRootDir();return mkdirSync(root,{recursive:!0}),mkdtempSync(join(root,".staging-"))}function movePluginTree(from,to){try{renameSync(from,to)}catch(err){if(err.code!=="EXDEV")throw err;cpSync(from,to,{recursive:!0,verbatimSymlinks:!0}),rmSync(from,{recursive:!0,force:!0})}}function register(entry){savePluginRegistry(upsertPluginEntry(loadPluginRegistry(),entry)),mkdirSync(pluginConfigDir(entry.id),{recursive:!0,mode:448}),mkdirSync(pluginStateDir(entry.id),{recursive:!0,mode:448})}async function preparePluginInstall(spec,opts={}){let match=spec.match(GITHUB_SPEC_RE);if(!match)fail(`install takes GitHub shorthand (owner/repo[/subdir]), got \`${spec}\``);let[,owner,repo,subdirRaw]=match,subdir=subdirRaw?.replace(/^\//,""),inherit=opts.inherit??!1,tmp=makeStagingDir();try{let url=`https://github.com/${owner}/${repo}.git`;if(inherit)console.log(`cloning ${url}${opts.ref?` @ ${opts.ref}`:""}`);if(opts.ref)await git(["clone","--quiet",url,tmp],{inherit}),await git(["checkout","--quiet",opts.ref],{cwd:tmp,inherit});else await git(["clone","--quiet","--depth","1",url,tmp],{inherit});let rootInClone=subdir?join(tmp,subdir):tmp,parsed=readManifestAt(rootInClone);checkVersionGate(parsed);let id=parsed.manifest.id,existing=loadPluginRegistry().plugins.find((p)=>p.id===id);if(existing?.source.kind==="link")fail(`\`${id}\` is locally linked at ${existing.root}; unlink it first`);if(!supportsPlatform({},parsed.manifest,currentPluginPlatform()))fail(`plugin declares platforms [${parsed.manifest.platforms?.join(", ")}]; this machine is unsupported`);return{preview:{id,name:parsed.manifest.name,version:parsed.manifest.version,description:parsed.manifest.description??null,source:`github.com/${owner}/${repo}${subdir?`/${subdir}`:""}`,commands:commandLines(parsed),warnings:parsed.warnings},commit:async()=>{try{await runBuildCommands(parsed,rootInClone,{inherit});let manifestPath=pluginManifestPath(rootInClone);if(!manifestPath)fail("manifest disappeared during build; aborting");if(manifestPath!==parsed.manifestPath)fail("manifest changed during build; aborting");if(readFileSync(manifestPath,"utf8")!==parsed.manifestSource)fail("manifest changed during build; aborting");let checkout=pluginCheckoutDir(id);return rmSync(checkout,{recursive:!0,force:!0}),mkdirSync(join(checkout,".."),{recursive:!0}),movePluginTree(tmp,checkout),register({id,source:{kind:"github",spec},root:subdir?join(checkout,subdir):checkout,enabled:!0,version:parsed.manifest.version,installedAt:Date.now()}),id}finally{rmSync(tmp,{recursive:!0,force:!0})}},discard:()=>rmSync(tmp,{recursive:!0,force:!0})}}catch(err){throw rmSync(tmp,{recursive:!0,force:!0}),err}}function printPreview(preview){console.log(`
4
4
  ${preview.name} (${preview.id}) v${preview.version} \u2014 ${preview.description??"no description"}`),console.log(`source: ${preview.source}`);for(let line of preview.commands)console.log(` ${line}`);for(let w of preview.warnings)console.log(` warning: ${w}`);console.log("")}async function confirmOrBail(yes){if(yes)return;if(!process.stdin.isTTY)fail("refusing to install without confirmation in a non-interactive terminal; pass --yes");let rl=createInterface({input:process.stdin,output:process.stdout}),answer=(await rl.question("Install this plugin and run its build commands? [y/N] ")).trim().toLowerCase();if(rl.close(),answer!=="y"&&answer!=="yes")fail("aborted")}async function installPlugin(spec,opts){let prepared=await preparePluginInstall(spec,{ref:opts.ref,inherit:!0});printPreview(prepared.preview);try{await confirmOrBail(opts.yes)}catch(err){throw prepared.discard(),err}let id=await prepared.commit();return console.log(`installed ${id} v${prepared.preview.version}`),id}function linkPlugin(dir){let root=resolve(dir);if(!existsSync(root))fail(`no such directory: ${root}`);let parsed=readManifestAt(root);checkVersionGate(parsed);let id=parsed.manifest.id;if(loadPluginRegistry().plugins.find((p)=>p.id===id)?.source.kind==="github")fail(`\`${id}\` is installed from GitHub; uninstall it before linking a local copy`);for(let w of parsed.warnings)console.log(`warning: ${w}`);if(!supportsPlatform({},parsed.manifest,currentPluginPlatform()))console.log(`warning: declares platforms [${parsed.manifest.platforms?.join(", ")}]; nothing will run on this machine`);register({id,source:{kind:"link"},root,enabled:!0,version:parsed.manifest.version,installedAt:Date.now()}),console.log(`linked ${id} v${parsed.manifest.version} \u2192 ${root}`)}
5
5
  export{PluginCliError,preparePluginInstall,installPlugin,linkPlugin};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{applyJitter,exponentialBackoff}from"./chunk-f60hmm20.js";var GH_PR_VIEW_FIELDS="number,url,title,state,baseRefName,headRefOid,reviewDecision,mergeable,statusCheckRollup,additions,deletions";function lifecycleFromState(state,reviewDecision){switch((state??"").toUpperCase()){case"MERGED":return"merged";case"CLOSED":return"closed";case"OPEN":return(reviewDecision??"").toUpperCase()==="APPROVED"?"ready_to_merge":"open";default:return"unknown"}}function entryCheckState(entry){let status=(entry.status??"").toUpperCase(),conclusion=(entry.conclusion??"").toUpperCase(),contextState=(entry.state??"").toUpperCase();if(status&&status!=="COMPLETED")return"pending";if(conclusion){if(conclusion==="SUCCESS"||conclusion==="NEUTRAL"||conclusion==="SKIPPED")return"passing";if(conclusion==="CANCELLED")return"cancelled";return"failing"}if(contextState==="SUCCESS")return"passing";if(contextState==="PENDING"||contextState==="EXPECTED")return"pending";if(contextState==="FAILURE"||contextState==="ERROR")return"failing";return"unknown"}function checkStateFromRollup(rollup){if(!rollup||rollup.length===0)return"none";let sawPending=!1,sawUnknown=!1,sawVerdict=!1;for(let entry of rollup){let s=entryCheckState(entry);if(s==="failing")return"failing";if(s==="cancelled")continue;if(sawVerdict=!0,s==="pending")sawPending=!0;else if(s==="unknown")sawUnknown=!0}if(sawPending)return"pending";if(sawUnknown)return"unknown";return sawVerdict?"passing":"none"}function mapGhPrView(view,at){if(!view||typeof view.number!=="number")return null;return{provider:"github",lifecycle:lifecycleFromState(view.state,view.reviewDecision),checkState:checkStateFromRollup(view.statusCheckRollup),number:view.number,url:view.url,title:view.title,...typeof view.additions==="number"?{additions:view.additions}:{},...typeof view.deletions==="number"?{deletions:view.deletions}:{},baseRef:view.baseRefName,reviewDecision:view.reviewDecision||void 0,mergeable:view.mergeable||void 0,...view.headRefOid?{headSha:view.headRefOid}:{},lastCheckedAt:at}}function samePrStatus(a,b){if(a===b)return!0;if(!a||!b)return!1;return a.provider===b.provider&&a.lifecycle===b.lifecycle&&a.checkState===b.checkState&&a.number===b.number&&a.url===b.url&&a.title===b.title&&a.additions===b.additions&&a.deletions===b.deletions&&a.baseRef===b.baseRef&&a.reviewDecision===b.reviewDecision&&a.mergeable===b.mergeable&&a.headSha===b.headSha}var NO_REMOTE_PATTERNS=["none of the git remotes","no git remote","to use github cli in a github repository","not a github repository"],AUTH_PATTERNS=["gh auth login","authentication required","not logged in","http 401","bad credentials","requires authentication"],NETWORK_PATTERNS=["could not resolve host","no such host","dial tcp","connection refused","connection reset","network is unreachable","i/o timeout","timeout","tls handshake","http 5","rate limit","try again"];function matchesAny(haystack,needles){return needles.some((n)=>haystack.includes(n))}function classifyGhFailure(s){if(s.parseError)return{kind:"error",error:"parse"};if(s.timedOut)return{kind:"error",error:"timeout"};if(s.cwdMissing)return{kind:"error",error:"worktree-missing"};if(s.spawnError)return{kind:"error",error:"missing-binary"};let err=(s.stderr??"").toLowerCase();if(matchesAny(err,NO_REMOTE_PATTERNS))return{kind:"error",error:"no-remote"};if(matchesAny(err,AUTH_PATTERNS))return{kind:"error",error:"auth"};if(matchesAny(err,NETWORK_PATTERNS))return{kind:"error",error:"network"};return{kind:"error",error:"unknown"}}function nextPrPoll(outcome,prevFailures,now,cfg,rand=Math.random){let at=(delay)=>now+applyJitter(delay,cfg.jitterRatio,rand);if(outcome.kind==="pr")return{nextAllowedAt:at(outcome.settled?cfg.settledMs:cfg.tickMs),failures:0};if(outcome.kind==="empty")return{nextAllowedAt:at(cfg.noPrMs),failures:0};if(outcome.error==="no-remote"||outcome.error==="worktree-missing")return{nextAllowedAt:at(cfg.noRemoteMs),failures:0};let failures=prevFailures+1;return{nextAllowedAt:at(exponentialBackoff(cfg.failureBaseMs,failures-1,cfg.failureCapMs)),failures}}function checkResolutionNotify(prev,next){if(prev!=="pending")return null;if(next==="passing"||next==="failing")return next;return null}
3
+ export{GH_PR_VIEW_FIELDS,mapGhPrView,samePrStatus,classifyGhFailure,nextPrPoll,checkResolutionNotify};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{stampOrigin}from"./chunk-k2fb370k.js";import{createStateCell}from"./chunk-7b2x6nkj.js";var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map};function decodeMachines(payload){let p=payload;if(!p||!Array.isArray(p.machines)||!Array.isArray(p.tasks)||!p.live||typeof p.live!=="object")return null;let map=(value)=>new Map(value&&typeof value==="object"?Object.entries(value):[]);return{machines:p.machines,tasks:p.tasks,live:{activity:map(p.live.activity),changes:map(p.live.changes),tokens:map(p.live.tokens)}}}class MachineFeed{local;machinesAcc=createStateCell([],"machines.status");remoteTasksAcc=createStateCell(null,"machines.remoteTasks");tasksAcc;merged=null;liveAcc=createStateCell(NO_LIVE,"machines.live");stops;constructor(local){this.local=local;this.tasksAcc=this.mergedTasks();let raw=local.rawChannelSignal("machines"),take=()=>{let next=decodeMachines(raw.get());if(!next)return;this.machinesAcc.set(next.machines),this.liveAcc.set(next.live),this.remoteTasksAcc.set(next.machines.length===0?null:next.tasks)};this.stops=[raw.subscribe(take)],take()}machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}mergedTasks(){let localTasks=this.local.tasksSignal(),get=()=>{let local=localTasks.get(),remote=this.remoteTasksAcc.get();if(remote===null)return local;if(this.merged?.local!==local||this.merged.remote!==remote){let value=[...local.map((task)=>stampOrigin(task,"local","local")),...remote];this.merged={local,remote,value}}return this.merged.value},state=get;return state.get=get,state.subscribe=(listener)=>{let stopLocal=localTasks.subscribe(listener),stopRemote=this.remoteTasksAcc.subscribe(listener);return()=>{stopLocal(),stopRemote()}},state}dispose(){for(let stop of this.stops)stop()}}
2
+ import{stampOrigin}from"./chunk-7ewphe3a.js";import{createStateCell}from"./chunk-7b2x6nkj.js";var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map};function decodeMachines(payload){let p=payload;if(!p||!Array.isArray(p.machines)||!Array.isArray(p.tasks)||!p.live||typeof p.live!=="object")return null;let map=(value)=>new Map(value&&typeof value==="object"?Object.entries(value):[]);return{machines:p.machines,tasks:p.tasks,live:{activity:map(p.live.activity),changes:map(p.live.changes),tokens:map(p.live.tokens)}}}class MachineFeed{local;machinesAcc=createStateCell([],"machines.status");remoteTasksAcc=createStateCell(null,"machines.remoteTasks");tasksAcc;merged=null;liveAcc=createStateCell(NO_LIVE,"machines.live");stops;constructor(local){this.local=local;this.tasksAcc=this.mergedTasks();let raw=local.rawChannelSignal("machines"),take=()=>{let next=decodeMachines(raw.get());if(!next)return;this.machinesAcc.set(next.machines),this.liveAcc.set(next.live),this.remoteTasksAcc.set(next.machines.length===0?null:next.tasks)};this.stops=[raw.subscribe(take)],take()}machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}mergedTasks(){let localTasks=this.local.tasksSignal(),get=()=>{let local=localTasks.get(),remote=this.remoteTasksAcc.get();if(remote===null)return local;if(this.merged?.local!==local||this.merged.remote!==remote){let value=[...local.map((task)=>stampOrigin(task,"local","local")),...remote];this.merged={local,remote,value}}return this.merged.value},state=get;return state.get=get,state.subscribe=(listener)=>{let stopLocal=localTasks.subscribe(listener),stopRemote=this.remoteTasksAcc.subscribe(listener);return()=>{stopLocal(),stopRemote()}},state}dispose(){for(let stop of this.stops)stop()}}
3
3
  export{decodeMachines,MachineFeed};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{MAX_NOTES,MULTI_REPO_CAP,REPO_NAME_RE,SESSION_PR_CAP,canonicalPrUrl,coerceTodos,isWorkspaceBackendId}from"./chunk-sckqk79z.js";import{logClient}from"./chunk-y8hjgmn0.js";import{toTaskId}from"./chunk-w2czjjxy.js";import{coerceVendorId}from"./chunk-8q0nmdh3.js";import{pathSyntax,samePath}from"./chunk-pn5ygqn6.js";import{DAEMON_MIGRATION_MARKER}from"./chunk-8rxg12aj.js";import{LockfileError,acquire}from"./chunk-n835vmw4.js";import{defaultClientLogPath}from"./chunk-2z2jwetd.js";import{existsSync}from"fs";import{copyFile,readFile}from"fs/promises";import{dirname,join}from"path";var AUTO_FIX_MAX=3,AT_REST={idle:!0,turn_complete:!0};function autoFixDecision(input){let{state,pr,engine}=input;if(!state||!pr)return{do:"skip"};if(pr.lifecycle!=="open"&&pr.lifecycle!=="ready_to_merge")return{do:"skip"};if(pr.checkState==="passing")return state.attempts>0||state.stopped||state.lastSha?{do:"reset"}:{do:"skip"};if(pr.checkState!=="failing"||!pr.headSha)return{do:"skip"};if(pr.headSha===state.lastSha)return{do:"skip"};if(state.stopped)return{do:"skip"};if(state.attempts>=3)return{do:"stop"};return AT_REST[engine??""]?{do:"fire"}:{do:"wait"}}function coerceAutoFix(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value,attempts=typeof v.attempts==="number"&&Number.isInteger(v.attempts)&&v.attempts>=0?v.attempts:0;return{attempts:Math.min(attempts,3),...typeof v.lastSha==="string"&&v.lastSha.length>0?{lastSha:v.lastSha}:{},...v.stopped===!0?{stopped:!0}:{}}}function coerceTask(value){if(!value||typeof value!=="object")return null;let v=value;if(typeof v.id!=="string"||typeof v.title!=="string"||typeof v.repo!=="string"||typeof v.branch!=="string"||typeof v.worktreePath!=="string"||typeof v.status!=="string"||typeof v.createdAt!=="string"||typeof v.updatedAt!=="string")return null;if(!isTaskStatus(v.status))return null;let fromProjectRow=v.kind==="main"||v.fromProjectRow===!0,kind=v.kind==="main"||v.kind==="dir"?"dir":"task",noProject=kind==="dir"&&(v.noProject===!0||v.scratch===!0),deletion=coerceDeletion(v.deletion),quotaResume=coerceQuotaResume(v.quotaResume),scheduledStart=coerceScheduledStart(v.scheduledStart),linkedWorkItem=coerceLinkedWorkItem(v.linkedWorkItem),dispatcher=coerceDispatcher(v.dispatcher),lineage=coerceLineage(v),routine=coerceRoutine(v.routine),extraRepos=coerceExtraRepos(v.extraRepos,v.repo),workspace=coerceWorkspace(v.workspace),sessionPrs=coerceSessionPrs(v.sessionPrs),todos=coerceTodos(v.todos),autoFixCi=coerceAutoFix(v.autoFixCi),report=coerceWorkerReport(v.report),progress=coerceProgress(v.progress);return{id:toTaskId(v.id),title:v.title,repo:v.repo,branch:v.branch,worktreePath:v.worktreePath,status:v.status,pinned:typeof v.pinned==="boolean"?v.pinned:!1,...v.kept===!0?{kept:!0}:{},...typeof v.notes==="string"&&v.notes.length>0?{notes:v.notes.slice(0,MAX_NOTES)}:{},...todos?{todos}:{},...autoFixCi?{autoFixCi}:{},kind,...fromProjectRow?{fromProjectRow:!0}:{},...noProject?{noProject:!0}:{},...typeof v.connector==="string"&&v.connector.length>0?{connector:v.connector}:{},...routine?{routine}:{},vendor:coerceVendorId(typeof v.vendor==="string"?v.vendor:void 0),...typeof v.command==="string"&&v.command.trim().length>0?{command:v.command}:{},prStatus:coercePRStatus(v.prStatus),...typeof v.modelEffort==="string"&&v.modelEffort.length>0?{modelEffort:v.modelEffort}:{},...typeof v.model==="string"&&v.model.length>0?{model:v.model}:{},...typeof v.tier==="string"&&v.tier.length>0?{tier:v.tier}:{},...typeof v.groupId==="string"&&v.groupId.length>0?{groupId:v.groupId}:{},...v.observedLanguage==="zh"||v.observedLanguage==="en"?{observedLanguage:v.observedLanguage}:{},...deletion?{deletion}:{},...quotaResume?{quotaResume}:{},...scheduledStart?{scheduledStart}:{},...linkedWorkItem?{linkedWorkItem}:{},...dispatcher?{dispatcher}:{},...lineage,...v.deleteBranchPending===!0?{deleteBranchPending:!0}:{},...typeof v.prompt==="string"&&v.prompt.length>0?{prompt:v.prompt}:{},...typeof v.baseRef==="string"&&v.baseRef.trim().length>0?{baseRef:v.baseRef}:{},...typeof v.worktreeName==="string"&&v.worktreeName.trim().length>0?{worktreeName:v.worktreeName}:{},...typeof v.gitRepo==="string"&&v.gitRepo.trim().length>0?{gitRepo:v.gitRepo}:{},...extraRepos?{extraRepos}:{},...workspace?{workspace}:{},...sessionPrs?{sessionPrs}:{},...report?{report}:{},...progress?{progress}:{},...v.requireReport===!0?{requireReport:!0}:{},...typeof v.engineTitle==="string"&&v.engineTitle?{engineTitle:v.engineTitle}:{},...v.worktreeOnly===!0?{worktreeOnly:!0}:{},...v.archived===!0?{archived:!0}:{},createdAt:v.createdAt,updatedAt:v.updatedAt}}function coerceWorkspace(value){if(!value||typeof value!=="object")return;let w=value;if(!isWorkspaceBackendId(w.backend))return;return{backend:w.backend,...typeof w.ref==="string"&&w.ref.length>0?{ref:w.ref}:{}}}function coerceExtraRepos(value,primary){if(!Array.isArray(value))return;let out=[];for(let entry of value){if(out.length>=MULTI_REPO_CAP-1)break;if(!entry||typeof entry!=="object")continue;let e=entry;if(typeof e.name!=="string"||!REPO_NAME_RE.test(e.name))continue;if(typeof e.repo!=="string"||!pathSyntax(e.repo).isAbsolute(e.repo))continue;let repo=e.repo;if(samePath(repo,primary)||out.some((o)=>o.name===e.name||samePath(o.repo,repo)))continue;out.push({name:e.name,repo,branch:typeof e.branch==="string"?e.branch:"",worktreePath:typeof e.worktreePath==="string"?e.worktreePath:"",...typeof e.baseRef==="string"&&e.baseRef.trim().length>0?{baseRef:e.baseRef}:{},...coercePRStatus(e.prStatus)?{prStatus:coercePRStatus(e.prStatus)}:{}})}return out.length>0?out:void 0}function coerceSessionPrs(value){if(!Array.isArray(value))return;let out=[];for(let entry of value){if(!entry||typeof entry!=="object")continue;let e=entry,url=typeof e.url==="string"?canonicalPrUrl(e.url):void 0;if(!url||typeof e.addedAt!=="string"||out.some((o)=>o.url===url))continue;let status=coercePRStatus(e.status);out.push({url,addedAt:e.addedAt,...status?{status}:{}})}return out.length>0?out.slice(-SESSION_PR_CAP):void 0}function coerceWorkerReport(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;return{at:v.at,...typeof v.branch==="string"&&v.branch.length>0?{branch:v.branch}:{},...typeof v.pr==="number"&&Number.isFinite(v.pr)?{pr:v.pr}:{},...typeof v.summary==="string"&&v.summary.length>0?{summary:v.summary}:{}}}function coerceProgress(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.note!=="string"||v.note.length===0||typeof v.at!=="string"||v.at.length===0)return;return{note:v.note,at:v.at}}function coerceDispatcher(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.taskId!=="string"||v.taskId.length===0)return;if(typeof v.tabId!=="string"||v.tabId.length===0)return;return{taskId:v.taskId,tabId:v.tabId}}function coerceTaskRef(value,selfId){return typeof value==="string"&&value.length>0&&value!==selfId?value:void 0}function coerceCwdSubpath(value){if(typeof value!=="string"||value.length===0)return;if(/^[/\\]|^[a-z]:/i.test(value))return;return value.split(/[/\\]/).includes("..")?void 0:value}function coerceLineage(v){let selfId=v.id,parentTaskId=coerceTaskRef(v.parentTaskId,selfId),sharesWorkspaceOf=v.kind==="main"?void 0:coerceTaskRef(v.sharesWorkspaceOf,selfId),cwdSubpath=coerceCwdSubpath(v.cwdSubpath),ptyAlias=coerceDispatcher(v.ptyAlias);return{...parentTaskId?{parentTaskId:toTaskId(parentTaskId)}:{},...sharesWorkspaceOf?{sharesWorkspaceOf:toTaskId(sharesWorkspaceOf)}:{},...cwdSubpath?{cwdSubpath}:{},...ptyAlias?{ptyAlias}:{}}}function coerceRoutine(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.automationId!=="string"||v.automationId.length===0)return;return{automationId:v.automationId}}function coerceQuotaResume(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.resumeAt!=="string"||v.resumeAt.length===0)return;if(typeof v.requestedAt!=="string"||v.requestedAt.length===0)return;return{resumeAt:v.resumeAt,requestedAt:v.requestedAt}}function coerceScheduledStart(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(typeof v.at!=="string"||v.at.length===0)return;if(typeof v.prompt!=="string"||v.prompt.length===0)return;return{at:v.at,prompt:v.prompt}}function coerceLinkedWorkItem(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.provider!=="github")return;if(v.type!=="issue"&&v.type!=="pr")return;if(typeof v.number!=="number"||!Number.isFinite(v.number))return;if(typeof v.title!=="string"||typeof v.url!=="string"||v.url.length===0)return;return{provider:v.provider,type:v.type,number:v.number,title:v.title,url:v.url}}function coerceDeletion(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(v.phase!=="queued"&&v.phase!=="running"&&v.phase!=="error"||typeof v.force!=="boolean"||typeof v.requestedAt!=="string"||v.requestedAt.length===0||v.error!==void 0&&typeof v.error!=="string")return;return{phase:v.phase,force:v.force,...typeof v.deleteBranch==="boolean"?{deleteBranch:v.deleteBranch}:{},requestedAt:v.requestedAt,...typeof v.error==="string"?{error:v.error}:{}}}function coercePRStatus(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let v=value;if(!isPRProviderId(v.provider)||!isPRLifecycleState(v.lifecycle)||!isPRCheckState(v.checkState))return;return{provider:v.provider,lifecycle:v.lifecycle,checkState:v.checkState,...typeof v.number==="number"&&Number.isFinite(v.number)?{number:v.number}:{},...typeof v.url==="string"?{url:v.url}:{},...typeof v.title==="string"?{title:v.title}:{},...typeof v.additions==="number"&&Number.isFinite(v.additions)?{additions:v.additions}:{},...typeof v.deletions==="number"&&Number.isFinite(v.deletions)?{deletions:v.deletions}:{},...typeof v.baseRef==="string"?{baseRef:v.baseRef}:{},...typeof v.reviewDecision==="string"?{reviewDecision:v.reviewDecision}:{},...typeof v.mergeable==="string"?{mergeable:v.mergeable}:{},...typeof v.headSha==="string"?{headSha:v.headSha}:{},...typeof v.lastCheckedAt==="string"?{lastCheckedAt:v.lastCheckedAt}:{},...typeof v.lastError==="string"?{lastError:v.lastError}:{}}}function isPRProviderId(v){return v==="github"||v==="gitlab"||v==="bitbucket"||v==="unknown"}function isPRLifecycleState(v){return v==="creating"||v==="open"||v==="ready_to_merge"||v==="merged"||v==="closed"||v==="unknown"}function isPRCheckState(v){return v==="none"||v==="pending"||v==="passing"||v==="failing"||v==="unknown"}function isTaskStatus(s){return s==="backlog"||s==="in_progress"||s==="in_review"||s==="done"||s==="canceled"||s==="error"}var sleep=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),LOCK_RETRY_DELAY_MS=25,LOCK_MAX_WAIT_MS=5000;async function acquireWithRetry(lockPath){let deadline=Date.now()+LOCK_MAX_WAIT_MS;for(;;)try{return await acquire(lockPath)}catch(err){if(!(err instanceof LockfileError)||Date.now()>=deadline)throw err;await sleep(LOCK_RETRY_DELAY_MS)}}var CURRENT_VERSION=3;async function backupCorruptManifest(path,now=()=>new Date){let backupPath=`${path}.corrupt-${now().toISOString().replaceAll(":","-")}`;try{return await copyFile(path,backupPath),backupPath}catch{return null}}var SUPPORTED_VERSIONS=new Set([1,2,3]);function warnManifestRecovery(message,manifestPath){console.warn(message),logClient("tasks-index",message,manifestPath?defaultClientLogPath(dirname(dirname(manifestPath))):void 0)}async function recoverUnsupportedVersion(parsed,sourcePath){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return!1;let version=parsed.version;if(version===void 0||SUPPORTED_VERSIONS.has(version))return!1;let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} has unsupported version=${String(version)}; recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),!0}function normalizeIndex(parsed,source){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return warnManifestRecovery(`[rove] tasks.json at ${source} is not an object; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let obj=parsed,version=obj.version;if(version!==void 0&&!SUPPORTED_VERSIONS.has(version))return warnManifestRecovery(`[rove] tasks.json at ${source} has unsupported version=${String(version)}; recovering with empty index.`,source),{version:CURRENT_VERSION,tasks:[]};let rawTasks=Array.isArray(obj.tasks)?obj.tasks:[],tasks=[];for(let entry of rawTasks){let task=coerceTask(entry);if(task)tasks.push(task);else console.warn(`[rove] dropping malformed task entry from ${source}: ${JSON.stringify(entry)}`)}return{version:CURRENT_VERSION,tasks}}var TOMBSTONE_TTL_MS=2592000000;function readableLegacyIndexPath(canonicalPath,legacyPath){return existsSync(join(dirname(canonicalPath),DAEMON_MIGRATION_MARKER))?void 0:legacyPath}async function readDiskIndex(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(sourcePath,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath);if(!legacy)return{tasks:[],removed:[]};sourcePath=legacy;try{raw=await readFile(sourcePath,"utf8")}catch(legacyErr){if(legacyErr.code==="ENOENT")return{tasks:[],removed:[]};throw legacyErr}}let parsed;try{parsed=JSON.parse(raw)}catch{return await backupCorruptManifest(sourcePath),{tasks:[],removed:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{tasks:[],removed:[]};return{tasks:normalizeIndex(parsed,sourcePath).tasks,removed:coerceTombstones(parsed)}}function coerceTombstones(parsed){if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return[];let raw=parsed.removed;if(!Array.isArray(raw))return[];let out=[];for(let entry of raw){if(!entry||typeof entry!=="object")continue;let v=entry;if(typeof v.id==="string"&&v.id.length>0&&typeof v.at==="string")out.push({id:v.id,at:v.at})}return out}function mergeTasksWithDisk(cacheTasks,diskTasks,dirty,removed,diskRemoved=[],now=Date.now()){let tombstones=new Map;for(let t of diskRemoved){let at=Date.parse(t.at);if(!Number.isFinite(at)||now-at>TOMBSTONE_TTL_MS)continue;tombstones.set(t.id,t.at)}for(let[id,at]of removed)tombstones.set(id,at);let diskById=new Map(diskTasks.map((t)=>[t.id,t])),result=[],included=new Set;for(let task of cacheTasks){if(tombstones.has(task.id))continue;if(dirty.has(task.id))result.push(task);else{let onDisk=diskById.get(task.id);if(onDisk===void 0)continue;result.push(onDisk)}included.add(task.id)}for(let task of diskTasks){if(included.has(task.id)||tombstones.has(task.id))continue;result.push(task),included.add(task.id)}return{tasks:result,removed:[...tombstones].map(([id,at])=>({id,at}))}}async function recoverIndexFromDisk(path,legacyPath){let raw,sourcePath=path;try{raw=await readFile(path,"utf8")}catch(err){if(err.code!=="ENOENT")throw err;let legacy=readableLegacyIndexPath(path,legacyPath),legacyRaw;if(legacy)try{legacyRaw=await readFile(legacy,"utf8"),sourcePath=legacy}catch(legacyErr){if(legacyErr.code!=="ENOENT")throw legacyErr}if(legacyRaw===void 0)return{version:CURRENT_VERSION,tasks:[]};raw=legacyRaw}let parsed;try{parsed=JSON.parse(raw)}catch(err){let backup=await backupCorruptManifest(sourcePath);return warnManifestRecovery(`[rove] tasks.json at ${sourcePath} is corrupted (${err.message}); recovering with empty index.${backup?` Original bytes backed up to ${backup}.`:" Backup copy failed; the stale file is left in place."}`,sourcePath),{version:CURRENT_VERSION,tasks:[]}}if(await recoverUnsupportedVersion(parsed,sourcePath))return{version:CURRENT_VERSION,tasks:[]};return normalizeIndex(parsed,sourcePath)}
3
+ export{AUTO_FIX_MAX,autoFixDecision,acquireWithRetry,readableLegacyIndexPath,readDiskIndex,mergeTasksWithDisk,recoverIndexFromDisk};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RELEASE_CHANNELS,channelOf}from"./chunk-tdzdrnse.js";import{loadStateFile,patchStateFile}from"./chunk-nks2q6d9.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
2
+ import{RELEASE_CHANNELS,channelOf}from"./chunk-qpemynnh.js";import{loadStateFile,patchStateFile}from"./chunk-nks2q6d9.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
3
3
  export{UPDATE_CHANNEL_KEY,UPDATE_NOTIFY_KEY,normalizeReleaseChannel,preferredReleaseChannel,updateNotifyEnabled,rememberReleaseChannel,updateDelayHours};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{invokeVerb}from"./chunk-c4kr46da.js";import"./chunk-xmwrg55j.js";import{defaultApiRuntime,loadContext}from"./chunk-c1va68mx.js";import"./chunk-62b9mm81.js";import"./chunk-57atdjmz.js";import"./chunk-73a9kk03.js";import"./chunk-16rp8nn7.js";import"./chunk-ggnk6hg8.js";import"./chunk-sns4xm7n.js";import"./chunk-hawwvad6.js";import"./chunk-evf15cs5.js";import"./chunk-zcywdm3y.js";import"./chunk-4kepb278.js";import"./chunk-aena2jzj.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-axycrfkq.js";import"./chunk-5mhvjytn.js";import"./chunk-jpc5yh8e.js";import"./chunk-c0af07nt.js";import"./chunk-x729vdm1.js";import"./chunk-g2tqea7f.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-5swzs64n.js";import"./chunk-mdx18vtz.js";import"./chunk-785c8xtm.js";import"./chunk-cfb6mvz5.js";import"./chunk-y0e28qha.js";import"./chunk-gx0hxf04.js";import"./chunk-7eqzs28e.js";import"./chunk-5x9zmxbm.js";import"./chunk-f1csqde7.js";import"./chunk-m1jbthc5.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-tdzdrnse.js";import"./chunk-grbrh92f.js";import{SUBCOMMAND_VERBS}from"./chunk-8jp0h0cb.js";import"./chunk-v8ms64g1.js";import"./chunk-7b2x6nkj.js";import"./chunk-8ka3rkq0.js";import"./chunk-p55es0nf.js";import"./chunk-2caxfsms.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-wmrmwncn.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-vpk5m2z6.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-vnp1k7ek.js";import"./chunk-c9c6yczz.js";import"./chunk-cw6xz64t.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-5rxef858.js";import"./chunk-sy81vcaz.js";import"./chunk-bn8nrqde.js";import"./chunk-6qwjd3da.js";import"./chunk-f60hmm20.js";import"./chunk-03ab55aq.js";import"./chunk-w7zv47mp.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-78y80xe8.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import"./chunk-wx77yjhc.js";import"./chunk-nks2q6d9.js";import"./chunk-r4vwq5wv.js";import"./chunk-b43gbrar.js";import"./chunk-7dy9dtnd.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-xdmamqy7.js";import"./chunk-m74qxqw0.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{execFile}from"child_process";var LARK_CLI="lark-cli";function larkCli(args,timeoutMs=30000){return new Promise((resolve)=>{execFile(LARK_CLI,[...args],{timeout:timeoutMs,encoding:"utf8"},(err,stdout,stderr)=>resolve({ok:!err,stdout:stdout??"",stderr:stderr||(err?err.message:"")}))})}function json(stdout){try{let value=JSON.parse(stdout);return value&&typeof value==="object"?value:null}catch{return null}}async function botInfo(){let res=await larkCli(["api","GET","/open-apis/bot/v3/info","--as","bot"]),data=json(res.stdout)?.data??json(res.stdout)?.bot;return typeof data?.open_id==="string"&&data.open_id?{openId:data.open_id,name:typeof data.app_name==="string"?data.app_name:""}:null}async function authStatus(){let raw=json((await larkCli(["auth","status"])).stdout),user=raw?.identities?.user;return{...typeof raw?.appId==="string"&&raw.appId?{appId:raw.appId}:{},...typeof user?.openId==="string"&&user.openId?{userOpenId:user.openId}:{},...typeof user?.userName==="string"?{userName:user.userName}:{}}}async function react(messageId,emoji){return await larkCli(["im","reactions","create","--as","bot","--message-id",messageId,"--data",JSON.stringify({reaction_type:{emoji_type:emoji}})])}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var SEEN_CAP=500,DEFAULT_TONE="\u7B80\u77ED\u76F4\u63A5\uFF0C\u50CF\u540C\u4E8B\u804A\u5929\uFF0C\u7ED3\u8BBA\u5148\u8BF4\uFF0C\u4E0D\u5BA2\u5957",strings=(value)=>Array.isArray(value)?value.filter((v)=>typeof v==="string"):[];function readJson(path){try{let value=JSON.parse(readFileSync(path,"utf8"));return value&&typeof value==="object"?value:null}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
2
+ import{invokeVerb}from"./chunk-3eqhtvm1.js";import"./chunk-pk67ddfn.js";import{defaultApiRuntime,loadContext}from"./chunk-9c06ccvf.js";import"./chunk-6n9wzp5t.js";import"./chunk-9sq4jh9k.js";import"./chunk-73a9kk03.js";import"./chunk-336z42rb.js";import"./chunk-ggnk6hg8.js";import"./chunk-sns4xm7n.js";import"./chunk-hawwvad6.js";import"./chunk-7cm66y22.js";import"./chunk-zcywdm3y.js";import"./chunk-4kepb278.js";import"./chunk-fqdx10w8.js";import"./chunk-awerm3vq.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-hdea2ss8.js";import"./chunk-5mhvjytn.js";import"./chunk-jpc5yh8e.js";import"./chunk-w9fdfcnc.js";import"./chunk-q1tm27sa.js";import"./chunk-g2tqea7f.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-5swzs64n.js";import"./chunk-mdx18vtz.js";import"./chunk-1jp3vdzc.js";import"./chunk-vk8t0x7q.js";import"./chunk-y0e28qha.js";import"./chunk-gx0hxf04.js";import"./chunk-7eqzs28e.js";import"./chunk-5x9zmxbm.js";import"./chunk-f1csqde7.js";import"./chunk-m1jbthc5.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-qpemynnh.js";import"./chunk-grbrh92f.js";import{SUBCOMMAND_VERBS}from"./chunk-8jp0h0cb.js";import"./chunk-kr7jw1s4.js";import"./chunk-7b2x6nkj.js";import"./chunk-jw8fp9fk.js";import"./chunk-6bxdexbq.js";import"./chunk-2caxfsms.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-wmrmwncn.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-9c723k0b.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-vnp1k7ek.js";import"./chunk-c9c6yczz.js";import"./chunk-cw6xz64t.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-fj7nj0vy.js";import"./chunk-s2b2nfeb.js";import"./chunk-zvnzy679.js";import"./chunk-6qwjd3da.js";import"./chunk-f60hmm20.js";import"./chunk-03ab55aq.js";import"./chunk-w7zv47mp.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-78y80xe8.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import"./chunk-wx77yjhc.js";import"./chunk-nks2q6d9.js";import"./chunk-fczxyfgn.js";import"./chunk-nbfxhvby.js";import"./chunk-n5at7bsq.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-q5agazsv.js";import"./chunk-1cye0btk.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{execFile}from"child_process";var LARK_CLI="lark-cli";function larkCli(args,timeoutMs=30000){return new Promise((resolve)=>{execFile(LARK_CLI,[...args],{timeout:timeoutMs,encoding:"utf8"},(err,stdout,stderr)=>resolve({ok:!err,stdout:stdout??"",stderr:stderr||(err?err.message:"")}))})}function json(stdout){try{let value=JSON.parse(stdout);return value&&typeof value==="object"?value:null}catch{return null}}async function botInfo(){let res=await larkCli(["api","GET","/open-apis/bot/v3/info","--as","bot"]),data=json(res.stdout)?.data??json(res.stdout)?.bot;return typeof data?.open_id==="string"&&data.open_id?{openId:data.open_id,name:typeof data.app_name==="string"?data.app_name:""}:null}async function authStatus(){let raw=json((await larkCli(["auth","status"])).stdout),user=raw?.identities?.user;return{...typeof raw?.appId==="string"&&raw.appId?{appId:raw.appId}:{},...typeof user?.openId==="string"&&user.openId?{userOpenId:user.openId}:{},...typeof user?.userName==="string"?{userName:user.userName}:{}}}async function react(messageId,emoji){return await larkCli(["im","reactions","create","--as","bot","--message-id",messageId,"--data",JSON.stringify({reaction_type:{emoji_type:emoji}})])}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var SEEN_CAP=500,DEFAULT_TONE="\u7B80\u77ED\u76F4\u63A5\uFF0C\u50CF\u540C\u4E8B\u804A\u5929\uFF0C\u7ED3\u8BBA\u5148\u8BF4\uFF0C\u4E0D\u5BA2\u5957",strings=(value)=>Array.isArray(value)?value.filter((v)=>typeof v==="string"):[];function readJson(path){try{let value=JSON.parse(readFileSync(path,"utf8"));return value&&typeof value==="object"?value:null}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
3
3
  `,{mode:384}),renameSync(tmp,path)}class LarkStore{dir;constructor(homeDir){this.dir=join(resolveDaemonHomeDir(homeDir),ROVE_STATE_DIR_BASENAME,"lark")}get agentDir(){return join(this.dir,"agent")}ensureDir(){mkdirSync(this.dir,{recursive:!0,mode:448})}readConfig(){let raw=readJson(join(this.dir,"config.json"));if(!raw||typeof raw.botOpenId!=="string"||!raw.botOpenId)return null;return{botOpenId:raw.botOpenId,botName:typeof raw.botName==="string"?raw.botName:"",...typeof raw.ownerOpenId==="string"&&raw.ownerOpenId?{ownerOpenId:raw.ownerOpenId}:{},...typeof raw.ownerName==="string"&&raw.ownerName?{ownerName:raw.ownerName}:{},allow:strings(raw.allow),tone:typeof raw.tone==="string"&&raw.tone?raw.tone:DEFAULT_TONE,savedAt:typeof raw.savedAt==="string"?raw.savedAt:""}}writeConfig(config){this.ensureDir(),writeJson(join(this.dir,"config.json"),config)}clearConfig(){let had=this.readConfig()!==null;return rmSync(join(this.dir,"config.json"),{force:!0}),rmSync(join(this.dir,"state.json"),{force:!0}),had}readState(){let raw=readJson(join(this.dir,"state.json")),agent=raw?.agent;return{...typeof agent?.taskId==="string"&&typeof agent.tab==="string"?{agent:{taskId:agent.taskId,tab:agent.tab}}:{},...typeof raw?.tone==="string"?{tone:raw.tone}:{},seen:strings(raw?.seen),pending:strings(raw?.pending)}}writeState(state){this.ensureDir(),writeJson(join(this.dir,"state.json"),{...state,seen:state.seen.slice(-SEEN_CAP)})}}var run=(args)=>spawnSync(LARK_CLI,[...args],{stdio:"inherit"}).status===0;async function connectLark(store,opts){let say=opts.say??(()=>{}),terminal={ok:!1,message:"rove lark connect"};if(spawnSync(LARK_CLI,["--version"],{stdio:"ignore"}).error)return{ok:!1,message:"npm i -g @larksuite/cli && rove lark connect"};if(!(await authStatus()).appId){if(!opts.interactive)return terminal;if(say("No Lark app yet: lark-cli will create one in your browser."),!run(["config","init","--new",...opts.brand?["--brand",opts.brand]:[]]))return{ok:!1,message:"lark-cli config init did not finish"}}let bot=await botInfo();if(!bot)return{ok:!1,message:`${LARK_CLI} api GET /open-apis/bot/v3/info --as bot`};let owner=await authStatus();if(!owner.userOpenId){if(!opts.interactive)return terminal;if(say("Sign in to Lark as yourself, so the bot knows who you are."),!run(["auth","login","--scope","auth:user.id:read"]))return{ok:!1,message:"lark-cli auth login did not finish"};owner=await authStatus()}let previous=store.readConfig(),config={botOpenId:bot.openId,botName:bot.name,...owner.userOpenId?{ownerOpenId:owner.userOpenId}:{},...owner.userName?{ownerName:owner.userName}:{},allow:(previous?.allow??[]).filter((id)=>id!==owner.userOpenId),tone:previous?.tone??DEFAULT_TONE,savedAt:previous?.savedAt||new Date().toISOString()};return store.writeConfig(config),{ok:!0,config}}var CLI_NAME=ROVE_PRODUCT_NAME,LARK_USAGE=[`Usage: ${CLI_NAME} lark <connect|disconnect|status|allow|deny|tone>`,"","Talk to your own Rove agent from Lark (\u98DE\u4E66): DM the bot or @ it in a group. The agent","answers in the thread and starts Rove tasks for real work. The daemon must be running.","Lark is reached through lark-cli (npm i -g @larksuite/cli), which keeps the app's credentials.","","Commands:"," connect [--brand feishu|lark] Set up lark-cli's app if there is none (opens the browser),"," check its bot, and let you (lark-cli's signed-in user) talk to it"," disconnect Stop listening; the agent's project and the lark-cli app stay"," status The bot, allowed senders and tone"," allow <open_id> Let another person talk to the agent (ids: the daemon log's refusals)"," deny <open_id> Revoke a person added with allow",` tone [text] How the agent sounds; no text resets it to "${DEFAULT_TONE}"`,""].join(`
4
4
  `);function fail(message){process.stderr.write(`${CLI_NAME} lark: ${message}
5
5
  `),process.exit(1)}async function connect(store,argv){let at=argv.indexOf("--brand"),brand=at>=0?argv[at+1]:void 0,say=(line)=>process.stdout.write(`${line}
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Orchestrator}from"./chunk-n9v5x83q.js";import"./chunk-12yy593m.js";import"./chunk-ew207hnv.js";import"./chunk-fwfd7s00.js";import"./chunk-wk38kegh.js";import"./chunk-4dt1gfb3.js";import"./chunk-1wdp0qh4.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-4kepb278.js";import"./chunk-fqdx10w8.js";import"./chunk-awerm3vq.js";import"./chunk-hdea2ss8.js";import"./chunk-vk8t0x7q.js";import"./chunk-y0e28qha.js";import"./chunk-gx0hxf04.js";import"./chunk-7eqzs28e.js";import"./chunk-5x9zmxbm.js";import"./chunk-m1jbthc5.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-9k0r47z3.js";import"./chunk-7b2x6nkj.js";import"./chunk-mqfvzdpr.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-cw6xz64t.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-f60hmm20.js";import"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import"./chunk-nks2q6d9.js";import"./chunk-ptyqj15s.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{PLACEHOLDER_TASK_TITLE,Orchestrator};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{MachineHub}from"./chunk-k2fb370k.js";import"./chunk-484edssp.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-x729vdm1.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-785c8xtm.js";import{machineDaemonSocket}from"./chunk-cfb6mvz5.js";import"./chunk-y0e28qha.js";import"./chunk-gx0hxf04.js";import"./chunk-7eqzs28e.js";import"./chunk-5x9zmxbm.js";import"./chunk-ytrktnmv.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-9k0r47z3.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-tdzdrnse.js";import"./chunk-7b2x6nkj.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-wrqv141p.js";import"./chunk-nr7c9q0j.js";import{isWindowsMachine}from"./chunk-r478tzjz.js";import{listMachines}from"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import{loadStateFile}from"./chunk-nks2q6d9.js";import"./chunk-ptyqj15s.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-pn5ygqn6.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
2
+ import{MachineHub}from"./chunk-7ewphe3a.js";import"./chunk-wxrbpxzx.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-q1tm27sa.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-1jp3vdzc.js";import{machineDaemonSocket}from"./chunk-vk8t0x7q.js";import"./chunk-y0e28qha.js";import"./chunk-gx0hxf04.js";import"./chunk-7eqzs28e.js";import"./chunk-5x9zmxbm.js";import"./chunk-ytrktnmv.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-9k0r47z3.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-qpemynnh.js";import"./chunk-7b2x6nkj.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-wrqv141p.js";import"./chunk-nr7c9q0j.js";import{isWindowsMachine}from"./chunk-r478tzjz.js";import{listMachines}from"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import{loadStateFile}from"./chunk-nks2q6d9.js";import"./chunk-ptyqj15s.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-pn5ygqn6.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{interactiveEngineCommand,listPresetIds}from"./chunk-p55es0nf.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{engineEntry}from"./chunk-sy81vcaz.js";import{installedEngineIds}from"./chunk-bn8nrqde.js";import{spawn,spawnSync}from"child_process";import{statSync}from"fs";import path from"path";function whichOnPath(bin){let bunWhich=globalThis.Bun?.which;if(bunWhich)return bunWhich(bin);let out=spawnSync(process.platform==="win32"?"where":"which",[bin],{encoding:"utf8"});if(out.status!==0)return null;return out.stdout.split(`
2
+ import{interactiveEngineCommand,listPresetIds}from"./chunk-6bxdexbq.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{engineEntry}from"./chunk-s2b2nfeb.js";import{installedEngineIds}from"./chunk-zvnzy679.js";import{spawn,spawnSync}from"child_process";import{statSync}from"fs";import path from"path";function whichOnPath(bin){let bunWhich=globalThis.Bun?.which;if(bunWhich)return bunWhich(bin);let out=spawnSync(process.platform==="win32"?"where":"which",[bin],{encoding:"utf8"});if(out.status!==0)return null;return out.stdout.split(`
3
3
  `).map((l)=>l.trim()).find(Boolean)??null}var LOGIN_PROBE_MS=5000,MARK="__rove_which__";function whichInLoginShell(bin){return new Promise((resolve)=>{let out="",child;try{let quoted=`'${bin.replaceAll("'","'\\''")}'`;child=spawn(resolveSessionShell(),["-ilc",`printf '\\n${MARK}%s\\n' "$(command -v ${quoted})"`],{stdio:["ignore","pipe","ignore"],detached:!0})}catch{return resolve(null)}let timer=setTimeout(()=>child.kill("SIGKILL"),LOGIN_PROBE_MS);child.stdout?.on("data",(b)=>{out+=b.toString()}),child.on("error",()=>{clearTimeout(timer),resolve(null)}),child.on("close",()=>{clearTimeout(timer);let line=out.split(`
4
4
  `).find((l)=>l.startsWith(MARK));resolve(line?.slice(MARK.length).trim()||null)})})}var defaultDeps={which:(bin)=>whichOnPath(bin)??(process.platform==="win32"?null:whichInLoginShell(bin)),command:(vendor)=>interactiveEngineCommand(vendor)};async function probeLaunchBinary(argv,which){let bin=argv[0]?.trim();if(!bin)return{found:!1,error:"no launch command"};if(bin.includes(path.sep)||bin.startsWith(".")){try{if(statSync(bin).isFile())return{found:!0,path:bin}}catch{}return{found:!1,error:`not found at ${bin}`}}let found=await which(bin);return found?{found:!0,path:found}:{found:!1,error:"not found on PATH"}}async function detectEngineStatus(vendor,over={}){let deps={...defaultDeps,...over},detector=engineEntry(vendor).detectAccount;if(!detector)return{vendor,binary:await probeLaunchBinary(deps.command(vendor),deps.which),account:null};let status=await detector(deps.accountDeps),binary=status.binary.found?status.binary:await probeLaunchBinary(deps.command(vendor),deps.which);return{vendor,binary,account:status.account,accountError:status.accountError}}function detectEngineStatuses(vendors,over={}){return Promise.all(vendors.map((v)=>detectEngineStatus(v,over)))}function describeAccount(account){if(account===null)return"login not detectable";switch(account.kind){case"oauth":return"email"in account?`logged in (${account.email}${account.organization?`, ${account.organization}`:""})`:"logged in";case"chatgpt":return`logged in (${account.email}${account.plan?`, ${account.plan}`:""})`;case"apikey":return"API key";case"token":return`token (${account.source})`;default:return"no account"}}function engineUsable(status){return status.binary.found&&status.account?.kind!=="none"}async function probeableEngineIds(){return[...new Set([...listPresetIds(),...await installedEngineIds()])]}function summarizeEngines(statuses){let usable=[],signedOut=[];for(let status of statuses)if(engineUsable(status))usable.push(status.vendor);else if(status.binary.found)signedOut.push(status.vendor);return{usable,signedOut}}import{spawn as spawn2}from"child_process";import path2 from"path";var VERSION_PROBE_MS=3000,MAX_OUTPUT=4096;function parseVersionOutput(output){return/\b\d+(?:\.\d+)+(?:-[0-9A-Za-z.]+)?\b/.exec(output)?.[0]??null}var runVersionCommand=(bin,args)=>new Promise((resolve)=>{let out="",child;try{child=spawn2(bin,[...args],{stdio:["ignore","pipe","ignore"]})}catch{return resolve(null)}let timer=setTimeout(()=>child.kill("SIGKILL"),VERSION_PROBE_MS);child.stdout?.on("data",(b)=>{if(out.length<MAX_OUTPUT)out+=b.toString()}),child.on("error",()=>{clearTimeout(timer),resolve(null)}),child.on("close",(code)=>{clearTimeout(timer),resolve(code===0?out:null)})});async function readEngineVersion(vendor,binary,run=runVersionCommand){if(!binary.found)return null;let entry=engineEntry(vendor),own=entry.defaultCommand[0];if(!entry.versionArgs||!own)return null;if(path2.basename(binary.path)!==path2.basename(own))return null;let output=await run(binary.path,entry.versionArgs).catch(()=>null);return output===null?null:parseVersionOutput(output)}function withEngineVersions(statuses,run=runVersionCommand){return Promise.all(statuses.map(async(status)=>{let version=await readEngineVersion(status.vendor,status.binary,run);return version?{...status,version}:status}))}
5
5
  export{detectEngineStatus,detectEngineStatuses,describeAccount,probeableEngineIds,summarizeEngines,readEngineVersion,withEngineVersions};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useT,useTheme}from"./chunk-qbd69xdf.js";import"./chunk-ksrsyzhy.js";import{$jsx,$jsxs,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-484edssp.js";import"./chunk-6xr1prk6.js";import"./chunk-z2vgeqbx.js";import"./chunk-5swzs64n.js";import"./chunk-mdx18vtz.js";import"./chunk-ytrktnmv.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-9k0r47z3.js";import{BREAKING_VERSIONS,CURRENT_VERSION,breakingVersionsCrossed,fetchReleaseNotes,fetchReleaseSummaries,updateCommandFor}from"./chunk-tdzdrnse.js";import"./chunk-grbrh92f.js";import{currentLang}from"./chunk-v8ms64g1.js";import"./chunk-7b2x6nkj.js";import"./chunk-vpk5m2z6.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-c9c6yczz.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-h8qg9v95.js";import"./chunk-0zs13rdq.js";import"./chunk-nks2q6d9.js";import"./chunk-r4vwq5wv.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__toESM}from"./chunk-91sykzqq.js";import{TextAttributes}from"@opentui/core";var import_react2=__toESM(require_react_production(),1);var RELEASE_LIMIT=20;function VersionsPage(props){let{theme}=useTheme(),t=useT(),renderer=useRenderer(),[releases,setReleases]=import_react2.useState(null),[cursor,setCursor]=import_react2.useState(0),[notes,setNotes]=import_react2.useState({}),[status,setStatus]=import_react2.useState(null),selected=releases?.[cursor],crossings=selected?breakingVersionsCrossed(CURRENT_VERSION,selected.version):[],loadSummaries=props.fetchSummaries??fetchReleaseSummaries,loadNotes=props.fetchNotes??fetchReleaseNotes;import_react2.useEffect(()=>{loadSummaries(RELEASE_LIMIT).then((fetched)=>setReleases(fetched))},[loadSummaries]);let selectedVersion=selected?.version;import_react2.useEffect(()=>{if(selectedVersion===void 0||notes[selectedVersion]!==void 0)return;setNotes((cache)=>({...cache,[selectedVersion]:"loading"})),loadNotes(selectedVersion,currentLang()).then((fetched)=>{setNotes((cache)=>({...cache,[selectedVersion]:fetched??"missing"}))})},[selectedVersion,notes,loadNotes]);function move(delta){let count=releases?.length??0;if(count===0)return;setCursor((index)=>(index+delta+count)%count)}async function installSelected(){if(!selected)return;setStatus(t("update.statusRunningUpdater")),await new Promise((resolve)=>setTimeout(resolve,30)),await runShellUpdater({renderer,t,targetLabel:selected.version,command:updateCommandFor(selected.version)})}useBindings(()=>({bindings:[{key:"up",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>void installSelected()},{key:"u",cmd:()=>void installSelected()},...pageCloseBindings(props.onClose)]}));let selectedNotes=selectedVersion===void 0?void 0:notes[selectedVersion];return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes.BOLD,wrapMode:"none",children:t("update.versions.pageTitle")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:props.onClose,children:t("update.versions.closeHint")})]}),$jsxs("box",{flexDirection:"row",flexGrow:1,paddingTop:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:26,flexShrink:0,children:[releases===null?$jsx("text",{fg:theme.textMuted,children:t("update.versions.loading")}):null,releases!==null&&releases.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.versions.unavailable")}):null,(releases??[]).map((release,index)=>{let active=index===cursor,tags=[release.version===CURRENT_VERSION?t("update.versions.tagCurrent"):"",index===0?t("update.versions.tagLatest"):"",BREAKING_VERSIONS.includes(release.version)?t("update.versions.tagBreaking"):""].filter(Boolean).join(" ");return $jsxs("box",{flexDirection:"row",gap:1,paddingLeft:1,backgroundColor:active?theme.primary:void 0,onMouseUp:()=>setCursor(index),children:[$jsxs("text",{fg:active?theme.selectedListItemText:theme.text,attributes:release.version===CURRENT_VERSION?TextAttributes.BOLD:void 0,wrapMode:"none",children:["v",release.version]}),tags?$jsx("text",{fg:active?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:tags}):null]},release.version)})]}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsx("scrollbox",{flexGrow:1,flexShrink:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:0,children:[selectedNotes==="loading"?$jsx("text",{fg:theme.textMuted,children:t("update.loadingNotes")}):null,selectedNotes==="missing"?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.notesUnavailable")}):null,selectedNotes!==void 0&&selectedNotes!=="loading"&&selectedNotes!=="missing"?$jsx(ReleaseNotesBody,{body:selectedNotes.body}):null]})}),crossings.length>0?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t("update.versions.breakingWarning",{versions:crossings.join(", ")})}):null]})]}),status?$jsx("text",{fg:theme.info,wrapMode:"word",children:status}):null,$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes.DIM,wrapMode:"none",children:t("update.versions.footerHint")})})]})}var INLINE_ROWS=24;async function startVersionsHost(){await bootPaneHost({inlineRows:INLINE_ROWS,setup:()=>({root:()=>$jsx(VersionsPage,{onClose:()=>process.exit(0)})})})}export{startVersionsHost,VersionsPage};
2
+ import{ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useT,useTheme}from"./chunk-gbcyjs7c.js";import"./chunk-ksrsyzhy.js";import{$jsx,$jsxs,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-wxrbpxzx.js";import"./chunk-6xr1prk6.js";import"./chunk-qq2arpfc.js";import"./chunk-5swzs64n.js";import"./chunk-mdx18vtz.js";import"./chunk-ytrktnmv.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-9k0r47z3.js";import{BREAKING_VERSIONS,CURRENT_VERSION,breakingVersionsCrossed,fetchReleaseNotes,fetchReleaseSummaries,updateCommandFor}from"./chunk-qpemynnh.js";import"./chunk-grbrh92f.js";import{currentLang}from"./chunk-kr7jw1s4.js";import"./chunk-7b2x6nkj.js";import"./chunk-9c723k0b.js";import"./chunk-rxqdw6s5.js";import"./chunk-tn9gtf18.js";import"./chunk-c9c6yczz.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-h8qg9v95.js";import"./chunk-0zs13rdq.js";import"./chunk-nks2q6d9.js";import"./chunk-fczxyfgn.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__toESM}from"./chunk-91sykzqq.js";import{TextAttributes}from"@opentui/core";var import_react2=__toESM(require_react_production(),1);var RELEASE_LIMIT=20;function VersionsPage(props){let{theme}=useTheme(),t=useT(),renderer=useRenderer(),[releases,setReleases]=import_react2.useState(null),[cursor,setCursor]=import_react2.useState(0),[notes,setNotes]=import_react2.useState({}),[status,setStatus]=import_react2.useState(null),selected=releases?.[cursor],crossings=selected?breakingVersionsCrossed(CURRENT_VERSION,selected.version):[],loadSummaries=props.fetchSummaries??fetchReleaseSummaries,loadNotes=props.fetchNotes??fetchReleaseNotes;import_react2.useEffect(()=>{loadSummaries(RELEASE_LIMIT).then((fetched)=>setReleases(fetched))},[loadSummaries]);let selectedVersion=selected?.version;import_react2.useEffect(()=>{if(selectedVersion===void 0||notes[selectedVersion]!==void 0)return;setNotes((cache)=>({...cache,[selectedVersion]:"loading"})),loadNotes(selectedVersion,currentLang()).then((fetched)=>{setNotes((cache)=>({...cache,[selectedVersion]:fetched??"missing"}))})},[selectedVersion,notes,loadNotes]);function move(delta){let count=releases?.length??0;if(count===0)return;setCursor((index)=>(index+delta+count)%count)}async function installSelected(){if(!selected)return;setStatus(t("update.statusRunningUpdater")),await new Promise((resolve)=>setTimeout(resolve,30)),await runShellUpdater({renderer,t,targetLabel:selected.version,command:updateCommandFor(selected.version)})}useBindings(()=>({bindings:[{key:"up",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>void installSelected()},{key:"u",cmd:()=>void installSelected()},...pageCloseBindings(props.onClose)]}));let selectedNotes=selectedVersion===void 0?void 0:notes[selectedVersion];return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes.BOLD,wrapMode:"none",children:t("update.versions.pageTitle")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:props.onClose,children:t("update.versions.closeHint")})]}),$jsxs("box",{flexDirection:"row",flexGrow:1,paddingTop:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:26,flexShrink:0,children:[releases===null?$jsx("text",{fg:theme.textMuted,children:t("update.versions.loading")}):null,releases!==null&&releases.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.versions.unavailable")}):null,(releases??[]).map((release,index)=>{let active=index===cursor,tags=[release.version===CURRENT_VERSION?t("update.versions.tagCurrent"):"",index===0?t("update.versions.tagLatest"):"",BREAKING_VERSIONS.includes(release.version)?t("update.versions.tagBreaking"):""].filter(Boolean).join(" ");return $jsxs("box",{flexDirection:"row",gap:1,paddingLeft:1,backgroundColor:active?theme.primary:void 0,onMouseUp:()=>setCursor(index),children:[$jsxs("text",{fg:active?theme.selectedListItemText:theme.text,attributes:release.version===CURRENT_VERSION?TextAttributes.BOLD:void 0,wrapMode:"none",children:["v",release.version]}),tags?$jsx("text",{fg:active?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:tags}):null]},release.version)})]}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsx("scrollbox",{flexGrow:1,flexShrink:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:0,children:[selectedNotes==="loading"?$jsx("text",{fg:theme.textMuted,children:t("update.loadingNotes")}):null,selectedNotes==="missing"?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.notesUnavailable")}):null,selectedNotes!==void 0&&selectedNotes!=="loading"&&selectedNotes!=="missing"?$jsx(ReleaseNotesBody,{body:selectedNotes.body}):null]})}),crossings.length>0?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t("update.versions.breakingWarning",{versions:crossings.join(", ")})}):null]})]}),status?$jsx("text",{fg:theme.info,wrapMode:"word",children:status}):null,$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes.DIM,wrapMode:"none",children:t("update.versions.footerHint")})})]})}var INLINE_ROWS=24;async function startVersionsHost(){await bootPaneHost({inlineRows:INLINE_ROWS,setup:()=>({root:()=>$jsx(VersionsPage,{onClose:()=>process.exit(0)})})})}export{startVersionsHost,VersionsPage};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{__require}from"./chunk-91sykzqq.js";var welcomeWrite=Promise.resolve();function trackWelcomeWrite(write){welcomeWrite=write}async function launchTui(){let{startTui}=await import("./chunk-6926g5q3.js");await startTui(),await welcomeWrite;let{runPendingWelcomeInstalls}=await import("./chunk-tsmybvy0.js");runPendingWelcomeInstalls()}
2
+ import{__require}from"./chunk-91sykzqq.js";var welcomeWrite=Promise.resolve();function trackWelcomeWrite(write){welcomeWrite=write}async function launchTui(){let{startTui}=await import("./chunk-88590vqy.js");await startTui(),await welcomeWrite;let{runPendingWelcomeInstalls}=await import("./chunk-ps4srps8.js");runPendingWelcomeInstalls()}
3
3
  export{trackWelcomeWrite,launchTui};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-xmwrg55j.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-c1va68mx.js";import{ensurePluginEnginesLoaded}from"./chunk-57atdjmz.js";import{openDaemonSession}from"./chunk-sns4xm7n.js";import{requireVerbInstalled,verbInstalled}from"./chunk-g2tqea7f.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-cfb6mvz5.js";import{ApiError}from"./chunk-5x9zmxbm.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{argvHasFlag}from"./chunk-78y80xe8.js";import{errorMessage}from"./chunk-0zs13rdq.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
2
+ import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-pk67ddfn.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-9c06ccvf.js";import{ensurePluginEnginesLoaded}from"./chunk-9sq4jh9k.js";import{openDaemonSession}from"./chunk-sns4xm7n.js";import{requireVerbInstalled,verbInstalled}from"./chunk-g2tqea7f.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-vk8t0x7q.js";import{ApiError}from"./chunk-5x9zmxbm.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{argvHasFlag}from"./chunk-78y80xe8.js";import{errorMessage}from"./chunk-0zs13rdq.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
3
3
  `)}function emit(value,pretty){let warning=takeIdentityWarning(),payload=warning&&value&&typeof value==="object"&&!Array.isArray(value)?{...value,identityWarning:warning}:value;writeJson(envelopeMode?successEnvelope(payload):payload,pretty)}function fail(message,code,exitCode=1,data){let error=errorBody(new ApiError(message,code,data));if(envelopeMode)writeJson({apiVersion:ROVE_API_VERSION,ok:!1,error},!1);else writeJson({error},!1,process.stderr);process.exit(exitCode)}var USAGE_ERROR_CODES=new Set(["BAD_VERB","UNKNOWN_VERB","BAD_FLAG","MISSING_FLAG","MISSING_VERB","BAD_DAEMON","UNKNOWN_MACHINE"]);async function invokeVerb(verbName,argv,deps){return runVerb(verbName,{argv},deps)}async function runApiSubcommand(argv){let[verbName,...withMachine]=argv,{machine,rest}=takeMachineFlag(withMachine);if(envelopeMode=argvHasFlag(rest,"--envelope"),!verbName||verbName==="--help"||verbName==="-h"||verbName==="help"){if(!verbName)fail(apiUsage(),"MISSING_VERB",2);process.stdout.write(`${apiUsage()}
4
4
  `);return}ensurePluginEnginesLoaded();let verb=findVerb(verbName);if(!verb){let err=unknownVerbError(verbName);fail(`${err.message}
5
5
  ${apiUsage()}`,err.code,2,err.data)}let parsed;try{parsed=parseFlags(rest,booleanFlagsOf(verb),repeatableFlagsOf(verb))}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(parsed.help){if(!verbInstalled(verb))try{requireVerbInstalled(verb)}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data)}process.stdout.write(`${verbHelp(verb)}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{realPathOrSelf}from"./chunk-wx77yjhc.js";import{claudeGlobalConfigPath,updateSharedJsonSync,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-xdmamqy7.js";import"./chunk-m74qxqw0.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import{isObject}from"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{existsSync,lstatSync}from"fs";import path from"path";function trustClaudeWorktree(worktreePath,home){let resolved=realPathOrSelf(worktreePath),project=process.platform==="win32"?resolved.replaceAll("\\","/"):resolved,deps=vendorWriteHomeDeps(home),current=claudeGlobalConfigPath(deps.env,deps.home()),legacy=path.join(vendorConfigHome("claude",deps),".config.json"),stat=lstatSync(legacy,{throwIfNoEntry:!1});if(stat?.isSymbolicLink())throw Error("Refusing to replace a symlinked Claude config");let useLegacy=stat?.isFile()&&(stat.size>0||(stat.mode&146)!==0&&!existsSync(current));updateSharedJsonSync(useLegacy?legacy:current,(raw)=>{if(raw===void 0)return{};let doc=JSON.parse(raw);if(!isObject(doc))throw Error("Claude trust config must be a JSON object");return doc},(doc)=>{if(doc.projects!==void 0&&!isObject(doc.projects))throw Error("Claude trust projects must be an object");let projects={...doc.projects},existing=Object.hasOwn(projects,project)?projects[project]:{};if(!isObject(existing))throw Error("Claude trust project must be an object");if(existing.hasTrustDialogAccepted===!0)return;return projects[project]={...existing,hasTrustDialogAccepted:!0,hasCompletedProjectOnboarding:!0},JSON.stringify({...doc,projects},null,2)})}export{trustClaudeWorktree};
2
+ import{realPathOrSelf}from"./chunk-wx77yjhc.js";import{claudeGlobalConfigPath,updateSharedJsonSync,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-q5agazsv.js";import"./chunk-1cye0btk.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import{isObject}from"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{existsSync,lstatSync}from"fs";import path from"path";function trustClaudeWorktree(worktreePath,home){let resolved=realPathOrSelf(worktreePath),project=process.platform==="win32"?resolved.replaceAll("\\","/"):resolved,deps=vendorWriteHomeDeps(home),current=claudeGlobalConfigPath(deps.env,deps.home()),legacy=path.join(vendorConfigHome("claude",deps),".config.json"),stat=lstatSync(legacy,{throwIfNoEntry:!1});if(stat?.isSymbolicLink())throw Error("Refusing to replace a symlinked Claude config");let useLegacy=stat?.isFile()&&(stat.size>0||(stat.mode&146)!==0&&!existsSync(current));updateSharedJsonSync(useLegacy?legacy:current,(raw)=>{if(raw===void 0)return{};let doc=JSON.parse(raw);if(!isObject(doc))throw Error("Claude trust config must be a JSON object");return doc},(doc)=>{if(doc.projects!==void 0&&!isObject(doc.projects))throw Error("Claude trust projects must be an object");let projects={...doc.projects},existing=Object.hasOwn(projects,project)?projects[project]:{};if(!isObject(existing))throw Error("Claude trust project must be an object");if(existing.hasTrustDialogAccepted===!0)return;return projects[project]={...existing,hasTrustDialogAccepted:!0,hasCompletedProjectOnboarding:!0},JSON.stringify({...doc,projects},null,2)})}export{trustClaudeWorktree};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{failureHint}from"./chunk-ryfvgfan.js";import"./chunk-v8ms64g1.js";import"./chunk-7b2x6nkj.js";import{errorMessage}from"./chunk-0zs13rdq.js";import"./chunk-r4vwq5wv.js";import"./chunk-91sykzqq.js";function debugEnabled(env){return env.ROVE_DEBUG==="1"||env.ROVE_DEBUG==="1"}function failureSubject(cliName,argv){let verb=argv[2];return verb&&!verb.startsWith("-")&&!verb.includes("/")?`${cliName} ${verb}`:cliName}function summarizeCliGitError(message,cwd){if(!/not a git repository/i.test(message))return null;return`${cwd} is not a git repository \u2014 run this inside one, or pass a repo path.`}function formatCliFailure(err,opts){let subject=failureSubject(opts.cliName,opts.argv);if(debugEnabled(opts.env))return`${subject}: ${String(err instanceof Error?err.stack??err:err)}
2
+ import{failureHint}from"./chunk-vrcn6zhe.js";import"./chunk-kr7jw1s4.js";import"./chunk-7b2x6nkj.js";import{errorMessage}from"./chunk-0zs13rdq.js";import"./chunk-fczxyfgn.js";import"./chunk-91sykzqq.js";function debugEnabled(env){return env.ROVE_DEBUG==="1"||env.ROVE_DEBUG==="1"}function failureSubject(cliName,argv){let verb=argv[2];return verb&&!verb.startsWith("-")&&!verb.includes("/")?`${cliName} ${verb}`:cliName}function summarizeCliGitError(message,cwd){if(!/not a git repository/i.test(message))return null;return`${cwd} is not a git repository \u2014 run this inside one, or pass a repo path.`}function formatCliFailure(err,opts){let subject=failureSubject(opts.cliName,opts.argv);if(debugEnabled(opts.env))return`${subject}: ${String(err instanceof Error?err.stack??err:err)}
3
3
  ${failureHint(err,opts.cliName)}`;let raw=errorMessage(err),git=summarizeCliGitError(raw,opts.cwd);return`${subject}: ${git??`${raw}
4
4
  ${failureHint(err,opts.cliName)}`}`}export{summarizeCliGitError,formatCliFailure,failureSubject};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ensureGlobalRoveHooks,readStdinText,readTextWithTimeout,runHookSubcommand}from"./chunk-tyq1tvdh.js";import"./chunk-zcywdm3y.js";import"./chunk-2bgmby1d.js";import"./chunk-jpc5yh8e.js";import"./chunk-ws2q07kb.js";import"./chunk-sy81vcaz.js";import"./chunk-bn8nrqde.js";import"./chunk-6qwjd3da.js";import"./chunk-f60hmm20.js";import"./chunk-03ab55aq.js";import"./chunk-w7zv47mp.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-78y80xe8.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import"./chunk-wx77yjhc.js";import"./chunk-nks2q6d9.js";import"./chunk-b43gbrar.js";import"./chunk-7dy9dtnd.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-xdmamqy7.js";import"./chunk-m74qxqw0.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runHookSubcommand,readTextWithTimeout,readStdinText,ensureGlobalRoveHooks};
2
+ import{ensureGlobalRoveHooks,readStdinText,readTextWithTimeout,runHookSubcommand}from"./chunk-w2cf7bgt.js";import"./chunk-zcywdm3y.js";import"./chunk-2bgmby1d.js";import"./chunk-jpc5yh8e.js";import"./chunk-ws2q07kb.js";import"./chunk-s2b2nfeb.js";import"./chunk-zvnzy679.js";import"./chunk-6qwjd3da.js";import"./chunk-f60hmm20.js";import"./chunk-03ab55aq.js";import"./chunk-w7zv47mp.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-5kyajt3q.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-52stxk43.js";import"./chunk-h8qg9v95.js";import"./chunk-78y80xe8.js";import"./chunk-0zs13rdq.js";import"./chunk-tm6vvy5t.js";import"./chunk-wx77yjhc.js";import"./chunk-nks2q6d9.js";import"./chunk-nbfxhvby.js";import"./chunk-n5at7bsq.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-q5agazsv.js";import"./chunk-1cye0btk.js";import"./chunk-sckqk79z.js";import"./chunk-y8hjgmn0.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-8rxg12aj.js";import"./chunk-n835vmw4.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runHookSubcommand,readTextWithTimeout,readStdinText,ensureGlobalRoveHooks};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{chatConnectorStatuses,connectChatConnector,disconnectChatConnector,runConnectorCli,startChatConnectors,updateChatConnector}from"./chunk-q04f1v0q.js";import"./chunk-91sykzqq.js";export{updateChatConnector,startChatConnectors,runConnectorCli,disconnectChatConnector,connectChatConnector,chatConnectorStatuses};
2
+ import{chatConnectorStatuses,connectChatConnector,disconnectChatConnector,runConnectorCli,startChatConnectors,updateChatConnector}from"./chunk-h407rq50.js";import"./chunk-91sykzqq.js";export{updateChatConnector,startChatConnectors,runConnectorCli,disconnectChatConnector,connectChatConnector,chatConnectorStatuses};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{findVerb}from"./chunk-c1va68mx.js";import{VERB_GROUP_IDS}from"./chunk-g2tqea7f.js";import{loadStateFile,updateStateFile}from"./chunk-nks2q6d9.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
2
+ import{findVerb}from"./chunk-9c06ccvf.js";import{VERB_GROUP_IDS}from"./chunk-g2tqea7f.js";import{loadStateFile,updateStateFile}from"./chunk-nks2q6d9.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
3
3
  export{INBOUND_KEY,INBOUND_CLASSES,inboundClassOf,deniedClasses,inboundRefusal,setInbound};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{vendorFromArgv}from"./chunk-5rxef858.js";import{engineEntry}from"./chunk-sy81vcaz.js";import{isContribEngine}from"./chunk-bn8nrqde.js";import{getCustomEngineIds,getPersistedString}from"./chunk-52stxk43.js";import{argvHasFlag}from"./chunk-78y80xe8.js";import{getPersistedBool}from"./chunk-nks2q6d9.js";import{roveCliInvocation}from"./chunk-6hjt5an9.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-8q0nmdh3.js";var PERMISSION_BYPASS_KEY="engines.permissionBypass";function permissionBypassEnabled(){return getPersistedBool(PERMISSION_BYPASS_KEY,!0)}function engineCommandKey(vendor){return`engineCommand.${vendor}`}function engineNameKey(vendor){return`engineName.${vendor}`}function engineDisplayName(vendor){return getPersistedString(engineNameKey(vendor))?.trim()||engineEntry(vendor).displayName}function humanizeSlug(id){return id.split(/[-_]+/).filter((word)=>word.length>0).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")}function engineRenamedFrom(vendor,override){let name=override.trim(),base=engineEntry(vendor).displayName;if(!name||name===base||name===humanizeSlug(vendor))return;return base}function defaultEngineCommand(vendor){return engineEntry(coerceVendorId(vendor)).defaultCommand}function parseEngineCommand(command){let out=[],token="",hasToken=!1,quote=null;for(let ch of command){if(quote){if(ch===quote)quote=null;else token+=ch;continue}if(ch==='"'||ch==="'"){quote=ch,hasToken=!0;continue}if(/\s/.test(ch)){if(hasToken)out.push(token),token="",hasToken=!1;continue}token+=ch,hasToken=!0}if(hasToken)out.push(token);return out}function interactiveEngineCommand(vendor,effort,model){let v=coerceVendorId(vendor),override=getPersistedString(engineCommandKey(v))?.trim(),base=(()=>{if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(v)})();return withEngineHostedArgs(withEngineModel(withEngineEffort(base,v,effort),v,model),v)}function withEngineHostedArgs(argv,vendor){let entry=engineEntry(coerceVendorId(vendor)),bypass=entry.permissionBypass,bypassed=bypass&&permissionBypassEnabled()&&!bypass.present.some((f)=>argvHasFlag(argv,f))?bypass.argv(argv):argv,args=entry.terminalTitle?.launchArgs,titled=args&&args.length>0?[...bypassed,...args]:bypassed;return entry.hostedStartArgv?.(titled)??titled}function withEngineEffort(argv,vendor,effort){let trimmed=effort?.trim();if(!trimmed)return argv;let entry=engineEntry(coerceVendorId(vendor));if(!entry.effortLevels?.includes(trimmed))return argv;return entry.effortArgv?.(argv,trimmed)??argv}function withEngineModel(argv,vendor,model){let trimmed=model?.trim();if(!trimmed)return argv;return engineEntry(coerceVendorId(vendor)).modelArgv?.(argv,trimmed)??argv}function roveApiInvocation(){let quote=(a)=>/^[A-Za-z0-9_/.:=-]+$/.test(a)?a:`'${a.replace(/'/g,"'\\''")}'`;try{return[...roveCliInvocation(),"api"].map(quote).join(" ")}catch{return"rove api"}}import{randomUUID}from"crypto";function hasFlag(argv,flag){return argv.some((a)=>a===flag||a.startsWith(`${flag}=`))}function controlsOwnSession(identity,argv){return(identity?.sessionControlFlags??[]).some((flag)=>hasFlag(argv,flag))}function pinSessionArgv(identity,argv,sessionId){if(!identity?.pinFlag)return argv;if(controlsOwnSession(identity,argv))return argv;return[...argv,identity.pinFlag,sessionId]}function acceptsPinnedSession(identity,argv){return!!identity?.pinFlag&&!controlsOwnSession(identity,argv)}function resumeSessionArgv(identity,base,sessionId){if(!sessionId||!identity?.resumeArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.resumeArgv(base,sessionId)}function pickUnclaimedSessionId(ids,claimed){for(let i=ids.length-1;i>=0;i--){let id=ids[i];if(id&&!claimed.has(id))return id}return null}function forkSessionArgvFor(identity,base,sourceId,newId){if(!sourceId||!identity?.forkArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.forkArgv(base,sourceId,newId)}function acceptsSessionFork(identity){return!!identity?.forkArgv}var GENERIC_PROTOCOL="generic",ENGINE_PROTOCOLS=BUILTIN_VENDORS;function engineProtocolKey(id){return`engineProtocol.${id}`}function getEngineProtocol(id){if(isBuiltinVendor(id)||isContribEngine(id))return id;let raw=getPersistedString(engineProtocolKey(id))?.trim();return raw&&ENGINE_PROTOCOLS.includes(raw)?raw:void 0}function isPresetId(id){return isBuiltinVendor(id)||isContribEngine(id)||getCustomEngineIds().includes(id)}function listPresetIds(){return[...new Set([...BUILTIN_VENDORS,...getCustomEngineIds()])]}function describePreset(id){let command=getPersistedString(engineCommandKey(id))?.trim()||defaultEngineCommand(id).join(" ");return{id,name:engineDisplayName(id),command,protocol:getEngineProtocol(id)??GENERIC_PROTOCOL,builtin:isBuiltinVendor(id)}}function listEnginePresets(){return listPresetIds().map(describePreset)}function resolveCommandProtocol(command){let trimmed=command?.trim();if(!trimmed)return GENERIC_PROTOCOL;if(isPresetId(trimmed))return getEngineProtocol(trimmed)??GENERIC_PROTOCOL;let fromArgv=vendorFromArgv(trimmed);if(fromArgv)return fromArgv;let argv0=parseEngineCommand(trimmed)[0];if(argv0)for(let id of getCustomEngineIds()){let preset=getPersistedString(engineCommandKey(id))?.trim();if(preset&&parseEngineCommand(preset)[0]===argv0)return getEngineProtocol(id)??GENERIC_PROTOCOL}return GENERIC_PROTOCOL}function engineLaunchArgv(spec){let command=spec.command?.trim();if(!command)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);let vendor=(isPresetId(command)?getEngineProtocol(command):void 0)??resolveCommandProtocol(command),base=isPresetId(command)?presetBaseArgv(command):(()=>{let argv=parseEngineCommand(command);return argv.length>0?argv:null})();if(!base)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);return withEngineHostedArgs(withEngineModel(withEngineEffort(base,vendor,spec.effort),vendor,spec.model),vendor)}function presetBaseArgv(id){let override=getPersistedString(engineCommandKey(id))?.trim();if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(id)}function sessionProtocol(vendor){let id=vendor?.trim();if(!id)return"claude";return getEngineProtocol(id)??id}function protocolEntry(vendor){return engineEntry(sessionProtocol(vendor))}function withPinnedSessionId(argv,vendor,newId=randomUUID){let identity=engineEntry(sessionProtocol(vendor)).sessionIdentity;if(!acceptsPinnedSession(identity,argv))return{argv,sessionId:null};let sessionId=newId();return{argv:pinSessionArgv(identity,argv,sessionId),sessionId}}function engineResumeArgv(base,vendor,sessionId){return resumeSessionArgv(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sessionId)}function engineCanFork(vendor){return acceptsSessionFork(engineEntry(sessionProtocol(vendor)).sessionIdentity)}function engineForkArgv(base,vendor,sourceId,newId){return forkSessionArgvFor(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sourceId,newId)}
2
+ import{vendorFromArgv}from"./chunk-fj7nj0vy.js";import{engineEntry}from"./chunk-s2b2nfeb.js";import{isContribEngine}from"./chunk-zvnzy679.js";import{getCustomEngineIds,getPersistedString}from"./chunk-52stxk43.js";import{argvHasFlag}from"./chunk-78y80xe8.js";import{getPersistedBool}from"./chunk-nks2q6d9.js";import{roveCliInvocation}from"./chunk-6hjt5an9.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-8q0nmdh3.js";var PERMISSION_BYPASS_KEY="engines.permissionBypass";function permissionBypassEnabled(){return getPersistedBool(PERMISSION_BYPASS_KEY,!0)}function engineCommandKey(vendor){return`engineCommand.${vendor}`}function engineNameKey(vendor){return`engineName.${vendor}`}function engineDisplayName(vendor){return getPersistedString(engineNameKey(vendor))?.trim()||engineEntry(vendor).displayName}function humanizeSlug(id){return id.split(/[-_]+/).filter((word)=>word.length>0).map((word)=>word.charAt(0).toUpperCase()+word.slice(1)).join(" ")}function engineRenamedFrom(vendor,override){let name=override.trim(),base=engineEntry(vendor).displayName;if(!name||name===base||name===humanizeSlug(vendor))return;return base}function defaultEngineCommand(vendor){return engineEntry(coerceVendorId(vendor)).defaultCommand}function parseEngineCommand(command){let out=[],token="",hasToken=!1,quote=null;for(let ch of command){if(quote){if(ch===quote)quote=null;else token+=ch;continue}if(ch==='"'||ch==="'"){quote=ch,hasToken=!0;continue}if(/\s/.test(ch)){if(hasToken)out.push(token),token="",hasToken=!1;continue}token+=ch,hasToken=!0}if(hasToken)out.push(token);return out}function interactiveEngineCommand(vendor,effort,model){let v=coerceVendorId(vendor),override=getPersistedString(engineCommandKey(v))?.trim(),base=(()=>{if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(v)})();return withEngineHostedArgs(withEngineModel(withEngineEffort(base,v,effort),v,model),v)}function withEngineHostedArgs(argv,vendor){let entry=engineEntry(coerceVendorId(vendor)),bypass=entry.permissionBypass,bypassed=bypass&&permissionBypassEnabled()&&!bypass.present.some((f)=>argvHasFlag(argv,f))?bypass.argv(argv):argv,args=entry.terminalTitle?.launchArgs,titled=args&&args.length>0?[...bypassed,...args]:bypassed;return entry.hostedStartArgv?.(titled)??titled}function withEngineEffort(argv,vendor,effort){let trimmed=effort?.trim();if(!trimmed)return argv;let entry=engineEntry(coerceVendorId(vendor));if(!entry.effortLevels?.includes(trimmed))return argv;return entry.effortArgv?.(argv,trimmed)??argv}function withEngineModel(argv,vendor,model){let trimmed=model?.trim();if(!trimmed)return argv;return engineEntry(coerceVendorId(vendor)).modelArgv?.(argv,trimmed)??argv}function roveApiInvocation(){let quote=(a)=>/^[A-Za-z0-9_/.:=-]+$/.test(a)?a:`'${a.replace(/'/g,"'\\''")}'`;try{return[...roveCliInvocation(),"api"].map(quote).join(" ")}catch{return"rove api"}}import{randomUUID}from"crypto";function hasFlag(argv,flag){return argv.some((a)=>a===flag||a.startsWith(`${flag}=`))}function controlsOwnSession(identity,argv){return(identity?.sessionControlFlags??[]).some((flag)=>hasFlag(argv,flag))}function pinSessionArgv(identity,argv,sessionId){if(!identity?.pinFlag)return argv;if(controlsOwnSession(identity,argv))return argv;return[...argv,identity.pinFlag,sessionId]}function acceptsPinnedSession(identity,argv){return!!identity?.pinFlag&&!controlsOwnSession(identity,argv)}function resumeSessionArgv(identity,base,sessionId){if(!sessionId||!identity?.resumeArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.resumeArgv(base,sessionId)}function pickUnclaimedSessionId(ids,claimed){for(let i=ids.length-1;i>=0;i--){let id=ids[i];if(id&&!claimed.has(id))return id}return null}function forkSessionArgvFor(identity,base,sourceId,newId){if(!sourceId||!identity?.forkArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.forkArgv(base,sourceId,newId)}function acceptsSessionFork(identity){return!!identity?.forkArgv}var GENERIC_PROTOCOL="generic",ENGINE_PROTOCOLS=BUILTIN_VENDORS;function engineProtocolKey(id){return`engineProtocol.${id}`}function getEngineProtocol(id){if(isBuiltinVendor(id)||isContribEngine(id))return id;let raw=getPersistedString(engineProtocolKey(id))?.trim();return raw&&ENGINE_PROTOCOLS.includes(raw)?raw:void 0}function isPresetId(id){return isBuiltinVendor(id)||isContribEngine(id)||getCustomEngineIds().includes(id)}function listPresetIds(){return[...new Set([...BUILTIN_VENDORS,...getCustomEngineIds()])]}function describePreset(id){let command=getPersistedString(engineCommandKey(id))?.trim()||defaultEngineCommand(id).join(" ");return{id,name:engineDisplayName(id),command,protocol:getEngineProtocol(id)??GENERIC_PROTOCOL,builtin:isBuiltinVendor(id)}}function listEnginePresets(){return listPresetIds().map(describePreset)}function resolveCommandProtocol(command){let trimmed=command?.trim();if(!trimmed)return GENERIC_PROTOCOL;if(isPresetId(trimmed))return getEngineProtocol(trimmed)??GENERIC_PROTOCOL;let fromArgv=vendorFromArgv(trimmed);if(fromArgv)return fromArgv;let argv0=parseEngineCommand(trimmed)[0];if(argv0)for(let id of getCustomEngineIds()){let preset=getPersistedString(engineCommandKey(id))?.trim();if(preset&&parseEngineCommand(preset)[0]===argv0)return getEngineProtocol(id)??GENERIC_PROTOCOL}return GENERIC_PROTOCOL}function engineLaunchArgv(spec){let command=spec.command?.trim();if(!command)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);let vendor=(isPresetId(command)?getEngineProtocol(command):void 0)??resolveCommandProtocol(command),base=isPresetId(command)?presetBaseArgv(command):(()=>{let argv=parseEngineCommand(command);return argv.length>0?argv:null})();if(!base)return interactiveEngineCommand(spec.vendor,spec.effort,spec.model);return withEngineHostedArgs(withEngineModel(withEngineEffort(base,vendor,spec.effort),vendor,spec.model),vendor)}function presetBaseArgv(id){let override=getPersistedString(engineCommandKey(id))?.trim();if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(id)}function sessionProtocol(vendor){let id=vendor?.trim();if(!id)return"claude";return getEngineProtocol(id)??id}function protocolEntry(vendor){return engineEntry(sessionProtocol(vendor))}function withPinnedSessionId(argv,vendor,newId=randomUUID){let identity=engineEntry(sessionProtocol(vendor)).sessionIdentity;if(!acceptsPinnedSession(identity,argv))return{argv,sessionId:null};let sessionId=newId();return{argv:pinSessionArgv(identity,argv,sessionId),sessionId}}function engineResumeArgv(base,vendor,sessionId){return resumeSessionArgv(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sessionId)}function engineCanFork(vendor){return acceptsSessionFork(engineEntry(sessionProtocol(vendor)).sessionIdentity)}function engineForkArgv(base,vendor,sourceId,newId){return forkSessionArgvFor(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sourceId,newId)}
3
3
  export{PERMISSION_BYPASS_KEY,engineCommandKey,engineNameKey,engineDisplayName,humanizeSlug,engineRenamedFrom,defaultEngineCommand,interactiveEngineCommand,roveApiInvocation,pickUnclaimedSessionId,GENERIC_PROTOCOL,ENGINE_PROTOCOLS,engineProtocolKey,getEngineProtocol,listPresetIds,describePreset,listEnginePresets,resolveCommandProtocol,engineLaunchArgv,sessionProtocol,protocolEntry,withPinnedSessionId,engineResumeArgv,engineCanFork,engineForkArgv};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{readTabsSnapshot}from"./chunk-evf15cs5.js";import{parseNumstatRows}from"./chunk-fxpbaff2.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-dmzg9zdc.js";import{readHeadSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import{READ_ONLY_GIT_ENV}from"./chunk-9k0r47z3.js";import{t}from"./chunk-v8ms64g1.js";import{engineCanFork,engineDisplayName,getEngineProtocol,protocolEntry,sessionProtocol}from"./chunk-p55es0nf.js";import{execHostForWorktreePath}from"./chunk-cw6xz64t.js";import{supportsStructuredHistory}from"./chunk-sy81vcaz.js";import{getPersistedString,getPersistedValue}from"./chunk-52stxk43.js";import{recordSpawn}from"./chunk-h8qg9v95.js";import{errorMessage}from"./chunk-0zs13rdq.js";import{rollupPr}from"./chunk-sckqk79z.js";import{isObject}from"./chunk-a6z2ggxd.js";import{acquireSync,releaseSync}from"./chunk-n835vmw4.js";import{secretsPath}from"./chunk-pzbcbmm4.js";import{readFile,stat}from"fs/promises";var PER_SESSION=3,SNIPPET_RADIUS=60,READ_BATCH=8,READ_BUDGET_MS=1500;function snippetOf(text,needle){let flat=text.replace(/\s+/g," "),want=needle.replace(/\s+/g," "),at=flat.toLowerCase().indexOf(want.toLowerCase());if(at<0)return null;let start=Math.max(0,at-SNIPPET_RADIUS),end=Math.min(flat.length,at+want.length+SNIPPET_RADIUS);return`${start>0?"\u2026":""}${flat.slice(start,end).trim()}${end<flat.length?"\u2026":""}`}function matchMessages(messages,needle,max){let out=[];for(let m of messages){if(m.role!=="user"&&m.role!=="assistant")continue;for(let b of m.blocks){if(b.type!=="text")continue;let snippet=snippetOf(b.text,needle);if(snippet===null)continue;out.push({role:m.role,at:m.timestamp,snippet});break}if(out.length>=max)break}return out}function prefilterToken(query){return query.split(/["\\\s]+/).reduce((a,b)=>b.length>a.length?b:a,"")}async function candidatesOf(tasks,skipped){let claimed=new Set,pinned=[],unpinned=[],sharedDirs=new Map;for(let t2 of tasks)if(t2.worktreePath)sharedDirs.set(t2.worktreePath,(sharedDirs.get(t2.worktreePath)??0)+1);for(let task of tasks){if(task.origin){skipped.push({taskId:task.id,reason:"other-machine"});continue}let vendor=task.vendor,tabs=(readTabsSnapshot(task.id)?.tabs??[]).filter((t2)=>t2.kind==="engine"),any=!1;for(let tab of tabs){let tabVendor=tab.vendor??vendor;if(!tabVendor||!supportsStructuredHistory(sessionProtocol(tabVendor))||!tab.sessionId)continue;if(claimed.has(tab.sessionId))continue;claimed.add(tab.sessionId);let reader=protocolEntry(tabVendor).history;pinned.push({task,reader,sessionId:tab.sessionId,tabId:tab.id,path:null,mtimeMs:0}),any=!0}if(any)continue;if(!vendor||!supportsStructuredHistory(sessionProtocol(vendor))){skipped.push({taskId:task.id,reason:"engine-unsupported"});continue}let worktree=task.worktreePath;if(worktree&&(sharedDirs.get(worktree)??0)===1)unpinned.push({task,reader:protocolEntry(vendor).history,worktree})}let listed=await Promise.all(unpinned.map(async({task,reader,worktree})=>(await reader.listSessionIdsForWorktree(worktree)).filter((id)=>!claimed.has(id)).map((sessionId)=>({task,reader,sessionId,path:null,mtimeMs:0})))),all=[...pinned,...listed.flat()];return Promise.all(all.map(async(c)=>{let worktree=c.task.worktreePath||c.task.repo,path=await c.reader.transcriptPath(c.sessionId,worktree).catch(()=>null),mtimeMs=path?await stat(path).then((s)=>s.mtimeMs,()=>0):0;return{...c,path,mtimeMs}}))}async function filesContaining(paths,token){if(paths.length===0||token==="")return new Set(paths);let rg=Bun.which("rg");if(rg){let proc=Bun.spawn([rg,"-l","-i","-F","--no-messages","--",token,...paths],{stdout:"pipe",stderr:"ignore"}),out=await new Response(proc.stdout).text();return await proc.exited,new Set(out.split(`
2
+ import{readTabsSnapshot}from"./chunk-7cm66y22.js";import{parseNumstatRows}from"./chunk-fxpbaff2.js";import{parsePorcelainRows,unquoteGitPath}from"./chunk-dmzg9zdc.js";import{readHeadSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import{READ_ONLY_GIT_ENV}from"./chunk-9k0r47z3.js";import{t}from"./chunk-kr7jw1s4.js";import{engineCanFork,engineDisplayName,getEngineProtocol,protocolEntry,sessionProtocol}from"./chunk-6bxdexbq.js";import{execHostForWorktreePath}from"./chunk-cw6xz64t.js";import{supportsStructuredHistory}from"./chunk-s2b2nfeb.js";import{getPersistedString,getPersistedValue}from"./chunk-52stxk43.js";import{recordSpawn}from"./chunk-h8qg9v95.js";import{errorMessage}from"./chunk-0zs13rdq.js";import{rollupPr}from"./chunk-sckqk79z.js";import{isObject}from"./chunk-a6z2ggxd.js";import{acquireSync,releaseSync}from"./chunk-n835vmw4.js";import{secretsPath}from"./chunk-pzbcbmm4.js";import{readFile,stat}from"fs/promises";var PER_SESSION=3,SNIPPET_RADIUS=60,READ_BATCH=8,READ_BUDGET_MS=1500;function snippetOf(text,needle){let flat=text.replace(/\s+/g," "),want=needle.replace(/\s+/g," "),at=flat.toLowerCase().indexOf(want.toLowerCase());if(at<0)return null;let start=Math.max(0,at-SNIPPET_RADIUS),end=Math.min(flat.length,at+want.length+SNIPPET_RADIUS);return`${start>0?"\u2026":""}${flat.slice(start,end).trim()}${end<flat.length?"\u2026":""}`}function matchMessages(messages,needle,max){let out=[];for(let m of messages){if(m.role!=="user"&&m.role!=="assistant")continue;for(let b of m.blocks){if(b.type!=="text")continue;let snippet=snippetOf(b.text,needle);if(snippet===null)continue;out.push({role:m.role,at:m.timestamp,snippet});break}if(out.length>=max)break}return out}function prefilterToken(query){return query.split(/["\\\s]+/).reduce((a,b)=>b.length>a.length?b:a,"")}async function candidatesOf(tasks,skipped){let claimed=new Set,pinned=[],unpinned=[],sharedDirs=new Map;for(let t2 of tasks)if(t2.worktreePath)sharedDirs.set(t2.worktreePath,(sharedDirs.get(t2.worktreePath)??0)+1);for(let task of tasks){if(task.origin){skipped.push({taskId:task.id,reason:"other-machine"});continue}let vendor=task.vendor,tabs=(readTabsSnapshot(task.id)?.tabs??[]).filter((t2)=>t2.kind==="engine"),any=!1;for(let tab of tabs){let tabVendor=tab.vendor??vendor;if(!tabVendor||!supportsStructuredHistory(sessionProtocol(tabVendor))||!tab.sessionId)continue;if(claimed.has(tab.sessionId))continue;claimed.add(tab.sessionId);let reader=protocolEntry(tabVendor).history;pinned.push({task,reader,sessionId:tab.sessionId,tabId:tab.id,path:null,mtimeMs:0}),any=!0}if(any)continue;if(!vendor||!supportsStructuredHistory(sessionProtocol(vendor))){skipped.push({taskId:task.id,reason:"engine-unsupported"});continue}let worktree=task.worktreePath;if(worktree&&(sharedDirs.get(worktree)??0)===1)unpinned.push({task,reader:protocolEntry(vendor).history,worktree})}let listed=await Promise.all(unpinned.map(async({task,reader,worktree})=>(await reader.listSessionIdsForWorktree(worktree)).filter((id)=>!claimed.has(id)).map((sessionId)=>({task,reader,sessionId,path:null,mtimeMs:0})))),all=[...pinned,...listed.flat()];return Promise.all(all.map(async(c)=>{let worktree=c.task.worktreePath||c.task.repo,path=await c.reader.transcriptPath(c.sessionId,worktree).catch(()=>null),mtimeMs=path?await stat(path).then((s)=>s.mtimeMs,()=>0):0;return{...c,path,mtimeMs}}))}async function filesContaining(paths,token){if(paths.length===0||token==="")return new Set(paths);let rg=Bun.which("rg");if(rg){let proc=Bun.spawn([rg,"-l","-i","-F","--no-messages","--",token,...paths],{stdout:"pipe",stderr:"ignore"}),out=await new Response(proc.stdout).text();return await proc.exited,new Set(out.split(`
3
3
  `).filter(Boolean))}let needle=token.toLowerCase(),hits=new Set;for(let p of paths)if((await readFile(p,"utf8").catch(()=>"")).toLowerCase().includes(needle))hits.add(p);return hits}async function searchTasks(tasks,query,limit,budgetMs=READ_BUDGET_MS){let started=Date.now(),skipped=[],candidates=await candidatesOf(tasks,skipped),withPath=candidates.filter((c)=>c.path!==null).map((c)=>c.path),hits=await filesContaining(withPath,prefilterToken(query)),toRead=candidates.filter((c)=>c.path===null||hits.has(c.path)).sort((a,b)=>b.mtimeMs-a.mtimeMs),matches=[],scanned=0;while(scanned<toRead.length&&matches.length<limit&&Date.now()-started<budgetMs){let batch=toRead.slice(scanned,scanned+READ_BATCH),read=await Promise.all(batch.map((c)=>c.reader.readHistory(c.sessionId).catch(()=>[])));for(let[i,messages]of read.entries()){let c=batch[i];scanned++;for(let m of matchMessages(messages,query,Math.min(PER_SESSION,limit-matches.length)))matches.push({taskId:c.task.id,title:c.task.title,...c.tabId?{tabId:c.tabId}:{},...m});if(matches.length>=limit)break}}return{query,matches,skipped,truncated:scanned<toRead.length}}async function runWorktreeGit(worktreePath,args,options={}){if(!worktreePath)return{stdout:"",stderr:"worktreePath is required",status:-1};let exec=(options.execForPath??execHostForWorktreePath)(worktreePath),controller=options.timeoutMs&&options.timeoutMs>0?new AbortController:null,timedOut=!1,timer=controller?setTimeout(()=>{timedOut=!0,controller.abort()},options.timeoutMs):null,signal=controller&&options.signal?AbortSignal.any([controller.signal,options.signal]):controller?.signal??options.signal,result;try{recordSpawn("worktree.content",["git",...args],worktreePath),result=await exec.run(["git",...args],{cwd:worktreePath,env:READ_ONLY_GIT_ENV,signal})}catch(err){if(timer)clearTimeout(timer);return{stdout:"",stderr:errorMessage(err),status:-1}}if(timer)clearTimeout(timer);if(timedOut&&result.exitCode===-1&&!result.stderr)return{stdout:result.stdout,stderr:`git ${args.join(" ")} timed out after ${options.timeoutMs}ms`,status:-1};return{stdout:result.stdout,stderr:result.stderr,status:result.exitCode}}function readLocalWorktreeHead(worktreePath,deps={}){if(!worktreePath||(deps.execForPath??execHostForWorktreePath)(worktreePath).isRemote)return null;try{let dirs=resolveGitDirs(worktreePath);return dirs?readHeadSha(dirs):null}catch{return null}}function worktreeFilePath(worktreePath,relPath){if(!worktreePath||!relPath)return null;if(/^[/\\]/.test(relPath)||/^[a-zA-Z]:[/\\]/.test(relPath))return null;if(relPath.split(/[/\\]/).some((part)=>part===".."))return null;let parts=relPath.split("/");return`${worktreePath.replace(/\/+$/,"")}/${parts.filter(Boolean).join("/")}`}async function worktreeFileSize(worktreePath,relPath,deps={}){let path=worktreeFilePath(worktreePath,relPath);if(!path)return null;let exec=(deps.execForPath??execHostForWorktreePath)(worktreePath);try{let res=await exec.run(["wc","-c",path]);if(res.exitCode!==0)return null;let n=Number.parseInt(res.stdout.trim().split(/\s+/)[0]??"",10);return Number.isFinite(n)?n:null}catch{return null}}async function readWorktreeFile(worktreePath,relPath,deps={}){let path=worktreeFilePath(worktreePath,relPath);if(!path)return null;let exec=(deps.execForPath??execHostForWorktreePath)(worktreePath);try{return await exec.readFile(path)}catch{return null}}import{readdir}from"fs/promises";import{join}from"path";async function runGit(args,cwd,signal){if(!cwd)throw Error("git(): cwd is required");let result=await runWorktreeGit(cwd,args,{signal}),exitCode=result.status??-1;if(exitCode!==0){let stderr=(result.stderr??"").trim(),stdout=(result.stdout??"").trim();throw Error(`git ${args.join(" ")} (cwd=${cwd}) exited with code ${exitCode}: ${stderr||stdout||"(no output)"}`)}return result.stdout??""}async function listFiles(worktreePath,signal){let out;try{out=await runGit(["ls-files","--cached","--others","--exclude-standard","--full-name"],worktreePath,signal)}catch(err){if(!(err instanceof Error&&err.message.includes("not a git repository"))||execHostForWorktreePath(worktreePath).isRemote)throw err;return listFolderFiles(worktreePath,signal)}let lines=out.split(`
4
4
  `).map((l)=>unquoteGitPath(l.replace(/\r$/,""))),set=new Set;for(let line of lines)if(line.length>0)set.add(line);return Array.from(set).sort()}var FOLDER_WALK_CAP=50000,FOLDER_WALK_SKIP=new Set([".git","node_modules"]);async function listFolderFiles(root,signal){let files=[],dirs=[""],seen=0;for(let i=0;i<dirs.length&&seen<FOLDER_WALK_CAP&&!signal?.aborted;i++){let rel=dirs[i],entries=await readdir(rel?join(root,rel):root,{withFileTypes:!0}).catch(()=>[]);for(let entry of entries){seen++;let path=rel?`${rel}/${entry.name}`:entry.name;if(entry.isDirectory()){if(!FOLDER_WALK_SKIP.has(entry.name))dirs.push(path)}else files.push(path)}}return files.sort()}async function statusFiles(worktreePath,signal){let out=await runGit(["status","--porcelain"],worktreePath,signal),entries=parseStatusEntries(out),stats=new Map;try{let diffOut=await runGit(["diff","--no-color","--numstat","-z","HEAD"],worktreePath,signal);stats=new Map(parseNumstat(diffOut).map((n)=>[n.path,{added:n.added,deleted:n.deleted}]))}catch{try{let cachedOut=await runGit(["diff","--no-color","--numstat","-z","--cached"],worktreePath,signal);stats=new Map(parseNumstat(cachedOut).map((n)=>[n.path,{added:n.added,deleted:n.deleted}]))}catch{stats=new Map}}let merged=entries.map((e)=>{let s=stats.get(e.path);if(s)return{...e,added:s.added,deleted:s.deleted};return e});if(merged.some(isUntrackedDir))try{let others=(await runGit(["ls-files","--others","--exclude-standard","--full-name"],worktreePath,signal)).split(`
5
5
  `).filter((l)=>l.length>0);attachUntrackedChildren(merged,others)}catch{}let untracked=[];for(let e of merged){if(e.status!=="?")continue;if(e.children)untracked.push(...e.children);else if(e.added==null&&!e.path.endsWith("/"))untracked.push(e)}if(untracked.length>0)await Promise.all(untracked.map(async(e)=>{let added=await countAddedLines(worktreePath,e.path,signal);if(added!=null)e.added=added,e.deleted=0}));for(let e of merged){if(!e.children)continue;let sum=0,counted=!1;for(let c of e.children)if(c.added!=null)sum+=c.added,counted=!0;if(counted)e.added=sum,e.deleted=0}return merged}function isUntrackedDir(e){return e.status==="?"&&e.path.endsWith("/")}function attachUntrackedChildren(entries,others){for(let e of entries){if(!isUntrackedDir(e))continue;e.children=others.filter((p)=>p.startsWith(e.path)).map((p)=>({path:p,status:"?"}))}}var BASE_TTL_MS=300000,baseCache=new Map;async function resolveBase(worktreePath,prBaseRef,signal){if(prBaseRef&&prBaseRef.trim().length>0)return prBaseRef.trim();let hit=baseCache.get(worktreePath);if(hit&&Date.now()-hit.at<BASE_TTL_MS){if(hit.head===void 0)return hit.base;if((readLocalWorktreeHead(worktreePath)??await revParse("HEAD",worktreePath,signal))===hit.head)return hit.base}let resolved=await resolveBaseUncached(worktreePath,signal);if(!signal?.aborted)baseCache.set(worktreePath,{...resolved,at:Date.now()});return resolved.base}async function resolveBaseUncached(worktreePath,signal){try{let head2=(await runGit(["symbolic-ref","--short","refs/remotes/origin/HEAD"],worktreePath,signal)).trim();if(head2.length>0)return{base:head2}}catch{}for(let guess of["origin/main","origin/master"])try{return await runGit(["rev-parse","--verify","--quiet",guess],worktreePath,signal),{base:guess}}catch{}let head=await revParse("HEAD",worktreePath,signal);for(let guess of["main","master"]){let sha=await revParse(guess,worktreePath,signal);if(sha!=null&&sha!==head)return{base:guess,head}}return{base:null,head}}async function revParse(ref,worktreePath,signal){try{let out=(await runGit(["rev-parse","--verify","--quiet",ref],worktreePath,signal)).trim();return out.length>0?out:null}catch{return null}}async function statusFilesBranch(worktreePath,base,signal){let range=`${base}...HEAD`,[nameStatusOut,numstatOut]=await Promise.all([runGit(["diff","--no-color","--name-status",range],worktreePath,signal),runGit(["diff","--no-color","--numstat","-z",range],worktreePath,signal)]),counts=new Map(parseNumstat(numstatOut).map((n)=>[n.path,{added:n.added,deleted:n.deleted}])),entries=[];for(let{status,path}of parseNameStatus(nameStatusOut)){let c=counts.get(path);entries.push({path,status,added:c?.added,deleted:c?.deleted})}return entries}function parseNameStatus(raw){let out=[];for(let rawLine of raw.split(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{hookConfigIssues}from"./chunk-t4zxjveq.js";import{readOutdatedCache}from"./chunk-498t9sjd.js";import{tightenPluginPermissions}from"./chunk-2d0yz3mg.js";import{engineSkillDir,readSkillCopy}from"./chunk-c0xxw2hd.js";import{PREFIX_KEY_ID,defaultKeymapCopy,findBinding,restoreTerminal}from"./chunk-ksrsyzhy.js";import{AUTO_ROUTING_TIERS}from"./chunk-62b9mm81.js";import{reloadPluginEngines}from"./chunk-57atdjmz.js";import{expandHome}from"./chunk-evf15cs5.js";import{ENGINE_ACTIVITY_KINDS}from"./chunk-zcywdm3y.js";import{isUngrouped}from"./chunk-axycrfkq.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-jpc5yh8e.js";import{pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import{machineDaemonSocket}from"./chunk-cfb6mvz5.js";import{readOnlyGitProcessEnv}from"./chunk-9k0r47z3.js";import{tildify}from"./chunk-grbrh92f.js";import{t}from"./chunk-v8ms64g1.js";import{createStateCell}from"./chunk-7b2x6nkj.js";import{readFirstNonEmptyRepoFile}from"./chunk-tteswdyf.js";import{THEME_MODE_PREFERENCES}from"./chunk-vpk5m2z6.js";import{activityHookAdapters,engineEntry}from"./chunk-sy81vcaz.js";import{maybeStartScheduledRun,spawnCapture}from"./chunk-f60hmm20.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import{recordSpawn}from"./chunk-h8qg9v95.js";import{errorMessage,isDiskFull}from"./chunk-0zs13rdq.js";import{loadStateFile}from"./chunk-nks2q6d9.js";import{LOCALES}from"./chunk-r4vwq5wv.js";import{ROVE_HOOK_VERSION}from"./chunk-7dy9dtnd.js";import{pathIdentity,pathSyntax}from"./chunk-pn5ygqn6.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-yt15y085.js";import{promptAttachmentsDir}from"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import{readRoveEnv}from"./chunk-nc46gddg.js";var pluginPageErrorState=createStateCell([],"plugin-page-errors");function pluginPageErrors(){return pluginPageErrorState.get()}var WORKING_BORDER_KEY="appearance.workingBorder",WORKING_BORDERS=["flow","still"],DEFAULT_WORKING_BORDER="flow";function normalizeWorkingBorder(raw){return WORKING_BORDERS.includes(raw)?raw:"flow"}var SCROLLBACK_ROWS_KEY="terminal.scrollbackRows",DEFAULT_SCROLLBACK_ROWS=1000,SCROLLBACK_ROWS_MIN=100,SCROLLBACK_ROWS_MAX=1e5;function normalizeScrollbackRows(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"?Number.parseInt(value.trim(),10):Number.NaN;if(!Number.isFinite(n))return DEFAULT_SCROLLBACK_ROWS;return Math.min(SCROLLBACK_ROWS_MAX,Math.max(SCROLLBACK_ROWS_MIN,n))}function persistedScrollbackRows(){return normalizeScrollbackRows(loadStateFile()[SCROLLBACK_ROWS_KEY])}function relativeBuckets(absMs){let minutes=Math.floor(absMs/60000),hours=Math.floor(minutes/60);return{minutes,hours,days:Math.floor(hours/24)}}function relativeAge(ms,nowMs=Date.now()){let delta=Math.max(0,nowMs-ms),secs=Math.floor(delta/1000);if(secs<60)return`${secs}s`;let{minutes,hours,days}=relativeBuckets(delta);if(minutes<60)return`${minutes}m`;if(hours<24)return`${hours}h`;return`${days}d`}function truncateEnd(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`${points.slice(0,Math.max(0,max-1)).join("")}\u2026`}function truncateEndCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let total=0;for(let ch of s)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let ch of s){let w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out+=ch}return`${out}\u2026`}function truncateStart(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`\u2026${points.slice(points.length-Math.max(0,max-1)).join("")}`}function truncateStartCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let points=[...s],total=0;for(let ch of points)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let i=points.length-1;i>=0;i--){let ch=points[i],w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out=ch+out}return`\u2026${out}`}var EVENT_FEED_LIMIT=12,FRAGMENT_MAX=40;function str(value){return typeof value==="string"?value:""}function detailFragment(event){let detail=event.detail;if(!detail)return"";let{tool,compact,subagent}=detail,fragment=str(tool?.name)||str(compact?.trigger)||str(subagent?.type)||str(detail.note);return truncateEnd(fragment,FRAGMENT_MAX)}function eventRows(events,nowMs,limit=EVENT_FEED_LIMIT){return events.slice(-limit).reverse().map((event,index)=>{let tail=[detailFragment(event),str(event.vendor)].filter((part)=>part.length>0);return{key:`${event.at}:${index}`,age:relativeAge(event.at,nowMs),kind:event.kind,tail:tail.join(" \xB7 ")}})}function reconcileStableRows(prev,next,keyOf,equals,opts={}){if(prev.length===0)return next;let prevByKey=new Map;for(let row of prev)prevByKey.set(keyOf(row),row);let allReused=prev.length===next.length,out=Array(next.length);for(let i=0;i<next.length;i++){let fresh=next[i],old=prevByKey.get(keyOf(fresh));if(old&&equals(old,fresh)&&(!opts.samePosition||prev[i]===old)){if(out[i]=old,allReused&&prev[i]!==old)allReused=!1}else out[i]=fresh,allReused=!1}return allReused?prev:out}function compareNewest(a,b){let byTime=Date.parse(b.createdAt)-Date.parse(a.createdAt);if(Number.isFinite(byTime)&&byTime!==0)return byTime;return String(b.id).localeCompare(String(a.id))}function compareRecent(a,b){let byTime=taskTime(b)-taskTime(a);if(byTime!==0)return byTime;return String(b.id).localeCompare(String(a.id))}var nameCollator=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function compareName(a,b){let byName=nameCollator.compare(a.title.trim(),b.title.trim());if(byName!==0)return byName;return String(a.id).localeCompare(String(b.id))}function taskTime(task){let parsed=Date.parse(task.updatedAt||task.createdAt);return Number.isFinite(parsed)?parsed:0}function repoBasename(repo){return pathSyntax(repo).basename(repo)||repo}function sidebarProjectKey(repo,machineId="local"){let path=pathIdentity(repo.trim())||repo;return machineId==="local"?path:`${machineId}\x00${path}`}function sidebarProjectKeyOfTask(task){return sidebarProjectKey(task.repo,task.origin?.machineId??"local")}function isLocalTask(task){return(task.origin?.machineId??"local")==="local"}function isNoProjectTask(task){return isUngrouped(task)}function sidebarProjectKeyResolver(tasks){let counted=tasks.filter((task)=>{let phase=task.deletion?.phase;if(phase==="queued"||phase==="running")return!1;return!isNoProjectTask(task)}),repoIdOf=new Map;for(let task of counted){if(!task.repoId)continue;let key=sidebarProjectKeyOfTask(task);if(!repoIdOf.has(key))repoIdOf.set(key,task.repoId)}if(repoIdOf.size===0)return sidebarProjectKeyOfTask;let home=new Map;for(let task of counted){let key=sidebarProjectKeyOfTask(task),id=repoIdOf.get(key);if(!id)continue;let rank=isLocalTask(task)?0:1,current=home.get(id);if(!current||rank<current.rank)home.set(id,{key,rank})}return(task)=>{let key=sidebarProjectKeyOfTask(task),id=repoIdOf.get(key);return id&&home.get(id)?.key||key}}function repoIdTail(id){return id.startsWith("root:")?null:id.split("/").slice(-2).join("/")}function sidebarRepoLabel(project,all){let base=repoBasename(project.repo),others=all.filter((other)=>other!==project&&repoBasename(other.repo)===base);if(others.length===0)return base;let id=project.repoId,tail=id?repoIdTail(id):null;if(id&&tail)return others.some((other)=>other.repoId&&other.repoId!==id&&repoIdTail(other.repoId)===tail)?id:tail;return sidebarProjectLabel(project.repo,others.map((other)=>other.repo))}function sidebarProjectLabel(repo,repos,hostLabel){let base=repoBasename(repo),host=hostLabel??"",collisions=repos.map((entry)=>typeof entry==="string"?{repo:entry}:entry).filter((entry)=>entry.repo!==repo||(entry.hostLabel??"")!==host).filter((entry)=>repoBasename(entry.repo)===base);if(collisions.length===0)return base;if(collisions.some((entry)=>(entry.hostLabel??"")===host)){let tail=pathTail(repo);return collisions.some((entry)=>(entry.hostLabel??"")!==host&&pathTail(entry.repo)===tail)&&host?`${host}:${tail}`:tail}return host?`${host}:${base}`:base}function pathTail(repo){let syntax=pathSyntax(repo);return syntax.normalize(repo).split(syntax.sep).filter(Boolean).slice(-2).join("/")}import{randomBytes}from"crypto";import{existsSync,mkdirSync,writeFileSync}from"fs";import{isAbsolute,join}from"path";var ATTACHMENT_EXTENSION_REGEX=/\.(png|jpe?g|gif|webp|pdf)$/i,PDF_EXTENSION_REGEX=/\.pdf$/i;function removeOuterQuotes(text){if(text.startsWith('"')&&text.endsWith('"')||text.startsWith("'")&&text.endsWith("'"))return text.slice(1,-1);return text}function stripBackslashEscapes(path){let placeholder=`__DOUBLE_BACKSLASH_${randomBytes(8).toString("hex")}__`;return path.replace(/\\\\/g,placeholder).replace(/\\(.)/g,"$1").replaceAll(placeholder,"\\")}function asAttachmentPath(text,exists=existsSync){let cleaned=stripBackslashEscapes(removeOuterQuotes(text.trim()));if(!ATTACHMENT_EXTENSION_REGEX.test(cleaned))return null;if(!isAbsolute(cleaned))return null;return exists(cleaned)?cleaned:null}function asAttachmentPaths(pasted,exists=existsSync){let lines=pasted.split(`
2
+ import{hookConfigIssues}from"./chunk-ghfqyrbr.js";import{readOutdatedCache}from"./chunk-498t9sjd.js";import{tightenPluginPermissions}from"./chunk-2d0yz3mg.js";import{engineSkillDir,readSkillCopy}from"./chunk-zp78250b.js";import{PREFIX_KEY_ID,defaultKeymapCopy,findBinding,restoreTerminal}from"./chunk-ksrsyzhy.js";import{AUTO_ROUTING_TIERS}from"./chunk-6n9wzp5t.js";import{reloadPluginEngines}from"./chunk-9sq4jh9k.js";import{expandHome}from"./chunk-7cm66y22.js";import{ENGINE_ACTIVITY_KINDS}from"./chunk-zcywdm3y.js";import{isUngrouped}from"./chunk-hdea2ss8.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-jpc5yh8e.js";import{pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import{machineDaemonSocket}from"./chunk-vk8t0x7q.js";import{readOnlyGitProcessEnv}from"./chunk-9k0r47z3.js";import{tildify}from"./chunk-grbrh92f.js";import{t}from"./chunk-kr7jw1s4.js";import{createStateCell}from"./chunk-7b2x6nkj.js";import{readFirstNonEmptyRepoFile}from"./chunk-tteswdyf.js";import{THEME_MODE_PREFERENCES}from"./chunk-9c723k0b.js";import{activityHookAdapters,engineEntry}from"./chunk-s2b2nfeb.js";import{maybeStartScheduledRun,spawnCapture}from"./chunk-f60hmm20.js";import{RoveDaemonClient}from"./chunk-84q9hv7m.js";import{recordSpawn}from"./chunk-h8qg9v95.js";import{errorMessage,isDiskFull}from"./chunk-0zs13rdq.js";import{loadStateFile}from"./chunk-nks2q6d9.js";import{LOCALES}from"./chunk-fczxyfgn.js";import{ROVE_HOOK_VERSION}from"./chunk-n5at7bsq.js";import{pathIdentity,pathSyntax}from"./chunk-pn5ygqn6.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-yt15y085.js";import{promptAttachmentsDir}from"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import{readRoveEnv}from"./chunk-nc46gddg.js";var pluginPageErrorState=createStateCell([],"plugin-page-errors");function pluginPageErrors(){return pluginPageErrorState.get()}var WORKING_BORDER_KEY="appearance.workingBorder",WORKING_BORDERS=["flow","still"],DEFAULT_WORKING_BORDER="flow";function normalizeWorkingBorder(raw){return WORKING_BORDERS.includes(raw)?raw:"flow"}var SCROLLBACK_ROWS_KEY="terminal.scrollbackRows",DEFAULT_SCROLLBACK_ROWS=1000,SCROLLBACK_ROWS_MIN=100,SCROLLBACK_ROWS_MAX=1e5;function normalizeScrollbackRows(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"?Number.parseInt(value.trim(),10):Number.NaN;if(!Number.isFinite(n))return DEFAULT_SCROLLBACK_ROWS;return Math.min(SCROLLBACK_ROWS_MAX,Math.max(SCROLLBACK_ROWS_MIN,n))}function persistedScrollbackRows(){return normalizeScrollbackRows(loadStateFile()[SCROLLBACK_ROWS_KEY])}function relativeBuckets(absMs){let minutes=Math.floor(absMs/60000),hours=Math.floor(minutes/60);return{minutes,hours,days:Math.floor(hours/24)}}function relativeAge(ms,nowMs=Date.now()){let delta=Math.max(0,nowMs-ms),secs=Math.floor(delta/1000);if(secs<60)return`${secs}s`;let{minutes,hours,days}=relativeBuckets(delta);if(minutes<60)return`${minutes}m`;if(hours<24)return`${hours}h`;return`${days}d`}function truncateEnd(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`${points.slice(0,Math.max(0,max-1)).join("")}\u2026`}function truncateEndCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let total=0;for(let ch of s)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let ch of s){let w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out+=ch}return`${out}\u2026`}function truncateStart(s,max){if(max<=0)return"";let points=[...s];if(points.length<=max)return s;return`\u2026${points.slice(points.length-Math.max(0,max-1)).join("")}`}function truncateStartCells(s,maxCells,cellsOf){if(maxCells<=0)return"";let points=[...s],total=0;for(let ch of points)total+=cellsOf(ch.codePointAt(0)??0);if(total<=maxCells)return s;let used=0,out="";for(let i=points.length-1;i>=0;i--){let ch=points[i],w=cellsOf(ch.codePointAt(0)??0);if(used+w>maxCells-1)break;used+=w,out=ch+out}return`\u2026${out}`}var EVENT_FEED_LIMIT=12,FRAGMENT_MAX=40;function str(value){return typeof value==="string"?value:""}function detailFragment(event){let detail=event.detail;if(!detail)return"";let{tool,compact,subagent}=detail,fragment=str(tool?.name)||str(compact?.trigger)||str(subagent?.type)||str(detail.note);return truncateEnd(fragment,FRAGMENT_MAX)}function eventRows(events,nowMs,limit=EVENT_FEED_LIMIT){return events.slice(-limit).reverse().map((event,index)=>{let tail=[detailFragment(event),str(event.vendor)].filter((part)=>part.length>0);return{key:`${event.at}:${index}`,age:relativeAge(event.at,nowMs),kind:event.kind,tail:tail.join(" \xB7 ")}})}function reconcileStableRows(prev,next,keyOf,equals,opts={}){if(prev.length===0)return next;let prevByKey=new Map;for(let row of prev)prevByKey.set(keyOf(row),row);let allReused=prev.length===next.length,out=Array(next.length);for(let i=0;i<next.length;i++){let fresh=next[i],old=prevByKey.get(keyOf(fresh));if(old&&equals(old,fresh)&&(!opts.samePosition||prev[i]===old)){if(out[i]=old,allReused&&prev[i]!==old)allReused=!1}else out[i]=fresh,allReused=!1}return allReused?prev:out}function compareNewest(a,b){let byTime=Date.parse(b.createdAt)-Date.parse(a.createdAt);if(Number.isFinite(byTime)&&byTime!==0)return byTime;return String(b.id).localeCompare(String(a.id))}function compareRecent(a,b){let byTime=taskTime(b)-taskTime(a);if(byTime!==0)return byTime;return String(b.id).localeCompare(String(a.id))}var nameCollator=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});function compareName(a,b){let byName=nameCollator.compare(a.title.trim(),b.title.trim());if(byName!==0)return byName;return String(a.id).localeCompare(String(b.id))}function taskTime(task){let parsed=Date.parse(task.updatedAt||task.createdAt);return Number.isFinite(parsed)?parsed:0}function repoBasename(repo){return pathSyntax(repo).basename(repo)||repo}function sidebarProjectKey(repo,machineId="local"){let path=pathIdentity(repo.trim())||repo;return machineId==="local"?path:`${machineId}\x00${path}`}function sidebarProjectKeyOfTask(task){return sidebarProjectKey(task.repo,task.origin?.machineId??"local")}function isLocalTask(task){return(task.origin?.machineId??"local")==="local"}function isNoProjectTask(task){return isUngrouped(task)}function sidebarProjectKeyResolver(tasks){let counted=tasks.filter((task)=>{let phase=task.deletion?.phase;if(phase==="queued"||phase==="running")return!1;return!isNoProjectTask(task)}),repoIdOf=new Map;for(let task of counted){if(!task.repoId)continue;let key=sidebarProjectKeyOfTask(task);if(!repoIdOf.has(key))repoIdOf.set(key,task.repoId)}if(repoIdOf.size===0)return sidebarProjectKeyOfTask;let home=new Map;for(let task of counted){let key=sidebarProjectKeyOfTask(task),id=repoIdOf.get(key);if(!id)continue;let rank=isLocalTask(task)?0:1,current=home.get(id);if(!current||rank<current.rank)home.set(id,{key,rank})}return(task)=>{let key=sidebarProjectKeyOfTask(task),id=repoIdOf.get(key);return id&&home.get(id)?.key||key}}function repoIdTail(id){return id.startsWith("root:")?null:id.split("/").slice(-2).join("/")}function sidebarRepoLabel(project,all){let base=repoBasename(project.repo),others=all.filter((other)=>other!==project&&repoBasename(other.repo)===base);if(others.length===0)return base;let id=project.repoId,tail=id?repoIdTail(id):null;if(id&&tail)return others.some((other)=>other.repoId&&other.repoId!==id&&repoIdTail(other.repoId)===tail)?id:tail;return sidebarProjectLabel(project.repo,others.map((other)=>other.repo))}function sidebarProjectLabel(repo,repos,hostLabel){let base=repoBasename(repo),host=hostLabel??"",collisions=repos.map((entry)=>typeof entry==="string"?{repo:entry}:entry).filter((entry)=>entry.repo!==repo||(entry.hostLabel??"")!==host).filter((entry)=>repoBasename(entry.repo)===base);if(collisions.length===0)return base;if(collisions.some((entry)=>(entry.hostLabel??"")===host)){let tail=pathTail(repo);return collisions.some((entry)=>(entry.hostLabel??"")!==host&&pathTail(entry.repo)===tail)&&host?`${host}:${tail}`:tail}return host?`${host}:${base}`:base}function pathTail(repo){let syntax=pathSyntax(repo);return syntax.normalize(repo).split(syntax.sep).filter(Boolean).slice(-2).join("/")}import{randomBytes}from"crypto";import{existsSync,mkdirSync,writeFileSync}from"fs";import{isAbsolute,join}from"path";var ATTACHMENT_EXTENSION_REGEX=/\.(png|jpe?g|gif|webp|pdf)$/i,PDF_EXTENSION_REGEX=/\.pdf$/i;function removeOuterQuotes(text){if(text.startsWith('"')&&text.endsWith('"')||text.startsWith("'")&&text.endsWith("'"))return text.slice(1,-1);return text}function stripBackslashEscapes(path){let placeholder=`__DOUBLE_BACKSLASH_${randomBytes(8).toString("hex")}__`;return path.replace(/\\\\/g,placeholder).replace(/\\(.)/g,"$1").replaceAll(placeholder,"\\")}function asAttachmentPath(text,exists=existsSync){let cleaned=stripBackslashEscapes(removeOuterQuotes(text.trim()));if(!ATTACHMENT_EXTENSION_REGEX.test(cleaned))return null;if(!isAbsolute(cleaned))return null;return exists(cleaned)?cleaned:null}function asAttachmentPaths(pasted,exists=existsSync){let lines=pasted.split(`
3
3
  `).map((l)=>l.trim()).filter((l)=>l.length>0);if(lines.length===0)return null;let paths=[];for(let line of lines){let p=asAttachmentPath(line,exists);if(!p)return null;paths.push(p)}return paths}function attachmentLabel(path,index){if(PDF_EXTENSION_REGEX.test(path))return`pdf[${index}]`;return ATTACHMENT_EXTENSION_REGEX.test(path)?`images[${index}]`:`files[${index}]`}function appendAttachmentRefs(prompt,attachments){if(attachments.length===0)return prompt;let refs=attachments.map((p,i)=>`${attachmentLabel(p,i)}: ${p}`).join(`
4
4
  `);return`${prompt}
5
5