@sma1lboy/rove 0.9.281 → 0.9.283-next.102

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 (148) hide show
  1. package/dist/cli/{chunk-14tevt5v.js → chunk-0b6mqb7z.js} +1 -1
  2. package/dist/cli/{chunk-v3ecphrz.js → chunk-0heg44e1.js} +1 -1
  3. package/dist/cli/{chunk-rjq38twt.js → chunk-0m8javx8.js} +1 -1
  4. package/dist/cli/{chunk-n0rdn2fn.js → chunk-0sy3bez6.js} +2 -2
  5. package/dist/cli/{chunk-y2v1x23z.js → chunk-12nsdpm3.js} +1 -1
  6. package/dist/cli/{chunk-bagwgxsg.js → chunk-131bpjms.js} +1 -1
  7. package/dist/cli/{chunk-3qj9yw5c.js → chunk-188ztxe4.js} +2 -2
  8. package/dist/cli/{chunk-j5y7hhc2.js → chunk-1fvj9amb.js} +2 -2
  9. package/dist/cli/{chunk-qcjkactr.js → chunk-1gxnd3qq.js} +1 -1
  10. package/dist/cli/{chunk-sm96b61g.js → chunk-1pryvpg1.js} +1 -1
  11. package/dist/cli/{chunk-895yqjjz.js → chunk-22emnsn5.js} +1 -1
  12. package/dist/cli/{chunk-6wt08a28.js → chunk-22gfxgj6.js} +1 -1
  13. package/dist/cli/{chunk-q2nhmaq9.js → chunk-2f4mt5k0.js} +3 -3
  14. package/dist/cli/{chunk-xqvyzv62.js → chunk-2xpvbqzy.js} +1 -1
  15. package/dist/cli/{chunk-32y7f5dr.js → chunk-3ptv653h.js} +1 -1
  16. package/dist/cli/{chunk-twy9bfps.js → chunk-42m08y8e.js} +4 -4
  17. package/dist/cli/{chunk-4yr1534j.js → chunk-45a1xqc4.js} +1 -1
  18. package/dist/cli/{chunk-n2zgej1a.js → chunk-4gjj2ed9.js} +1 -1
  19. package/dist/cli/{chunk-j2e7jgh8.js → chunk-4qenh5zx.js} +1 -1
  20. package/dist/cli/{chunk-w7v71t7e.js → chunk-53pn0a9z.js} +1 -1
  21. package/dist/cli/{chunk-x119xqa6.js → chunk-5ah5hade.js} +1 -1
  22. package/dist/cli/{chunk-fq2pefc5.js → chunk-5jbfscxy.js} +1 -1
  23. package/dist/cli/{chunk-kp43j420.js → chunk-5jj8g02m.js} +1 -1
  24. package/dist/cli/{chunk-e58kj4gm.js → chunk-5mhf43dx.js} +1 -1
  25. package/dist/cli/{chunk-dkx7s5rk.js → chunk-5we7drd0.js} +1 -1
  26. package/dist/cli/{chunk-w8dmmnys.js → chunk-61fvqbh6.js} +1 -1
  27. package/dist/cli/chunk-69kd26wk.js +3 -0
  28. package/dist/cli/{chunk-5swmvt20.js → chunk-6gtkv1jx.js} +1 -1
  29. package/dist/cli/{chunk-y07cp9mb.js → chunk-6mm1672p.js} +1 -1
  30. package/dist/cli/{chunk-01tghgf3.js → chunk-6pb0cs94.js} +1 -1
  31. package/dist/cli/{chunk-k2rmj0v3.js → chunk-7tnse4jm.js} +3 -3
  32. package/dist/cli/{chunk-bm6qhcck.js → chunk-88yjj159.js} +1 -1
  33. package/dist/cli/{chunk-x1ghdmp1.js → chunk-8ac8k0ba.js} +1 -1
  34. package/dist/cli/{chunk-jar50zcp.js → chunk-8qgwpha3.js} +1 -1
  35. package/dist/cli/{chunk-9rj2fx6v.js → chunk-8ttn73cv.js} +1 -1
  36. package/dist/cli/{chunk-qzzmd63x.js → chunk-8y10pmkf.js} +2 -2
  37. package/dist/cli/{chunk-vtay379p.js → chunk-a2yka96d.js} +1 -1
  38. package/dist/cli/{chunk-46qs744w.js → chunk-adas765b.js} +1 -1
  39. package/dist/cli/chunk-an97ga8b.js +2 -0
  40. package/dist/cli/{chunk-0a65j1zj.js → chunk-ar3mt81z.js} +1 -1
  41. package/dist/cli/{chunk-hzz020xx.js → chunk-betn5ma1.js} +1 -1
  42. package/dist/cli/{chunk-p2cbtrzg.js → chunk-c8qjy6rx.js} +1 -1
  43. package/dist/cli/{chunk-agvtzads.js → chunk-cacct9gd.js} +1 -1
  44. package/dist/cli/{chunk-q72w3dsx.js → chunk-cmtck38h.js} +1 -1
  45. package/dist/cli/{chunk-03fv92ya.js → chunk-cxrb7s61.js} +1 -1
  46. package/dist/cli/{chunk-ga82ras9.js → chunk-cyn10x4g.js} +2 -2
  47. package/dist/cli/{chunk-9qpea48c.js → chunk-cza57nay.js} +3 -3
  48. package/dist/cli/{chunk-x94e0rw4.js → chunk-d9x7zeh7.js} +1 -1
  49. package/dist/cli/chunk-e2freh5a.js +2 -0
  50. package/dist/cli/{chunk-eege1x0a.js → chunk-e4fp3w22.js} +1 -1
  51. package/dist/cli/{chunk-1vxtd8rh.js → chunk-ee8917py.js} +1 -1
  52. package/dist/cli/{chunk-cx78tyg1.js → chunk-ek39ktjy.js} +1 -1
  53. package/dist/cli/{chunk-zpxpwgds.js → chunk-eyaaaprw.js} +1 -1
  54. package/dist/cli/{chunk-3pgp6z3k.js → chunk-f30d15nr.js} +1 -1
  55. package/dist/cli/{chunk-cs410j8b.js → chunk-fjsmqvaq.js} +1 -1
  56. package/dist/cli/{chunk-3m0ydze9.js → chunk-fv1yy6zg.js} +1 -1
  57. package/dist/cli/{chunk-1a57ejnh.js → chunk-fyhrnwsh.js} +1 -1
  58. package/dist/cli/{chunk-q6cwy6v5.js → chunk-g5g1fbf3.js} +1 -1
  59. package/dist/cli/{chunk-k9xabf0t.js → chunk-gbzjbk8h.js} +5 -5
  60. package/dist/cli/{chunk-z43e08kw.js → chunk-gfdd2jbp.js} +1 -1
  61. package/dist/cli/chunk-gygdyf0s.js +3 -0
  62. package/dist/cli/{chunk-0gbg7bg8.js → chunk-h27064am.js} +1 -1
  63. package/dist/cli/{chunk-4gjvmfa9.js → chunk-hgtf6yvg.js} +5 -5
  64. package/dist/cli/{chunk-a5xbsvx2.js → chunk-j8eejjw0.js} +1 -1
  65. package/dist/cli/{chunk-xxz3np4w.js → chunk-jc77vqz7.js} +1 -1
  66. package/dist/cli/{chunk-3x5g06mw.js → chunk-jkssty8x.js} +1 -1
  67. package/dist/cli/{chunk-k3h4cpdy.js → chunk-jn8fkzm7.js} +1 -1
  68. package/dist/cli/{chunk-5rgrde6b.js → chunk-jnt3nf6w.js} +1 -1
  69. package/dist/cli/{chunk-kt5ngemc.js → chunk-jwn1bpdq.js} +1 -1
  70. package/dist/cli/{chunk-xekk4k54.js → chunk-kjvdz8y1.js} +1 -1
  71. package/dist/cli/{chunk-kdnk8m5j.js → chunk-m2aqz600.js} +1 -1
  72. package/dist/cli/{chunk-4w4tpsqx.js → chunk-mkb5mmmw.js} +1 -1
  73. package/dist/cli/chunk-nbcm8d58.js +3 -0
  74. package/dist/cli/{chunk-dsdtq087.js → chunk-nf1gqqv8.js} +1 -1
  75. package/dist/cli/{chunk-teh40faw.js → chunk-np319fys.js} +1 -1
  76. package/dist/cli/{chunk-ggnq2vvk.js → chunk-paashxkd.js} +1 -1
  77. package/dist/cli/{chunk-vytrhm50.js → chunk-pmwk2etg.js} +1 -1
  78. package/dist/cli/{chunk-ec3esgj4.js → chunk-pmz7t8xx.js} +1 -1
  79. package/dist/cli/{chunk-6mg5zp8y.js → chunk-pwt6bgb9.js} +1 -1
  80. package/dist/cli/{chunk-ap3fgbbt.js → chunk-q5h20fkf.js} +1 -1
  81. package/dist/cli/{chunk-rjfdzjhj.js → chunk-q89yrevw.js} +1 -1
  82. package/dist/cli/{chunk-zr058kbe.js → chunk-qnv8ggxh.js} +1 -1
  83. package/dist/cli/{chunk-sakkdjyn.js → chunk-qtx79czn.js} +1 -1
  84. package/dist/cli/chunk-rg50pcvt.js +2 -0
  85. package/dist/cli/chunk-rmnm3f9n.js +3 -0
  86. package/dist/cli/{chunk-b5fdqynx.js → chunk-rqx18p02.js} +1 -1
  87. package/dist/cli/{chunk-29kvfqeh.js → chunk-rsdykw6f.js} +1 -1
  88. package/dist/cli/{chunk-ww0zctb7.js → chunk-s61x3krj.js} +1 -1
  89. package/dist/cli/{chunk-c9ptxthj.js → chunk-s7kertfd.js} +1 -1
  90. package/dist/cli/{chunk-bcyex84w.js → chunk-s7ttzm9a.js} +1 -1
  91. package/dist/cli/{chunk-njncqdwf.js → chunk-s88gxrtj.js} +1 -1
  92. package/dist/cli/{chunk-vx44yxra.js → chunk-sc72402g.js} +1 -1
  93. package/dist/cli/{chunk-nkgn0bqq.js → chunk-sy7812gv.js} +1 -1
  94. package/dist/cli/{chunk-btxfcc77.js → chunk-syfddt6h.js} +5 -5
  95. package/dist/cli/{chunk-tgv90744.js → chunk-t1ye845a.js} +1 -1
  96. package/dist/cli/{chunk-6hcyvg0m.js → chunk-tay29xzx.js} +1 -1
  97. package/dist/cli/{chunk-cx8wnz54.js → chunk-tn4jd3yg.js} +1 -1
  98. package/dist/cli/{chunk-rqm2kn0c.js → chunk-tv4mbxyj.js} +1 -1
  99. package/dist/cli/{chunk-w3kvkax7.js → chunk-v89nwpyr.js} +1 -1
  100. package/dist/cli/{chunk-r7tbzgt7.js → chunk-v8kksfg2.js} +1 -1
  101. package/dist/cli/{chunk-w6ft4djp.js → chunk-va59neh9.js} +1 -1
  102. package/dist/cli/{chunk-4vkrv4eb.js → chunk-vpgfb42r.js} +1 -1
  103. package/dist/cli/{chunk-hmy01yg2.js → chunk-w34wwqwq.js} +10 -9
  104. package/dist/cli/{chunk-gzkes5bw.js → chunk-w94ykg0q.js} +1 -1
  105. package/dist/cli/{chunk-ejfs22aq.js → chunk-w9t5fw20.js} +1 -1
  106. package/dist/cli/{chunk-bbt217yd.js → chunk-wfepe53b.js} +1 -1
  107. package/dist/cli/{chunk-j19av093.js → chunk-wkze838c.js} +1 -1
  108. package/dist/cli/chunk-x7fmexjc.js +2 -0
  109. package/dist/cli/{chunk-95kk75wh.js → chunk-xb196wqg.js} +1 -1
  110. package/dist/cli/{chunk-0nkk13z9.js → chunk-xck2mva9.js} +1 -1
  111. package/dist/cli/{chunk-x35dfb1x.js → chunk-xj5yj34d.js} +7 -7
  112. package/dist/cli/{chunk-16e6jqq6.js → chunk-xr117xs9.js} +1 -1
  113. package/dist/cli/{chunk-tjhw09bz.js → chunk-xs6w6ekc.js} +2 -2
  114. package/dist/cli/{chunk-08mb3qss.js → chunk-xte1k7mk.js} +1 -1
  115. package/dist/cli/{chunk-qecygh3f.js → chunk-ypfrkpe9.js} +1 -1
  116. package/dist/cli/{chunk-aq4j8ar4.js → chunk-z16wb344.js} +1 -1
  117. package/dist/cli/{chunk-f23manyf.js → chunk-z26xjafb.js} +1 -1
  118. package/dist/cli/{chunk-jj5f4n51.js → chunk-z3hfz52n.js} +1 -1
  119. package/dist/cli/chunk-zcrggyg5.js +2 -0
  120. package/dist/cli/chunk-zj7m55h0.js +7 -0
  121. package/dist/cli/{chunk-hnxs5shy.js → chunk-zy0v59vp.js} +12 -12
  122. package/dist/cli/index.js +7 -7
  123. package/dist/cli/pty-host-node.mjs +22 -2
  124. package/dist/cli/rove.js +1 -1
  125. package/dist/completions/rove.bash +2 -2
  126. package/dist/completions/rove.fish +2 -2
  127. package/dist/completions/rove.zsh +2 -2
  128. package/dist/skills/rove/SKILL.md +1 -1
  129. package/dist/skills/rove/references/api-flags.md +2 -0
  130. package/dist/web/assets/index-BtnHQrTu.js +63 -0
  131. package/dist/web/assets/index-CYI4H9R1.css +1 -0
  132. package/dist/web/assets/term-mount-BrP-ENHg.css +1 -0
  133. package/dist/web/assets/term-mount-CFCIuHzW.js +93 -0
  134. package/dist/web/index.html +2 -2
  135. package/dist/web/relay/index.html +4 -4
  136. package/package.json +3 -3
  137. package/dist/cli/chunk-453qpfae.js +0 -2
  138. package/dist/cli/chunk-7911jkq6.js +0 -2
  139. package/dist/cli/chunk-9vwb9f7q.js +0 -7
  140. package/dist/cli/chunk-hv79ys32.js +0 -2
  141. package/dist/cli/chunk-qqr4tfhk.js +0 -3
  142. package/dist/cli/chunk-rfp0ayra.js +0 -3
  143. package/dist/cli/chunk-sqdmngys.js +0 -2
  144. package/dist/cli/chunk-tq0h3vy6.js +0 -3
  145. package/dist/cli/chunk-yn01fet6.js +0 -3
  146. package/dist/cli/chunk-z8rvxvx5.js +0 -2
  147. package/dist/web/assets/index-Bo92_NP5.css +0 -1
  148. package/dist/web/assets/index-Ct8dDnCc.js +0 -154
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{spawnCapture}from"./chunk-2tfnscxk.js";import{CONTRIB_ENGINE_IDS,contribEngineEntry,detectBobAccount,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectKimiAccount,isContribEngine,isTransientFailureText,mergeFlatHooks,parseFlatHooks,pluginEngineIds,writeIfChanged}from"./chunk-hzz020xx.js";import{TomlError,parse}from"./chunk-w7zv47mp.js";import{ClaudeHookAdapter,isRovePluginEnabled}from"./chunk-7bakcyes.js";import{GATED_TOOL_VERBS,JsonHookAdapter,ROVE_HOOK_VERSION,bobDbPath,bobHome,bobTrustPath,claudeGlobalConfigPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isJsonlLineWithinBound,readFirstLineBounded,readSharedConfigSync,readTextFileBounded,readTextFileIfRegular,roveHookArgs,roveHookInvocation,skillsDirUnder,updateSharedJsonSync,vendorAgentDir,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-8qkyd589.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import{samePath}from"./chunk-pn5ygqn6.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync as existsSync5}from"fs";import{homedir as homedir6}from"os";import{join as join4}from"path";var BOB_SCREEN_MANIFEST={rules:[{state:"blocked",any:["complete sign-in in your browser"]},{state:"blocked",all:["do you trust this folder?"],any:["trust folder","don't trust"]},{state:"blocked",all:["approve once"],any:["reject","always allow"]},{state:"working",any:["enter to steer","tab to queue"]},{state:"idle",lineRegex:["^\\s*\\w[\\w ]* mode( \xB7|\\s*$)"]}]};import{homedir}from"os";var TRUSTED="TRUST_FOLDER";function trustBobWorktree(worktreePath,home=homedir()){updateSharedJsonSync(bobTrustPath(home),(raw)=>{if(raw===void 0)return{};try{return JSON.parse(raw)}catch{return{}}},(doc)=>{let folders=doc.folders&&typeof doc.folders==="object"&&!Array.isArray(doc.folders)?doc.folders:{};if(folders[worktreePath]===TRUSTED)return;let merged={...doc,version:doc.version??1,folders:{...folders,[worktreePath]:TRUSTED}};return`${JSON.stringify(merged,null,2)}
2
+ import{spawnCapture}from"./chunk-2tfnscxk.js";import{CONTRIB_ENGINE_IDS,contribEngineEntry,detectBobAccount,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectKimiAccount,isContribEngine,isTransientFailureText,mergeFlatHooks,parseFlatHooks,pluginEngineIds,writeIfChanged}from"./chunk-betn5ma1.js";import{TomlError,parse}from"./chunk-w7zv47mp.js";import{ClaudeHookAdapter,isRovePluginEnabled}from"./chunk-7bakcyes.js";import{GATED_TOOL_VERBS,JsonHookAdapter,ROVE_HOOK_VERSION,bobDbPath,bobHome,bobTrustPath,claudeGlobalConfigPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isJsonlLineWithinBound,readFirstLineBounded,readSharedConfigSync,readTextFileBounded,readTextFileIfRegular,roveHookArgs,roveHookInvocation,skillsDirUnder,updateSharedJsonSync,vendorAgentDir,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-8qkyd589.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import{roveStateDir}from"./chunk-z1nj22va.js";import{samePath}from"./chunk-pn5ygqn6.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync as existsSync5}from"fs";import{homedir as homedir6}from"os";import{join as join5}from"path";var BOB_SCREEN_MANIFEST={rules:[{state:"blocked",any:["complete sign-in in your browser"]},{state:"blocked",all:["do you trust this folder?"],any:["trust folder","don't trust"]},{state:"blocked",all:["approve once"],any:["reject","always allow"]},{state:"working",any:["enter to steer","tab to queue"]},{state:"idle",lineRegex:["^\\s*\\w[\\w ]* mode( \xB7|\\s*$)"]}]};import{homedir}from"os";var TRUSTED="TRUST_FOLDER";function trustBobWorktree(worktreePath,home=homedir()){updateSharedJsonSync(bobTrustPath(home),(raw)=>{if(raw===void 0)return{};try{return JSON.parse(raw)}catch{return{}}},(doc)=>{let folders=doc.folders&&typeof doc.folders==="object"&&!Array.isArray(doc.folders)?doc.folders:{};if(folders[worktreePath]===TRUSTED)return;let merged={...doc,version:doc.version??1,folders:{...folders,[worktreePath]:TRUSTED}};return`${JSON.stringify(merged,null,2)}
3
3
  `})}var claudeCapabilities={interruptSequence:"\x1B"},claudeIdentity={shortName:"Claude"};import{homedir as homedir2,userInfo}from"os";import path from"path";var OAUTH_USAGE_URL="https://api.anthropic.com/api/oauth/usage",OAUTH_BETA_HEADER="oauth-2025-04-20",OAUTH_USER_AGENT="claude-cli/2.1.198 (external, cli)",USAGE_TIMEOUT_MS=1e4,KEYCHAIN_SERVICE="Claude Code-credentials";function parseResetsAtMs(value){if(value==null)return null;let numeric=typeof value==="number"?value:/^\d+(?:\.\d+)?$/.test(value.trim())?Number(value):null;if(numeric!=null){if(!Number.isFinite(numeric)||numeric<=0)return null;return numeric<1000000000000?numeric*1000:numeric}let parsed=Date.parse(String(value));return Number.isNaN(parsed)?null:parsed}var clampPercent=(value)=>Math.min(100,Math.max(0,Math.round(value)));function windowLabel(kind,scopeModel){if(kind==="weekly_scoped"&&scopeModel)return scopeModel;return kind.startsWith("weekly")||kind.startsWith("seven_day")?"7d":"5h"}function usageFromClaudePayload(payload,capturedAt){let windows=[];if(payload.limits?.length)for(let limit of payload.limits){if(typeof limit.kind!=="string"||typeof limit.percent!=="number")continue;windows.push({kind:limit.kind,label:windowLabel(limit.kind,limit.scope?.model?.display_name),percent:clampPercent(limit.percent),resetsAt:parseResetsAtMs(limit.resets_at)})}else{if(typeof payload.five_hour?.utilization==="number")windows.push({kind:"session",label:"5h",percent:clampPercent(payload.five_hour.utilization),resetsAt:parseResetsAtMs(payload.five_hour.resets_at)});if(typeof payload.seven_day?.utilization==="number")windows.push({kind:"weekly_all",label:"7d",percent:clampPercent(payload.seven_day.utilization),resetsAt:parseResetsAtMs(payload.seven_day.resets_at)})}return{windows,capturedAt}}function parseCredentials(raw){try{let oauth=JSON.parse(raw)?.claudeAiOauth;if(!oauth||typeof oauth.accessToken!=="string"||!oauth.accessToken)return null;return{accessToken:oauth.accessToken,...typeof oauth.expiresAt==="number"&&Number.isFinite(oauth.expiresAt)?{expiresAt:oauth.expiresAt}:{}}}catch{return null}}var isFresh=(c)=>c.expiresAt===void 0||c.expiresAt>Date.now();async function readFileCredentials(dir){try{return parseCredentials(await readTextFileBounded(path.join(dir,".credentials.json")))}catch{return null}}async function readKeychainCredentials(){if(process.platform!=="darwin")return null;let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),3000);try{let result=await spawnCapture("security",["find-generic-password","-a",userInfo().username,"-w","-s",KEYCHAIN_SERVICE],{cwd:homedir2(),signal:controller.signal});return result.status===0?parseCredentials(result.stdout.trim()):null}finally{clearTimeout(timeout)}}async function readAccessToken(){let configDir=process.env.CLAUDE_CONFIG_DIR?.trim();if(configDir){let fromFile=await readFileCredentials(configDir);return fromFile&&isFresh(fromFile)?fromFile.accessToken:null}return[await readKeychainCredentials(),await readFileCredentials(vendorConfigHome("claude"))].find((c)=>c!=null&&isFresh(c))?.accessToken??null}async function fetchClaudeQuotaUsage(now=Date.now){let token=await readAccessToken().catch(()=>null);if(!token)return null;let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),USAGE_TIMEOUT_MS);try{let response=await fetch(OAUTH_USAGE_URL,{headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json","User-Agent":OAUTH_USER_AGENT,"anthropic-beta":OAUTH_BETA_HEADER},signal:controller.signal});if(!response.ok)return null;return usageFromClaudePayload(await response.json(),now())}catch{return null}finally{clearTimeout(timeout)}}function trustClaudeWorktree(worktreePath,home){let deps=vendorWriteHomeDeps(home);updateSharedJsonSync(claudeGlobalConfigPath(deps.env,deps.home()),(raw)=>{if(raw===void 0)return{};let doc=JSON.parse(raw);if(!isObject(doc))throw Error("Claude trust config must be a JSON object");return doc},(doc)=>{if(doc.projects!==void 0&&!isObject(doc.projects))throw Error("Claude trust projects must be an object");let projects={...doc.projects},existing=Object.hasOwn(projects,worktreePath)?projects[worktreePath]:{};if(!isObject(existing))throw Error("Claude trust project must be an object");if(existing.hasTrustDialogAccepted===!0)return;return projects[worktreePath]={...existing,hasTrustDialogAccepted:!0,hasCompletedProjectOnboarding:!0},JSON.stringify({...doc,projects},null,2)})}function isSyntheticClaudeRecord(record){return record.isMeta===!0||record.isCompactSummary===!0||record.type==="api-request-blob"}function isClaudeCommandBreadcrumb(blocks){if(blocks.length===0)return!1;for(let b of blocks){if(b.type!=="text")return!1;let t=b.text.trim();if(!t.startsWith("<command-name>")&&!t.startsWith("<command-message>")&&!t.startsWith("<local-command"))return!1}return!0}function isClaudeSystemReminder(block){if(block.type!=="text")return!1;let t=block.text.trim();return t.startsWith("<system-reminder>")&&t.endsWith("</system-reminder>")}function opensTurn(content){if(typeof content==="string")return content.trim().length>0;if(!Array.isArray(content))return!1;return content.some((b)=>!isObject(b)||b.type!=="tool_result")}function num(v){return typeof v==="number"&&Number.isFinite(v)?v:0}function readUsage(v){if(!isObject(v))return;return{input_tokens:num(v.input_tokens),output_tokens:num(v.output_tokens),cache_read_input_tokens:num(v.cache_read_input_tokens),cache_creation_input_tokens:num(v.cache_creation_input_tokens)}}function finish(draft){if(!draft.id)return null;let totals={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};for(let u of draft.usageByMessage.values())totals.input_tokens+=u.input_tokens,totals.output_tokens+=u.output_tokens,totals.cache_read_input_tokens+=u.cache_read_input_tokens,totals.cache_creation_input_tokens+=u.cache_creation_input_tokens;return{id:draft.id,sessionId:draft.sessionId,...draft.model?{model:draft.model}:{},startedAt:draft.startedAt,endedAt:draft.endedAt,...draft.usageByMessage.size>0?{usage:totals}:{}}}function parseClaudeTurns(raw,fallbackSessionId=""){let out=[],draft=null;for(let line of raw.split(`
4
4
  `)){let trimmed=line.trim();if(!trimmed||!isJsonlLineWithinBound(trimmed))continue;let record;try{record=JSON.parse(trimmed)}catch{continue}if(!isObject(record)||isSyntheticClaudeRecord(record))continue;let inner=isObject(record.message)?record.message:record,at=typeof record.timestamp==="string"?Date.parse(record.timestamp):Number.NaN;if(!Number.isFinite(at))continue;let sessionId=typeof record.sessionId==="string"?record.sessionId:fallbackSessionId;if(inner.role==="user"){if(!opensTurn(inner.content))continue;if(draft){let done=finish(draft);if(done)out.push(done)}draft={id:"",sessionId,startedAt:at,endedAt:at,usageByMessage:new Map};continue}if(inner.role!=="assistant"||!draft)continue;if(draft.endedAt=at,typeof inner.model==="string")draft.model=inner.model;let messageId=typeof inner.id==="string"?inner.id:"";if(messageId)draft.id=messageId;let usage=readUsage(inner.usage);if(usage&&messageId)draft.usageByMessage.set(messageId,usage)}if(draft){let done=finish(draft);if(done)out.push(done)}return out}async function readClaudeTurns(transcriptPath){try{let raw=await readTextFileBounded(transcriptPath);return parseClaudeTurns(raw)}catch{return[]}}var HEX_RE=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;function parseHex(value){let match=HEX_RE.exec(value);if(!match)return[0,0,0];return[Number.parseInt(match[1],16),Number.parseInt(match[2],16),Number.parseInt(match[3],16)]}function luminance([red,green,blue]){return(red*0.2126+green*0.7152+blue*0.0722)/255}function blend(from,to,amount){return[Math.round(from[0]+(to[0]-from[0])*amount),Math.round(from[1]+(to[1]-from[1])*amount),Math.round(from[2]+(to[2]-from[2])*amount)]}function codexUserMessageBackground(background){return luminance(background)>0.5?blend(background,[0,0,0],0.04):blend(background,[255,255,255],0.12)}function transcriptRewrite(palette){let foreground=parseHex(palette.foreground),background=parseHex(palette.background),backgroundIsLight=luminance(background)>0.5;return{matchBackground:codexUserMessageBackground(background),foreground:backgroundIsLight?foreground:background,background:backgroundIsLight?background:foreground}}var codexTerminalPresentation={alternateScreenStyleRewrites:(palette)=>[transcriptRewrite(palette)]};var codexCapabilities={preparePromptSubmission:(prompt)=>{return/^[\/!]/.test(prompt.trimStart())?prompt:`${prompt} `},beforePromptSubmit:"\x1B[F",terminalPresentation:codexTerminalPresentation,interruptSequence:"\x1B"},codexIdentity={shortName:"Codex"};import{join}from"path";var EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"Stop",verb:"turn-complete"},{event:"SessionEnd",verb:"session-end"},{event:"PreCompact",verb:"pre-compact"},{event:"PostCompact",verb:"post-compact"},{event:"SubagentStart",verb:"subagent-start"},{event:"SubagentStop",verb:"subagent-stop"},{event:"PreToolUse",verb:"tool-pre"},{event:"PostToolUse",verb:"tool-post"}],ROVE_CODEX_HOOK_EVENTS=EVENT_MAP.map((e)=>e.event);function codexHooksPath(){return join(vendorConfigHome("codex"),"hooks.json")}class CodexHookAdapter extends JsonHookAdapter{vendor="codex";setupCommand="/hooks";eventMap=EVENT_MAP;globalSettingsPath(){return codexHooksPath()}activityDetailFromPayload(kind,payload){if(kind==="tool-pre"||kind==="tool-post")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{}}};if(kind==="pre-compact"||kind==="post-compact")return{compact:{trigger:payload.trigger==="manual"?"manual":"auto"}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}}import{createHash}from"crypto";function createAppendParseCache(opts){let maxFiles=opts.maxFiles??8,cache=new Map;function remember(filePath,entry){if(cache.delete(filePath),cache.set(filePath,entry),cache.size>maxFiles){let oldest=cache.keys().next().value;if(oldest!==void 0)cache.delete(oldest)}}return function(filePath,raw,ctx){let stableLength=raw.lastIndexOf(`
5
5
  `)+1,entry=cache.get(filePath),verifiedLength=Math.min(entry?.prefixLength??0,stableLength),hash=createHash("sha256").update(raw.slice(0,verifiedLength)),unchanged=entry!==void 0&&Object.is(entry.context,ctx)&&entry.prefixLength<=stableLength&&hash.copy().digest("hex")===entry.prefixHash,prefixState;if(unchanged)prefixState=entry.prefixLength<stableLength?opts.parseChunk(raw.slice(entry.prefixLength,stableLength),entry.state,ctx):entry.state;else prefixState=opts.parseChunk(raw.slice(0,stableLength),opts.initial(ctx),ctx);if(!unchanged||entry.prefixLength!==stableLength||entry.state!==prefixState)remember(filePath,{context:ctx,prefixLength:stableLength,prefixHash:hash.update(raw.slice(verifiedLength,stableLength)).digest("hex"),state:prefixState});let tail=raw.slice(stableLength);return tail.trim().length>0?opts.parseChunk(tail,prefixState,ctx):prefixState}}var sortedMessages=new WeakMap;function sortByTimestamp(messages){let hit=sortedMessages.get(messages);if(hit)return hit;let sorted=[...messages].sort((a,b)=>a.timestamp<b.timestamp?-1:a.timestamp>b.timestamp?1:0);return sortedMessages.set(messages,sorted),sorted}function normalizeCodexContent(raw){if(typeof raw==="string")return raw.length>0?[{type:"text",text:raw}]:[];if(!Array.isArray(raw))return[];let blocks=[];for(let item of raw){if(typeof item==="string"){if(item.length>0)blocks.push({type:"text",text:item});continue}if(!isObject(item))continue;let t=typeof item.type==="string"?item.type:void 0;if(t==="input_text"||t==="output_text"){let text=typeof item.text==="string"?item.text:"";if(text.length>0)blocks.push({type:"text",text});continue}if(t)blocks.push({type:"text",text:`[codex: ${t}]`})}return blocks}function isSyntheticCodexUserRow(blocks){if(blocks.length===0)return!1;for(let b of blocks){if(b.type!=="text")return!1;let t=(b.text??"").trim();if(!isTagEnvelope(t)&&!isInstructionsEnvelope(t))return!1}return!0}var ENVELOPE_TAGS=["environment_context","recommended_plugins","user_instructions"];function isTagEnvelope(text){return ENVELOPE_TAGS.some((tag)=>text.startsWith(`<${tag}>`)&&text.endsWith(`</${tag}>`))}function isInstructionsEnvelope(text){return text.startsWith("# AGENTS.md instructions")&&text.includes("<INSTRUCTIONS>")}function codexUsageToSnapshot(usage,opts={}){let totalInput=numberOr(usage.input_tokens,0),cachedInput=numberOr(usage.cached_input_tokens,0),output=numberOr(usage.output_tokens,0),nonCachedInput=Math.max(0,totalInput-cachedInput);if(totalInput<=0&&output<=0&&cachedInput<=0)return;return{input_tokens:nonCachedInput,output_tokens:output,...cachedInput>0?{cache_read_input_tokens:cachedInput}:{},...validPositive(opts.contextWindowTokens)?{context_window_tokens:opts.contextWindowTokens}:{}}}function numberOr(v,fallback){return typeof v==="number"&&Number.isFinite(v)?v:fallback}function validPositive(v){return typeof v==="number"&&Number.isFinite(v)&&v>0}var emptyState={messages:[],latestUsage:void 0,latestUsageTimestampMs:null},cache=createAppendParseCache({initial:()=>emptyState,parseChunk:foldRolloutChunk});function parseRolloutRaw(filePath,raw,sessionId){let state=cache(filePath,raw,sessionId);return{messages:sortByTimestamp(state.messages),...state.latestUsage?{usageMetrics:state.latestUsage}:{}}}function foldRolloutChunk(chunk,prev,sessionId){let updatedMessages,writableMessages=()=>{return updatedMessages??=[...prev.messages],updatedMessages},latestUsage=prev.latestUsage,latestUsageTimestampMs=prev.latestUsageTimestampMs;for(let line of chunk.split(`
@@ -34,8 +34,8 @@ ${body}
34
34
  `)}function mergeKimiHooks(content,install,inv=roveHookInvocation(),opts={}){let base=removeKimiHookBlock(content);if(!install)return base;let trimmed=base.replace(/\n+$/,"");return`${trimmed.length>0?`${trimmed}
35
35
 
36
36
  `:""}${renderKimiHookBlock(inv,opts)}
37
- `}function kimiFailureDetail(payload){let type=typeof payload.error_type==="string"?payload.error_type:"",message=typeof payload.error_message==="string"?payload.error_message:"",note=type||void 0;return{failure:(()=>{if(type==="APIProviderRateLimitError"||message.includes("provider.rate_limit"))return"rate_limit";if(type==="APIProviderQuotaExhaustedError")return"rate_limit";if(message.includes("provider.auth_error"))return"billing";return"other"})(),...note?{note}:{}}}class KimiHookAdapter{vendor="kimi";supportsHooks(){return!0}globalSettingsPath(){return kimiConfigPath()}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return kimiFailureDetail(payload);if(kind==="awaiting-input")return{waiting:"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{}}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync2(dirname2(settingsFilePath)))return{ok:!0};return await editTomlConfig(settingsFilePath,(cur)=>mergeKimiHooks(cur,!0,void 0,opts)),{ok:!0}}async removeActivityHooks(settingsFilePath){if(!existsSync2(settingsFilePath))return;await editTomlConfig(settingsFilePath,(cur)=>mergeKimiHooks(cur,!1))}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}async function editTomlConfig(path9,transform){try{let current="";try{current=await readFile(path9,"utf8")}catch(error){if(!(error&&typeof error==="object"&&("code"in error)&&error.code==="ENOENT"))return}let next=transform(current);if(next===current)return;await mkdir2(dirname2(path9),{recursive:!0}),await writeFile(path9,next)}catch{}}var KIMI_SCREEN_MANIFEST={rules:[{state:"blocked",all:["\u21B5 confirm"],any:["approve","reject","revise"]},{state:"blocked",all:["\u2191\u2193 navigate","esc exit"]},{state:"blocked",all:["\u2191\u2193 select","esc cancel"]},{state:"working",lineRegex:["^\\s*(\uD83C\uDF15|\uD83C\uDF16|\uD83C\uDF17|\uD83C\uDF18|\uD83C\uDF11|\uD83C\uDF12|\uD83C\uDF13|\uD83C\uDF14)","^\\s*[\\u2800-\\u28FF]+\\s*(thinking|working|using )"]}]};import{createHash as createHash2}from"crypto";import{mkdirSync as mkdirSync2,writeFileSync as writeFileSync2}from"fs";import path9 from"path";function kimiTrustFilePath(worktreePath,home){let resolved=realPathOrSelf(worktreePath),hash=createHash2("sha256").update(resolved).digest("hex").slice(0,12),dir=path9.basename(resolved).toLowerCase();return path9.join(vendorConfigHome("kimi",vendorWriteHomeDeps(home)),"workspace-trust",`wd_${dir}_${hash}`)}function trustKimiWorktree(worktreePath,home){let file=kimiTrustFilePath(worktreePath,home);mkdirSync2(path9.dirname(file),{recursive:!0,mode:448});try{writeFileSync2(file,JSON.stringify({root:realPathOrSelf(worktreePath),trustedAt:Date.now()}),{mode:384,flag:"wx"})}catch(error){if(!(error instanceof Error&&("code"in error)&&error.code==="EEXIST"))throw error}}import{execFile}from"child_process";import{promisify}from"util";var run=promisify(execFile),LIST_TIMEOUT_MS=15000;async function stdoutOf(bin,args){let{stdout}=await run(bin,[...args],{encoding:"utf8",timeout:LIST_TIMEOUT_MS,maxBuffer:4194304});return stdout}var CLAUDE_MODELS=[{id:"fable"},{id:"opus"},{id:"sonnet"}],CODEX_MODELS=[{id:"gpt-6-astra"},{id:"gpt-5.6-luna"},{id:"gpt-5.6-sol"},{id:"gpt-5.5"}];function isClaudeFamilyModel(model){return/^(claude-|anthropic\/)|^(fable|opus|sonnet|haiku)(\[|$)/i.test(model.trim())}function isOpenAiFamilyModel(model){return/^(gpt-|o\d|codex-|openai\/)/i.test(model.trim())}function parsePiModelTable(stdout){let out=[];for(let line of stdout.split(`
38
- `)){let cols=line.trim().split(/\s+/);if(cols.length<2)continue;let[provider,model]=cols;if(provider==="provider"&&model==="model")continue;out.push({id:`${provider}/${model}`,label:model})}return out}async function listPiModels(){return parsePiModelTable(await stdoutOf("pi",["--list-models"]))}function parseOmpModelJson(stdout){let models=JSON.parse(stdout).models;if(!Array.isArray(models))throw Error("omp models --json: no `models` array");let out=[];for(let m of models){if(typeof m.selector!=="string"||!m.selector)continue;out.push({id:m.selector,...typeof m.name==="string"&&m.name?{label:m.name}:{}})}return out}async function listOmpModels(){return parseOmpModelJson(await stdoutOf("omp",["models","--json"]))}var piCapabilities={interruptSequence:"\x1B"},ompCapabilities={interruptSequence:"\x1B",inlineImageEnv:{PI_FORCE_IMAGE_PROTOCOL:"kitty",PI_KITTY_PLACEHOLDERS:"1",PI_FORCE_HYPERLINKS:"1"}},piIdentity={shortName:"Pi"},ompIdentity={shortName:"OMP"};import{existsSync as existsSync3}from"fs";import{rm as rm2}from"fs/promises";import path10 from"path";function renderPiExtensionSource(opts){let{vendor,invocation,toolEvents=!1}=opts,tool=toolEvents?TOOL_SECTION:"";return`/**
37
+ `}function kimiFailureDetail(payload){let type=typeof payload.error_type==="string"?payload.error_type:"",message=typeof payload.error_message==="string"?payload.error_message:"",note=type||void 0;return{failure:(()=>{if(type==="APIProviderRateLimitError"||message.includes("provider.rate_limit"))return"rate_limit";if(type==="APIProviderQuotaExhaustedError")return"rate_limit";if(message.includes("provider.auth_error"))return"billing";return"other"})(),...note?{note}:{}}}class KimiHookAdapter{vendor="kimi";supportsHooks(){return!0}globalSettingsPath(){return kimiConfigPath()}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return kimiFailureDetail(payload);if(kind==="awaiting-input")return{waiting:"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{}}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync2(dirname2(settingsFilePath)))return{ok:!0};return await editTomlConfig(settingsFilePath,(cur)=>mergeKimiHooks(cur,!0,void 0,opts)),{ok:!0}}async removeActivityHooks(settingsFilePath){if(!existsSync2(settingsFilePath))return;await editTomlConfig(settingsFilePath,(cur)=>mergeKimiHooks(cur,!1))}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}async function editTomlConfig(path9,transform){try{let current="";try{current=await readFile(path9,"utf8")}catch(error){if(!(error&&typeof error==="object"&&("code"in error)&&error.code==="ENOENT"))return}let next=transform(current);if(next===current)return;await mkdir2(dirname2(path9),{recursive:!0}),await writeFile(path9,next)}catch{}}var KIMI_SCREEN_MANIFEST={rules:[{state:"blocked",all:["\u21B5 confirm"],any:["approve","reject","revise"]},{state:"blocked",all:["\u2191\u2193 navigate","esc exit"]},{state:"blocked",all:["\u2191\u2193 select","esc cancel"]},{state:"working",lineRegex:["^\\s*(\uD83C\uDF15|\uD83C\uDF16|\uD83C\uDF17|\uD83C\uDF18|\uD83C\uDF11|\uD83C\uDF12|\uD83C\uDF13|\uD83C\uDF14)","^\\s*[\\u2800-\\u28FF]+\\s*(thinking|working|using )"]}]};import{createHash as createHash2}from"crypto";import{mkdirSync as mkdirSync2,writeFileSync as writeFileSync2}from"fs";import path9 from"path";function kimiTrustFilePath(worktreePath,home){let resolved=realPathOrSelf(worktreePath),hash=createHash2("sha256").update(resolved).digest("hex").slice(0,12),dir=path9.basename(resolved).toLowerCase();return path9.join(vendorConfigHome("kimi",vendorWriteHomeDeps(home)),"workspace-trust",`wd_${dir}_${hash}`)}function trustKimiWorktree(worktreePath,home){let file=kimiTrustFilePath(worktreePath,home);mkdirSync2(path9.dirname(file),{recursive:!0,mode:448});try{writeFileSync2(file,JSON.stringify({root:realPathOrSelf(worktreePath),trustedAt:Date.now()}),{mode:384,flag:"wx"})}catch(error){if(!(error instanceof Error&&("code"in error)&&error.code==="EEXIST"))throw error}}import{execFile}from"child_process";import{mkdirSync as mkdirSync3,readFileSync,renameSync,statSync,writeFileSync as writeFileSync3}from"fs";import{delimiter,dirname as dirname3,isAbsolute,join as join4}from"path";import{promisify}from"util";var run=promisify(execFile),LIST_TIMEOUT_MS=15000;async function stdoutOf(bin,args){let{stdout}=await run(bin,[...args],{encoding:"utf8",timeout:LIST_TIMEOUT_MS,maxBuffer:4194304});return stdout}var CACHE_TTL_MS=900000;function binaryKey(bin){let dirs=isAbsolute(bin)?[""]:(process.env.PATH??"").split(delimiter);for(let dir of dirs){let candidate=dir?join4(dir,bin):bin;try{let s=statSync(candidate);if(s.isFile())return`${candidate}:${s.mtimeMs}:${s.size}`}catch{}}return`${bin}:unknown`}function readCache(key){try{let hit=JSON.parse(readFileSync(join4(roveStateDir(),"model-lists.json"),"utf8"))[key];if(!hit||typeof hit.at!=="number"||Date.now()-hit.at>CACHE_TTL_MS)return null;return Array.isArray(hit.models)?hit.models:null}catch{return null}}function writeCache(key,models){let path10=join4(roveStateDir(),"model-lists.json");try{mkdirSync3(dirname3(path10),{recursive:!0});let all={};try{let parsed=JSON.parse(readFileSync(path10,"utf8"));if(parsed&&typeof parsed==="object")all=parsed}catch{}all[key]={at:Date.now(),models};let tmp=`${path10}.tmp-${process.pid}`;writeFileSync3(tmp,JSON.stringify(all)),renameSync(tmp,path10)}catch{}}async function cachedModelList(bin,args,parse2){let key=`${bin} ${args.join(" ")} ${binaryKey(bin)}`,hit=readCache(key);if(hit)return hit;let models=parse2(await stdoutOf(bin,args));return writeCache(key,models),models}var CLAUDE_MODELS=[{id:"fable"},{id:"opus"},{id:"sonnet"}],CODEX_MODELS=[{id:"gpt-6-astra"},{id:"gpt-5.6-luna"},{id:"gpt-5.6-sol"},{id:"gpt-5.5"}];function isClaudeFamilyModel(model){return/^(claude-|anthropic\/)|^(fable|opus|sonnet|haiku)(\[|$)/i.test(model.trim())}function isOpenAiFamilyModel(model){return/^(gpt-|o\d|codex-|openai\/)/i.test(model.trim())}function parsePiModelTable(stdout){let out=[];for(let line of stdout.split(`
38
+ `)){let cols=line.trim().split(/\s+/);if(cols.length<2)continue;let[provider,model]=cols;if(provider==="provider"&&model==="model")continue;out.push({id:`${provider}/${model}`,label:model})}return out}async function listPiModels(){return cachedModelList("pi",["--list-models"],parsePiModelTable)}function parseOmpModelJson(stdout){let models=JSON.parse(stdout).models;if(!Array.isArray(models))throw Error("omp models --json: no `models` array");let out=[];for(let m of models){if(typeof m.selector!=="string"||!m.selector)continue;out.push({id:m.selector,...typeof m.name==="string"&&m.name?{label:m.name}:{}})}return out}async function listOmpModels(){return cachedModelList("omp",["models","--json"],parseOmpModelJson)}var piCapabilities={interruptSequence:"\x1B"},ompCapabilities={interruptSequence:"\x1B",inlineImageEnv:{PI_FORCE_IMAGE_PROTOCOL:"kitty",PI_KITTY_PLACEHOLDERS:"1",PI_FORCE_HYPERLINKS:"1"}},piIdentity={shortName:"Pi"},ompIdentity={shortName:"OMP"};import{existsSync as existsSync3}from"fs";import{rm as rm2}from"fs/promises";import path10 from"path";function renderPiExtensionSource(opts){let{vendor,invocation,toolEvents=!1}=opts,tool=toolEvents?TOOL_SECTION:"";return`/**
39
39
  * Rove activity hook \u2014 GENERATED, installed and rewritten by Rove on every
40
40
  * launch (${vendor}). Local edits are overwritten; to stop reporting, delete
41
41
  * this file or turn Rove's global hooks off.
@@ -161,8 +161,8 @@ ${tool}}
161
161
  tool_name: field(event, "toolName"),
162
162
  }),
163
163
  )
164
- `;var ACTIVITY_EXTENSION_FILE="rove-activity.ts";function piExtensionsDir(vendor,deps){return path10.join(vendorAgentDir(vendor,deps),"extensions")}function piActivityExtensionPath(vendor,deps){return path10.join(piExtensionsDir(vendor,deps),ACTIVITY_EXTENSION_FILE)}function piFailureDetail(payload){let raw=typeof payload.error_message==="string"?payload.error_message:"",message=raw.toLowerCase(),note=raw?raw.slice(0,200):void 0;return{failure:(()=>{if(/insufficient|credit|billing|payment required|\b402\b|quota exceeded|out of credits/.test(message))return"billing";if(/rate.?limit|too many requests|\b429\b|overloaded|capacity/.test(message))return"rate_limit";if(isTransientFailureText(message))return"transient";return"other"})(),...note?{note}:{}}}class PiFamilyHookAdapter{family;vendor;constructor(family){this.family=family;this.vendor=family}supportsHooks(){return!0}globalSettingsPath(){return piActivityExtensionPath(this.family)}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return piFailureDetail(payload);if(kind==="awaiting-input")return{waiting:payload.waiting==="input"?"input":"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed"){let name=typeof payload.tool_name==="string"?payload.tool_name:void 0;return{tool:{...name?{name}:{}}}}return}sessionFromPayload(payload){let sessionId=typeof payload.session_id==="string"?payload.session_id:void 0;if(!sessionId)return;let transcriptPath3=typeof payload.transcript_path==="string"?payload.transcript_path:void 0;return{sessionId,...transcriptPath3?{transcriptPath:transcriptPath3}:{}}}async installActivityHooks(settingsFilePath,opts={}){let agentDir=path10.dirname(path10.dirname(settingsFilePath));if(!existsSync3(agentDir))return{ok:!0};let source=renderPiExtensionSource({vendor:this.family,invocation:roveHookInvocation(),toolEvents:opts.toolEvents??!1});return await writeIfChanged(settingsFilePath,source),{ok:!0}}async removeActivityHooks(settingsFilePath){try{await rm2(settingsFilePath,{force:!0})}catch{}}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}var OMP_SCREEN_MANIFEST={rules:[{state:"blocked",all:["allow tool"],any:["approve","deny"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]{1,2}\\s+\\d+s\\s+\xB7"]},{state:"idle",lineRegex:["^\\s*\xB7\\s+\\S+.*\xB7"]}]},PI_SCREEN_MANIFEST={rules:[{state:"blocked",all:["trust project folder?"]},{state:"blocked",all:["\u2191\u2193 navigate","escape/ctrl+c cancel"]},{state:"working",any:["working..."]},{state:"idle",lineRegex:["^\\s*[\u2191\u2193]\\s*\\d"]}]};var OMP_SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var OMP_WORKING_PREFIXES=OMP_SPINNER_FRAMES.map((frame)=>`${"\u03C0"} ${frame}`),OMP_ATTENTION_PREFIXES=[`${"\u03C0"} !`],OMP_STATUS_PREFIXES=[...OMP_WORKING_PREFIXES,...OMP_ATTENTION_PREFIXES,`${"\u03C0"} >`,`${"\u03C0"}:`],PI_STATUS_PREFIXES=[`${"\u03C0"} -`];import{existsSync as existsSync4,mkdirSync as mkdirSync3,readFileSync,writeFileSync as writeFileSync3}from"fs";import path11 from"path";function piTrustPath(deps){return path11.join(vendorAgentDir("pi",deps),"trust.json")}function trustPiWorktree(worktreePath,deps){let file=piTrustPath(deps);try{let existing={};if(existsSync4(file)){let parsed=JSON.parse(readFileSync(file,"utf8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return;for(let[key,value]of Object.entries(parsed))existing[key]=value===!0}existing[realPathOrSelf(worktreePath)]=!0,mkdirSync3(path11.dirname(file),{recursive:!0}),writeFileSync3(file,`${JSON.stringify(existing,null,2)}
164
+ `;var ACTIVITY_EXTENSION_FILE="rove-activity.ts";function piExtensionsDir(vendor,deps){return path10.join(vendorAgentDir(vendor,deps),"extensions")}function piActivityExtensionPath(vendor,deps){return path10.join(piExtensionsDir(vendor,deps),ACTIVITY_EXTENSION_FILE)}function piFailureDetail(payload){let raw=typeof payload.error_message==="string"?payload.error_message:"",message=raw.toLowerCase(),note=raw?raw.slice(0,200):void 0;return{failure:(()=>{if(/insufficient|credit|billing|payment required|\b402\b|quota exceeded|out of credits/.test(message))return"billing";if(/rate.?limit|too many requests|\b429\b|overloaded|capacity/.test(message))return"rate_limit";if(isTransientFailureText(message))return"transient";return"other"})(),...note?{note}:{}}}class PiFamilyHookAdapter{family;vendor;constructor(family){this.family=family;this.vendor=family}supportsHooks(){return!0}globalSettingsPath(){return piActivityExtensionPath(this.family)}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return piFailureDetail(payload);if(kind==="awaiting-input")return{waiting:payload.waiting==="input"?"input":"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed"){let name=typeof payload.tool_name==="string"?payload.tool_name:void 0;return{tool:{...name?{name}:{}}}}return}sessionFromPayload(payload){let sessionId=typeof payload.session_id==="string"?payload.session_id:void 0;if(!sessionId)return;let transcriptPath3=typeof payload.transcript_path==="string"?payload.transcript_path:void 0;return{sessionId,...transcriptPath3?{transcriptPath:transcriptPath3}:{}}}async installActivityHooks(settingsFilePath,opts={}){let agentDir=path10.dirname(path10.dirname(settingsFilePath));if(!existsSync3(agentDir))return{ok:!0};let source=renderPiExtensionSource({vendor:this.family,invocation:roveHookInvocation(),toolEvents:opts.toolEvents??!1});return await writeIfChanged(settingsFilePath,source),{ok:!0}}async removeActivityHooks(settingsFilePath){try{await rm2(settingsFilePath,{force:!0})}catch{}}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}var OMP_SCREEN_MANIFEST={rules:[{state:"blocked",all:["allow tool"],any:["approve","deny"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]{1,2}\\s+\\d+s\\s+\xB7"]},{state:"idle",lineRegex:["^\\s*\xB7\\s+\\S+.*\xB7"]}]},PI_SCREEN_MANIFEST={rules:[{state:"blocked",all:["trust project folder?"]},{state:"blocked",all:["\u2191\u2193 navigate","escape/ctrl+c cancel"]},{state:"working",any:["working..."]},{state:"idle",lineRegex:["^\\s*[\u2191\u2193]\\s*\\d"]}]};var OMP_SPINNER_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];var OMP_WORKING_PREFIXES=OMP_SPINNER_FRAMES.map((frame)=>`${"\u03C0"} ${frame}`),OMP_ATTENTION_PREFIXES=[`${"\u03C0"} !`],OMP_STATUS_PREFIXES=[...OMP_WORKING_PREFIXES,...OMP_ATTENTION_PREFIXES,`${"\u03C0"} >`,`${"\u03C0"}:`],PI_STATUS_PREFIXES=[`${"\u03C0"} -`];import{existsSync as existsSync4,mkdirSync as mkdirSync4,readFileSync as readFileSync2,writeFileSync as writeFileSync4}from"fs";import path11 from"path";function piTrustPath(deps){return path11.join(vendorAgentDir("pi",deps),"trust.json")}function trustPiWorktree(worktreePath,deps){let file=piTrustPath(deps);try{let existing={};if(existsSync4(file)){let parsed=JSON.parse(readFileSync2(file,"utf8"));if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))return;for(let[key,value]of Object.entries(parsed))existing[key]=value===!0}existing[realPathOrSelf(worktreePath)]=!0,mkdirSync4(path11.dirname(file),{recursive:!0}),writeFileSync4(file,`${JSON.stringify(existing,null,2)}
165
165
  `)}catch{}}import{stat as stat6}from"fs/promises";class EngineTurnDetector{supportsCompletionMarkers(){return!0}async latestCompletion(worktree){return(await this.latestActivity(worktree)).marker}async latestActivityInFile(_transcriptPath){return null}}function createEngineTurnDetector(vendor){return engineEntry(vendor).createTurnDetector()}var statFile=(path12)=>stat6(path12).catch(()=>null);function completionReader(deps,parse2){let cache4=new Map;return async(path12,knownMtime)=>{let info=deps.statFile?await deps.statFile(path12):null;if(deps.statFile&&!info)return null;let mtimeMs=info?.mtimeMs??knownMtime??await(deps.statMtimeMs??(async(p)=>(await statFile(p))?.mtimeMs??0))(path12);if(!info&&knownMtime===void 0&&mtimeMs===0)return null;let key=info?`${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`:String(mtimeMs),hit=cache4.get(path12);if(mtimeMs>0&&hit?.key===key)return hit.scan;let raw;try{raw=await deps.readFile(path12)}catch{return cache4.delete(path12),null}if(raw===null)return cache4.delete(path12),null;let scan={marker:parse2(raw,path12,mtimeMs),mtimeMs};if(cache4.delete(path12),cache4.set(path12,{key,scan}),cache4.size>8){let oldest=cache4.keys().next().value;if(oldest!==void 0)cache4.delete(oldest)}return scan}}var defaultClaudeDeps={listSessionFiles:(worktree)=>listSessionFilesForWorktree(worktree),readFile:readTextFileIfRegular,statFile};class ClaudeTurnDetector extends EngineTurnDetector{deps;vendor="claude";readCompletion;constructor(deps=defaultClaudeDeps){super();this.deps=deps;this.readCompletion=completionReader(deps,latestClaudeCompletionMarkerFromJsonl)}async latestActivity(worktree){let files=await this.deps.listSessionFiles(worktree),mtimeMs=files[0]?.mtimeMs??0,latest=null;for(let file of files.slice(0,4)){let marker=(await this.readCompletion(file.path,file.mtimeMs))?.marker;if(marker&&(!latest||marker.timestampMs>latest.timestampMs))latest=marker}return{marker:latest,mtimeMs}}latestActivityInFile(transcriptPath3){return this.readCompletion(transcriptPath3)}}var defaultCodexDeps={findLatestRollout:(worktree)=>findLatestRolloutForWorktree(worktree),readFile:readTextFileIfRegular,statFile};class CodexTurnDetector extends EngineTurnDetector{deps;vendor="codex";readCompletion;constructor(deps=defaultCodexDeps){super();this.deps=deps;this.readCompletion=completionReader(deps,latestCodexCompletionMarkerFromJsonl)}latestActivityInFile(transcriptPath3){return this.readCompletion(transcriptPath3)}async latestActivity(worktree){if(!worktree)return{marker:null,mtimeMs:0};let found=await this.deps.findLatestRollout(worktree);return found?await this.readCompletion(found.path,found.mtimeMs)??{marker:null,mtimeMs:0}:{marker:null,mtimeMs:0}}}class UnknownTurnDetector extends EngineTurnDetector{vendor;constructor(vendor){super();this.vendor=vendor}supportsCompletionMarkers(){return!1}async latestActivity(){return{marker:null,mtimeMs:0}}}var CLAUDE_TURN_END_STOP_REASONS=new Set(["end_turn","stop_sequence","max_tokens","refusal"]);function latestClaudeCompletionMarkerFromJsonl(raw,sourceId="claude",fallbackMtimeMs=0){let latest=null,lineNo=0;for(let line of raw.split(`
166
166
  `)){lineNo++;let record=parseJsonLine(line);if(!record)continue;let inner=isObject(record.message)?record.message:record;if(inner.role!=="assistant")continue;if(typeof inner.stop_reason!=="string")continue;if(!CLAUDE_TURN_END_STOP_REASONS.has(inner.stop_reason))continue;let timestampMs=timestampFromRecord(record,fallbackMtimeMs),marker={id:`claude:${sourceId}:${timestampMs}:${lineNo}`,timestampMs,source:"claude"};if(!latest||marker.timestampMs>=latest.timestampMs)latest=marker}return latest}var CODEX_ROLLOUT_DONE_EVENTS=new Set(["task_complete","turn_complete","turn_aborted"]);function isCodexCompletionRecord(record){if(record.type==="turn.completed")return!0;if(record.type!=="event_msg")return!1;let payload=isObject(record.payload)?record.payload:void 0;return typeof payload?.type==="string"&&CODEX_ROLLOUT_DONE_EVENTS.has(payload.type)}function latestCodexCompletionMarkerFromJsonl(raw,sourceId="codex"){let latest=null,lineNo=0;for(let line of raw.split(`
167
- `)){lineNo++;let record=parseJsonLine(line);if(!record||!isCodexCompletionRecord(record))continue;let timestampMs=timestampFromRecord(record,0),marker={id:`codex:${sourceId}:${timestampMs}:${lineNo}`,timestampMs,source:"codex"};if(!latest||marker.timestampMs>=latest.timestampMs)latest=marker}return latest}function parseJsonLine(line){if(!isJsonlLineWithinBound(line))return null;let trimmed=line.trim();if(!trimmed)return null;try{let parsed=JSON.parse(trimmed);return isObject(parsed)?parsed:null}catch{return null}}function timestampFromRecord(record,fallback){let ts=typeof record.timestamp==="string"?Date.parse(record.timestamp):Number.NaN;return Number.isFinite(ts)?ts:fallback}var BUILTIN_ENGINES={claude:{vendor:"claude",builtin:!0,displayName:claudeIdentity.shortName,defaultCommand:["claude"],listModels:async()=>CLAUDE_MODELS,modelArgv:(base,model)=>[...base,"--model",model],addDirArgv:(base,dirs)=>[...base,...dirs.map((dir)=>`--add-dir=${dir}`)],effortLevels:["low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"--effort",level],foreignModel:isOpenAiFamilyModel,history:claudeHistoryReader,detectAccount:(deps)=>detectClaudeAccount(deps),createHookAdapter:()=>new ClaudeHookAdapter,skillsDir:()=>isRovePluginEnabled()?null:skillsDirUnder(vendorConfigHome("claude")),createTurnDetector:()=>new ClaudeTurnDetector,capabilities:claudeCapabilities,identity:claudeIdentity,trustWorktree:trustClaudeWorktree,terminalTitle:{ownsStatus:!0,statusPrefixes:["\u2733","\u2802","\u2810","\u25D0","\u25D1"],workingPrefixes:["\u2802","\u2810","\u25D0","\u25D1"]},sessionIdentity:{pinFlag:"--session-id",sessionControlFlags:["--session-id","--resume","-r","--continue","-c","--from-pr"],resumeArgv:(base,id)=>[...base,"--resume",id],forkArgv:(base,sourceId,newId)=>{let forked=[...base,"--resume",sourceId,"--fork-session"];return newId?[...forked,"--session-id",newId]:forked}},quotaUsage:()=>fetchClaudeQuotaUsage(),readTurns:readClaudeTurns},codex:{vendor:"codex",builtin:!0,displayName:codexIdentity.shortName,defaultCommand:["codex"],effortLevels:["none","low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"-c",`model_reasoning_effort=${level}`],listModels:async()=>CODEX_MODELS,modelArgv:(base,model)=>[...base,"--model",model],addDirArgv:(base,dirs)=>[...base,...dirs.map((dir)=>`--add-dir=${dir}`)],hostedStartArgv:(argv)=>{for(let i=1;i<argv.length;i++){let arg=argv[i];if(arg==="--")break;let config=arg==="-c"||arg==="--config"?argv[++i]:arg.startsWith("--config=")?arg.slice(9):arg.startsWith("-c")?arg.slice(2).replace(/^=/,""):void 0;if(config&&/^\s*check_for_update_on_startup\s*=/.test(config))return argv}return[...argv,"-c","check_for_update_on_startup=false"]},foreignModel:isClaudeFamilyModel,errorLine:/^\s*\u25A0\s+\S/,history:codexHistoryReader,detectAccount:(deps)=>detectCodexAccount(deps),createHookAdapter:()=>new CodexHookAdapter,skillsDir:()=>skillsDirUnder(vendorConfigHome("codex")),createTurnDetector:()=>new CodexTurnDetector,capabilities:codexCapabilities,identity:codexIdentity,trustWorktree:trustCodexWorktree,readTurns:readCodexTurns,terminalTitle:{ownsStatus:!0,launchArgs:["-c",'tui.terminal_title=["activity","thread-title"]'],statusPrefixes:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],workingPrefixes:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],sessionIdFromTitle:codexSessionIdFromTitle},sessionIdentity:{resumeArgv:(base,id)=>{let[bin,...rest]=base;return bin?[bin,"resume",...rest,id]:base},forkArgv:(base,sourceId)=>{let[bin,...rest]=base;return bin?[bin,"fork",...rest,sourceId]:null}},quotaUsage:()=>fetchCodexQuotaUsage()},bob:{vendor:"bob",builtin:!0,displayName:"IBM Bob",defaultCommand:["bob","chat","--trust"],firstMessageDelivery:"paste",history:bobHistoryReader,detectAccount:(deps)=>detectBobAccount(deps),trustWorktree:trustBobWorktree,createHookAdapter:()=>new NoopHookAdapter("bob"),skillsDir:()=>skillsDirUnder(bobHome()),createTurnDetector:()=>new UnknownTurnDetector("bob"),screenManifest:BOB_SCREEN_MANIFEST},copilot:{vendor:"copilot",builtin:!0,displayName:"Copilot",defaultCommand:["copilot"],history:copilotHistoryReader,detectAccount:(deps)=>detectCopilotAccount(deps),createHookAdapter:()=>new CopilotHookAdapter,skillsDir:()=>skillsDirUnder(vendorConfigHome("copilot")),createTurnDetector:()=>new UnknownTurnDetector("copilot"),trustWorktree:trustCopilotWorktree,screenManifest:COPILOT_SCREEN_MANIFEST},kimi:{vendor:"kimi",builtin:!0,displayName:"Kimi",defaultCommand:["kimi"],firstMessageDelivery:"paste",processNames:["kimi-co"],modelArgv:(base,model)=>[...base,"--model",model],trustWorktree:trustKimiWorktree,history:kimiHistoryReader,detectAccount:(deps)=>detectKimiAccount(deps),createHookAdapter:()=>new KimiHookAdapter,skillsDir:()=>existsSync5(vendorConfigHome("kimi"))?join4(homedir6(),".agents","skills"):null,createTurnDetector:()=>new UnknownTurnDetector("kimi"),sessionIdentity:{sessionControlFlags:["-S","--session","-c","--continue"],resumeArgv:(base,id)=>[...base,"-S",id]},screenManifest:KIMI_SCREEN_MANIFEST},pi:{vendor:"pi",builtin:!0,displayName:piIdentity.shortName,defaultCommand:["pi"],effortLevels:["off","minimal","low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"--thinking",level],listModels:listPiModels,modelArgv:(base,model)=>[...base,"--model",model],history:piHistoryReader,createHookAdapter:()=>new PiFamilyHookAdapter("pi"),skillsDir:()=>skillsDirUnder(vendorAgentDir("pi")),createTurnDetector:()=>new UnknownTurnDetector("pi"),capabilities:piCapabilities,identity:piIdentity,trustWorktree:trustPiWorktree,terminalTitle:{ownsStatus:!1,statusPrefixes:PI_STATUS_PREFIXES},sessionIdentity:{pinFlag:"--session-id",sessionControlFlags:["--session-id","--session","-c","--continue","-r","--resume","--fork"],resumeArgv:(base,id)=>[...base,"--session",id],forkArgv:(base,sourceId)=>[...base,"--fork",sourceId]},screenManifest:PI_SCREEN_MANIFEST},omp:{vendor:"omp",builtin:!0,displayName:ompIdentity.shortName,defaultCommand:["omp"],effortLevels:["off","minimal","low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"--thinking",level],listModels:listOmpModels,modelArgv:(base,model)=>[...base,`--model=${model}`],history:ompHistoryReader,createHookAdapter:()=>new PiFamilyHookAdapter("omp"),createTurnDetector:()=>new UnknownTurnDetector("omp"),capabilities:ompCapabilities,identity:ompIdentity,terminalTitle:{ownsStatus:!0,statusPrefixes:OMP_STATUS_PREFIXES,workingPrefixes:OMP_WORKING_PREFIXES,attentionPrefixes:OMP_ATTENTION_PREFIXES},sessionIdentity:{sessionControlFlags:["-c","--continue","-r","--resume"],resumeArgv:(base,id)=>[...base,"-r",id]},screenManifest:OMP_SCREEN_MANIFEST}};function stripStatusPrefix(title,prefixes){for(let prefix of[...prefixes].sort((a,b)=>b.length-a.length)){if(!title.startsWith(prefix))continue;let rest=title.slice(prefix.length).trimStart();if(rest.length===0)return title;return rest}return title}function titleTurnHint(config,title){let working=config?.workingPrefixes;if(config?.ownsStatus!==!0||!working||working.length===0)return null;let trimmed=title.trim();if(trimmed.length===0)return null;if(config.attentionPrefixes?.some((prefix)=>trimmed.startsWith(prefix)))return null;return working.some((prefix)=>trimmed.startsWith(prefix))?"working":"rest"}function titleSessionId(config,title){let trimmed=title.trim();if(!trimmed)return null;return config?.sessionIdFromTitle?.(trimmed)??null}function titleIsPlaceholder(config,title){return titleSessionId(config,title)!==null}function customEngineEntry(vendor){return{vendor,builtin:!1,displayName:vendor,defaultCommand:[vendor],history:EMPTY_HISTORY,createHookAdapter:()=>new NoopHookAdapter(vendor),createTurnDetector:()=>new UnknownTurnDetector(vendor)}}function engineEntry(vendor){if(isBuiltinVendor(vendor))return BUILTIN_ENGINES[vendor];let custom=customEngineEntry(vendor);return isContribEngine(vendor)?contribEngineEntry(vendor,custom):custom}function identifiableEngineIds(){return[...BUILTIN_VENDORS,...CONTRIB_ENGINE_IDS,...pluginEngineIds()]}function supportsStructuredHistory(vendor){return engineEntry(vendor).history.readHistory!==EMPTY_HISTORY.readHistory}var ALL_STATUS_PREFIXES=[...new Set(Object.values(BUILTIN_ENGINES).flatMap((entry)=>entry.terminalTitle?.statusPrefixes??[]))];function engineStatusPrefixes(vendor){let declared=engineEntry(vendor).terminalTitle?.statusPrefixes;return declared&&declared.length>0?declared:ALL_STATUS_PREFIXES}function stripEngineStatusPrefix(title,vendor){return stripStatusPrefix(title,vendor?engineStatusPrefixes(vendor):ALL_STATUS_PREFIXES)}function engineTitleTurnHint(vendor,title){return titleTurnHint(engineEntry(vendor).terminalTitle,title)}function engineSessionIdFromTitle(vendor,title){return titleSessionId(engineEntry(vendor).terminalTitle,title)}function isEnginePlaceholderTitle(title,vendor){return titleIsPlaceholder(engineEntry(vendor).terminalTitle,title)}function getCapabilities(vendor){return engineEntry(vendor).capabilities}function vendorsWithQuotaProbe(){return Object.values(BUILTIN_ENGINES).filter((entry)=>entry.quotaUsage).map((entry)=>entry.vendor)}function vendorsWithTurnReader(){return Object.values(BUILTIN_ENGINES).filter((entry)=>entry.readTurns).map((entry)=>entry.vendor)}function vendorsWithEffortLevels(){return Object.values(BUILTIN_ENGINES).filter((entry)=>(entry.effortLevels?.length??0)>0).map((entry)=>entry.vendor)}function createEngineHookAdapter(vendor){return engineEntry(vendor).createHookAdapter()}function activityHookAdapters(){return identifiableEngineIds().map((vendor)=>createEngineHookAdapter(vendor)).filter((adapter)=>adapter.supportsHooks())}class NoopHookAdapter{vendor;constructor(vendor){this.vendor=vendor}supportsHooks(){return!1}globalSettingsPath(){return""}activityDetailFromPayload(){return}sessionFromPayload(){return}async installActivityHooks(){return{ok:!0}}async removeActivityHooks(){}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}
167
+ `)){lineNo++;let record=parseJsonLine(line);if(!record||!isCodexCompletionRecord(record))continue;let timestampMs=timestampFromRecord(record,0),marker={id:`codex:${sourceId}:${timestampMs}:${lineNo}`,timestampMs,source:"codex"};if(!latest||marker.timestampMs>=latest.timestampMs)latest=marker}return latest}function parseJsonLine(line){if(!isJsonlLineWithinBound(line))return null;let trimmed=line.trim();if(!trimmed)return null;try{let parsed=JSON.parse(trimmed);return isObject(parsed)?parsed:null}catch{return null}}function timestampFromRecord(record,fallback){let ts=typeof record.timestamp==="string"?Date.parse(record.timestamp):Number.NaN;return Number.isFinite(ts)?ts:fallback}var BUILTIN_ENGINES={claude:{vendor:"claude",builtin:!0,displayName:claudeIdentity.shortName,defaultCommand:["claude"],listModels:async()=>CLAUDE_MODELS,modelArgv:(base,model)=>[...base,"--model",model],addDirArgv:(base,dirs)=>[...base,...dirs.map((dir)=>`--add-dir=${dir}`)],effortLevels:["low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"--effort",level],foreignModel:isOpenAiFamilyModel,history:claudeHistoryReader,detectAccount:(deps)=>detectClaudeAccount(deps),createHookAdapter:()=>new ClaudeHookAdapter,skillsDir:()=>isRovePluginEnabled()?null:skillsDirUnder(vendorConfigHome("claude")),createTurnDetector:()=>new ClaudeTurnDetector,capabilities:claudeCapabilities,identity:claudeIdentity,trustWorktree:trustClaudeWorktree,terminalTitle:{ownsStatus:!0,statusPrefixes:["\u2733","\u2802","\u2810","\u25D0","\u25D1"],workingPrefixes:["\u2802","\u2810","\u25D0","\u25D1"]},sessionIdentity:{pinFlag:"--session-id",sessionControlFlags:["--session-id","--resume","-r","--continue","-c","--from-pr"],resumeArgv:(base,id)=>[...base,"--resume",id],forkArgv:(base,sourceId,newId)=>{let forked=[...base,"--resume",sourceId,"--fork-session"];return newId?[...forked,"--session-id",newId]:forked}},quotaUsage:()=>fetchClaudeQuotaUsage(),readTurns:readClaudeTurns},codex:{vendor:"codex",builtin:!0,displayName:codexIdentity.shortName,defaultCommand:["codex"],effortLevels:["none","low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"-c",`model_reasoning_effort=${level}`],listModels:async()=>CODEX_MODELS,modelArgv:(base,model)=>[...base,"--model",model],addDirArgv:(base,dirs)=>[...base,...dirs.map((dir)=>`--add-dir=${dir}`)],hostedStartArgv:(argv)=>{for(let i=1;i<argv.length;i++){let arg=argv[i];if(arg==="--")break;let config=arg==="-c"||arg==="--config"?argv[++i]:arg.startsWith("--config=")?arg.slice(9):arg.startsWith("-c")?arg.slice(2).replace(/^=/,""):void 0;if(config&&/^\s*check_for_update_on_startup\s*=/.test(config))return argv}return[...argv,"-c","check_for_update_on_startup=false"]},foreignModel:isClaudeFamilyModel,errorLine:/^\s*\u25A0\s+\S/,history:codexHistoryReader,detectAccount:(deps)=>detectCodexAccount(deps),createHookAdapter:()=>new CodexHookAdapter,skillsDir:()=>skillsDirUnder(vendorConfigHome("codex")),createTurnDetector:()=>new CodexTurnDetector,capabilities:codexCapabilities,identity:codexIdentity,trustWorktree:trustCodexWorktree,readTurns:readCodexTurns,terminalTitle:{ownsStatus:!0,launchArgs:["-c",'tui.terminal_title=["activity","thread-title"]'],statusPrefixes:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],workingPrefixes:["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],sessionIdFromTitle:codexSessionIdFromTitle},sessionIdentity:{resumeArgv:(base,id)=>{let[bin,...rest]=base;return bin?[bin,"resume",...rest,id]:base},forkArgv:(base,sourceId)=>{let[bin,...rest]=base;return bin?[bin,"fork",...rest,sourceId]:null}},quotaUsage:()=>fetchCodexQuotaUsage()},bob:{vendor:"bob",builtin:!0,displayName:"IBM Bob",defaultCommand:["bob","chat","--trust"],firstMessageDelivery:"paste",history:bobHistoryReader,detectAccount:(deps)=>detectBobAccount(deps),trustWorktree:trustBobWorktree,createHookAdapter:()=>new NoopHookAdapter("bob"),skillsDir:()=>skillsDirUnder(bobHome()),createTurnDetector:()=>new UnknownTurnDetector("bob"),screenManifest:BOB_SCREEN_MANIFEST},copilot:{vendor:"copilot",builtin:!0,displayName:"Copilot",defaultCommand:["copilot"],history:copilotHistoryReader,detectAccount:(deps)=>detectCopilotAccount(deps),createHookAdapter:()=>new CopilotHookAdapter,skillsDir:()=>skillsDirUnder(vendorConfigHome("copilot")),createTurnDetector:()=>new UnknownTurnDetector("copilot"),trustWorktree:trustCopilotWorktree,screenManifest:COPILOT_SCREEN_MANIFEST},kimi:{vendor:"kimi",builtin:!0,displayName:"Kimi",defaultCommand:["kimi"],firstMessageDelivery:"paste",processNames:["kimi-co"],modelArgv:(base,model)=>[...base,"--model",model],trustWorktree:trustKimiWorktree,history:kimiHistoryReader,detectAccount:(deps)=>detectKimiAccount(deps),createHookAdapter:()=>new KimiHookAdapter,skillsDir:()=>existsSync5(vendorConfigHome("kimi"))?join5(homedir6(),".agents","skills"):null,createTurnDetector:()=>new UnknownTurnDetector("kimi"),sessionIdentity:{sessionControlFlags:["-S","--session","-c","--continue"],resumeArgv:(base,id)=>[...base,"-S",id]},screenManifest:KIMI_SCREEN_MANIFEST},pi:{vendor:"pi",builtin:!0,displayName:piIdentity.shortName,defaultCommand:["pi"],effortLevels:["off","minimal","low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"--thinking",level],listModels:listPiModels,modelArgv:(base,model)=>[...base,"--model",model],history:piHistoryReader,createHookAdapter:()=>new PiFamilyHookAdapter("pi"),skillsDir:()=>skillsDirUnder(vendorAgentDir("pi")),createTurnDetector:()=>new UnknownTurnDetector("pi"),capabilities:piCapabilities,identity:piIdentity,trustWorktree:trustPiWorktree,terminalTitle:{ownsStatus:!1,statusPrefixes:PI_STATUS_PREFIXES},sessionIdentity:{pinFlag:"--session-id",sessionControlFlags:["--session-id","--session","-c","--continue","-r","--resume","--fork"],resumeArgv:(base,id)=>[...base,"--session",id],forkArgv:(base,sourceId)=>[...base,"--fork",sourceId]},screenManifest:PI_SCREEN_MANIFEST},omp:{vendor:"omp",builtin:!0,displayName:ompIdentity.shortName,defaultCommand:["omp"],effortLevels:["off","minimal","low","medium","high","xhigh","max"],effortArgv:(base,level)=>[...base,"--thinking",level],listModels:listOmpModels,modelArgv:(base,model)=>[...base,`--model=${model}`],history:ompHistoryReader,createHookAdapter:()=>new PiFamilyHookAdapter("omp"),createTurnDetector:()=>new UnknownTurnDetector("omp"),capabilities:ompCapabilities,identity:ompIdentity,terminalTitle:{ownsStatus:!0,statusPrefixes:OMP_STATUS_PREFIXES,workingPrefixes:OMP_WORKING_PREFIXES,attentionPrefixes:OMP_ATTENTION_PREFIXES},sessionIdentity:{sessionControlFlags:["-c","--continue","-r","--resume"],resumeArgv:(base,id)=>[...base,"-r",id]},screenManifest:OMP_SCREEN_MANIFEST}};function stripStatusPrefix(title,prefixes){for(let prefix of[...prefixes].sort((a,b)=>b.length-a.length)){if(!title.startsWith(prefix))continue;let rest=title.slice(prefix.length).trimStart();if(rest.length===0)return title;return rest}return title}function titleTurnHint(config,title){let working=config?.workingPrefixes;if(config?.ownsStatus!==!0||!working||working.length===0)return null;let trimmed=title.trim();if(trimmed.length===0)return null;if(config.attentionPrefixes?.some((prefix)=>trimmed.startsWith(prefix)))return null;return working.some((prefix)=>trimmed.startsWith(prefix))?"working":"rest"}function titleSessionId(config,title){let trimmed=title.trim();if(!trimmed)return null;return config?.sessionIdFromTitle?.(trimmed)??null}function titleIsPlaceholder(config,title){return titleSessionId(config,title)!==null}function customEngineEntry(vendor){return{vendor,builtin:!1,displayName:vendor,defaultCommand:[vendor],history:EMPTY_HISTORY,createHookAdapter:()=>new NoopHookAdapter(vendor),createTurnDetector:()=>new UnknownTurnDetector(vendor)}}function engineEntry(vendor){if(isBuiltinVendor(vendor))return BUILTIN_ENGINES[vendor];let custom=customEngineEntry(vendor);return isContribEngine(vendor)?contribEngineEntry(vendor,custom):custom}function identifiableEngineIds(){return[...BUILTIN_VENDORS,...CONTRIB_ENGINE_IDS,...pluginEngineIds()]}function supportsStructuredHistory(vendor){return engineEntry(vendor).history.readHistory!==EMPTY_HISTORY.readHistory}var ALL_STATUS_PREFIXES=[...new Set(Object.values(BUILTIN_ENGINES).flatMap((entry)=>entry.terminalTitle?.statusPrefixes??[]))];function engineStatusPrefixes(vendor){let declared=engineEntry(vendor).terminalTitle?.statusPrefixes;return declared&&declared.length>0?declared:ALL_STATUS_PREFIXES}function stripEngineStatusPrefix(title,vendor){return stripStatusPrefix(title,vendor?engineStatusPrefixes(vendor):ALL_STATUS_PREFIXES)}function engineTitleTurnHint(vendor,title){return titleTurnHint(engineEntry(vendor).terminalTitle,title)}function engineSessionIdFromTitle(vendor,title){return titleSessionId(engineEntry(vendor).terminalTitle,title)}function isEnginePlaceholderTitle(title,vendor){return titleIsPlaceholder(engineEntry(vendor).terminalTitle,title)}function getCapabilities(vendor){return engineEntry(vendor).capabilities}function vendorsWithQuotaProbe(){return Object.values(BUILTIN_ENGINES).filter((entry)=>entry.quotaUsage).map((entry)=>entry.vendor)}function vendorsWithTurnReader(){return Object.values(BUILTIN_ENGINES).filter((entry)=>entry.readTurns).map((entry)=>entry.vendor)}function vendorsWithEffortLevels(){return Object.values(BUILTIN_ENGINES).filter((entry)=>(entry.effortLevels?.length??0)>0).map((entry)=>entry.vendor)}function createEngineHookAdapter(vendor){return engineEntry(vendor).createHookAdapter()}function activityHookAdapters(){return identifiableEngineIds().map((vendor)=>createEngineHookAdapter(vendor)).filter((adapter)=>adapter.supportsHooks())}class NoopHookAdapter{vendor;constructor(vendor){this.vendor=vendor}supportsHooks(){return!1}globalSettingsPath(){return""}activityDetailFromPayload(){return}sessionFromPayload(){return}async installActivityHooks(){return{ok:!0}}async removeActivityHooks(){}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}
168
168
  export{realPathOrSelf,createEngineHookAdapter,activityHookAdapters,NoopHookAdapter,createEngineTurnDetector,engineEntry,identifiableEngineIds,supportsStructuredHistory,engineStatusPrefixes,stripEngineStatusPrefix,engineTitleTurnHint,engineSessionIdFromTitle,isEnginePlaceholderTitle,getCapabilities,vendorsWithQuotaProbe,vendorsWithTurnReader,vendorsWithEffortLevels};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{CATALOGS,DEFAULT_LOCALE,LOCALES}from"./chunk-9vwb9f7q.js";import{createStateCell}from"./chunk-cmp64q4j.js";function lookup(catalog,key){let node=catalog;for(let part of key.split("."))if(node&&typeof node==="object"&&part in node)node=node[part];else return;return typeof node==="string"?node:void 0}function interpolate(template,params){if(!params)return template;return template.replace(/\{(\w+)\}/g,(whole,name)=>(name in params)?String(params[name]):whole)}function lookupKeys(catalog,group,key){return catalog.keys[group]?.[key]}var langState=createStateCell(DEFAULT_LOCALE);function setLocaleLang(lang){if(CATALOGS[lang])langState.set(lang)}function currentLang(){return langState.get()}function intlLocale(){return LOCALES.find((locale)=>locale.id===langState.get())?.intl??"en-US"}function localeState(){return langState}var pluginNamespaces=new Set;function registerMessages(namespace,messages){let en=CATALOGS.en,zh=CATALOGS.zh;if(namespace in en&&!pluginNamespaces.has(namespace))throw Error(`i18n namespace "${namespace}" belongs to the host`);if(pluginNamespaces.add(namespace),en[namespace]=messages.en,messages.zh)zh[namespace]=messages.zh;else delete zh[namespace]}function t(key,params){let lang=langState.get(),resolved=lookup(CATALOGS[lang],key)??lookup(CATALOGS.en,key)??key;return interpolate(resolved,params)}function tKeys(group,key){let lang=langState.get();return lookupKeys(CATALOGS[lang],group,key)??lookupKeys(CATALOGS.en,group,key)??key}
2
+ import{CATALOGS,DEFAULT_LOCALE,LOCALES}from"./chunk-zj7m55h0.js";import{createStateCell}from"./chunk-cmp64q4j.js";function lookup(catalog,key){let node=catalog;for(let part of key.split("."))if(node&&typeof node==="object"&&part in node)node=node[part];else return;return typeof node==="string"?node:void 0}function interpolate(template,params){if(!params)return template;return template.replace(/\{(\w+)\}/g,(whole,name)=>(name in params)?String(params[name]):whole)}function lookupKeys(catalog,group,key){return catalog.keys[group]?.[key]}var langState=createStateCell(DEFAULT_LOCALE);function setLocaleLang(lang){if(CATALOGS[lang])langState.set(lang)}function currentLang(){return langState.get()}function intlLocale(){return LOCALES.find((locale)=>locale.id===langState.get())?.intl??"en-US"}function localeState(){return langState}var pluginNamespaces=new Set;function registerMessages(namespace,messages){let en=CATALOGS.en,zh=CATALOGS.zh;if(namespace in en&&!pluginNamespaces.has(namespace))throw Error(`i18n namespace "${namespace}" belongs to the host`);if(pluginNamespaces.add(namespace),en[namespace]=messages.en,messages.zh)zh[namespace]=messages.zh;else delete zh[namespace]}function t(key,params){let lang=langState.get(),resolved=lookup(CATALOGS[lang],key)??lookup(CATALOGS.en,key)??key;return interpolate(resolved,params)}function tKeys(group,key){let lang=langState.get();return lookupKeys(CATALOGS[lang],group,key)??lookupKeys(CATALOGS.en,group,key)??key}
3
3
  export{setLocaleLang,currentLang,intlLocale,localeState,registerMessages,t,tKeys};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-cs410j8b.js";import"./chunk-btxfcc77.js";import"./chunk-tgv90744.js";import"./chunk-kdnk8m5j.js";import"./chunk-qcjkactr.js";import"./chunk-rjfdzjhj.js";import"./chunk-zpxpwgds.js";import"./chunk-agvtzads.js";import"./chunk-pm91e38v.js";import"./chunk-2xsxcdp6.js";import"./chunk-17e2tgyg.js";import"./chunk-1vxtd8rh.js";import"./chunk-q8ffd1pc.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-n0rdn2fn.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-01tghgf3.js";import"./chunk-y07cp9mb.js";import"./chunk-vytrhm50.js";import"./chunk-vp29jgbt.js";import"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import"./chunk-qkehg2c1.js";import"./chunk-w6ft4djp.js";import"./chunk-vx44yxra.js";import"./chunk-z43e08kw.js";import"./chunk-w77s2df8.js";import"./chunk-mqfvzdpr.js";import"./chunk-gzkes5bw.js";import"./chunk-rxqdw6s5.js";import"./chunk-8ng1756g.js";import"./chunk-kxp04jnp.js";import"./chunk-1a57ejnh.js";import"./chunk-qecygh3f.js";import"./chunk-rjq38twt.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-g9ba25q5.js";import"./chunk-ggnq2vvk.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-mdc7b01e.js";import"./chunk-tn9gtf18.js";import"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-e58kj4gm.js";import"./chunk-0a65j1zj.js";import"./chunk-bcyex84w.js";import"./chunk-5rgrde6b.js";import"./chunk-4gjvmfa9.js";import"./chunk-2tfnscxk.js";import"./chunk-hzz020xx.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-9rj2fx6v.js";import"./chunk-rfp0ayra.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-40dgv828.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-yn01fet6.js";import"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-a5xbsvx2.js";import"./chunk-9vwb9f7q.js";import"./chunk-cmp64q4j.js";import"./chunk-qzzmd63x.js";import"./chunk-96kvwzj8.js";import"./chunk-7bakcyes.js";import"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams};
2
+ import{argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-fjsmqvaq.js";import"./chunk-syfddt6h.js";import"./chunk-t1ye845a.js";import"./chunk-m2aqz600.js";import"./chunk-1gxnd3qq.js";import"./chunk-q89yrevw.js";import"./chunk-eyaaaprw.js";import"./chunk-cacct9gd.js";import"./chunk-pm91e38v.js";import"./chunk-2xsxcdp6.js";import"./chunk-17e2tgyg.js";import"./chunk-ee8917py.js";import"./chunk-q8ffd1pc.js";import"./chunk-4hestsjp.js";import"./chunk-qgrg9a5n.js";import"./chunk-2bgmby1d.js";import"./chunk-0sy3bez6.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-6pb0cs94.js";import"./chunk-6mm1672p.js";import"./chunk-pmwk2etg.js";import"./chunk-vp29jgbt.js";import"./chunk-gq36nzg8.js";import"./chunk-sq6zj3fb.js";import"./chunk-qkehg2c1.js";import"./chunk-va59neh9.js";import"./chunk-sc72402g.js";import"./chunk-gfdd2jbp.js";import"./chunk-w77s2df8.js";import"./chunk-mqfvzdpr.js";import"./chunk-w94ykg0q.js";import"./chunk-rxqdw6s5.js";import"./chunk-8ng1756g.js";import"./chunk-kxp04jnp.js";import"./chunk-fyhrnwsh.js";import"./chunk-ypfrkpe9.js";import"./chunk-0m8javx8.js";import"./chunk-r5j8fycq.js";import"./chunk-xfgqae9t.js";import"./chunk-j1z9kgyd.js";import"./chunk-g9ba25q5.js";import"./chunk-paashxkd.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-mdc7b01e.js";import"./chunk-tn9gtf18.js";import"./chunk-22emnsn5.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-5mhf43dx.js";import"./chunk-ar3mt81z.js";import"./chunk-s7ttzm9a.js";import"./chunk-jnt3nf6w.js";import"./chunk-hgtf6yvg.js";import"./chunk-2tfnscxk.js";import"./chunk-betn5ma1.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-8ttn73cv.js";import"./chunk-gygdyf0s.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-40dgv828.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-69kd26wk.js";import"./chunk-zsfyj36g.js";import"./chunk-2r1fgng9.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-j8eejjw0.js";import"./chunk-zj7m55h0.js";import"./chunk-cmp64q4j.js";import"./chunk-8y10pmkf.js";import"./chunk-96kvwzj8.js";import"./chunk-7bakcyes.js";import"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{smallIgnoredPaths}from"./chunk-xmwp6je4.js";import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-1vxtd8rh.js";import{readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-895yqjjz.js";import{getRemoteRepoConfig}from"./chunk-rfp0ayra.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import path4 from"path";function parseDirtyPaths(stdout){return parsePorcelainRows(stdout).filter((row)=>(row.x+row.y).trim().length>0).map((row)=>row.path).filter((p)=>p.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var METER_RE=/(\d{1,3})% \(\d+\/\d+\)/g;function checkoutProgressReader(onPercent){let tail="",last=-1;return(chunk)=>{let text=tail+chunk,end=Math.max(text.lastIndexOf("\r"),text.lastIndexOf(`
2
+ import{DIRTY_WORKTREE_CODE,canonicalize,describeDirtyWorktreeWork,isRoveManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-ee8917py.js";import{readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{execHostForRepo,execHostForWorktreePath}from"./chunk-22emnsn5.js";import{getRemoteRepoConfig}from"./chunk-gygdyf0s.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{smallIgnoredPaths}from"./chunk-xmwp6je4.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import path4 from"path";function parseDirtyPaths(stdout){return parsePorcelainRows(stdout).filter((row)=>(row.x+row.y).trim().length>0).map((row)=>row.path).filter((p)=>p.length>0)}function isDirtyOutput(stdout){return parseDirtyPaths(stdout).length>0}var METER_RE=/(\d{1,3})% \(\d+\/\d+\)/g;function checkoutProgressReader(onPercent){let tail="",last=-1;return(chunk)=>{let text=tail+chunk,end=Math.max(text.lastIndexOf("\r"),text.lastIndexOf(`
3
3
  `));if(end<0){tail=text;return}tail=text.slice(end+1);let percent=-1;for(let match of text.slice(0,end).matchAll(METER_RE))percent=Number(match[1]);if(percent<0||percent>100||percent===last)return;last=percent,onPercent(percent)}}class CheckpointError extends Error{code;constructor(code,reason){super(`${code}: ${reason}`);this.code=code;this.name="CheckpointError"}}function checkpointRef(taskId,n){return`refs/rove/checkpoints/${taskId}/${n}`}var FALLBACK_IDENTITY={GIT_AUTHOR_NAME:"Rove",GIT_AUTHOR_EMAIL:"rove@localhost",GIT_COMMITTER_NAME:"Rove",GIT_COMMITTER_EMAIL:"rove@localhost"};function parseSubject(subject){let parts=subject.trim().split(/\s+/).slice(3),at=parts.pop()??"";return parts[0]?{at,tabId:parts[0]}:{at}}async function listCheckpoints(deps,exec,cwd,taskId){let prefix=`refs/rove/checkpoints/${taskId}/`,out=await deps.runGit(exec,["for-each-ref","--format=%(refname)%09%(objectname)%09%(tree)%09%(subject)",prefix],{cwd,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return[];let records=[];for(let line of out.stdout.split(`
4
4
  `)){let[ref,commit,tree,subject=""]=line.split("\t"),n=Number(ref?.slice(prefix.length));if(!ref||!commit||!tree||!Number.isInteger(n))continue;records.push({n,ref,commit,tree,...parseSubject(subject)})}return records.sort((a,b)=>a.n-b.n)}async function gitlinkPaths(exec,deps,cwd,tree){let out=await deps.runGit(exec,["ls-tree","-r",tree],{cwd,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return[];return out.stdout.split(`
5
5
  `).filter((line)=>line.startsWith("160000 ")).map((line)=>line.slice(line.indexOf("\t")+1)).filter((p)=>p.length>0)}async function withTempIndex(deps,exec,cwd,body){let name=`rove-ckpt-index-${process.pid}-${Math.random().toString(36).slice(2,8)}`,indexPath=(await deps.runGit(exec,["rev-parse","--git-path",name],{cwd,allowFail:!0,readOnly:!0})).stdout.trim();if(!indexPath)throw new CheckpointError("CHECKPOINT_FAILED",`${cwd} is not a git work tree`);try{return await body((args,extraEnv)=>deps.runGit(exec,args,{cwd,allowFail:!0,env:{GIT_INDEX_FILE:indexPath,...extraEnv}}),indexPath)}finally{await exec.run(["rm","-f",indexPath],{cwd}).catch(()=>{return})}}async function snapshotTree(deps,exec,cwd,head){let tree=await withTempIndex(deps,exec,cwd,async(gitIdx,indexPath)=>{let real=(await deps.runGit(exec,["rev-parse","--git-path","index"],{cwd,allowFail:!0,readOnly:!0})).stdout.trim();if(!(real!==""&&(await exec.run(["cp","-p",real,indexPath],{cwd}).catch(()=>{return}))?.exitCode===0)&&head&&(await gitIdx(["read-tree",head])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","read-tree failed");if((await gitIdx(["add","-A"])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","git add -A failed");let written=(await gitIdx(["write-tree"])).stdout.trim();if(!written)throw new CheckpointError("CHECKPOINT_FAILED","write-tree failed");return written});return{tree,uncaptured:await gitlinkPaths(exec,deps,cwd,tree)}}async function headCommit(deps,exec,cwd){let out=await deps.runGit(exec,["rev-parse","--verify","-q","HEAD"],{cwd,allowFail:!0,readOnly:!0});return out.exitCode===0?out.stdout.trim():""}async function takeCheckpoint(deps,exec,worktreePath,taskId,opts={}){let head=await headCommit(deps,exec,worktreePath),{tree,uncaptured}=await snapshotTree(deps,exec,worktreePath,head),existing=await listCheckpoints(deps,exec,worktreePath,taskId),latest=existing[existing.length-1];if(latest&&latest.tree===tree)return{created:!1,checkpoint:latest};let at=(opts.now??new Date).toISOString(),hasIdentity=(await deps.runGit(exec,["var","GIT_COMMITTER_IDENT"],{cwd:worktreePath,allowFail:!0,readOnly:!0})).exitCode===0;for(let n=(latest?.n??0)+1,attempt=0;attempt<5;n++,attempt++){let message=["rove checkpoint",n,opts.tabId,at].filter((p)=>p!==void 0&&p!=="").join(" "),commitArgs=head?["commit-tree",tree,"-p",head,"-m",message]:["commit-tree",tree,"-m",message],commit=await deps.runGit(exec,commitArgs,{cwd:worktreePath,allowFail:!0,...hasIdentity?{}:{env:FALLBACK_IDENTITY}}),sha=commit.stdout.trim();if(commit.exitCode!==0||!sha)throw new CheckpointError("CHECKPOINT_FAILED",`commit-tree failed: ${commit.stderr.trim()}`);let ref=checkpointRef(taskId,n);if((await deps.runGit(exec,["update-ref",ref,sha,""],{cwd:worktreePath,allowFail:!0})).exitCode===0)return await pruneCheckpoints(deps,exec,worktreePath,taskId).catch(()=>{return}),{created:!0,checkpoint:{n,ref,commit:sha,tree,at,...opts.tabId?{tabId:opts.tabId}:{}},uncaptured}}throw new CheckpointError("CHECKPOINT_FAILED",`could not allocate a checkpoint number for ${taskId}`)}async function deleteRefs(deps,exec,cwd,refs){for(let ref of refs)await deps.runGit(exec,["update-ref","-d",ref],{cwd,allowFail:!0})}async function pruneCheckpoints(deps,exec,cwd,taskId,keep=100){let all=await listCheckpoints(deps,exec,cwd,taskId),doomed=all.slice(0,Math.max(0,all.length-keep));return await deleteRefs(deps,exec,cwd,doomed.map((c)=>c.ref)),doomed.length}async function deleteTaskCheckpoints(deps,exec,cwd,taskId){let all=await listCheckpoints(deps,exec,cwd,taskId);return await deleteRefs(deps,exec,cwd,all.map((c)=>c.ref)),all.length}async function moveTaskCheckpoints(deps,exec,cwd,fromId,toId){let moved=0;for(let c of await listCheckpoints(deps,exec,cwd,fromId)){if((await deps.runGit(exec,["update-ref",checkpointRef(toId,c.n),c.commit,""],{cwd,allowFail:!0})).exitCode!==0)continue;await deleteRefs(deps,exec,cwd,[c.ref]),moved++}return moved}async function rewindTo(deps,exec,worktreePath,taskId,n,opts={}){let target=(await listCheckpoints(deps,exec,worktreePath,taskId)).find((c)=>c.n===n);if(!target)throw new CheckpointError("CHECKPOINT_NOT_FOUND",`task ${taskId} has no checkpoint ${n}`);let taken=await takeCheckpoint(deps,exec,worktreePath,taskId,{now:opts.now}),undo=taken.checkpoint,uncaptured=taken.created?taken.uncaptured:[];await withTempIndex(deps,exec,worktreePath,async(gitIdx)=>{if((await gitIdx(["read-tree",undo.tree])).exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED","read-tree (current) failed");let res=await gitIdx(["read-tree","--reset","-u",target.tree]);if(res.exitCode!==0)throw new CheckpointError("CHECKPOINT_FAILED",`read-tree failed: ${res.stderr.trim()}`)});let head=await headCommit(deps,exec,worktreePath);return await deps.runGit(exec,head?["reset","-q"]:["read-tree","--empty"],{cwd:worktreePath,allowFail:!0}),{target,undo,uncaptured}}import fs from"fs/promises";import path from"path";var WORKTREE_CLONE_IGNORED_KEY="worktree.cloneIgnored",DEFAULT_CLONE_DIRS=["node_modules",".venv","target",".build"];function isCloneIgnoredEnabled(){return loadStateFile()[WORKTREE_CLONE_IGNORED_KEY]!==!1}function parseCloneDirs(text){return text.split(/\r?\n/).map((line)=>line.replace(/#.*$/,"").trim()).filter((e)=>e.length>0&&e!=="."&&e!==".."&&!/[/\\]/.test(e)&&!e.startsWith("-"))}function resolveCloneDirs(worktreePath){let file=readFirstNonEmptyRepoFile(worktreePath,"clone-dirs");return file===void 0?DEFAULT_CLONE_DIRS:parseCloneDirs(file)}var CLONEFILEAT_PERL='my $r = syscall(462, -2, $ARGV[0], -2, $ARGV[1], 0); if ($r != 0) { print STDERR "clonefileat: $!\\n"; exit 1 }';function defaultCloneDeps(exec){return{platform:process.platform,statDev:async(p)=>(await fs.stat(p)).dev,isApfs:async(p)=>{let r=await exec.run(["/bin/df","-T","apfs",p]);return r.exitCode===0&&r.stdout.trim().split(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{canonPath,normalizeMainRepo,randomDirTaskSuffix,repoWorkingDir,samePrStatus,titleFromRepo}from"./chunk-zr058kbe.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-c1dz3qg3.js";import{CLONEFILEAT_PERL,GitWorktreeManager,defaultExecDeps,git,isDirtyOutput,parseDirtyPaths}from"./chunk-3x5g06mw.js";import{LAUNCH_PREFIX_FILE}from"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-2xsxcdp6.js";import{CannotDeleteMainTaskError,DirtyWorktreeError,EmptyBranchDirtyWorktreeError,EmptyBranchError,ExtraRepoNotGitError,ForkUnsupportedError,GitCommandFailedError,IllegalTransitionError,InvalidWorktreeNameError,LandConflictError,MainCheckoutDirtyError,MissingRefError,MoveRefusedError,NotAGitRepoError,NotALinkedRepoError,REMOTE_PARENT_UNSUPPORTED_CODE,RemoteExtraUnsupportedError,RemoteParentUnsupportedError,ReparentRefusedError,RepoDuplicateError,TaskDeletingError,TaskNotFoundError,TooManyReposError,WorktreeNameTakenError,WorktreeRemoveFailedError,canonicalize,listWorktreeDirNames,worktreePathFor}from"./chunk-1vxtd8rh.js";import{detectLanguage}from"./chunk-hpay0ax8.js";import{resolvePreferredVendor}from"./chunk-9rj2fx6v.js";import{addSavedRepo,getPersistedString,getSavedRepos,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot}from"./chunk-rfp0ayra.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{projectRejection,rejectionReason}from"./chunk-7mwvvj46.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{MULTI_REPO_CAP,SESSION_PR_CAP,WORKSPACE_CAPABILITIES,applyTodoOps,checkNotes,childrenOf,gitRepoOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName,workspaceBackendId,workspaceCapabilities}from"./chunk-x1jxxmtc.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{pathIdentity,pathWithin,samePath}from"./chunk-pn5ygqn6.js";class WorkspaceCheckpoints{store;worktrees;workspaces;requireTask;constructor(store,worktrees,workspaces,requireTask){this.store=store;this.worktrees=worktrees;this.workspaces=workspaces;this.requireTask=requireTask}workspaceOwner(id){let task=this.requireTask(id);return(task.sharesWorkspaceOf?this.store.get(task.sharesWorkspaceOf):void 0)??task}checkpointScope(id){let owner=this.workspaceOwner(id),sharers=this.store.list().filter((t)=>t.sharesWorkspaceOf===owner.id&&!t.deletion);return{ownerId:String(owner.id),sharerIds:[String(owner.id),...sharers.map((t)=>String(t.id))]}}canCheckpoint(id){if(!this.store.get(id))return!1;let owner=this.workspaceOwner(id);return workspaceCapabilities(owner).checkpoint&&!owner.deletion&&owner.worktreePath!==""}async target(id){let owner=this.workspaceOwner(id),own=this.canCheckpoint(id)?this.workspaces.get(workspaceBackendId(owner)).checkpoints:void 0,dir=owner.worktreePath;if(!this.canCheckpoint(id)||!await this.worktrees.pathExists(own?dir:`${dir}/.git`))throw Error(`NOT_CHECKPOINTABLE: ${owner.kind==="task"?"the task has no workspace on disk":`a ${owner.kind} task works in your own checkout`}`);let ownerId=String(owner.id);return{ownerId,dir,via:own??{take:(d,opts)=>this.worktrees.takeCheckpoint(d,ownerId,opts),list:(d)=>this.worktrees.listCheckpoints(d,ownerId),rewind:(d,n)=>this.worktrees.rewindToCheckpoint(d,ownerId,n)}}}async takeCheckpoint(id,opts){let{dir,via}=await this.target(id);return via.take(dir,opts)}async listCheckpoints(id){let{dir,via}=await this.target(id);return via.list(dir)}async rewindToCheckpoint(id,n){let{dir,via}=await this.target(id);return via.rewind(dir,n)}async exportBranch(id){let owner=this.workspaceOwner(id),backend=this.workspaces.get(workspaceBackendId(owner));if(!backend.exportBranch||!owner.worktreePath)throw Error("EXPORT_UNSUPPORTED: the task's branch is already in its repo (or it has no workspace yet)");return backend.exportBranch({path:owner.worktreePath,repo:gitRepoOf(owner),branch:owner.branch})}}var TYPE_PREFIXES=new Set(["feat","feature","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","build","perf","style","revert","release"]),BRAND_TOKENS=new Set(["rove"]);function inferBranchStyle(names){let typed=new Map,bare=0;for(let raw of new Set(names)){let name=raw.trim();if(!name||name==="HEAD")continue;let slash=name.indexOf("/");if(slash===-1){bare+=1;continue}let prefix=name.slice(0,slash);if(TYPE_PREFIXES.has(prefix))typed.set(prefix,(typed.get(prefix)??0)+1)}let typedTotal=0;for(let n of typed.values())typedTotal+=n;if(typedTotal===0||typedTotal<bare)return{kind:"bare"};let best="",bestN=0;for(let[prefix,n]of typed)if(n>bestN||n===bestN&&(best===""||prefix<best))best=prefix,bestN=n;return{kind:"typed",defaultPrefix:best}}function slugTokens(title){return title.toLowerCase().replace(/[^a-z0-9]+/g,"-").split("-").filter((t)=>t.length>0&&!BRAND_TOKENS.has(t))}function capSlug(tokens){let slug="";for(let token of tokens){let candidate=slug?`${slug}-${token}`:token;if(candidate.length>32)return slug||token.slice(0,32);slug=candidate}return slug}function identitySlug(taskId){return`task-${taskId.slice(-6).toLowerCase()}`}function deriveConventionBranch(title,style,taskId){let tokens=slugTokens(title);if(style.kind==="typed"){let first=tokens[0];return`${first!==void 0&&TYPE_PREFIXES.has(first)?tokens.shift():style.defaultPrefix}/${capSlug(tokens)||identitySlug(taskId)}`}return capSlug(tokens)||identitySlug(taskId)}function uniqueBranchName(base,taken,taskId){let dirs=new Set;for(let name of taken)for(let i=name.indexOf("/");i>0;i=name.indexOf("/",i+1))dirs.add(name.slice(0,i));let isFree=(name)=>!taken.has(name)&&!dirs.has(name),segments=base.split("/"),root=segments.slice(0,-1).some((_,i)=>taken.has(segments.slice(0,i+1).join("/")))?segments.join("-"):base;if(isFree(root))return root;for(let n=2;n<=99;n+=1){let candidate=`${root}-${n}`;if(isFree(candidate))return candidate}return`${root}-${taskId.slice(-6).toLowerCase()}`}function planExtraRepos(primary,inputs){if(inputs.length===0)return[];if(1+inputs.length>MULTI_REPO_CAP)throw new TooManyReposError(1+inputs.length,MULTI_REPO_CAP);if(isRemoteRepoKey(primary))throw new RemoteExtraUnsupportedError(primary);let seen=new Set([canonPath(primary)]),names=new Set([repoNameOf(primary)]);return inputs.map((input)=>{if(isRemoteRepoKey(input.repo))throw new RemoteExtraUnsupportedError(input.repo);let{repo}=normalizeMainRepo(input.repo);if(!isGitRepo(repo))throw new ExtraRepoNotGitError(input.repo);if(seen.has(canonPath(repo)))throw new RepoDuplicateError(repo);seen.add(canonPath(repo));let name=uniqueRepoName(repoNameOf(repo),names);names.add(name);let baseRef=input.baseRef?.trim();return{name,repo,branch:"",worktreePath:"",...baseRef?{baseRef}:{}}})}async function rollbackWorktree(backend,created){try{await backend.dispose({path:created.path,...created.fresh},created.fresh?{force:!0,deleteBranch:!0}:{force:!0})}catch(err){console.error(`[rove] ensureWorktree rollback failed for ${created.path}:`,err)}}async function extrasToMaterialise(worktrees,extras){let missing=[];for(let extra of extras??[])if(!extra.worktreePath||!await worktrees.pathExists(extra.worktreePath))missing.push(extra);return missing}function scaleProgress(onProgress,step,total){return onProgress&&((percent)=>onProgress(Math.floor((step+percent/100)/total*100)))}async function materialiseExtras(opts){let{worktrees,backend,slugs,task}=opts,callerNamed=task.branch!=="",created=[],picked=[],done=new Map,missing=await extrasToMaterialise(worktrees,task.extraRepos);try{for(let[index,extra]of missing.entries()){if(extra.worktreePath)await worktrees.pruneWorktrees(extra.repo);let names=await worktrees.listBranchNames(extra.repo),branch=extra.branch||(callerNamed||!names.includes(opts.branch)?opts.branch:uniqueBranchName(opts.branch,new Set(names),task.id)),slug=await slugs.allocate(extra.repo);picked.push({repo:extra.repo,slug});let info=await backend.materialize({repo:extra.repo,slug,branch,baseRef:extra.baseRef,onProgress:opts.progressFor(index)});created.push({path:info.path,...names.includes(branch)?{}:{fresh:{repo:extra.repo,branch}}}),done.set(extra.name,{...extra,branch,worktreePath:info.path})}}catch(err){for(let wt of created.reverse())await rollbackWorktree(backend,wt);for(let{repo,slug}of picked)slugs.cancel(repo,slug);throw err}return{extraRepos:(task.extraRepos??[]).map((e)=>done.get(e.name)??e),created,slugs:picked}}function nestingParent(store,id){let parent=store.get(id);if(!parent)throw new TaskNotFoundError(id);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(isRemoteRepoKey(parent.repo))throw new RemoteParentUnsupportedError(String(parent.id));return toTaskId(lineageRootId(store.list(),parent.id))}async function createTaskRow(deps,input){if(!input.repo)throw Error("createTask: repo is required");let extraRepos=planExtraRepos(normalizeMainRepo(input.repo).repo,input.extraRepos??[]),parentTaskId=input.parentTaskId?nestingParent(deps.store,input.parentTaskId):void 0,repo=(await deps.mainTasks.ensureIfEligible(input.repo,input.projectIntent??"explicit"))?.repo??normalizeMainRepo(input.repo).repo,title=sanitizeTaskTitle(input.title??PLACEHOLDER_TASK_TITLE)||PLACEHOLDER_TASK_TITLE,worktreeName=input.worktreeName?.trim();if(worktreeName)await deps.claimWorktreeName(repo,worktreeName);return await deps.store.create({repo,title,branch:input.branch??"",worktreePath:"",status:"backlog",kind:"task",vendor:input.vendor??DEFAULT_TASK_VENDOR,...input.command?.trim()?{command:input.command.trim()}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},...input.tier?.trim()?{tier:input.tier.trim()}:{},...input.groupId?{groupId:input.groupId}:{},...input.dispatcher?{dispatcher:input.dispatcher}:{},...parentTaskId?{parentTaskId}:{},...input.cwdSubpath?{cwdSubpath:input.cwdSubpath}:{},...input.routine?{routine:input.routine}:{},...input.baseRef?.trim()?{baseRef:input.baseRef.trim()}:{},...extraRepos.length>0?{extraRepos}:{},...input.workspace?{workspace:input.workspace}:{},...worktreeName?{worktreeName}:{}})}async function openDirectoryTaskRow(deps,input){if(!input.dir)throw Error("openDirectoryTask: dir is required");let dir=canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:dir,status:"backlog",kind:"dir",...input.scratch?{scratch:!0}:{},...input.noProject?{noProject:!0}:{},...input.routine?{routine:input.routine}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},vendor:input.vendor??resolvePreferredVendor()})}async function adoptScratchRepoRow(deps,id,repo){let task=deps.store.get(id);if(!task||task.kind!=="dir"||task.scratch!==!0)return;let dir=canonPath(repo);await deps.store.update(id,{repo:dir,worktreePath:dir,scratch:!1,title:titleFromRepo(dir)})}class BorrowedBackend{id="borrowed";capabilities=WORKSPACE_CAPABILITIES.borrowed;async materialize(spec){return{backend:this.id,path:spec.path??repoWorkingDir(spec.repo)}}async dispose(){}}import{execFile}from"child_process";import{promises as fs,statSync}from"fs";import path from"path";import{promisify}from"util";var run=promisify(execFile),CP_CHUNK=200;function cloneFlags(){if(process.platform==="darwin")return["-c","-R","-P"];if(process.platform==="linux")return["--reflink=always","-a"];return null}var cpClone=async(entries,to)=>{let flags=cloneFlags();if(!flags)throw new ForkUnsupportedError(`copy-on-write clones are not supported on ${process.platform}`);for(let i=0;i<entries.length;i+=CP_CHUNK)try{await run("cp",[...flags,...entries.slice(i,i+CP_CHUNK),`${to}${path.sep}`])}catch(err){let detail=err.stderr?.trim()||String(err);throw Error(`cloning the worktree failed: ${detail}`)}},probeCache=new Map;async function cloneOneFile(source,target){if(process.platform==="darwin")await run("/usr/bin/perl",["-e",CLONEFILEAT_PERL,source,target]);else if(process.platform==="linux")await run("cp",["--reflink=always",source,target]);else throw Error(`no clone primitive on ${process.platform}`)}var volumeProbe=(from,toDir)=>{let key=`${statSync(from).dev}:${statSync(toDir).dev}`,known=probeCache.get(key);if(!known)known=(async()=>{let probe=path.join(toDir,`.rove-clone-probe-${process.pid}`);try{return await cloneOneFile(path.join(from,".git"),probe),!0}catch{return!1}finally{await fs.rm(probe,{force:!0})}})(),probeCache.set(key,known);return known};async function git2(cwd,args){let{stdout}=await run("git",[...args],{cwd,maxBuffer:67108864});return stdout.trim()}class CowCloneBackend{plain;id="cow-clone";capabilities=WORKSPACE_CAPABILITIES["cow-clone"];probe;cloneEntries;constructor(plain,deps={}){this.plain=plain;this.probe=deps.probe??volumeProbe,this.cloneEntries=deps.cloneEntries??cpClone}async materialize(spec){let parent=spec.forkFrom;if(!parent)return{...await this.plain.materialize(spec),backend:this.id};if(isRemoteRepoKey(spec.repo))throw new ForkUnsupportedError("a remote project's worktree cannot be cloned");let target=worktreePathFor(spec.repo,spec.slug),root=path.dirname(target);if(await fs.mkdir(root,{recursive:!0}),!await this.probe(parent,root))throw new ForkUnsupportedError(`${parent} and ${root} are not on one volume that can clone files (APFS, btrfs, XFS with reflink); the fork would have to copy the whole tree`);let head=await git2(parent,["rev-parse","HEAD"]);await git2(spec.repo,["worktree","add","--no-checkout","-b",spec.branch,target,head]);try{let entries=(await fs.readdir(parent)).filter((name)=>name!==".git").map((name)=>path.join(parent,name));await this.cloneEntries(entries,target),await this.carryIndex(parent,target)}catch(err){throw await this.discard(spec.repo,target,spec.branch),err}return{backend:this.id,path:target}}async carryIndex(parent,target){let indexOf=(dir)=>git2(dir,["rev-parse","--path-format=absolute","--git-path","index"]);try{await fs.copyFile(await indexOf(parent),await indexOf(target)),await git2(target,["update-index","-q","--refresh"])}catch{await git2(target,["reset","-q"])}}async discard(repo,target,branch){await git2(repo,["worktree","remove","--force",target]).catch(()=>{}),await fs.rm(target,{recursive:!0,force:!0}),await git2(repo,["worktree","prune"]).catch(()=>{}),await git2(repo,["branch","-D",branch]).catch(()=>{})}dispose(target,opts){return this.plain.dispose(target,opts)}}class GitWorktreeBackend{worktrees;id="git-worktree";capabilities=WORKSPACE_CAPABILITIES["git-worktree"];constructor(worktrees){this.worktrees=worktrees}async materialize(spec){let info=await this.worktrees.createForTask({repo:spec.repo,slug:spec.slug,branch:spec.branch,baseRef:spec.baseRef,onProgress:spec.onProgress});return{backend:this.id,path:info.path}}async dispose(target,opts){await this.worktrees.remove(target.path,{...opts,repo:target.repo,branch:target.branch})}}import{execFile as execFile2}from"child_process";import{createHash}from"crypto";import{promises as fs2,readFileSync}from"fs";import os from"os";import path2 from"path";import{promisify as promisify2}from"util";var LAYERFS_CONFIG_KEY="experimental.layerfs",STATE_FILE=".rove-layerfs.json",SANDBOX_USER="501:20",SANDBOX_HOME="/tmp/rove-home",KILL_TAGGED=`for p in /proc/[0-9]*; do tr '\\0' '\\n' < $p/environ 2>/dev/null | grep -qx "$1" && kill -KILL \${p#/proc/}; done; true`,KILL_UNDER='for p in /proc/[0-9]*; do case $(readlink $p/cwd) in "$1"|"$1"/*) kill -KILL ${p#/proc/};; esac; done; sleep 0.2',execRun=async(file,args)=>{try{let{stdout}=await promisify2(execFile2)(file,[...args],{maxBuffer:67108864});return stdout}catch(err){let e=err;throw Error((e.stderr?.trim()||e.stdout?.trim()||e.message).slice(0,2000))}};function parseLayerfsEnv(text){let env={};for(let line of text.split(`
2
+ import{canonPath,normalizeMainRepo,randomDirTaskSuffix,repoWorkingDir,samePrStatus,titleFromRepo}from"./chunk-qnv8ggxh.js";import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-c1dz3qg3.js";import{CLONEFILEAT_PERL,GitWorktreeManager,defaultExecDeps,git,isDirtyOutput,parseDirtyPaths}from"./chunk-jkssty8x.js";import{LAUNCH_PREFIX_FILE}from"./chunk-4dt1gfb3.js";import{PLACEHOLDER_TASK_TITLE,isPlaceholderDerivedBranch,sanitizeTaskTitle}from"./chunk-2xsxcdp6.js";import{CannotDeleteMainTaskError,DirtyWorktreeError,EmptyBranchDirtyWorktreeError,EmptyBranchError,ExtraRepoNotGitError,ForkUnsupportedError,GitCommandFailedError,IllegalTransitionError,InvalidWorktreeNameError,LandConflictError,MainCheckoutDirtyError,MissingRefError,MoveRefusedError,NotAGitRepoError,NotALinkedRepoError,REMOTE_PARENT_UNSUPPORTED_CODE,RemoteExtraUnsupportedError,RemoteParentUnsupportedError,ReparentRefusedError,RepoDuplicateError,TaskDeletingError,TaskNotFoundError,TooManyReposError,WorktreeNameTakenError,WorktreeRemoveFailedError,canonicalize,listWorktreeDirNames,worktreePathFor}from"./chunk-ee8917py.js";import{detectLanguage}from"./chunk-hpay0ax8.js";import{resolvePreferredVendor}from"./chunk-8ttn73cv.js";import{addSavedRepo,getPersistedString,getSavedRepos,isGitRepo,isRemoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot}from"./chunk-gygdyf0s.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{projectRejection,rejectionReason}from"./chunk-7mwvvj46.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{MULTI_REPO_CAP,SESSION_PR_CAP,WORKSPACE_CAPABILITIES,applyTodoOps,checkNotes,childrenOf,gitRepoOf,lineageRootId,pickRepos,repoNameOf,subtreeIds,taskCwd,taskRepos,taskWorktreePaths,uniqueRepoName,workspaceBackendId,workspaceCapabilities}from"./chunk-x1jxxmtc.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{pathIdentity,pathWithin,samePath}from"./chunk-pn5ygqn6.js";class WorkspaceCheckpoints{store;worktrees;workspaces;requireTask;constructor(store,worktrees,workspaces,requireTask){this.store=store;this.worktrees=worktrees;this.workspaces=workspaces;this.requireTask=requireTask}workspaceOwner(id){let task=this.requireTask(id);return(task.sharesWorkspaceOf?this.store.get(task.sharesWorkspaceOf):void 0)??task}checkpointScope(id){let owner=this.workspaceOwner(id),sharers=this.store.list().filter((t)=>t.sharesWorkspaceOf===owner.id&&!t.deletion);return{ownerId:String(owner.id),sharerIds:[String(owner.id),...sharers.map((t)=>String(t.id))]}}canCheckpoint(id){if(!this.store.get(id))return!1;let owner=this.workspaceOwner(id);return workspaceCapabilities(owner).checkpoint&&!owner.deletion&&owner.worktreePath!==""}async target(id){let owner=this.workspaceOwner(id),own=this.canCheckpoint(id)?this.workspaces.get(workspaceBackendId(owner)).checkpoints:void 0,dir=owner.worktreePath;if(!this.canCheckpoint(id)||!await this.worktrees.pathExists(own?dir:`${dir}/.git`))throw Error(`NOT_CHECKPOINTABLE: ${owner.kind==="task"?"the task has no workspace on disk":`a ${owner.kind} task works in your own checkout`}`);let ownerId=String(owner.id);return{ownerId,dir,via:own??{take:(d,opts)=>this.worktrees.takeCheckpoint(d,ownerId,opts),list:(d)=>this.worktrees.listCheckpoints(d,ownerId),rewind:(d,n)=>this.worktrees.rewindToCheckpoint(d,ownerId,n)}}}async takeCheckpoint(id,opts){let{dir,via}=await this.target(id);return via.take(dir,opts)}async listCheckpoints(id){let{dir,via}=await this.target(id);return via.list(dir)}async rewindToCheckpoint(id,n){let{dir,via}=await this.target(id);return via.rewind(dir,n)}async exportBranch(id){let owner=this.workspaceOwner(id),backend=this.workspaces.get(workspaceBackendId(owner));if(!backend.exportBranch||!owner.worktreePath)throw Error("EXPORT_UNSUPPORTED: the task's branch is already in its repo (or it has no workspace yet)");return backend.exportBranch({path:owner.worktreePath,repo:gitRepoOf(owner),branch:owner.branch})}}var TYPE_PREFIXES=new Set(["feat","feature","fix","bugfix","hotfix","chore","docs","doc","refactor","test","tests","ci","build","perf","style","revert","release"]),BRAND_TOKENS=new Set(["rove"]);function inferBranchStyle(names){let typed=new Map,bare=0;for(let raw of new Set(names)){let name=raw.trim();if(!name||name==="HEAD")continue;let slash=name.indexOf("/");if(slash===-1){bare+=1;continue}let prefix=name.slice(0,slash);if(TYPE_PREFIXES.has(prefix))typed.set(prefix,(typed.get(prefix)??0)+1)}let typedTotal=0;for(let n of typed.values())typedTotal+=n;if(typedTotal===0||typedTotal<bare)return{kind:"bare"};let best="",bestN=0;for(let[prefix,n]of typed)if(n>bestN||n===bestN&&(best===""||prefix<best))best=prefix,bestN=n;return{kind:"typed",defaultPrefix:best}}function slugTokens(title){return title.toLowerCase().replace(/[^a-z0-9]+/g,"-").split("-").filter((t)=>t.length>0&&!BRAND_TOKENS.has(t))}function capSlug(tokens){let slug="";for(let token of tokens){let candidate=slug?`${slug}-${token}`:token;if(candidate.length>32)return slug||token.slice(0,32);slug=candidate}return slug}function identitySlug(taskId){return`task-${taskId.slice(-6).toLowerCase()}`}function deriveConventionBranch(title,style,taskId){let tokens=slugTokens(title);if(style.kind==="typed"){let first=tokens[0];return`${first!==void 0&&TYPE_PREFIXES.has(first)?tokens.shift():style.defaultPrefix}/${capSlug(tokens)||identitySlug(taskId)}`}return capSlug(tokens)||identitySlug(taskId)}function uniqueBranchName(base,taken,taskId){let dirs=new Set;for(let name of taken)for(let i=name.indexOf("/");i>0;i=name.indexOf("/",i+1))dirs.add(name.slice(0,i));let isFree=(name)=>!taken.has(name)&&!dirs.has(name),segments=base.split("/"),root=segments.slice(0,-1).some((_,i)=>taken.has(segments.slice(0,i+1).join("/")))?segments.join("-"):base;if(isFree(root))return root;for(let n=2;n<=99;n+=1){let candidate=`${root}-${n}`;if(isFree(candidate))return candidate}return`${root}-${taskId.slice(-6).toLowerCase()}`}function planExtraRepos(primary,inputs){if(inputs.length===0)return[];if(1+inputs.length>MULTI_REPO_CAP)throw new TooManyReposError(1+inputs.length,MULTI_REPO_CAP);if(isRemoteRepoKey(primary))throw new RemoteExtraUnsupportedError(primary);let seen=new Set([canonPath(primary)]),names=new Set([repoNameOf(primary)]);return inputs.map((input)=>{if(isRemoteRepoKey(input.repo))throw new RemoteExtraUnsupportedError(input.repo);let{repo}=normalizeMainRepo(input.repo);if(!isGitRepo(repo))throw new ExtraRepoNotGitError(input.repo);if(seen.has(canonPath(repo)))throw new RepoDuplicateError(repo);seen.add(canonPath(repo));let name=uniqueRepoName(repoNameOf(repo),names);names.add(name);let baseRef=input.baseRef?.trim();return{name,repo,branch:"",worktreePath:"",...baseRef?{baseRef}:{}}})}async function rollbackWorktree(backend,created){try{await backend.dispose({path:created.path,...created.fresh},created.fresh?{force:!0,deleteBranch:!0}:{force:!0})}catch(err){console.error(`[rove] ensureWorktree rollback failed for ${created.path}:`,err)}}async function extrasToMaterialise(worktrees,extras){let missing=[];for(let extra of extras??[])if(!extra.worktreePath||!await worktrees.pathExists(extra.worktreePath))missing.push(extra);return missing}function scaleProgress(onProgress,step,total){return onProgress&&((percent)=>onProgress(Math.floor((step+percent/100)/total*100)))}async function materialiseExtras(opts){let{worktrees,backend,slugs,task}=opts,callerNamed=task.branch!=="",created=[],picked=[],done=new Map,missing=await extrasToMaterialise(worktrees,task.extraRepos);try{for(let[index,extra]of missing.entries()){if(extra.worktreePath)await worktrees.pruneWorktrees(extra.repo);let names=await worktrees.listBranchNames(extra.repo),branch=extra.branch||(callerNamed||!names.includes(opts.branch)?opts.branch:uniqueBranchName(opts.branch,new Set(names),task.id)),slug=await slugs.allocate(extra.repo);picked.push({repo:extra.repo,slug});let info=await backend.materialize({repo:extra.repo,slug,branch,baseRef:extra.baseRef,onProgress:opts.progressFor(index)});created.push({path:info.path,...names.includes(branch)?{}:{fresh:{repo:extra.repo,branch}}}),done.set(extra.name,{...extra,branch,worktreePath:info.path})}}catch(err){for(let wt of created.reverse())await rollbackWorktree(backend,wt);for(let{repo,slug}of picked)slugs.cancel(repo,slug);throw err}return{extraRepos:(task.extraRepos??[]).map((e)=>done.get(e.name)??e),created,slugs:picked}}function nestingParent(store,id){let parent=store.get(id);if(!parent)throw new TaskNotFoundError(id);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(isRemoteRepoKey(parent.repo))throw new RemoteParentUnsupportedError(String(parent.id));return toTaskId(lineageRootId(store.list(),parent.id))}async function createTaskRow(deps,input){if(!input.repo)throw Error("createTask: repo is required");let extraRepos=planExtraRepos(normalizeMainRepo(input.repo).repo,input.extraRepos??[]),parentTaskId=input.parentTaskId?nestingParent(deps.store,input.parentTaskId):void 0,repo=(await deps.mainTasks.ensureIfEligible(input.repo,input.projectIntent??"explicit"))?.repo??normalizeMainRepo(input.repo).repo,title=sanitizeTaskTitle(input.title??PLACEHOLDER_TASK_TITLE)||PLACEHOLDER_TASK_TITLE,worktreeName=input.worktreeName?.trim();if(worktreeName)await deps.claimWorktreeName(repo,worktreeName);return await deps.store.create({repo,title,branch:input.branch??"",worktreePath:"",status:"backlog",kind:"task",vendor:input.vendor??DEFAULT_TASK_VENDOR,...input.command?.trim()?{command:input.command.trim()}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},...input.tier?.trim()?{tier:input.tier.trim()}:{},...input.groupId?{groupId:input.groupId}:{},...input.dispatcher?{dispatcher:input.dispatcher}:{},...parentTaskId?{parentTaskId}:{},...input.cwdSubpath?{cwdSubpath:input.cwdSubpath}:{},...input.routine?{routine:input.routine}:{},...input.baseRef?.trim()?{baseRef:input.baseRef.trim()}:{},...extraRepos.length>0?{extraRepos}:{},...input.workspace?{workspace:input.workspace}:{},...worktreeName?{worktreeName}:{}})}async function openDirectoryTaskRow(deps,input){if(!input.dir)throw Error("openDirectoryTask: dir is required");let dir=canonPath(input.dir),title=(input.title?sanitizeTaskTitle(input.title):"")||(input.scratch?"":`${titleFromRepo(dir)}-${randomDirTaskSuffix()}`);return deps.store.create({repo:dir,title,branch:"",worktreePath:dir,status:"backlog",kind:"dir",...input.scratch?{scratch:!0}:{},...input.noProject?{noProject:!0}:{},...input.routine?{routine:input.routine}:{},...input.modelEffort?{modelEffort:input.modelEffort}:{},...input.model?.trim()?{model:input.model.trim()}:{},vendor:input.vendor??resolvePreferredVendor()})}async function adoptScratchRepoRow(deps,id,repo){let task=deps.store.get(id);if(!task||task.kind!=="dir"||task.scratch!==!0)return;let dir=canonPath(repo);await deps.store.update(id,{repo:dir,worktreePath:dir,scratch:!1,title:titleFromRepo(dir)})}class BorrowedBackend{id="borrowed";capabilities=WORKSPACE_CAPABILITIES.borrowed;async materialize(spec){return{backend:this.id,path:spec.path??repoWorkingDir(spec.repo)}}async dispose(){}}import{execFile}from"child_process";import{promises as fs,statSync}from"fs";import path from"path";import{promisify}from"util";var run=promisify(execFile),CP_CHUNK=200;function cloneFlags(){if(process.platform==="darwin")return["-c","-R","-P"];if(process.platform==="linux")return["--reflink=always","-a"];return null}var cpClone=async(entries,to)=>{let flags=cloneFlags();if(!flags)throw new ForkUnsupportedError(`copy-on-write clones are not supported on ${process.platform}`);for(let i=0;i<entries.length;i+=CP_CHUNK)try{await run("cp",[...flags,...entries.slice(i,i+CP_CHUNK),`${to}${path.sep}`])}catch(err){let detail=err.stderr?.trim()||String(err);throw Error(`cloning the worktree failed: ${detail}`)}},probeCache=new Map;async function cloneOneFile(source,target){if(process.platform==="darwin")await run("/usr/bin/perl",["-e",CLONEFILEAT_PERL,source,target]);else if(process.platform==="linux")await run("cp",["--reflink=always",source,target]);else throw Error(`no clone primitive on ${process.platform}`)}var volumeProbe=(from,toDir)=>{let key=`${statSync(from).dev}:${statSync(toDir).dev}`,known=probeCache.get(key);if(!known)known=(async()=>{let probe=path.join(toDir,`.rove-clone-probe-${process.pid}`);try{return await cloneOneFile(path.join(from,".git"),probe),!0}catch{return!1}finally{await fs.rm(probe,{force:!0})}})(),probeCache.set(key,known);return known};async function git2(cwd,args){let{stdout}=await run("git",[...args],{cwd,maxBuffer:67108864});return stdout.trim()}class CowCloneBackend{plain;id="cow-clone";capabilities=WORKSPACE_CAPABILITIES["cow-clone"];probe;cloneEntries;constructor(plain,deps={}){this.plain=plain;this.probe=deps.probe??volumeProbe,this.cloneEntries=deps.cloneEntries??cpClone}async materialize(spec){let parent=spec.forkFrom;if(!parent)return{...await this.plain.materialize(spec),backend:this.id};if(isRemoteRepoKey(spec.repo))throw new ForkUnsupportedError("a remote project's worktree cannot be cloned");let target=worktreePathFor(spec.repo,spec.slug),root=path.dirname(target);if(await fs.mkdir(root,{recursive:!0}),!await this.probe(parent,root))throw new ForkUnsupportedError(`${parent} and ${root} are not on one volume that can clone files (APFS, btrfs, XFS with reflink); the fork would have to copy the whole tree`);let head=await git2(parent,["rev-parse","HEAD"]);await git2(spec.repo,["worktree","add","--no-checkout","-b",spec.branch,target,head]);try{let entries=(await fs.readdir(parent)).filter((name)=>name!==".git").map((name)=>path.join(parent,name));await this.cloneEntries(entries,target),await this.carryIndex(parent,target)}catch(err){throw await this.discard(spec.repo,target,spec.branch),err}return{backend:this.id,path:target}}async carryIndex(parent,target){let indexOf=(dir)=>git2(dir,["rev-parse","--path-format=absolute","--git-path","index"]);try{await fs.copyFile(await indexOf(parent),await indexOf(target)),await git2(target,["update-index","-q","--refresh"])}catch{await git2(target,["reset","-q"])}}async discard(repo,target,branch){await git2(repo,["worktree","remove","--force",target]).catch(()=>{}),await fs.rm(target,{recursive:!0,force:!0}),await git2(repo,["worktree","prune"]).catch(()=>{}),await git2(repo,["branch","-D",branch]).catch(()=>{})}dispose(target,opts){return this.plain.dispose(target,opts)}}class GitWorktreeBackend{worktrees;id="git-worktree";capabilities=WORKSPACE_CAPABILITIES["git-worktree"];constructor(worktrees){this.worktrees=worktrees}async materialize(spec){let info=await this.worktrees.createForTask({repo:spec.repo,slug:spec.slug,branch:spec.branch,baseRef:spec.baseRef,onProgress:spec.onProgress});return{backend:this.id,path:info.path}}async dispose(target,opts){await this.worktrees.remove(target.path,{...opts,repo:target.repo,branch:target.branch})}}import{execFile as execFile2}from"child_process";import{createHash}from"crypto";import{promises as fs2,readFileSync}from"fs";import os from"os";import path2 from"path";import{promisify as promisify2}from"util";var LAYERFS_CONFIG_KEY="experimental.layerfs",STATE_FILE=".rove-layerfs.json",SANDBOX_USER="501:20",SANDBOX_HOME="/tmp/rove-home",KILL_TAGGED=`for p in /proc/[0-9]*; do tr '\\0' '\\n' < $p/environ 2>/dev/null | grep -qx "$1" && kill -KILL \${p#/proc/}; done; true`,KILL_UNDER='for p in /proc/[0-9]*; do case $(readlink $p/cwd) in "$1"|"$1"/*) kill -KILL ${p#/proc/};; esac; done; sleep 0.2',execRun=async(file,args)=>{try{let{stdout}=await promisify2(execFile2)(file,[...args],{maxBuffer:67108864});return stdout}catch(err){let e=err;throw Error((e.stderr?.trim()||e.stdout?.trim()||e.message).slice(0,2000))}};function parseLayerfsEnv(text){let env={};for(let line of text.split(`
3
3
  `)){let m=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)=(.*)$/.exec(line);if(m)env[m[1]]=m[2].trim().replace(/^(["'])(.*)\1$/,"$2")}return env}class LayerfsBackend{id="layerfs";capabilities=WORKSPACE_CAPABILITIES.layerfs;run;configPath;platform;rootChecked=!1;constructor(deps={}){this.run=deps.run??execRun,this.configPath=deps.configPath??(()=>getPersistedString(LAYERFS_CONFIG_KEY)),this.platform=deps.platform??process.platform}async preflight(){this.env(),await this.requireRoot()}env(){if(this.platform!=="linux")throw unavailable(`it runs on Linux Runners only, not ${this.platform}`);let file=this.configPath();if(!file)throw unavailable(`set ${LAYERFS_CONFIG_KEY} in state.json to a LayerFS env file`);let env;try{env=parseLayerfsEnv(readFileSync(file,"utf8"))}catch(err){throw unavailable(`cannot read ${file}: ${err.message}`)}for(let key of["LAYERFS_CLI","LAYERFS_NODE","LAYERFS_HOME","LAYERFS_STORE_PATH","LAYERFS_IMAGE"])if(!env[key])throw unavailable(`${file} does not set ${key}`);return env}async requireRoot(){if(this.rootChecked)return;try{await this.run("sudo",["-n","true"])}catch{throw Error("LAYERFS_NEEDS_ROOT: LayerFS Store calls run as root, and `sudo -n` cannot (configure passwordless sudo for this user)")}this.rootChecked=!0}async lfs(project,...args){let env=this.env();await this.requireRoot();let pass=Object.entries(env).filter(([k])=>k!=="LAYERFS_CLI"&&k!=="LAYERFS_NODE").map(([k,v])=>`${k}=${v}`),out=await this.run("sudo",["-n","env",...pass,`LAYERFS_PROJECT=${project}`,env.LAYERFS_NODE,env.LAYERFS_CLI,...args]);return JSON.parse(out)}docker(...args){return this.run("docker",args)}inSandbox(s,dir,...argv){return this.docker("exec","-u",SANDBOX_USER,"-w",dir,"-e",`HOME=${SANDBOX_HOME}`,s.container,...argv)}async ensureProject(repo){let project=`rove-${createHash("sha1").update(repo).digest("hex").slice(0,12)}`;try{await this.lfs(project,"project","list_branches","--page-size","1")}catch{await this.lfs(project,"init",project,repo,"--timeout","1800000")}return project}async materialize(spec){if(spec.forkFrom||spec.path)throw unavailable("a layerfs task cannot be forked or borrow a directory");this.env();let dir=worktreePathFor(spec.repo,spec.slug),project=await this.ensureProject(spec.repo),branch=`${spec.slug}-${Date.now().toString(36)}`;await this.lfs(project,"branch","fork",branch);let{sandbox}=await this.lfs(project,"sandbox","create"),s={project,sandbox,ws:"",container:"",branch,gitBase:"",checkpoints:[]};try{s.container=await this.containerOf(project,sandbox),await this.mount(s,dir),await this.inSandbox(s,dir,"git","checkout","-q","-b",spec.branch,...spec.baseRef?[spec.baseRef]:[]),s.gitBase=(await this.inSandbox(s,dir,"git","rev-parse","HEAD")).trim();let reap=["docker","exec","-u",SANDBOX_USER,s.container,"sh","-c",KILL_TAGGED,"sh","ROVE_LAUNCH={launch}"];await fs2.writeFile(path2.join(dir,LAUNCH_PREFIX_FILE),JSON.stringify({prefix:this.launchPrefix(s,dir),reap})),await this.save(dir,s)}catch(err){throw await this.teardown(s,dir,!0).catch(()=>{}),err}return{backend:this.id,path:dir,ref:`${project}:${branch}`}}launchPrefix(s,dir){let env=["-e",`HOME=${SANDBOX_HOME}`,"-e","ROVE_LAUNCH={launch}","-e","TERM","-e","COLUMNS","-e","LINES"];return["docker","exec","-it","-u",SANDBOX_USER,"-w",dir,...env,s.container]}async containerOf(project,sandbox){let id=(await this.docker("ps","-q","--filter",`label=layerfs.project=${project}`,"--filter",`label=layerfs.sandbox=${sandbox}`)).trim();if(!id||id.includes(`
4
4
  `))throw Error(`no single container for LayerFS sandbox ${project}/${sandbox}`);return id}async mount(s,dir){s.ws=(await this.lfs(s.project,"workspace","mount",s.sandbox,s.branch)).ws,await fs2.mkdir(dir,{recursive:!0}),await this.bind(s,dir)}async bind(s,dir){let mountPath=s.ws.slice(s.ws.indexOf(":")+1),script=`mkdir -p "$1" ${SANDBOX_HOME} && chown ${SANDBOX_USER} ${SANDBOX_HOME} && mount --bind "$2" "$1"`;await this.docker("exec","-u","0",s.container,"sh","-c",script,"sh",dir,mountPath)}async unbind(s,dir){try{await this.docker("exec","-u","0",s.container,"umount",dir)}catch(err){if(!/busy/i.test(err.message))throw err;throw Error(`WORKSPACE_BUSY: a process still runs in ${dir} inside the sandbox; close the task's terminals first`)}}async unmount(s,dir,discard){await this.unbind(s,dir);try{await this.lfs(s.project,"workspace","unmount",s.ws,...discard?["--discard"]:[])}catch(err){if(await this.bind(s,dir),!/"code":"Dirty"/.test(err.message))throw err;throw Error(`WORKSPACE_DIRTY: LayerFS has uncommitted changes in ${dir}; checkpoint first, or force`)}}async teardown(s,dir,discard){if(s.ws){if(s.container)await this.docker("exec","-u",SANDBOX_USER,s.container,"sh","-c",KILL_UNDER,"sh",dir);await this.unmount(s,dir,discard)}await this.lfs(s.project,"sandbox","close",s.sandbox),await fs2.rm(path2.join(dir,STATE_FILE),{force:!0}),await fs2.rm(path2.join(dir,LAUNCH_PREFIX_FILE),{force:!0}),await fs2.rmdir(dir).catch(()=>{})}async dispose(target,opts){let s=await this.load(target.path).catch(()=>{return});if(!s){await fs2.rm(path2.join(target.path,LAUNCH_PREFIX_FILE),{force:!0}),await fs2.rmdir(target.path).catch(()=>{});return}await this.teardown(s,target.path,opts.force===!0)}async dirtyPaths(dir){let s=await this.load(dir).catch(()=>{return});if(!s?.ws)return[];let{items}=await this.lfs(s.project,"sandbox","list_workspaces",s.sandbox);return items.find((w)=>`${s.sandbox}:${w.path}`===s.ws)?.changed?["(changes since the last checkpoint, inside the LayerFS sandbox)"]:[]}checkpoints={take:(dir,opts)=>this.take(dir,opts?.tabId),list:async(dir)=>(await this.load(dir)).checkpoints,rewind:async(dir,n)=>{let target=(await this.load(dir)).checkpoints.find((c)=>c.n===n);if(!target)throw Error(`CHECKPOINT_NOT_FOUND: checkpoint ${n} does not exist`);let undo=(await this.take(dir)).checkpoint,after=await this.load(dir),fork=`${after.branch.replace(/-r[0-9a-z]+$/,"")}-r${Date.now().toString(36)}`;return await this.lfs(after.project,"branch","fork",fork,target.commit),await this.unmount(after,dir,!0),after.branch=fork,await this.mount(after,dir),await this.save(dir,after),{target,undo,uncaptured:[]}}};async take(dir,tabId){let s=await this.load(dir),latest=s.checkpoints.at(-1),reply=await this.lfs(s.project,"workspace","commit",s.ws,"-m","rove checkpoint",...latest?[]:["--force"]);if(latest&&reply.kind==="UpToDate")return{created:!1,checkpoint:latest};let checkpoint={n:(latest?.n??0)+1,ref:`layerfs:${s.project}:${s.branch}`,commit:reply.head,tree:reply.commit?.root??reply.root??reply.head,at:new Date().toISOString(),...tabId?{tabId}:{}};return s.checkpoints.push(checkpoint),await this.save(dir,s),{created:!0,checkpoint,uncaptured:[]}}async exportBranch(target){let s=await this.load(target.path),inner=`/tmp/rove-export-${process.pid}.bundle`;await this.inSandbox(s,target.path,"git","bundle","create","-q",inner,target.branch,`^${s.gitBase}`);let local=path2.join(os.tmpdir(),`rove-layerfs-${process.pid}-${Date.now()}.bundle`);try{await this.docker("cp",`${s.container}:${inner}`,local),await this.run("git",["-C",target.repo,"fetch","-q",local,`${target.branch}:refs/heads/${target.branch}`]);let commit=(await this.run("git",["-C",target.repo,"rev-parse",target.branch])).trim();return{branch:target.branch,commit}}finally{await fs2.rm(local,{force:!0})}}async load(dir){return JSON.parse(await fs2.readFile(path2.join(dir,STATE_FILE),"utf8"))}save(dir,s){return fs2.writeFile(path2.join(dir,STATE_FILE),`${JSON.stringify(s,null,2)}
5
5
  `)}}function unavailable(why){return Error(`LAYERFS_UNAVAILABLE: the layerfs workspace backend is unavailable: ${why}`)}class WorkspaceRegistry{backends=new Map;constructor(backends){for(let backend of backends)this.backends.set(backend.id,backend)}get(id){let backend=this.backends.get(id);if(!backend)throw Error(`workspace backend '${id}' is not available in this build`);return backend}}function createWorkspaceRegistry(worktrees,cowClone){let plain=new GitWorktreeBackend(worktrees);return new WorkspaceRegistry([plain,new BorrowedBackend,new CowCloneBackend(plain,cowClone),new LayerfsBackend])}async function createOrForkTask(deps,input){if(input.workspace)await deps.workspaces.get(input.workspace.backend).preflight?.();let createRow=(row)=>createTaskRow(deps,row),{forkFrom}=input;return forkFrom?forkTaskRow({...deps,createRow},{...input,forkFrom}):createRow(input)}async function forkTaskRow(deps,input){let parent=deps.store.get(input.forkFrom);if(!parent)throw new TaskNotFoundError(input.forkFrom);if(parent.deletion)throw new TaskDeletingError(String(parent.id));if(!workspaceCapabilities(parent).ownsDirectory)throw new ForkUnsupportedError("a main or directory task has no Rove-created worktree to clone");if(isRemoteRepoKey(parent.repo))throw new ForkUnsupportedError("a remote project's worktree cannot be cloned");if(parent.extraRepos?.length)throw new ForkUnsupportedError("a multi-repo task cannot be forked: only its primary repo would be cloned");let parentPath=await deps.ensureWorktree(parent.id),baseRef=git(["rev-parse","HEAD"],{cwd:parentPath,readOnly:!0}).stdout.trim(),child=await deps.createRow({...input,repo:gitRepoOf(parent),title:input.title??`${parent.title} (fork)`,baseRef,workspace:{backend:"cow-clone",ref:String(parent.id)},...parent.cwdSubpath?{cwdSubpath:parent.cwdSubpath}:{}});if(parent.gitRepo)await deps.store.update(child.id,{repo:parent.repo,gitRepo:parent.gitRepo});try{await deps.cloneInto(child,parentPath)}catch(err){throw await discard(deps,child).catch((cleanup)=>console.error(`[rove] fork rollback failed for ${child.id}:`,cleanup)),await deps.store.remove(child.id),err}return deps.store.get(child.id)??child}async function discard(deps,child){let row=deps.store.get(child.id);if(!row?.worktreePath)return;await deps.workspaces.get(workspaceBackendId(row)).dispose({path:row.worktreePath,repo:gitRepoOf(row),branch:row.branch},{force:!0,deleteBranch:!0})}function baseRepoCtx(repo,deps){let basePath=deps.remoteBasePath(repo);return{exec:deps.execForRepo(repo),dir:basePath??repo}}async function landGit(exec,dir,args,opts){let r=await exec.run(["git",...args],{cwd:dir,env:opts?.readOnly?READ_ONLY_GIT_ENV:void 0});return{stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode}}async function isDirty(exec,dir){return isDirtyOutput((await landGit(exec,dir,["status","--porcelain"],{readOnly:!0})).stdout)}async function landPreflight(task,deps=defaultExecDeps){let refuse=(pf,refusal)=>{let refused={...pf,refusal};return{...refused,message:landRefusalError(task,refused).message}},branch=task.branch.trim();if(!branch)throw Error(`landPreflight: task ${task.id} has no branch to land (never materialised)`);let{exec,dir}=baseRepoCtx(gitRepoOf(task),deps),headOut=await landGit(exec,dir,["symbolic-ref","--short","HEAD"],{readOnly:!0}),landedOn=headOut.stdout.trim();if(headOut.exitCode!==0||!landedOn){let headCommit=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0}),detached=headCommit.exitCode===0&&headCommit.stdout.trim().length>0;return refuse({branch,landedOn:"",baseDir:dir},detached?"DETACHED_HEAD":"UNREADABLE_BASE")}if(landedOn===branch)return refuse({branch,landedOn,baseDir:dir},"SAME_BRANCH");let baseDirty=await isDirty(exec,dir),aheadOut=await landGit(exec,dir,["rev-list","--count",`${landedOn}..${branch}`],{readOnly:!0});if(aheadOut.exitCode!==0){let baseHead=await landGit(exec,dir,["rev-parse","--verify","--quiet","HEAD"],{readOnly:!0});if(baseHead.exitCode!==0||!baseHead.stdout.trim())return refuse({branch,landedOn,baseDirty,baseDir:dir},"UNBORN_BASE");return refuse({branch,landedOn,baseDirty,baseDir:dir},baseDirty?"MAIN_CHECKOUT_DIRTY":"MISSING_REF")}let parsed=Number.parseInt(aheadOut.stdout.trim(),10),base={branch,landedOn,baseDirty,baseDir:dir,...Number.isFinite(parsed)?{ahead:parsed}:{}};if(baseDirty)return refuse(base,"MAIN_CHECKOUT_DIRTY");if(base.ahead!==0)return base;let worktreePath=task.worktreePath.trim();if(worktreePath){let manager=new GitWorktreeManager(deps),dirty=!1;try{dirty=await manager.isDirty(worktreePath)}catch{dirty=!1}if(dirty){let wtExec=deps.execForPath(worktreePath),files=parseDirtyPaths((await landGit(wtExec,worktreePath,["status","--porcelain"],{readOnly:!0})).stdout);return refuse({...base,dirtyFiles:files},"EMPTY_BRANCH_DIRTY_WORKTREE")}}return refuse(base,"EMPTY_BRANCH")}function landRefusalError(task,pf){switch(pf.refusal){case"DETACHED_HEAD":return Error(`landTask: base checkout at ${pf.baseDir} is in detached-HEAD state; check out a branch first`);case"UNREADABLE_BASE":return Error(`landTask: could not read HEAD of the base checkout at ${pf.baseDir} \u2014 is it still a git repo?`);case"UNBORN_BASE":return Error(`landTask: base checkout at ${pf.baseDir} is on '${pf.landedOn}' but has no commits yet, so there is nothing to merge '${pf.branch}' into; make the first commit there (or \`git merge --ff-only ${pf.branch}\`) and land again`);case"SAME_BRANCH":return Error(`landTask: base checkout is already on '${pf.branch}' \u2014 nothing to land onto`);case"MAIN_CHECKOUT_DIRTY":return new MainCheckoutDirtyError(gitRepoOf(task),pf.baseDir);case"MISSING_REF":return new MissingRefError(pf.branch,pf.landedOn,pf.baseDir);case"EMPTY_BRANCH_DIRTY_WORKTREE":return new EmptyBranchDirtyWorktreeError(pf.branch,pf.landedOn,task.worktreePath.trim(),[...pf.dirtyFiles??[]]);case"EMPTY_BRANCH":return new EmptyBranchError(pf.branch,pf.landedOn)}}function assertOwnsBranch(task){if(workspaceCapabilities(task).ownsBranch)return;throw Error(task.kind==="main"?"landTask: a main task has no branch to land":"landTask: a directory task has no Rove-managed branch to land")}async function landTaskWithCleanup(task,opts,deps){assertOwnsBranch(task);let result=await landTask(task,{strategy:opts.strategy});return finishLanded(task,result,opts,deps)}async function finishLanded(task,result,opts,deps){let worktree=opts.removeWorktree===!1?void 0:await removeLandedWorktree(task,opts.callerCwd,deps),branchAnchor=null,branchKept,worktreeGone=!task.worktreePath.trim()||worktree?.removed===!0;if(opts.deleteBranch&&!worktreeGone)branchKept={reason:worktree?.reason??`worktree ${task.worktreePath} was kept, and still has the branch checked out`};else if(opts.deleteBranch){let outcome=await deps.worktrees.deleteBranch(gitRepoOf(task),result.branch,{force:!0,onAnchor:(record)=>{branchAnchor=record}});if(!outcome.deleted)branchKept={reason:outcome.reason}}return{...result,...worktree?{worktree}:{},...branchAnchor?{branchAnchor}:{},...branchKept?{branchKept}:{}}}async function removeLandedWorktree(task,callerCwd,deps){let worktreePath=task.worktreePath.trim();if(!worktreePath)return{removed:!1,reason:"task has no worktree on disk (never materialised)"};let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(gitRepoOf(task))))return{removed:!1,reason:"refusing to remove the base checkout"};if(deps.sharesWorktree?.(task))return{removed:!1,reason:`kept ${worktreePath}: other tasks still run in this directory`};if(callerCwd){if(pathWithin(wt,canonicalize(callerCwd))!==null)return{removed:!1,reason:`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`}}if(deps.tearDownSession)try{await deps.tearDownSession(task.id)}catch{}let residue;try{await deps.worktrees.remove(worktreePath,{onResidue:(r)=>{residue=r}})}catch(err){return{removed:!1,reason:errText(err)}}try{await deps.clearWorktreePath(task.id)}catch(err){return{removed:!0,reason:`worktree removed, but clearing the task's worktree path failed: ${errText(err)}`,...residue?{residue}:{}}}return{removed:!0,...residue?{residue}:{}}}function errText(err){return err instanceof Error?err.message:String(err)}async function conflictedFiles(exec,dir){return(await landGit(exec,dir,["diff","--name-only","--diff-filter=U"],{readOnly:!0})).stdout.split(`
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{engineEntry,identifiableEngineIds}from"./chunk-4gjvmfa9.js";import{recordSpawn}from"./chunk-40dgv828.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{basename}from"path";var WRAPPERS=new Set(["node","bun","npx","deno","sh","zsh","bash","env","script"]);function binaryName(token){return basename(token).replace(/\.(exe|js|mjs|cjs)$/,"")}function executableNameFromArgv(argv){for(let token of argv.slice(0,8)){if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))continue;let name=binaryName(token);if(WRAPPERS.has(name))continue;return name||null}return null}function vendorFromArgv(commandLine){let name=executableNameFromArgv(commandLine.trim().split(/\s+/));if(!name)return null;return identifiableEngineIds().find((v)=>{let entry=engineEntry(v);return entry.defaultCommand[0]===name||entry.processNames?.includes(name)===!0})??null}function parsePsSnapshot(text){let rows=[];for(let line of text.split(`
2
+ import{engineEntry,identifiableEngineIds}from"./chunk-hgtf6yvg.js";import{recordSpawn}from"./chunk-40dgv828.js";import{loadStateFile}from"./chunk-32j6y5d1.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{basename}from"path";var WRAPPERS=new Set(["node","bun","npx","deno","sh","zsh","bash","env","script"]);function binaryName(token){return basename(token).replace(/\.(exe|js|mjs|cjs)$/,"")}function executableNameFromArgv(argv){for(let token of argv.slice(0,8)){if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))continue;let name=binaryName(token);if(WRAPPERS.has(name))continue;return name||null}return null}function vendorFromArgv(commandLine){let name=executableNameFromArgv(commandLine.trim().split(/\s+/));if(!name)return null;return identifiableEngineIds().find((v)=>{let entry=engineEntry(v);return entry.defaultCommand[0]===name||entry.processNames?.includes(name)===!0})??null}function parsePsSnapshot(text){let rows=[];for(let line of text.split(`
3
3
  `)){let m=/^\s*(\d+)\s+(\d+)\s+(\S.*)$/.exec(line);if(m)rows.push({pid:Number(m[1]),ppid:Number(m[2]),args:m[3]})}return rows}function childrenIndex(rows){let kids=new Map;for(let row of rows){let list=kids.get(row.ppid);if(list)list.push(row);else kids.set(row.ppid,[row])}return kids}function hasAncestor(rows,pid,ancestorPid){let parents=new Map(rows.map((r)=>[r.pid,r.ppid])),cur=pid;for(let hops=0;hops<=rows.length;hops++){if(cur===ancestorPid)return!0;let next=parents.get(cur);if(next===void 0||next<=1)return!1;cur=next}return!1}function customEngineBinaries(){let state=loadStateFile(),ids=state.customEngineIds,out=new Map;if(!Array.isArray(ids))return out;for(let id of ids){if(typeof id!=="string"||id.trim().length===0)continue;let command=state[`engineCommand.${id}`],argv=typeof command==="string"&&command.trim().length>0?command.trim().split(/\s+/):[id],name=executableNameFromArgv(argv);if(name)out.set(name,id)}return out}function findDescendant(rows,rootPid,pick){let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]],visited=new Set;while(queue.length>0){let row=queue.shift();if(!row)break;if(visited.has(row.pid))continue;visited.add(row.pid);let hit=pick(row);if(hit!==null)return hit;queue.push(...kids.get(row.pid)??[])}return null}function walkDescendants(rows,rootPid,identify){return findDescendant(rows,rootPid,(row)=>{let vendor=identify(row.args);return vendor?{vendor,argv:row.args,pid:row.pid}:null})}function foregroundEngineIn(rows,rootPid){let builtin=walkDescendants(rows,rootPid,vendorFromArgv);if(builtin)return builtin;let custom=customEngineBinaries();if(custom.size===0)return null;return walkDescendants(rows,rootPid,(args)=>custom.get(executableNameFromArgv(args.trim().split(/\s+/))??"")??null)}function engineProcessIn(rows,rootPid,extraLaunch){if(foregroundEngineIn(rows,rootPid))return!0;let expected=extraLaunch?executableNameFromArgv(typeof extraLaunch==="string"?[extraLaunch]:extraLaunch):null;if(!expected)return!1;return findDescendant(rows,rootPid,(row)=>executableNameFromArgv(row.args.trim().split(/\s+/))===expected?!0:null)===!0}var PS_PROBE_TIMEOUT_MS=5000,bunPsSpawn=()=>{recordSpawn("engine.foregroundWalk",["ps","-A","-o","pid=,ppid=,args="]);let proc=Bun.spawn(["ps","-A","-o","pid=,ppid=,args="],{stdout:"pipe",stderr:"ignore"});return{text:new Response(proc.stdout).text(),kill:()=>proc.kill()}};async function psSnapshotWith(spawn,timeoutMs=PS_PROBE_TIMEOUT_MS){let proc=spawn(),timer;try{let text=await Promise.race([proc.text,new Promise((_resolve,reject)=>{timer=setTimeout(()=>{try{proc.kill()}catch{}reject(new PsProbeUnavailableError(`ps did not answer within ${timeoutMs}ms`))},timeoutMs)})]);if(parsePsSnapshot(text).length===0)throw new PsProbeUnavailableError("ps returned no usable rows");return text}finally{if(timer)clearTimeout(timer)}}var psSnapshot=async(anchors)=>{if(process.platform!=="win32")return psSnapshotWith(bunPsSpawn);let{defaultWinProcessProbe,winProcessSnapshot}=await import("./chunk-14f459aa.js");return winProcessSnapshot(anchors??[],defaultWinProcessProbe())};async function foregroundEngine(rootPid,snapshot=psSnapshot){try{return foregroundEngineIn(parsePsSnapshot(await snapshot([rootPid])),rootPid)}catch{return null}}
4
4
  export{vendorFromArgv,parsePsSnapshot,hasAncestor,foregroundEngineIn,engineProcessIn,PS_PROBE_TIMEOUT_MS,psSnapshotWith,psSnapshot,foregroundEngine};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-a5xbsvx2.js";import"./chunk-9vwb9f7q.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
2
+ import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-j8eejjw0.js";import"./chunk-zj7m55h0.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{launchTui,trackWelcomeWrite}from"./chunk-14tevt5v.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
2
+ import{launchTui,trackWelcomeWrite}from"./chunk-0b6mqb7z.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{loadPluginRegistry,readPluginManifest}from"./chunk-n0rdn2fn.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-hzz020xx.js";import{getCustomEngineIds}from"./chunk-rfp0ayra.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
2
+ import{loadPluginRegistry,readPluginManifest}from"./chunk-0sy3bez6.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-betn5ma1.js";import{getCustomEngineIds}from"./chunk-gygdyf0s.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
3
3
  export{loadPluginEngines,reloadPluginEngines,ensurePluginEnginesLoaded,registeredEngineIds};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{GitWorktreeManager}from"./chunk-3x5g06mw.js";import"./chunk-xmwp6je4.js";import"./chunk-1vxtd8rh.js";import"./chunk-gq36nzg8.js";import"./chunk-catrr0z3.js";import"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-rfp0ayra.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-40dgv828.js";import"./chunk-6xppe9bj.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{GitWorktreeManager};
2
+ import{GitWorktreeManager}from"./chunk-jkssty8x.js";import"./chunk-ee8917py.js";import"./chunk-gq36nzg8.js";import"./chunk-catrr0z3.js";import"./chunk-22emnsn5.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-gygdyf0s.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-40dgv828.js";import"./chunk-xmwp6je4.js";import"./chunk-6xppe9bj.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{GitWorktreeManager};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var TOP_LEVEL_SUBCOMMANDS=["completions","add","remove","adopt","export","repo","api","daemon","machine","weixin","doctor","config","reset","theme","skill","plugin","feedback","update"],SUBCOMMAND_VERBS={daemon:["status","start","stop","restart","relay"],machine:["add","doctor","remove","list","tunnel","inbound","primary"],plugin:["install","link","list","search","outdated","update","enable","disable","unlink","uninstall","config-dir","log","action","pane"],repo:["show","set","unset"],skill:["install","status","print"],theme:["list","add","remove"],weixin:["login","logout","status","allow","deny","send","agent"]};
3
+ export{TOP_LEVEL_SUBCOMMANDS,SUBCOMMAND_VERBS};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{getKeychainPassword,isKeychainSupported,remoteKeychainRef,setKeychainPassword}from"./chunk-sak1tphp.js";import{RemoteExecHost}from"./chunk-y1xnjx8x.js";import{addRemoteRepo,isRemoteProjectsEnabled}from"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import{errorMessage}from"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import{remoteControlSocketPath}from"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{createInterface}from"readline";var CLI_NAME=ROVE_PRODUCT_NAME,USAGE=`Usage: ${CLI_NAME} add --remote --host <host> --user <user> --path <basePath>
2
+ import{getKeychainPassword,isKeychainSupported,remoteKeychainRef,setKeychainPassword}from"./chunk-sak1tphp.js";import{RemoteExecHost}from"./chunk-y1xnjx8x.js";import{addRemoteRepo,isRemoteProjectsEnabled}from"./chunk-gygdyf0s.js";import"./chunk-40dgv828.js";import{errorMessage}from"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import{remoteControlSocketPath}from"./chunk-z1nj22va.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{createInterface}from"readline";var CLI_NAME=ROVE_PRODUCT_NAME,USAGE=`Usage: ${CLI_NAME} add --remote --host <host> --user <user> --path <basePath>
3
3
  [--port N] [--key [path] | --password]
4
4
 
5
5
  Register an experimental SSH-backed project. Worktrees are created on <host>
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{execHostForRepo,execHostForWorktreePath,localSpawnCwd,remoteKeyForRepo,remoteSpecFromConfig,worktreeUsable}from"./chunk-895yqjjz.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{worktreeUsable,remoteSpecFromConfig,remoteKeyForRepo,localSpawnCwd,execHostForWorktreePath,execHostForRepo};
2
+ import{execHostForRepo,execHostForWorktreePath,localSpawnCwd,remoteKeyForRepo,remoteSpecFromConfig,worktreeUsable}from"./chunk-22emnsn5.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-gygdyf0s.js";import"./chunk-40dgv828.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7kysxgbq.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{worktreeUsable,remoteSpecFromConfig,remoteKeyForRepo,localSpawnCwd,execHostForWorktreePath,execHostForRepo};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{detectLanguage}from"./chunk-hpay0ax8.js";import{REPO_CONFIG_DIRS,isNonEmptyRepoFile,readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{getRepoInitOverride}from"./chunk-rfp0ayra.js";import{existsSync}from"fs";import{join}from"path";var LOCKFILE_DEPENDENCY_DIRS=[["bun.lock","node_modules"],["bun.lockb","node_modules"],["package-lock.json","node_modules"],["yarn.lock","node_modules"],["pnpm-lock.yaml","node_modules"],["Cargo.lock","target"],["poetry.lock",".venv"],["uv.lock",".venv"]];function missingDependenciesCoda(worktreePath,language){let missing=new Set;for(let[lockfile,dependencyDir]of LOCKFILE_DEPENDENCY_DIRS){if(!existsSync(join(worktreePath,lockfile)))continue;if(existsSync(join(worktreePath,dependencyDir)))continue;missing.add(dependencyDir)}if(missing.size===0)return;let dirs=[...missing].join(", ");if(language==="zh")return`\u8865\u5145\uFF1A\u8FD9\u4E2A worktree \u6CA1\u6709\u88C5\u4F9D\u8D56\uFF08\u4ED3\u5E93\u91CC\u6709 lockfile\uFF0C\u4F46 ${dirs} \u4E0D\u5B58\u5728\uFF09\u3002\u5728\u76F8\u4FE1\u4EFB\u4F55\u6784\u5EFA / \u6D4B\u8BD5\u7ED3\u679C\u4E4B\u524D\uFF0C\u5148\u8DD1\u4E00\u904D\u672C\u4ED3\u5E93\u7684\u5B89\u88C5\u6B65\u9AA4\u2014\u2014\u8FD9\u91CC\u7684\u5931\u8D25\u591A\u534A\u662F\u56E0\u4E3A\u6CA1\u88C5\u4F9D\u8D56\uFF0C\u800C\u4E0D\u662F\u4EE3\u7801\u56DE\u5F52\u3002\u5982\u679C\u8FD9\u4E2A\u4ED3\u5E93\u6BCF\u6B21\u90FD\u9700\u8981\u88C5\uFF0C\u53EF\u4EE5\u8003\u8651\u52A0\u4E00\u4E2A \`.rove/init.sh\`\u3002`;return`PS: this worktree has no installed dependencies (${dirs} missing beside a committed lockfile). Run the repo's install step before trusting build/test results \u2014 a failure here is most likely the missing install, not a regression. If this repo always needs one, consider adding \`.rove/init.sh\`.`}var INIT_SCRIPT_FILENAME="init.sh",INIT_PROMPT_FILENAME="init-prompt.md";function repoFileScript(worktreePath){for(let dir of REPO_CONFIG_DIRS)if(existsSync(join(worktreePath,dir,INIT_SCRIPT_FILENAME)))return`sh ${dir}/${INIT_SCRIPT_FILENAME}`;return}function repoFilePrompt(worktreePath){return readFirstNonEmptyRepoFile(worktreePath,INIT_PROMPT_FILENAME)}function describeRepoInitSources(repoRoot){let describe=(filename,counts)=>{let taken=!1;return REPO_CONFIG_DIRS.map((dir)=>{let absolute=join(repoRoot,dir,filename),effective=!taken&&counts(absolute);if(effective)taken=!0;return{rel:`${dir}/${filename}`,present:existsSync(absolute),effective}})};return{script:describe(INIT_SCRIPT_FILENAME,existsSync),prompt:describe(INIT_PROMPT_FILENAME,isNonEmptyRepoFile)}}function resolveRepoInit(repoRoot,worktreePath){let override=repoRoot?getRepoInitOverride(repoRoot):{},initScript=repoFileScript(worktreePath)??override.initScript,initPrompt=repoFilePrompt(worktreePath)??override.initPrompt;return{initScript:initScript&&initScript.trim().length>0?initScript:void 0,initPrompt:initPrompt&&initPrompt.trim().length>0?initPrompt:void 0}}function firstMessageFor(intent,init,worktreePath){if(intent.kind==="none")return;if(intent.kind==="explicit")return{source:"explicit",text:intent.prompt};if(intent.kind==="new-task"){let deps=init.initScript?void 0:missingDependenciesCoda(worktreePath,detectLanguage(intent.prompt)??void 0);return{source:"explicit",text:[intent.prompt,deps].filter(Boolean).join(`
2
+ import{detectLanguage}from"./chunk-hpay0ax8.js";import{REPO_CONFIG_DIRS,isNonEmptyRepoFile,readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{getRepoInitOverride}from"./chunk-gygdyf0s.js";import{existsSync}from"fs";import{join}from"path";var LOCKFILE_DEPENDENCY_DIRS=[["bun.lock","node_modules"],["bun.lockb","node_modules"],["package-lock.json","node_modules"],["yarn.lock","node_modules"],["pnpm-lock.yaml","node_modules"],["Cargo.lock","target"],["poetry.lock",".venv"],["uv.lock",".venv"]];function missingDependenciesCoda(worktreePath,language){let missing=new Set;for(let[lockfile,dependencyDir]of LOCKFILE_DEPENDENCY_DIRS){if(!existsSync(join(worktreePath,lockfile)))continue;if(existsSync(join(worktreePath,dependencyDir)))continue;missing.add(dependencyDir)}if(missing.size===0)return;let dirs=[...missing].join(", ");if(language==="zh")return`\u8865\u5145\uFF1A\u8FD9\u4E2A worktree \u6CA1\u6709\u88C5\u4F9D\u8D56\uFF08\u4ED3\u5E93\u91CC\u6709 lockfile\uFF0C\u4F46 ${dirs} \u4E0D\u5B58\u5728\uFF09\u3002\u5728\u76F8\u4FE1\u4EFB\u4F55\u6784\u5EFA / \u6D4B\u8BD5\u7ED3\u679C\u4E4B\u524D\uFF0C\u5148\u8DD1\u4E00\u904D\u672C\u4ED3\u5E93\u7684\u5B89\u88C5\u6B65\u9AA4\u2014\u2014\u8FD9\u91CC\u7684\u5931\u8D25\u591A\u534A\u662F\u56E0\u4E3A\u6CA1\u88C5\u4F9D\u8D56\uFF0C\u800C\u4E0D\u662F\u4EE3\u7801\u56DE\u5F52\u3002\u5982\u679C\u8FD9\u4E2A\u4ED3\u5E93\u6BCF\u6B21\u90FD\u9700\u8981\u88C5\uFF0C\u53EF\u4EE5\u8003\u8651\u52A0\u4E00\u4E2A \`.rove/init.sh\`\u3002`;return`PS: this worktree has no installed dependencies (${dirs} missing beside a committed lockfile). Run the repo's install step before trusting build/test results \u2014 a failure here is most likely the missing install, not a regression. If this repo always needs one, consider adding \`.rove/init.sh\`.`}var INIT_SCRIPT_FILENAME="init.sh",INIT_PROMPT_FILENAME="init-prompt.md";function repoFileScript(worktreePath){for(let dir of REPO_CONFIG_DIRS)if(existsSync(join(worktreePath,dir,INIT_SCRIPT_FILENAME)))return`sh ${dir}/${INIT_SCRIPT_FILENAME}`;return}function repoFilePrompt(worktreePath){return readFirstNonEmptyRepoFile(worktreePath,INIT_PROMPT_FILENAME)}function describeRepoInitSources(repoRoot){let describe=(filename,counts)=>{let taken=!1;return REPO_CONFIG_DIRS.map((dir)=>{let absolute=join(repoRoot,dir,filename),effective=!taken&&counts(absolute);if(effective)taken=!0;return{rel:`${dir}/${filename}`,present:existsSync(absolute),effective}})};return{script:describe(INIT_SCRIPT_FILENAME,existsSync),prompt:describe(INIT_PROMPT_FILENAME,isNonEmptyRepoFile)}}function resolveRepoInit(repoRoot,worktreePath){let override=repoRoot?getRepoInitOverride(repoRoot):{},initScript=repoFileScript(worktreePath)??override.initScript,initPrompt=repoFilePrompt(worktreePath)??override.initPrompt;return{initScript:initScript&&initScript.trim().length>0?initScript:void 0,initPrompt:initPrompt&&initPrompt.trim().length>0?initPrompt:void 0}}function firstMessageFor(intent,init,worktreePath){if(intent.kind==="none")return;if(intent.kind==="explicit")return{source:"explicit",text:intent.prompt};if(intent.kind==="new-task"){let deps=init.initScript?void 0:missingDependenciesCoda(worktreePath,detectLanguage(intent.prompt)??void 0);return{source:"explicit",text:[intent.prompt,deps].filter(Boolean).join(`
3
3
 
4
4
  `)}}let text=init.initPrompt?.trim();return text?{source:"repo-init",text}:void 0}function resolveEngineLaunchInit(repoRoot,worktreePath,intent={kind:"repo-init"}){let init=resolveRepoInit(repoRoot,worktreePath);return{initScript:init.initScript,firstMessage:firstMessageFor(intent,init,worktreePath)}}
5
5
  export{missingDependenciesCoda,describeRepoInitSources,resolveRepoInit,resolveEngineLaunchInit};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{PreambleStripper}from"./chunk-sq6zj3fb.js";import{shQuote}from"./chunk-y1xnjx8x.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";import{RoveDaemonClient}from"./chunk-qzzmd63x.js";import{homeDir}from"./chunk-z1nj22va.js";import{logClientError}from"./chunk-0g4wc808.js";import{shortHomeTag}from"./chunk-eqdbfgq5.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-f8gg8cqh.js";import{spawn as spawn3}from"child_process";import{mkdirSync as mkdirSync3,rmSync as rmSync2}from"fs";import{connect as netConnect}from"net";import{tmpdir}from"os";import{join}from"path";var LOCAL_MACHINE_ID="local",ALIAS_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function isValidMachineAlias(alias){return alias!==LOCAL_MACHINE_ID&&alias.length<=64&&ALIAS_RE.test(alias)}function parseSshTarget(target){let trimmed=target.trim();if(!trimmed)return null;let at=trimmed.lastIndexOf("@"),user=at>=0?trimmed.slice(0,at):void 0,rest=at>=0?trimmed.slice(at+1):trimmed;if(at>=0&&!user)return null;let bracketed=/^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(rest),portMatch=bracketed?null:/^([^:]*):(\d{1,5})$/.exec(rest),host=bracketed?bracketed[1]??"":portMatch?portMatch[1]??"":rest,rawPort=bracketed?bracketed[2]:portMatch?.[2],port=rawPort?Number(rawPort):void 0;if(!host||/\s/.test(host))return null;if(port!==void 0&&(port<1||port>65535))return null;return{host,...user?{user}:{},...port?{port}:{}}}function defaultMachineAlias(args){let source=!args.typedUser&&args.port===void 0&&!isIpLiteral(args.typedHost)?args.typedHost:args.remoteHostname||args.typedHost;return sanitizeAlias(source)}function isIpLiteral(host){return host.includes(":")||/^\d{1,3}(\.\d{1,3}){3}$/.test(host)}function sanitizeAlias(raw){return(raw.split(".")[0]??raw).replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)}function sshTargetOf(config){return config.user?`${config.user}@${config.host}`:config.host}function readMachines(state){let raw=state.machines;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function listMachines(){let machines=readMachines(loadStateFile());return Object.entries(machines).map(([alias,config])=>({alias,...config}))}function getMachine(alias){return readMachines(loadStateFile())[alias]??null}function addMachine(alias,config){let added=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};added=machines[alias]===void 0,machines[alias]={...config,addedAt:config.addedAt??machines[alias]?.addedAt??new Date().toISOString()},state.machines=machines;return}),{added}}function updateMachine(alias,patch){updateStateFile((state)=>{let machines={...readMachines(state)},existing=machines[alias];if(!existing)return!1;machines[alias]={...existing,...patch},state.machines=machines;return})}function setMachineIdentity(alias,identity){updateMachine(alias,{identity})}function removeMachine(alias){let removed=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};if(removed=machines[alias]!==void 0,!removed)return!1;delete machines[alias],state.machines=machines;return}),removed}function dedupeMachines(entries){let kept=[],seen=[];for(let entry of entries){let identity=entry.identity;if(identity){if(seen.some((other)=>sameMachine(other,identity)))continue;seen.push(identity)}kept.push(entry)}return kept}function sameMachine(a,b){return a.hostname===b.hostname&&a.homeDir===b.homeDir&&a.daemonPid===b.daemonPid}function duplicateAliasOf(machines,self,identity){for(let[alias,config]of Object.entries(machines)){if(alias===self)continue;let other=config.identity;if(!other)continue;if(other.hostname===identity.hostname&&other.homeDir===identity.homeDir&&other.daemonPid===identity.daemonPid)return alias}return null}var CONTROL_PERSIST_SECONDS=300;function machineSocketDir(alias,home=homeDir()){let natural=join(home,".rove","machines",alias);if(Buffer.byteLength(join(natural,"daemon.sock"),"utf8")<=SOCKET_PATH_LIMIT)return natural;return join(tmpdir(),`rove-m-${shortHomeTag(home)}-${shortHomeTag(alias)}`)}var SOCKET_PATH_LIMIT=100;function localDaemonSocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"daemon.sock")}function localPtySocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"pty.sock")}function controlPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"cm")}function machineSshArgs(alias,config,opts={}){let argv=["ssh"];if(opts.batch!==!1)argv.push("-o","BatchMode=yes");if(opts.mux!==!1&&process.platform!=="win32")argv.push("-o","ControlMaster=auto","-o",`ControlPath=${controlPath(alias,opts.home)}`,"-o",`ControlPersist=${CONTROL_PERSIST_SECONDS}`);if(argv.push("-o","StrictHostKeyChecking=accept-new"),config.port)argv.push("-p",String(config.port));if(config.auth.kind==="key"&&config.auth.keyPath)argv.push("-i",config.auth.keyPath);return argv.push(sshTargetOf(config)),argv}import{spawn as spawn2}from"child_process";import{mkdirSync as mkdirSync2,rmSync}from"fs";import{createServer}from"net";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";function isWindowsPath(path){return/^[A-Za-z]:[\\/]/.test(path)||/^\\\\[.?]\\/.test(path)}function isWindowsMachine(config){if(config.sockets&&(isWindowsPath(config.sockets.daemon)||isWindowsPath(config.sockets.pty)))return!0;return config.roveBin!==void 0&&isWindowsPath(config.roveBin)}function psQuote(value){return`'${value.replaceAll("'","''")}'`}function powershellCommand(script){return`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function windowsRoveCommand(roveBin,args){return powershellCommand(`& ${psQuote(roveBin)} ${args.map(psQuote).join(" ")}; exit $LASTEXITCODE`)}var WINDOWS_LOCATE_SCRIPT=['$dirs = @("$env:APPDATA\\npm", "$env:USERPROFILE\\.bun\\bin", "$env:LOCALAPPDATA\\pnpm", $env:NVM_SYMLINK)',"$dirs += [Environment]::GetEnvironmentVariable('Path', 'User') -split ';'","foreach ($d in $dirs) { if (-not $d) { continue }",` foreach ($n in 'rove.cmd', 'rove.exe') { $p = Join-Path $d $n; if (Test-Path -LiteralPath $p) { "ROVE_BIN=$p"; exit 0 } } }`,"exit 1"].join(`
2
+ import{PreambleStripper}from"./chunk-sq6zj3fb.js";import{shQuote}from"./chunk-y1xnjx8x.js";import{loadStateFile,updateStateFile}from"./chunk-32j6y5d1.js";import{RoveDaemonClient}from"./chunk-8y10pmkf.js";import{homeDir}from"./chunk-z1nj22va.js";import{logClientError}from"./chunk-0g4wc808.js";import{shortHomeTag}from"./chunk-eqdbfgq5.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-f8gg8cqh.js";import{spawn as spawn3}from"child_process";import{mkdirSync as mkdirSync3,rmSync as rmSync2}from"fs";import{connect as netConnect}from"net";import{tmpdir}from"os";import{join}from"path";var LOCAL_MACHINE_ID="local",ALIAS_RE=/^[A-Za-z0-9][A-Za-z0-9._-]*$/;function isValidMachineAlias(alias){return alias!==LOCAL_MACHINE_ID&&alias.length<=64&&ALIAS_RE.test(alias)}function parseSshTarget(target){let trimmed=target.trim();if(!trimmed)return null;let at=trimmed.lastIndexOf("@"),user=at>=0?trimmed.slice(0,at):void 0,rest=at>=0?trimmed.slice(at+1):trimmed;if(at>=0&&!user)return null;let bracketed=/^\[([^\]]+)\](?::(\d{1,5}))?$/.exec(rest),portMatch=bracketed?null:/^([^:]*):(\d{1,5})$/.exec(rest),host=bracketed?bracketed[1]??"":portMatch?portMatch[1]??"":rest,rawPort=bracketed?bracketed[2]:portMatch?.[2],port=rawPort?Number(rawPort):void 0;if(!host||/\s/.test(host))return null;if(port!==void 0&&(port<1||port>65535))return null;return{host,...user?{user}:{},...port?{port}:{}}}function defaultMachineAlias(args){let source=!args.typedUser&&args.port===void 0&&!isIpLiteral(args.typedHost)?args.typedHost:args.remoteHostname||args.typedHost;return sanitizeAlias(source)}function isIpLiteral(host){return host.includes(":")||/^\d{1,3}(\.\d{1,3}){3}$/.test(host)}function sanitizeAlias(raw){return(raw.split(".")[0]??raw).replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)}function sshTargetOf(config){return config.user?`${config.user}@${config.host}`:config.host}function readMachines(state){let raw=state.machines;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function listMachines(){let machines=readMachines(loadStateFile());return Object.entries(machines).map(([alias,config])=>({alias,...config}))}function getMachine(alias){return readMachines(loadStateFile())[alias]??null}function addMachine(alias,config){let added=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};added=machines[alias]===void 0,machines[alias]={...config,addedAt:config.addedAt??machines[alias]?.addedAt??new Date().toISOString()},state.machines=machines;return}),{added}}function updateMachine(alias,patch){updateStateFile((state)=>{let machines={...readMachines(state)},existing=machines[alias];if(!existing)return!1;machines[alias]={...existing,...patch},state.machines=machines;return})}function setMachineIdentity(alias,identity){updateMachine(alias,{identity})}function removeMachine(alias){let removed=!1;return updateStateFile((state)=>{let machines={...readMachines(state)};if(removed=machines[alias]!==void 0,!removed)return!1;delete machines[alias],state.machines=machines;return}),removed}function dedupeMachines(entries){let kept=[],seen=[];for(let entry of entries){let identity=entry.identity;if(identity){if(seen.some((other)=>sameMachine(other,identity)))continue;seen.push(identity)}kept.push(entry)}return kept}function sameMachine(a,b){return a.hostname===b.hostname&&a.homeDir===b.homeDir&&a.daemonPid===b.daemonPid}function duplicateAliasOf(machines,self,identity){for(let[alias,config]of Object.entries(machines)){if(alias===self)continue;let other=config.identity;if(!other)continue;if(other.hostname===identity.hostname&&other.homeDir===identity.homeDir&&other.daemonPid===identity.daemonPid)return alias}return null}var CONTROL_PERSIST_SECONDS=300;function machineSocketDir(alias,home=homeDir()){let natural=join(home,".rove","machines",alias);if(Buffer.byteLength(join(natural,"daemon.sock"),"utf8")<=SOCKET_PATH_LIMIT)return natural;return join(tmpdir(),`rove-m-${shortHomeTag(home)}-${shortHomeTag(alias)}`)}var SOCKET_PATH_LIMIT=100;function localDaemonSocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"daemon.sock")}function localPtySocketPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"pty.sock")}function controlPath(alias,home=homeDir()){return join(machineSocketDir(alias,home),"cm")}function machineSshArgs(alias,config,opts={}){let argv=["ssh"];if(opts.batch!==!1)argv.push("-o","BatchMode=yes");if(opts.mux!==!1&&process.platform!=="win32")argv.push("-o","ControlMaster=auto","-o",`ControlPath=${controlPath(alias,opts.home)}`,"-o",`ControlPersist=${CONTROL_PERSIST_SECONDS}`);if(argv.push("-o","StrictHostKeyChecking=accept-new"),config.port)argv.push("-p",String(config.port));if(config.auth.kind==="key"&&config.auth.keyPath)argv.push("-i",config.auth.keyPath);return argv.push(sshTargetOf(config)),argv}import{spawn as spawn2}from"child_process";import{mkdirSync as mkdirSync2,rmSync}from"fs";import{createServer}from"net";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";function isWindowsPath(path){return/^[A-Za-z]:[\\/]/.test(path)||/^\\\\[.?]\\/.test(path)}function isWindowsMachine(config){if(config.sockets&&(isWindowsPath(config.sockets.daemon)||isWindowsPath(config.sockets.pty)))return!0;return config.roveBin!==void 0&&isWindowsPath(config.roveBin)}function psQuote(value){return`'${value.replaceAll("'","''")}'`}function powershellCommand(script){return`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function windowsRoveCommand(roveBin,args){return powershellCommand(`& ${psQuote(roveBin)} ${args.map(psQuote).join(" ")}; exit $LASTEXITCODE`)}var WINDOWS_LOCATE_SCRIPT=['$dirs = @("$env:APPDATA\\npm", "$env:USERPROFILE\\.bun\\bin", "$env:LOCALAPPDATA\\pnpm", $env:NVM_SYMLINK)',"$dirs += [Environment]::GetEnvironmentVariable('Path', 'User') -split ';'","foreach ($d in $dirs) { if (-not $d) { continue }",` foreach ($n in 'rove.cmd', 'rove.exe') { $p = Join-Path $d $n; if (Test-Path -LiteralPath $p) { "ROVE_BIN=$p"; exit 0 } } }`,"exit 1"].join(`
3
3
  `),WINDOWS_LOCATE_ROVE=powershellCommand(WINDOWS_LOCATE_SCRIPT),WINDOWS_ROVE_MISSING=/'(?:[^'\r\n]*[\\/])?rove(?:\.cmd|\.exe|\.ps1)?' is not recognized as (?:an internal or external command|(?:the|a) name of a cmdlet)/i,WINDOWS_SCRIPTS_DISABLED=/rove\.ps1 cannot be loaded because running scripts is disabled/i;function windowsNoRoveMessage(alias,output){if(WINDOWS_SCRIPTS_DISABLED.test(output))return[`${alias}'s ssh sessions run Windows PowerShell, whose execution policy refuses npm's rove.ps1, and no rove.cmd was found to use instead.`,`On ${alias}, either allow scripts for your user: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`,'or make ssh use PowerShell 7 (elevated): New-ItemProperty -Path HKLM:\\SOFTWARE\\OpenSSH -Name DefaultShell -Value "$env:ProgramFiles\\PowerShell\\7\\pwsh.exe" -PropertyType String -Force'].join(`
4
4
  `);return[`Rove is not on the PATH of ssh sessions on ${alias} (Windows), nor in %APPDATA%\\npm, ~\\.bun\\bin or the user PATH.`,"Install it there in a PowerShell: npm install -g @sma1lboy/rove",`If it is installed elsewhere, add that folder to your user PATH on ${alias}, then restart sshd (elevated: Restart-Service sshd) so new sessions see it.`].join(`
5
5
  `)}var WINDOWS_SSHD_BANNER=/remote software version OpenSSH_for_Windows/i,WINDOWS_SSHD_STEPS=["Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0","Set-Service sshd -StartupType Automatic; Start-Service sshd","if (-not (Get-NetFirewallRule -Name OpenSSH-Server-In-TCP -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name OpenSSH-Server-In-TCP -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 }"];function windowsAuthorizeKeySteps(publicKey){let key=psQuote(publicKey.trim());return["# Administrator account (elevated PowerShell):",`Add-Content -Path "$env:ProgramData\\ssh\\administrators_authorized_keys" -Value ${key}`,'icacls.exe "$env:ProgramData\\ssh\\administrators_authorized_keys" /inheritance:r /grant "*S-1-5-32-544:F" /grant "SYSTEM:F"',"# Standard account (normal PowerShell):",`New-Item -ItemType Directory -Force "$HOME\\.ssh" | Out-Null; Add-Content -Path "$HOME\\.ssh\\authorized_keys" -Value ${key}`]}var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target,windows=!1){if(windows&&(kind==="refused"||kind==="timeout"))return[`${target} (Windows) ${kind==="refused"?"refused the connection: its OpenSSH Server is not running":"did not answer on the ssh port: its OpenSSH Server is off, or the firewall drops it"}.`,"In an elevated PowerShell there:",...WINDOWS_SSHD_STEPS.map((step)=>` ${step}`)].join(`
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{NoopHookAdapter,activityHookAdapters,createEngineHookAdapter}from"./chunk-4gjvmfa9.js";import"./chunk-2tfnscxk.js";import"./chunk-hzz020xx.js";import"./chunk-w7zv47mp.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7bakcyes.js";import"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{createEngineHookAdapter,activityHookAdapters,NoopHookAdapter};
2
+ import{NoopHookAdapter,activityHookAdapters,createEngineHookAdapter}from"./chunk-hgtf6yvg.js";import"./chunk-2tfnscxk.js";import"./chunk-betn5ma1.js";import"./chunk-w7zv47mp.js";import"./chunk-gygdyf0s.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-7bakcyes.js";import"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{createEngineHookAdapter,activityHookAdapters,NoopHookAdapter};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ensurePluginEnginesLoaded,loadPluginEngines,registeredEngineIds,reloadPluginEngines}from"./chunk-kdnk8m5j.js";import"./chunk-n0rdn2fn.js";import"./chunk-j1z9kgyd.js";import"./chunk-hzz020xx.js";import"./chunk-w7zv47mp.js";import"./chunk-rfp0ayra.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-96kvwzj8.js";import"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{reloadPluginEngines,registeredEngineIds,loadPluginEngines,ensurePluginEnginesLoaded};
2
+ import{ensurePluginEnginesLoaded,loadPluginEngines,registeredEngineIds,reloadPluginEngines}from"./chunk-m2aqz600.js";import"./chunk-0sy3bez6.js";import"./chunk-j1z9kgyd.js";import"./chunk-betn5ma1.js";import"./chunk-w7zv47mp.js";import"./chunk-gygdyf0s.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-7mwvvj46.js";import"./chunk-32j6y5d1.js";import"./chunk-96kvwzj8.js";import"./chunk-8qkyd589.js";import"./chunk-7kysxgbq.js";import"./chunk-hz1x3hak.js";import"./chunk-x1jxxmtc.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-8t7qbr1e.js";import"./chunk-bejhca6z.js";import"./chunk-br8r72bf.js";import"./chunk-yt15y085.js";import"./chunk-z1nj22va.js";import"./chunk-zt7wfnva.js";import"./chunk-0g4wc808.js";import"./chunk-pn5ygqn6.js";import"./chunk-eqdbfgq5.js";import"./chunk-f8gg8cqh.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{reloadPluginEngines,registeredEngineIds,loadPluginEngines,ensurePluginEnginesLoaded};