@sma1lboy/rove 0.9.302-next.413 → 0.9.304

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 (102) hide show
  1. package/dist/cli/chunk-0r64dqy3.js +3 -0
  2. package/dist/cli/{chunk-vn0rnzyt.js → chunk-16sb3y82.js} +1 -1
  3. package/dist/cli/chunk-1fw86kg2.js +2 -0
  4. package/dist/cli/{chunk-bz0zm1kd.js → chunk-1w2dx91w.js} +1 -1
  5. package/dist/cli/{chunk-xjf4k0xf.js → chunk-22syh28c.js} +1 -1
  6. package/dist/cli/chunk-2ze5ss4k.js +2 -0
  7. package/dist/cli/chunk-46zqt24x.js +2 -0
  8. package/dist/cli/{chunk-r2ez4ker.js → chunk-4whghfgg.js} +1 -1
  9. package/dist/cli/{chunk-0et8q8pm.js → chunk-5gw9f1zb.js} +4 -4
  10. package/dist/cli/{chunk-gej20ab5.js → chunk-689sfk7h.js} +1 -1
  11. package/dist/cli/{chunk-s29k086j.js → chunk-6b852k6c.js} +1 -1
  12. package/dist/cli/chunk-6y1jamqn.js +2 -0
  13. package/dist/cli/{chunk-gwnxv2rz.js → chunk-76433s6v.js} +1 -1
  14. package/dist/cli/{chunk-qnjnb133.js → chunk-7c89khwg.js} +1 -1
  15. package/dist/cli/{chunk-zye0b9c0.js → chunk-7d22h7qg.js} +1 -1
  16. package/dist/cli/{chunk-6h8sxpmj.js → chunk-7w43ktng.js} +1 -1
  17. package/dist/cli/{chunk-x6w8cdbk.js → chunk-7z2bmv13.js} +1 -1
  18. package/dist/cli/{chunk-w2k5rw0q.js → chunk-7zawz6sa.js} +4 -4
  19. package/dist/cli/chunk-8647s43m.js +2 -0
  20. package/dist/cli/chunk-8xdhw922.js +13 -0
  21. package/dist/cli/{chunk-5ff40r8a.js → chunk-ahnv378z.js} +1 -1
  22. package/dist/cli/chunk-akygcre8.js +2 -0
  23. package/dist/cli/chunk-am3vaamq.js +2 -0
  24. package/dist/cli/{chunk-r4q693ge.js → chunk-ammf7919.js} +1 -1
  25. package/dist/cli/{chunk-4ayp6znk.js → chunk-b7bbnx1x.js} +1 -1
  26. package/dist/cli/{chunk-mkbyb8d1.js → chunk-b8hd91nv.js} +3 -3
  27. package/dist/cli/{chunk-fpecy1fw.js → chunk-bznee97z.js} +1 -1
  28. package/dist/cli/chunk-cb3krnqn.js +2 -0
  29. package/dist/cli/{chunk-kbqgzx65.js → chunk-cmbd3s71.js} +11 -11
  30. package/dist/cli/chunk-cw9h73h5.js +12 -0
  31. package/dist/cli/{chunk-9vmd0bhr.js → chunk-d3d06a4w.js} +1 -1
  32. package/dist/cli/{chunk-j3zj2gm6.js → chunk-d4eav2xt.js} +1 -1
  33. package/dist/cli/{chunk-e0fgmktj.js → chunk-d4w91a02.js} +1 -1
  34. package/dist/cli/chunk-d9e1vx7y.js +15 -0
  35. package/dist/cli/{chunk-rnrja9fy.js → chunk-e04yypye.js} +2 -2
  36. package/dist/cli/{chunk-z9tgh00y.js → chunk-emj5p5k7.js} +1 -1
  37. package/dist/cli/chunk-fg7kv30n.js +2 -0
  38. package/dist/cli/{chunk-r79n2ebq.js → chunk-g770enx5.js} +2 -2
  39. package/dist/cli/{chunk-jpjabj96.js → chunk-ga0kvz6j.js} +1 -1
  40. package/dist/cli/{chunk-rw890y60.js → chunk-gb2ahsfx.js} +1 -1
  41. package/dist/cli/{chunk-63ktckgj.js → chunk-gd8gc37t.js} +1 -1
  42. package/dist/cli/{chunk-rmmetv42.js → chunk-gdjaf50p.js} +1 -1
  43. package/dist/cli/{chunk-j7k15ems.js → chunk-gpmpv5gw.js} +1 -1
  44. package/dist/cli/{chunk-nwz00nba.js → chunk-gr9555d9.js} +1 -1
  45. package/dist/cli/{chunk-7qxvdms8.js → chunk-j1rw5jdt.js} +1 -1
  46. package/dist/cli/chunk-jb63kaer.js +20 -0
  47. package/dist/cli/{chunk-k6wxbh9e.js → chunk-jkxn32nk.js} +1 -1
  48. package/dist/cli/{chunk-m1dgjq5f.js → chunk-jx0sfc90.js} +1 -1
  49. package/dist/cli/{chunk-d6nhhxmh.js → chunk-kyddm7xe.js} +1 -1
  50. package/dist/cli/{chunk-gqkpq2hm.js → chunk-m6ekn4q8.js} +1 -1
  51. package/dist/cli/{chunk-06kf5yg7.js → chunk-mb2tfr2c.js} +2 -2
  52. package/dist/cli/{chunk-xzhb4qs8.js → chunk-mdypt84n.js} +1 -1
  53. package/dist/cli/{chunk-han0d078.js → chunk-pe92nt86.js} +1 -1
  54. package/dist/cli/{chunk-hafbyy9x.js → chunk-q6q4aram.js} +2 -2
  55. package/dist/cli/{chunk-gx3j06wx.js → chunk-q8b6gnc5.js} +1 -1
  56. package/dist/cli/{chunk-d11v35wg.js → chunk-qjr63j9v.js} +1 -1
  57. package/dist/cli/{chunk-e4gepsz1.js → chunk-qnkq7d8z.js} +2 -2
  58. package/dist/cli/chunk-r9yx4k0q.js +6 -0
  59. package/dist/cli/{chunk-bwcyr929.js → chunk-rajwag3e.js} +1 -1
  60. package/dist/cli/chunk-scb1g3zf.js +2 -0
  61. package/dist/cli/{chunk-pbc7wz8k.js → chunk-sd6eae1h.js} +5 -5
  62. package/dist/cli/{chunk-37we82a4.js → chunk-sfskhmzp.js} +1 -1
  63. package/dist/cli/{chunk-r9c7txh5.js → chunk-tr9n297x.js} +2 -2
  64. package/dist/cli/{chunk-hykerb6a.js → chunk-tzf7b25k.js} +1 -1
  65. package/dist/cli/{chunk-0dwn2emg.js → chunk-vk2xz0s4.js} +4 -4
  66. package/dist/cli/{chunk-1wnjq6ej.js → chunk-wjz55sc3.js} +1 -1
  67. package/dist/cli/{chunk-r0p3qshx.js → chunk-x3c6f2sf.js} +1 -1
  68. package/dist/cli/{chunk-nb99x2kt.js → chunk-x4gqyhhv.js} +2 -5
  69. package/dist/cli/{chunk-1a9b3pv2.js → chunk-xhtzck2v.js} +1 -1
  70. package/dist/cli/chunk-xrg2tc6p.js +2 -0
  71. package/dist/cli/{chunk-gz3sxsp7.js → chunk-yebkeqj2.js} +1 -1
  72. package/dist/cli/{chunk-z9wneamr.js → chunk-ykm19q7h.js} +1 -1
  73. package/dist/cli/{chunk-f69jsv6b.js → chunk-ytx7x3j8.js} +1 -1
  74. package/dist/cli/{chunk-bpvx5c14.js → chunk-zpdvfb01.js} +1 -1
  75. package/dist/cli/chunk-zshgx9fp.js +6 -0
  76. package/dist/cli/index.js +3 -3
  77. package/dist/cli/rove.js +3 -3
  78. package/dist/web/assets/index-CdiGbCTZ.css +1 -0
  79. package/dist/web/assets/index-D9TLg2oV.js +84 -0
  80. package/dist/web/assets/{term-mount-BMZoD8Pz.js → term-mount-Cn86hde_.js} +1 -1
  81. package/dist/web/index.html +2 -2
  82. package/dist/web/relay/index.html +4 -4
  83. package/package.json +3 -3
  84. package/dist/cli/chunk-0fp12xka.js +0 -2
  85. package/dist/cli/chunk-22w1w79j.js +0 -2
  86. package/dist/cli/chunk-24v4zec6.js +0 -2
  87. package/dist/cli/chunk-5qhcp29a.js +0 -2
  88. package/dist/cli/chunk-7108m3qy.js +0 -6
  89. package/dist/cli/chunk-8d6xcvar.js +0 -2
  90. package/dist/cli/chunk-8z73wx8z.js +0 -2
  91. package/dist/cli/chunk-9dyc2wh8.js +0 -2
  92. package/dist/cli/chunk-9g86yj8d.js +0 -2
  93. package/dist/cli/chunk-abrs0bnr.js +0 -15
  94. package/dist/cli/chunk-e99pbfjx.js +0 -2
  95. package/dist/cli/chunk-fphcr46j.js +0 -3
  96. package/dist/cli/chunk-jc32k4kz.js +0 -20
  97. package/dist/cli/chunk-q8brjhze.js +0 -6
  98. package/dist/cli/chunk-s889e8z0.js +0 -2
  99. package/dist/cli/chunk-wxrf9ca8.js +0 -2
  100. package/dist/cli/chunk-yv86xb1s.js +0 -13
  101. package/dist/web/assets/index-DSdc8V8J.css +0 -1
  102. package/dist/web/assets/index-yhJ5VDGJ.js +0 -84
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{isPathLikeArg,runOpenDirectory}from"./chunk-zye0b9c0.js";import"./chunk-1feav1w3.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runOpenDirectory,isPathLikeArg};
2
+ import{isPathLikeArg,runOpenDirectory}from"./chunk-7d22h7qg.js";import"./chunk-1feav1w3.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runOpenDirectory,isPathLikeArg};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{getGlobalDefaultVendor}from"./chunk-2x6s7z8w.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-fphcr46j.js";import{runAsync}from"./chunk-nw48bskt.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000,GH_TIMEOUT_MS=60000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
2
+ import{getGlobalDefaultVendor}from"./chunk-2x6s7z8w.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-0r64dqy3.js";import{runAsync}from"./chunk-nw48bskt.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000,GH_TIMEOUT_MS=60000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
3
3
  `)}function normalizeText(value,label){let trimmed=value.trim();if(!trimmed)throw Error(`${label} is required`);return trimmed}function issueCreateArgv(slug,title,kind){return["issue","create","-R",slug,"--title",title,"--label",KIND_LABEL[kind],"--body-file","-"]}function newIssueUrl(slug,title,body,kind){let prefilled=body.length>MAX_PREFILL_BODY?`${body.slice(0,MAX_PREFILL_BODY)}
4
4
 
5
5
  [truncated]`:body,query=new URLSearchParams({title,body:prefilled,labels:KIND_LABEL[kind]});return`https://github.com/${slug}/issues/new?${query.toString()}`}var ISSUE_URL=/https:\/\/\S+\/issues\/(\d+)/;async function submitFeedback(input,deps={}){let title=normalizeText(input.title,"feedback title"),kind=input.kind??DEFAULT_FEEDBACK_KIND,body=`${normalizeText(input.body,"feedback body")}
@@ -1,8 +1,5 @@
1
1
  // @bun
2
- import{machineSocketDir,machineSshArgs,sshTargetOf}from"./chunk-q6qmv2jq.js";import{shQuote}from"./chunk-y1xnjx8x.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-g6wb8p4p.js";function isWindowsPath(path){return/^[A-Za-z]:[\\/]/.test(path)||/^\\\\[.?]\\/.test(path)}function isWindowsMachine(config){if(config.sockets&&(isWindowsPath(config.sockets.daemon)||isWindowsPath(config.sockets.pty)))return!0;return config.roveBin!==void 0&&isWindowsPath(config.roveBin)}function psQuote(value){return`'${value.replaceAll("'","''")}'`}function powershellCommand(script){return`powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand ${Buffer.from(script,"utf16le").toString("base64")}`}function windowsRoveCommand(roveBin,args){return powershellCommand(`& ${psQuote(roveBin)} ${args.map(psQuote).join(" ")}; exit $LASTEXITCODE`)}var WINDOWS_LOCATE_SCRIPT=['$dirs = @("$env:APPDATA\\npm", "$env:USERPROFILE\\.bun\\bin", "$env:LOCALAPPDATA\\pnpm", $env:NVM_SYMLINK)',"$dirs += [Environment]::GetEnvironmentVariable('Path', 'User') -split ';'","foreach ($d in $dirs) { if (-not $d) { continue }",` foreach ($n in 'rove.cmd', 'rove.exe') { $p = Join-Path $d $n; if (Test-Path -LiteralPath $p) { "ROVE_BIN=$p"; exit 0 } } }`,"exit 1"].join(`
3
- `),WINDOWS_LOCATE_ROVE=powershellCommand(WINDOWS_LOCATE_SCRIPT),WINDOWS_ROVE_MISSING=/'(?:[^'\r\n]*[\\/])?rove(?:\.cmd|\.exe|\.ps1)?' is not recognized as (?:an internal or external command|(?:the|a) name of a cmdlet)/i,WINDOWS_SCRIPTS_DISABLED=/rove\.ps1 cannot be loaded because running scripts is disabled/i;function windowsNoRoveMessage(alias,output){if(WINDOWS_SCRIPTS_DISABLED.test(output))return[`${alias}'s ssh sessions run Windows PowerShell, whose execution policy refuses npm's rove.ps1, and no rove.cmd was found to use instead.`,`On ${alias}, either allow scripts for your user: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`,'or make ssh use PowerShell 7 (elevated): New-ItemProperty -Path HKLM:\\SOFTWARE\\OpenSSH -Name DefaultShell -Value "$env:ProgramFiles\\PowerShell\\7\\pwsh.exe" -PropertyType String -Force'].join(`
4
- `);return[`Rove is not on the PATH of ssh sessions on ${alias} (Windows), nor in %APPDATA%\\npm, ~\\.bun\\bin or the user PATH.`,"Install it there in a PowerShell: npm install -g @sma1lboy/rove",`If it is installed elsewhere, add that folder to your user PATH on ${alias}, then restart sshd (elevated: Restart-Service sshd) so new sessions see it.`].join(`
5
- `)}var WINDOWS_SSHD_BANNER=/remote software version OpenSSH_for_Windows/i,WINDOWS_SSHD_STEPS=["Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0","Set-Service sshd -StartupType Automatic; Start-Service sshd","if (-not (Get-NetFirewallRule -Name OpenSSH-Server-In-TCP -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name OpenSSH-Server-In-TCP -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 }"];function windowsAuthorizeKeySteps(publicKey){let key=psQuote(publicKey.trim());return["# Administrator account (elevated PowerShell):",`Add-Content -Path "$env:ProgramData\\ssh\\administrators_authorized_keys" -Value ${key}`,'icacls.exe "$env:ProgramData\\ssh\\administrators_authorized_keys" /inheritance:r /grant "*S-1-5-32-544:F" /grant "SYSTEM:F"',"# Standard account (normal PowerShell):",`New-Item -ItemType Directory -Force "$HOME\\.ssh" | Out-Null; Add-Content -Path "$HOME\\.ssh\\authorized_keys" -Value ${key}`]}import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target,windows=!1){if(windows&&(kind==="refused"||kind==="timeout"))return[`${target} (Windows) ${kind==="refused"?"refused the connection: its OpenSSH Server is not running":"did not answer on the ssh port: its OpenSSH Server is off, or the firewall drops it"}.`,"In an elevated PowerShell there:",...WINDOWS_SSHD_STEPS.map((step)=>` ${step}`)].join(`
2
+ import{machineSocketDir,machineSshArgs,sshTargetOf}from"./chunk-q6qmv2jq.js";import{WINDOWS_LOCATE_ROVE,WINDOWS_ROVE_MISSING,WINDOWS_SCRIPTS_DISABLED,WINDOWS_SSHD_BANNER,WINDOWS_SSHD_STEPS,isWindowsMachine,isWindowsPath,windowsNoRoveMessage,windowsRoveCommand}from"./chunk-cw9h73h5.js";import{shQuote}from"./chunk-y1xnjx8x.js";import{PRE_RENAME_VERSION_KEY}from"./chunk-g6wb8p4p.js";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target,windows=!1){if(windows&&(kind==="refused"||kind==="timeout"))return[`${target} (Windows) ${kind==="refused"?"refused the connection: its OpenSSH Server is not running":"did not answer on the ssh port: its OpenSSH Server is off, or the firewall drops it"}.`,"In an elevated PowerShell there:",...WINDOWS_SSHD_STEPS.map((step)=>` ${step}`)].join(`
6
3
  `);if(windows&&kind==="auth-denied")return`${target} (Windows) rejected every key ssh offered. For an Administrators account, OpenSSH for Windows reads only %ProgramData%\\ssh\\administrators_authorized_keys; ~\\.ssh\\authorized_keys is ignored.`;switch(kind){case"unresolved":return`${target} does not resolve to an address. Check the name, or the Host block in ~/.ssh/config; on a tailnet, check \`tailscale status\`.`;case"refused":return`${target} refused the connection: nothing listens for ssh there. Enable Remote Login / start sshd on it (Windows: \`Start-Service sshd\`, elevated), or pass the right --port.`;case"timeout":return`${target} did not answer. Is it awake and on this network (or VPN / tailnet)?`;case"host-key-changed":return`${target}'s host key CHANGED since you last connected. That is either a reinstall or someone in the middle. If you reinstalled it, remove the old key with \`ssh-keygen -R <host>\` and retry; otherwise stop here.`;case"host-key-unverified":return`${target}'s host key is not trusted yet. Run \`rove machine add\` in a terminal to confirm its fingerprint, or connect once with \`ssh ${target}\`.`;case"auth-denied":return`${target} rejected every key ssh offered. Load your key into ssh-agent, pass --identity <key>, or install a key there with \`ssh-copy-id ${target}\`.`;case"unknown":return`ssh to ${target} failed. Run \`ssh ${target} true\` to see why.`}}async function runOnMachine(alias,config,command,opts={}){try{mkdirSync(machineSocketDir(alias,opts.home),{recursive:!0,mode:448})}catch{}let base=machineSshArgs(alias,config,{home:opts.home,mux:opts.sshFlags===void 0}),argv=[base[0]??"ssh",...opts.sshFlags??[],...base.slice(1),command];return await new Promise((resolve)=>{let stdout="",stderr="",settled=!1,done=(exitCode)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({stdout,stderr,exitCode})},child=spawn(argv[0]??"ssh",argv.slice(1),{stdio:["ignore","pipe","pipe"]}),timer=setTimeout(()=>{child.kill("SIGKILL"),stderr+=`
7
4
  timed out`,done(-1)},opts.timeoutMs??30000);child.stdout?.on("data",(c)=>{stdout+=c.toString()}),child.stderr?.on("data",(c)=>{stderr+=c.toString()}),child.on("error",()=>done(-1)),child.on("close",(code)=>done(code??-1))})}function unansweringDaemonPid(stdout){let match=/\(stale pidfile pid=(\d+)\)/.exec(stdout);return match?Number(match[1]):null}async function discoverMachine(alias,config,opts={}){let found=await probe(alias,config,config.roveBin,opts);if(found.ok||found.code!=="NO_ROVE")return found;let locate=found.windows?WINDOWS_LOCATE_ROVE:LOCATE_ROVE_SCRIPT,located=parseLocatedRove((await runOnMachine(alias,config,locate,opts)).stdout);if(!located||located===config.roveBin)return found;let retry=await probe(alias,config,located,opts);return retry.ok?{...retry,roveBin:located}:retry}function learnedFrom(found){return{sockets:{daemon:found.status.socketPath,pty:found.status.ptySocketPath},...found.roveBin?{roveBin:found.roveBin}:{},...found.status.relayPreamble?{relayPreamble:!0}:{}}}function remoteRove(roveBin,args){if(roveBin&&isWindowsPath(roveBin))return windowsRoveCommand(roveBin,args);return[roveCommand(roveBin),...args].join(" ")}function roveCommand(roveBin){if(!roveBin)return"rove";return`PATH=${shQuote(posix.dirname(roveBin))}:"$PATH" ${shQuote(roveBin)}`}var LOCATE_ROVE_SCRIPT=[`p=$("\${SHELL:-sh}" -lc 'command -v rove' 2>/dev/null)`,'if [ -n "$p" ] && [ -x "$p" ]; then echo "ROVE_BIN=$p"; exit 0; fi','for p in "$HOME/.bun/bin/rove" "$HOME/.npm-global/bin/rove" "$HOME/.local/bin/rove" /opt/homebrew/bin/rove /usr/local/bin/rove "$HOME"/.nvm/versions/node/*/bin/rove; do',' if [ -x "$p" ]; then echo "ROVE_BIN=$p"; exit 0; fi',"done","exit 1"].join(`
8
5
  `);function parseLocatedRove(stdout){return/^ROVE_BIN=((?:\/|[A-Za-z]:\\)\S.*)$/m.exec(stdout)?.[1]?.trim()??null}var ROVE_MISSING=/(?:^|\W)rove:? (?:command not found|not found)|command not found:? rove|\/rove:? No such file or directory|no such file or directory: \S*\/rove\b/i;async function probe(alias,config,roveBin,opts){let status=remoteRove(roveBin,["daemon","status","--json"]),first=await runOnMachine(alias,config,status,opts),parsed=parseStatusJson(first.stdout);if(parsed)return withNoise(windowsReady(alias,parsed),first.stdout);let combined=`${first.stdout}
@@ -10,4 +7,4 @@ ${first.stderr}`.trim();if(WINDOWS_ROVE_MISSING.test(combined)||WINDOWS_SCRIPTS_
10
7
  ${combined}`:remedy}}let pid=unansweringDaemonPid(first.stdout);if(pid&&!isWindowsMachine(config)){if((await runOnMachine(alias,config,`kill -0 ${pid}`,opts)).exitCode===0)return{ok:!1,code:"NO_DAEMON",message:`the Rove daemon on ${alias} (pid ${pid}) is running but did not answer: it is busy or hung. It was left alone, because restarting it stops whatever it is doing. If it stays this way, run \`rove daemon restart\` on ${alias}.`}}let started=await runOnMachine(alias,config,remoteRove(roveBin,["daemon","restart"]),{...opts,timeoutMs:60000}),second=await runOnMachine(alias,config,status,opts),retry=parseStatusJson(second.stdout);if(retry)return withNoise(windowsReady(alias,retry),second.stdout);if(looksLikeOldStatus(second.stdout))return{ok:!1,code:"BAD_STATUS",message:`${alias} runs a Rove too old for machines (its \`daemon status\` reports no pty socket). Upgrade it: \`ssh ${alias} npm i -g @sma1lboy/rove\`.`};return{ok:!1,code:started.exitCode===0?"BAD_STATUS":"NO_DAEMON",message:`could not read a daemon status from ${alias}: ${`${second.stdout}
11
8
  ${second.stderr}
12
9
  ${started.stderr}`.trim()||"no output"}`}}function withNoise(found,stdout){let noise=Buffer.byteLength(stdout.slice(0,Math.max(0,stdout.indexOf("{"))),"utf8");return found.ok&&noise>0?{...found,shellNoise:noise}:found}async function sshServerIsWindows(alias,config,opts={}){let run=await runOnMachine(alias,config,"exit",{...opts,timeoutMs:15000,sshFlags:["-v"]});return WINDOWS_SSHD_BANNER.test(run.stderr)}function windowsReady(alias,status){if(status.relayPreamble||!isWindowsPath(status.socketPath))return{ok:!0,status};return{ok:!1,code:"BAD_STATUS",message:`${alias} runs a Rove too old to serve another machine from Windows (rove ${status.roveVersion||"?"}; it needs \`rove daemon relay --preamble\`). Update it there: \`npm install -g @sma1lboy/rove\`.`}}function firstJsonObject(text){let start=text.indexOf("{");if(start<0)return null;let depth=0,inString=!1,escaped=!1;for(let i=start;i<text.length;i++){let ch=text[i];if(inString){if(escaped)escaped=!1;else if(ch==="\\")escaped=!0;else if(ch==='"')inString=!1;continue}if(ch==='"')inString=!0;else if(ch==="{")depth++;else if(ch==="}"&&--depth===0)return text.slice(start,i+1)}return null}function looksLikeOldStatus(stdout){let json=firstJsonObject(stdout);if(json===null)return!1;try{let raw=JSON.parse(json);return typeof raw.socketPath==="string"&&typeof raw.ptySocketPath!=="string"}catch{return!1}}function parseStatusJson(stdout){let json=firstJsonObject(stdout);if(json===null)return null;let raw;try{raw=JSON.parse(json)}catch{return null}if(!raw||typeof raw!=="object")return null;let o=raw,socketPath=typeof o.socketPath==="string"?o.socketPath:"",ptySocketPath=typeof o.ptySocketPath==="string"?o.ptySocketPath:"";if(!socketPath||!ptySocketPath)return null;return{socketPath,ptySocketPath,homeDir:typeof o.homeDir==="string"?o.homeDir:"",hostname:typeof o.hostname==="string"?o.hostname:"",roveVersion:statusVersion(o),daemonPid:typeof o.daemonPid==="number"?o.daemonPid:0,relayPreamble:o.relayPreamble===!0}}function statusVersion(o){if(typeof o.roveVersion==="string")return o.roveVersion;let old=o[PRE_RENAME_VERSION_KEY];return typeof old==="string"?old:""}
13
- export{isWindowsMachine,windowsAuthorizeKeySteps,runOnMachine,discoverMachine,learnedFrom,remoteRove,sshServerIsWindows};
10
+ export{runOnMachine,discoverMachine,learnedFrom,remoteRove,sshServerIsWindows};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-yv86xb1s.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
2
+ import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-8xdhw922.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-5gw9f1zb.js";import"./chunk-16sb3y82.js";import"./chunk-8hfkcjxm.js";import"./chunk-h9z9x14k.js";import"./chunk-j2k6f128.js";import"./chunk-38hnq4aq.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-79wejcs5.js";import"./chunk-vpm8dfyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-psxhek7n.js";import"./chunk-x3c6f2sf.js";import"./chunk-zpdvfb01.js";import"./chunk-mdx18vtz.js";import"./chunk-q8b6gnc5.js";import"./chunk-r9yx4k0q.js";import"./chunk-7w43ktng.js";import"./chunk-x4gqyhhv.js";import"./chunk-q6qmv2jq.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-2x6s7z8w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-0r64dqy3.js";import"./chunk-kyddm7xe.js";import"./chunk-bznee97z.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-4whghfgg.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-q6q4aram.js";import"./chunk-d9e1vx7y.js";import"./chunk-cw9h73h5.js";import"./chunk-zc7e78mv.js";import"./chunk-pe92nt86.js";import"./chunk-nw48bskt.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-133c884f.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-ahbw1f8n.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-rz5sspn8.js";import"./chunk-hmfqyvet.js";import"./chunk-2bapg0v2.js";import"./chunk-w7zv47mp.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-07665jz6.js";import"./chunk-40dgv828.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-yvg46jh9.js";import"./chunk-xasg8z9e.js";import"./chunk-8xdhw922.js";import"./chunk-cmp64q4j.js";import"./chunk-j152pk57.js";import"./chunk-c4dfktv2.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-g755p68b.js";import"./chunk-tcmzq86w.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{isShellKind,shippedCompletionsPath}from"./chunk-mwbs7818.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";import{t}from"./chunk-yv86xb1s.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{appendFileSync,existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{basename,join}from"path";var PENDING_COMPLETIONS_KEY="welcomePendingCompletions";function detectShell(env=process.env){let shell=basename(env.SHELL??"");return shell==="zsh"||shell==="bash"||shell==="fish"?shell:null}function completionHook(shell,cli,shipped){if(shipped===null)return legacyCompletionHook(shell,cli);return shell==="fish"?`test -f "${shipped}"; and source "${shipped}"`:`[ -f "${shipped}" ] && source "${shipped}"`}function legacyCompletionHook(shell,cli){return shell==="fish"?`${cli} completions fish | source`:`command -v ${cli} >/dev/null && source <(${cli} completions ${shell})`}function shippedScriptFor(shell,cli){let path=shippedCompletionsPath(shell,cli);return existsSync(path)?path:null}function installCompletions(shell,home=homedir(),cli=ROVE_PRODUCT_NAME,shipped=shippedScriptFor(shell,cli)){let hook=completionHook(shell,cli,shipped);if(shell==="fish"){let dir=join(home,".config","fish","completions"),path=join(dir,`${cli}.fish`);return mkdirSync(dir,{recursive:!0}),writeFileSync(path,`${hook}
2
+ import{isShellKind,shippedCompletionsPath}from"./chunk-mwbs7818.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";import{t}from"./chunk-8xdhw922.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{appendFileSync,existsSync,mkdirSync,readFileSync,writeFileSync}from"fs";import{homedir}from"os";import{basename,join}from"path";var PENDING_COMPLETIONS_KEY="welcomePendingCompletions";function detectShell(env=process.env){let shell=basename(env.SHELL??"");return shell==="zsh"||shell==="bash"||shell==="fish"?shell:null}function completionHook(shell,cli,shipped){if(shipped===null)return legacyCompletionHook(shell,cli);return shell==="fish"?`test -f "${shipped}"; and source "${shipped}"`:`[ -f "${shipped}" ] && source "${shipped}"`}function legacyCompletionHook(shell,cli){return shell==="fish"?`${cli} completions fish | source`:`command -v ${cli} >/dev/null && source <(${cli} completions ${shell})`}function shippedScriptFor(shell,cli){let path=shippedCompletionsPath(shell,cli);return existsSync(path)?path:null}function installCompletions(shell,home=homedir(),cli=ROVE_PRODUCT_NAME,shipped=shippedScriptFor(shell,cli)){let hook=completionHook(shell,cli,shipped);if(shell==="fish"){let dir=join(home,".config","fish","completions"),path=join(dir,`${cli}.fish`);return mkdirSync(dir,{recursive:!0}),writeFileSync(path,`${hook}
3
3
  `),{path,installed:!0}}let rc=join(home,shell==="zsh"?".zshrc":".bashrc"),existing=existsSync(rc)?readFileSync(rc,"utf8"):"";if(existing.includes(hook))return{path:rc,installed:!1};let legacy=legacyCompletionHook(shell,cli);if(existing.includes(legacy))return writeFileSync(rc,existing.replace(legacy,hook)),{path:rc,installed:!0};if(existing.includes(`${cli} completions`))return{path:rc,installed:!1};return appendFileSync(rc,`
4
4
  # ${cli} completions
5
5
  ${hook}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{parseDaemonStopReason}from"./chunk-6xr1prk6.js";import{isRowTokenTone}from"./chunk-mdx18vtz.js";import{sameWorktreeChanges}from"./chunk-55ajzrj6.js";import{CURRENT_VERSION}from"./chunk-fphcr46j.js";import{ensureDaemonReachable,isStaleInstallError,restartDaemon}from"./chunk-k7tdg6kb.js";import{DAEMON_PROTOCOL_VERSION,MIN_COMPATIBLE_PROTOCOL_VERSION,isAttentionInboxState,isDaemonVersionStale,isForeignDaemonHome,isProtocolCompatible,isRoutineInboxState}from"./chunk-84q9hv7m.js";import{parseModUiPayload}from"./chunk-96kvwzj8.js";import{createStateCell,mapReadableState}from"./chunk-cmp64q4j.js";import{logClient,logClientError}from"./chunk-y8hjgmn0.js";import{toTaskId}from"./chunk-xy8be792.js";import{homeDir}from"./chunk-8143k3t6.js";function parseWorktreeChangesPayload(payload){let changes=payload?.changes;if(!changes||typeof changes!=="object"||Array.isArray(changes))return null;let map=new Map;for(let[path,value]of Object.entries(changes)){let counts=value;if(typeof counts?.added!=="number"||typeof counts.deleted!=="number")return null;map.set(path,{added:counts.added,deleted:counts.deleted,...typeof counts.behind==="number"?{behind:counts.behind}:{},...typeof counts.ahead==="number"?{ahead:counts.ahead}:{}})}let unreadable=payload?.unreadable;if(Array.isArray(unreadable)){for(let path of unreadable)if(typeof path==="string"&&path.length>0)map.set(path,null)}return map}function sameWorktreeChangesMap(a,b){if(a.size!==b.size)return!1;for(let[path,counts]of a){if(!b.has(path))return!1;if(!sameWorktreeChanges(counts,b.get(path)??null))return!1}return!0}function parseToken(raw){if(!raw||typeof raw!=="object")return null;let t=raw;if(typeof t.source!=="string"||typeof t.key!=="string")return null;if(typeof t.text!=="string"||t.text.length===0)return null;if(typeof t.expiresAt!=="number"||!Number.isFinite(t.expiresAt))return null;return{source:t.source,key:t.key,text:t.text,...isRowTokenTone(t.tone)?{tone:t.tone}:{},expiresAt:t.expiresAt}}function parseRowTokensPayload(payload){let tokens=payload?.tokens;if(!tokens||typeof tokens!=="object"||Array.isArray(tokens))return null;let out=new Map;for(let[taskId,list]of Object.entries(tokens)){if(!Array.isArray(list))continue;let parsed=list.map(parseToken).filter((token)=>token!==null);if(parsed.length>0)out.set(taskId,parsed)}return out}function sameRowTokenMap(a,b){if(a.size!==b.size)return!1;for(let[taskId,left]of a){let right=b.get(taskId);if(!right||right.length!==left.length)return!1;for(let[i,token]of left.entries()){let other=right[i];if(!other||other.source!==token.source||other.key!==token.key||other.text!==token.text||other.tone!==token.tone||other.expiresAt!==token.expiresAt)return!1}}return!0}function liveRowTokens(map,taskId,now){let tokens=map?.get(taskId);if(!tokens||tokens.length===0)return[];return tokens.filter((token)=>token.expiresAt>now)}function shouldLogReconnectAttempt(attempt){if(attempt>100)return!1;return attempt===1||attempt%10===0}function describePayload(value){if(value===void 0)return"undefined";if(value===null)return"null";let type=Array.isArray(value)?"array":typeof value,text;try{text=typeof value==="string"?value:JSON.stringify(value)}catch{text=String(value)}if(text.length>120)text=`${text.slice(0,120)}\u2026`;return`${type}:${text}`}function decodeUiPrefsPayload(payload){let p=payload;if(!p||typeof p!=="object"||!("theme"in p))return null;if(p.theme!==null&&typeof p.theme!=="string")return null;return{theme:typeof p.theme==="string"&&p.theme.length>0?p.theme:null,..."themeMode"in p?{themeMode:typeof p.themeMode==="string"?p.themeMode:null}:{},transparentBackground:p.transparentBackground!==!1,focusAccent:typeof p.focusAccent==="string"?p.focusAccent:null,locale:typeof p.locale==="string"?p.locale:"",sortMode:p.sortMode==="recent"||p.sortMode==="attention"||p.sortMode==="name"?p.sortMode:"default",keysCollapsed:p.keysCollapsed===!0,projectFilter:typeof p.projectFilter==="string"&&p.projectFilter.length>0?p.projectFilter:null}}function contextPart(p){let items=Array.isArray(p.items)?p.items.filter((i)=>typeof i?.name==="string"&&typeof i?.tokens==="number"):[];return{key:p.key,tokens:p.tokens,...typeof p.label==="string"?{label:p.label}:{},...items.length>0?{items:items.map(({name,tokens})=>({name,tokens}))}:{},...typeof p.itemCount==="number"?{itemCount:p.itemCount}:{},...p.deferred===!0?{deferred:!0}:{}}}var TOKEN_TOTAL_FIELDS=["inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens"];function parseContextUsagePayload(payload){let context=payload?.context;if(!context||typeof context!=="object"||Array.isArray(context))return null;let map=new Map;for(let[key,value]of Object.entries(context)){let v=value;if(typeof v?.contextTokens!=="number")return null;if(v.contextWindowTokens!==void 0&&typeof v.contextWindowTokens!=="number")return null;let parts=v.parts;if(parts!==void 0&&(!Array.isArray(parts)||!parts.every((p)=>typeof p?.key==="string"&&typeof p?.tokens==="number")))return null;let totals={};for(let field of TOKEN_TOTAL_FIELDS){let raw=v[field];if(raw===void 0)continue;if(typeof raw!=="number")return null;totals[field]=raw}map.set(key,{contextTokens:v.contextTokens,...typeof v.contextWindowTokens==="number"?{contextWindowTokens:v.contextWindowTokens}:{},...v.approximate===!0?{approximate:!0}:{},...totals,...Array.isArray(parts)?{parts:parts.map(contextPart)}:{}})}return map}function sameContextUsageMap(a,b){if(a.size!==b.size)return!1;for(let[key,value]of a){let other=b.get(key);if(!other||other.contextTokens!==value.contextTokens||other.contextWindowTokens!==value.contextWindowTokens||other.approximate!==value.approximate||TOKEN_TOTAL_FIELDS.some((field)=>other[field]!==value[field])||JSON.stringify(other.parts)!==JSON.stringify(value.parts))return!1}return!0}function parseUsageSnapshotPayload(payload){let usage=payload?.usage;if(!usage||typeof usage!=="object"||Array.isArray(usage))return null;let map=new Map;for(let[vendor,value]of Object.entries(usage)){let snapshot=value;if(typeof snapshot?.capturedAt!=="number"||!Array.isArray(snapshot.windows))return null;let windows=[];for(let raw of snapshot.windows){let w=raw;if(typeof w?.kind!=="string"||typeof w.label!=="string"||typeof w.percent!=="number")return null;if(w.resetsAt!==null&&typeof w.resetsAt!=="number")return null;windows.push({kind:w.kind,label:w.label,percent:w.percent,resetsAt:w.resetsAt})}map.set(vendor,{windows,capturedAt:snapshot.capturedAt})}return map}function sameUsageSnapshotMap(a,b){if(a.size!==b.size)return!1;for(let[vendor,usage]of a){let other=b.get(vendor);if(!other||other.capturedAt!==usage.capturedAt||other.windows.length!==usage.windows.length)return!1;for(let i=0;i<usage.windows.length;i++){let x=usage.windows[i],y=other.windows[i];if(!x||!y||x.kind!==y.kind||x.label!==y.label||x.percent!==y.percent||x.resetsAt!==y.resetsAt)return!1}}return!0}function parseTranscriptActivityPayload(payload){let activity=payload?.activity;if(!activity||typeof activity!=="object"||Array.isArray(activity))return null;let map=new Map;for(let[path,value]of Object.entries(activity)){let v=value;if(typeof v?.mtimeMs!=="number"||typeof v.completionAt!=="number")return null;if(v.completionId!==null&&typeof v.completionId!=="string")return null;map.set(path,{mtimeMs:v.mtimeMs,completionId:v.completionId,completionAt:v.completionAt})}return map}function sameTranscriptActivityMap(a,b){if(a.size!==b.size)return!1;for(let[path,v]of a){let other=b.get(path);if(!other||other.mtimeMs!==v.mtimeMs||other.completionId!==v.completionId||other.completionAt!==v.completionAt)return!1}return!0}function deserializeTask(s){return{id:toTaskId(s.id),title:s.title,repo:s.repo,branch:s.branch,worktreePath:s.worktreePath,kind:s.kind==="main"?"dir":s.kind,...s.scratch?{scratch:!0}:{},...s.noProject?{noProject:!0}:{},...s.routine?{routine:s.routine}:{},status:s.status,pinned:s.pinned,...s.kept?{kept:!0}:{},...s.notes?{notes:s.notes}:{},...s.todos?{todos:s.todos}:{},...s.archived?{archived:!0}:{},vendor:s.vendor,command:s.command,prStatus:s.prStatus,modelEffort:s.modelEffort,model:s.model,tier:s.tier,groupId:s.groupId,observedLanguage:s.observedLanguage,deletion:s.deletion,quotaResume:s.quotaResume,scheduledStart:s.scheduledStart,...s.autoFixCi?{autoFixCi:s.autoFixCi}:{},linkedWorkItem:s.linkedWorkItem,dispatcher:s.dispatcher,...s.parentTaskId?{parentTaskId:toTaskId(s.parentTaskId)}:{},...s.sharesWorkspaceOf?{sharesWorkspaceOf:toTaskId(s.sharesWorkspaceOf)}:{},...s.cwdSubpath?{cwdSubpath:s.cwdSubpath}:{},...s.ptyAlias?{ptyAlias:s.ptyAlias}:{},...s.extraRepos?.length?{extraRepos:s.extraRepos}:{},...s.workspace?{workspace:s.workspace}:{},...s.sessionPrs?.length?{sessionPrs:s.sessionPrs}:{},requireReport:s.requireReport,...s.worktreeOnly?{worktreeOnly:!0}:{},prompt:s.prompt,baseRef:s.baseRef,worktreeName:s.worktreeName,...s.gitRepo?{gitRepo:s.gitRepo}:{},report:s.report,...s.repoId?{repoId:s.repoId}:{},createdAt:s.createdAt,updatedAt:s.updatedAt}}async function runReconnectLoop(deps){let delayMs=deps.spawnDaemon?Math.floor(Math.random()*400):500,attempt=0;while(!deps.isDisposed()){if(delayMs>0)await new Promise((r)=>setTimeout(r,delayMs));if(deps.isDisposed())break;attempt++;try{if(deps.spawnDaemon)await deps.ensureReachable();await deps.init(),logClient("orch",`reconnected and re-subscribed after ${attempt} attempt(s) \u2014 task list re-synced`);return}catch(err){if(isStaleInstallError(err)){logClientError("orch-reconnect-fatal",err),deps.onFatal?.(err);return}if(deps.shouldLogAttempt(attempt))logClientError("orch-reconnect",err);delayMs=delayMs===0?500:Math.min(delayMs*2,3000)}}}function singleFlightReconnect(deps){let current=null;return(spawnDaemon)=>{if(current)return current;let task=runReconnectLoop({...deps,spawnDaemon});current=task;let clear=()=>{if(current===task)current=null};return task.then(clear,clear),task}}async function performInit(client,opts,signals){let hello=await client.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION,minProtocolVersion:MIN_COMPATIBLE_PROTOCOL_VERSION}),daemonVersion=typeof hello.protocolVersion==="number"?hello.protocolVersion:DAEMON_PROTOCOL_VERSION,daemonMin=typeof hello.minProtocolVersion==="number"?hello.minProtocolVersion:daemonVersion;if(!isProtocolCompatible({localVersion:DAEMON_PROTOCOL_VERSION,localMin:MIN_COMPATIBLE_PROTOCOL_VERSION,remoteVersion:daemonVersion,remoteMin:daemonMin}))throw Error(`Rove daemon is protocol v${daemonVersion} (min v${daemonMin}); this client is v${DAEMON_PROTOCOL_VERSION} (min v${MIN_COMPATIBLE_PROTOCOL_VERSION}). Restart the daemon (\`rove daemon restart\`) or upgrade Rove.`);let clientHome=homeDir();if(!opts.expectForeignHome&&isForeignDaemonHome(hello.homeDir,clientHome))throw Error(`Rove daemon on this socket serves ${hello.homeDir}, but this client uses ${clientHome}. A sandbox or dev daemon has taken the production socket \u2014 stop it (\`rove daemon stop\`), or unset ROVE_DAEMON_SOCKET_PATH / ROVE_DAEMON_SOCKET_PATH before starting it.`);if(signals.setDaemonVersionSig(typeof hello.roveVersion==="string"?hello.roveVersion:null),opts.onPeerIdentity?.({hostname:typeof hello.hostname==="string"?hello.hostname:"",homeDir:typeof hello.homeDir==="string"?hello.homeDir:"",daemonPid:typeof hello.daemonPid==="number"?hello.daemonPid:0,roveVersion:typeof hello.roveVersion==="string"?hello.roveVersion:""}),signals.setDaemonRestartingSig(!1),hello.tasks&&opts.subscribesTasks)signals.setTasks(hello.tasks.map(deserializeTask));if(await client.subscribe({role:opts.role,channels:opts.channels,cellPixelSize:opts.cellPixelSize}),hello.capabilities?.includes("worktree.changes")){if(signals.worktreeChangesAcc()===null)signals.setWorktreeChangesSig(new Map)}else signals.setWorktreeChangesSig(null);if(hello.capabilities?.includes("transcript.activity")){if(signals.transcriptActivityAcc()===null)signals.setTranscriptActivitySig(new Map)}else signals.setTranscriptActivitySig(null);signals.setConnectionState("online"),logClient("orch",`subscribed as ${opts.role} (${signals.tasksAcc().length} tasks)`)}function ordinalOf(tabId,fallback){let match=/^tab-(\d+)$/.exec(tabId);return match?Number(match[1]):fallback}function adoptTabs(state,tabIds){let known=new Set(state.tabs.map((tab)=>tab.id)),fresh=[];for(let id of tabIds){if(known.has(id))continue;known.add(id),fresh.push(id)}if(fresh.length===0)return state;let minted=state.nextOrdinal,adopted=fresh.map((id)=>({kind:"engine",id,title:null,ordinal:ordinalOf(id,minted++),spawned:!0}));adopted.sort((a,b)=>a.ordinal-b.ordinal);let tabs=[...state.tabs,...adopted],maxOrdinal=tabs.reduce((max,tab)=>Math.max(max,tab.ordinal),0);return{tabs,activeId:state.activeId,nextOrdinal:Math.max(state.nextOrdinal,maxOrdinal+1)}}function isAddedTab(raw){if(typeof raw!=="object"||raw===null)return!1;if(!("id"in raw)||typeof raw.id!=="string")return!1;if(!("ordinal"in raw)||typeof raw.ordinal!=="number")return!1;if(!("title"in raw)||raw.title!==null&&typeof raw.title!=="string")return!1;if(!("kind"in raw))return!1;if(raw.kind==="engine")return!0;return raw.kind==="command"&&"command"in raw&&Array.isArray(raw.command)}function absorbTab(state,tab){let nextOrdinal=Math.max(state.nextOrdinal,tab.ordinal+1),known=state.tabs.find((t)=>t.id===tab.id);if(known?.kind===tab.kind){if(Object.entries(tab).every(([key,value])=>JSON.stringify(Reflect.get(known,key))===JSON.stringify(value))&&nextOrdinal===state.nextOrdinal)return state}let merged=known?.kind===tab.kind?{...known,...tab,title:known.title}:tab,tabs=known?state.tabs.map((t)=>t===known?merged:t):[...state.tabs,merged];return{...state,tabs,nextOrdinal}}var MAP_CHANNELS={"usage.snapshot":{what:"usage payload",parse:parseUsageSnapshotPayload,same:sameUsageSnapshotMap,read:(signals)=>signals.usageSnapshotAcc(),write:(signals,next)=>signals.setUsageSnapshotSig(next)},"usage.context":{what:"context payload",parse:parseContextUsagePayload,same:sameContextUsageMap,read:(signals)=>signals.contextUsageAcc(),write:(signals,next)=>signals.setContextUsageSig(next)},"worktree.changes":{what:"changes payload",parse:parseWorktreeChangesPayload,same:sameWorktreeChangesMap,read:(signals)=>signals.worktreeChangesAcc(),write:(signals,next)=>signals.setWorktreeChangesSig(next)},"transcript.activity":{what:"activity payload",parse:parseTranscriptActivityPayload,same:sameTranscriptActivityMap,read:(signals)=>signals.transcriptActivityAcc(),write:(signals,next)=>signals.setTranscriptActivitySig(next)},"mod.ui":{what:"mod pane list",parse:parseModUiPayload,same:(a,b)=>JSON.stringify(a)===JSON.stringify(b),read:(signals)=>signals.modPanesAcc(),write:(signals,next)=>signals.setModPanesSig(next)},"task.tokens":{what:"token map",parse:parseRowTokensPayload,same:sameRowTokenMap,read:(signals)=>signals.rowTokensAcc(),write:(signals,next)=>signals.setRowTokensSig(next)}};function handleMapChannel(name,payload,signals){let channel=MAP_CHANNELS[name];if(!channel)return!1;let next=channel.parse(payload);if(!next)return logClientError("orch",`dropped ${name} event: malformed ${channel.what} (${describePayload(payload)})`),!0;let current=channel.read(signals);if(current&&channel.same(current,next))return!0;return channel.write(signals,next),!0}function writeGraphicsToStdout(data){if(!process.stdout.isTTY)return;process.stdout.write(data)}function pruneEngineState(tasks,signals){let live=new Set(tasks.map((t)=>t.id)),current=signals.engineStateAcc();if(current.size>0){let next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setEngineStateSig(next)}let tabs=signals.engineTabStateAcc();if(tabs.size>0){let nextTabs=null;for(let key of tabs.keys()){if(live.has(key))continue;if(!nextTabs)nextTabs=new Map(tabs);nextTabs.delete(key)}if(nextTabs)signals.setEngineTabStateSig(nextTabs)}let lifecycle=signals.engineLifecycleAcc();if(lifecycle.size>0){let nextLifecycle=null;for(let key of lifecycle.keys()){if(live.has(key))continue;if(!nextLifecycle)nextLifecycle=new Map(lifecycle);nextLifecycle.delete(key)}if(nextLifecycle)signals.setEngineLifecycleSig(nextLifecycle)}}function pruneTaskJobs(tasks,signals){let current=signals.taskJobsAcc();if(current.size===0)return;let live=new Set(tasks.map((t)=>t.id)),next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setTaskJobsSig(next)}function handleOrchestratorEvent(name,payload,signals){if(name==="task.snapshot"){let value=payload?.tasks;if(Array.isArray(value))signals.setTasks(value.map(deserializeTask)),pruneEngineState(value,signals),pruneTaskJobs(value,signals);else logClientError("orch",`dropped task.snapshot event: tasks is not an array (got ${describePayload(value)})`);return}if(name==="daemon.stopping"){let p=payload;if(typeof p?.roveVersion==="string")signals.setDaemonVersionSig(p.roveVersion);if(parseDaemonStopReason(p?.reason)==="restart")signals.setDaemonRestartingSig(!0);return}if(name==="active-task"){let id=payload?.taskId;signals.setActiveTaskSig(typeof id==="string"?id:null);return}if(name==="update"){let info=payload?.info;signals.setUpdateSig(info??null);return}if(name==="engine-state"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.state!=="string"){logClientError("orch",`dropped engine-state event: taskId/state must be strings (taskId=${describePayload(p?.taskId)}, state=${describePayload(p?.state)})`);return}let tabId=typeof p.tabId==="string"&&p.tabId?p.tabId:void 0,entry={state:p.state,detail:p.detail,...typeof p.sessionId==="string"&&p.sessionId?{sessionId:p.sessionId}:{},...typeof p.transcriptPath==="string"&&p.transcriptPath?{transcriptPath:p.transcriptPath}:{},...tabId?{tabId}:{},at:typeof p.at==="number"?p.at:0},prevTaskState=signals.engineStateAcc().get(p.taskId)?.state;if(!tabId){let next=new Map(signals.engineStateAcc());if(p.state==="idle")next.delete(p.taskId);else next.set(p.taskId,entry);signals.setEngineStateSig(next)}if((p.state==="idle"||p.state==="turn_complete"||p.state==="error"||p.state==="running"&&prevTaskState!=="running")&&signals.engineLifecycleAcc().has(p.taskId)){let lifecycle=new Map(signals.engineLifecycleAcc());lifecycle.delete(p.taskId),signals.setEngineLifecycleSig(lifecycle)}if(tabId){let nextTabs=new Map(signals.engineTabStateAcc()),tabs=new Map(nextTabs.get(p.taskId)??[]);tabs.set(tabId,entry),nextTabs.set(p.taskId,tabs),signals.setEngineTabStateSig(nextTabs)}return}if(name==="attention.inbox"){let items=payload?.items;if(!Array.isArray(items)){logClientError("orch",`dropped attention.inbox event: items is not an array (${describePayload(items)})`);return}let kept=items.filter((item)=>{if(!item||typeof item!=="object"||Array.isArray(item))return!1;let p=item;return(typeof p.taskId==="string"||p.taskId===null&&isRoutineInboxState(p.state))&&(p.tabId===null||typeof p.tabId==="string")&&isAttentionInboxState(p.state)&&(p.unread===void 0||typeof p.unread==="boolean")&&typeof p.at==="number"});if(kept.length!==items.length)logClientError("orch",`dropped ${items.length-kept.length} malformed attention.inbox item(s) of ${items.length} (${describePayload(items)})`);if(kept.length===0&&items.length>0)return;signals.setAttentionInboxSig(kept.map((item)=>({...item,unread:item.unread!==!1})));return}if(name==="gates"){let gates=payload?.gates;if(!Array.isArray(gates)){logClientError("orch",`dropped gates event: gates is not an array (${describePayload(gates)})`);return}let kept=gates.filter((g)=>{if(!g||typeof g!=="object"||Array.isArray(g))return!1;let p=g;return typeof p.id==="string"&&typeof p.taskId==="string"&&typeof p.question==="string"});if(kept.length===0&&gates.length>0)return;signals.setGatesSig(kept.map((g)=>({...g,options:Array.isArray(g.options)?g.options:[]})));return}if(name==="task.jobs"){let p=payload;if(typeof p?.taskId!=="string"||p.kind!=="ensureWorktree"){logClientError("orch",`dropped task.jobs event: expected string taskId + kind "ensureWorktree" (taskId=${describePayload(p?.taskId)}, kind=${describePayload(p?.kind)})`);return}let current=signals.taskJobsAcc();if(p.phase==="running"){let progress=typeof p.progress==="number"&&Number.isFinite(p.progress)?p.progress:current.get(p.taskId)?.progress,next=new Map(current);next.set(p.taskId,progress===void 0?{kind:p.kind}:{kind:p.kind,progress}),signals.setTaskJobsSig(next);return}if((p.phase==="done"||p.phase==="error")&&current.has(p.taskId)){let next=new Map(current);next.delete(p.taskId),signals.setTaskJobsSig(next)}return}if(handleMapChannel(name,payload,signals))return;if(name==="tab.open"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||typeof p.title!=="string"||!Array.isArray(p.argv)){logClientError("orch",`dropped tab.open event: malformed payload (${describePayload(payload)})`);return}signals.setTabOpenSig(p);return}if(name==="tab.close"){let p=payload;if(!(p&&"kind"in p&&p.kind==="terminal-tab"?typeof p.taskId==="string"&&typeof p.tabId==="string"&&typeof p.requestId==="string"&&typeof p.at==="number":typeof p?.taskId==="string"&&typeof p.at==="number"&&("title"in p)&&typeof p.title==="string")){logClientError("orch",`dropped tab.close event: malformed payload (${describePayload(payload)})`);return}signals.setTabCloseSig(p);return}if(name==="tab.rename"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.tabId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped tab.rename event: malformed payload (${describePayload(payload)})`);return}signals.setTabRenameSig(p);return}if(name==="tabs.changed"){let p=payload,state=p?.state;if(typeof p?.taskId!=="string"||typeof p.rev!=="number"||state!==null&&(typeof state!=="object"||!Array.isArray(state?.tabs))){logClientError("orch",`dropped tabs.changed event: malformed payload (${describePayload(payload)})`);return}signals.emitTabsChanged(p);return}if(name==="row.status"){let p=payload;if(typeof p?.rev!=="number"||typeof p.tasks!=="object"||p.tasks===null){logClientError("orch",`dropped row.status event: malformed payload (${describePayload(payload)})`);return}signals.emitRowStatus(p);return}if(name==="tab.add"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||!isAddedTab(p.tab)){logClientError("orch",`dropped tab.add event: malformed payload (${describePayload(payload)})`);return}signals.setTabAddSig({taskId:p.taskId,tab:p.tab,at:p.at});return}if(name==="ui.prompt"){let p=payload;if(typeof p?.promptId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped ui.prompt event: malformed payload (${describePayload(payload)})`);return}signals.setUiPromptSig(p);return}if(name==="engine.lifecycle"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.kind!=="string"){logClientError("orch",`dropped engine.lifecycle event: malformed payload (${describePayload(payload)})`);return}let prev=signals.engineLifecycleAcc(),cur=prev.get(p.taskId)??{subagents:0},entry=p.kind==="subagent-start"?{subagents:cur.subagents+1}:p.kind==="subagent-stop"?{subagents:Math.max(0,cur.subagents-1)}:cur;if(entry===cur&&!prev.has(p.taskId))return;let map=new Map(prev);if(entry.subagents===0)map.delete(p.taskId);else map.set(p.taskId,entry);signals.setEngineLifecycleSig(map);return}if(name==="graphics.write"){let p=payload;if(typeof p?.data!=="string"||typeof p.imageId!=="number"||typeof p.at!=="number"){logClientError("orch",`dropped graphics.write event: malformed payload (${describePayload(payload)})`);return}signals.writeGraphics(Buffer.from(p.data,"base64"));return}if(name==="notice.event"){let p=payload;if(typeof p?.title!=="string"||typeof p.at!=="number"||typeof p.kind!=="string"){logClientError("orch",`dropped notice.event: malformed payload (${describePayload(payload)})`);return}signals.setNoticeSig(p);return}if(name==="ui-prefs"){let decoded=decodeUiPrefsPayload(payload);if(!decoded){let theme=payload?.theme;logClientError("orch",`dropped ui-prefs event: theme must be a string (got ${describePayload(theme)})`);return}signals.setUiPrefsSig(decoded);return}if(name==="state"||name==="machines"){signals.setRawSig(name,payload);return}if(name==="keybindings"){let p=payload;if(typeof p?.rev!=="number"){logClientError("orch",`dropped keybindings event: rev must be a number (got ${describePayload(p?.rev)})`);return}signals.setKeybindingsRevSig(p.rev)}}function subscribeTasksOp(tasks,listener){try{listener(tasks())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw on subscribe:",err)}return tasks.subscribe(()=>{try{listener(tasks.get())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw:",err)}})}async function legacyAdoptedTasksOp(client){return(await client.request("worktree.legacyAdopted",{})).tasks.map(deserializeTask)}class RowStatusChannel{client;listeners=new Set;constructor(client){this.client=client}emit=(payload)=>{for(let listener of this.listeners)listener(payload)};onChanged=(listener)=>{return this.listeners.add(listener),()=>this.listeners.delete(listener)};list=()=>this.client.request("status.list");viewing=(taskId,tabId)=>this.client.request("ui.viewing",taskId===null?{taskId:null}:{taskId,...tabId?{tabId}:{}});answered=(taskId,tabId)=>this.client.request("activity.answered",{taskId,tabId})}class TabsChannel{client;listeners=new Set;constructor(client){this.client=client}emit=(event)=>{for(let listener of this.listeners)listener(event)};onChanged=(listener)=>{return this.listeners.add(listener),()=>this.listeners.delete(listener)};apply=(taskId,ops)=>this.client.request("tabs.apply",{taskId,ops});list=()=>this.client.request("tabs.list");reserve=(taskId,count)=>this.client.request("tabs.reserve",{taskId,count});release=(taskId,from,to)=>this.client.request("tabs.release",{taskId,from,to})}async function createTaskOp(client,input){let{modelEffort,...rest}=input,res=await client.request("task.create",{...rest,effort:modelEffort});return deserializeTask(res.task)}async function ensureProjectOp(client,repo){return(await client.request("project.ensure",{repo})).repo}async function openDirectoryTaskOp(client,input){let res=await client.request("task.openDir",input);return deserializeTask(res.task)}async function adoptScratchRepoOp(client,id,repo){await client.request("task.adoptScratchRepo",{taskId:String(id),repo})}async function moveTaskToProjectOp(client,id,repo){let res=await client.request("task.moveToProject",{taskId:String(id),repo});return{repo:res.repo,moved:res.moved}}async function ensureWorktreeOp(client,id){return(await client.request("task.ensureWorktree",{taskId:String(id)})).worktreePath}async function forgetProjectOp(client,repo){await client.request("project.forget",{repo})}function reportEngineInterruptOp(client,taskId,tabId){client.request("engine.reportEvent",{kind:"turn-interrupted",taskId,tabId}).catch(()=>{})}async function setTitleOp(client,id,title){await client.request("task.rename",{taskId:String(id),title})}async function setBranchOp(client,id,branch){await client.request("task.setBranch",{taskId:String(id),branch})}async function setVendorOp(client,id,vendor,effort,model){await client.request("task.setVendor",{taskId:String(id),vendor,...effort!==void 0?{effort}:{},...model!==void 0?{model}:{}})}async function setCommandOp(client,id,command,vendor){await client.request("task.setCommand",{taskId:String(id),command,...vendor?{vendor}:{}})}async function setPinnedOp(client,id,pinned){await client.request("task.pin",{taskId:String(id),pinned})}async function archiveTaskOp(client,id,archived,flags={}){await client.request("task.archive",{taskId:String(id),archived,...flags})}async function moveTaskOp(client,id,delta){await client.request("task.move",{taskId:String(id),direction:delta<0?"up":"down"})}async function moveProjectOp(c,repo,target,side){await c.request("project.move",{repo,target,side})}async function setPromptOp(client,id,prompt){await client.request("task.setPrompt",{taskId:String(id),prompt})}async function setStatusOp(client,id,status){await client.request("task.status",{taskId:String(id),status})}async function deleteTaskOp(client,id,opts){return client.request("task.delete",{taskId:String(id),force:opts?.force,deleteBranch:opts?.deleteBranch,cascade:opts?.cascade})}async function spawnChildTaskOp(client,input){let{dispatcher,...rest}=input,res=await client.request("task.spawn",{...rest,...dispatcher?{dispatcherTaskId:dispatcher.taskId,dispatcherTabId:dispatcher.tabId}:{}});return{task:deserializeTask(res.task),parentDirty:res.parentDirty,sharedLinks:res.sharedLinks}}async function dismissAttentionOp(client,taskId,tabId,at,deliveryId){return(await client.request("attention.dismiss",{taskId:String(taskId),...tabId!==null?{tabId}:{},at,...deliveryId!==void 0?{deliveryId}:{}})).deleted}async function dismissRoutineAttentionOp(client,automationId){return(await client.request("attention.dismissRoutine",{automationId})).deleted}async function answerGateOp(client,gateId,answer){return{delivered:(await client.request("gate.answer",{gateId,...answer,by:"tui"})).delivered}}async function withdrawGateOp(client,gateId){await client.request("gate.withdraw",{gateId})}async function markAttentionReadOp(client,taskId,tabId,at){return(await client.request("attention.read",{taskId:String(taskId),...tabId!==null?{tabId}:{},at})).updated}async function landPreflightOp(client,id){return(await client.request("task.landPreflight",{taskId:String(id)})).result}async function landTaskOp(client,id,opts){return(await client.request("task.land",{taskId:String(id),strategy:opts?.strategy,deleteBranch:opts?.deleteBranch,removeWorktree:opts?.removeWorktree,callerCwd:opts?.callerCwd})).result}async function discoverAdoptableWorktreesOp(client,repo){return(await client.request("worktree.discoverAdoptable",{repo})).worktrees}async function adoptWorktreeOp(client,input){let res=await client.request("worktree.adopt",input);return deserializeTask(res.task)}async function listWorktreesOp(client,opts){return(await client.request("worktree.list",{network:opts?.network!==!1})).projects}async function removeWorktreeOp(client,path,force){return(await client.request("worktree.remove",{path,force})).residue??null}async function syncBaseOp(client,taskId){let res=await client.request("task.syncBase",{taskId}),failed=res.result.repos?.find((r)=>!r.ok);if(failed)throw Error(failed.error??"sync failed");return res.result}async function failingChecksOp(client,taskId){let res=await client.request("pr.failingChecks",{taskId});return{checks:res.checks??[],totalFailing:res.totalFailing??0,...res.unavailable?{unavailable:res.unavailable}:{}}}async function rerunFailedChecksOp(client,taskId){let res=await client.request("pr.rerunFailedChecks",{taskId});return{rerunRuns:res.rerunRuns??0,external:res.external??0,...res.refused?{refused:res.refused}:{},...res.unavailable?{unavailable:res.unavailable}:{}}}async function listIssuesOp(client,repoRoot){return client.request("issue.list",{repoRoot})}async function listIssueReposOp(client){return(await client.request("issue.repos",{})).repos??[]}async function listFieldNotesOp(client,repo){return(await client.request("note.list",{repo})).notes??[]}async function deleteFieldNoteOp(client,repo,id){return(await client.request("note.delete",{repo,id})).deleted===!0}async function mutateIssueOp(client,repoRoot,op){return client.request("issue.mutate",{repoRoot,op})}async function listAutomationsOp(client){return client.request("automation.list",{})}async function createAutomationOp(client,input){return client.request("automation.create",input)}async function automationRunsOp(client,id){return client.request("automation.runs",{id})}async function setAutomationEnabledOp(client,id,enabled){return client.request("automation.update",{id,enabled})}async function runAutomationNowOp(client,id){return client.request("automation.runNow",{id})}async function deleteAutomationOp(client,id){return client.request("automation.delete",{id})}async function listWorkItemsOp(client,args){return client.request("workitem.list",args)}async function startWorkItemOp(client,args){return client.request("workitem.start",args)}async function setActiveTaskOp(client,id){await client.request("task.setActive",{taskId:id===null?null:String(id)})}function replyTabCloseOp(client,requestId,closed){client.request("terminalTab.closeReply",{requestId,closed}).catch(()=>{})}function replyPromptOp(client,promptId,value){client.request("ui.promptReply",{promptId,...value!==void 0?{value}:{}}).catch(()=>{})}function reportUiEventOp(client,kind,taskId,detail){client.request("ui.reportEvent",{kind,...taskId?{taskId}:{},...detail?{detail}:{}}).catch(()=>{})}function recentTaskEventsOp(client,id){return client.request("task.recentEvents",{taskId:String(id)})}class RemoteOrchestrator{client;tasksAcc=createStateCell([],"orchestrator.tasks");activeTaskAcc=createStateCell(null,"orchestrator.active-task");updateAcc=createStateCell(null);daemonVersionAcc=createStateCell(null);daemonRestartingAcc=createStateCell(!1);daemonStaleAcc=mapReadableState(this.daemonVersionAcc,(version)=>isDaemonVersionStale(version??void 0,CURRENT_VERSION));engineStateAcc=createStateCell(new Map);engineTabStateAcc=createStateCell(new Map);attentionInboxAcc=createStateCell([]);gatesAcc=createStateCell([]);taskJobsAcc=createStateCell(new Map);rowTokensAcc=createStateCell(new Map);modPanesAcc=createStateCell([]);worktreeChangesAcc=createStateCell(null);usageSnapshotAcc=createStateCell(null);contextUsageAcc=createStateCell(null);transcriptActivityAcc=createStateCell(null);noticeAcc=createStateCell(null);tabOpenAcc=createStateCell(null);tabCloseAcc=createStateCell(null);tabRenameAcc=createStateCell(null);tabAddAcc=createStateCell(null);tabs;rowStatus;uiPromptAcc=createStateCell(null);engineLifecycleAcc=createStateCell(new Map);uiPrefsAcc=createStateCell(null);rawAcc={state:createStateCell(null),machines:createStateCell(null)};keybindingsRevAcc=createStateCell(null);connectionStateAcc=createStateCell("online","orchestrator.connection");staleInstallAcc=createStateCell(null);ensureReachable;role;cellPixelSize;channels;subscribesTasks;expectForeignHome;onPeerIdentity;reconnectLoop;signals;constructor(client,options={}){this.client=client;this.ensureReachable=options.ensureReachable??ensureDaemonReachable,this.role=options.role??"pane",this.cellPixelSize=options.cellPixelSize??null,this.channels=options.channels,this.subscribesTasks=!options.channels||options.channels.includes("task.snapshot"),this.expectForeignHome=options.expectForeignHome===!0,this.onPeerIdentity=options.onPeerIdentity,this.reconnectLoop=singleFlightReconnect({isDisposed:()=>client.isDisposed,ensureReachable:this.ensureReachable,init:()=>this.init(),shouldLogAttempt:shouldLogReconnectAttempt,onFatal:(err)=>this.staleInstallAcc.set(err instanceof Error?err.message:String(err))}),this.tabs=new TabsChannel(client),this.rowStatus=new RowStatusChannel(client),this.signals={writeGraphics:options.graphicsOut??(this.role==="gui"?writeGraphicsToStdout:()=>{}),tasksAcc:this.tasksAcc,setTasks:this.tasksAcc.set,setActiveTaskSig:this.activeTaskAcc.set,setUpdateSig:this.updateAcc.set,setDaemonVersionSig:this.daemonVersionAcc.set,setDaemonRestartingSig:this.daemonRestartingAcc.set,engineStateAcc:this.engineStateAcc,setEngineStateSig:this.engineStateAcc.set,engineTabStateAcc:this.engineTabStateAcc,setEngineTabStateSig:this.engineTabStateAcc.set,setAttentionInboxSig:this.attentionInboxAcc.set,setGatesSig:this.gatesAcc.set,taskJobsAcc:this.taskJobsAcc,setTaskJobsSig:this.taskJobsAcc.set,rowTokensAcc:this.rowTokensAcc,setRowTokensSig:this.rowTokensAcc.set,modPanesAcc:this.modPanesAcc,setModPanesSig:this.modPanesAcc.set,worktreeChangesAcc:this.worktreeChangesAcc,setWorktreeChangesSig:this.worktreeChangesAcc.set,usageSnapshotAcc:this.usageSnapshotAcc,setUsageSnapshotSig:this.usageSnapshotAcc.set,contextUsageAcc:this.contextUsageAcc,setContextUsageSig:this.contextUsageAcc.set,transcriptActivityAcc:this.transcriptActivityAcc,setTranscriptActivitySig:this.transcriptActivityAcc.set,setNoticeSig:this.noticeAcc.set,setTabOpenSig:this.tabOpenAcc.set,setTabCloseSig:this.tabCloseAcc.set,setTabRenameSig:this.tabRenameAcc.set,setTabAddSig:this.tabAddAcc.set,emitTabsChanged:this.tabs.emit,emitRowStatus:this.rowStatus.emit,setUiPromptSig:this.uiPromptAcc.set,engineLifecycleAcc:this.engineLifecycleAcc,setEngineLifecycleSig:this.engineLifecycleAcc.set,setUiPrefsSig:this.uiPrefsAcc.set,setRawSig:(name,payload)=>this.rawAcc[name].set(payload),setKeybindingsRevSig:this.keybindingsRevAcc.set,setConnectionState:this.connectionStateAcc.set},this.client.on("*",(frame)=>handleOrchestratorEvent(frame.name,frame.payload,this.signals)),this.client.onLifecycle("close",()=>{this.connectionStateAcc.set("disconnected");let spawnDaemon=this.role==="gui";logClient("orch",spawnDaemon?"daemon socket closed \u2014 starting silent spawning reconnect loop":"daemon socket closed \u2014 starting non-spawning reconnect loop"),this.reconnectLoop(spawnDaemon)})}writeGraphics(data){this.signals.writeGraphics(data)}async init(){await performInit(this.client,{role:this.role,cellPixelSize:this.cellPixelSize,channels:this.channels,subscribesTasks:this.subscribesTasks,expectForeignHome:this.expectForeignHome,onPeerIdentity:this.onPeerIdentity},this.signals)}connectionStateSignal(){return this.connectionStateAcc}staleInstallSignal(){return this.staleInstallAcc}async manualReconnect(){this.client.forceDisconnect(),await this.reconnectLoop(!0)}dispose(){this.client.close()}tasksSignal=()=>this.tasksAcc;activeTaskSignal=()=>this.activeTaskAcc;updateSignal=()=>this.updateAcc;daemonVersionSignal=()=>this.daemonVersionAcc;daemonStaleSignal=()=>this.daemonStaleAcc;daemonRestartingSignal=()=>this.daemonRestartingAcc;async restartDaemon(){await restartDaemon().catch(()=>{})}engineStateSignal=()=>this.engineStateAcc;engineTabStatesSignal=()=>this.engineTabStateAcc;attentionInboxSignal=()=>this.attentionInboxAcc;gatesSignal=()=>this.gatesAcc;taskJobsSignal=()=>this.taskJobsAcc;rowTokensSignal=()=>this.rowTokensAcc;modPanesSignal=()=>this.modPanesAcc;pressMod=(plugin,pane,key)=>this.client.request("mod.press",{plugin,pane,key});submitMod=(plugin,pane,key,value)=>this.client.request("mod.submit",{plugin,pane,key,value});worktreeChangesSignal=()=>this.worktreeChangesAcc;usageSnapshotSignal=()=>this.usageSnapshotAcc;contextUsageSignal=()=>this.contextUsageAcc;transcriptActivitySignal=()=>this.transcriptActivityAcc;transcriptActivityStore=()=>this.transcriptActivityAcc;noticeStore=()=>this.noticeAcc;tabOpenStore=()=>this.tabOpenAcc;tabCloseStore=()=>this.tabCloseAcc;tabRenameStore=()=>this.tabRenameAcc;tabAddStore=()=>this.tabAddAcc;rpc={request:(name,payload)=>this.client.request(name,payload)};replyTerminalTabClose=(requestId,closed)=>replyTabCloseOp(this.client,requestId,closed);uiPromptStore=()=>this.uiPromptAcc;replyPrompt=(promptId,value)=>replyPromptOp(this.client,promptId,value);engineLifecycleSignal=()=>this.engineLifecycleAcc;recentTaskEvents(id){return recentTaskEventsOp(this.client,id)}reportUiEvent=(kind,taskId,detail)=>reportUiEventOp(this.client,kind,taskId,detail);reportScreenInput=async(taskId,tabId,blocked)=>{await this.client.request("engine.reportEvent",{source:"screen",taskId,tabId,blocked})};reportEngineInterrupt=(taskId,tabId)=>reportEngineInterruptOp(this.client,String(taskId),tabId);uiPrefsSignal=()=>this.uiPrefsAcc;uiPrefsStore=()=>this.uiPrefsAcc;rawChannelSignal=(name)=>this.rawAcc[name];keybindingsRevSignal=()=>this.keybindingsRevAcc;keybindingsRevStore=()=>this.keybindingsRevAcc;listTasks=()=>this.tasksAcc();getTask=(id)=>this.tasksAcc().find((task)=>task.id===id);subscribeTasks(listener){return subscribeTasksOp(this.tasksAcc,listener)}createTask=(input)=>createTaskOp(this.client,input);ensureProject=(repo)=>ensureProjectOp(this.client,repo);openDirectoryTask=(input)=>openDirectoryTaskOp(this.client,input);adoptScratchRepo=(id,repo)=>adoptScratchRepoOp(this.client,id,repo);moveTaskToProject=(id,repo)=>moveTaskToProjectOp(this.client,id,repo);ensureWorktree=(id)=>ensureWorktreeOp(this.client,id);forgetProject=(repo)=>forgetProjectOp(this.client,repo);setTitle=(id,title)=>setTitleOp(this.client,id,title);setBranch=(id,branch)=>setBranchOp(this.client,id,branch);setVendor=(id,vendor,effort,model)=>setVendorOp(this.client,id,vendor,effort,model);setCommand=(id,command,vendor)=>setCommandOp(this.client,id,command,vendor);setPinned=(id,pinned)=>setPinnedOp(this.client,id,pinned);archiveTask=(id,archived,force,promote)=>archiveTaskOp(this.client,id,archived,{force,promote});moveTask=(id,delta)=>moveTaskOp(this.client,id,delta);moveProject=(from,to,at)=>moveProjectOp(this.client,from,to,at);setStatus=(id,status)=>setStatusOp(this.client,id,status);setPrompt=(id,prompt)=>setPromptOp(this.client,id,prompt);deleteTask=(id,opts)=>deleteTaskOp(this.client,id,opts);spawnChildTask=(input)=>spawnChildTaskOp(this.client,input);dismissAttention=(taskId,tabId,at,deliveryId)=>dismissAttentionOp(this.client,taskId,tabId,at,deliveryId);dismissRoutineAttention=(automationId)=>dismissRoutineAttentionOp(this.client,automationId);markAttentionRead=(taskId,tabId,at)=>markAttentionReadOp(this.client,taskId,tabId,at);answerGate=(gateId,answer)=>answerGateOp(this.client,gateId,answer);withdrawGate=(gateId)=>withdrawGateOp(this.client,gateId);landPreflight(id){return landPreflightOp(this.client,id)}landTask(id,opts){return landTaskOp(this.client,id,opts)}discoverAdoptableWorktrees=(repo)=>discoverAdoptableWorktreesOp(this.client,repo);legacyAdoptedTasks=()=>legacyAdoptedTasksOp(this.client);adoptWorktree(input){return adoptWorktreeOp(this.client,input)}listWorktrees(opts){return listWorktreesOp(this.client,opts)}listIssues(repoRoot){return listIssuesOp(this.client,repoRoot)}listIssueRepos(){return listIssueReposOp(this.client)}mutateIssue(repoRoot,op){return mutateIssueOp(this.client,repoRoot,op)}listAutomations=()=>listAutomationsOp(this.client);createAutomation=(i)=>createAutomationOp(this.client,i);automationRuns=(id)=>automationRunsOp(this.client,id);setAutomationEnabled=(id,on)=>setAutomationEnabledOp(this.client,id,on);runAutomationNow=(id)=>runAutomationNowOp(this.client,id);deleteAutomation=(id)=>deleteAutomationOp(this.client,id);listWorkItems=(a)=>listWorkItemsOp(this.client,a);listFieldNotes=(repo)=>listFieldNotesOp(this.client,repo);deleteFieldNote=(repo,id)=>deleteFieldNoteOp(this.client,repo,id);failingChecks=(taskId)=>failingChecksOp(this.client,taskId);rerunFailedChecks=(taskId)=>rerunFailedChecksOp(this.client,taskId);syncBase=(taskId)=>syncBaseOp(this.client,taskId);startWorkItem=(a)=>startWorkItemOp(this.client,a);removeWorktree(path,force){return removeWorktreeOp(this.client,path,force)}setActiveTask(id){return setActiveTaskOp(this.client,id)}}
2
+ import{parseDaemonStopReason}from"./chunk-6xr1prk6.js";import{isRowTokenTone}from"./chunk-mdx18vtz.js";import{sameWorktreeChanges}from"./chunk-55ajzrj6.js";import{CURRENT_VERSION}from"./chunk-0r64dqy3.js";import{ensureDaemonReachable,isStaleInstallError,restartDaemon}from"./chunk-k7tdg6kb.js";import{DAEMON_PROTOCOL_VERSION,MIN_COMPATIBLE_PROTOCOL_VERSION,isAttentionInboxState,isDaemonVersionStale,isForeignDaemonHome,isProtocolCompatible,isRoutineInboxState}from"./chunk-84q9hv7m.js";import{parseModUiPayload}from"./chunk-96kvwzj8.js";import{createStateCell,mapReadableState}from"./chunk-cmp64q4j.js";import{logClient,logClientError}from"./chunk-y8hjgmn0.js";import{toTaskId}from"./chunk-xy8be792.js";import{homeDir}from"./chunk-8143k3t6.js";function parseWorktreeChangesPayload(payload){let changes=payload?.changes;if(!changes||typeof changes!=="object"||Array.isArray(changes))return null;let map=new Map;for(let[path,value]of Object.entries(changes)){let counts=value;if(typeof counts?.added!=="number"||typeof counts.deleted!=="number")return null;map.set(path,{added:counts.added,deleted:counts.deleted,...typeof counts.behind==="number"?{behind:counts.behind}:{},...typeof counts.ahead==="number"?{ahead:counts.ahead}:{}})}let unreadable=payload?.unreadable;if(Array.isArray(unreadable)){for(let path of unreadable)if(typeof path==="string"&&path.length>0)map.set(path,null)}return map}function sameWorktreeChangesMap(a,b){if(a.size!==b.size)return!1;for(let[path,counts]of a){if(!b.has(path))return!1;if(!sameWorktreeChanges(counts,b.get(path)??null))return!1}return!0}function parseToken(raw){if(!raw||typeof raw!=="object")return null;let t=raw;if(typeof t.source!=="string"||typeof t.key!=="string")return null;if(typeof t.text!=="string"||t.text.length===0)return null;if(typeof t.expiresAt!=="number"||!Number.isFinite(t.expiresAt))return null;return{source:t.source,key:t.key,text:t.text,...isRowTokenTone(t.tone)?{tone:t.tone}:{},expiresAt:t.expiresAt}}function parseRowTokensPayload(payload){let tokens=payload?.tokens;if(!tokens||typeof tokens!=="object"||Array.isArray(tokens))return null;let out=new Map;for(let[taskId,list]of Object.entries(tokens)){if(!Array.isArray(list))continue;let parsed=list.map(parseToken).filter((token)=>token!==null);if(parsed.length>0)out.set(taskId,parsed)}return out}function sameRowTokenMap(a,b){if(a.size!==b.size)return!1;for(let[taskId,left]of a){let right=b.get(taskId);if(!right||right.length!==left.length)return!1;for(let[i,token]of left.entries()){let other=right[i];if(!other||other.source!==token.source||other.key!==token.key||other.text!==token.text||other.tone!==token.tone||other.expiresAt!==token.expiresAt)return!1}}return!0}function liveRowTokens(map,taskId,now){let tokens=map?.get(taskId);if(!tokens||tokens.length===0)return[];return tokens.filter((token)=>token.expiresAt>now)}function shouldLogReconnectAttempt(attempt){if(attempt>100)return!1;return attempt===1||attempt%10===0}function describePayload(value){if(value===void 0)return"undefined";if(value===null)return"null";let type=Array.isArray(value)?"array":typeof value,text;try{text=typeof value==="string"?value:JSON.stringify(value)}catch{text=String(value)}if(text.length>120)text=`${text.slice(0,120)}\u2026`;return`${type}:${text}`}function decodeUiPrefsPayload(payload){let p=payload;if(!p||typeof p!=="object"||!("theme"in p))return null;if(p.theme!==null&&typeof p.theme!=="string")return null;return{theme:typeof p.theme==="string"&&p.theme.length>0?p.theme:null,..."themeMode"in p?{themeMode:typeof p.themeMode==="string"?p.themeMode:null}:{},transparentBackground:p.transparentBackground!==!1,focusAccent:typeof p.focusAccent==="string"?p.focusAccent:null,locale:typeof p.locale==="string"?p.locale:"",sortMode:p.sortMode==="recent"||p.sortMode==="attention"||p.sortMode==="name"?p.sortMode:"default",keysCollapsed:p.keysCollapsed===!0,projectFilter:typeof p.projectFilter==="string"&&p.projectFilter.length>0?p.projectFilter:null}}function contextPart(p){let items=Array.isArray(p.items)?p.items.filter((i)=>typeof i?.name==="string"&&typeof i?.tokens==="number"):[];return{key:p.key,tokens:p.tokens,...typeof p.label==="string"?{label:p.label}:{},...items.length>0?{items:items.map(({name,tokens})=>({name,tokens}))}:{},...typeof p.itemCount==="number"?{itemCount:p.itemCount}:{},...p.deferred===!0?{deferred:!0}:{}}}var TOKEN_TOTAL_FIELDS=["inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens"];function parseContextUsagePayload(payload){let context=payload?.context;if(!context||typeof context!=="object"||Array.isArray(context))return null;let map=new Map;for(let[key,value]of Object.entries(context)){let v=value;if(typeof v?.contextTokens!=="number")return null;if(v.contextWindowTokens!==void 0&&typeof v.contextWindowTokens!=="number")return null;let parts=v.parts;if(parts!==void 0&&(!Array.isArray(parts)||!parts.every((p)=>typeof p?.key==="string"&&typeof p?.tokens==="number")))return null;let totals={};for(let field of TOKEN_TOTAL_FIELDS){let raw=v[field];if(raw===void 0)continue;if(typeof raw!=="number")return null;totals[field]=raw}map.set(key,{contextTokens:v.contextTokens,...typeof v.contextWindowTokens==="number"?{contextWindowTokens:v.contextWindowTokens}:{},...v.approximate===!0?{approximate:!0}:{},...totals,...Array.isArray(parts)?{parts:parts.map(contextPart)}:{}})}return map}function sameContextUsageMap(a,b){if(a.size!==b.size)return!1;for(let[key,value]of a){let other=b.get(key);if(!other||other.contextTokens!==value.contextTokens||other.contextWindowTokens!==value.contextWindowTokens||other.approximate!==value.approximate||TOKEN_TOTAL_FIELDS.some((field)=>other[field]!==value[field])||JSON.stringify(other.parts)!==JSON.stringify(value.parts))return!1}return!0}function parseUsageSnapshotPayload(payload){let usage=payload?.usage;if(!usage||typeof usage!=="object"||Array.isArray(usage))return null;let map=new Map;for(let[vendor,value]of Object.entries(usage)){let snapshot=value;if(typeof snapshot?.capturedAt!=="number"||!Array.isArray(snapshot.windows))return null;let windows=[];for(let raw of snapshot.windows){let w=raw;if(typeof w?.kind!=="string"||typeof w.label!=="string"||typeof w.percent!=="number")return null;if(w.resetsAt!==null&&typeof w.resetsAt!=="number")return null;windows.push({kind:w.kind,label:w.label,percent:w.percent,resetsAt:w.resetsAt})}map.set(vendor,{windows,capturedAt:snapshot.capturedAt})}return map}function sameUsageSnapshotMap(a,b){if(a.size!==b.size)return!1;for(let[vendor,usage]of a){let other=b.get(vendor);if(!other||other.capturedAt!==usage.capturedAt||other.windows.length!==usage.windows.length)return!1;for(let i=0;i<usage.windows.length;i++){let x=usage.windows[i],y=other.windows[i];if(!x||!y||x.kind!==y.kind||x.label!==y.label||x.percent!==y.percent||x.resetsAt!==y.resetsAt)return!1}}return!0}function parseTranscriptActivityPayload(payload){let activity=payload?.activity;if(!activity||typeof activity!=="object"||Array.isArray(activity))return null;let map=new Map;for(let[path,value]of Object.entries(activity)){let v=value;if(typeof v?.mtimeMs!=="number"||typeof v.completionAt!=="number")return null;if(v.completionId!==null&&typeof v.completionId!=="string")return null;map.set(path,{mtimeMs:v.mtimeMs,completionId:v.completionId,completionAt:v.completionAt})}return map}function sameTranscriptActivityMap(a,b){if(a.size!==b.size)return!1;for(let[path,v]of a){let other=b.get(path);if(!other||other.mtimeMs!==v.mtimeMs||other.completionId!==v.completionId||other.completionAt!==v.completionAt)return!1}return!0}function deserializeTask(s){return{id:toTaskId(s.id),title:s.title,repo:s.repo,branch:s.branch,worktreePath:s.worktreePath,kind:s.kind==="main"?"dir":s.kind,...s.scratch?{scratch:!0}:{},...s.noProject?{noProject:!0}:{},...s.routine?{routine:s.routine}:{},status:s.status,pinned:s.pinned,...s.kept?{kept:!0}:{},...s.notes?{notes:s.notes}:{},...s.todos?{todos:s.todos}:{},...s.archived?{archived:!0}:{},vendor:s.vendor,command:s.command,prStatus:s.prStatus,modelEffort:s.modelEffort,model:s.model,tier:s.tier,groupId:s.groupId,observedLanguage:s.observedLanguage,deletion:s.deletion,quotaResume:s.quotaResume,scheduledStart:s.scheduledStart,...s.autoFixCi?{autoFixCi:s.autoFixCi}:{},linkedWorkItem:s.linkedWorkItem,dispatcher:s.dispatcher,...s.parentTaskId?{parentTaskId:toTaskId(s.parentTaskId)}:{},...s.sharesWorkspaceOf?{sharesWorkspaceOf:toTaskId(s.sharesWorkspaceOf)}:{},...s.cwdSubpath?{cwdSubpath:s.cwdSubpath}:{},...s.ptyAlias?{ptyAlias:s.ptyAlias}:{},...s.extraRepos?.length?{extraRepos:s.extraRepos}:{},...s.workspace?{workspace:s.workspace}:{},...s.sessionPrs?.length?{sessionPrs:s.sessionPrs}:{},requireReport:s.requireReport,...s.worktreeOnly?{worktreeOnly:!0}:{},prompt:s.prompt,baseRef:s.baseRef,worktreeName:s.worktreeName,...s.gitRepo?{gitRepo:s.gitRepo}:{},report:s.report,...s.repoId?{repoId:s.repoId}:{},createdAt:s.createdAt,updatedAt:s.updatedAt}}async function runReconnectLoop(deps){let delayMs=deps.spawnDaemon?Math.floor(Math.random()*400):500,attempt=0;while(!deps.isDisposed()){if(delayMs>0)await new Promise((r)=>setTimeout(r,delayMs));if(deps.isDisposed())break;attempt++;try{if(deps.spawnDaemon)await deps.ensureReachable();await deps.init(),logClient("orch",`reconnected and re-subscribed after ${attempt} attempt(s) \u2014 task list re-synced`);return}catch(err){if(isStaleInstallError(err)){logClientError("orch-reconnect-fatal",err),deps.onFatal?.(err);return}if(deps.shouldLogAttempt(attempt))logClientError("orch-reconnect",err);delayMs=delayMs===0?500:Math.min(delayMs*2,3000)}}}function singleFlightReconnect(deps){let current=null;return(spawnDaemon)=>{if(current)return current;let task=runReconnectLoop({...deps,spawnDaemon});current=task;let clear=()=>{if(current===task)current=null};return task.then(clear,clear),task}}async function performInit(client,opts,signals){let hello=await client.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION,minProtocolVersion:MIN_COMPATIBLE_PROTOCOL_VERSION}),daemonVersion=typeof hello.protocolVersion==="number"?hello.protocolVersion:DAEMON_PROTOCOL_VERSION,daemonMin=typeof hello.minProtocolVersion==="number"?hello.minProtocolVersion:daemonVersion;if(!isProtocolCompatible({localVersion:DAEMON_PROTOCOL_VERSION,localMin:MIN_COMPATIBLE_PROTOCOL_VERSION,remoteVersion:daemonVersion,remoteMin:daemonMin}))throw Error(`Rove daemon is protocol v${daemonVersion} (min v${daemonMin}); this client is v${DAEMON_PROTOCOL_VERSION} (min v${MIN_COMPATIBLE_PROTOCOL_VERSION}). Restart the daemon (\`rove daemon restart\`) or upgrade Rove.`);let clientHome=homeDir();if(!opts.expectForeignHome&&isForeignDaemonHome(hello.homeDir,clientHome))throw Error(`Rove daemon on this socket serves ${hello.homeDir}, but this client uses ${clientHome}. A sandbox or dev daemon has taken the production socket \u2014 stop it (\`rove daemon stop\`), or unset ROVE_DAEMON_SOCKET_PATH / ROVE_DAEMON_SOCKET_PATH before starting it.`);if(signals.setDaemonVersionSig(typeof hello.roveVersion==="string"?hello.roveVersion:null),opts.onPeerIdentity?.({hostname:typeof hello.hostname==="string"?hello.hostname:"",homeDir:typeof hello.homeDir==="string"?hello.homeDir:"",daemonPid:typeof hello.daemonPid==="number"?hello.daemonPid:0,roveVersion:typeof hello.roveVersion==="string"?hello.roveVersion:""}),signals.setDaemonRestartingSig(!1),hello.tasks&&opts.subscribesTasks)signals.setTasks(hello.tasks.map(deserializeTask));if(await client.subscribe({role:opts.role,channels:opts.channels,cellPixelSize:opts.cellPixelSize}),hello.capabilities?.includes("worktree.changes")){if(signals.worktreeChangesAcc()===null)signals.setWorktreeChangesSig(new Map)}else signals.setWorktreeChangesSig(null);if(hello.capabilities?.includes("transcript.activity")){if(signals.transcriptActivityAcc()===null)signals.setTranscriptActivitySig(new Map)}else signals.setTranscriptActivitySig(null);signals.setConnectionState("online"),logClient("orch",`subscribed as ${opts.role} (${signals.tasksAcc().length} tasks)`)}function ordinalOf(tabId,fallback){let match=/^tab-(\d+)$/.exec(tabId);return match?Number(match[1]):fallback}function adoptTabs(state,tabIds){let known=new Set(state.tabs.map((tab)=>tab.id)),fresh=[];for(let id of tabIds){if(known.has(id))continue;known.add(id),fresh.push(id)}if(fresh.length===0)return state;let minted=state.nextOrdinal,adopted=fresh.map((id)=>({kind:"engine",id,title:null,ordinal:ordinalOf(id,minted++),spawned:!0}));adopted.sort((a,b)=>a.ordinal-b.ordinal);let tabs=[...state.tabs,...adopted],maxOrdinal=tabs.reduce((max,tab)=>Math.max(max,tab.ordinal),0);return{tabs,activeId:state.activeId,nextOrdinal:Math.max(state.nextOrdinal,maxOrdinal+1)}}function isAddedTab(raw){if(typeof raw!=="object"||raw===null)return!1;if(!("id"in raw)||typeof raw.id!=="string")return!1;if(!("ordinal"in raw)||typeof raw.ordinal!=="number")return!1;if(!("title"in raw)||raw.title!==null&&typeof raw.title!=="string")return!1;if(!("kind"in raw))return!1;if(raw.kind==="engine")return!0;return raw.kind==="command"&&"command"in raw&&Array.isArray(raw.command)}function absorbTab(state,tab){let nextOrdinal=Math.max(state.nextOrdinal,tab.ordinal+1),known=state.tabs.find((t)=>t.id===tab.id);if(known?.kind===tab.kind){if(Object.entries(tab).every(([key,value])=>JSON.stringify(Reflect.get(known,key))===JSON.stringify(value))&&nextOrdinal===state.nextOrdinal)return state}let merged=known?.kind===tab.kind?{...known,...tab,title:known.title}:tab,tabs=known?state.tabs.map((t)=>t===known?merged:t):[...state.tabs,merged];return{...state,tabs,nextOrdinal}}var MAP_CHANNELS={"usage.snapshot":{what:"usage payload",parse:parseUsageSnapshotPayload,same:sameUsageSnapshotMap,read:(signals)=>signals.usageSnapshotAcc(),write:(signals,next)=>signals.setUsageSnapshotSig(next)},"usage.context":{what:"context payload",parse:parseContextUsagePayload,same:sameContextUsageMap,read:(signals)=>signals.contextUsageAcc(),write:(signals,next)=>signals.setContextUsageSig(next)},"worktree.changes":{what:"changes payload",parse:parseWorktreeChangesPayload,same:sameWorktreeChangesMap,read:(signals)=>signals.worktreeChangesAcc(),write:(signals,next)=>signals.setWorktreeChangesSig(next)},"transcript.activity":{what:"activity payload",parse:parseTranscriptActivityPayload,same:sameTranscriptActivityMap,read:(signals)=>signals.transcriptActivityAcc(),write:(signals,next)=>signals.setTranscriptActivitySig(next)},"mod.ui":{what:"mod pane list",parse:parseModUiPayload,same:(a,b)=>JSON.stringify(a)===JSON.stringify(b),read:(signals)=>signals.modPanesAcc(),write:(signals,next)=>signals.setModPanesSig(next)},"task.tokens":{what:"token map",parse:parseRowTokensPayload,same:sameRowTokenMap,read:(signals)=>signals.rowTokensAcc(),write:(signals,next)=>signals.setRowTokensSig(next)}};function handleMapChannel(name,payload,signals){let channel=MAP_CHANNELS[name];if(!channel)return!1;let next=channel.parse(payload);if(!next)return logClientError("orch",`dropped ${name} event: malformed ${channel.what} (${describePayload(payload)})`),!0;let current=channel.read(signals);if(current&&channel.same(current,next))return!0;return channel.write(signals,next),!0}function writeGraphicsToStdout(data){if(!process.stdout.isTTY)return;process.stdout.write(data)}function pruneEngineState(tasks,signals){let live=new Set(tasks.map((t)=>t.id)),current=signals.engineStateAcc();if(current.size>0){let next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setEngineStateSig(next)}let tabs=signals.engineTabStateAcc();if(tabs.size>0){let nextTabs=null;for(let key of tabs.keys()){if(live.has(key))continue;if(!nextTabs)nextTabs=new Map(tabs);nextTabs.delete(key)}if(nextTabs)signals.setEngineTabStateSig(nextTabs)}let lifecycle=signals.engineLifecycleAcc();if(lifecycle.size>0){let nextLifecycle=null;for(let key of lifecycle.keys()){if(live.has(key))continue;if(!nextLifecycle)nextLifecycle=new Map(lifecycle);nextLifecycle.delete(key)}if(nextLifecycle)signals.setEngineLifecycleSig(nextLifecycle)}}function pruneTaskJobs(tasks,signals){let current=signals.taskJobsAcc();if(current.size===0)return;let live=new Set(tasks.map((t)=>t.id)),next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setTaskJobsSig(next)}function handleOrchestratorEvent(name,payload,signals){if(name==="task.snapshot"){let value=payload?.tasks;if(Array.isArray(value))signals.setTasks(value.map(deserializeTask)),pruneEngineState(value,signals),pruneTaskJobs(value,signals);else logClientError("orch",`dropped task.snapshot event: tasks is not an array (got ${describePayload(value)})`);return}if(name==="daemon.stopping"){let p=payload;if(typeof p?.roveVersion==="string")signals.setDaemonVersionSig(p.roveVersion);if(parseDaemonStopReason(p?.reason)==="restart")signals.setDaemonRestartingSig(!0);return}if(name==="active-task"){let id=payload?.taskId;signals.setActiveTaskSig(typeof id==="string"?id:null);return}if(name==="update"){let info=payload?.info;signals.setUpdateSig(info??null);return}if(name==="engine-state"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.state!=="string"){logClientError("orch",`dropped engine-state event: taskId/state must be strings (taskId=${describePayload(p?.taskId)}, state=${describePayload(p?.state)})`);return}let tabId=typeof p.tabId==="string"&&p.tabId?p.tabId:void 0,entry={state:p.state,detail:p.detail,...typeof p.sessionId==="string"&&p.sessionId?{sessionId:p.sessionId}:{},...typeof p.transcriptPath==="string"&&p.transcriptPath?{transcriptPath:p.transcriptPath}:{},...tabId?{tabId}:{},at:typeof p.at==="number"?p.at:0},prevTaskState=signals.engineStateAcc().get(p.taskId)?.state;if(!tabId){let next=new Map(signals.engineStateAcc());if(p.state==="idle")next.delete(p.taskId);else next.set(p.taskId,entry);signals.setEngineStateSig(next)}if((p.state==="idle"||p.state==="turn_complete"||p.state==="error"||p.state==="running"&&prevTaskState!=="running")&&signals.engineLifecycleAcc().has(p.taskId)){let lifecycle=new Map(signals.engineLifecycleAcc());lifecycle.delete(p.taskId),signals.setEngineLifecycleSig(lifecycle)}if(tabId){let nextTabs=new Map(signals.engineTabStateAcc()),tabs=new Map(nextTabs.get(p.taskId)??[]);tabs.set(tabId,entry),nextTabs.set(p.taskId,tabs),signals.setEngineTabStateSig(nextTabs)}return}if(name==="attention.inbox"){let items=payload?.items;if(!Array.isArray(items)){logClientError("orch",`dropped attention.inbox event: items is not an array (${describePayload(items)})`);return}let kept=items.filter((item)=>{if(!item||typeof item!=="object"||Array.isArray(item))return!1;let p=item;return(typeof p.taskId==="string"||p.taskId===null&&isRoutineInboxState(p.state))&&(p.tabId===null||typeof p.tabId==="string")&&isAttentionInboxState(p.state)&&(p.unread===void 0||typeof p.unread==="boolean")&&typeof p.at==="number"});if(kept.length!==items.length)logClientError("orch",`dropped ${items.length-kept.length} malformed attention.inbox item(s) of ${items.length} (${describePayload(items)})`);if(kept.length===0&&items.length>0)return;signals.setAttentionInboxSig(kept.map((item)=>({...item,unread:item.unread!==!1})));return}if(name==="gates"){let gates=payload?.gates;if(!Array.isArray(gates)){logClientError("orch",`dropped gates event: gates is not an array (${describePayload(gates)})`);return}let kept=gates.filter((g)=>{if(!g||typeof g!=="object"||Array.isArray(g))return!1;let p=g;return typeof p.id==="string"&&typeof p.taskId==="string"&&typeof p.question==="string"});if(kept.length===0&&gates.length>0)return;signals.setGatesSig(kept.map((g)=>({...g,options:Array.isArray(g.options)?g.options:[]})));return}if(name==="task.jobs"){let p=payload;if(typeof p?.taskId!=="string"||p.kind!=="ensureWorktree"){logClientError("orch",`dropped task.jobs event: expected string taskId + kind "ensureWorktree" (taskId=${describePayload(p?.taskId)}, kind=${describePayload(p?.kind)})`);return}let current=signals.taskJobsAcc();if(p.phase==="running"){let progress=typeof p.progress==="number"&&Number.isFinite(p.progress)?p.progress:current.get(p.taskId)?.progress,next=new Map(current);next.set(p.taskId,progress===void 0?{kind:p.kind}:{kind:p.kind,progress}),signals.setTaskJobsSig(next);return}if((p.phase==="done"||p.phase==="error")&&current.has(p.taskId)){let next=new Map(current);next.delete(p.taskId),signals.setTaskJobsSig(next)}return}if(handleMapChannel(name,payload,signals))return;if(name==="tab.open"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||typeof p.title!=="string"||!Array.isArray(p.argv)){logClientError("orch",`dropped tab.open event: malformed payload (${describePayload(payload)})`);return}signals.setTabOpenSig(p);return}if(name==="tab.close"){let p=payload;if(!(p&&"kind"in p&&p.kind==="terminal-tab"?typeof p.taskId==="string"&&typeof p.tabId==="string"&&typeof p.requestId==="string"&&typeof p.at==="number":typeof p?.taskId==="string"&&typeof p.at==="number"&&("title"in p)&&typeof p.title==="string")){logClientError("orch",`dropped tab.close event: malformed payload (${describePayload(payload)})`);return}signals.setTabCloseSig(p);return}if(name==="tab.rename"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.tabId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped tab.rename event: malformed payload (${describePayload(payload)})`);return}signals.setTabRenameSig(p);return}if(name==="tabs.changed"){let p=payload,state=p?.state;if(typeof p?.taskId!=="string"||typeof p.rev!=="number"||state!==null&&(typeof state!=="object"||!Array.isArray(state?.tabs))){logClientError("orch",`dropped tabs.changed event: malformed payload (${describePayload(payload)})`);return}signals.emitTabsChanged(p);return}if(name==="row.status"){let p=payload;if(typeof p?.rev!=="number"||typeof p.tasks!=="object"||p.tasks===null){logClientError("orch",`dropped row.status event: malformed payload (${describePayload(payload)})`);return}signals.emitRowStatus(p);return}if(name==="tab.add"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||!isAddedTab(p.tab)){logClientError("orch",`dropped tab.add event: malformed payload (${describePayload(payload)})`);return}signals.setTabAddSig({taskId:p.taskId,tab:p.tab,at:p.at});return}if(name==="ui.prompt"){let p=payload;if(typeof p?.promptId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped ui.prompt event: malformed payload (${describePayload(payload)})`);return}signals.setUiPromptSig(p);return}if(name==="engine.lifecycle"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.kind!=="string"){logClientError("orch",`dropped engine.lifecycle event: malformed payload (${describePayload(payload)})`);return}let prev=signals.engineLifecycleAcc(),cur=prev.get(p.taskId)??{subagents:0},entry=p.kind==="subagent-start"?{subagents:cur.subagents+1}:p.kind==="subagent-stop"?{subagents:Math.max(0,cur.subagents-1)}:cur;if(entry===cur&&!prev.has(p.taskId))return;let map=new Map(prev);if(entry.subagents===0)map.delete(p.taskId);else map.set(p.taskId,entry);signals.setEngineLifecycleSig(map);return}if(name==="graphics.write"){let p=payload;if(typeof p?.data!=="string"||typeof p.imageId!=="number"||typeof p.at!=="number"){logClientError("orch",`dropped graphics.write event: malformed payload (${describePayload(payload)})`);return}signals.writeGraphics(Buffer.from(p.data,"base64"));return}if(name==="notice.event"){let p=payload;if(typeof p?.title!=="string"||typeof p.at!=="number"||typeof p.kind!=="string"){logClientError("orch",`dropped notice.event: malformed payload (${describePayload(payload)})`);return}signals.setNoticeSig(p);return}if(name==="ui-prefs"){let decoded=decodeUiPrefsPayload(payload);if(!decoded){let theme=payload?.theme;logClientError("orch",`dropped ui-prefs event: theme must be a string (got ${describePayload(theme)})`);return}signals.setUiPrefsSig(decoded);return}if(name==="state"||name==="machines"){signals.setRawSig(name,payload);return}if(name==="keybindings"){let p=payload;if(typeof p?.rev!=="number"){logClientError("orch",`dropped keybindings event: rev must be a number (got ${describePayload(p?.rev)})`);return}signals.setKeybindingsRevSig(p.rev)}}function subscribeTasksOp(tasks,listener){try{listener(tasks())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw on subscribe:",err)}return tasks.subscribe(()=>{try{listener(tasks.get())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw:",err)}})}async function legacyAdoptedTasksOp(client){return(await client.request("worktree.legacyAdopted",{})).tasks.map(deserializeTask)}class RowStatusChannel{client;listeners=new Set;constructor(client){this.client=client}emit=(payload)=>{for(let listener of this.listeners)listener(payload)};onChanged=(listener)=>{return this.listeners.add(listener),()=>this.listeners.delete(listener)};list=()=>this.client.request("status.list");viewing=(taskId,tabId)=>this.client.request("ui.viewing",taskId===null?{taskId:null}:{taskId,...tabId?{tabId}:{}});answered=(taskId,tabId)=>this.client.request("activity.answered",{taskId,tabId})}class TabsChannel{client;listeners=new Set;constructor(client){this.client=client}emit=(event)=>{for(let listener of this.listeners)listener(event)};onChanged=(listener)=>{return this.listeners.add(listener),()=>this.listeners.delete(listener)};apply=(taskId,ops)=>this.client.request("tabs.apply",{taskId,ops});list=()=>this.client.request("tabs.list");reserve=(taskId,count)=>this.client.request("tabs.reserve",{taskId,count});release=(taskId,from,to)=>this.client.request("tabs.release",{taskId,from,to})}async function createTaskOp(client,input){let{modelEffort,...rest}=input,res=await client.request("task.create",{...rest,effort:modelEffort});return deserializeTask(res.task)}async function ensureProjectOp(client,repo){return(await client.request("project.ensure",{repo})).repo}async function openDirectoryTaskOp(client,input){let res=await client.request("task.openDir",input);return deserializeTask(res.task)}async function adoptScratchRepoOp(client,id,repo){await client.request("task.adoptScratchRepo",{taskId:String(id),repo})}async function moveTaskToProjectOp(client,id,repo){let res=await client.request("task.moveToProject",{taskId:String(id),repo});return{repo:res.repo,moved:res.moved}}async function ensureWorktreeOp(client,id){return(await client.request("task.ensureWorktree",{taskId:String(id)})).worktreePath}async function forgetProjectOp(client,repo){await client.request("project.forget",{repo})}function reportEngineInterruptOp(client,taskId,tabId){client.request("engine.reportEvent",{kind:"turn-interrupted",taskId,tabId}).catch(()=>{})}async function setTitleOp(client,id,title){await client.request("task.rename",{taskId:String(id),title})}async function setBranchOp(client,id,branch){await client.request("task.setBranch",{taskId:String(id),branch})}async function setVendorOp(client,id,vendor,effort,model){await client.request("task.setVendor",{taskId:String(id),vendor,...effort!==void 0?{effort}:{},...model!==void 0?{model}:{}})}async function setCommandOp(client,id,command,vendor){await client.request("task.setCommand",{taskId:String(id),command,...vendor?{vendor}:{}})}async function setPinnedOp(client,id,pinned){await client.request("task.pin",{taskId:String(id),pinned})}async function archiveTaskOp(client,id,archived,flags={}){await client.request("task.archive",{taskId:String(id),archived,...flags})}async function moveTaskOp(client,id,delta){await client.request("task.move",{taskId:String(id),direction:delta<0?"up":"down"})}async function moveProjectOp(c,repo,target,side){await c.request("project.move",{repo,target,side})}async function setPromptOp(client,id,prompt){await client.request("task.setPrompt",{taskId:String(id),prompt})}async function setStatusOp(client,id,status){await client.request("task.status",{taskId:String(id),status})}async function deleteTaskOp(client,id,opts){return client.request("task.delete",{taskId:String(id),force:opts?.force,deleteBranch:opts?.deleteBranch,cascade:opts?.cascade})}async function spawnChildTaskOp(client,input){let{dispatcher,...rest}=input,res=await client.request("task.spawn",{...rest,...dispatcher?{dispatcherTaskId:dispatcher.taskId,dispatcherTabId:dispatcher.tabId}:{}});return{task:deserializeTask(res.task),parentDirty:res.parentDirty,sharedLinks:res.sharedLinks}}async function dismissAttentionOp(client,taskId,tabId,at,deliveryId){return(await client.request("attention.dismiss",{taskId:String(taskId),...tabId!==null?{tabId}:{},at,...deliveryId!==void 0?{deliveryId}:{}})).deleted}async function dismissRoutineAttentionOp(client,automationId){return(await client.request("attention.dismissRoutine",{automationId})).deleted}async function answerGateOp(client,gateId,answer){return{delivered:(await client.request("gate.answer",{gateId,...answer,by:"tui"})).delivered}}async function withdrawGateOp(client,gateId){await client.request("gate.withdraw",{gateId})}async function markAttentionReadOp(client,taskId,tabId,at){return(await client.request("attention.read",{taskId:String(taskId),...tabId!==null?{tabId}:{},at})).updated}async function landPreflightOp(client,id){return(await client.request("task.landPreflight",{taskId:String(id)})).result}async function landTaskOp(client,id,opts){return(await client.request("task.land",{taskId:String(id),strategy:opts?.strategy,deleteBranch:opts?.deleteBranch,removeWorktree:opts?.removeWorktree,callerCwd:opts?.callerCwd})).result}async function discoverAdoptableWorktreesOp(client,repo){return(await client.request("worktree.discoverAdoptable",{repo})).worktrees}async function adoptWorktreeOp(client,input){let res=await client.request("worktree.adopt",input);return deserializeTask(res.task)}async function listWorktreesOp(client,opts){return(await client.request("worktree.list",{network:opts?.network!==!1})).projects}async function removeWorktreeOp(client,path,force){return(await client.request("worktree.remove",{path,force})).residue??null}async function syncBaseOp(client,taskId){let res=await client.request("task.syncBase",{taskId}),failed=res.result.repos?.find((r)=>!r.ok);if(failed)throw Error(failed.error??"sync failed");return res.result}async function failingChecksOp(client,taskId){let res=await client.request("pr.failingChecks",{taskId});return{checks:res.checks??[],totalFailing:res.totalFailing??0,...res.unavailable?{unavailable:res.unavailable}:{}}}async function rerunFailedChecksOp(client,taskId){let res=await client.request("pr.rerunFailedChecks",{taskId});return{rerunRuns:res.rerunRuns??0,external:res.external??0,...res.refused?{refused:res.refused}:{},...res.unavailable?{unavailable:res.unavailable}:{}}}async function listIssuesOp(client,repoRoot){return client.request("issue.list",{repoRoot})}async function listIssueReposOp(client){return(await client.request("issue.repos",{})).repos??[]}async function listFieldNotesOp(client,repo){return(await client.request("note.list",{repo})).notes??[]}async function deleteFieldNoteOp(client,repo,id){return(await client.request("note.delete",{repo,id})).deleted===!0}async function mutateIssueOp(client,repoRoot,op){return client.request("issue.mutate",{repoRoot,op})}async function listAutomationsOp(client){return client.request("automation.list",{})}async function createAutomationOp(client,input){return client.request("automation.create",input)}async function automationRunsOp(client,id){return client.request("automation.runs",{id})}async function setAutomationEnabledOp(client,id,enabled){return client.request("automation.update",{id,enabled})}async function runAutomationNowOp(client,id){return client.request("automation.runNow",{id})}async function deleteAutomationOp(client,id){return client.request("automation.delete",{id})}async function listWorkItemsOp(client,args){return client.request("workitem.list",args)}async function startWorkItemOp(client,args){return client.request("workitem.start",args)}async function setActiveTaskOp(client,id){await client.request("task.setActive",{taskId:id===null?null:String(id)})}function replyTabCloseOp(client,requestId,closed){client.request("terminalTab.closeReply",{requestId,closed}).catch(()=>{})}function replyPromptOp(client,promptId,value){client.request("ui.promptReply",{promptId,...value!==void 0?{value}:{}}).catch(()=>{})}function reportUiEventOp(client,kind,taskId,detail){client.request("ui.reportEvent",{kind,...taskId?{taskId}:{},...detail?{detail}:{}}).catch(()=>{})}function recentTaskEventsOp(client,id){return client.request("task.recentEvents",{taskId:String(id)})}class RemoteOrchestrator{client;tasksAcc=createStateCell([],"orchestrator.tasks");activeTaskAcc=createStateCell(null,"orchestrator.active-task");updateAcc=createStateCell(null);daemonVersionAcc=createStateCell(null);daemonRestartingAcc=createStateCell(!1);daemonStaleAcc=mapReadableState(this.daemonVersionAcc,(version)=>isDaemonVersionStale(version??void 0,CURRENT_VERSION));engineStateAcc=createStateCell(new Map);engineTabStateAcc=createStateCell(new Map);attentionInboxAcc=createStateCell([]);gatesAcc=createStateCell([]);taskJobsAcc=createStateCell(new Map);rowTokensAcc=createStateCell(new Map);modPanesAcc=createStateCell([]);worktreeChangesAcc=createStateCell(null);usageSnapshotAcc=createStateCell(null);contextUsageAcc=createStateCell(null);transcriptActivityAcc=createStateCell(null);noticeAcc=createStateCell(null);tabOpenAcc=createStateCell(null);tabCloseAcc=createStateCell(null);tabRenameAcc=createStateCell(null);tabAddAcc=createStateCell(null);tabs;rowStatus;uiPromptAcc=createStateCell(null);engineLifecycleAcc=createStateCell(new Map);uiPrefsAcc=createStateCell(null);rawAcc={state:createStateCell(null),machines:createStateCell(null)};keybindingsRevAcc=createStateCell(null);connectionStateAcc=createStateCell("online","orchestrator.connection");staleInstallAcc=createStateCell(null);ensureReachable;role;cellPixelSize;channels;subscribesTasks;expectForeignHome;onPeerIdentity;reconnectLoop;signals;constructor(client,options={}){this.client=client;this.ensureReachable=options.ensureReachable??ensureDaemonReachable,this.role=options.role??"pane",this.cellPixelSize=options.cellPixelSize??null,this.channels=options.channels,this.subscribesTasks=!options.channels||options.channels.includes("task.snapshot"),this.expectForeignHome=options.expectForeignHome===!0,this.onPeerIdentity=options.onPeerIdentity,this.reconnectLoop=singleFlightReconnect({isDisposed:()=>client.isDisposed,ensureReachable:this.ensureReachable,init:()=>this.init(),shouldLogAttempt:shouldLogReconnectAttempt,onFatal:(err)=>this.staleInstallAcc.set(err instanceof Error?err.message:String(err))}),this.tabs=new TabsChannel(client),this.rowStatus=new RowStatusChannel(client),this.signals={writeGraphics:options.graphicsOut??(this.role==="gui"?writeGraphicsToStdout:()=>{}),tasksAcc:this.tasksAcc,setTasks:this.tasksAcc.set,setActiveTaskSig:this.activeTaskAcc.set,setUpdateSig:this.updateAcc.set,setDaemonVersionSig:this.daemonVersionAcc.set,setDaemonRestartingSig:this.daemonRestartingAcc.set,engineStateAcc:this.engineStateAcc,setEngineStateSig:this.engineStateAcc.set,engineTabStateAcc:this.engineTabStateAcc,setEngineTabStateSig:this.engineTabStateAcc.set,setAttentionInboxSig:this.attentionInboxAcc.set,setGatesSig:this.gatesAcc.set,taskJobsAcc:this.taskJobsAcc,setTaskJobsSig:this.taskJobsAcc.set,rowTokensAcc:this.rowTokensAcc,setRowTokensSig:this.rowTokensAcc.set,modPanesAcc:this.modPanesAcc,setModPanesSig:this.modPanesAcc.set,worktreeChangesAcc:this.worktreeChangesAcc,setWorktreeChangesSig:this.worktreeChangesAcc.set,usageSnapshotAcc:this.usageSnapshotAcc,setUsageSnapshotSig:this.usageSnapshotAcc.set,contextUsageAcc:this.contextUsageAcc,setContextUsageSig:this.contextUsageAcc.set,transcriptActivityAcc:this.transcriptActivityAcc,setTranscriptActivitySig:this.transcriptActivityAcc.set,setNoticeSig:this.noticeAcc.set,setTabOpenSig:this.tabOpenAcc.set,setTabCloseSig:this.tabCloseAcc.set,setTabRenameSig:this.tabRenameAcc.set,setTabAddSig:this.tabAddAcc.set,emitTabsChanged:this.tabs.emit,emitRowStatus:this.rowStatus.emit,setUiPromptSig:this.uiPromptAcc.set,engineLifecycleAcc:this.engineLifecycleAcc,setEngineLifecycleSig:this.engineLifecycleAcc.set,setUiPrefsSig:this.uiPrefsAcc.set,setRawSig:(name,payload)=>this.rawAcc[name].set(payload),setKeybindingsRevSig:this.keybindingsRevAcc.set,setConnectionState:this.connectionStateAcc.set},this.client.on("*",(frame)=>handleOrchestratorEvent(frame.name,frame.payload,this.signals)),this.client.onLifecycle("close",()=>{this.connectionStateAcc.set("disconnected");let spawnDaemon=this.role==="gui";logClient("orch",spawnDaemon?"daemon socket closed \u2014 starting silent spawning reconnect loop":"daemon socket closed \u2014 starting non-spawning reconnect loop"),this.reconnectLoop(spawnDaemon)})}writeGraphics(data){this.signals.writeGraphics(data)}async init(){await performInit(this.client,{role:this.role,cellPixelSize:this.cellPixelSize,channels:this.channels,subscribesTasks:this.subscribesTasks,expectForeignHome:this.expectForeignHome,onPeerIdentity:this.onPeerIdentity},this.signals)}connectionStateSignal(){return this.connectionStateAcc}staleInstallSignal(){return this.staleInstallAcc}async manualReconnect(){this.client.forceDisconnect(),await this.reconnectLoop(!0)}dispose(){this.client.close()}tasksSignal=()=>this.tasksAcc;activeTaskSignal=()=>this.activeTaskAcc;updateSignal=()=>this.updateAcc;daemonVersionSignal=()=>this.daemonVersionAcc;daemonStaleSignal=()=>this.daemonStaleAcc;daemonRestartingSignal=()=>this.daemonRestartingAcc;async restartDaemon(){await restartDaemon().catch(()=>{})}engineStateSignal=()=>this.engineStateAcc;engineTabStatesSignal=()=>this.engineTabStateAcc;attentionInboxSignal=()=>this.attentionInboxAcc;gatesSignal=()=>this.gatesAcc;taskJobsSignal=()=>this.taskJobsAcc;rowTokensSignal=()=>this.rowTokensAcc;modPanesSignal=()=>this.modPanesAcc;pressMod=(plugin,pane,key)=>this.client.request("mod.press",{plugin,pane,key});submitMod=(plugin,pane,key,value)=>this.client.request("mod.submit",{plugin,pane,key,value});worktreeChangesSignal=()=>this.worktreeChangesAcc;usageSnapshotSignal=()=>this.usageSnapshotAcc;contextUsageSignal=()=>this.contextUsageAcc;transcriptActivitySignal=()=>this.transcriptActivityAcc;transcriptActivityStore=()=>this.transcriptActivityAcc;noticeStore=()=>this.noticeAcc;tabOpenStore=()=>this.tabOpenAcc;tabCloseStore=()=>this.tabCloseAcc;tabRenameStore=()=>this.tabRenameAcc;tabAddStore=()=>this.tabAddAcc;rpc={request:(name,payload)=>this.client.request(name,payload)};replyTerminalTabClose=(requestId,closed)=>replyTabCloseOp(this.client,requestId,closed);uiPromptStore=()=>this.uiPromptAcc;replyPrompt=(promptId,value)=>replyPromptOp(this.client,promptId,value);engineLifecycleSignal=()=>this.engineLifecycleAcc;recentTaskEvents(id){return recentTaskEventsOp(this.client,id)}reportUiEvent=(kind,taskId,detail)=>reportUiEventOp(this.client,kind,taskId,detail);reportScreenInput=async(taskId,tabId,blocked)=>{await this.client.request("engine.reportEvent",{source:"screen",taskId,tabId,blocked})};reportEngineInterrupt=(taskId,tabId)=>reportEngineInterruptOp(this.client,String(taskId),tabId);uiPrefsSignal=()=>this.uiPrefsAcc;uiPrefsStore=()=>this.uiPrefsAcc;rawChannelSignal=(name)=>this.rawAcc[name];keybindingsRevSignal=()=>this.keybindingsRevAcc;keybindingsRevStore=()=>this.keybindingsRevAcc;listTasks=()=>this.tasksAcc();getTask=(id)=>this.tasksAcc().find((task)=>task.id===id);subscribeTasks(listener){return subscribeTasksOp(this.tasksAcc,listener)}createTask=(input)=>createTaskOp(this.client,input);ensureProject=(repo)=>ensureProjectOp(this.client,repo);openDirectoryTask=(input)=>openDirectoryTaskOp(this.client,input);adoptScratchRepo=(id,repo)=>adoptScratchRepoOp(this.client,id,repo);moveTaskToProject=(id,repo)=>moveTaskToProjectOp(this.client,id,repo);ensureWorktree=(id)=>ensureWorktreeOp(this.client,id);forgetProject=(repo)=>forgetProjectOp(this.client,repo);setTitle=(id,title)=>setTitleOp(this.client,id,title);setBranch=(id,branch)=>setBranchOp(this.client,id,branch);setVendor=(id,vendor,effort,model)=>setVendorOp(this.client,id,vendor,effort,model);setCommand=(id,command,vendor)=>setCommandOp(this.client,id,command,vendor);setPinned=(id,pinned)=>setPinnedOp(this.client,id,pinned);archiveTask=(id,archived,force,promote)=>archiveTaskOp(this.client,id,archived,{force,promote});moveTask=(id,delta)=>moveTaskOp(this.client,id,delta);moveProject=(from,to,at)=>moveProjectOp(this.client,from,to,at);setStatus=(id,status)=>setStatusOp(this.client,id,status);setPrompt=(id,prompt)=>setPromptOp(this.client,id,prompt);deleteTask=(id,opts)=>deleteTaskOp(this.client,id,opts);spawnChildTask=(input)=>spawnChildTaskOp(this.client,input);dismissAttention=(taskId,tabId,at,deliveryId)=>dismissAttentionOp(this.client,taskId,tabId,at,deliveryId);dismissRoutineAttention=(automationId)=>dismissRoutineAttentionOp(this.client,automationId);markAttentionRead=(taskId,tabId,at)=>markAttentionReadOp(this.client,taskId,tabId,at);answerGate=(gateId,answer)=>answerGateOp(this.client,gateId,answer);withdrawGate=(gateId)=>withdrawGateOp(this.client,gateId);landPreflight(id){return landPreflightOp(this.client,id)}landTask(id,opts){return landTaskOp(this.client,id,opts)}discoverAdoptableWorktrees=(repo)=>discoverAdoptableWorktreesOp(this.client,repo);legacyAdoptedTasks=()=>legacyAdoptedTasksOp(this.client);adoptWorktree(input){return adoptWorktreeOp(this.client,input)}listWorktrees(opts){return listWorktreesOp(this.client,opts)}listIssues(repoRoot){return listIssuesOp(this.client,repoRoot)}listIssueRepos(){return listIssueReposOp(this.client)}mutateIssue(repoRoot,op){return mutateIssueOp(this.client,repoRoot,op)}listAutomations=()=>listAutomationsOp(this.client);createAutomation=(i)=>createAutomationOp(this.client,i);automationRuns=(id)=>automationRunsOp(this.client,id);setAutomationEnabled=(id,on)=>setAutomationEnabledOp(this.client,id,on);runAutomationNow=(id)=>runAutomationNowOp(this.client,id);deleteAutomation=(id)=>deleteAutomationOp(this.client,id);listWorkItems=(a)=>listWorkItemsOp(this.client,a);listFieldNotes=(repo)=>listFieldNotesOp(this.client,repo);deleteFieldNote=(repo,id)=>deleteFieldNoteOp(this.client,repo,id);failingChecks=(taskId)=>failingChecksOp(this.client,taskId);rerunFailedChecks=(taskId)=>rerunFailedChecksOp(this.client,taskId);syncBase=(taskId)=>syncBaseOp(this.client,taskId);startWorkItem=(a)=>startWorkItemOp(this.client,a);removeWorktree(path,force){return removeWorktreeOp(this.client,path,force)}setActiveTask(id){return setActiveTaskOp(this.client,id)}}
3
3
  export{liveRowTokens,adoptTabs,absorbTab,RemoteOrchestrator};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import{TaskDeletingError}from"./chunk-79wejcs5.js";import{awaitEngineProcess,deliverToHostedKey,enginePresence,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-fpecy1fw.js";import{buildEngineSessionLaunch,launchReposOf,markCliTabSession,publishCliTabSnapshot,readDaemonTabs,trustEngineWorktree,trustExtraRepos}from"./chunk-hafbyy9x.js";import{engineLaunchArgv,engineResumeArgv,protocolEntry,withPinnedSessionId}from"./chunk-zc7e78mv.js";import{hostedKeyFor}from"./chunk-g9ba25q5.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{taskCwd}from"./chunk-tcmzq86w.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);let hasExtras=Boolean(task.extraRepos?.length);if(task.worktreePath&&!hasExtras){let repos=task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0;return{task,worktreePath:taskCwd(task),repos}}let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath:taskCwd({worktreePath,cwdSubpath:task.cwdSubpath}),repos:hasExtras||task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"},repos),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,model:task.model})[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,options={}){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let base=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model}),row=(await readDaemonTabs(link,taskId).catch(()=>{return}))?.tabs.find((tab)=>tab.id==="tab-1"),held=row?.kind==="engine"&&row.spawned&&row.sessionId?row.sessionId:null,resumeArgv=held&&!options.newConversation?engineResumeArgv(base,task.vendor,held):null,host=await ensureHostedSessionHost();try{let start=async(argv,text)=>{let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt:text},repos,argv),opened=await ensureHostedEngine(host.rpc,worktreePath,launch);if(!opened.alive)return{started:!1,error:"hosted session did not open",key:launch.key};let wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs},reattached=opened.created===!1&&opened.respawned!==!0,paste=launch.firstMessage??(reattached?text:void 0);if((paste?await pastePromptWhenEngineUp(host.rpc,launch.key,base[0],paste,wait):await awaitEngineProcess(host.rpc,launch.key,base[0],wait))!==null)return{started:!0,key:launch.key};if(reattached)return{started:!1,error:"NOT_DELIVERED: tab-1 was already open and the prompt could not be pasted into its engine",key:launch.key};return{started:!1,error:await startFailureReason(host.rpc,launch.key),key:launch.key}};if(resumeArgv){let resumed=await start(resumeArgv,options.resumedPrompt??prompt);if(resumed.started)return{started:!0,resumed:!0};await killHostedSessions(host.rpc,[resumed.key],{wait:!0})}let pinned=withPinnedSessionId(base,task.vendor),{key:_key,...fresh}=await start(pinned.argv,prompt);if(fresh.started)await publishCliTabSnapshot(link,taskId,pinned.sessionId),await markCliTabSession(link,taskId,"tab-1",pinned.sessionId);return fresh}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,repos,argv=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model})){return trustEngineWorktree(task.vendor,worktreePath),trustExtraRepos(task.vendor,repos),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo,repos},worktreePath,shell:resolveSessionShell(),argv,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],task.scope);if(!key)return!1;let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return!1;return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})!==null}catch{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],task.scope);if(!key)return{outcome:"no-session"};let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}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=hostedKeyFor(target.id,target.tabId,target.scope);if(!key)return{outcome:"no-session"};let 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}),presence=await enginePresence(session.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:target.tabId};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId,scope){let host=await openHostedSessionHost();if(!host)return;try{let keys=hostedTaskKeys(await listHostedSessions(host.rpc),taskId,scope);await killHostedSessions(host.rpc,keys,{wait:!0})}catch{}finally{host.close()}}async function stopTaskEngineTabAdapter(taskId,tabId,scope){let host=await openHostedSessionHost();if(!host)return;try{let key=hostedKeyFor(taskId,tabId,scope);if(key)await killHostedSessions(host.rpc,[key],{wait:!0})}finally{host.close()}}
2
+ import{deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import{TaskDeletingError}from"./chunk-79wejcs5.js";import{awaitEngineProcess,deliverToHostedKey,enginePresence,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp}from"./chunk-bznee97z.js";import{buildEngineSessionLaunch,launchReposOf,markCliTabSession,publishCliTabSnapshot,readDaemonTabs,trustEngineWorktree,trustExtraRepos}from"./chunk-q6q4aram.js";import{engineLaunchArgv,engineResumeArgv,protocolEntry,withPinnedSessionId}from"./chunk-zc7e78mv.js";import{hostedKeyFor}from"./chunk-g9ba25q5.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{taskCwd}from"./chunk-tcmzq86w.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);let hasExtras=Boolean(task.extraRepos?.length);if(task.worktreePath&&!hasExtras){let repos=task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0;return{task,worktreePath:taskCwd(task),repos}}let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath:taskCwd({worktreePath,cwdSubpath:task.cwdSubpath}),repos:hasExtras||task.sharesWorkspaceOf?await launchReposOf(link,taskId):void 0}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"},repos),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,model:task.model})[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,options={}){let{task,worktreePath,repos}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let base=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model}),row=(await readDaemonTabs(link,taskId).catch(()=>{return}))?.tabs.find((tab)=>tab.id==="tab-1"),held=row?.kind==="engine"&&row.spawned&&row.sessionId?row.sessionId:null,resumeArgv=held&&!options.newConversation?engineResumeArgv(base,task.vendor,held):null,host=await ensureHostedSessionHost();try{let start=async(argv,text)=>{let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt:text},repos,argv),opened=await ensureHostedEngine(host.rpc,worktreePath,launch);if(!opened.alive)return{started:!1,error:"hosted session did not open",key:launch.key};let wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs},reattached=opened.created===!1&&opened.respawned!==!0,paste=launch.firstMessage??(reattached?text:void 0);if((paste?await pastePromptWhenEngineUp(host.rpc,launch.key,base[0],paste,wait):await awaitEngineProcess(host.rpc,launch.key,base[0],wait))!==null)return{started:!0,key:launch.key};if(reattached)return{started:!1,error:"NOT_DELIVERED: tab-1 was already open and the prompt could not be pasted into its engine",key:launch.key};return{started:!1,error:await startFailureReason(host.rpc,launch.key),key:launch.key}};if(resumeArgv){let resumed=await start(resumeArgv,options.resumedPrompt??prompt);if(resumed.started)return{started:!0,resumed:!0};await killHostedSessions(host.rpc,[resumed.key],{wait:!0})}let pinned=withPinnedSessionId(base,task.vendor),{key:_key,...fresh}=await start(pinned.argv,prompt);if(fresh.started)await publishCliTabSnapshot(link,taskId,pinned.sessionId),await markCliTabSession(link,taskId,"tab-1",pinned.sessionId);return fresh}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,repos,argv=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort,model:task.model})){return trustEngineWorktree(task.vendor,worktreePath),trustExtraRepos(task.vendor,repos),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo,repos},worktreePath,shell:resolveSessionShell(),argv,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],task.scope);if(!key)return!1;let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return!1;return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})!==null}catch{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],task.scope);if(!key)return{outcome:"no-session"};let presence=await enginePresence(sessions.find((s)=>s.key===key)?.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}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=hostedKeyFor(target.id,target.tabId,target.scope);if(!key)return{outcome:"no-session"};let 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}),presence=await enginePresence(session.pid,engineArgv);if(presence.kind!=="engine")return{outcome:"no-engine",tabId:target.tabId};return await deliverToHostedKey(host.rpc,key,prompt,{vendor:presence.vendor})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId,scope){let host=await openHostedSessionHost();if(!host)return;try{let keys=hostedTaskKeys(await listHostedSessions(host.rpc),taskId,scope);await killHostedSessions(host.rpc,keys,{wait:!0})}catch{}finally{host.close()}}async function stopTaskEngineTabAdapter(taskId,tabId,scope){let host=await openHostedSessionHost();if(!host)return;try{let key=hostedKeyFor(taskId,tabId,scope);if(key)await killHostedSessions(host.rpc,[key],{wait:!0})}finally{host.close()}}
3
3
  export{deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,tearDownTaskSessionAdapter,stopTaskEngineTabAdapter};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{preferredReleaseChannel}from"./chunk-gx3j06wx.js";import{discoverMachine,remoteRove,runOnMachine}from"./chunk-nb99x2kt.js";var DEFAULTS={version:async(entry)=>{let found=await discoverMachine(entry.alias,entry);return found.ok?found.status.roveVersion||null:null},installed:async(entry)=>{let out=await runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,["--version"]),{timeoutMs:30000});return/\b(\d+\.\d+\.\d+\S*)/.exec(out.stdout)?.[1]??null},run:(entry,args,timeoutMs)=>runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,args),{timeoutMs}),channel:preferredReleaseChannel},lastLines=(run)=>`${run.stdout}
2
+ import{preferredReleaseChannel}from"./chunk-q8b6gnc5.js";import{discoverMachine,remoteRove,runOnMachine}from"./chunk-x4gqyhhv.js";var DEFAULTS={version:async(entry)=>{let found=await discoverMachine(entry.alias,entry);return found.ok?found.status.roveVersion||null:null},installed:async(entry)=>{let out=await runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,["--version"]),{timeoutMs:30000});return/\b(\d+\.\d+\.\d+\S*)/.exec(out.stdout)?.[1]??null},run:(entry,args,timeoutMs)=>runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,args),{timeoutMs}),channel:preferredReleaseChannel},lastLines=(run)=>`${run.stdout}
3
3
  ${run.stderr}`.trim().split(`
4
4
  `).slice(-6).join(`
5
5
  `)||`exit ${run.exitCode}`;async function upgradeMachine(entry,overrides={}){let deps={...DEFAULTS,...overrides},{alias}=entry,from=await deps.version(entry),install=await deps.run(entry,["update","--channel",deps.channel()],600000);if(install.exitCode!==0)throw Error(`rove update on ${alias} failed:
@@ -0,0 +1,6 @@
1
+ // @bun
2
+ import{CURRENT_VERSION}from"./chunk-0r64dqy3.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-d9e1vx7y.js";import"./chunk-cw9h73h5.js";import"./chunk-pe92nt86.js";import"./chunk-nw48bskt.js";import{flagValue}from"./chunk-zsfyj36g.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir))}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
3
+ `);if(lines.length<=count+1)return text;return`${lines.slice(0,count).join(`
4
+ `)}
5
+ [cut at line ${from+count-1}; pass offset to read on]`}if(name==="write"){if(typeof a.content!=="string")throw Error("content is required");return write(a.content),`wrote ${path}`}if(name==="edit"){let{old_string:from,new_string:to}=a;if(typeof from!=="string"||typeof to!=="string"||!from)throw Error("old_string and new_string are required");let text=must(run(`cat -- ${file}`)),hits=text.split(from).length-1;if(hits===0)throw Error(`old_string not found in ${path}`);if(hits>1&&a.replace_all!==!0)throw Error(`old_string occurs ${hits} times in ${path}; add context to make it unique, or pass replace_all`);return write(text.split(from).join(to)),`edited ${path} (${hits} replacement${hits===1?"":"s"})`}throw Error(`unknown tool: ${name}`)}function mcpReply(run,msg){if(msg.id===void 0||!msg.method)return null;let result=(value)=>({jsonrpc:"2.0",id:msg.id,result:value});if(msg.method==="initialize")return result({protocolVersion:typeof msg.params?.protocolVersion==="string"?msg.params.protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rove-workspace",version:CURRENT_VERSION}});if(msg.method==="ping")return result({});if(msg.method==="tools/list")return result({tools:TOOLS});if(msg.method==="tools/call"){let args=msg.params?.arguments??{};try{let text=callWorkspaceTool(run,String(msg.params?.name??""),args);return result({content:[{type:"text",text}]})}catch(err){return result({content:[{type:"text",text:err instanceof Error?err.message:String(err)}],isError:!0})}}return{jsonrpc:"2.0",id:msg.id,error:{code:-32601,message:`method not found: ${msg.method}`}}}async function serveMcp(rx){let run=runThrough(rx);for await(let line of createInterface({input:process.stdin})){if(!line.trim())continue;let msg;try{msg=JSON.parse(line)}catch{continue}let reply=mcpReply(run,msg);if(reply)process.stdout.write(`${JSON.stringify(reply)}
6
+ `)}}export{runRemoteWorkspaceSubcommand,mcpReply,fileHookReply,callWorkspaceTool,bashHookReply};
package/dist/cli/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- import{isPathLikeArg}from"./chunk-zye0b9c0.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION}from"./chunk-fphcr46j.js";import{switchFlag}from"./chunk-zsfyj36g.js";import{expandTilde}from"./chunk-1feav1w3.js";import{errorMessage}from"./chunk-9gctbddn.js";import{rejectionReason}from"./chunk-mg1cas61.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{resolve}from"path";var DYNAMIC_COMMANDS=new Map([["_trust-claude-worktree",async(paths)=>{let{trustClaudeWorktree}=await import("./chunk-pd819cnw.js");for(let path of paths)try{trustClaudeWorktree(path)}catch{}}],["completions",async(args)=>{let{runCompletionsSubcommand}=await import("./chunk-e4gepsz1.js");await runCompletionsSubcommand(args)}],["export",async(args)=>{let{runExportSubcommand}=await import("./chunk-szxbn69n.js");await runExportSubcommand(args)}],["repo",async(args)=>{let{runRepoSubcommand}=await import("./chunk-2pc4wpm4.js");await runRepoSubcommand(args)}],["api",async(args)=>{let{runApiSubcommand}=await import("./chunk-e99pbfjx.js");await runApiSubcommand(args)}],["update",async(args)=>{let{runUpdateSubcommand}=await import("./chunk-r79n2ebq.js");await runUpdateSubcommand(args)}],["theme",async(args)=>{let{runThemeSubcommand}=await import("./chunk-sqcntdty.js");await runThemeSubcommand(args)}],["feedback",async(args)=>{let{runFeedbackSubcommand}=await import("./chunk-gej20ab5.js");await runFeedbackSubcommand(args)}],["daemon",async(args)=>{let{runDaemonSubcommand}=await import("./chunk-rnrja9fy.js");await runDaemonSubcommand(args)}],["machine",async(args)=>{let{runMachineSubcommand}=await import("./chunk-w2k5rw0q.js");await runMachineSubcommand(args)}],["weixin",async(args)=>{let{runChannelCli}=await import("./chunk-d11v35wg.js");await runChannelCli("weixin",args)}],["doctor",async(args)=>{let{runDoctorSubcommand}=await import("./chunk-xzhb4qs8.js");await runDoctorSubcommand(args)}],["config",async(args)=>{let{runConfigSubcommand}=await import("./chunk-0r5jdh3b.js");await runConfigSubcommand(args)}],["reset",async(args)=>{let{runResetSubcommand}=await import("./chunk-xjf4k0xf.js");await runResetSubcommand(args)}],["pty-host",async(args)=>{let{runPtyHostSubcommand}=await import("./chunk-bwcyr929.js");await runPtyHostSubcommand(args)}],["skill",async(args)=>{let{runSkillSubcommand}=await import("./chunk-wh147k4t.js");await runSkillSubcommand(args)}],["plugin",async(args)=>{let{runPluginSubcommand}=await import("./chunk-r9c7txh5.js");await runPluginSubcommand(args)}],["remote-workspace",async(args)=>{let{runRemoteWorkspaceSubcommand}=await import("./chunk-q8brjhze.js");await runRemoteWorkspaceSubcommand(args)}],["hook",async(args)=>{let{runHookSubcommand}=await import("./chunk-96jqrzcp.js");await runHookSubcommand(args)}]]);function topLevelUsage(cliName=ROVE_PRODUCT_NAME){return[`${cliName} ${CURRENT_VERSION}`,"",`Usage: ${cliName} [command] [options]`,"","Run with no command to launch PureTUI.",`Run \`${cliName} .\` (or \`${cliName} <path>\`) to open a directory as a standalone task.`,"","Commands:"," completions <shell> Generate shell completion script (bash/zsh/fish)"," add [path] Save a repo path for the new-task picker"," remove [path] Forget a saved project (inverse of add; non-destructive)"," adopt [glob] Import existing git worktrees as tasks"," export [--csv|--json] Print the task list (json/csv/table; daemon-free)"," repo <verb> Per-repo init script + first prompt (show|set|unset)",` api <verb> Scriptable RPC surface for agents (see \`${cliName} api --help\`)`," daemon <verb> Manage the daemon (start|stop|status|restart|autostart)"," machine <verb> Other computers running Rove (add|doctor|remove|list)"," weixin <verb> Talk to Rove from WeChat (login|logout|status|allow|deny|send|agent)"," doctor [--report|--fix] Diagnose daemon/PTY/engines/git; --fix walks the remedies",` config [--path] Open ${cliName}'s config file (state.json) in your editor`," reset [--hard] Stop runtimes; optionally wipe task/UI state"," theme <verb> Manage user themes (list|add|remove)",` skill <verb> Install the ${cliName} agent skill (install|status|command|print)`," plugin <verb> Install and run plugins (install|link|list|action|\u2026)"," feedback File a GitHub issue on the Rove repo",` update [version|channel|list] Self-update ${cliName}, switch channel, or list versions`,"","Options:"," -v, --version Print version"," -h, --help Print this help"," --skill Print the agent skill file and exit"," --web [bridge flags] Serve the browser client on 127.0.0.1 and print its link"].join(`
4
- `)}var bridge=()=>import("./chunk-k6wxbh9e.js"),CLI_NAME=ROVE_PRODUCT_NAME,ADD_USAGE=[`Usage: ${CLI_NAME} add [path]`,` ${CLI_NAME} add --remote --host <host> --user <user> --path <basePath> [--port N] [--key [path] | --password]`,"","Save a repo for the new-task picker. With --remote, register an SSH-backed","project whose worktrees live on <host>; engine launch over SSH is pending.",""].join(`
3
+ import{isPathLikeArg}from"./chunk-7d22h7qg.js";import{matchPathGlob}from"./chunk-kg11c1py.js";import{CURRENT_VERSION}from"./chunk-0r64dqy3.js";import{switchFlag}from"./chunk-zsfyj36g.js";import{expandTilde}from"./chunk-1feav1w3.js";import{errorMessage}from"./chunk-9gctbddn.js";import{rejectionReason}from"./chunk-mg1cas61.js";import{BUILTIN_VENDORS,coerceVendorId,isBuiltinVendor}from"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{resolve}from"path";var DYNAMIC_COMMANDS=new Map([["_trust-claude-worktree",async(paths)=>{let{trustClaudeWorktree}=await import("./chunk-pd819cnw.js");for(let path of paths)try{trustClaudeWorktree(path)}catch{}}],["completions",async(args)=>{let{runCompletionsSubcommand}=await import("./chunk-qnkq7d8z.js");await runCompletionsSubcommand(args)}],["export",async(args)=>{let{runExportSubcommand}=await import("./chunk-szxbn69n.js");await runExportSubcommand(args)}],["repo",async(args)=>{let{runRepoSubcommand}=await import("./chunk-2pc4wpm4.js");await runRepoSubcommand(args)}],["api",async(args)=>{let{runApiSubcommand}=await import("./chunk-46zqt24x.js");await runApiSubcommand(args)}],["update",async(args)=>{let{runUpdateSubcommand}=await import("./chunk-g770enx5.js");await runUpdateSubcommand(args)}],["theme",async(args)=>{let{runThemeSubcommand}=await import("./chunk-sqcntdty.js");await runThemeSubcommand(args)}],["feedback",async(args)=>{let{runFeedbackSubcommand}=await import("./chunk-689sfk7h.js");await runFeedbackSubcommand(args)}],["daemon",async(args)=>{let{runDaemonSubcommand}=await import("./chunk-e04yypye.js");await runDaemonSubcommand(args)}],["machine",async(args)=>{let{runMachineSubcommand}=await import("./chunk-7zawz6sa.js");await runMachineSubcommand(args)}],["weixin",async(args)=>{let{runChannelCli}=await import("./chunk-qjr63j9v.js");await runChannelCli("weixin",args)}],["doctor",async(args)=>{let{runDoctorSubcommand}=await import("./chunk-mdypt84n.js");await runDoctorSubcommand(args)}],["config",async(args)=>{let{runConfigSubcommand}=await import("./chunk-0r5jdh3b.js");await runConfigSubcommand(args)}],["reset",async(args)=>{let{runResetSubcommand}=await import("./chunk-22syh28c.js");await runResetSubcommand(args)}],["pty-host",async(args)=>{let{runPtyHostSubcommand}=await import("./chunk-rajwag3e.js");await runPtyHostSubcommand(args)}],["skill",async(args)=>{let{runSkillSubcommand}=await import("./chunk-wh147k4t.js");await runSkillSubcommand(args)}],["plugin",async(args)=>{let{runPluginSubcommand}=await import("./chunk-tr9n297x.js");await runPluginSubcommand(args)}],["remote-workspace",async(args)=>{let{runRemoteWorkspaceSubcommand}=await import("./chunk-zshgx9fp.js");await runRemoteWorkspaceSubcommand(args)}],["hook",async(args)=>{let{runHookSubcommand}=await import("./chunk-96jqrzcp.js");await runHookSubcommand(args)}]]);function topLevelUsage(cliName=ROVE_PRODUCT_NAME){return[`${cliName} ${CURRENT_VERSION}`,"",`Usage: ${cliName} [command] [options]`,"","Run with no command to launch PureTUI.",`Run \`${cliName} .\` (or \`${cliName} <path>\`) to open a directory as a standalone task.`,"","Commands:"," completions <shell> Generate shell completion script (bash/zsh/fish)"," add [path] Save a repo path for the new-task picker"," remove [path] Forget a saved project (inverse of add; non-destructive)"," adopt [glob] Import existing git worktrees as tasks"," export [--csv|--json] Print the task list (json/csv/table; daemon-free)"," repo <verb> Per-repo init script + first prompt (show|set|unset)",` api <verb> Scriptable RPC surface for agents (see \`${cliName} api --help\`)`," daemon <verb> Manage the daemon (start|stop|status|restart|autostart)"," machine <verb> Other computers running Rove (add|doctor|remove|list)"," weixin <verb> Talk to Rove from WeChat (login|logout|status|allow|deny|send|agent)"," doctor [--report|--fix] Diagnose daemon/PTY/engines/git; --fix walks the remedies",` config [--path] Open ${cliName}'s config file (state.json) in your editor`," reset [--hard] Stop runtimes; optionally wipe task/UI state"," theme <verb> Manage user themes (list|add|remove)",` skill <verb> Install the ${cliName} agent skill (install|status|command|print)`," plugin <verb> Install and run plugins (install|link|list|action|\u2026)"," feedback File a GitHub issue on the Rove repo",` update [version|channel|list] Self-update ${cliName}, switch channel, or list versions`,"","Options:"," -v, --version Print version"," -h, --help Print this help"," --skill Print the agent skill file and exit"," --web [bridge flags] Serve the browser client on 127.0.0.1 and print its link"].join(`
4
+ `)}var bridge=()=>import("./chunk-jkxn32nk.js"),CLI_NAME=ROVE_PRODUCT_NAME,ADD_USAGE=[`Usage: ${CLI_NAME} add [path]`,` ${CLI_NAME} add --remote --host <host> --user <user> --path <basePath> [--port N] [--key [path] | --password]`,"","Save a repo for the new-task picker. With --remote, register an SSH-backed","project whose worktrees live on <host>; engine launch over SSH is pending.",""].join(`
5
5
  `);async function runAddSubcommand(rest){let arg=rest[0];if(arg==="--help"||arg==="-h"||arg==="help"){process.stdout.write(ADD_USAGE);return}if(arg==="--remote"){let{runAddRemote}=await import("./chunk-hepgmh0p.js");await runAddRemote(rest.slice(1));return}if(arg?.startsWith("-"))process.stderr.write(`${CLI_NAME} add: unknown flag "${arg}"
6
6
 
7
7
  ${ADD_USAGE}`),process.exit(2);let target=resolve(process.cwd(),expandTilde(arg&&arg.length>0?arg:".")),{addSavedRepo}=await import("./chunk-kd1cfcx1.js"),result=addSavedRepo(target);if(result.rejected)process.stderr.write(`${CLI_NAME} add: "${arg&&arg.length>0?arg:"."}" cannot be a project \u2014 ${rejectionReason(result.rejected)} (resolved to ${result.path}).
@@ -23,4 +23,4 @@ ${ADOPT_USAGE}
23
23
  pass a path glob to adopt, e.g. ${CLI_NAME} adopt '${repo}/*' --yes`);return}let matched=worktrees.filter(isMatch);if(matched.length===0){console.log(`
24
24
  no worktrees match glob ${JSON.stringify(glob)}`);return}if(!yes){console.log(`
25
25
  ${matched.length} worktree(s) match \u2014 re-run with --yes to adopt them`);return}await adoptWorktreesInto(orch,repo,matched,vendor),console.log(`done \u2014 adopted ${matched.length} worktree(s)`)}function printTopLevelUsage(out){out.write(`${topLevelUsage()}
26
- `)}var COMMANDS=new Map([["add",runAddSubcommand],["remove",runRemoveSubcommand],["adopt",runAdoptSubcommand],...DYNAMIC_COMMANDS]);async function main(){let[,,...rawArgs]=process.argv,[subcommand,...rest]=rawArgs;if(subcommand==="--version"||subcommand==="-v"||subcommand==="version"){let{CURRENT_VERSION:CURRENT_VERSION2}=await import("./chunk-4ayp6znk.js");console.log(`${CLI_NAME} ${CURRENT_VERSION2}`);return}if(subcommand==="--help"||subcommand==="-h"||subcommand==="help"){printTopLevelUsage(process.stdout);return}if(subcommand==="--skill"){let{runSkillSubcommand}=await import("./chunk-wh147k4t.js");await runSkillSubcommand(["print"]);return}if(subcommand==="--web"){let{runWebSubcommand}=await import("./chunk-63ktckgj.js");await runWebSubcommand(rest);return}let handler=subcommand!==void 0?COMMANDS.get(subcommand):void 0;if(handler){await handler(rest);return}if(subcommand!==void 0&&isPathLikeArg(subcommand)){let{runOpenDirectory}=await import("./chunk-1wnjq6ej.js");await runOpenDirectory(subcommand);return}if(subcommand!==void 0)console.error(`${CLI_NAME}: unknown command '${subcommand}'`),printTopLevelUsage(process.stderr),process.exit(2);let{publishRoveTerminalTitle}=await import("./chunk-g8wrdp7n.js");publishRoveTerminalTitle();let{launchTui}=await import("./chunk-37we82a4.js");await launchTui()}var cliDone=main().catch(async(err)=>{let{formatCliFailure}=await import("./chunk-s29k086j.js");console.error(formatCliFailure(err,{cliName:CLI_NAME,argv:process.argv,cwd:process.cwd(),env:process.env})),process.exit(1)});export{cliDone};
26
+ `)}var COMMANDS=new Map([["add",runAddSubcommand],["remove",runRemoveSubcommand],["adopt",runAdoptSubcommand],...DYNAMIC_COMMANDS]);async function main(){let[,,...rawArgs]=process.argv,[subcommand,...rest]=rawArgs;if(subcommand==="--version"||subcommand==="-v"||subcommand==="version"){let{CURRENT_VERSION:CURRENT_VERSION2}=await import("./chunk-b7bbnx1x.js");console.log(`${CLI_NAME} ${CURRENT_VERSION2}`);return}if(subcommand==="--help"||subcommand==="-h"||subcommand==="help"){printTopLevelUsage(process.stdout);return}if(subcommand==="--skill"){let{runSkillSubcommand}=await import("./chunk-wh147k4t.js");await runSkillSubcommand(["print"]);return}if(subcommand==="--web"){let{runWebSubcommand}=await import("./chunk-gd8gc37t.js");await runWebSubcommand(rest);return}let handler=subcommand!==void 0?COMMANDS.get(subcommand):void 0;if(handler){await handler(rest);return}if(subcommand!==void 0&&isPathLikeArg(subcommand)){let{runOpenDirectory}=await import("./chunk-wjz55sc3.js");await runOpenDirectory(subcommand);return}if(subcommand!==void 0)console.error(`${CLI_NAME}: unknown command '${subcommand}'`),printTopLevelUsage(process.stderr),process.exit(2);let{publishRoveTerminalTitle}=await import("./chunk-g8wrdp7n.js");publishRoveTerminalTitle();let{launchTui}=await import("./chunk-sfskhmzp.js");await launchTui()}var cliDone=main().catch(async(err)=>{let{formatCliFailure}=await import("./chunk-6b852k6c.js");console.error(formatCliFailure(err,{cliName:CLI_NAME,argv:process.argv,cwd:process.cwd(),env:process.env})),process.exit(1)});export{cliDone};
package/dist/cli/rove.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import{join as u}from"node:path";import{createInterface as a}from"node:readline/promises";import{pathToFileURL as tt}from"node:url";import{spawnSync as z}from"node:child_process";import{constants as O,accessSync as P}from"node:fs";import{homedir as V}from"node:os";import{basename as R,delimiter as I,dirname as U,join as x}from"node:path";import{fileURLToPath as C}from"node:url";var Z={$schema:"https://json.schemastore.org/package.json",name:"@sma1lboy/rove",version:"0.9.302-next.413",description:"Rove: all your coding agents, in one place. An agentic development environment (ADE) for your terminal: Claude Code, Codex, Copilot and more, side by side in isolated worktrees, handing tasks to each other.",keywords:["terminal","tui","cli","ade","agentic-development-environment","multiplexer","ai-agents","coding-agent","ai-coding-assistant","agentic-ai","parallel-agents","git-worktree","claude-code","codex","llm","developer-tools"],type:"module",packageManager:"bun@1.3.13",bin:{rove:"dist/cli/rove.js"},files:["dist/cli","dist/completions","dist/web","dist/web-ui","dist/skills","dist/voice","dist/*.wav","README.md","LICENSE"],publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sma1lboy/rove.git"},homepage:"https://rove.run",bugs:{url:"https://github.com/Sma1lboy/rove/issues"},engines:{bun:">=1.3.11"},scripts:{dev:"ROVE_DEV=1 bun --conditions=browser ./src/cli/rove.ts","dev:mock":"ROVE_DEV=1 bun ./src/tui-react/mock/host.tsx","dev:sandbox":"bun run scripts/dev-sandbox.ts run","dev:sandbox:reset":"bun run scripts/dev-sandbox.ts reset",build:"bun run scripts/build.ts","build:rubric":"bun run scripts/build-tier-rubric.ts",compile:"bun run scripts/compile.ts",typecheck:"tsc --noEmit","check-i18n":"bun run scripts/check-i18n.ts",test:"bun run test:fast && bun run test:socket","perf:golden":"bun scripts/perf-golden.ts","rove-bench":"bun --conditions=browser scripts/rove-bench.ts","pty:soak":"bun scripts/pty-soak.ts","test:fast":"vitest run --passWithNoTests --minWorkers=1 --maxWorkers=8","test:socket":"ROVE_INCLUDE_SOCKET=1 vitest run test/daemon --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:socket:coverage":"ROVE_INCLUDE_SOCKET=1 ROVE_COVERAGE_DAEMON=1 vitest run test/daemon --coverage --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:behavior":"ROVE_INCLUDE_BEHAVIOR=1 vitest run test/behavior --pool forks --minWorkers=1 --maxWorkers=1 --retry=2 --passWithNoTests","test:render":"bun scripts/render-track.mjs",coverage:"vitest run --coverage --passWithNoTests",bench:"vitest bench --run",lint:"biome check .",knip:"knip-bun",postinstall:"bun run scripts/check-preview-deps.ts || true",prepublishOnly:"bun run typecheck && bun run build","plugin-sandbox":"bun run scripts/plugin-sandbox.ts"},"//":"biome.json + bunfig.toml live at the monorepo root since they apply repo-wide; bun.lock also lives at root (workspace-shared).",dependencies:{"@ansi-tools/parser":"^1.0.15","@opentui/core":"0.8.4","@opentui/react":"0.8.4","@xterm/addon-serialize":"^0.14.0","@xterm/addon-unicode11":"^0.9.0","@xterm/headless":"^6.0.0",react:"^19.2.8","smol-toml":"^1.7.1",ws:"^8.21.3",yaml:"^2.9.0"},optionalDependencies:{"@sma1lboy/opentui-rove-darwin-arm64":"0.8.4-rove.1","@sma1lboy/opentui-rove-linux-x64":"0.8.4-rove.1","node-pty":"^1.1.0"},devDependencies:{"@biomejs/biome":"1.9.4","@sma1lboy/rove-daemon":"0.7.23","@tsconfig/bun":"1.0.11","@types/bun":"1.3.14","@types/node":"25.6.2","@types/react":"^19.2.0","@vitest/coverage-v8":"2.1.9",knip:"^6.14.2","react-devtools-core":"^7.0.1","rove-bridge":"0.0.62","rove-weixin":"0.0.62",typescript:"5.8.2",vitest:"2.1.9"},trustedDependencies:[]};var d="rove";var y=d;var o="ROVE_BUN",_="ROVE_NO_BUN_BOOTSTRAP",G="ROVE_SKIP_BUN_CHECK",k=Z.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0",H=(t)=>{try{return P(t,O.X_OK),!0}catch{return!1}},B=(t)=>t==="win32"?"bun.exe":"bun",f=(t)=>{let s=z(t,["--version"],{encoding:"utf8",timeout:5000});if(s.error||s.status!==0)return null;return s.stdout?.split(`
3
- `)[0]?.trim()??""};function v(t){return t.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function $(t,s=k){let c=v(t),b=v(s);if(!c||!b)return!0;let g=c.split(".").map(Number),i=b.split(".").map(Number);for(let r=0;r<3;r++){let W=g[r]??0,p=i[r]??0;if(W!==p)return W>p}return!0}function J(t=process.env){return t[G]==="1"}function h(t={}){let s=t.env??process.env,c=t.platform??process.platform,b=t.home??s.HOME??s.USERPROFILE??V(),g=B(c),i=[],r=s[o]?.trim();if(r)i.push(r);for(let Y of(s.PATH??s.Path??"").split(I))if(Y)i.push(x(Y,g));let W=s.BUN_INSTALL?.trim();if(W)i.push(x(W,"bin",g));if(b)i.push(x(b,".bun","bin",g));let p=t.launcherDir;if(p)i.push(x(p,"..","..","node_modules","bun","bin",g)),i.push(x(p,"..","..","..","bun","bin",g));return i}function N(t={}){let s=t.isExecutable??H;return h(t).find((c)=>s(c))??null}function Q(t={}){let s=t.isExecutable??H,c=t.bunVersionOf??f;if(J(t.env??process.env))return{bun:N(t),stale:null,unusable:null};let b=null,g=null;for(let i of h(t)){if(!s(i))continue;let r=c(i);if(r===null){g??=i;continue}if($(r))return{bun:i,stale:b,unusable:g};b??={path:i,version:v(r)??r}}return{bun:null,stale:b,unusable:g}}function q(t){return U(C(t))}function A(t){return R(C(t)).replace(/\.[cm]?[jt]s$/,"")}function n(t=process.platform){return t==="win32"?["powershell","-NoProfile","-Command","irm bun.sh/install.ps1 | iex"]:["bash","-c","curl -fsSL https://bun.sh/install | bash"]}function K(t=y,s=process.platform){let c=s==="win32"?'powershell -c "irm bun.sh/install.ps1 | iex"':"curl -fsSL https://bun.sh/install | bash";return[`${t}: Rove runs on the Bun runtime, and no Bun was found on this machine.`,"","Install Bun, then run this command again:",` ${c}`," npm install -g bun # any platform, if you already have npm","","Or install Bun and Rove together in one step:"," curl -fsSL https://rove.run/install.sh | sh","",`Already have Bun somewhere unusual? Point Rove at it: ${o}=/path/to/bun`,""].join(`
2
+ import{join as u}from"node:path";import{createInterface as a}from"node:readline/promises";import{pathToFileURL as tt}from"node:url";import{spawnSync as z}from"node:child_process";import{constants as O,accessSync as P}from"node:fs";import{homedir as V}from"node:os";import{basename as R,delimiter as I,dirname as U,join as x}from"node:path";import{fileURLToPath as C}from"node:url";var Z={$schema:"https://json.schemastore.org/package.json",name:"@sma1lboy/rove",version:"0.9.304",description:"Rove: all your coding agents, in one place. An agentic development environment (ADE) for your terminal: Claude Code, Codex, Copilot and more, side by side in isolated worktrees, handing tasks to each other.",keywords:["terminal","tui","cli","ade","agentic-development-environment","multiplexer","ai-agents","coding-agent","ai-coding-assistant","agentic-ai","parallel-agents","git-worktree","claude-code","codex","llm","developer-tools"],type:"module",packageManager:"bun@1.3.13",bin:{rove:"dist/cli/rove.js"},files:["dist/cli","dist/completions","dist/web","dist/web-ui","dist/skills","dist/voice","dist/*.wav","README.md","LICENSE"],publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sma1lboy/rove.git"},homepage:"https://rove.run",bugs:{url:"https://github.com/Sma1lboy/rove/issues"},engines:{bun:">=1.3.11"},scripts:{dev:"ROVE_DEV=1 bun --conditions=browser ./src/cli/rove.ts","dev:mock":"ROVE_DEV=1 bun ./src/tui-react/mock/host.tsx","dev:sandbox":"bun run scripts/dev-sandbox.ts run","dev:sandbox:reset":"bun run scripts/dev-sandbox.ts reset",build:"bun run scripts/build.ts","build:rubric":"bun run scripts/build-tier-rubric.ts",compile:"bun run scripts/compile.ts",typecheck:"tsc --noEmit","check-i18n":"bun run scripts/check-i18n.ts",test:"bun run test:fast && bun run test:socket","perf:golden":"bun scripts/perf-golden.ts","rove-bench":"bun --conditions=browser scripts/rove-bench.ts","pty:soak":"bun scripts/pty-soak.ts","test:fast":"vitest run --passWithNoTests --minWorkers=1 --maxWorkers=8","test:socket":"ROVE_INCLUDE_SOCKET=1 vitest run test/daemon --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:socket:coverage":"ROVE_INCLUDE_SOCKET=1 ROVE_COVERAGE_DAEMON=1 vitest run test/daemon --coverage --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:behavior":"ROVE_INCLUDE_BEHAVIOR=1 vitest run test/behavior --pool forks --minWorkers=1 --maxWorkers=1 --retry=2 --passWithNoTests","test:render":"bun scripts/render-track.mjs",coverage:"vitest run --coverage --passWithNoTests",bench:"vitest bench --run",lint:"biome check .",knip:"knip-bun",postinstall:"bun run scripts/check-preview-deps.ts || true",prepublishOnly:"bun run typecheck && bun run build","plugin-sandbox":"bun run scripts/plugin-sandbox.ts"},"//":"biome.json + bunfig.toml live at the monorepo root since they apply repo-wide; bun.lock also lives at root (workspace-shared).",dependencies:{"@ansi-tools/parser":"^1.0.15","@opentui/core":"0.8.4","@opentui/react":"0.8.4","@xterm/addon-serialize":"^0.14.0","@xterm/addon-unicode11":"^0.9.0","@xterm/headless":"^6.0.0",react:"^19.2.8","smol-toml":"^1.7.1",ws:"^8.21.3",yaml:"^2.9.0"},optionalDependencies:{"@sma1lboy/opentui-rove-darwin-arm64":"0.8.4-rove.1","@sma1lboy/opentui-rove-linux-x64":"0.8.4-rove.1","node-pty":"^1.1.0"},devDependencies:{"@biomejs/biome":"1.9.4","@sma1lboy/rove-daemon":"0.7.23","@tsconfig/bun":"1.0.11","@types/bun":"1.3.14","@types/node":"25.6.2","@types/react":"^19.2.0","@vitest/coverage-v8":"2.1.9",knip:"^6.14.2","react-devtools-core":"^7.0.1","rove-bridge":"0.0.65","rove-weixin":"0.0.65",typescript:"5.8.2",vitest:"2.1.9"},trustedDependencies:[]};var d="rove";var y=d;var o="ROVE_BUN",_="ROVE_NO_BUN_BOOTSTRAP",G="ROVE_SKIP_BUN_CHECK",k=Z.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0",H=(t)=>{try{return P(t,O.X_OK),!0}catch{return!1}},B=(t)=>t==="win32"?"bun.exe":"bun",f=(t)=>{let s=z(t,["--version"],{encoding:"utf8",timeout:5000});if(s.error||s.status!==0)return null;return s.stdout?.split(`
3
+ `)[0]?.trim()??""};function v(t){return t.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function $(t,s=k){let c=v(t),b=v(s);if(!c||!b)return!0;let g=c.split(".").map(Number),i=b.split(".").map(Number);for(let r=0;r<3;r++){let W=g[r]??0,e=i[r]??0;if(W!==e)return W>e}return!0}function J(t=process.env){return t[G]==="1"}function h(t={}){let s=t.env??process.env,c=t.platform??process.platform,b=t.home??s.HOME??s.USERPROFILE??V(),g=B(c),i=[],r=s[o]?.trim();if(r)i.push(r);for(let Y of(s.PATH??s.Path??"").split(I))if(Y)i.push(x(Y,g));let W=s.BUN_INSTALL?.trim();if(W)i.push(x(W,"bin",g));if(b)i.push(x(b,".bun","bin",g));let e=t.launcherDir;if(e)i.push(x(e,"..","..","node_modules","bun","bin",g)),i.push(x(e,"..","..","..","bun","bin",g));return i}function N(t={}){let s=t.isExecutable??H;return h(t).find((c)=>s(c))??null}function Q(t={}){let s=t.isExecutable??H,c=t.bunVersionOf??f;if(J(t.env??process.env))return{bun:N(t),stale:null,unusable:null};let b=null,g=null;for(let i of h(t)){if(!s(i))continue;let r=c(i);if(r===null){g??=i;continue}if($(r))return{bun:i,stale:b,unusable:g};b??={path:i,version:v(r)??r}}return{bun:null,stale:b,unusable:g}}function q(t){return U(C(t))}function A(t){return R(C(t)).replace(/\.[cm]?[jt]s$/,"")}function n(t=process.platform){return t==="win32"?["powershell","-NoProfile","-Command","irm bun.sh/install.ps1 | iex"]:["bash","-c","curl -fsSL https://bun.sh/install | bash"]}function K(t=y,s=process.platform){let c=s==="win32"?'powershell -c "irm bun.sh/install.ps1 | iex"':"curl -fsSL https://bun.sh/install | bash";return[`${t}: Rove runs on the Bun runtime, and no Bun was found on this machine.`,"","Install Bun, then run this command again:",` ${c}`," npm install -g bun # any platform, if you already have npm","","Or install Bun and Rove together in one step:"," curl -fsSL https://rove.run/install.sh | sh","",`Already have Bun somewhere unusual? Point Rove at it: ${o}=/path/to/bun`,""].join(`
4
4
  `)}function X(t,s,c=y){return[`${c}: this machine's Bun is too old for Rove — found ${s} at ${t}, need ${k} or newer.`,"","Rove's terminals are built on Bun's PTY API. An older Bun ignores it silently,","so every terminal and engine tab would open empty and stay empty.","","Upgrade Bun, then run this command again:"," bun upgrade # Bun installed itself (~/.bun)"," brew upgrade bun # Homebrew"," npm install -g bun@latest # npm-managed Bun","",`Have a newer Bun elsewhere? Point Rove at it: ${o}=/path/to/bun`,`Run on this one anyway (unsupported, terminals will be blank): ${G}=1`,""].join(`
5
5
  `)}function T(t,s=y){return[`${s}: the Bun at ${t} could not be run — \`${t} --version\` failed or never returned.`,"","Rove skipped it rather than starting through it, which would hang or fail","with a message from that binary instead of this one.","","Reinstall Bun, then run this command again:"," curl -fsSL https://bun.sh/install | bash","",`Have a working Bun elsewhere? Point Rove at it: ${o}=/path/to/bun`,""].join(`
6
6
  `)}function F(t=process.env,s=process.stdin,c=process.stdout){if(t[_]==="1")return!1;if(t.CI==="true"||t.CI==="1")return!1;return Boolean(s.isTTY&&c.isTTY)}function L(t={},s=z){let c=t.platform??process.platform,[b,...g]=n(c);if(!b)return null;let i=s(b,g,{stdio:"inherit"});if(i.error||i.status!==0)return null;return Q(t).bun}function l(t){if(typeof t.status==="number")return t.status;if(t.signal)return 128+(Object.hasOwn(j,t.signal)?j[t.signal]:0);return 1}var j={SIGINT:2,SIGQUIT:3,SIGKILL:9,SIGTERM:15};function m(t,s,c,b=z){let g=b(t,[s,...c],{stdio:"inherit"});if(g.error)return process.stderr.write(`rove: could not start Bun at ${t}: ${g.error.message}. Check that this path is executable, or reinstall Bun from https://bun.sh.
7
- `),1;return l(g)}var M=q(import.meta.url),e=A(import.meta.url),D=u(M,`${e}-run.js`);async function st(t){let s=a({input:process.stdin,output:process.stdout});try{let c=(await s.question(t)).trim().toLowerCase();return c===""||c==="y"||c==="yes"}finally{s.close()}}async function ct(){let t={launcherDir:M},s=Q(t);if(s.bun||!F())return s;let c=s.stale?`${e}: Bun ${s.stale.version} is too old for Rove (needs ${k}+). Install the latest Bun now? [Y/n] `:`${e}: Rove runs on the Bun runtime, and none is installed. Install Bun now? [Y/n] `;if(!await st(c))return s;return{bun:L(t),stale:s.stale,unusable:s.unusable}}var w=globalThis.Bun;if(w){let t=w.version;if(t&&!J()&&!$(t))process.stderr.write(X(process.execPath,t,e)),process.exit(1);await import(tt(D).href)}else{let{bun:t,stale:s,unusable:c}=await ct();if(!t){let b=s?X(s.path,s.version,e):c?T(c,e):K(e);process.stderr.write(b),process.exit(1)}process.exit(m(t,D,process.argv.slice(2)))}
7
+ `),1;return l(g)}var M=q(import.meta.url),p=A(import.meta.url),D=u(M,`${p}-run.js`);async function st(t){let s=a({input:process.stdin,output:process.stdout});try{let c=(await s.question(t)).trim().toLowerCase();return c===""||c==="y"||c==="yes"}finally{s.close()}}async function ct(){let t={launcherDir:M},s=Q(t);if(s.bun||!F())return s;let c=s.stale?`${p}: Bun ${s.stale.version} is too old for Rove (needs ${k}+). Install the latest Bun now? [Y/n] `:`${p}: Rove runs on the Bun runtime, and none is installed. Install Bun now? [Y/n] `;if(!await st(c))return s;return{bun:L(t),stale:s.stale,unusable:s.unusable}}var w=globalThis.Bun;if(w){let t=w.version;if(t&&!J()&&!$(t))process.stderr.write(X(process.execPath,t,p)),process.exit(1);await import(tt(D).href)}else{let{bun:t,stale:s,unusable:c}=await ct();if(!t){let b=s?X(s.path,s.version,p):c?T(c,p):K(p);process.stderr.write(b),process.exit(1)}process.exit(m(t,D,process.argv.slice(2)))}