@sma1lboy/rove 0.9.110 → 0.9.148

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 (194) hide show
  1. package/README.md +0 -1
  2. package/dist/cli/chunk-003tvywc.js +3 -0
  3. package/dist/cli/chunk-0b48bpkd.js +2 -0
  4. package/dist/cli/chunk-0dv2xssg.js +19 -0
  5. package/dist/cli/chunk-0sm2k04y.js +3 -0
  6. package/dist/cli/chunk-0vmrteyg.js +3 -0
  7. package/dist/cli/chunk-13s8rnk5.js +3 -0
  8. package/dist/cli/chunk-1kktfmtg.js +4 -0
  9. package/dist/cli/chunk-1rkb0j1j.js +3 -0
  10. package/dist/cli/chunk-1tx1s5v6.js +2 -0
  11. package/dist/cli/chunk-1x0vahnn.js +2 -0
  12. package/dist/cli/chunk-20pt9yqh.js +4 -0
  13. package/dist/cli/chunk-2brn8e1y.js +3 -0
  14. package/dist/cli/chunk-2fypr41w.js +3 -0
  15. package/dist/cli/chunk-2jxdzw4r.js +3 -0
  16. package/dist/cli/chunk-2pqqvse3.js +2 -0
  17. package/dist/cli/chunk-39s1ndtm.js +106 -0
  18. package/dist/cli/chunk-3bfm4hrs.js +3 -0
  19. package/dist/cli/chunk-3rqa4pyt.js +28 -0
  20. package/dist/cli/chunk-3ry6prwn.js +3 -0
  21. package/dist/cli/chunk-3ztek08w.js +4 -0
  22. package/dist/cli/chunk-49s2zc0h.js +8 -0
  23. package/dist/cli/chunk-4wwx51m5.js +3 -0
  24. package/dist/cli/chunk-5ar3vspk.js +9 -0
  25. package/dist/cli/chunk-5bn91n19.js +3 -0
  26. package/dist/cli/chunk-5c3d1y0r.js +2 -0
  27. package/dist/cli/chunk-5hhvrvgm.js +8 -0
  28. package/dist/cli/chunk-6dn6h640.js +3 -0
  29. package/dist/cli/chunk-6frfschk.js +2 -0
  30. package/dist/cli/chunk-6xppe9bj.js +3 -0
  31. package/dist/cli/chunk-6zwg6me2.js +4 -0
  32. package/dist/cli/chunk-764bsyb0.js +1 -0
  33. package/dist/cli/chunk-79gqh5p2.js +5 -0
  34. package/dist/cli/chunk-7ngv7v9g.js +9 -0
  35. package/dist/cli/chunk-7nhdvr5v.js +4 -0
  36. package/dist/cli/chunk-7pfnda5z.js +12 -0
  37. package/dist/cli/chunk-7q67dz4c.js +3 -0
  38. package/dist/cli/chunk-8ddjfc2v.js +4 -0
  39. package/dist/cli/chunk-8g456mmt.js +3 -0
  40. package/dist/cli/chunk-8sbevss4.js +4 -0
  41. package/dist/cli/chunk-91j0an0j.js +2 -0
  42. package/dist/cli/chunk-99devyxr.js +2 -0
  43. package/dist/cli/chunk-9c1e5z6a.js +3 -0
  44. package/dist/cli/chunk-a4a4qaa2.js +3 -0
  45. package/dist/cli/chunk-adez6hq4.js +69 -0
  46. package/dist/cli/chunk-aq912vvw.js +3 -0
  47. package/dist/cli/chunk-arf294te.js +2 -0
  48. package/dist/cli/chunk-awsawfrm.js +2 -0
  49. package/dist/cli/chunk-aynx3d2a.js +2 -0
  50. package/dist/cli/chunk-b8d162tf.js +3 -0
  51. package/dist/cli/chunk-b99tf0jr.js +3 -0
  52. package/dist/cli/chunk-bj59a9mg.js +3 -0
  53. package/dist/cli/chunk-c6mthex1.js +5 -0
  54. package/dist/cli/chunk-cb2fpajx.js +3 -0
  55. package/dist/cli/chunk-cbkje3aw.js +2 -0
  56. package/dist/cli/chunk-df7qe9y7.js +4 -0
  57. package/dist/cli/chunk-dkxhmj9k.js +25 -0
  58. package/dist/cli/chunk-dqndd97s.js +7 -0
  59. package/dist/cli/chunk-dvabncrk.js +7 -0
  60. package/dist/cli/chunk-dvcb6mk4.js +3 -0
  61. package/dist/cli/chunk-dw853n4w.js +3 -0
  62. package/dist/cli/chunk-dx6b3dv8.js +7 -0
  63. package/dist/cli/chunk-e1g9mvww.js +11 -0
  64. package/dist/cli/chunk-ef11h2am.js +3 -0
  65. package/dist/cli/chunk-ef39ym8f.js +3 -0
  66. package/dist/cli/chunk-eq5f3z2f.js +3 -0
  67. package/dist/cli/chunk-ewdhz3dv.js +2 -0
  68. package/dist/cli/chunk-f6zsej8e.js +3 -0
  69. package/dist/cli/chunk-g1ybdgad.js +25 -0
  70. package/dist/cli/chunk-gbasmvsc.js +4 -0
  71. package/dist/cli/chunk-gjf604bb.js +3 -0
  72. package/dist/cli/chunk-gm3vj0fv.js +5 -0
  73. package/dist/cli/chunk-grh6dvfv.js +5 -0
  74. package/dist/cli/chunk-gwcneg6c.js +2 -0
  75. package/dist/cli/chunk-h5j8b87f.js +2 -0
  76. package/dist/cli/chunk-h79zfebh.js +7 -0
  77. package/dist/cli/chunk-h82kzdsn.js +3 -0
  78. package/dist/cli/chunk-hape5vwj.js +3 -0
  79. package/dist/cli/chunk-hg5x2wr0.js +3 -0
  80. package/dist/cli/chunk-j4xfsn9g.js +5 -0
  81. package/dist/cli/chunk-jfqbq12b.js +18 -0
  82. package/dist/cli/chunk-jsss3ze7.js +11 -0
  83. package/dist/cli/chunk-jvpzy378.js +3 -0
  84. package/dist/cli/chunk-jvxh93nz.js +3 -0
  85. package/dist/cli/chunk-jyv82gf0.js +258 -0
  86. package/dist/cli/chunk-k3ksts6g.js +3 -0
  87. package/dist/cli/chunk-kdrrw9tm.js +2 -0
  88. package/dist/cli/chunk-kg11c1py.js +3 -0
  89. package/dist/cli/chunk-kwe61yx7.js +3 -0
  90. package/dist/cli/chunk-m0fz6g32.js +16 -0
  91. package/dist/cli/chunk-mb5m7ex7.js +2 -0
  92. package/dist/cli/chunk-me77sx3d.js +3 -0
  93. package/dist/cli/chunk-mfqjdpd8.js +2 -0
  94. package/dist/cli/chunk-mggca3k4.js +4 -0
  95. package/dist/cli/chunk-mjvq39gf.js +4 -0
  96. package/dist/cli/chunk-mrwee8sj.js +3 -0
  97. package/dist/cli/chunk-my20q579.js +3 -0
  98. package/dist/cli/chunk-nceh1q3d.js +12 -0
  99. package/dist/cli/chunk-ncsgawg7.js +2 -0
  100. package/dist/cli/chunk-nm6adny4.js +4 -0
  101. package/dist/cli/chunk-np07kccr.js +4 -0
  102. package/dist/cli/chunk-nrnjt5b6.js +2 -0
  103. package/dist/cli/chunk-p7kztgsd.js +4 -0
  104. package/dist/cli/chunk-pbqwegjy.js +2 -0
  105. package/dist/cli/chunk-pcvk98rr.js +3 -0
  106. package/dist/cli/chunk-pdh5w4ht.js +3 -0
  107. package/dist/cli/chunk-pdj8kqa1.js +74 -0
  108. package/dist/cli/chunk-pw6yfj10.js +3 -0
  109. package/dist/cli/chunk-q6579rbz.js +3 -0
  110. package/dist/cli/chunk-q7dr9eh6.js +3 -0
  111. package/dist/cli/chunk-qkehg2c1.js +3 -0
  112. package/dist/cli/chunk-qtke4x42.js +3 -0
  113. package/dist/cli/chunk-rxvbm4vt.js +7 -0
  114. package/dist/cli/chunk-s66eh0pw.js +8 -0
  115. package/dist/cli/chunk-s76r56rj.js +3 -0
  116. package/dist/cli/chunk-sdyzxayr.js +3 -0
  117. package/dist/cli/chunk-svpn3av1.js +3 -0
  118. package/dist/cli/chunk-t0kta7rb.js +5 -0
  119. package/dist/cli/chunk-v5893dx3.js +2 -0
  120. package/dist/cli/chunk-vapjtyv9.js +7 -0
  121. package/dist/cli/chunk-vpzvcxc1.js +3 -0
  122. package/dist/cli/chunk-vqpa27cf.js +15 -0
  123. package/dist/cli/chunk-vws0j65e.js +4 -0
  124. package/dist/cli/chunk-vyb5a2rh.js +4 -0
  125. package/dist/cli/chunk-vzxbe80f.js +7 -0
  126. package/dist/cli/chunk-w5xy83ze.js +2 -0
  127. package/dist/cli/chunk-wqfp8d9w.js +3 -0
  128. package/dist/cli/chunk-wsvf9eka.js +33 -0
  129. package/dist/cli/chunk-x760j10f.js +3 -0
  130. package/dist/cli/chunk-x930m5fs.js +2 -0
  131. package/dist/cli/chunk-xbc3gcry.js +2 -0
  132. package/dist/cli/chunk-xy8be792.js +3 -0
  133. package/dist/cli/chunk-xzrqnpmh.js +4 -0
  134. package/dist/cli/chunk-y2yq6zca.js +3 -0
  135. package/dist/cli/chunk-yhcz2d2r.js +34 -0
  136. package/dist/cli/chunk-yk2ha5yj.js +3 -0
  137. package/dist/cli/chunk-ykvk2546.js +3 -0
  138. package/dist/cli/chunk-ympakh8w.js +6 -0
  139. package/dist/cli/chunk-yn5a7xcv.js +2 -0
  140. package/dist/cli/chunk-zb56ck5f.js +3 -0
  141. package/dist/cli/index.js +15 -850
  142. package/dist/cli/kobe-run.js +1 -858
  143. package/dist/cli/kobe.js +6 -6
  144. package/dist/cli/pty-host-node.mjs +167 -50
  145. package/dist/cli/rove-run.js +1 -858
  146. package/dist/cli/rove.js +6 -6
  147. package/dist/skills/rove/SKILL.md +29 -10
  148. package/dist/skills/rove/references/api-flags.md +35 -13
  149. package/dist/web-ui/assets/{ChatTerminal-BshL3M8G.js → harness-CYGJ4uoR.js} +19 -20
  150. package/dist/web-ui/assets/index-BTJ-X_4s.js +10 -0
  151. package/dist/web-ui/assets/index-Cs2vPLNB.css +1 -0
  152. package/dist/web-ui/index.html +2 -9
  153. package/dist/web-ui/pty-server.mjs +4 -5
  154. package/package.json +1 -1
  155. package/dist/web-ui/assets/AppShell-BGRIs5hW.js +0 -5
  156. package/dist/web-ui/assets/AppShell-HiyATJse.css +0 -1
  157. package/dist/web-ui/assets/Board-Bt3cwp25.js +0 -1
  158. package/dist/web-ui/assets/BoardPeek-BKR-tpS2.js +0 -2
  159. package/dist/web-ui/assets/ChatTranscript-B67_nnd6.js +0 -1
  160. package/dist/web-ui/assets/ConfirmDialog-kyA624OF.js +0 -1
  161. package/dist/web-ui/assets/IssueIntakePanel-BMP8Vc3E.js +0 -1
  162. package/dist/web-ui/assets/IssuePeek-C7afOYax.js +0 -1
  163. package/dist/web-ui/assets/IssuesPage-DwRaBB-m.js +0 -1
  164. package/dist/web-ui/assets/SettingsPage-CC1sDI8j.js +0 -2
  165. package/dist/web-ui/assets/SlideOver-B4sEOPyN.css +0 -1
  166. package/dist/web-ui/assets/SlideOver-Dq0ifiEm.js +0 -173
  167. package/dist/web-ui/assets/ViewToggle-mNsDLJp8.js +0 -1
  168. package/dist/web-ui/assets/WorkspaceTabs-DLzL-Tad.css +0 -1
  169. package/dist/web-ui/assets/WorkspaceTabs-ifAIZ5Fj.js +0 -3
  170. package/dist/web-ui/assets/active-task-gVYiAkLv.js +0 -1
  171. package/dist/web-ui/assets/arrow-left-CavMh90a.js +0 -1
  172. package/dist/web-ui/assets/board-DoArj55z.js +0 -1
  173. package/dist/web-ui/assets/chips-CS9PLtWy.js +0 -1
  174. package/dist/web-ui/assets/createLucideIcon-CuIQtyYV.js +0 -1
  175. package/dist/web-ui/assets/external-link-Du2dMe8S.js +0 -1
  176. package/dist/web-ui/assets/external-store-BCBJewGi.js +0 -1
  177. package/dist/web-ui/assets/harness-ClZMF1wx.js +0 -1
  178. package/dist/web-ui/assets/index-B4xJZEqf.js +0 -10
  179. package/dist/web-ui/assets/index-BnjD9Q-3.css +0 -1
  180. package/dist/web-ui/assets/issues-DwrKXp9c.js +0 -4
  181. package/dist/web-ui/assets/issues-ISAZBras.js +0 -1
  182. package/dist/web-ui/assets/lazy-issue-panels-DvXQJhKy.js +0 -6
  183. package/dist/web-ui/assets/rotate-cw-BXdpzm3v.js +0 -1
  184. package/dist/web-ui/assets/routes-DEEkL5gG.js +0 -1
  185. package/dist/web-ui/assets/store-BLM6nh6E.js +0 -2
  186. package/dist/web-ui/assets/tabs-CMZJhcSB.js +0 -1
  187. package/dist/web-ui/assets/task._taskId-BCIhg4IQ.js +0 -1
  188. package/dist/web-ui/assets/terminal-DOp1a9g6.js +0 -1
  189. package/dist/web-ui/assets/text-match-DW3sD-Rt.js +0 -1
  190. package/dist/web-ui/assets/time-kviT26Tm.js +0 -1
  191. package/dist/web-ui/assets/toast-C4yXq6hM.js +0 -1
  192. package/dist/web-ui/assets/web-transport-Beqz2mQ8.js +0 -1
  193. package/dist/web-ui/assets/worktrees-BGvJOG2b.js +0 -1
  194. /package/dist/web-ui/assets/{ChatTerminal-BrP-ENHg.css → harness-BrP-ENHg.css} +0 -0
@@ -0,0 +1,18 @@
1
+ // @bun
2
+ import{formatBytes}from"./chunk-my20q579.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,probeEngines,probeGit,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-bj59a9mg.js";import"./chunk-np07kccr.js";import"./chunk-0dv2xssg.js";import"./chunk-mrwee8sj.js";import"./chunk-q6579rbz.js";import"./chunk-hg5x2wr0.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-dqndd97s.js";import"./chunk-ympakh8w.js";import{kobeSkillState,skillInstallCommand}from"./chunk-g1ybdgad.js";import"./chunk-vyb5a2rh.js";import"./chunk-jyv82gf0.js";import{CURRENT_VERSION,package_default}from"./chunk-eq5f3z2f.js";import{resolveNodeBinary}from"./chunk-20pt9yqh.js";import"./chunk-q7dr9eh6.js";import"./chunk-jvxh93nz.js";import"./chunk-b99tf0jr.js";import{t}from"./chunk-b8d162tf.js";import"./chunk-8g456mmt.js";import"./chunk-sdyzxayr.js";import{isStaleInstallError,resolveKobeSpawn}from"./chunk-5bn91n19.js";import"./chunk-pdh5w4ht.js";import{readPidFile}from"./chunk-4wwx51m5.js";import{KobeDaemonClient}from"./chunk-79gqh5p2.js";import{isForeignDaemonHome}from"./chunk-3ztek08w.js";import"./chunk-kwe61yx7.js";import"./chunk-gbasmvsc.js";import"./chunk-yhcz2d2r.js";import"./chunk-df7qe9y7.js";import"./chunk-gwcneg6c.js";import"./chunk-7nhdvr5v.js";import"./chunk-2fypr41w.js";import"./chunk-k3ksts6g.js";import"./chunk-gjf604bb.js";import{readableLegacyIndexPath}from"./chunk-qtke4x42.js";import"./chunk-xy8be792.js";import"./chunk-2brn8e1y.js";import"./chunk-9c1e5z6a.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-6dn6h640.js";import"./chunk-h82kzdsn.js";import{activeCliName}from"./chunk-ef11h2am.js";import"./chunk-8ddjfc2v.js";import{LEGACY_KOBE_STATE_DIR_BASENAME}from"./chunk-cb2fpajx.js";import"./chunk-grh6dvfv.js";import"./chunk-pw6yfj10.js";import"./chunk-yk2ha5yj.js";import"./chunk-rxvbm4vt.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-x760j10f.js";import"./chunk-3bfm4hrs.js";import{__require}from"./chunk-wqfp8d9w.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)"];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`KOBE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{readFileSync}from"fs";var PTY_MARKER="KOBE_TERMINAL_PTY=1";async function run(argv){try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}}function parsePsRows(output){let rows=[];for(let line of output.split(`
3
+ `)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids){let marked=new Set;if(pids.length===0)return marked;if(process.platform==="linux"){for(let pid of pids)try{if(readFileSync(`/proc/${pid}/environ`,"utf8").split("\x00").includes(PTY_MARKER))marked.add(pid)}catch{}return marked}let result=await run(["ps","eww","-o","pid=,command=","-p",pids.join(",")]),marker=new RegExp(`(^|\\s)${PTY_MARKER}(\\s|$)`);for(let line of result.stdout.split(`
4
+ `)){let pid=Number.parseInt(line.trim().split(/\s+/)[0]??"",10);if(Number.isFinite(pid)&&marker.test(line))marked.add(pid)}return marked}async function ownPgid(){let result=await run(["ps","-o","pgid=","-p",String(process.pid)]),pgid=Number.parseInt(result.stdout.trim(),10);return Number.isFinite(pgid)?pgid:-1}async function collectOrphans(liveSessionPids){if(process.platform==="win32")return{orphans:[],error:null};let ps=await run(["ps","-A","-o","pid=,ppid=,pgid=,etime=,rss=,command="]);if(ps.code!==0)return{orphans:[],error:`ps exited ${ps.code}`};let rows=parsePsRows(ps.stdout),candidates=orphanCandidates(rows,await ownPgid(),liveSessionPids),marked=await markedPids(candidates.map((row)=>row.pid));return{orphans:candidates.filter((row)=>marked.has(row.pid)),error:null}}function formatMb(rssKb){return`${(rssKb/1024).toFixed(0)} MB`}function orphanDoctorLines(orphans,error,cliName,killing=!1){if(error)return[`orphans: \u2717 could not inspect the process table \u2014 ${error}`];if(orphans.length===0)return["orphans: \u2713 none \u2014 no processes left behind by a dead PTY session"];let totalMb=orphans.reduce((sum,row)=>sum+row.rssKb,0)/1024,lines=[`orphans: \u26A0 ${orphans.length} process(es) outlived the PTY session that spawned them (${totalMb.toFixed(0)} MB RSS)`," each is reparented to init, carries Rove's PTY marker, and its process"," group leader is gone \u2014 no live task owns them"];for(let row of[...orphans].sort((a,b)=>b.rssKb-a.rssKb))lines.push(` pid ${row.pid} (group ${row.pgid}) up ${row.etime}, ${formatMb(row.rssKb)}: ${row.command.slice(0,90)}`);if(!killing)lines.push(` \u2192 \`${cliName} doctor --kill-orphans\` ends those process groups (SIGTERM, then SIGKILL)`," read the list first: something you backgrounded from a Rove terminal and then"," closed the tab on looks exactly like a leak, and doctor cannot tell them apart");return lines}var GROUP_EXIT_GRACE_MS=2000,GROUP_POLL_MS=100;function groupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(err){return err.code!=="ESRCH"}}async function killOrphanGroups(orphans){let groups=[...new Set(orphans.map((row)=>row.pgid))];for(let pgid of groups)try{process.kill(-pgid,"SIGTERM")}catch{}let deadline=Date.now()+GROUP_EXIT_GRACE_MS,survivors=groups.filter(groupAlive);while(survivors.length>0&&Date.now()<deadline)await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),survivors=survivors.filter(groupAlive);for(let pgid of survivors)try{process.kill(-pgid,"SIGKILL")}catch{}return await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),{groups,survivors:survivors.filter(groupAlive)}}function multiplexerLabel(env){if(env.TMUX)return"tmux";if(env.ZELLIJ)return"zellij";if(env.STY)return"screen";return"no"}function terminalEnvLines(env){let show=(v)=>v&&v.length>0?v:"(unset)",program=env.TERM_PROGRAM?`${env.TERM_PROGRAM}${env.TERM_PROGRAM_VERSION?` v${env.TERM_PROGRAM_VERSION}`:""}`:"(unset)";return[`terminal: TERM=${show(env.TERM)} TERM_PROGRAM=${program} COLORTERM=${show(env.COLORTERM)}`,` running inside a multiplexer: ${multiplexerLabel(env)}`]}function parseKittyProbeReply(data){let kitty=data.match(/\x1b\[\?(\d+)u/);if(kitty?.[1]!==void 0)return{kind:"supported",flags:Number.parseInt(kitty[1],10)};if(/\x1b\[\?[\d;]*c/.test(data))return{kind:"unsupported"};return null}function kittyProbeLine(result){switch(result.kind){case"supported":return` kitty keyboard protocol: \u2713 answered (flags=${result.flags})`;case"unsupported":return[" kitty keyboard protocol: \u2717 not supported \u2014 legacy key path"," (ctrl+h/ctrl+j arrive as C0 backspace/linefeed bytes; the"," split chords ctrl+\\ and ctrl+= cannot be encoded at all)"].join(`
5
+ `);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}var CLI_NAME=activeCliName();function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new KobeDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(readFileSync2(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function tailFile(path,count){try{return readFileSync2(path,"utf8").split(`
6
+ `).filter((line)=>line.trim().length>0).slice(-count).join(`
7
+ `)}catch{return""}}function describeInstall(){try{let[,entry]=resolveKobeSpawn([]);return{line:`install: \u2713 ${entry??process.execPath}`,ok:!0}}catch(err){if(!isStaleInstallError(err))return{line:`install: ? could not check (${String(err)})`,ok:!0};return{line:["install: \u2717 GONE \u2014 this process is running from an install that no longer exists on disk"," it cannot start a daemon; every reconnect fails the same way until you reinstall"," \u2192 npm install -g @sma1lboy/rove (then relaunch Rove)"].join(`
8
+ `),ok:!1}}}async function appendUnavailableProcess(out,label,pidPath,socketPath){let pid=await readPidFile(pidPath),wedged=pid!==null&&pid!==void 0&&isProcessAlive(pid);if(wedged)out.push(`${label}: \u2717 WEDGED \u2014 process alive (pid ${pid}) but socket is unreachable`);else if(pid)out.push(`${label}: \u2717 not running (stale pidfile \u2192 pid ${pid} is gone)`);else out.push(`${label}: \u2717 not running (no pidfile)`);if(existsSync(socketPath))out.push(` orphan socket file present: ${socketPath}`);return wedged?"wedged":"down"}async function collectDoctor(){let daemonSocket=defaultDaemonSocketPath(),daemonLog=defaultDaemonLogPath(),ptySocket=defaultPtyHostSocketPath(),ptyLog=defaultPtyHostLogPath(),canonicalTasks=join2(roveStateDir(),"tasks.json"),legacyTasks=join2(homeDir(),LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),readableLegacy=readableLegacyIndexPath(canonicalTasks,legacyTasks),usingLegacyTasks=!existsSync(canonicalTasks)&&readableLegacy!==void 0&&existsSync(readableLegacy),tasksPath=usingLegacyTasks?legacyTasks:canonicalTasks,statePath=kvStatePath(),fixes=[],git=await probeGit();if(!git.found)fixes.push(humanOnlyFix("git"));let engines=await probeEngines();if(!engines.anyUsable)fixes.push(noEngineFix(engines.signedOut));let install=describeInstall();if(!install.ok)fixes.push(reinstallManualFix());let staleBun=!isBunAtLeast(Bun.version);if(staleBun)fixes.push(humanOnlyFix("staleBun"));let out=["Rove doctor",` build: v${CURRENT_VERSION} (${process.platform} ${process.arch}, bun ${Bun.version})`,...staleBun?[` \u26A0 bun ${Bun.version} is below the ${MIN_BUN_VERSION} Rove needs \u2014 terminals will not paint`]:[],` home: ${homeDir()}`,"",...await terminalDoctorLines(),git.line,"",...engines.lines,"",install.line,""],daemon=await requestIfReachable(daemonSocket,"daemon.status");if(daemon){let pid=typeof daemon.daemonPid==="number"?daemon.daemonPid:"?",uptime=typeof daemon.uptimeMs==="number"?fmtDuration(daemon.uptimeMs):"?",tasks=typeof daemon.taskCount==="number"?daemon.taskCount:"?",clients=typeof daemon.attachedClients==="number"?daemon.attachedClients:"?";out.push(`daemon: \u2713 running (pid ${pid}, up ${uptime}, ${tasks} task(s), ${clients} client(s))`);let version=typeof daemon.kobeVersion==="string"?daemon.kobeVersion:void 0;if(version&&version!==CURRENT_VERSION)out.push(` \u26A0 stale build: daemon is v${version}, you launched v${CURRENT_VERSION}`),out.push(` \u2192 run \`${CLI_NAME} daemon restart\`, then relaunch Rove`),fixes.push(daemonRestartFix(CLI_NAME,"daemonStale"));else if(version)out.push(` build: v${version}`);if(isForeignDaemonHome(typeof daemon.homeDir==="string"?daemon.homeDir:void 0,homeDir()))out.push(` \u26A0 foreign home: daemon serves ${String(daemon.homeDir)}, you are reading ${homeDir()}`),out.push(` \u2192 clear ROVE_HOME_DIR/KOBE_HOME_DIR, then \`${CLI_NAME} daemon restart\``);let tabs=(await requestIfReachable(daemonSocket,"debug.inspect"))?.activity?.tabs;if(tabs){let hookInput={socketPath:daemonSocket},verdict=classifyHookChannel({tabs,...hookInput});if(out.push("",...hookChannelDoctorLines(verdict,hookInput,CLI_NAME)),verdict.kind==="down")fixes.push(daemonRestartFix(CLI_NAME,"hooksDown"),engineTabsManualFix())}else out.push("","hooks: ? could not read the daemon's activity registry (debug.inspect unavailable)"),fixes.push(daemonRestartFix(CLI_NAME,"inspectStale"))}else{let state=await appendUnavailableProcess(out,"daemon ",defaultDaemonPidPath(),daemonSocket);fixes.push(state==="wedged"?resetManualFix(CLI_NAME,"resetDaemonWedged"):daemonRestartFix(CLI_NAME,"daemonDown"));let tail=tailFile(daemonLog,8);if(tail){out.push(" last lines of daemon.log:");for(let line of tail.split(`
9
+ `))out.push(` \u2502 ${line}`)}}out.push("");let inventory=await requestIfReachable(ptySocket,"pty.list");if(inventory){let sessions=inventory.sessions??[],parked=inventory.stats?.parkedSessions??sessions.filter((session)=>session.parked).length;if(out.push(`pty host: \u2713 running (${sessions.length} session(s), ${sessions.filter((session)=>session.alive).length} live, ${parked} parked)`),typeof inventory.pid==="number"&&typeof inventory.rssBytes==="number")out.push(` pid ${inventory.pid}, ${formatBytes(inventory.rssBytes)} RSS`);let stats=inventory.stats;if(stats&&typeof stats.ringBytes==="number"&&typeof stats.ringCapacityBytes==="number")out.push(` ring: ${formatBytes(stats.ringBytes)} / ${formatBytes(stats.ringCapacityBytes)}`);if(stats&&typeof stats.parkedScreenBytes==="number")out.push(` parked screens: ${formatBytes(stats.parkedScreenBytes)}`);if(stats&&typeof stats.parkRestoreDeltas==="number"&&typeof stats.parkRestoreFallbacks==="number")out.push(` park wakes: ${stats.parkRestoreDeltas} delta, ${stats.parkRestoreFallbacks} full replay fallback`)}else if(await appendUnavailableProcess(out,"pty host",defaultPtyHostPidPath(),ptySocket)==="wedged")fixes.push(resetManualFix(CLI_NAME,"resetPty"));else out.push(" starts on demand \u2014 the first task tab launches it; nothing to fix");if(process.platform==="win32"){let node=resolveNodeBinary();if(out.push(node?` node: \u2713 ${node} (the Windows PTY host runs under it)`:` node: \u2717 not found on PATH \u2014 the Windows PTY host cannot start
10
+ \u2192 install Node.js from https://nodejs.org`),!node)fixes.push(humanOnlyFix("windowsNode"))}if(process.platform==="darwin"){let helpers=spawnHelperDoctorLines(installedSpawnHelpers());if(out.push(...helpers.lines),helpers.broken.length>0)fixes.push(spawnHelperFix(helpers.broken))}out.push("");let liveSessionPids=new Set;for(let session of inventory?.sessions??[])if(session.alive&&typeof session.pid==="number")liveSessionPids.add(session.pid);let orphaned=await collectOrphans(liveSessionPids);if(out.push(...orphanDoctorLines(orphaned.orphans,orphaned.error,CLI_NAME),""),orphaned.orphans.length>0)fixes.push(killOrphansManualFix(CLI_NAME,orphaned.orphans.length));let legacy=await inspectLegacyTmux();if(out.push(...legacyTmuxDoctorLines(legacy),""),legacy.sessions.length>0)fixes.push(resetManualFix(CLI_NAME,"resetLegacy"));let skill=kobeSkillState(),installCommand=skillInstallCommand();if(!skill.installed)out.push("skill: \u2717 Rove agent skill not installed",` \u2192 ${installCommand}`),fixes.push(skillInstallFix(installCommand,!1));else if(skill.stale){let installed=skill.installedVersion===null?"unstamped":`v${skill.installedVersion}`;out.push(`skill: \u26A0 Rove agent skill out of date (${installed}; this Rove wants v${skill.currentVersion})`),out.push(` \u2192 ${installCommand}`),fixes.push(skillInstallFix(installCommand,!0))}else out.push(`skill: \u2713 Rove agent skill installed (v${skill.installedVersion})`);out.push("");let count=taskCount(tasksPath);return out.push(`tasks.json: ${describeFile(tasksPath)}${count===null?"":` \u2014 ${count} task(s)`}${usingLegacyTasks?` (legacy ${tasksPath}, not yet migrated)`:""}`),out.push(`state.json: ${describeFile(statePath)}`),out.push(`daemon.log: ${describeFile(daemonLog)}`),out.push(`pty.log: ${describeFile(ptyLog)}`),{lines:out,fixes,orphans:orphaned.orphans}}async function sweepOrphans(orphans){if(orphans.length===0)return["orphans: nothing to kill"];let{groups,survivors}=await killOrphanGroups(orphans),lines=[`orphans: signalled ${groups.length} process group(s) covering ${orphans.length} process(es)`];if(survivors.length>0)lines.push(` \u2717 still alive after SIGKILL: group(s) ${survivors.join(", ")} \u2014 inspect with \`ps -g <pgid>\``);else lines.push(" \u2713 all of them are gone");return lines}async function runDoctorSubcommand(argv=[]){if(argv.some((arg)=>arg==="--help"||arg==="-h"||arg==="help")){process.stdout.write([`Usage: ${CLI_NAME} doctor [--report] [--fix] [--kill-orphans]`,"","Read-only diagnosis of the daemon / Hosted PTY / engines / git / legacy tmux / state.","","Options:"," --report Also write a bug bundle (diagnosis + recent logs + env) to a file"," --fix Review the fixes one by one: safe ones run after a per-fix y/N,"," risky ones (kill sessions, install software) are printed only"," --kill-orphans End the process groups listed under `orphans:` (SIGTERM, then"," SIGKILL). Not undoable \u2014 run plain `doctor` and read the list first"," -h, --help Print this help",""].join(`
11
+ `));return}let report=argv.some((arg)=>arg==="--report"),fix=argv.some((arg)=>arg==="--fix"),kill=argv.some((arg)=>arg==="--kill-orphans"),known=new Set(["--report","--fix","--kill-orphans"]),unknown=argv.find((arg)=>arg.length>0&&!known.has(arg));if(unknown!==void 0)process.stderr.write(`${CLI_NAME} doctor: unexpected argument "${unknown}"
12
+
13
+ Usage: ${CLI_NAME} doctor [--report] [--fix] [--kill-orphans]
14
+ `),process.exit(2);let{lines,fixes,orphans}=await collectDoctor();if(!fix&&fixes.length>0)lines.push("",t("doctor.fix.hint",{count:fixes.length,command:`${CLI_NAME} doctor --fix`}));if(console.log(lines.join(`
15
+ `)),kill)console.log(`
16
+ ${(await sweepOrphans(orphans)).join(`
17
+ `)}`);if(fix)await applyFixes(fixes,defaultFixRuntime());if(report){let{writeReportBundle}=await import("./chunk-c6mthex1.js"),path=writeReportBundle(lines);console.log(`
18
+ report written: ${path}`),console.log("attach this file to a bug report \u2014 it includes recent daemon + pty-host logs and env.")}}export{runDoctorSubcommand};
@@ -0,0 +1,11 @@
1
+ // @bun
2
+ import{SUBCOMMAND_VERBS}from"./chunk-s76r56rj.js";import{expandTilde}from"./chunk-0vmrteyg.js";import{BUNDLED_THEME_JSONS,userThemesDir,validateTheme}from"./chunk-0sm2k04y.js";import{errorMessage}from"./chunk-2brn8e1y.js";import"./chunk-6dn6h640.js";import{activeCliName}from"./chunk-ef11h2am.js";import"./chunk-8ddjfc2v.js";import"./chunk-cb2fpajx.js";import"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";import{existsSync,mkdirSync,readFileSync,readdirSync,unlinkSync,writeFileSync}from"fs";import{basename,join,resolve}from"path";var CLI_NAME=activeCliName(),THEME_VERB_ALIASES={ls:"list",rm:"remove"},BUNDLED_NAMES=Object.keys(BUNDLED_THEME_JSONS);function fail(message){process.stderr.write(`${CLI_NAME} theme: ${message}
3
+ `),process.exit(1)}function failUsage(message){process.stderr.write(`${CLI_NAME} theme: ${message}
4
+
5
+ `),printUsage(),process.exit(2)}function listThemes(){let lines=[];lines.push("bundled:");for(let name of[...BUNDLED_NAMES].sort())lines.push(` ${name} [built-in]`);let dir=userThemesDir(),userFiles=[];try{userFiles=readdirSync(dir).filter((f)=>f.endsWith(".json")).sort()}catch{}if(lines.push(""),lines.push(`user (${dir}):`),userFiles.length===0)lines.push(" (none)");else for(let f of userFiles){let name=f.slice(0,-5),path=join(dir,f),overridesBundled=BUNDLED_NAMES.includes(name)?" (overrides built-in)":"";lines.push(` ${name}${overridesBundled} ${path}`)}process.stdout.write(`${lines.join(`
6
+ `)}
7
+ `)}async function readSource(source){if(/^https?:\/\//i.test(source)){let res;try{res=await fetch(source)}catch(err){fail(`failed to fetch ${source}: ${errorMessage(err)}`)}if(!res.ok)fail(`failed to fetch ${source}: HTTP ${res.status} ${res.statusText}`);let text2=await res.text(),cleanPath=source.split(/[?#]/)[0]??source,file2=basename(cleanPath)||"theme.json",defaultName2=file2.endsWith(".json")?file2.slice(0,-5):file2;return{text:text2,defaultName:defaultName2}}let abs=resolve(process.cwd(),expandTilde(source)),text;try{text=readFileSync(abs,"utf8")}catch(err){fail(`failed to read ${abs}: ${errorMessage(err)}`)}let file=basename(abs),defaultName=file.endsWith(".json")?file.slice(0,-5):file;return{text,defaultName}}function parseAddArgs(args){let source=null,name,force=!1;for(let i=0;i<args.length;i+=1){let a=args[i];if(a==="--force"||a==="-f"){force=!0;continue}if(a==="--name"||a==="-n"){let next=args[i+1];if(next===void 0)failUsage("--name requires a value");name=next,i+=1;continue}if(a.startsWith("--name=")){name=a.slice(7);continue}if(a.startsWith("--"))failUsage(`unknown flag: ${a}`);if(source===null){source=a;continue}failUsage(`unexpected positional argument: ${a}`)}if(source===null)failUsage("missing <source> (URL or path to theme JSON)");return{source,opts:{name,force}}}async function addTheme(args){let{source,opts}=parseAddArgs(args),{text,defaultName}=await readSource(source),parsed;try{parsed=JSON.parse(text)}catch(err){fail(`source is not valid JSON: ${errorMessage(err)}`)}let result=validateTheme(parsed);if(!result.ok)fail(`source is not a valid Rove theme: ${result.reason}`);let name=opts.name??defaultName;if(!name||!/^[a-zA-Z0-9._-]+$/.test(name))fail(`invalid theme name "${name}" (use letters, digits, '.', '_', '-')`);let dir=userThemesDir();mkdirSync(dir,{recursive:!0});let dest=join(dir,`${name}.json`);if(existsSync(dest)&&!opts.force)fail(`${dest} already exists (pass --force to overwrite)`);writeFileSync(dest,`${JSON.stringify(result.theme,null,2)}
8
+ `,"utf8"),process.stdout.write(`installed theme "${name}" -> ${dest}
9
+ `)}function removeTheme(args){let name=args[0];if(!name)failUsage("missing <name>");if(args.length>1)failUsage(`unexpected extra arguments after "${name}"`);if(BUNDLED_NAMES.includes(name))fail(`"${name}" is a built-in theme and cannot be removed`);let dest=join(userThemesDir(),`${name}.json`);if(!existsSync(dest))fail(`no user theme named "${name}" (looked for ${dest})`);unlinkSync(dest),process.stdout.write(`removed theme "${name}" (${dest})
10
+ `)}function printUsage(out=process.stderr){out.write([`Usage: ${CLI_NAME} theme <command> [args]`,"","Commands:"," list List bundled and user-installed themes"," add <source> [--name <name>] Install a theme from a URL or local path"," Pass --force to overwrite an existing user theme"," remove <name> Remove a user-installed theme","",`User themes live under: ${userThemesDir()}`,"Schema: https://raw.githubusercontent.com/sma1lboy/rove/main/packages/kobe/src/tui/context/theme/theme.schema.json",""].join(`
11
+ `))}async function runThemeSubcommand(args){let[action,...rest]=args;if(!action||action==="--help"||action==="-h"||action==="help"){if(printUsage(action?process.stdout:process.stderr),!action)process.exit(2);return}let verb=THEME_VERB_ALIASES[action]??action;if(!SUBCOMMAND_VERBS.theme.includes(verb))failUsage(`unknown action "${action}" (try ${SUBCOMMAND_VERBS.theme.map((v)=>`"${v}"`).join(", ")})`);if(verb==="list"){if(rest.length>0)failUsage(`"${action}" takes no arguments`);listThemes();return}if(verb==="add"){await addTheme(rest);return}if(verb==="remove"){removeTheme(rest);return}failUsage(`unknown action "${action}"`)}export{runThemeSubcommand};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{closeTab,engineTabArgv,initialTabs,terminalTabsKey}from"./chunk-y2yq6zca.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,isHostedTaskKey,killHostedSessions,listHostedSessions,listHostedSessionsOrNull,openHostedSessionHost,pastePromptWhenEngineUp,readPersistedTerminalDefaultColors,sessionHasEngine,writeHostedPromptIfClear}from"./chunk-adez6hq4.js";import{engineLaunchArgv}from"./chunk-q7dr9eh6.js";import{engineEntry}from"./chunk-yhcz2d2r.js";import{loadStateFile,patchStateFile,updateStateFile}from"./chunk-gjf604bb.js";import{existsSync}from"fs";function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function closeTabsSnapshot(taskId,tabId){let closing,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return!1;let{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return closing=void 0,!1;store[key]=next;return}),closing}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t)=>t.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t)=>{let key=`${taskId}::${t.id}`,isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:walked!==void 0?walked:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0))rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,autoTitle:null,alive:!0,engineAlive:engineAliveOf(`${taskId}::${tabId}`,!0,engineAlive),exit:null,unregistered:!0});return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}function hasLiveEngineTab(snapshot,taskId,sessions,engineAlive){let alive=aliveKeysOf(sessions),counts=(key)=>alive.has(key)&&engineAlive?.get(key)!==!1;if(counts(`${taskId}::tab-1`))return!0;return(snapshot?.tabs??[]).some((t)=>t.kind==="engine"&&counts(`${taskId}::${t.id}`))}function publishCliTabSnapshot(taskId,sessionId){if(!taskId)return;try{let key=terminalTabsKey(taskId);if(loadStateFile()[key]!==void 0)return;let seeded=initialTabs();patchStateFile({[key]:sessionId?{...seeded,tabs:seeded.tabs.map((t)=>t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}:seeded})}catch{}}function markCliTabSession(taskId,tabId,sessionId){try{let key=terminalTabsKey(taskId),existing=loadStateFile()[key];if(!existing||!Array.isArray(existing.tabs))return;patchStateFile({[key]:{...existing,tabs:existing.tabs.map((t)=>t.id===tabId&&t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}})}catch{}}function mintCliTab(taskId,vendor,command){let tabId="tab-1";try{let key=terminalTabsKey(taskId),existing=loadStateFile()[key],state=existing&&Array.isArray(existing.tabs)&&existing.tabs.length>0?existing:initialTabs(),ordinal=typeof state.nextOrdinal==="number"&&state.nextOrdinal>1?state.nextOrdinal:2;tabId=`tab-${ordinal}`,patchStateFile({[key]:{...state,tabs:[...state.tabs,{kind:"engine",id:tabId,title:null,ordinal,...vendor?{vendor}:{},...command?{engineCommand:command}:{}}],activeId:tabId,nextOrdinal:ordinal+1}})}catch{tabId=`tab-cli-${Date.now().toString(36)}`}return tabId}function restoredTabsOf(sessions,taskId,exceptKey){let prefix=`${taskId}::`,ids=[];for(let s of sessions){if(s.alive||s.restored!==!0||s.key===exceptKey||!s.key.startsWith(prefix))continue;let tab=s.key.slice(prefix.length);if(tab.includes("::"))continue;if(!ids.includes(tab))ids.push(tab)}let tabs=readTabsSnapshot(taskId)?.tabs??[];return ids.map((tab)=>{let sessionId=tabs.find((t)=>t.id===tab)?.sessionId;return sessionId?{tab,sessionId}:{tab}})}function restoredTabLaunch(task,tabId,worktreePath,shell){let tab=readTabsSnapshot(task.id)?.tabs.find((t)=>t.id===tabId&&t.kind==="engine");if(!tab)return null;let base=engineLaunchArgv({command:tab.engineCommand??(tab.vendor?void 0:task.command),vendor:tab.vendor??task.vendor,effort:task.modelEffort});return buildEngineSessionLaunch({task:{id:task.id,kind:task.kind??"task",vendor:tab.vendor??task.vendor,repo:task.repo},worktreePath,shell,argv:engineTabArgv(tab,base,!1,task.vendor),promptIntent:{kind:"none"},tabId})}class ApiError extends Error{code;data;constructor(message,code,data){super(message);this.code=code;this.data=data}}var DAEMON_CODE_PREFIX=/^([A-Z][A-Z0-9_]{2,}): /;function splitDaemonCode(message){let match=DAEMON_CODE_PREFIX.exec(message);if(!match?.[1])return null;return{code:match[1],rest:message.slice(match[0].length)}}function helpStep(verbName){return{hint:"run the verb's --help for its exact flag contract, then retry",nextCommandArgs:["api",verbName,"--help"]}}var VERB_GROUP_IDS=["discover","read","create","drive","edit","issues","workitems","routine","lifecycle","worktree","feedback"];var isTaskKey=isHostedTaskKey,findEngineKey=findHostedEngineKey,taskKeys=hostedTaskKeys,openPtyHost=openHostedSessionHost,ensurePtyHost=ensureHostedSessionHost,listSessions=listHostedSessions,listSessionsOrNull=listHostedSessionsOrNull,deliverToKey=deliverToHostedKey,writePrompt=writeHostedPromptIfClear,ENGINE_START_PROBE_MS=3000,ENGINE_START_POLL_MS=150,ENGINE_NOT_OBSERVED_REASON=`no engine process appeared in the session within ${ENGINE_START_PROBE_MS}ms`;function outcomeFields(outcome){if(!outcome)return{engineReady:!1,delivered:!1};return{engineReady:outcome.ready,delivered:!0,bytes:outcome.bytes,promptEcho:outcome.confirmed?"confirmed":"unconfirmed"}}async function deliverHostedPrompt(rpc,target,cwd,prompt,launch,opts){let{sessions=[]}=await rpc.request("pty.list",{}),existingKey=opts?.forceNew?null:findEngineKey(sessions,target.id,target.engineBin);if(existingKey){let pid=sessions.find((s)=>s.key===existingKey)?.pid;if(!await sessionHasEngine(pid,target.engineBin,opts?.snapshot))throw new ApiError(`task ${target.id}'s engine tab (${existingKey}) has no live engine process \u2014 its engine exited into a plain shell`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new",nextCommandArgs:["api","send","--task-id",target.id,"--tab","new","--prompt",prompt]});let deliveryOpts={screenManifest:resolveComposerManifest(opts?.vendor)},tabId=existingKey.split("::")[1]??"tab-1",outcome;try{outcome=await deliverToKey(rpc,existingKey,prompt,deliveryOpts)}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:existingKey,pane:existingKey,started:!1,...outcomeFields(outcome)}}if(!opts?.forceNew){let aliveTabs=sessions.filter((s)=>s.alive&&isTaskKey(s.key,target.id)).map((s)=>s.key);if(aliveTabs.length>0)throw new ApiError(`task ${target.id} has live tabs (${aliveTabs.join(", ")}) but none resolves as its engine tab \u2014 refusing to spawn a new engine`,"NO_ENGINE_TAB",{hint:"address a live engine tab explicitly with --tab <tab-N> (see pty-list), or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","pty-list"]})}let frozen=restoredTabsOf(sessions,target.id,launch.key),disclose=frozen.length>0?{frozenTabs:frozen}:{},staleCanonical=sessions.find((session)=>session.key===launch.key&&!session.alive);if(staleCanonical&&staleCanonical.restored!==!0)await rpc.request("pty.kill",{key:launch.key});let open=await rpc.request("pty.open",{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()});try{if(!open.alive)return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,engineReady:!1,delivered:!1,...disclose};if(launch.firstMessage){let tabId=launch.key.split("::")[1]??"tab-1",outcome;try{outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs,screenManifest:resolveComposerManifest(opts?.vendor)})}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,...outcomeFields(outcome),...disclose}}let started=open.created!==!1||open.respawned===!0;if(open.created===!1&&open.respawned!==!0){let tabId=launch.key.split("::")[1]??"tab-1",outcome;try{outcome=await writePrompt(rpc,launch.key,prompt,{screenManifest:resolveComposerManifest(opts?.vendor)})}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:launch.key,pane:launch.key,started,...outcomeFields(outcome),...disclose}}if(launch.initMarkerPath&&!existsSync(launch.initMarkerPath))return{session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!0,reason:"repo init script is still running; the engine has not started yet",...disclose};if(await awaitEngineProcess(rpc,launch.key,target.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts?.snapshot})===null)return{session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,launch.key)??ENGINE_NOT_OBSERVED_REASON,...disclose};return{session:launch.key,pane:launch.key,started,engineReady:!0,delivered:!0,...disclose}}finally{await rpc.request("pty.detach",{key:launch.key}).catch(()=>{})}}function resolveComposerManifest(vendor){return vendor?engineEntry(vendor).screenManifest:void 0}async function deferOrThrow(error,sink,taskId,tabId,prompt){if(sink){let deferred;try{deferred=await sink.defer({taskId,tabId,prompt,layer:error.layer})}catch{throw composerBusyApiError(error,taskId,prompt)}if(deferred.kind==="occupied")throw new ApiError(`task ${taskId} tab ${tabId} already has a deferred prompt`,"DEFERRED_PROMPT_PENDING",{taskId,tabId,existingId:deferred.id,hint:"a prompt is already held for this tab \u2014 deliver it with `deferred-release --id`, or drop it with `deferred-dismiss --id`, then send yours again (`deferred-list` shows the text and its expiry)",nextCommandArgs:["api","deferred-release","--id",deferred.id]});return{session:`${taskId}::${tabId}`,pane:`${taskId}::${tabId}`,started:!1,engineReady:!1,delivered:!1,deferred:{id:deferred.id,layer:error.layer,...deferred.expiresAt!==void 0?{expiresAt:deferred.expiresAt}:{}}}}throw composerBusyApiError(error,taskId,prompt)}function composerBusyApiError(error,taskId,prompt){let layerText=error.layer==="recent-human-write"?"user was typing recently":"composer has text";return new ApiError(`task ${taskId}'s composer is busy (${layerText})`,"COMPOSER_BUSY",{layer:error.layer,hint:"wait a moment and retry, or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","send","--task-id",taskId,"--prompt",prompt]})}var killTaskSessions=killHostedSessions;
3
+ export{ApiError,splitDaemonCode,helpStep,VERB_GROUP_IDS,taskEngineArgv,readTabsSnapshot,closeTabsSnapshot,unregisteredTabIds,joinTaskTabs,hasLiveEngineTab,publishCliTabSnapshot,markCliTabSession,mintCliTab,restoredTabLaunch,isTaskKey,findEngineKey,taskKeys,openPtyHost,ensurePtyHost,listSessions,listSessionsOrNull,deliverToKey,ENGINE_START_PROBE_MS,ENGINE_START_POLL_MS,ENGINE_NOT_OBSERVED_REASON,outcomeFields,deliverHostedPrompt,resolveComposerManifest,deferOrThrow,killTaskSessions};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function argvHasFlag(argv,flag){return argv.some((a)=>a===flag||a.startsWith(`${flag}=`))}function flagValue(argv,flag){for(let i=0;i<argv.length;i++){if(argv[i]===flag)return argv[i+1];if(argv[i].startsWith(`${flag}=`))return argv[i].slice(flag.length+1)}return}
3
+ export{argvHasFlag,flagValue};
@@ -0,0 +1,258 @@
1
+ // @bun
2
+ import{PLUGIN_EVENT_NAMES}from"./chunk-kwe61yx7.js";import{COMPAT_STATE_DIR_BASENAME,ROVE_STATE_DIR_BASENAME,readRoveHomeDirEnv}from"./chunk-3bfm4hrs.js";import{existsSync,readFileSync}from"fs";import{basename,join}from"path";/*!
3
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
4
+ * SPDX-License-Identifier: BSD-3-Clause
5
+ *
6
+ * Redistribution and use in source and binary forms, with or without
7
+ * modification, are permitted provided that the following conditions are met:
8
+ *
9
+ * 1. Redistributions of source code must retain the above copyright notice, this
10
+ * list of conditions and the following disclaimer.
11
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ * this list of conditions and the following disclaimer in the
13
+ * documentation and/or other materials provided with the distribution.
14
+ * 3. Neither the name of the copyright holder nor the names of its contributors
15
+ * may be used to endorse or promote products derived from this software without
16
+ * specific prior written permission.
17
+ *
18
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+ */var DATE_TIME_RE=/^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;class TomlDate extends Date{#hasDate=!1;#hasTime=!1;#offset=null;constructor(date){let hasDate=!0,hasTime=!0,offset="Z";if(typeof date==="string"){let match=date.match(DATE_TIME_RE);if(match){if(!match[1])hasDate=!1,date=`0000-01-01T${date}`;if(hasTime=!!match[2],hasTime&&date[10]===" "&&(date=date.replace(" ","T")),match[2]&&+match[2]>23)date="";else if(offset=match[3]||null,date=date.toUpperCase(),!offset&&hasTime)date+="Z"}else date=""}super(date);if(!isNaN(this.getTime()))this.#hasDate=hasDate,this.#hasTime=hasTime,this.#offset=offset}isDateTime(){return this.#hasDate&&this.#hasTime}isLocal(){return!this.#hasDate||!this.#hasTime||!this.#offset}isDate(){return this.#hasDate&&!this.#hasTime}isTime(){return this.#hasTime&&!this.#hasDate}isValid(){return this.#hasDate||this.#hasTime}toISOString(){let iso=super.toISOString();if(this.isDate())return iso.slice(0,10);if(this.isTime())return iso.slice(11,23);if(this.#offset===null)return iso.slice(0,-1);if(this.#offset==="Z")return iso;let offset=+this.#offset.slice(1,3)*60+ +this.#offset.slice(4,6);return offset=this.#offset[0]==="-"?offset:-offset,new Date(this.getTime()-offset*60000).toISOString().slice(0,-1)+this.#offset}static wrapAsOffsetDateTime(jsDate,offset="Z"){let date=new TomlDate(jsDate);return date.#offset=offset,date}static wrapAsLocalDateTime(jsDate){let date=new TomlDate(jsDate);return date.#offset=null,date}static wrapAsLocalDate(jsDate){let date=new TomlDate(jsDate);return date.#hasTime=!1,date.#offset=null,date}static wrapAsLocalTime(jsDate){let date=new TomlDate(jsDate);return date.#hasDate=!1,date.#offset=null,date}}/*!
29
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
30
+ * SPDX-License-Identifier: BSD-3-Clause
31
+ *
32
+ * Redistribution and use in source and binary forms, with or without
33
+ * modification, are permitted provided that the following conditions are met:
34
+ *
35
+ * 1. Redistributions of source code must retain the above copyright notice, this
36
+ * list of conditions and the following disclaimer.
37
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
38
+ * this list of conditions and the following disclaimer in the
39
+ * documentation and/or other materials provided with the distribution.
40
+ * 3. Neither the name of the copyright holder nor the names of its contributors
41
+ * may be used to endorse or promote products derived from this software without
42
+ * specific prior written permission.
43
+ *
44
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
45
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
46
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
47
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
48
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
50
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
51
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
52
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
53
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
54
+ */function getLineColFromPtr(string,ptr){let lines=string.slice(0,ptr).split(/\r\n|\n|\r/g);return[lines.length,lines.pop().length+1]}function makeCodeBlock(string,line,column){let lines=string.split(/\r\n|\n|\r/g),codeblock="",numberLen=(Math.log10(line+1)|0)+1;for(let i=line-1;i<=line+1;i++){let l=lines[i-1];if(!l)continue;if(codeblock+=i.toString().padEnd(numberLen," "),codeblock+=": ",codeblock+=l,codeblock+=`
55
+ `,i===line)codeblock+=" ".repeat(numberLen+column+2),codeblock+=`^
56
+ `}return codeblock}class TomlError extends Error{line;column;codeblock;constructor(message,options){let[line,column]=getLineColFromPtr(options.toml,options.ptr),codeblock=makeCodeBlock(options.toml,line,column);super(`Invalid TOML document: ${message}
57
+
58
+ ${codeblock}`,options);this.line=line,this.column=column,this.codeblock=codeblock}}/*!
59
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
60
+ * SPDX-License-Identifier: BSD-3-Clause
61
+ *
62
+ * Redistribution and use in source and binary forms, with or without
63
+ * modification, are permitted provided that the following conditions are met:
64
+ *
65
+ * 1. Redistributions of source code must retain the above copyright notice, this
66
+ * list of conditions and the following disclaimer.
67
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
68
+ * this list of conditions and the following disclaimer in the
69
+ * documentation and/or other materials provided with the distribution.
70
+ * 3. Neither the name of the copyright holder nor the names of its contributors
71
+ * may be used to endorse or promote products derived from this software without
72
+ * specific prior written permission.
73
+ *
74
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
75
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
76
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
77
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
78
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
79
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
80
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
81
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
82
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
83
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
84
+ */var INT_REGEX=/^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/,FLOAT_REGEX=/^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/,LEADING_ZERO=/^[+-]?0[0-9_]/;function parseString(str,ptr){let c=str[ptr++],first=c,isLiteral=c==="'",isMultiline=c===str[ptr]&&c===str[ptr+1];if(isMultiline){if(str[ptr+=2]===`
85
+ `)ptr++;else if(str[ptr]==="\r"&&str[ptr+1]===`
86
+ `)ptr+=2}let parsed="",sliceStart=ptr,state=0;for(let i=ptr;i<str.length;i++)if(c=str[i],isMultiline&&(c===`
87
+ `||c==="\r"&&str[i+1]===`
88
+ `))state=state&&3;else if(c<" "&&c!=="\t"||c==="\x7F")throw new TomlError("control characters are not allowed in strings",{toml:str,ptr:i});else if((!state||state===3)&&c===first&&(!isMultiline||str[i+1]===first&&str[i+2]===first)){if(isMultiline){if(str[i+3]===first)i++;if(str[i+3]===first)i++}return[state?parsed:parsed+str.slice(sliceStart,i),i+(isMultiline?3:1)]}else if(!state){if(!isLiteral&&c==="\\")parsed+=str.slice(sliceStart,sliceStart=i),state=1}else if(state===1)if(c==="x"||c==="u"||c==="U"){let value=0,len=c==="x"?2:c==="u"?4:8;for(let j=0;j<len;j++,i++){let hex=str.charCodeAt(i+1),digit=hex>=48&&hex<=57?hex-48:hex>=65&&hex<=70?hex-65+10:hex>=97&&hex<=102?hex-97+10:-1;if(digit<0)throw new TomlError("invalid non-hex character in unicode escape",{toml:str,ptr:i+1});value=value<<4|digit}if(value<0||value>1114111||value>=55296&&value<=57343)throw new TomlError("invalid unicode escape",{toml:str,ptr:i});parsed+=String.fromCodePoint(value),sliceStart=i+1,state=0}else if(c===" "||c==="\t")state=2;else{if(c==="b")parsed+="\b";else if(c==="t")parsed+="\t";else if(c==="n")parsed+=`
89
+ `;else if(c==="f")parsed+="\f";else if(c==="r")parsed+="\r";else if(c==="e")parsed+="\x1B";else if(c==='"')parsed+='"';else if(c==="\\")parsed+="\\";else throw new TomlError("unrecognized escape sequence",{toml:str,ptr:i});sliceStart=i+1,state=0}else if(c!==" "&&c!=="\t"){if(state===2)throw new TomlError("invalid escape: only line-ending whitespace may be escaped",{toml:str,ptr:sliceStart});state=!isLiteral&&c==="\\"?1:0,sliceStart=i}throw new TomlError("unfinished string",{toml:str,ptr})}function parseValue(value,toml,ptr,integersAsBigInt){if(value==="true")return!0;if(value==="false")return!1;if(value==="-inf")return-1/0;if(value==="inf"||value==="+inf")return 1/0;if(value==="nan"||value==="+nan"||value==="-nan")return NaN;if(value==="-0")return integersAsBigInt?0n:0;let isInt=INT_REGEX.test(value);if(isInt||FLOAT_REGEX.test(value)){if(LEADING_ZERO.test(value))throw new TomlError("leading zeroes are not allowed",{toml,ptr});value=value.replace(/_/g,"");let numeric=+value;if(isNaN(numeric))throw new TomlError("invalid number",{toml,ptr});if(isInt){if((isInt=!Number.isSafeInteger(numeric))&&!integersAsBigInt)throw new TomlError("integer value cannot be represented losslessly",{toml,ptr});if(isInt||integersAsBigInt===!0)numeric=BigInt(value)}return numeric}let date=new TomlDate(value);if(!date.isValid())throw new TomlError("invalid value",{toml,ptr});return date}/*!
90
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
91
+ * SPDX-License-Identifier: BSD-3-Clause
92
+ *
93
+ * Redistribution and use in source and binary forms, with or without
94
+ * modification, are permitted provided that the following conditions are met:
95
+ *
96
+ * 1. Redistributions of source code must retain the above copyright notice, this
97
+ * list of conditions and the following disclaimer.
98
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
99
+ * this list of conditions and the following disclaimer in the
100
+ * documentation and/or other materials provided with the distribution.
101
+ * 3. Neither the name of the copyright holder nor the names of its contributors
102
+ * may be used to endorse or promote products derived from this software without
103
+ * specific prior written permission.
104
+ *
105
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
106
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
107
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
108
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
109
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
110
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
111
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
112
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
113
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
114
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
115
+ */function indexOfNewline(str,start=0,end=str.length){let idx=str.indexOf(`
116
+ `,start);if(str[idx-1]==="\r")idx--;return idx<=end?idx:-1}function skipComment(str,ptr){for(let i=ptr;i<str.length;i++){let c=str[i];if(c===`
117
+ `)return i;if(c==="\r"&&str[i+1]===`
118
+ `)return i+1;if(c<" "&&c!=="\t"||c==="\x7F")throw new TomlError("control characters are not allowed in comments",{toml:str,ptr})}return str.length}function skipVoid(str,ptr,banNewLines,banComments){let c;while(!0){while((c=str[ptr])===" "||c==="\t"||!banNewLines&&(c===`
119
+ `||c==="\r"&&str[ptr+1]===`
120
+ `))ptr++;if(banComments||c!=="#")break;ptr=skipComment(str,ptr)}return ptr}function skipUntil(str,ptr,sep,end,banNewLines=!1){if(!end)return ptr=indexOfNewline(str,ptr),ptr<0?str.length:ptr;for(let i=ptr;i<str.length;i++){let c=str[i];if(c==="#"){if(i=indexOfNewline(str,i),i<0)break}else if(c===sep)return i+1;else if(c===end||banNewLines&&(c===`
121
+ `||c==="\r"&&str[i+1]===`
122
+ `))return i}throw new TomlError("cannot find end of structure",{toml:str,ptr})}/*!
123
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
124
+ * SPDX-License-Identifier: BSD-3-Clause
125
+ *
126
+ * Redistribution and use in source and binary forms, with or without
127
+ * modification, are permitted provided that the following conditions are met:
128
+ *
129
+ * 1. Redistributions of source code must retain the above copyright notice, this
130
+ * list of conditions and the following disclaimer.
131
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
132
+ * this list of conditions and the following disclaimer in the
133
+ * documentation and/or other materials provided with the distribution.
134
+ * 3. Neither the name of the copyright holder nor the names of its contributors
135
+ * may be used to endorse or promote products derived from this software without
136
+ * specific prior written permission.
137
+ *
138
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
139
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
140
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
141
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
142
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
143
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
144
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
145
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
146
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
147
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
148
+ */function sliceAndTrimEndOf(str,startPtr,endPtr){let value=str.slice(startPtr,endPtr),commentIdx=value.indexOf("#");if(commentIdx>-1)skipComment(str,commentIdx),value=value.slice(0,commentIdx);return[value.trimEnd(),commentIdx]}function extractValue(str,ptr,end,depth,integersAsBigInt){if(depth===0)throw new TomlError("document contains excessively nested structures. aborting.",{toml:str,ptr});let c=str[ptr];if(c==="["||c==="{"){let[value,endPtr2]=c==="["?parseArray(str,ptr,depth,integersAsBigInt):parseInlineTable(str,ptr,depth,integersAsBigInt);if(end){if(endPtr2=skipVoid(str,endPtr2),str[endPtr2]===",")endPtr2++;else if(str[endPtr2]!==end)throw new TomlError("expected comma or end of structure",{toml:str,ptr:endPtr2})}return[value,endPtr2]}if(c==='"'||c==="'"){let[parsed,endPtr2]=parseString(str,ptr);if(end){if(endPtr2=skipVoid(str,endPtr2),str[endPtr2]&&str[endPtr2]!==","&&str[endPtr2]!==end&&str[endPtr2]!==`
149
+ `&&str[endPtr2]!=="\r")throw new TomlError("unexpected character encountered",{toml:str,ptr:endPtr2});if(str[endPtr2]===",")endPtr2++}return[parsed,endPtr2]}let endPtr=skipUntil(str,ptr,",",end),slice=sliceAndTrimEndOf(str,ptr,endPtr-(str[endPtr-1]===","?1:0));if(!slice[0])throw new TomlError("incomplete key-value declaration: no value specified",{toml:str,ptr});if(end&&slice[1]>-1){if(endPtr=skipVoid(str,ptr+slice[1]),str[endPtr]===",")endPtr++}return[parseValue(slice[0],str,ptr,integersAsBigInt),endPtr]}/*!
150
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
151
+ * SPDX-License-Identifier: BSD-3-Clause
152
+ *
153
+ * Redistribution and use in source and binary forms, with or without
154
+ * modification, are permitted provided that the following conditions are met:
155
+ *
156
+ * 1. Redistributions of source code must retain the above copyright notice, this
157
+ * list of conditions and the following disclaimer.
158
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
159
+ * this list of conditions and the following disclaimer in the
160
+ * documentation and/or other materials provided with the distribution.
161
+ * 3. Neither the name of the copyright holder nor the names of its contributors
162
+ * may be used to endorse or promote products derived from this software without
163
+ * specific prior written permission.
164
+ *
165
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
166
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
167
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
168
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
169
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
170
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
171
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
172
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
173
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
174
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
175
+ */var KEY_PART_RE=/^[a-zA-Z0-9-_]+[ \t]*$/;function parseKey(str,ptr,end="="){let dot=ptr-1,parsed=[],endPtr=str.indexOf(end,ptr);if(endPtr<0)throw new TomlError("incomplete key-value: cannot find end of key",{toml:str,ptr});do{let c=str[ptr=++dot];if(c!==" "&&c!=="\t")if(c==='"'||c==="'"){if(c===str[ptr+1]&&c===str[ptr+2])throw new TomlError("multiline strings are not allowed in keys",{toml:str,ptr});let[part,eos]=parseString(str,ptr);dot=str.indexOf(".",eos);let strEnd=str.slice(eos,dot<0||dot>endPtr?endPtr:dot),newLine=indexOfNewline(strEnd);if(newLine>-1)throw new TomlError("newlines are not allowed in keys",{toml:str,ptr:ptr+dot+newLine});if(strEnd.trimStart())throw new TomlError("found extra tokens after the string part",{toml:str,ptr:eos});if(endPtr<eos){if(endPtr=str.indexOf(end,eos),endPtr<0)throw new TomlError("incomplete key-value: cannot find end of key",{toml:str,ptr})}parsed.push(part)}else{dot=str.indexOf(".",ptr);let part=str.slice(ptr,dot<0||dot>endPtr?endPtr:dot);if(!KEY_PART_RE.test(part))throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys",{toml:str,ptr});parsed.push(part.trimEnd())}}while(dot+1&&dot<endPtr);return[parsed,skipVoid(str,endPtr+1,!0,!0)]}function parseInlineTable(str,ptr,depth,integersAsBigInt){let res={},seen=new Set,c;ptr++;while((c=str[ptr++])!=="}"&&c)if(c===",")throw new TomlError("expected value, found comma",{toml:str,ptr:ptr-1});else if(c==="#")ptr=skipComment(str,ptr);else if(c!==" "&&c!=="\t"&&c!==`
176
+ `&&c!=="\r"){let k,t=res,hasOwn=!1,[key,keyEndPtr]=parseKey(str,ptr-1);for(let i=0;i<key.length;i++){if(i)t=hasOwn?t[k]:t[k]={};if(k=key[i],(hasOwn=Object.hasOwn(t,k))&&(typeof t[k]!=="object"||seen.has(t[k])))throw new TomlError("trying to redefine an already defined value",{toml:str,ptr});if(!hasOwn&&k==="__proto__")Object.defineProperty(t,k,{enumerable:!0,configurable:!0,writable:!0})}if(hasOwn)throw new TomlError("trying to redefine an already defined value",{toml:str,ptr});let[value,valueEndPtr]=extractValue(str,keyEndPtr,"}",depth-1,integersAsBigInt);seen.add(value),t[k]=value,ptr=valueEndPtr}if(!c)throw new TomlError("unfinished table encountered",{toml:str,ptr});return[res,ptr]}function parseArray(str,ptr,depth,integersAsBigInt){let res=[],c;ptr++;while((c=str[ptr++])!=="]"&&c)if(c===",")throw new TomlError("expected value, found comma",{toml:str,ptr:ptr-1});else if(c==="#")ptr=skipComment(str,ptr);else if(c!==" "&&c!=="\t"&&c!==`
177
+ `&&c!=="\r"){let e=extractValue(str,ptr-1,"]",depth-1,integersAsBigInt);res.push(e[0]),ptr=e[1]}if(!c)throw new TomlError("unfinished array encountered",{toml:str,ptr});return[res,ptr]}/*!
178
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
179
+ * SPDX-License-Identifier: BSD-3-Clause
180
+ *
181
+ * Redistribution and use in source and binary forms, with or without
182
+ * modification, are permitted provided that the following conditions are met:
183
+ *
184
+ * 1. Redistributions of source code must retain the above copyright notice, this
185
+ * list of conditions and the following disclaimer.
186
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
187
+ * this list of conditions and the following disclaimer in the
188
+ * documentation and/or other materials provided with the distribution.
189
+ * 3. Neither the name of the copyright holder nor the names of its contributors
190
+ * may be used to endorse or promote products derived from this software without
191
+ * specific prior written permission.
192
+ *
193
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
194
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
195
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
196
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
197
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
198
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
199
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
200
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
201
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
202
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
203
+ */function peekTable(key,table,meta,type){let t=table,m=meta,k,hasOwn=!1,state;for(let i=0;i<key.length;i++){if(i){if(t=hasOwn?t[k]:t[k]={},m=(state=m[k]).c,type===0&&(state.t===1||state.t===2))return null;if(state.t===2){let l=t.length-1;t=t[l],m=m[l].c}}if(k=key[i],(hasOwn=Object.hasOwn(t,k))&&m[k]?.t===0&&m[k]?.d)return null;if(!hasOwn){if(k==="__proto__")Object.defineProperty(t,k,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(m,k,{enumerable:!0,configurable:!0,writable:!0});m[k]={t:i<key.length-1&&type===2?3:type,d:!1,i:0,c:{}}}}if(state=m[k],state.t!==type&&!(type===1&&state.t===3))return null;if(type===2){if(!state.d)state.d=!0,t[k]=[];t[k].push(t={}),state.c[state.i++]=state={t:1,d:!1,i:0,c:{}}}if(state.d)return null;if(state.d=!0,type===1)t=hasOwn?t[k]:t[k]={};else if(type===0&&hasOwn)return null;return[k,t,state.c]}function parse(toml,{maxDepth=1000,integersAsBigInt}={}){let res={},meta={},tbl=res,m=meta;for(let ptr=skipVoid(toml,0);ptr<toml.length;){if(toml[ptr]==="["){let isTableArray=toml[++ptr]==="[",k=parseKey(toml,ptr+=+isTableArray,"]");if(isTableArray){if(toml[k[1]-1]!=="]")throw new TomlError("expected end of table declaration",{toml,ptr:k[1]-1});k[1]++}let p=peekTable(k[0],res,meta,isTableArray?2:1);if(!p)throw new TomlError("trying to redefine an already defined table or value",{toml,ptr});m=p[2],tbl=p[1],ptr=k[1]}else{let k=parseKey(toml,ptr),p=peekTable(k[0],tbl,m,0);if(!p)throw new TomlError("trying to redefine an already defined table or value",{toml,ptr});let v=extractValue(toml,k[1],void 0,maxDepth,integersAsBigInt);p[1][p[0]]=v[0],ptr=v[1]}if(ptr=skipVoid(toml,ptr,!0),toml[ptr]&&toml[ptr]!==`
204
+ `&&toml[ptr]!=="\r")throw new TomlError("each key-value declaration must be followed by an end-of-line",{toml,ptr});ptr=skipVoid(toml,ptr)}return res}/*!
205
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
206
+ * SPDX-License-Identifier: BSD-3-Clause
207
+ *
208
+ * Redistribution and use in source and binary forms, with or without
209
+ * modification, are permitted provided that the following conditions are met:
210
+ *
211
+ * 1. Redistributions of source code must retain the above copyright notice, this
212
+ * list of conditions and the following disclaimer.
213
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
214
+ * this list of conditions and the following disclaimer in the
215
+ * documentation and/or other materials provided with the distribution.
216
+ * 3. Neither the name of the copyright holder nor the names of its contributors
217
+ * may be used to endorse or promote products derived from this software without
218
+ * specific prior written permission.
219
+ *
220
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
221
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
222
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
223
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
224
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
225
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
226
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
227
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
228
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
229
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
230
+ *//*!
231
+ * Copyright (c) Squirrel Chat et al., All rights reserved.
232
+ * SPDX-License-Identifier: BSD-3-Clause
233
+ *
234
+ * Redistribution and use in source and binary forms, with or without
235
+ * modification, are permitted provided that the following conditions are met:
236
+ *
237
+ * 1. Redistributions of source code must retain the above copyright notice, this
238
+ * list of conditions and the following disclaimer.
239
+ * 2. Redistributions in binary form must reproduce the above copyright notice,
240
+ * this list of conditions and the following disclaimer in the
241
+ * documentation and/or other materials provided with the distribution.
242
+ * 3. Neither the name of the copyright holder nor the names of its contributors
243
+ * may be used to endorse or promote products derived from this software without
244
+ * specific prior written permission.
245
+ *
246
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
247
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
248
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
249
+ * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
250
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
251
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
252
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
253
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
254
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
255
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
256
+ */var PLUGIN_PLATFORMS=["macos","linux","windows"];class ManifestError extends Error{}function fail(message){throw new ManifestError(`rove-plugin.toml: ${message}`)}function asString(value,field){if(typeof value!=="string"||value.length===0)fail(`\`${field}\` must be a non-empty string`);return value}function asSettingDefault(value,field){if(value===void 0||value===!1)return;if(value===!0)return"1";if(typeof value==="number"&&Number.isFinite(value))return String(value);return asString(value,field)}var TIMEOUT_MIN_MS=100,TIMEOUT_MAX_MS=600000;function asTimeoutMs(value,field){if(value===void 0)return;if(typeof value!=="number"||!Number.isInteger(value)||value<TIMEOUT_MIN_MS||value>TIMEOUT_MAX_MS)fail(`\`${field}\` must be a whole number of milliseconds between ${TIMEOUT_MIN_MS} and ${TIMEOUT_MAX_MS}`);return value}function asCommand(value,field){if(!Array.isArray(value)||value.length===0||!value.every((v)=>typeof v==="string"&&v.length>0))fail(`\`${field}\` must be a non-empty array of strings (argv form)`);return value}function asPlatforms(value,field){if(value===void 0)return;if(!Array.isArray(value)||!value.every((v)=>PLUGIN_PLATFORMS.includes(v)))fail(`\`${field}\` must be an array drawn from ${PLUGIN_PLATFORMS.join(", ")}`);return value}function asTableArray(value,field){if(value===void 0)return[];if(!Array.isArray(value)||!value.every((v)=>typeof v==="object"&&v!==null&&!Array.isArray(v)))fail(`\`[[${field}]]\` must be an array of tables`);return value}function asStringArray(value,field){if(value===void 0)return;if(!Array.isArray(value)||!value.every((v)=>typeof v==="string"&&v.length>0))fail(`\`${field}\` must be a non-empty array of strings`);return value}var SETTING_KEY_RE=/^[A-Za-z_][A-Za-z0-9_]*$/,RESERVED_SETTING_KEYS=["PATH","HOME","SHELL","IFS","LD_PRELOAD","LD_LIBRARY_PATH","LD_AUDIT","DYLD_INSERT_LIBRARIES","DYLD_LIBRARY_PATH","DYLD_FRAMEWORK_PATH","NODE_OPTIONS","BUN_INSPECT","PYTHONPATH","PYTHONSTARTUP","PERL5OPT","PERL5LIB","RUBYOPT","BASH_ENV","ENV","GIT_SSH_COMMAND","GIT_SSH","GIT_EXTERNAL_DIFF","GIT_PAGER","PAGER","EDITOR","VISUAL"];function settingKeyRejection(key){if(!SETTING_KEY_RE.test(key))return`\`${key}\` is not a valid env var name (${SETTING_KEY_RE.source})`;if(RESERVED_SETTING_KEYS.includes(key))return`\`${key}\` is reserved; it steers how the plugin's own process runs`;return null}var PLUGIN_MANIFEST_FILENAME="rove-plugin.toml",LEGACY_PLUGIN_MANIFEST_FILENAME="kobe-plugin.toml",PLUGIN_MANIFEST_FILENAMES=[PLUGIN_MANIFEST_FILENAME,LEGACY_PLUGIN_MANIFEST_FILENAME],RESERVED_ENGINE_IDS=["claude","codex","copilot","kimi","gemini","opencode","cursor","grok","droid","amp"];function pluginManifestPath(root){for(let filename of PLUGIN_MANIFEST_FILENAMES){let path=join(root,filename);if(existsSync(path))return path}return null}function readPluginManifest(root){let path=pluginManifestPath(root);if(!path)throw new ManifestError(`no ${PLUGIN_MANIFEST_FILENAMES.join(" or ")} found at ${root}`);return parsePluginManifest(readFileSync(path,"utf8"),basename(path))}var PLUGIN_ID_RE=/^[A-Za-z0-9][A-Za-z0-9._:-]*$/,LOCAL_ID_RE=/^[A-Za-z0-9][A-Za-z0-9_:-]*$/;function qualifiedActionId(pluginId,actionId){return`${pluginId}.${actionId}`}function currentPluginPlatform(platform=process.platform){if(platform==="darwin")return"macos";if(platform==="linux")return"linux";if(platform==="win32")return"windows";return}function supportsPlatform(item,manifest,platform){let declared=item.platforms??manifest.platforms;if(!declared)return!0;return platform!==void 0&&declared.includes(platform)}function parsePluginManifest(text,filename=PLUGIN_MANIFEST_FILENAME){try{return parseCanonicalPluginManifest(text)}catch(err){if(filename!==PLUGIN_MANIFEST_FILENAME&&err instanceof ManifestError)throw new ManifestError(err.message.replace(/^rove-plugin\.toml:/,`${filename}:`));throw err}}function parseCanonicalPluginManifest(text){let raw;try{raw=parse(text)}catch(err){fail(`invalid TOML \u2014 ${err instanceof Error?err.message:String(err)}`)}let warnings=[],id=asString(raw.id,"id");if(!PLUGIN_ID_RE.test(id))fail(`plugin id \`${id}\` may use ASCII letters, digits, dot, colon, underscore, hyphen`);let name=asString(raw.name,"name"),version=asString(raw.version,"version"),rawMinVersion=raw.min_rove_version??raw.min_kobe_version,minKobeVersion=asString(rawMinVersion,"min_rove_version"),description=raw.description===void 0?void 0:asString(raw.description,"description"),platforms=asPlatforms(raw.platforms,"platforms");if(!platforms)warnings.push("no top-level `platforms` declared; assuming the plugin runs everywhere");if(raw.min_rove_version!==void 0&&raw.min_kobe_version!==void 0&&raw.min_rove_version!==raw.min_kobe_version)warnings.push("both `min_rove_version` and legacy `min_kobe_version` are set; using `min_rove_version`");let build=asTableArray(raw.build,"build").map((t,i)=>({command:asCommand(t.command,`build[${i}].command`),platforms:asPlatforms(t.platforms,`build[${i}].platforms`)})),startup=asTableArray(raw.startup,"startup").map((t,i)=>({command:asCommand(t.command,`startup[${i}].command`),platforms:asPlatforms(t.platforms,`startup[${i}].platforms`),timeoutMs:asTimeoutMs(t.timeout_ms,`startup[${i}].timeout_ms`)})),shutdown=asTableArray(raw.shutdown,"shutdown").map((t,i)=>({command:asCommand(t.command,`shutdown[${i}].command`),platforms:asPlatforms(t.platforms,`shutdown[${i}].platforms`),timeoutMs:asTimeoutMs(t.timeout_ms,`shutdown[${i}].timeout_ms`)})),actions=asTableArray(raw.actions,"actions").map((t,i)=>{let actionId=asString(t.id,`actions[${i}].id`);if(t.timeout_ms!==void 0)warnings.push(`actions[${i}] declares \`timeout_ms\`; actions are user-invoked and are never killed on a deadline`);if(!LOCAL_ID_RE.test(actionId))fail(`action id \`${actionId}\` may not contain dots`);return{id:actionId,title:asString(t.title,`actions[${i}].title`),command:asCommand(t.command,`actions[${i}].command`),platforms:asPlatforms(t.platforms,`actions[${i}].platforms`)}}),seen=new Set;for(let a of actions){if(seen.has(a.id))fail(`duplicate action id \`${a.id}\``);seen.add(a.id)}let panes=asTableArray(raw.panes,"panes").map((t,i)=>{let paneId=asString(t.id,`panes[${i}].id`);if(!LOCAL_ID_RE.test(paneId))fail(`pane id \`${paneId}\` may not contain dots`);if(t.timeout_ms!==void 0)warnings.push(`panes[${i}] declares \`timeout_ms\`; a pane is a terminal the user closes, not a bounded hook`);if(t.placement!==void 0&&t.placement!=="tab"&&t.placement!=="split")warnings.push(`pane \`${paneId}\` placement \`${String(t.placement)}\` is not supported yet; opening as a split`);return{id:paneId,title:asString(t.title,`panes[${i}].title`),placement:t.placement==="tab"?"tab":"split",command:asCommand(t.command,`panes[${i}].command`),platforms:asPlatforms(t.platforms,`panes[${i}].platforms`)}}),paneSeen=new Set;for(let p of panes){if(paneSeen.has(p.id))fail(`duplicate pane id \`${p.id}\``);paneSeen.add(p.id)}let events=asTableArray(raw.events,"events").flatMap((t,i)=>{let on=asString(t.on,`events[${i}].on`),hook={on,command:asCommand(t.command,`events[${i}].command`),platforms:asPlatforms(t.platforms,`events[${i}].platforms`),timeoutMs:asTimeoutMs(t.timeout_ms,`events[${i}].timeout_ms`)};if(!PLUGIN_EVENT_NAMES.includes(on))warnings.push(`unknown event \`${on}\`; this hook will never fire on this Rove version`);return[hook]}),settings=asTableArray(raw.settings,"settings").map((t,i)=>{let type=asString(t.type,`settings[${i}].type`);if(type!=="string"&&type!=="number"&&type!=="boolean"&&type!=="enum"&&type!=="secret")fail(`settings[${i}].type must be string | number | boolean | enum | secret`);let options=t.options===void 0?void 0:Array.isArray(t.options)&&t.options.every((o)=>typeof o==="string"&&o.length>0)?t.options:fail(`settings[${i}].options must be an array of strings`);if(type==="enum"&&(!options||options.length===0))fail(`settings[${i}] enum needs \`options\``);let settingDefault=asSettingDefault(t.default,`settings[${i}].default`),key=asString(t.key,`settings[${i}].key`),rejection=settingKeyRejection(key);if(rejection)fail(`settings[${i}].key ${rejection}`);return{key,label:asString(t.label,`settings[${i}].label`),type,...options?{options}:{},...settingDefault===void 0?{}:{default:settingDefault}}}),fileHandlers=asTableArray(raw.file_handlers,"file_handlers").map((t,i)=>{let pattern=asString(t.pattern,`file_handlers[${i}].pattern`);try{new RegExp(pattern)}catch{fail(`file_handlers[${i}].pattern is not a valid regex`)}let action=asString(t.action,`file_handlers[${i}].action`);if(!actions.some((a)=>a.id===action))fail(`file_handlers[${i}] names unknown action \`${action}\``);return{pattern,action}}),engines=asTableArray(raw.engines,"engines").map((t,i)=>{let engineId=asString(t.id,`engines[${i}].id`);if(!LOCAL_ID_RE.test(engineId))fail(`engine id \`${engineId}\` may not contain dots`);if(RESERVED_ENGINE_IDS.includes(engineId))fail(`engine id \`${engineId}\` shadows a built-in or shipped engine`);let rules=asTableArray(t.rules,`engines[${i}].rules`).map((r,j)=>{let state=asString(r.state,`engines[${i}].rules[${j}].state`);if(state!=="working"&&state!=="blocked"&&state!=="idle")fail(`engines[${i}].rules[${j}].state must be working | blocked | idle`);let lineRegex=asStringArray(r.line_regex,`engines[${i}].rules[${j}].line_regex`);for(let re of lineRegex??[])try{new RegExp(re)}catch{fail(`engines[${i}].rules[${j}].line_regex \`${re}\` is not a valid regex`)}let all=asStringArray(r.all,`engines[${i}].rules[${j}].all`),any=asStringArray(r.any,`engines[${i}].rules[${j}].any`);if(!all&&!any&&!lineRegex)fail(`engines[${i}].rules[${j}] needs at least one of all/any/line_regex`);return{state,...typeof r.bottom_lines==="number"?{bottomLines:r.bottom_lines}:{},...all?{all}:{},...any?{any}:{},...lineRegex?{lineRegex}:{}}}),identityRaw=t.identity,identity;if(identityRaw!==void 0){if(typeof identityRaw!=="object"||identityRaw===null||Array.isArray(identityRaw))fail(`engines[${i}].identity must be a table`);let idt=identityRaw,shortName=((key)=>idt[key]===void 0?void 0:asString(idt[key],`engines[${i}].identity.${key}`))("short_name");identity={...shortName!==void 0?{shortName}:{}}}let firstMessageDelivery;if(t.first_message_delivery!==void 0){let raw2=asString(t.first_message_delivery,`engines[${i}].first_message_delivery`);if(raw2!=="argv"&&raw2!=="paste")fail(`engines[${i}].first_message_delivery must be argv | paste`);firstMessageDelivery=raw2}return{id:engineId,name:asString(t.name,`engines[${i}].name`),command:asCommand(t.command,`engines[${i}].command`),...t.process_names===void 0?{}:{processNames:asCommand(t.process_names,`engines[${i}].process_names`)},rules,...identity?{identity}:{},...firstMessageDelivery?{firstMessageDelivery}:{}}}),engineSeen=new Set;for(let e of engines){if(engineSeen.has(e.id))fail(`duplicate engine id \`${e.id}\``);engineSeen.add(e.id)}return{manifest:{id,name,version,minKobeVersion,description,platforms,build,startup,shutdown,actions,events,panes,settings,fileHandlers,engines},warnings}}import{existsSync as existsSync2}from"fs";import{homedir}from"os";import{join as join2}from"path";function stateRoot(homeDir){let home=homeDir??readRoveHomeDirEnv()??homedir(),canonical=join2(home,ROVE_STATE_DIR_BASENAME);if(existsSync2(join2(canonical,"plugins.json")))return canonical;let legacy=join2(home,COMPAT_STATE_DIR_BASENAME);return existsSync2(join2(legacy,"plugins.json"))?legacy:canonical}function pluginRegistryPath(homeDir){return join2(stateRoot(homeDir),"plugins.json")}function pluginsRootDir(homeDir){return join2(stateRoot(homeDir),"plugins")}function legacyPluginsRootDir(homeDir){let home=homeDir??readRoveHomeDirEnv()??homedir();return join2(home,COMPAT_STATE_DIR_BASENAME,"plugins")}function pluginDataDir(id,homeDir){return join2(pluginsRootDir(homeDir),id)}function pluginCheckoutDir(id,homeDir){return join2(pluginDataDir(id,homeDir),"checkout")}function pluginConfigDir(id,homeDir){return join2(pluginDataDir(id,homeDir),"config")}function pluginStateDir(id,homeDir){return join2(pluginDataDir(id,homeDir),"state")}function pluginLogPath(id,homeDir){return join2(pluginDataDir(id,homeDir),"log.jsonl")}function pluginsOutdatedCachePath(homeDir){return join2(stateRoot(homeDir),"plugins-outdated.json")}import{mkdirSync,readFileSync as readFileSync2,writeFileSync}from"fs";import{dirname,join as join3,relative}from"path";var EMPTY={plugins:[]};function loadPluginRegistry(homeDir){let text;try{text=readFileSync2(pluginRegistryPath(homeDir),"utf8")}catch{return EMPTY}try{let raw=JSON.parse(text);if(!Array.isArray(raw.plugins))return EMPTY;return{plugins:raw.plugins.filter(isEntry).map((entry)=>withCanonicalRoot(entry,homeDir))}}catch{return EMPTY}}function withCanonicalRoot(entry,homeDir){if(entry.source.kind!=="github")return entry;let legacy=legacyPluginsRootDir(homeDir),canonical=pluginsRootDir(homeDir);if(legacy===canonical)return entry;let inside=relative(legacy,entry.root);if(inside===""||inside.startsWith("..")||inside.startsWith("/"))return entry;return{...entry,root:join3(canonical,inside)}}function isEntry(v){if(typeof v!=="object"||v===null)return!1;let e=v,source=e.source;return typeof e.id==="string"&&typeof e.root==="string"&&typeof e.enabled==="boolean"&&typeof e.version==="string"&&typeof e.installedAt==="number"&&typeof source==="object"&&source!==null&&(source.kind==="link"||source.kind==="github"&&typeof source.spec==="string")}function savePluginRegistry(registry,homeDir){let path=pluginRegistryPath(homeDir);mkdirSync(dirname(path),{recursive:!0}),writeFileSync(path,`${JSON.stringify(registry,null,2)}
257
+ `,{mode:384})}function upsertPluginEntry(registry,entry){return{plugins:[...registry.plugins.filter((p)=>p.id!==entry.id),entry]}}function removePluginEntry(registry,id){return{plugins:registry.plugins.filter((p)=>p.id!==id)}}
258
+ export{PLUGIN_MANIFEST_FILENAMES,pluginManifestPath,readPluginManifest,qualifiedActionId,currentPluginPlatform,supportsPlatform,parsePluginManifest,pluginRegistryPath,pluginsRootDir,pluginDataDir,pluginCheckoutDir,pluginConfigDir,pluginStateDir,pluginLogPath,pluginsOutdatedCachePath,loadPluginRegistry,savePluginRegistry,upsertPluginEntry,removePluginEntry};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{getPersistedBool,loadStateFile,patchStateFile,readSavedRepos,updateStateFile}from"./chunk-gjf604bb.js";import{projectRejection}from"./chunk-9c1e5z6a.js";import{kvStatePath}from"./chunk-6dn6h640.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";function isRemoteRepoKey(key){return key.startsWith("ssh://")}function isRemoteProjectsEnabled(){return getPersistedBool("experimental.remoteProjects",!1)}function remoteRepoKey(host,user,port,basePath){let authority=port?`${user}@${host}:${port}`:`${user}@${host}`,base=(basePath??"").trim().replace(/\/+$/,"");if(!base)return`ssh://${authority}`;return`ssh://${authority}${base.startsWith("/")?base:`/${base}`}`}function readRemoteRepos(state){let raw=state.remoteRepos;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function getRemoteRepoConfig(key){return readRemoteRepos(loadStateFile())[key]??null}function getRemoteRepos(){return readRemoteRepos(loadStateFile())}function addRemoteRepo(config){let key=remoteRepoKey(config.host,config.user,config.port,config.basePath),added=!1;return updateStateFile((state)=>{let repos={...readRemoteRepos(state)},legacyKey=remoteRepoKey(config.host,config.user,config.port);if(key!==legacyKey&&repos[legacyKey]?.basePath===config.basePath)key=legacyKey;repos[key]=config,state.remoteRepos=repos;let saved=readSavedRepos(state);if(added=!saved.includes(key),added)state.savedRepos=[...saved,key];return}),{key,added}}function resolveRepoRoot(absPath){if(isRemoteRepoKey(absPath))return absPath;let r=spawnSync("git",["rev-parse","--show-toplevel"],{cwd:absPath,encoding:"utf8",shell:!1});if(r.status!==0)return absPath;let top=(r.stdout??"").trim();if(!top)return absPath;try{if(realpathSync(absPath)===realpathSync(top))return absPath}catch{}return top}function isGitRepo(absPath){if(isRemoteRepoKey(absPath))return!1;let r=spawnSync("git",["rev-parse","--is-inside-work-tree"],{cwd:absPath,encoding:"utf8",shell:!1});return r.status===0&&(r.stdout??"").trim()==="true"}function resolveMainRepoRoot(absPath){if(isRemoteRepoKey(absPath))return absPath;let r=spawnSync("git",["worktree","list","--porcelain"],{cwd:absPath,encoding:"utf8",shell:!1});if(r.status!==0)return resolveRepoRoot(absPath);return(r.stdout??"").split(/\r?\n/).find((line)=>line.startsWith("worktree "))?.slice(9).trim()||resolveRepoRoot(absPath)}function statePath(){return kvStatePath()}function getSavedRepos(){return readSavedRepos(loadStateFile())}function getPersistedString(key){let value=loadStateFile()[key];return typeof value==="string"?value:void 0}function setPersistedString(key,value){patchStateFile({[key]:value})}function getCustomEngineIds(){let raw=loadStateFile().customEngineIds;if(!Array.isArray(raw))return[];return raw.filter((s)=>typeof s==="string"&&s.trim().length>0)}function getDisabledEngineIds(){let raw=loadStateFile().disabledEngineIds;if(!Array.isArray(raw))return[];return raw.filter((s)=>typeof s==="string"&&s.trim().length>0)}function addSavedRepo(absPath,opts={}){let normalized=resolveMainRepoRoot(absPath),rejected=opts.skipGate?null:projectRejection(normalized,isGitRepo,opts.intent??"explicit");if(rejected)return{added:!1,path:normalized,total:getSavedRepos().length,rejected};let result={added:!1,path:normalized,total:0};return updateStateFile((state)=>{let cur=readSavedRepos(state);if(cur.includes(normalized))return result={added:!1,path:normalized,total:cur.length},!1;state.savedRepos=[...cur,normalized],result={added:!0,path:normalized,total:cur.length+1};return}),result}function backfillSavedReposFromProjects(mainRepos){let added=[];for(let repo of mainRepos)if(addSavedRepo(repo,{intent:"explicit"}).added)added.push(repo);return added}function normalizeSavedRepos(){let cur=getSavedRepos(),seen=new Set,next=[],changed=!1;for(let p of cur){let top=resolveMainRepoRoot(p);if(top!==p)changed=!0;if(seen.has(top)){changed=!0;continue}seen.add(top),next.push(top)}if(!changed)return;patchStateFile({savedRepos:next})}function readRepoConfigs(state){let raw=state.repoConfigs;if(!raw||typeof raw!=="object"||Array.isArray(raw))return{};return raw}function coerceOverride(entry){if(!entry||typeof entry!=="object")return{};let e=entry;return{initScript:typeof e.initScript==="string"&&e.initScript.length>0?e.initScript:void 0,initPrompt:typeof e.initPrompt==="string"&&e.initPrompt.length>0?e.initPrompt:void 0}}function getRepoInitOverride(repoRoot){return coerceOverride(readRepoConfigs(loadStateFile())[resolveRepoRoot(repoRoot)])}function setRepoInitOverride(repoRoot,patch){let normalized=resolveRepoRoot(repoRoot),next={};return updateStateFile((state)=>{let configs={...readRepoConfigs(state)},cur=coerceOverride(configs[normalized]),nextScript=patch.initScript===void 0?cur.initScript:patch.initScript||void 0,nextPrompt=patch.initPrompt===void 0?cur.initPrompt:patch.initPrompt||void 0;if(next={...nextScript?{initScript:nextScript}:{},...nextPrompt?{initPrompt:nextPrompt}:{}},!next.initScript&&!next.initPrompt){let{[normalized]:_dropped,...rest}=configs;state.repoConfigs=rest}else configs[normalized]=next,state.repoConfigs=configs;return}),next}function removeSavedRepo(absPath){let result={removed:!1,path:absPath,total:0};return updateStateFile((state)=>{let cur=readSavedRepos(state);if(!cur.includes(absPath))return result={removed:!1,path:absPath,total:cur.length},!1;if(state.savedRepos=cur.filter((p)=>p!==absPath),isRemoteRepoKey(absPath)){let remotes=readRemoteRepos(state);if(absPath in remotes){let next={...remotes};delete next[absPath],state.remoteRepos=next}}result={removed:!0,path:absPath,total:cur.length-1};return}),result}
3
+ export{isRemoteRepoKey,isRemoteProjectsEnabled,remoteRepoKey,getRemoteRepoConfig,getRemoteRepos,addRemoteRepo,resolveRepoRoot,isGitRepo,resolveMainRepoRoot,statePath,getSavedRepos,getPersistedString,setPersistedString,getCustomEngineIds,getDisabledEngineIds,addSavedRepo,backfillSavedReposFromProjects,normalizeSavedRepos,getRepoInitOverride,setRepoInitOverride,removeSavedRepo};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{pathRejection,projectRejection,rejectionReason}from"./chunk-9c1e5z6a.js";import"./chunk-6dn6h640.js";import"./chunk-cb2fpajx.js";import"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";export{rejectionReason,projectRejection,pathRejection};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{basename}from"path";function globToRegExp(glob){let re="";for(let i=0;i<glob.length;i++){let c=glob[i];if(c==="*")if(glob[i+1]==="*")if((i===0||glob[i-1]==="/")&&glob[i+2]==="/")re+="(?:.*/)?",i+=2;else re+=".*",i++;else re+="[^/]*";else if(c==="?")re+="[^/]";else if(c&&"\\^$.|+()[]{}".includes(c))re+=`\\${c}`;else re+=c}return new RegExp(`^${re}$`)}function matchPathGlob(glob,p){let re;try{re=globToRegExp(glob)}catch{return!1}return re.test(p)||re.test(basename(p))}
3
+ export{matchPathGlob};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ var PLUGIN_EVENT_NAMES=["task.created","task.deleted","task.changed","task.landed","task.pr-changed","worktree.created","issue.changed","note.filed","message.delivered","attention.handled","automation.dispatched","automation.skipped","automation.failed","quota.exhausted","quota.resumed","session.exited","plugin.enabled","plugin.disabled","agent.turn-complete","agent.permission-needed","agent.rate-limited","agent.error","agent.running","agent.idle","session.start","session.end","turn.prompt","turn.complete","turn.failed","turn.interrupted","tool.pre","tool.post","tool.failed","attention.permission","attention.question","context.pre-compact","context.post-compact","subagent.start","subagent.stop","file.will-open","file.opened","file.closed","task.opened","project.opened","tab.opened","tab.closed"],DAEMON_CHANNELS=["task.snapshot","issue.snapshot","active-task","update","engine-state","attention.inbox","ui-prefs","keybindings","task.jobs","worktree.changes","transcript.activity","session.deliver","tab.open","tab.close","engine.lifecycle","notice.event","usage.snapshot","usage.context","ui.prompt"];
3
+ export{PLUGIN_EVENT_NAMES,DAEMON_CHANNELS};
@@ -0,0 +1,16 @@
1
+ // @bun
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,DEFAULT_RELEASE_CHANNEL,RELEASE_CHANNELS,UPDATE_COMMAND,UPDATE_SCRIPT_URL,breakingVersionsCrossed,channelOf,checkLatestVersion,fetchReleaseSummaries,recommendedGlobalInstallCommand}from"./chunk-eq5f3z2f.js";import"./chunk-6dn6h640.js";import{activeCliName}from"./chunk-ef11h2am.js";import"./chunk-8ddjfc2v.js";import"./chunk-cb2fpajx.js";import"./chunk-3bfm4hrs.js";import{__require}from"./chunk-wqfp8d9w.js";import{spawnSync}from"child_process";var CLI_NAME=activeCliName();function updatePlan(target){let shell=target===void 0?UPDATE_COMMAND:`${UPDATE_COMMAND} -s -- ${target}`;return{command:"sh",args:["-c",shell],display:shell}}var VERSION_SHAPE=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;function isReleaseChannel(value){return RELEASE_CHANNELS.includes(value)}function parseUpdateArgs(args){let dryRun=!1,list=!1,version,channel;for(let i=0;i<args.length;i+=1){let arg=args[i];if(arg===void 0)continue;if(arg==="--help"||arg==="-h"||arg==="help")return{help:!0,dryRun,list,version,channel};if(arg==="dry-run"||arg==="--dry-run"){dryRun=!0;continue}if(arg==="list"||arg==="--list"){list=!0;continue}if(arg==="--channel"||arg.startsWith("--channel=")){let value=(arg.startsWith("--channel=")?arg.slice(10):void 0)??args[++i];if(value===void 0||!isReleaseChannel(value))process.stderr.write(`${CLI_NAME} update: --channel expects one of ${RELEASE_CHANNELS.join(", ")}${value===void 0?"":` (got "${value}")`}
3
+
4
+ `),printUsage(process.stderr),process.exit(2);channel=value;continue}if(channel===void 0&&isReleaseChannel(arg)){channel=arg;continue}if(version===void 0&&VERSION_SHAPE.test(arg)){version=arg;continue}process.stderr.write(`${CLI_NAME} update: unknown argument "${arg}"
5
+
6
+ `),printUsage(process.stderr),process.exit(2)}return{help:!1,dryRun,list,version,channel}}function printUsage(out){out.write([`Usage: ${CLI_NAME} update [version|channel|list|dry-run]`,"","Runs Rove's GitHub-hosted update script. With [version] (e.g.","0.7.90) the script installs that exact release instead of the","head of your channel.","","Verbs (--flag spellings also accepted):"," list Browse recent versions \u2014 a TUI page with release notes"," when interactive, plain text when piped"," dry-run Print the command without running it","","Channels:"," latest Stable releases (default)"," nightly Automated nightly cut from main \u2014 newer, less baked","",`You are on: ${channelOf()}`,"","Switching channels is just installing from the other one; there is","no stored setting. Update checks follow the build you are running.","","Default command:",` ${UPDATE_COMMAND}`,"","Script URL:",` ${UPDATE_SCRIPT_URL}`,"","Manual fallback:",` ${recommendedGlobalInstallCommand()}`,"","Examples:",` ${CLI_NAME} update`,` ${CLI_NAME} update 0.7.90`,` ${CLI_NAME} update nightly`,` ${CLI_NAME} update --channel latest`,` ${CLI_NAME} update list`,` ${CLI_NAME} update dry-run`,""].join(`
7
+ `))}async function printVersionList(io){let releases=await fetchReleaseSummaries(20);if(releases.length===0)io.stderr.write(`${CLI_NAME} update: could not fetch the release list (offline or rate-limited)
8
+ `),io.exit(1);for(let release of releases){let markers=[release.version===CURRENT_VERSION?"(current)":"",BREAKING_VERSIONS.includes(release.version)?`(breaking \u2014 needs \`${CLI_NAME} reset\`)`:""].filter(Boolean).join(" ");io.stdout.write(`${release.version}${markers?` ${markers}`:""}
9
+ `)}io.stdout.write(`
10
+ install one with: ${CLI_NAME} update <version>
11
+ `)}async function warnBreakingCrossings(target,channel,io){if(BREAKING_VERSIONS.length===0)return;let resolved=target??(await checkLatestVersion({force:!0,channel}))?.latest;if(!resolved)return;let crossed=breakingVersionsCrossed(CURRENT_VERSION,resolved);if(crossed.length===0)return;io.stderr.write([`warning: ${CURRENT_VERSION} -> ${resolved} crosses breaking version(s): ${crossed.join(", ")}.`,`After this update, Rove will refuse to start until you run \`${CLI_NAME} reset\``,"(worktrees are never touched; add --hard only to also wipe the task index).",""].join(`
12
+ `))}async function runUpdateSubcommand(args,deps){let io={spawn:deps?.spawn??spawnSync,stdout:deps?.stdout??process.stdout,stderr:deps?.stderr??process.stderr,exit:deps?.exit??((code)=>process.exit(code))},parsed=parseUpdateArgs(args);if(parsed.help){printUsage(io.stdout);return}if(parsed.list){if(deps===void 0&&process.stdout.isTTY){let{startVersionsHost}=await import("./chunk-yn5a7xcv.js");await startVersionsHost();return}await printVersionList(io);return}let channel=parsed.channel??channelOf(),target=parsed.version??(channel===DEFAULT_RELEASE_CHANNEL?void 0:channel),plan=updatePlan(target),switching=parsed.channel!==void 0&&parsed.channel!==channelOf();if(io.stdout.write(`${CLI_NAME} ${CURRENT_VERSION} -> ${target??channel}
13
+ `),switching)io.stdout.write(`switching channel: ${channelOf()} -> ${channel}
14
+ `);if(io.stdout.write(`running: ${plan.display}
15
+ `),parsed.dryRun)return;await warnBreakingCrossings(parsed.version,channel,io);let result=io.spawn(plan.command,plan.args,{stdio:"inherit"});if(result.error)io.stderr.write(`${CLI_NAME} update: failed to run ${plan.command}: ${result.error.message}
16
+ `),io.exit(1);io.exit(result.status??1)}export{updatePlan,runUpdateSubcommand,parseUpdateArgs};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{StaleInstallError,autospawnDaemonEnv,connectIfRunning,connectOrStartDaemon,detachOptions,ensureDaemonReachable,isStaleInstallError,probeDaemonSocket,resolveKobeSpawn,spawnDetachedDaemon,testDaemonResponds,tryAcquireSpawnLock}from"./chunk-5bn91n19.js";import"./chunk-pdh5w4ht.js";import"./chunk-4wwx51m5.js";import"./chunk-79gqh5p2.js";import"./chunk-3ztek08w.js";import"./chunk-kwe61yx7.js";import"./chunk-grh6dvfv.js";import"./chunk-pw6yfj10.js";import"./chunk-x760j10f.js";import"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";export{tryAcquireSpawnLock,testDaemonResponds,spawnDetachedDaemon,resolveKobeSpawn,probeDaemonSocket,isStaleInstallError,ensureDaemonReachable,detachOptions,connectOrStartDaemon,connectIfRunning,autospawnDaemonEnv,StaleInstallError};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{TaskDeletingError,deriveTitleFromPrompt}from"./chunk-aq912vvw.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp,sessionHasEngine,trustEngineWorktree}from"./chunk-adez6hq4.js";import{engineLaunchArgv,protocolEntry}from"./chunk-q7dr9eh6.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{engineEntry}from"./chunk-yhcz2d2r.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";var MAX_SESSIONS_SCANNED=8;function titleFromMessages(messages){let firstUser=messages.find((m)=>m.role==="user");if(!firstUser)return"";let text=firstUser.blocks.filter((b)=>b.type==="text").map((b)=>b.text).join(" "),title=deriveTitleFromPrompt(text);return title.length>0?Buffer.from(title,"utf8").toString("utf8"):title}async function deriveTitleFromSession(worktree,vendor=DEFAULT_TASK_VENDOR){if(!worktree)return"";let{history}=protocolEntry(vendor),ids=await history.listSessionIdsForWorktree(worktree);for(let sessionId of ids.slice(0,MAX_SESSIONS_SCANNED)){let title=titleFromMessages(await history.readHistory(sessionId));if(title)return title}return""}async function deriveTitleFromSessionId(vendor,sessionId){if(!sessionId)return"";try{return titleFromMessages(await protocolEntry(vendor).history.readHistory(sessionId))}catch{return""}}async function getTask(link,taskId){let{task}=await link.request("task.get",{taskId});return task}async function ensureTaskWorktree(link,taskId){let task=await getTask(link,taskId);if(task.deletion)throw new TaskDeletingError(taskId);if(task.worktreePath)return{task,worktreePath:task.worktreePath};let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"}),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)throw Error(`failed to start hosted engine session for ${taskId}`);if(launch.firstMessage){let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort})[0];await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs}).catch(()=>!1)}}finally{host.close()}return{session:launch.key,worktreePath}}async function startTaskSessionWithPromptAdapter(link,taskId,prompt){let{task,worktreePath}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt}),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)return{started:!1,error:"hosted session did not open"};let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort})[0],wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs};if(launch.firstMessage){if(await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,wait)!==null)return{started:!0};return{started:!1,error:await startFailureReason(host.rpc,launch.key)}}if(await awaitEngineProcess(host.rpc,launch.key,engineBin,wait)!==null)return{started:!0};return{started:!1,error:await startFailureReason(host.rpc,launch.key)}}finally{host.close()}}async function startFailureReason(rpc,key){let tail=await hostedSessionFailureLine(rpc,key),base="engine process never started";return tail?`engine process never started; last session output: ${tail}`:"engine process never started"}function taskEngineLaunch(task,worktreePath,promptIntent){return trustEngineWorktree(task.vendor,worktreePath),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo},worktreePath,shell:resolveLoginShell({fallback:"/bin/zsh"}),argv:engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort}),promptIntent})}async function deliverPromptToLiveEngineAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return!1;try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0]);if(!key)return!1;if(!await sessionHasEngine(sessions.find((s)=>s.key===key)?.pid,engineArgv))return!1;let manifest=task.vendor?engineEntry(task.vendor).screenManifest:void 0;return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})!==null}catch(err){if(err instanceof ComposerBusyError)throw err;return!1}finally{host.close()}}function tabIdFromHostedKey(key){return key.split("::")[1]??"tab-1"}async function deliverPromptToLiveEngineDetailedAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0]);if(!key)return{outcome:"no-session"};if(!await sessionHasEngine(sessions.find((s)=>s.key===key)?.pid,engineArgv))return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};let manifest=task.vendor?engineEntry(task.vendor).screenManifest:void 0;try{return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}catch(err){if(err instanceof ComposerBusyError)return{outcome:"busy",tabId:tabIdFromHostedKey(key),layer:err.layer};throw err}}catch{return{outcome:"no-session"}}finally{host.close()}}async function deliverPromptToLiveEngineTabDetailedAdapter(target,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let key=`${target.id}::${target.tabId}`,sessions;try{sessions=await listHostedSessions(host.rpc)}catch{return{outcome:"no-session"}}let session=sessions.find((candidate)=>candidate.alive&&candidate.key===key);if(!session)return{outcome:"no-session"};let engineArgv=engineLaunchArgv({command:target.command,vendor:target.vendor});if(!await sessionHasEngine(session.pid,engineArgv))return{outcome:"no-engine",tabId:target.tabId};let manifest=target.vendor?engineEntry(target.vendor).screenManifest:void 0;try{return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}catch(err){if(err instanceof ComposerBusyError)return{outcome:"busy",tabId:target.tabId,layer:err.layer};throw err}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId){let host=await openHostedSessionHost();if(!host)return;try{await killHostedSessions(host.rpc,hostedTaskKeys(await listHostedSessions(host.rpc),taskId))}catch{}finally{host.close()}}
3
+ export{deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,tearDownTaskSessionAdapter};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{addRemoteRepo,addSavedRepo,backfillSavedReposFromProjects,getCustomEngineIds,getDisabledEngineIds,getPersistedString,getRemoteRepoConfig,getRemoteRepos,getRepoInitOverride,getSavedRepos,isGitRepo,isRemoteProjectsEnabled,isRemoteRepoKey,normalizeSavedRepos,remoteRepoKey,removeSavedRepo,resolveMainRepoRoot,resolveRepoRoot,setPersistedString,setRepoInitOverride,statePath}from"./chunk-k3ksts6g.js";import"./chunk-gjf604bb.js";import"./chunk-9c1e5z6a.js";import"./chunk-6dn6h640.js";import"./chunk-cb2fpajx.js";import"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";export{statePath,setRepoInitOverride,setPersistedString,resolveRepoRoot,resolveMainRepoRoot,removeSavedRepo,remoteRepoKey,normalizeSavedRepos,isRemoteRepoKey,isRemoteProjectsEnabled,isGitRepo,getSavedRepos,getRepoInitOverride,getRemoteRepos,getRemoteRepoConfig,getPersistedString,getDisabledEngineIds,getCustomEngineIds,backfillSavedReposFromProjects,addSavedRepo,addRemoteRepo};
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-eq5f3z2f.js";import{loadStateFile,patchStateFile}from"./chunk-gjf604bb.js";import{activeCliName}from"./chunk-ef11h2am.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=activeCliName(),lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
3
+ `)),process.exit(1)}if(lastRun!==CURRENT_VERSION)stampResetGate()}function stampResetGate(){try{patchStateFile({[LAST_RUN_VERSION_KEY]:CURRENT_VERSION})}catch{}}
4
+ export{LAST_RUN_VERSION_KEY,enforceResetGate,stampResetGate};
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{spawnSync}from"child_process";var ENCODER=new TextEncoder,DECODER=new TextDecoder;function isOctalDigit(ch){return ch>="0"&&ch<="7"}function readQuoted(field,start){let bytes=[],lit="",flush=()=>{if(lit.length>0){for(let b of ENCODER.encode(lit))bytes.push(b);lit=""}},i=start+1;while(i<field.length){let ch=field[i];if(ch==='"'){i++;break}if(ch==="\\"){let n=field[i+1];if(n===void 0){lit+="\\",i++;continue}switch(n){case"a":flush(),bytes.push(7),i+=2;break;case"b":flush(),bytes.push(8),i+=2;break;case"t":flush(),bytes.push(9),i+=2;break;case"n":flush(),bytes.push(10),i+=2;break;case"v":flush(),bytes.push(11),i+=2;break;case"f":flush(),bytes.push(12),i+=2;break;case"r":flush(),bytes.push(13),i+=2;break;case'"':lit+='"',i+=2;break;case"\\":lit+="\\",i+=2;break;default:if(isOctalDigit(n)){let oct="",j=i+1;while(j<field.length&&oct.length<3&&isOctalDigit(field[j]))oct+=field[j],j++;flush(),bytes.push(Number.parseInt(oct,8)&255),i=j}else lit+=n,i+=2;break}}else lit+=ch,i++}return flush(),{value:DECODER.decode(new Uint8Array(bytes)),end:i}}function unquoteGitPath(field){if(field.length===0||field[0]!=='"')return field;return readQuoted(field,0).value}function splitRenameField(field,sep){if(field[0]==='"'){let left=readQuoted(field,0);if(field.startsWith(sep,left.end))return{orig:left.value,neu:unquoteGitPath(field.slice(left.end+sep.length))};return null}let idx=field.indexOf(sep);if(idx<0)return null;return{orig:field.slice(0,idx),neu:unquoteGitPath(field.slice(idx+sep.length))}}function parsePorcelainRows(raw){let rows=[];for(let rawLine of raw.split(`
3
+ `)){let line=rawLine.replace(/\r$/,"");if(line.length<4)continue;if(line.startsWith("##"))continue;let x=line[0],y=line[1];if(line[2]!==" ")continue;let rest=line.slice(3);if(x==="R"||x==="C"||y==="R"||y==="C"){let split=splitRenameField(rest," -> ");if(split){rows.push({x,y,path:split.neu,origPath:split.orig});continue}}rows.push({x,y,path:unquoteGitPath(rest)})}return rows}function parseCount(token){if(token==="-")return null;let n=Number.parseInt(token,10);return Number.isNaN(n)?null:n}function parseNumstatRows(raw){let rows=[],fields=raw.split("\x00");if(fields.length>0&&fields[fields.length-1]==="")fields.pop();let i=0;while(i<fields.length){let header=fields[i],tab1=header.indexOf("\t");if(tab1<0){i++;continue}let tab2=header.indexOf("\t",tab1+1);if(tab2<0){i++;continue}let added=parseCount(header.slice(0,tab1)),deleted=parseCount(header.slice(tab1+1,tab2)),pathField=header.slice(tab2+1);if(pathField.length>0)rows.push({path:unquoteGitPath(pathField),added,deleted}),i++;else{if(i+2>=fields.length)break;rows.push({path:unquoteGitPath(fields[i+2]),origPath:unquoteGitPath(fields[i+1]),added,deleted}),i+=3}}return rows}var ZERO={added:0,deleted:0};function sameWorktreeChanges(a,b){if(a===null||b===null)return a===b;return a.added===b.added&&a.deleted===b.deleted&&a.behind===b.behind&&a.ahead===b.ahead}function pickPushedChanges(pushed,worktreePath){if(!pushed)return null;if(pushed.has(worktreePath))return pushed.get(worktreePath)??"unknown";return ZERO}function readWorktreeChanges(worktreePath){if(!worktreePath)return null;try{let out=spawnSync("git",["status","--porcelain=v1"],{cwd:worktreePath,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:readOnlyGitProcessEnv()});if(out.status!==0||out.stdout===void 0||out.stdout===null)return null;return parsePorcelain(out.stdout)}catch{return null}}function parsePorcelain(text){let added=0,deleted=0;for(let{x,y}of parsePorcelainRows(text))if(x==="D"||y==="D")deleted+=1;else added+=1;return{added,deleted}}
4
+ export{unquoteGitPath,parsePorcelainRows,parseNumstatRows,sameWorktreeChanges,pickPushedChanges,readWorktreeChanges,parsePorcelain};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{loadPluginRegistry,pluginConfigDir,pluginDataDir,pluginLogPath,pluginRegistryPath,pluginStateDir,pluginsRootDir}from"./chunk-jyv82gf0.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-4wwx51m5.js";import{chmodSync}from"fs";function tighten(path,mode){try{chmodSync(path,mode)}catch{}}function tightenPluginPermissions(id,homeDir){tighten(pluginDataDir(id,homeDir),OWNER_ONLY_DIR_MODE),tighten(pluginConfigDir(id,homeDir),OWNER_ONLY_DIR_MODE),tighten(pluginStateDir(id,homeDir),OWNER_ONLY_DIR_MODE),tighten(`${pluginConfigDir(id,homeDir)}/.env`,OWNER_ONLY_FILE_MODE),tighten(pluginLogPath(id,homeDir),OWNER_ONLY_FILE_MODE)}function tightenInstalledPluginPermissions(homeDir){tighten(pluginsRootDir(homeDir),OWNER_ONLY_DIR_MODE),tighten(pluginRegistryPath(homeDir),OWNER_ONLY_FILE_MODE);for(let entry of loadPluginRegistry(homeDir).plugins)tightenPluginPermissions(entry.id,homeDir)}var MONTH_NAMES=new Map([["JAN",1],["FEB",2],["MAR",3],["APR",4],["MAY",5],["JUN",6],["JUL",7],["AUG",8],["SEP",9],["OCT",10],["NOV",11],["DEC",12]]),DAY_NAMES=new Map([["SUN",0],["MON",1],["TUE",2],["WED",3],["THU",4],["FRI",5],["SAT",6]]);function fieldNumber(raw,names,field){let token=raw.toUpperCase(),named=names?.get(token);if(named!==void 0)return named;if(!/^\d+$/.test(token))throw Error(`invalid cron ${field}: ${raw}`);return Number(token)}function parseField(args){let out=new Set;for(let part of args.value.split(",")){if(part.length===0)throw Error(`invalid cron ${args.field}: ${args.value}`);let[spec,stepRaw,...extra]=part.split("/");if(extra.length>0||spec===void 0)throw Error(`invalid cron ${args.field}: ${part}`);let step=1;if(stepRaw!==void 0){if(!/^\d+$/.test(stepRaw))throw Error(`invalid cron ${args.field} step: ${part}`);if(step=Number(stepRaw),step<1)throw Error(`invalid cron ${args.field} step: ${part}`)}let lo,hi;if(spec==="*")lo=args.min,hi=args.max;else if(spec.includes("-")){let[loRaw,hiRaw,...rest]=spec.split("-");if(rest.length>0||loRaw===void 0||hiRaw===void 0)throw Error(`invalid cron ${args.field} range: ${part}`);lo=fieldNumber(loRaw,args.names,args.field),hi=fieldNumber(hiRaw,args.names,args.field)}else lo=fieldNumber(spec,args.names,args.field),hi=stepRaw===void 0?lo:args.max;if(lo<args.min||hi>args.max||lo>hi)throw Error(`cron ${args.field} out of range: ${part}`);for(let v=lo;v<=hi;v+=step)out.add(args.normalize?args.normalize(v):v)}return out}function parseCron(expression){if(expression.length>256)throw Error("cron expression is too long");let fields=expression.trim().split(/\s+/).filter(Boolean);if(fields.length!==5)throw Error(`cron expression needs 5 fields (minute hour day month weekday), got ${fields.length}`);let[minute,hour,dayOfMonth,month,dayOfWeek]=fields;return{minutes:parseField({value:minute,min:0,max:59,field:"minute"}),hours:parseField({value:hour,min:0,max:23,field:"hour"}),daysOfMonth:parseField({value:dayOfMonth,min:1,max:31,field:"day-of-month"}),months:parseField({value:month,min:1,max:12,field:"month",names:MONTH_NAMES}),daysOfWeek:parseField({value:dayOfWeek,min:0,max:7,field:"weekday",names:DAY_NAMES,normalize:(v)=>v%7}),dayOfMonthRestricted:dayOfMonth!=="*",dayOfWeekRestricted:dayOfWeek!=="*"}}function isValidCron(expression){try{return parseCron(expression),!0}catch{return!1}}function instantOf(d,hour,minute){return new Date(d.year,d.month-1,d.day,hour,minute,0,0).getTime()}function localDayOf(ms){let d=new Date(ms);return{year:d.getFullYear(),month:d.getMonth()+1,day:d.getDate()}}function shiftDay(d,delta){return localDayOf(new Date(d.year,d.month-1,d.day+delta,12,0,0,0).getTime())}function dayMatches(rule,d){if(!rule.months.has(d.month))return!1;let domMatch=rule.daysOfMonth.has(d.day),dowMatch=rule.daysOfWeek.has(new Date(d.year,d.month-1,d.day).getDay());if(rule.dayOfMonthRestricted&&rule.dayOfWeekRestricted)return domMatch||dowMatch;if(rule.dayOfMonthRestricted)return domMatch;if(rule.dayOfWeekRestricted)return dowMatch;return!0}function floorToMinute(ms){return ms-ms%60000}function sorted(values,direction){return[...values].sort((a,b)=>(a-b)*direction)}function nextCronAfter(expression,afterMs){let rule=parseCron(expression),hours=sorted(rule.hours,1),minutes=sorted(rule.minutes,1),from=new Date(floorToMinute(afterMs)+60000),day=localDayOf(from.getTime()),fromHour=from.getHours(),fromMinute=from.getMinutes();for(let i=0;i<3294;i++){if(dayMatches(rule,day))for(let hour of hours){if(hour<fromHour)continue;for(let minute of minutes){if(hour===fromHour&&minute<fromMinute)continue;let at=instantOf(day,hour,minute);if(at>afterMs)return at}}day=shiftDay(day,1),fromHour=0,fromMinute=0}throw Error(`cron expression never matches: ${expression}`)}function latestCronAtOrBefore(expression,nowMs,notBeforeMs){if(nowMs<notBeforeMs)return null;let rule=parseCron(expression),hours=sorted(rule.hours,-1),minutes=sorted(rule.minutes,-1),from=new Date(floorToMinute(nowMs)),day=localDayOf(from.getTime()),fromHour=from.getHours(),fromMinute=from.getMinutes();for(let i=0;i<3294;i++){if(instantOf(day,23,59)<notBeforeMs)return null;if(dayMatches(rule,day))for(let hour of hours){if(hour>fromHour)continue;for(let minute of minutes){if(hour===fromHour&&minute>fromMinute)continue;let at=instantOf(day,hour,minute);if(at>nowMs)continue;return at>=notBeforeMs?at:null}}day=shiftDay(day,-1),fromHour=23,fromMinute=59}return null}function countCronBetween(expression,fromMs,beforeMs,cap=500){if(!(fromMs<beforeMs))return 0;let count=0,cursor=fromMs-1;while(count<cap){let at;try{at=nextCronAfter(expression,cursor)}catch{return count}if(at>=beforeMs)return count;count+=1,cursor=at}return count}
3
+ export{tightenPluginPermissions,tightenInstalledPluginPermissions,isValidCron,nextCronAfter,latestCronAtOrBefore,countCronBetween};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ function formatBytes(n){if(n<1024)return`${n} B`;let units=["KB","MB","GB","TB"],v=n/1024,i=0;while(v>=1023.5&&i<units.length-1)v/=1024,i++;let oneDecimal=v.toFixed(1);return`${Number(oneDecimal)>=100?Math.round(v):oneDecimal} ${units[i]}`}
3
+ export{formatBytes};