@sma1lboy/rove 0.9.251 → 0.9.253
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.
- package/dist/cli/{chunk-9v568ape.js → chunk-02h0488p.js} +1 -1
- package/dist/cli/{chunk-r0etyq15.js → chunk-08ycv55d.js} +1 -1
- package/dist/cli/{chunk-mdnrrj16.js → chunk-0x7zcw52.js} +1 -1
- package/dist/cli/{chunk-gaf6n1ea.js → chunk-19h18xca.js} +1 -1
- package/dist/cli/{chunk-84bmcqyz.js → chunk-1mpheecn.js} +1 -1
- package/dist/cli/chunk-1qge84t7.js +3 -0
- package/dist/cli/{chunk-md094j05.js → chunk-278sc87n.js} +1 -1
- package/dist/cli/{chunk-jfnr89qj.js → chunk-2bmebw8q.js} +2 -2
- package/dist/cli/{chunk-ncrr0fa3.js → chunk-2nfz06mq.js} +1 -1
- package/dist/cli/chunk-34vpdm19.js +2 -0
- package/dist/cli/{chunk-qyfmfpjg.js → chunk-3dgghmjv.js} +1 -1
- package/dist/cli/chunk-3j1x55tc.js +2 -0
- package/dist/cli/{chunk-q854fweb.js → chunk-3jnw3ftt.js} +1 -1
- package/dist/cli/chunk-3r4ekafa.js +2 -0
- package/dist/cli/{chunk-sgegp9x9.js → chunk-4zhmbqt3.js} +1 -1
- package/dist/cli/{chunk-bvqwgrar.js → chunk-65tbvcjj.js} +1 -1
- package/dist/cli/{chunk-zcadc92x.js → chunk-67q0qw7z.js} +1 -1
- package/dist/cli/{chunk-e1xvz3sv.js → chunk-68gxqtse.js} +1 -1
- package/dist/cli/{chunk-kb3zvtkj.js → chunk-6e54q8g5.js} +1 -1
- package/dist/cli/chunk-6k424rbf.js +2 -0
- package/dist/cli/{chunk-ga5f2pyc.js → chunk-6r84zkcz.js} +1 -1
- package/dist/cli/{chunk-s5k3g5ra.js → chunk-6ygwq4w5.js} +1 -1
- package/dist/cli/{chunk-cp5jp5mq.js → chunk-75zg2k73.js} +1 -1
- package/dist/cli/{chunk-zcwgmz5p.js → chunk-76adkzyf.js} +1 -1
- package/dist/cli/{chunk-v312167r.js → chunk-7cd1epfw.js} +1 -1
- package/dist/cli/chunk-7ghwdjdc.js +3 -0
- package/dist/cli/{chunk-86chrjqr.js → chunk-7hkkjx6g.js} +1 -1
- package/dist/cli/{chunk-8sbbzs5g.js → chunk-814ktvx2.js} +1 -1
- package/dist/cli/chunk-8je3dmzq.js +2 -0
- package/dist/cli/{chunk-719avf77.js → chunk-8wze6dnr.js} +1 -1
- package/dist/cli/{chunk-8spmjwwz.js → chunk-97vsqj97.js} +1 -1
- package/dist/cli/chunk-9g7gneek.js +30 -0
- package/dist/cli/chunk-9jbcfrse.js +2 -0
- package/dist/cli/{chunk-m4wy9ja5.js → chunk-9r6x8mh4.js} +1 -1
- package/dist/cli/chunk-9vd6fv1k.js +3 -0
- package/dist/cli/{chunk-6ahc8w4p.js → chunk-9wkf17yd.js} +1 -1
- package/dist/cli/{chunk-7z9yfnjd.js → chunk-ad5gbdcf.js} +1 -1
- package/dist/cli/{chunk-vd8qqev9.js → chunk-admwmjjy.js} +1 -1
- package/dist/cli/{chunk-tntdcyra.js → chunk-afwh7as3.js} +1 -1
- package/dist/cli/{chunk-mq06xpqr.js → chunk-avdg2rrh.js} +1 -1
- package/dist/cli/chunk-avz72132.js +3 -0
- package/dist/cli/chunk-ax7wzcam.js +2 -0
- package/dist/cli/{chunk-zk5qkkb1.js → chunk-axxf5dkq.js} +1 -1
- package/dist/cli/{chunk-p2jeq98m.js → chunk-b18pnmsv.js} +1 -1
- package/dist/cli/chunk-b1mk33gy.js +2 -0
- package/dist/cli/{chunk-a7kq09ke.js → chunk-b31cte10.js} +1 -1
- package/dist/cli/{chunk-032g0ahy.js → chunk-b3j5s2jb.js} +1 -1
- package/dist/cli/{chunk-2apszxn2.js → chunk-b7xjhgts.js} +1 -1
- package/dist/cli/{chunk-jrdwedn2.js → chunk-bdvqjzwh.js} +1 -1
- package/dist/cli/chunk-bk4pfjs0.js +31 -0
- package/dist/cli/{chunk-fktvtdkb.js → chunk-bphs6am4.js} +1 -1
- package/dist/cli/chunk-bq0xsdqx.js +3 -0
- package/dist/cli/{chunk-n52x0ehz.js → chunk-c3d36ryd.js} +1 -1
- package/dist/cli/chunk-c4e149yb.js +2 -0
- package/dist/cli/chunk-cgy92ks5.js +2 -0
- package/dist/cli/chunk-cjxvb9vg.js +2 -0
- package/dist/cli/{chunk-y5dk90tw.js → chunk-dehnv06q.js} +1 -1
- package/dist/cli/{chunk-y1cb8pj5.js → chunk-dk0hffvd.js} +1 -1
- package/dist/cli/{chunk-q5bhq11t.js → chunk-dkb8nj75.js} +1 -1
- package/dist/cli/chunk-dx72asyw.js +2 -0
- package/dist/cli/{chunk-7vv6160d.js → chunk-epyw87gt.js} +1 -1
- package/dist/cli/{chunk-s2t9acrv.js → chunk-f6836h0n.js} +1 -1
- package/dist/cli/chunk-ffjwgbck.js +3 -0
- package/dist/cli/chunk-ft6ftksv.js +2 -0
- package/dist/cli/chunk-g3wdrhxk.js +11 -0
- package/dist/cli/{chunk-ra40m849.js → chunk-gb3qb83h.js} +1 -1
- package/dist/cli/chunk-ghyz3fd7.js +4 -0
- package/dist/cli/chunk-gt1vbz3f.js +5 -0
- package/dist/cli/{chunk-8ezc1ban.js → chunk-hbq7nqnp.js} +2 -2
- package/dist/cli/{chunk-2pen6b1t.js → chunk-hm7t9gkb.js} +1 -1
- package/dist/cli/{chunk-ayr5dpgc.js → chunk-hqzgejfj.js} +1 -1
- package/dist/cli/{chunk-e003wm6d.js → chunk-j26zqrnq.js} +2 -2
- package/dist/cli/{chunk-1tebqkdv.js → chunk-jbqpyp76.js} +1 -1
- package/dist/cli/{chunk-daw4mxq3.js → chunk-jk9b9ztf.js} +1 -1
- package/dist/cli/{chunk-w2sp489k.js → chunk-k3wzznqw.js} +1 -1
- package/dist/cli/{chunk-rhq87p4r.js → chunk-k8dm013e.js} +1 -1
- package/dist/cli/{chunk-6ms5chc3.js → chunk-ke3t032y.js} +1 -1
- package/dist/cli/{chunk-a7m7w6d1.js → chunk-m6qv5rsv.js} +1 -1
- package/dist/cli/{chunk-g5rr5fpn.js → chunk-mrtfvgb2.js} +1 -1
- package/dist/cli/{chunk-mnpewdhd.js → chunk-mt8vtz20.js} +2 -2
- package/dist/cli/{chunk-dgbcpkr2.js → chunk-mw35vd6g.js} +1 -1
- package/dist/cli/{chunk-g872swb8.js → chunk-mwm63vz3.js} +9 -9
- package/dist/cli/chunk-my20q579.js +3 -0
- package/dist/cli/chunk-n7dtvega.js +2 -0
- package/dist/cli/chunk-nhpadsbv.js +2 -0
- package/dist/cli/{chunk-6h0n4b5t.js → chunk-p8d9va1w.js} +2 -2
- package/dist/cli/{chunk-7j00hbq5.js → chunk-p98w5ffk.js} +1 -1
- package/dist/cli/chunk-parvvj8h.js +2 -0
- package/dist/cli/{chunk-vwg79maj.js → chunk-pcyatg4b.js} +1 -1
- package/dist/cli/{chunk-apfzdw7g.js → chunk-pkq8n3gs.js} +2 -2
- package/dist/cli/chunk-pwybgztt.js +2 -0
- package/dist/cli/chunk-q1e0qqmd.js +3 -0
- package/dist/cli/{chunk-5q08srg6.js → chunk-q349ydch.js} +1 -1
- package/dist/cli/chunk-qb6ktr8a.js +2 -0
- package/dist/cli/chunk-qc06psqb.js +3 -0
- package/dist/cli/{chunk-mw0ysrpd.js → chunk-qk5f6p3e.js} +1 -1
- package/dist/cli/chunk-r2pd9tv9.js +3 -0
- package/dist/cli/{chunk-h7y9v8k1.js → chunk-r4bn0mtb.js} +1 -1
- package/dist/cli/{chunk-5456ttpr.js → chunk-rm2wy5hf.js} +3 -3
- package/dist/cli/chunk-rpm771v5.js +15 -0
- package/dist/cli/{chunk-8ja7jrhc.js → chunk-s21t29qn.js} +1 -1
- package/dist/cli/{chunk-w4cpkhzj.js → chunk-sb2xg6py.js} +2 -2
- package/dist/cli/{chunk-963er0h4.js → chunk-sk3h2pzj.js} +3 -3
- package/dist/cli/{chunk-nsqsvgry.js → chunk-sncjkw3g.js} +3 -3
- package/dist/cli/chunk-t6j3pmpp.js +2 -0
- package/dist/cli/{chunk-crdyt04z.js → chunk-tmz0wzq8.js} +1 -1
- package/dist/cli/{chunk-w7yg0bbz.js → chunk-tq1hrd9n.js} +1 -1
- package/dist/cli/{chunk-x0rvg54z.js → chunk-v0jvt60f.js} +1 -1
- package/dist/cli/chunk-v8s0s21v.js +2 -0
- package/dist/cli/{chunk-ny12rama.js → chunk-v9avfsxq.js} +1 -1
- package/dist/cli/chunk-v9dcyjmj.js +9 -0
- package/dist/cli/chunk-vcq9hb2a.js +3 -0
- package/dist/cli/chunk-vx4e787s.js +3 -0
- package/dist/cli/{chunk-vgknea9y.js → chunk-wbtebbrv.js} +1 -1
- package/dist/cli/{chunk-meyfwc50.js → chunk-wkk63qck.js} +1 -1
- package/dist/cli/chunk-wq6pfbek.js +6 -0
- package/dist/cli/{chunk-nep425b6.js → chunk-x2c8f2qz.js} +1 -1
- package/dist/cli/{chunk-0y4qgnby.js → chunk-x5ymh8ev.js} +1 -1
- package/dist/cli/{chunk-568q390y.js → chunk-x7r75e3p.js} +2 -2
- package/dist/cli/chunk-xg6zg6kz.js +2 -0
- package/dist/cli/chunk-xgq5ycyn.js +2 -0
- package/dist/cli/{chunk-21ek142k.js → chunk-xkr7fwvb.js} +1 -1
- package/dist/cli/{chunk-mv0hp5cv.js → chunk-xmf4053m.js} +1 -1
- package/dist/cli/{chunk-gp991c3v.js → chunk-xpxxgzw9.js} +1 -1
- package/dist/cli/{chunk-s5a5dyab.js → chunk-y33j54yr.js} +2 -2
- package/dist/cli/{chunk-hq9tbzqa.js → chunk-y55zpren.js} +1 -1
- package/dist/cli/{chunk-4rx3nhvq.js → chunk-yjk0465m.js} +1 -1
- package/dist/cli/chunk-yq99x0r6.js +2 -0
- package/dist/cli/{chunk-qstjfseh.js → chunk-yshp8cmx.js} +1 -1
- package/dist/cli/chunk-z3zaa155.js +3 -0
- package/dist/cli/{chunk-npwzmmv9.js → chunk-z7zm8h1q.js} +2 -2
- package/dist/cli/chunk-zfjqy7hp.js +52 -0
- package/dist/cli/{chunk-mre9g9vq.js → chunk-zmw0v18d.js} +1 -1
- package/dist/cli/chunk-zy20hzvh.js +4 -0
- package/dist/cli/index.js +8 -8
- package/dist/cli/pty-host-node.mjs +3 -0
- package/dist/cli/rove-run.js +1 -1
- package/dist/cli/rove.js +1 -1
- package/dist/completions/rove.bash +2 -2
- package/dist/completions/rove.fish +2 -2
- package/dist/completions/rove.zsh +2 -2
- package/dist/skills/rove/SKILL.md +50 -2
- package/dist/skills/rove/references/api-flags.md +38 -7
- package/dist/web/assets/{index-DHlgMx7L.js → index-DmRZRttZ.js} +2 -2
- package/dist/web/index.html +1 -1
- package/package.json +3 -3
- package/dist/cli/chunk-1exaxwyv.js +0 -2
- package/dist/cli/chunk-28wjmb9f.js +0 -2
- package/dist/cli/chunk-2dpr8gps.js +0 -2
- package/dist/cli/chunk-2g2w5vvn.js +0 -2
- package/dist/cli/chunk-3msnqacf.js +0 -2
- package/dist/cli/chunk-5r71q63g.js +0 -2
- package/dist/cli/chunk-6f01fsje.js +0 -2
- package/dist/cli/chunk-6rrzq5et.js +0 -3
- package/dist/cli/chunk-76n3d9x3.js +0 -2
- package/dist/cli/chunk-88czbfqx.js +0 -3
- package/dist/cli/chunk-8s0mz115.js +0 -52
- package/dist/cli/chunk-964z8ccb.js +0 -3
- package/dist/cli/chunk-9h940gnr.js +0 -2
- package/dist/cli/chunk-cb1dg7nz.js +0 -2
- package/dist/cli/chunk-d99385f2.js +0 -22
- package/dist/cli/chunk-dcjxtwdb.js +0 -7
- package/dist/cli/chunk-e1x88j3k.js +0 -3
- package/dist/cli/chunk-f7rmd4zk.js +0 -6
- package/dist/cli/chunk-fsdh66fa.js +0 -2
- package/dist/cli/chunk-h9kzwj14.js +0 -2
- package/dist/cli/chunk-k9spgfmx.js +0 -3
- package/dist/cli/chunk-mf7fb92r.js +0 -2
- package/dist/cli/chunk-mnm9n2vr.js +0 -2
- package/dist/cli/chunk-nj53wrzz.js +0 -2
- package/dist/cli/chunk-nxe45n7k.js +0 -17
- package/dist/cli/chunk-pdvyfz3n.js +0 -3
- package/dist/cli/chunk-q3xt0mqt.js +0 -3
- package/dist/cli/chunk-q6qhk171.js +0 -2
- package/dist/cli/chunk-qft75bkm.js +0 -2
- package/dist/cli/chunk-qxzrdfh7.js +0 -11
- package/dist/cli/chunk-qzsahxd9.js +0 -3
- package/dist/cli/chunk-r2c5nbcq.js +0 -4
- package/dist/cli/chunk-regtterm.js +0 -9
- package/dist/cli/chunk-rf0jrh3q.js +0 -2
- package/dist/cli/chunk-rkgnrfga.js +0 -2
- package/dist/cli/chunk-rqpwy31f.js +0 -2
- package/dist/cli/chunk-rt4tg426.js +0 -4
- package/dist/cli/chunk-sqp33pwr.js +0 -2
- package/dist/cli/chunk-t33z2kdv.js +0 -3
- package/dist/cli/chunk-v6d6kvmk.js +0 -2
- package/dist/cli/chunk-x33sm4rp.js +0 -5
- package/dist/cli/chunk-yknavm97.js +0 -3
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{defaultFixRuntime}from"./chunk-ffjwgbck.js";import{discoverMachine,roveCommand}from"./chunk-v9dcyjmj.js";import{addMachine,defaultMachineAlias,duplicateAliasOf,getMachine,isValidMachineAlias,listMachines,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,removeMachine,sanitizeAlias,setMachineIdentity,sshTargetOf,updateMachine}from"./chunk-3jnw3ftt.js";import{shQuote}from"./chunk-b7xjhgts.js";import"./chunk-7kysxgbq.js";import{CURRENT_VERSION}from"./chunk-75zg2k73.js";import{loadStateFile}from"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import{homeDir}from"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-b3j5s2jb.js";import"./chunk-r2pd9tv9.js";import"./chunk-cmp64q4j.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{spawn}from"child_process";import{appendFileSync,chmodSync,existsSync,mkdirSync}from"fs";import{homedir}from"os";import{dirname}from"path";function parseSshG(stdout,home=homedir()){let values=new Map;for(let line of stdout.split(`
|
|
3
|
+
`)){let space=line.indexOf(" ");if(space>0)values.set(line.slice(0,space).toLowerCase(),line.slice(space+1).trim())}let hostname=values.get("hostname")??"",port=Number(values.get("port")??"22")||22,files=(key)=>(values.get(key)??"").split(/\s+/).filter((f)=>f&&f!=="none").map((f)=>f.startsWith("~/")?`${home}${f.slice(1)}`:f),alias=values.get("hostkeyalias"),proxy=(key)=>{let v=values.get(key);return v!==void 0&&v!=="none"};return{knownHostsName:alias&&alias!=="none"?alias:port===22?hostname:`[${hostname}]:${port}`,hostname,port,userKnownHosts:files("userknownhostsfile"),globalKnownHosts:files("globalknownhostsfile"),proxied:proxy("proxyjump")||proxy("proxycommand")}}async function checkHostKey(config){let target=sshTargetOf(config),resolved=await run(["ssh","-G",...config.port?["-p",String(config.port)]:[],target]);if(resolved.code!==0)return{state:"skipped",reason:"ssh -G failed"};let destination=parseSshG(resolved.stdout);if(!destination.hostname)return{state:"skipped",reason:"ssh -G named no host"};if(destination.proxied)return{state:"skipped",reason:"reached through a proxy"};for(let file of[...destination.userKnownHosts,...destination.globalKnownHosts]){if(!existsSync(file))continue;if((await run(["ssh-keygen","-F",destination.knownHostsName,"-f",file])).code===0)return{state:"known"}}let keys=(await run(["ssh-keyscan","-T","5","-p",String(destination.port),destination.hostname])).stdout.split(`
|
|
4
|
+
`).filter((line)=>line.trim()&&!line.startsWith("#"));if(keys.length===0)return{state:"skipped",reason:"the host offered no key"};let named=keys.map((line)=>line.replace(/^\S+/,destination.knownHostsName)),fingerprints=(await run(["ssh-keygen","-l","-f","-"],`${named.join(`
|
|
5
|
+
`)}
|
|
6
|
+
`)).stdout.split(`
|
|
7
|
+
`).filter((line)=>line.trim());return{state:"unknown",destination,fingerprints,trust(){let file=destination.userKnownHosts[0]??`${homedir()}/.ssh/known_hosts`;mkdirSync(dirname(file),{recursive:!0,mode:448}),appendFileSync(file,`${named.join(`
|
|
8
|
+
`)}
|
|
9
|
+
`,{mode:384});try{chmodSync(file,384)}catch{}}}}function run(argv,stdin){return new Promise((resolve)=>{let stdout="",child=spawn(argv[0]??"ssh",argv.slice(1),{stdio:[stdin===void 0?"ignore":"pipe","pipe","ignore"]}),timer=setTimeout(()=>child.kill("SIGKILL"),15000);if(child.stdout?.on("data",(chunk)=>{stdout+=chunk.toString()}),child.on("error",()=>{clearTimeout(timer),resolve({code:-1,stdout})}),child.on("close",(code)=>{clearTimeout(timer),resolve({code:code??-1,stdout})}),stdin!==void 0)child.stdin?.end(stdin)})}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync}from"fs";import{hostname}from"os";import{join}from"path";function hubKeyPath(home=homeDir()){return join(home,".rove","ssh","hub_ed25519")}var INSTALL_SCRIPT="curl -fsSL https://rove.run/install.sh | sh";function fixesFor(failure,alias,config,keyPath=hubKeyPath()){let target=sshTargetOf(config),ssh=(cmd,batch=!0)=>[...machineSshArgs(alias,config,{batch}),cmd];if(failure.code==="SSH_FAILED"&&failure.ssh==="auth-denied"&&config.auth.kind==="key"){let fixes=[];if(!existsSync2(keyPath))fixes.push({kind:"run",id:"hub-key",label:"Create a key this hub logs in with",shown:`ssh-keygen -t ed25519 -N "" -C ${hubKeyComment()} -f ${keyPath}`,why:"A dedicated key revokes this hub alone: delete its one line on the machine. No passphrase, so the hub can reconnect unattended; the file is owner-only.",argv:()=>{return mkdirSync2(join(keyPath,".."),{recursive:!0,mode:448}),["ssh-keygen","-q","-t","ed25519","-N","","-C",hubKeyComment(),"-f",keyPath]}});return fixes.push({kind:"run",id:"install-hub-key",label:`Authorize that key on ${target}`,shown:`ssh ${target} 'append ${keyPath}.pub to ~/.ssh/authorized_keys'`,why:"The one interactive step: ssh asks for your password on that machine once. Rove never sees it.",argv:()=>ssh(authorizeKeyScript(readFileSync(`${keyPath}.pub`,"utf8").trim()),!1),apply:(c)=>({...c,auth:{kind:"key",keyPath}})}),fixes}if(failure.code==="SSH_FAILED")return[];if(failure.code==="NO_ROVE")return[{kind:"install",id:"install-rove",label:`Install Rove on ${target}`,shown:`ssh ${target} '${INSTALL_SCRIPT}'`,why:"The official install script: sets up Bun if needed, then Rove, for that user only.",argv:()=>ssh(INSTALL_SCRIPT)}];if(failure.code==="BAD_STATUS"&&/too old/.test(failure.message))return[{kind:"install",id:"update-rove",label:`Update Rove on ${target}`,shown:`ssh ${target} 'rove update'`,why:"Its Rove predates machines; `rove update` moves it to the current release.",argv:()=>ssh(`${roveCommand(config.roveBin)} update`)}];return[{kind:"manual",id:"daemon-log",label:`Rove on ${target} would not start its daemon`,action:`ssh ${target} 'tail -n 40 ~/.rove/daemon.log'`}]}function hubKeyComment(){return`rove-hub@${hostname()}`}function authorizeKeyScript(publicKey){let line=shQuote(publicKey);return["umask 077","mkdir -p ~/.ssh","touch ~/.ssh/authorized_keys",`grep -qxF ${line} ~/.ssh/authorized_keys || printf '%s\\n' ${line} >> ~/.ssh/authorized_keys`].join(" && ")}async function establishMachine(alias,initial,rt){let discover=rt.discover??discoverMachine,config=initial,tried=new Set;for(;;){let found=await discover(alias,config);if(found.ok)return{ok:!0,found,config:found.roveBin?{...config,roveBin:found.roveBin}:config};rt.out(found.message);let fixes=fixesFor(found,alias,config),runnable=fixes.filter((f)=>f.kind!=="manual"&&!tried.has(f.id));for(let fix of fixes)if(fix.kind==="manual")rt.out(` \u2192 ${fix.action}`);if(runnable.length===0)return{ok:!1,failure:found};for(let fix of runnable){if(fix.kind==="manual")continue;if(tried.add(fix.id),rt.out(` ${fix.label}`),rt.out(` will run: ${fix.shown}`),rt.out(` ${fix.why}`),rt.planOnly)continue;if(rt.ask&&!await rt.confirm(" Run it? [y/N] "))return{ok:!1,failure:found};let code=await rt.exec(fix.argv());if(code!==0)return rt.out(` failed (exit ${code})`),{ok:!1,failure:found};if(fix.apply)config=fix.apply(config)}if(rt.planOnly)return rt.out(" Not a terminal: nothing was run. Re-run in a terminal, or pass --yes."),{ok:!1,failure:found}}}var CLI_NAME=ROVE_PRODUCT_NAME,MACHINE_USAGE=[`Usage: ${CLI_NAME} machine <add|remove|list> [options]`,"","Manage the other computers running Rove. Each one is reached over SSH;","its tasks appear in the sidebar under a row of its own.","","Commands:"," add <ssh-target> Register a machine (verifies it, offering fixes, before saving)"," doctor [alias] Re-check registered machines and offer the same fixes"," remove <alias> Forget a machine (nothing on it is touched)"," list Show registered machines","","Add options:"," --alias <name> Local name for the machine (default: the target you typed)"," --port <n> SSH port (default: whatever ssh_config says)"," --identity <file> SSH private key (default: ssh-agent / ssh_config)"," --yes Run every offered fix without asking (add, doctor)",""," <ssh-target> is [user@]host[:port] \u2014 usually just an ssh_config Host alias."," In a terminal, a key the machine rejects or a missing Rove is offered as"," a fix (a dedicated hub key, the install script) instead of an error.",""].join(`
|
|
10
|
+
`);function usageError(message){process.stderr.write(`${CLI_NAME} machine: ${message}
|
|
11
|
+
|
|
12
|
+
${MACHINE_USAGE}
|
|
13
|
+
`),process.exit(2)}function fail(message){process.stderr.write(`${CLI_NAME} machine: ${message}
|
|
14
|
+
`),process.exit(1)}function flagValue(argv,name){for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg===void 0)continue;if(arg.startsWith(`--${name}=`))return arg.slice(name.length+3);if(arg!==`--${name}`)continue;let value=argv[i+1];if(value===void 0||value.startsWith("--"))usageError(`--${name} needs a value`);return value}return}async function runMachineSubcommand(argv){let[verb,...rest]=argv;if(!verb||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${MACHINE_USAGE}
|
|
15
|
+
`);return}if(verb==="list")return list();if(verb==="add")return await add(rest);if(verb==="doctor")return await doctor(rest);if(verb==="remove")return remove(rest);usageError(`unknown verb "${verb}"`)}async function add(argv){let target=positionalOf(argv);if(!target)usageError("add needs an ssh target, e.g. `machine add narwhal`");let parsed=parseSshTarget(target);if(!parsed)usageError(`"${target}" is not a valid ssh target ([user@]host[:port])`);let portFlag=flagValue(argv,"port"),port=portFlag?Number(portFlag):parsed.port;if(port!==void 0&&(!Number.isInteger(port)||port<1||port>65535))usageError("--port must be 1-65535");let identity=flagValue(argv,"identity"),requested=flagValue(argv,"alias");if(requested&&!isValidMachineAlias(requested))usageError(`--alias must be letters/digits/._- and cannot be "local" (got "${requested}")`);let probeAlias=requested??sanitizeAlias(parsed.host),config={host:parsed.host,...parsed.user?{user:parsed.user}:{},...port?{port}:{},auth:identity?{kind:"key",keyPath:identity}:{kind:"key"}};await confirmHostKey(config),process.stderr.write(`${CLI_NAME} machine: contacting ${sshTargetOf(config)}\u2026
|
|
16
|
+
`);let established=await establishMachine(probeAlias,config,setupRuntime(argv));if(!established.ok)fail("nothing was saved");let{found,config:settled}=established,alias=requested??defaultMachineAlias({typedHost:parsed.host,typedUser:parsed.user,port,remoteHostname:found.status.hostname});if(!isValidMachineAlias(alias))fail(`could not derive a usable alias from "${found.status.hostname}" \u2014 pass --alias`);let identityTriple={hostname:found.status.hostname,homeDir:found.status.homeDir,daemonPid:found.status.daemonPid},duplicate=duplicateAliasOf(readMachines(loadStateFile()),alias,identityTriple),sockets={daemon:found.status.socketPath,pty:found.status.ptySocketPath};if(found.roveBin)process.stderr.write(`${CLI_NAME} machine: rove is not on ${alias}'s non-interactive PATH; using ${found.roveBin}
|
|
17
|
+
`);addMachine(alias,{...settled,identity:identityTriple,sockets}),setMachineIdentity(alias,identityTriple);let{ensureForwards}=await import("./chunk-xg6zg6kz.js"),up=await ensureForwards({alias,config:settled,remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(process.stdout.write(`${CLI_NAME} machine: ${alias} \u2192 ${sshTargetOf(settled)} (rove ${found.status.roveVersion||"?"} on ${found.status.hostname||"?"})
|
|
18
|
+
`),!up)process.stderr.write(`${CLI_NAME} machine: registered, but could not forward ${alias}'s socket yet \u2014 it will show as offline until the connection comes up
|
|
19
|
+
`);if(duplicate)process.stdout.write(`${CLI_NAME} machine: ${alias} is the same machine as ${duplicate} (hostname/homeDir/pid match) \u2014 the sidebar shows one row
|
|
20
|
+
`)}function setupRuntime(argv){let yes=argv.includes("--yes"),fixRuntime=defaultFixRuntime();return{confirm:fixRuntime.confirm,exec:fixRuntime.exec,out:(line)=>process.stderr.write(`${line}
|
|
21
|
+
`),ask:!yes,planOnly:!yes&&process.stdin.isTTY!==!0}}async function doctor(argv){let alias=positionalOf(argv),entries=listMachines().filter((m)=>!alias||m.alias===alias);if(alias&&entries.length===0)fail(`no machine named "${alias}" (see \`${CLI_NAME} machine list\`)`);if(entries.length===0){process.stdout.write(`No machines registered. Add one with \`${CLI_NAME} machine add <ssh-target>\`.
|
|
22
|
+
`);return}let rt=setupRuntime(argv),{ensureForwards}=await import("./chunk-xg6zg6kz.js"),failed=0;for(let{alias:name,...config}of entries){process.stderr.write(`${CLI_NAME} machine: checking ${name} (${sshTargetOf(config)})\u2026
|
|
23
|
+
`);let established=await establishMachine(name,config,rt);if(!established.ok){failed++,process.stdout.write(`${name} \u2717 ${established.failure.code}
|
|
24
|
+
`);continue}let{found,config:settled}=established,sockets={daemon:found.status.socketPath,pty:found.status.ptySocketPath};updateMachine(name,{...settled,sockets});let up=await ensureForwards({alias:name,config:settled,remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty}),version=found.status.roveVersion||"?",skew=version!==CURRENT_VERSION?` (this machine runs ${CURRENT_VERSION})`:"";if(process.stdout.write(`${name} ${up?"\u2713":"\u2717 socket not forwarded"} rove ${version}${skew} on ${found.status.hostname||"?"}
|
|
25
|
+
`),!up)failed++}if(failed>0)process.exitCode=1}async function confirmHostKey(config){let check=await checkHostKey(config);if(check.state!=="unknown")return;let write=(line)=>{process.stderr.write(`${line}
|
|
26
|
+
`)};write(`${CLI_NAME} machine: first connection to ${sshTargetOf(config)} (${check.destination.knownHostsName}). Its host key:`);for(let line of check.fingerprints)write(` ${line}`);if(process.stdin.isTTY!==!0){write(`${CLI_NAME} machine: not a terminal; trusting it on first use, as ssh would`);return}if(write("Compare it with the machine's own `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` if you can."),!await defaultFixRuntime().confirm("Trust this host key? [y/N] "))fail("host key not trusted; nothing was saved");check.trust()}function remove(argv){let alias=argv[0];if(!alias)usageError("remove needs an alias, e.g. `machine remove narwhal`");if(!getMachine(alias))fail(`no machine named "${alias}" (see \`${CLI_NAME} machine list\`)`);removeMachine(alias),process.stdout.write(`${CLI_NAME} machine: removed ${alias}. Nothing on that machine was changed \u2014 its daemon, tasks and worktrees are untouched.
|
|
27
|
+
`),process.stdout.write(`${CLI_NAME} machine: leftover sockets live in ${machineSocketDir(alias)}
|
|
28
|
+
`)}function list(){let machines=listMachines();if(machines.length===0){process.stdout.write(`No machines registered. Add one with \`${CLI_NAME} machine add <ssh-target>\`.
|
|
29
|
+
`);return}let all=readMachines(loadStateFile()),rows=machines.map((entry)=>{let duplicate=entry.identity?duplicateAliasOf(all,entry.alias,entry.identity):null;return[entry.alias,sshTargetOf(entry),entry.identity?.hostname??"\u2014",duplicate?`same machine as ${duplicate}`:""]}),widths=[0,1,2].map((i)=>Math.max(...rows.map((row)=>(row[i]??"").length),0));for(let row of rows){let line=[0,1,2].map((i)=>(row[i]??"").padEnd(widths[i]??0)).join(" ");process.stdout.write(`${line}${row[3]?` ${row[3]}`:""}
|
|
30
|
+
`.replace(/\s+$/,`
|
|
31
|
+
`))}}var SWITCHES=new Set(["--yes"]);function positionalOf(argv){for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg===void 0)continue;if(arg.startsWith("--")){if(!arg.includes("=")&&!SWITCHES.has(arg))i++;continue}return arg}return}export{runMachineSubcommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{describeRepoInitSources,missingDependenciesCoda,resolveEngineLaunchInit,resolveRepoInit}from"./chunk-
|
|
2
|
+
import{describeRepoInitSources,missingDependenciesCoda,resolveEngineLaunchInit,resolveRepoInit}from"./chunk-08ycv55d.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{resolveRepoInit,resolveEngineLaunchInit,missingDependenciesCoda,describeRepoInitSources};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{REPEAT_SEP,VerbArgs,defaultApiRuntime,findVerb,parseFlags,unknownVerbError,validateAgainstSpec}from"./chunk-rpm771v5.js";import{ensurePluginEnginesLoaded}from"./chunk-c3d36ryd.js";import{ApiError,cliCaller,splitDaemonCode}from"./chunk-x7r75e3p.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{ROVE_API_VERSION}from"./chunk-278sc87n.js";function toApiError(err){if(err instanceof ApiError)return err;let message=errorMessage(err);if(/task not found/i.test(message))return new ApiError(message,"TASK_NOT_FOUND",{hint:"that task id does not exist (deleted or mistyped) \u2014 list live tasks and retry with a real id",nextCommandArgs:["api","list"]});if(/unknown daemon request:/i.test(message))return versionSkewError(message);let coded=splitDaemonCode(message);if(coded)return new ApiError(coded.rest,coded.code);return new ApiError(message,"RPC_ERROR")}function versionSkewError(message){return new ApiError(message,"DAEMON_VERSION_SKEW",{hint:"the running daemon is a different build than this CLI, so it does not serve this verb \u2014 restart the daemon to pick up this build, then retry (if the verb is gone for good, `rove api schema` lists what this daemon actually serves)",nextCommandArgs:["daemon","restart"]})}function errorBody(err){return{message:err.message,code:err.code,...err.data}}function successEnvelope(result){return{apiVersion:ROVE_API_VERSION,ok:!0,result}}function errorEnvelope(err){return{apiVersion:ROVE_API_VERSION,ok:!1,error:errorBody(toApiError(err))}}function flagText(name,spec,value){let type=spec?.type;if(typeof value==="string")return value;if(spec?.repeatable&&Array.isArray(value)&&value.every((item)=>typeof item==="string"))return value.join(REPEAT_SEP);if(typeof value==="boolean"&&(type==="bool"||type===void 0))return String(value);if(typeof value==="number"&&(type==="int"||type==="uint"||type===void 0))return String(value);if(Array.isArray(value)&&(type==="csv"||type===void 0)){if(!value.every((item)=>typeof item==="string"&&!item.includes(",")))throw new ApiError(`param ${name} must be a list of strings without ","`,"BAD_FLAG");return value.join(",")}throw new ApiError(`param ${name} does not fit its ${type} flag`,"BAD_FLAG")}function paramsToFlags(verb,params){let flags=new Map;for(let[name,value]of Object.entries(params))flags.set(name,flagText(name,verb.flags.find((f)=>f.name===name),value));return flags}function booleanFlagsOf(verb){return new Set(verb.flags.filter((f)=>f.type==="bool").map((f)=>f.name))}function repeatableFlagsOf(verb){return new Set(verb.flags.filter((f)=>f.repeatable).map((f)=>f.name))}async function callVerb(verb,flags,deps){let caller=deps.caller??cliCaller();try{return await verb.handler({args:new VerbArgs(verb,flags,caller),caller,client:deps.client,runtime:deps.runtime??defaultApiRuntime})}catch(err){throw toApiError(err)}}async function runVerb(verbName,input,deps){ensurePluginEnginesLoaded();let verb=findVerb(verbName);if(!verb)throw unknownVerbError(verbName);if(verb.cliOnly&&!(deps.caller??cliCaller()).cli)throw new ApiError(`"${verbName}" streams over stdout/stdin, so only \`rove api\` can run it`,"CLI_ONLY_VERB",{hint:"run it as a CLI command on the machine whose daemon you are talking to"});let flags="argv"in input?parseFlags(input.argv,booleanFlagsOf(verb),repeatableFlagsOf(verb)).flags:paramsToFlags(verb,input.params);return validateAgainstSpec(verb,flags),callVerb(verb,flags,deps)}async function executeVerb(verbName,input,deps){try{return successEnvelope(await runVerb(verbName,input,deps))}catch(err){return errorEnvelope(err)}}
|
|
3
|
+
export{toApiError,errorBody,successEnvelope,errorEnvelope,paramsToFlags,booleanFlagsOf,repeatableFlagsOf,callVerb,runVerb,executeVerb};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{loadPluginRegistry,readPluginManifest}from"./chunk-
|
|
2
|
+
import{loadPluginRegistry,readPluginManifest}from"./chunk-admwmjjy.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-sb2xg6py.js";import{getCustomEngineIds}from"./chunk-xkr7fwvb.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
|
|
3
3
|
export{loadPluginEngines,reloadPluginEngines,ensurePluginEnginesLoaded,registeredEngineIds};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{NoopHookAdapter,activityHookAdapters,createEngineHookAdapter}from"./chunk-hm7t9gkb.js";import"./chunk-2tfnscxk.js";import"./chunk-sb2xg6py.js";import"./chunk-w7zv47mp.js";import"./chunk-2brn8e1y.js";import"./chunk-q1e0qqmd.js";import"./chunk-gt1vbz3f.js";import"./chunk-avz72132.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-y55zpren.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{createEngineHookAdapter,activityHookAdapters,NoopHookAdapter};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-rpm771v5.js";import"./chunk-2bmebw8q.js";import"./chunk-c3d36ryd.js";import"./chunk-hqzgejfj.js";import"./chunk-6ygwq4w5.js";import"./chunk-cbc1h345.js";import"./chunk-1mpheecn.js";import"./chunk-17e2tgyg.js";import"./chunk-mrtfvgb2.js";import"./chunk-4hestsjp.js";import"./chunk-41x1hrqe.js";import"./chunk-5mhvjytn.js";import"./chunk-b18pnmsv.js";import"./chunk-2bgmby1d.js";import"./chunk-admwmjjy.js";import"./chunk-ghyz3fd7.js";import"./chunk-atn06ncf.js";import"./chunk-tq1hrd9n.js";import"./chunk-qkehg2c1.js";import"./chunk-x2c8f2qz.js";import"./chunk-0x7zcw52.js";import"./chunk-02h0488p.js";import"./chunk-dehnv06q.js";import"./chunk-sak1tphp.js";import"./chunk-4250pw6r.js";import"./chunk-zmw0v18d.js";import"./chunk-rxqdw6s5.js";import"./chunk-67q0qw7z.js";import"./chunk-vjvkkrzc.js";import"./chunk-z3zaa155.js";import"./chunk-08ycv55d.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-s21t29qn.js";import"./chunk-hm7t9gkb.js";import"./chunk-2tfnscxk.js";import"./chunk-sb2xg6py.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-6xppe9bj.js";import"./chunk-b7xjhgts.js";import"./chunk-x7r75e3p.js";import"./chunk-zsfyj36g.js";import"./chunk-ad5gbdcf.js";import"./chunk-19h18xca.js";import"./chunk-p98w5ffk.js";import"./chunk-ag3txfg2.js";import"./chunk-2brn8e1y.js";import"./chunk-q1e0qqmd.js";import"./chunk-gt1vbz3f.js";import"./chunk-avz72132.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import"./chunk-75zg2k73.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-b3j5s2jb.js";import"./chunk-r2pd9tv9.js";import"./chunk-cmp64q4j.js";import"./chunk-y33j54yr.js";import"./chunk-278sc87n.js";import"./chunk-y55zpren.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Orchestrator}from"./chunk-pkq8n3gs.js";import"./chunk-tmz0wzq8.js";import"./chunk-68gxqtse.js";import"./chunk-f6836h0n.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-cbc1h345.js";import"./chunk-1mpheecn.js";import"./chunk-41x1hrqe.js";import"./chunk-dehnv06q.js";import"./chunk-sak1tphp.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-2tfnscxk.js";import"./chunk-m6qv5rsv.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-b7xjhgts.js";import"./chunk-2brn8e1y.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cmp64q4j.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{PLACEHOLDER_TASK_TITLE,Orchestrator};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{getKeychainPassword}from"./chunk-sak1tphp.js";import{LocalExecHost,RemoteExecHost}from"./chunk-b7xjhgts.js";import{getRemoteRepoConfig,getRemoteRepos,isRemoteRepoKey}from"./chunk-xkr7fwvb.js";import{remoteControlSocketPath}from"./chunk-prqeddy7.js";function remoteSpecFromConfig(config){let cfgAuth=config.auth,auth=cfgAuth.kind==="key"?{kind:"key",keyPath:cfgAuth.keyPath}:{kind:"password",getPassword:()=>getKeychainPassword(cfgAuth.keychainRef)};return{host:config.host,user:config.user,port:config.port,auth,controlPath:remoteControlSocketPath(config.host,config.user,config.port)}}var remoteHostCache=new Map;function cachedRemoteHost(config){let spec=remoteSpecFromConfig(config),cached=remoteHostCache.get(spec.controlPath);if(cached)return cached;let host=new RemoteExecHost(spec);return remoteHostCache.set(spec.controlPath,host),host}function execHostForRepo(repoKey){let config=getRemoteRepoConfig(repoKey);if(!config)return new LocalExecHost;return cachedRemoteHost(config)}function execHostForWorktreePath(worktreePath){for(let config of Object.values(getRemoteRepos()))if(worktreePath===config.basePath||worktreePath.startsWith(`${config.basePath}/`))return cachedRemoteHost(config);return new LocalExecHost}function remoteKeyForRepo(repo){return repo&&isRemoteRepoKey(repo)?repo:void 0}
|
|
3
3
|
export{execHostForRepo,execHostForWorktreePath,remoteKeyForRepo};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{loadPluginRegistry,pluginConfigDir,pluginDataDir,pluginLogPath,pluginRegistryPath,pluginStateDir,pluginsRootDir}from"./chunk-
|
|
2
|
+
import{loadPluginRegistry,pluginConfigDir,pluginDataDir,pluginLogPath,pluginRegistryPath,pluginStateDir,pluginsRootDir}from"./chunk-admwmjjy.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-yt15y085.js";import{chmodSync}from"fs";function tighten(path,mode){try{chmodSync(path,mode)}catch{}}function tightenPluginPermissions(id,homeDir){tighten(pluginDataDir(id,homeDir),OWNER_ONLY_DIR_MODE),tighten(pluginConfigDir(id,homeDir),OWNER_ONLY_DIR_MODE),tighten(pluginStateDir(id,homeDir),OWNER_ONLY_DIR_MODE),tighten(`${pluginConfigDir(id,homeDir)}/.env`,OWNER_ONLY_FILE_MODE),tighten(pluginLogPath(id,homeDir),OWNER_ONLY_FILE_MODE)}function tightenInstalledPluginPermissions(homeDir){tighten(pluginsRootDir(homeDir),OWNER_ONLY_DIR_MODE),tighten(pluginRegistryPath(homeDir),OWNER_ONLY_FILE_MODE);for(let entry of loadPluginRegistry(homeDir).plugins)tightenPluginPermissions(entry.id,homeDir)}
|
|
3
3
|
export{tightenPluginPermissions,tightenInstalledPluginPermissions};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{submitFeedback}from"./chunk-
|
|
2
|
+
import{submitFeedback}from"./chunk-tq1hrd9n.js";import"./chunk-75zg2k73.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";var CLI_NAME=ROVE_PRODUCT_NAME,FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--category <slug>]`,"","Create a GitHub Discussion in the Rove repository using the GitHub CLI.","","Requires:"," gh auth login","","Options:"," --title <text> Discussion title"," --body <text> Discussion body"," --body-file <path> Read the Discussion body from a file; use - for stdin"," --category <slug> Discussion category slug (default: feedback)"," -h, --help Print this help",""].join(`
|
|
3
3
|
`);function usageError(message){process.stderr.write(`${CLI_NAME} feedback: ${message}
|
|
4
4
|
|
|
5
5
|
${FEEDBACK_USAGE}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{readLastActiveTaskId,writeLastActiveTaskId}from"./chunk-f6836h0n.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{writeLastActiveTaskId,readLastActiveTaskId};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{writeOutdatedCache}from"./chunk-
|
|
2
|
+
import{writeOutdatedCache}from"./chunk-jbqpyp76.js";import{PluginCliError,installPlugin}from"./chunk-65tbvcjj.js";import{loadPluginRegistry,pluginCheckoutDir,pluginConfigDir,pluginDataDir,pluginStateDir,removePluginEntry,savePluginRegistry}from"./chunk-admwmjjy.js";import"./chunk-w7zv47mp.js";import"./chunk-75zg2k73.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-278sc87n.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{execFileSync}from"child_process";import{existsSync,mkdirSync,readdirSync,renameSync}from"fs";import{join}from"path";function gitOut(args,cwd){try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function checkEntry(entry){let repoSpec=entry.source.spec.split("/").slice(0,2).join("/"),localSha=gitOut(["rev-parse","HEAD"],pluginCheckoutDir(entry.id)),remote=gitOut(["ls-remote",`https://github.com/${repoSpec}.git`,"HEAD"]),remoteSha=remote?remote.split(/\s+/)[0]??null:null;return{id:entry.id,spec:entry.source.spec,version:entry.version,localSha,remoteSha,behind:Boolean(localSha&&remoteSha&&localSha!==remoteSha)}}function listOutdated(){let rows=loadPluginRegistry().plugins.filter((p)=>p.source.kind==="github").map(checkEntry);return writeOutdatedCache(rows.filter((r)=>r.behind).map((r)=>r.id)),rows}function printOutdated(){let rows=listOutdated();if(rows.length===0){console.log("no GitHub-installed plugins.");return}for(let r of rows){let status=r.behind?"update available":r.remoteSha===null?"remote unreachable":r.localSha===null?"local sha unreadable":"up to date";console.log(`${r.id} v${r.version} ${status}`)}}function migrateRenamedPlugin(oldId,newId){for(let dirOf of[pluginConfigDir,pluginStateDir]){let from=dirOf(oldId),to=dirOf(newId);if(!existsSync(from))continue;mkdirSync(to,{recursive:!0});for(let entry of readdirSync(from)){if(existsSync(join(to,entry)))continue;renameSync(join(from,entry),join(to,entry))}}savePluginRegistry(removePluginEntry(loadPluginRegistry(),oldId)),console.log(`renamed ${oldId} \u2192 ${newId}: settings and state carried over, old entry unregistered`),console.log(` leftover checkout (safe to remove): ${pluginDataDir(oldId)}`)}async function updatePlugins(ids,opts){let rows=listOutdated(),targets;if(opts.all){if(targets=rows.filter((r)=>r.behind),targets.length===0){console.log("all plugins up to date.");return}}else{if(ids.length===0)throw new PluginCliError("update takes plugin ids or --all");targets=ids.map((id)=>{let row=rows.find((r)=>r.id===id);if(!row)throw new PluginCliError(`\`${id}\` is not a GitHub-installed plugin; see \`${ROVE_PRODUCT_NAME} plugin list\``);return row})}for(let target of targets){if(!target.behind&&!ids.includes(target.id))continue;console.log(`updating ${target.id} (${target.spec})\u2026`);let installedId=await installPlugin(target.spec,{yes:opts.yes});if(installedId!==target.id)migrateRenamedPlugin(target.id,installedId)}listOutdated()}export{updatePlugins,printOutdated};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{loadStateFile,patchStateFile}from"./chunk-
|
|
2
|
+
import{loadStateFile,patchStateFile}from"./chunk-axxf5dkq.js";var LAST_ACTIVE_TASK_KEY="lastActive.taskId";function readLastActiveTaskId(){let value=loadStateFile()[LAST_ACTIVE_TASK_KEY];return typeof value==="string"&&value?value:null}function writeLastActiveTaskId(id){patchStateFile({[LAST_ACTIVE_TASK_KEY]:id})}
|
|
3
3
|
export{readLastActiveTaskId,writeLastActiveTaskId};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{t}from"./chunk-b3j5s2jb.js";import{createInterface}from"readline";function daemonRestartFix(cliName,reason){return{kind:"run",id:"daemon-restart",label:t(`doctor.fix.${reason}`),command:[cliName,"daemon","restart"],why:t("doctor.fix.daemonRestartWhy")}}function skillInstallFix(installCommand,stale){return{kind:"run",id:"skill-install",label:t(stale?"doctor.fix.skillStale":"doctor.fix.skillMissing"),command:installCommand.split(" "),why:t("doctor.fix.skillInstallWhy")}}function resetManualFix(cliName,reason){return{kind:"manual",id:`reset:${reason}`,label:t(`doctor.fix.${reason}`),action:`${cliName} reset`,why:t("doctor.fix.resetWhy")}}function killOrphansManualFix(cliName,count){return{kind:"manual",id:"kill-orphans",label:t("doctor.fix.orphans",{count}),action:`${cliName} doctor --kill-orphans`,why:t("doctor.fix.orphansWhy")}}function engineTabsManualFix(){return{kind:"manual",id:"engine-tabs",label:t("doctor.fix.engineTabs"),action:t("doctor.fix.engineTabsAction"),why:t("doctor.fix.engineTabsWhy")}}function reinstallManualFix(){return{kind:"manual",id:"reinstall",label:t("doctor.fix.staleInstall"),action:t("doctor.fix.staleInstallAction"),why:t("doctor.fix.staleInstallWhy")}}function spawnHelperFix(paths){return{kind:"run",id:"spawn-helper-chmod",label:t("doctor.fix.spawnHelper"),command:["chmod","755",...paths],why:t("doctor.fix.spawnHelperWhy")}}function humanOnlyFix(reason,vars){return{kind:"manual",id:reason,label:t(`doctor.fix.${reason}`),action:t(`doctor.fix.${reason}Action`,vars),why:t("doctor.fix.humanOnlyWhy")}}function noEngineFix(signedOut){return signedOut.length>0?humanOnlyFix("noEngineLogin",{list:signedOut.join(", ")}):humanOnlyFix("noEngine")}function dedupeFixes(fixes){let seen=new Set;return fixes.filter((fix)=>{if(seen.has(fix.id))return!1;return seen.add(fix.id),!0})}async function applyFixes(collected,rt){let fixes=dedupeFixes(collected);if(fixes.length===0){rt.out(""),rt.out(t("doctor.fix.none"));return}let runnable=fixes.filter((fix)=>fix.kind==="run");if(runnable.length>0){rt.out(""),rt.out(t("doctor.fix.header"));for(let fix of runnable){if(rt.out(` ${fix.label}`),rt.out(` ${t("doctor.fix.willRun",{command:fix.command.join(" ")})}`),rt.out(` ${fix.why}`),!rt.interactive)continue;if(!await rt.confirm(` ${t("doctor.fix.confirmPrompt")}`)){rt.out(` ${t("doctor.fix.skipped")}`);continue}let code=await rt.exec(fix.command);rt.out(code===0?` ${t("doctor.fix.done")}`:` ${t("doctor.fix.failed",{code})}`)}if(!rt.interactive)rt.out(` ${t("doctor.fix.nonInteractive")}`)}let manual=fixes.filter((fix)=>fix.kind==="manual");if(manual.length>0){rt.out(""),rt.out(t("doctor.fix.manualHeader"));for(let fix of manual)rt.out(` ${fix.label}`),rt.out(` \u2192 ${fix.action}`),rt.out(` ${fix.why}`)}}async function confirmTty(question){let readline=createInterface({input:process.stdin,output:process.stdout});try{let answer=await new Promise((resolve)=>readline.question(question,resolve));return answer.trim().toLowerCase()==="y"||answer.trim().toLowerCase()==="yes"}finally{readline.close()}}async function execInherited(command){try{return await Bun.spawn([...command],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}catch{return 127}}function defaultFixRuntime(){return{confirm:confirmTty,exec:execInherited,out:(line)=>console.log(line),interactive:process.stdin.isTTY===!0}}
|
|
3
|
+
export{daemonRestartFix,skillInstallFix,resetManualFix,killOrphansManualFix,engineTabsManualFix,reinstallManualFix,spawnHelperFix,humanOnlyFix,noEngineFix,applyFixes,defaultFixRuntime};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,tearDownTaskSessionAdapter}from"./chunk-97vsqj97.js";import{Orchestrator}from"./chunk-pkq8n3gs.js";import{GH_PR_VIEW_FIELDS,classifyGhFailure,mapGhPrView,nextPrPoll,samePrStatus}from"./chunk-tmz0wzq8.js";import{GitWorktreeManager,parseDirtyPaths}from"./chunk-68gxqtse.js";import"./chunk-f6836h0n.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{startChatChannels}from"./chunk-v9avfsxq.js";import{auditDeletionBranchKept,auditDeletionResidue,auditDeletionSalvaged,auditWorktreeResidue,auditWorktreeSalvaged,parseAheadBehind,startDaemonServer}from"./chunk-9g7gneek.js";import"./chunk-r3s2t9af.js";import"./chunk-a4hsqj1b.js";import"./chunk-dk0hffvd.js";import"./chunk-k67vbszb.js";import{preferredReleaseChannel}from"./chunk-avdg2rrh.js";import{TaskIndexStore}from"./chunk-r4bn0mtb.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-cbc1h345.js";import"./chunk-1mpheecn.js";import{affectsActivityState,isEngineActivityKind}from"./chunk-17e2tgyg.js";import"./chunk-4hestsjp.js";import"./chunk-41x1hrqe.js";import"./chunk-5mhvjytn.js";import"./chunk-b18pnmsv.js";import"./chunk-2bgmby1d.js";import"./chunk-admwmjjy.js";import"./chunk-atn06ncf.js";import"./chunk-qkehg2c1.js";import{autoStatusEnabled}from"./chunk-02h0488p.js";import{execHostForWorktreePath}from"./chunk-dehnv06q.js";import"./chunk-sak1tphp.js";import"./chunk-4250pw6r.js";import{GENERIC_PROTOCOL,engineDisplayName,engineProtocolKey,getEngineProtocol,protocolEntry,resolveCommandProtocol,roveApiInvocation,sessionProtocol}from"./chunk-zmw0v18d.js";import{installDaemonCrashHandlers,logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-67q0qw7z.js";import"./chunk-vjvkkrzc.js";import"./chunk-z3zaa155.js";import"./chunk-08ycv55d.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-s21t29qn.js";import{createEngineTurnDetector,engineEntry,engineTitleTurnHint,vendorsWithQuotaProbe}from"./chunk-hm7t9gkb.js";import{spawnCapture}from"./chunk-2tfnscxk.js";import{availableEngineIds}from"./chunk-sb2xg6py.js";import"./chunk-w7zv47mp.js";import"./chunk-k3wzznqw.js";import"./chunk-etfh8f4z.js";import"./chunk-m6qv5rsv.js";import{parsePorcelain}from"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import{DEFAULT_BASE_REF_CANDIDATES,readHeadSha,readRefSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import"./chunk-b7xjhgts.js";import{argvHasFlag,switchFlag}from"./chunk-zsfyj36g.js";import{connectOrStartDaemon,daemonSpawnReason}from"./chunk-ad5gbdcf.js";import{stopDaemonProcess}from"./chunk-19h18xca.js";import"./chunk-p98w5ffk.js";import"./chunk-2brn8e1y.js";import"./chunk-q1e0qqmd.js";import"./chunk-gt1vbz3f.js";import"./chunk-avz72132.js";import{DEFAULT_TASK_VENDOR,isTaskStatus}from"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import{migrateRoveDaemonStateLayout}from"./chunk-tdhk4dz8.js";import{SUBCOMMAND_VERBS}from"./chunk-1qge84t7.js";import{CURRENT_VERSION,checkLatestVersion}from"./chunk-75zg2k73.js";import{backfillSavedReposFromProjects,getCustomEngineIds,getPersistedString,getRemoteRepoConfig,getSavedRepos,setPersistedString}from"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import{releaseSync}from"./chunk-qk5f6p3e.js";import{isProcessAlive,readPidFile}from"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-r2pd9tv9.js";import"./chunk-cmp64q4j.js";import{RoveDaemonClient}from"./chunk-y33j54yr.js";import"./chunk-278sc87n.js";import{rotateLogIfNeeded}from"./chunk-y55zpren.js";import"./chunk-pn5ygqn6.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import{readRoveHomeDirEnv}from"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";function sniffProtocolFromTitle(title){let trimmed=title?.trim();if(!trimmed)return null;let owners=new Map;for(let vendor of BUILTIN_VENDORS)for(let glyph of engineEntry(vendor).terminalTitle?.statusPrefixes??[])owners.set(glyph,[...owners.get(glyph)??[],vendor]);for(let glyph of[...owners.keys()].sort((a,b)=>b.length-a.length)){if(!trimmed.startsWith(glyph))continue;if(trimmed.slice(glyph.length).trim().length===0)continue;let vendors=owners.get(glyph)??[];if(vendors.length===1)return vendors[0];return null}return null}function protocolUpgradeFromLiveSession(task,evidence){let command=task.command?.trim();if(!command)return null;if(task.vendor&&isBuiltinVendor(task.vendor))return null;if(resolveCommandProtocol(command)!==GENERIC_PROTOCOL)return null;let walk=evidence.walkVendor,vendor=walk!==null&&isBuiltinVendor(walk)?walk:sniffProtocolFromTitle(evidence.title);return vendor?{command,vendor}:null}function protocolWriteBackFromLiveSession(task,evidence,customEngineIds){let id=task.vendor?.trim();if(!id)return null;if(getEngineProtocol(id)!==void 0)return null;if(!customEngineIds.includes(id))return null;let walk=evidence.walkVendor;return walk!==null&&isBuiltinVendor(walk)?{id,protocol:walk}:null}async function latestTranscriptMtime(vendor,worktree){if(!worktree)return 0;return protocolEntry(vendor).history.latestTranscriptMtimeForWorktree(worktree)}async function maybeAutoStart(orch,taskId,enabled=autoStatusEnabled){if(!enabled())return"skipped";let task=orch.getTask(taskId);if(!task)return"skipped";if((task.kind??"task")==="main")return"skipped";if(task.status!=="backlog")return"skipped";return await orch.setStatus(taskId,"in_progress"),"moved"}var SYNC_TIMEOUT_MS=60000,SYNC_CONFLICT="SYNC_CONFLICT",SYNC_DIRTY="SYNC_WORKTREE_DIRTY";async function git(cwd,args,signal,write=!1){return spawnCapture("git",args,{cwd,env:write?process.env:readOnlyGitProcessEnv(),signal})}function parseConflictedPaths(stdout){return stdout.split(`
|
|
3
|
+
`).map((line)=>line.trim()).filter((line)=>line.length>0)}async function syncWorktreeWithBase(worktreePath,baseRef,signal){let status=await git(worktreePath,["status","--porcelain=v1"],signal);if(status.status!==0)throw Error("git status failed");let dirty=parseDirtyPaths(status.stdout);if(dirty.length>0)throw Error(`${SYNC_DIRTY}: ${dirty.join(", ")}`);let before=await git(worktreePath,["rev-parse","HEAD"],signal),merge=await git(worktreePath,["merge","--no-edit",baseRef],signal,!0);if(merge.status!==0){let conflicted=await git(worktreePath,["diff","--name-only","--diff-filter=U"],signal),paths=parseConflictedPaths(conflicted.stdout);if(paths.length>0)throw Error(`${SYNC_CONFLICT}: ${paths.join(", ")}`);let detail=merge.stderr?.trim();throw Error(detail?`git merge ${baseRef} failed \u2014 ${detail}`:`git merge ${baseRef} failed`)}let after=await git(worktreePath,["rev-parse","HEAD"],signal);return{baseRef,alreadyCurrent:before.status===0&&before.stdout.trim()===after.stdout.trim()}}import{readFileSync}from"fs";import{join}from"path";var BASE_REF_TTL_MS=300000,cache=new Map;async function git2(worktreePath,args,signal){return await spawnCapture("git",[...args],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal})}async function refExists(worktreePath,ref,signal){return(await git2(worktreePath,["rev-parse","--verify","--quiet",ref],signal)).status===0}async function sharesHistory(worktreePath,ref,signal){return(await git2(worktreePath,["merge-base",ref,"HEAD"],signal)).status===0}async function baseCheckoutBranchFromGit(worktreePath,signal){let out=await git2(worktreePath,["worktree","list","--porcelain"],signal);if(out.status!==0)return null;return(out.stdout.split(`
|
|
4
|
+
|
|
5
|
+
`,1)[0]??"").split(`
|
|
6
|
+
`).find((l)=>l.startsWith("branch "))?.slice(7).trim().replace(/^refs\/heads\//,"")||null}function readRefSymbolic(dirs,ref){for(let dir of[dirs.gitDir,dirs.commonDir])try{let target=readFileSync(join(dir,ref),"utf8").trim().match(/^ref:\s*(.+)$/)?.[1]?.trim();if(target)return target}catch{}return null}function ladderFromFiles(worktreePath){let dirs=resolveGitDirs(worktreePath);if(!dirs)return;let originHead=readRefSymbolic(dirs,"refs/remotes/origin/HEAD")?.replace(/^refs\/remotes\//,""),baseCheckout=readRefSymbolic({gitDir:dirs.commonDir,commonDir:dirs.commonDir},"HEAD")?.replace(/^refs\/heads\//,""),names=[],head=readHeadSha(dirs),parts=[`HEAD=${head}`];for(let guess of[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]]){if(names.includes(guess))continue;let sha=readRefSha(dirs,guess);if(sha===null)continue;names.push(guess),parts.push(`${guess}=${sha}`)}return{names,fingerprint:head===null?null:parts.join(",")}}async function ladderFromGit(worktreePath,signal){let head=await git2(worktreePath,["symbolic-ref","--short","refs/remotes/origin/HEAD"],signal),originHead=head.status===0?head.stdout.trim():"",baseCheckout=await baseCheckoutBranchFromGit(worktreePath,signal),names=[],candidates=[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]];for(let guess of candidates){if(names.includes(guess))continue;if(await refExists(worktreePath,guess,signal))names.push(guess)}return{names,fingerprint:null}}async function resolveBaseRefCached(worktreePath,recordedBaseRef,signal,now=Date.now()){if(recordedBaseRef){let dirs=resolveGitDirs(worktreePath);if(dirs&&readRefSha(dirs,recordedBaseRef)!==null)return recordedBaseRef;if(await refExists(worktreePath,recordedBaseRef,signal))return recordedBaseRef}let hit=cache.get(worktreePath);if(hit&&now-hit.at<BASE_REF_TTL_MS)return hit.ref;let ladder=ladderFromFiles(worktreePath)??await ladderFromGit(worktreePath,signal);if(hit&&ladder.fingerprint!==null&&hit.fingerprint===ladder.fingerprint)return cache.set(worktreePath,{...hit,at:now}),hit.ref;let ref=null;for(let candidate of ladder.names)if(await sharesHistory(worktreePath,candidate,signal)){ref=candidate;break}return cache.set(worktreePath,{ref,at:now,fingerprint:ladder.fingerprint}),ref}var cache2=new Map;function readShas(worktreePath,baseRef){let dirs=resolveGitDirs(worktreePath);if(!dirs)return null;let head=readHeadSha(dirs),base=readRefSha(dirs,baseRef);return head&&base?{head,base}:null}async function driftCached(worktreePath,baseRef,compute){let shas=readShas(worktreePath,baseRef),hit=shas?cache2.get(worktreePath):void 0;if(shas&&hit&&hit.head===shas.head&&hit.base===shas.base)return hit.value;let value=await compute();if(shas&&value!==null)cache2.set(worktreePath,{...shas,value});return value}import{statSync}from"fs";function judgeWorktree(signals,nowMs){if(signals.dirty)return{verdict:"active",reason:"dirty"};if(signals.prState==="open")return{verdict:"active",reason:"prOpen"};if(signals.prState==="merged")return{verdict:"merged",reason:"prMerged"};if(signals.aheadOfDefault===0)return{verdict:"merged",reason:"inMain"};if(signals.prState==="closed")return{verdict:"stale",reason:"prClosed"};if(signals.lastActivityMs>0&&nowMs-signals.lastActivityMs>1209600000)return{verdict:"stale",reason:"idle"};return{verdict:"fresh",reason:"fresh"}}function parseGhPrList(stdout){let entries;try{entries=JSON.parse(stdout)}catch{return null}if(!Array.isArray(entries))return null;let rank={open:3,merged:2,closed:1},map=new Map;for(let entry of entries){let branch=entry?.headRefName,rawState=entry?.state;if(typeof branch!=="string"||typeof rawState!=="string")continue;let state=rawState.toLowerCase();if(state!=="open"&&state!=="merged"&&state!=="closed")continue;let cur=map.get(branch);if(!cur||rank[state]>rank[cur])map.set(branch,state)}return map}var TIMEOUT_MS=4000,manager=new GitWorktreeManager;function createdAt(path){try{let stat=statSync(path);return stat.birthtimeMs||stat.mtimeMs}catch{return 0}}async function run(path,argv){return execHostForWorktreePath(path).run(argv,{cwd:path,signal:AbortSignal.timeout(TIMEOUT_MS)})}async function branchOnRemote(path,branch){try{let out=await run(path,["git","ls-remote","--exit-code","--heads","origin",branch]);return out.exitCode===0?!0:out.exitCode===2?!1:null}catch{return null}}async function defaultRef(repo){try{let out=await run(repo,["git","symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(out.exitCode===0&&out.stdout.trim())return out.stdout.trim()}catch{}for(let guess of["origin/main","origin/master"])try{if((await run(repo,["git","rev-parse","--verify","--quiet",guess])).exitCode===0)return guess}catch{}return null}async function prStates(repo){try{let origin=await run(repo,["git","remote","get-url","origin"]);if(origin.exitCode!==0||!origin.stdout.includes("github.com"))return null;let out=await run(repo,["gh","pr","list","--state","all","--limit","200","--json","headRefName,state"]);return out.exitCode===0?parseGhPrList(out.stdout):null}catch{return null}}async function ahead(path,ref){if(!ref)return null;try{let out=await run(path,["git","rev-list","--count",`${ref}..HEAD`]),value=Number.parseInt(out.stdout.trim(),10);return out.exitCode===0&&!Number.isNaN(value)?value:null}catch{return null}}async function listWorktreeProjectsAdapter(network){let repos=getSavedRepos().filter((repo)=>!getRemoteRepoConfig(repo)),now=Date.now();return Promise.all(repos.map(async(repo)=>{let[worktrees,states,ref]=await Promise.all([manager.listAll(repo),network?prStates(repo):null,defaultRef(repo)]),rows=await Promise.all(worktrees.map(async(worktree)=>{let[remote,aheadBy]=await Promise.all([network?branchOnRemote(worktree.path,worktree.branch):null,ahead(worktree.path,ref)]),judgement=judgeWorktree({dirty:worktree.dirty===!0,prState:states?.get(worktree.branch)??null,aheadOfDefault:aheadBy,lastActivityMs:worktree.lastActivityMs},now);return{...worktree,repo,createdAtMs:createdAt(worktree.path),branchOnRemote:remote,verdict:judgement.verdict,verdictReason:judgement.reason}}));return{repo,worktrees:rows}}))}async function listUnreadableWorktreesAdapter(repo){return manager.listUnreadableWorktrees(repo)}async function removeWorktreeAdapter(path,force){let residue=null;return await manager.remove(path,{force,onSalvage:(record)=>{if(record)auditWorktreeSalvaged(path,record.ref,record.commit,record.uncaptured)},onResidue:(r)=>{residue={path:r.path,reason:r.reason},auditWorktreeResidue(r.path,r.reason)}}),residue}function resolveProtocolUpgradeAndLearnPreset(task,evidence){let preset=protocolWriteBackFromLiveSession(task,evidence,getCustomEngineIds());if(preset)setPersistedString(engineProtocolKey(preset.id),preset.protocol);return protocolUpgradeFromLiveSession(task,evidence)}var daemonRuntime={currentVersion:CURRENT_VERSION,async invokeApi(verb,params,socketPath,route){let[{executeVerb,errorEnvelope},{REMOTE_CALLER},{RoveDaemonClient:RoveDaemonClient2}]=await Promise.all([import("./chunk-n7dtvega.js"),import("./chunk-ft6ftksv.js"),import("./chunk-yq99x0r6.js")]),client=new RoveDaemonClient2(socketPath);try{await client.connect();let{invokeRouted}=await import("./chunk-8je3dmzq.js");return await invokeRouted({verb,params,machine:route?.machine,forwarded:route?.forwarded,isLocalTask:(id)=>client.request("task.get",{taskId:id}).then(()=>!0,()=>!1),runHere:()=>executeVerb(verb,{params},{client,caller:REMOTE_CALLER})})}catch(err){return errorEnvelope(err)}finally{client.close()}},defaultTaskVendor:DEFAULT_TASK_VENDOR,placeholderTaskTitle:PLACEHOLDER_TASK_TITLE,isTaskStatus,isEngineActivityKind,affectsActivityState,async foregroundEngines(pids){let rows=parsePsSnapshot(await psSnapshot([...pids])),out=new Map;for(let pid of pids){let found=foregroundEngineIn(rows,pid);out.set(pid,found?{vendor:found.vendor,pid:found.pid}:null)}return out},titleTurnHint:(vendor,title)=>engineTitleTurnHint(sessionProtocol(vendor),title),resolveProtocolUpgrade:resolveProtocolUpgradeAndLearnPreset,readEngineTurns:async(vendor,transcriptPath)=>await protocolEntry(vendor).readTurns?.(transcriptPath)??[],checkLatestVersion:()=>checkLatestVersion({channel:preferredReleaseChannel()}),latestTranscriptMtime,deriveTitleFromSession,createEngineTurnDetector:(vendor)=>createEngineTurnDetector(sessionProtocol(vendor)),async runWorktreeStatus(worktreePath,signal,baseRef){let result=await spawnCapture("git",["status","--porcelain=v1"],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});if(result.status!==0)throw Error("git status failed");let counts=parsePorcelain(result.stdout),base=await resolveBaseRefCached(worktreePath,baseRef,signal);if(!base)return counts;let drift=await driftCached(worktreePath,base,async()=>{let out=await spawnCapture("git",["rev-list","--left-right","--count",`${base}...HEAD`],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});return out.status===0?parseAheadBehind(out.stdout):null});return drift===null?counts:{...counts,...drift}},maybeAutoStart:(orch,taskId)=>maybeAutoStart(orch,taskId),listWorktreeProjects:listWorktreeProjectsAdapter,listUnreadableWorktrees:listUnreadableWorktreesAdapter,removeWorktree:removeWorktreeAdapter,async syncWorktreeWithBase(worktreePath,recordedBaseRef){let controller=new AbortController,timer=setTimeout(()=>controller.abort(),SYNC_TIMEOUT_MS);try{let baseRef=await resolveBaseRefCached(worktreePath,recordedBaseRef,controller.signal);if(!baseRef)throw Error("no base ref resolves for this worktree");return await syncWorktreeWithBase(worktreePath,baseRef,controller.signal)}finally{clearTimeout(timer)}},availableEngineIds,engineDisplayName,roveApiInvocation,engineEntry,ensureTaskSession:ensureTaskSessionAdapter,startTaskSessionWithPrompt:startTaskSessionWithPromptAdapter,tearDownTaskSession:tearDownTaskSessionAdapter,async readEngineContextUsage(vendor,sessionId){let read=protocolEntry(vendor).history.readUsageSnapshot;if(!read)return null;let snapshot=await read(sessionId);if(snapshot?.context_tokens===void 0)return null;return{contextTokens:snapshot.context_tokens,...snapshot.context_window_tokens===void 0?{}:{contextWindowTokens:snapshot.context_window_tokens},...snapshot.context_tokens_approximate?{approximate:!0}:{},...snapshot.input_tokens===void 0?{}:{inputTokens:snapshot.input_tokens},...snapshot.output_tokens===void 0?{}:{outputTokens:snapshot.output_tokens},...snapshot.cache_read_input_tokens===void 0?{}:{cacheReadTokens:snapshot.cache_read_input_tokens},...snapshot.cache_creation_input_tokens===void 0?{}:{cacheCreationTokens:snapshot.cache_creation_input_tokens}}},quotaUsage:(vendor)=>engineEntry(vendor).quotaUsage?.()??Promise.resolve(null),vendorsWithQuotaProbe,deliverPromptToLiveEngine:deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailed:deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailed:deliverPromptToLiveEngineTabDetailedAdapter,getPersistedString,setPersistedString,getSavedRepos:()=>[...getSavedRepos()],prStatus:{viewFields:GH_PR_VIEW_FIELDS,mapView:(view,at)=>mapGhPrView(view,at),sameStatus:samePrStatus,nextPoll:(outcome,failures,now,config,random)=>nextPrPoll(outcome,failures,now,config,random),classify:classifyGhFailure}};import{homedir}from"os";async function createRoveCore(options={}){let homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),store=new TaskIndexStore({homeDir});await store.load();let worktrees=new GitWorktreeManager,orchestrator=new Orchestrator({store,worktrees,onSalvage:(taskId,salvage)=>auditDeletionSalvaged(String(taskId),salvage.ref,salvage.commit,store.get(taskId)?.repo,salvage.uncaptured),onWorktreeResidue:(taskId,residue)=>auditDeletionResidue(String(taskId),residue.path,residue.reason),onBranchKept:(taskId,kept)=>auditDeletionBranchKept(String(taskId),kept.branch,kept.reason),tearDownSession:(taskId)=>tearDownTaskSessionAdapter(String(taskId))}),backfilled=backfillSavedReposFromProjects(store.list().filter((task)=>task.kind==="main").map((task)=>task.repo));if(backfilled.length>0)console.error(`[rove] added ${backfilled.length} existing project(s) to the new-task picker`);return{homeDir,orchestrator,store,worktrees,async close(){orchestrator.dispose()}}}import{existsSync,readFileSync as readFileSync2,readdirSync,statSync as statSync2,unlinkSync}from"fs";import{join as join2}from"path";var TMP_MAX_AGE_MS=300000;function sweepIndexLeftovers(stateDir,now=Date.now()){let tmp=[],tmpBytes=0,entries;try{entries=readdirSync(stateDir)}catch{return{tmp,tmpBytes,lock:!1}}for(let name of entries){if(!name.startsWith("tasks.json.")||!name.endsWith(".tmp"))continue;let path=join2(stateDir,name);try{let stat=statSync2(path);if(now-stat.mtimeMs<TMP_MAX_AGE_MS)continue;unlinkSync(path),tmp.push(path),tmpBytes+=stat.size}catch{}}return{tmp,tmpBytes,lock:clearStaleLock(join2(stateDir,"tasks.json.lock"))}}function clearStaleLock(lockPath){let holder;try{holder=readFileSync2(lockPath,"utf8").trim()}catch{return!1}let pid=Number.parseInt(holder,10);if(Number.isFinite(pid)&&pid>0&&isProcessAlive(pid))return!1;return releaseSync(lockPath,holder),!existsSync(lockPath)}var CLI_NAME=ROVE_PRODUCT_NAME;function printDaemonUsage(out){out.write([`Usage: ${CLI_NAME} daemon <command>`,"","Commands:"," status Print the running daemon's status JSON (default)"," start Run the daemon in the foreground (this process becomes it)"," --resident: never idle-stop when the last TUI leaves (headless host)"," stop Ask the running daemon to shut down"," restart Stop the daemon (graceful \u2192 SIGTERM \u2192 SIGKILL) and respawn it",""].join(`
|
|
7
|
+
`))}async function runDaemonSubcommand(argv){let[command="status",...flags]=argv,socketPath=defaultDaemonSocketPath(),pidPath=defaultDaemonPidPath();if(command==="--help"||command==="-h"||command==="help"){printDaemonUsage(process.stdout);return}if(!SUBCOMMAND_VERBS.daemon.includes(command))process.stderr.write(`${CLI_NAME} daemon: unknown command "${command}"
|
|
8
|
+
|
|
9
|
+
`),printDaemonUsage(process.stderr),process.exit(2);let badFlag=flags.find((flag)=>!(command==="start"&&argvHasFlag([flag],"--resident"))&&!(command==="status"&&flag==="--json")),resident=switchFlag(flags,"--resident");if(badFlag!==void 0||resident===void 0)process.stderr.write(`${CLI_NAME} daemon ${command}: bad option "${badFlag??flags.join(" ")}"
|
|
10
|
+
|
|
11
|
+
`),printDaemonUsage(process.stderr),process.exit(2);if(command==="status"){let client=new RoveDaemonClient(socketPath);try{let status=await client.request("daemon.status");console.log(JSON.stringify(status,null,2))}catch{let pid=await readPidFile(pidPath);if(pid)console.log(`${CLI_NAME} daemon: no daemon socket at ${socketPath} (stale pidfile pid=${pid})`);else console.log(`${CLI_NAME} daemon: no daemon running at ${socketPath}`);process.exitCode=1}finally{client.close()}return}if(command==="stop"){let client=new RoveDaemonClient(socketPath);try{await client.request("daemon.stop"),console.log(`${CLI_NAME} daemon: stop requested`)}catch{console.log(`${CLI_NAME} daemon: no daemon running at ${socketPath}`)}finally{client.close()}return}if(command==="restart"){await stopDaemonProcess(socketPath,pidPath,{reason:"restart"}),(await connectOrStartDaemon("explicit-restart")).close(),console.log(`${CLI_NAME} daemon: restarted, listening on ${socketPath}`);return}rotateLogIfNeeded(defaultDaemonLogPath()),installDaemonCrashHandlers(),logDaemonInfo("boot",`daemon starting \u2014 ${daemonSpawnReason()} (pid ${process.pid}, v${CURRENT_VERSION})`);let core,channels=[],server=await startDaemonServer(async()=>{let migration=migrateRoveDaemonStateLayout();for(let warning of migration.warnings)console.error(`[rove] daemon state migration will retry: ${warning}`);core=await createRoveCore();let swept=sweepIndexLeftovers(core.store.stateDir);if(swept.lock||swept.tmp.length>0)console.error(`[rove] swept crash leftovers in ${core.store.stateDir}: ${swept.tmp.length} orphaned staging file(s) (${swept.tmpBytes} bytes)${swept.lock?", stale task-index lockfile":""}`);return core.orchestrator},{runtime:daemonRuntime,socketPath,pidPath,plugins:{binPath:resolvePluginBinPath()},keepAlive:()=>channels.some((channel)=>channel.keepAlive()),resident,onStop:async()=>{for(let channel of channels)channel.stop();await core?.close()}});console.log(`${CLI_NAME} daemon: listening on ${server.socketPath}`),channels=await startChatChannels({socketPath:server.socketPath,log:logDaemonInfo,keepAliveChanged:()=>server.reevaluateIdle()});let shutdown=async()=>{await server.close(),process.exit(0)};process.once("SIGINT",()=>void shutdown()),process.once("SIGTERM",()=>void shutdown())}export{runDaemonSubcommand};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{getGlobalDefaultVendor,getRepoLastActiveVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-
|
|
2
|
+
import{getGlobalDefaultVendor,getRepoLastActiveVendor,resolvePreferredVendor,setGlobalDefaultVendor,setRepoLastActiveVendor}from"./chunk-m6qv5rsv.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{setRepoLastActiveVendor,setGlobalDefaultVendor,resolvePreferredVendor,getRepoLastActiveVendor,getGlobalDefaultVendor};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import{getPersistedString}from"./chunk-xkr7fwvb.js";import{recordSpawn}from"./chunk-40dgv828.js";import{pathSyntax,pathWithin}from"./chunk-pn5ygqn6.js";var EDITOR_KINDS=["auto","vim","nvim","nano","emacs","custom"],AUTO_EDITOR_CANDIDATES=["nvim","vim","emacs","nano"],EDITOR_KIND_KEY="editor.kind",EDITOR_CUSTOM_KEY="editor.customCommand",DEFAULT_EDITOR_KIND="auto";function normalizeEditorKind(value){return EDITOR_KINDS.includes(value)?value:"auto"}var FILE_PLACEHOLDER="{file}",LINE_PLACEHOLDER="{line}",PLUS_LINE_EDITORS=new Set(["vi","vim","nvim","nano","emacs","emacsclient","micro","kak","mg","joe"]),SUFFIX_LINE_EDITORS=new Set(["hx","helix"]);function firstToken(cmd){return cmd.trim().split(/\s+/)[0]??""}function buildEditorCommand(kind,customCommand,absPath,envEditor,line){if(kind==="vim"||kind==="nvim"||kind==="nano"||kind==="emacs")return plainEditorCommand(kind,absPath,line);let tmpl=(customCommand.trim()||(envEditor??"").trim()).trim();if(!tmpl)return null;let bin=firstToken(tmpl);if(!bin)return null;let hasLine=tmpl.includes(LINE_PLACEHOLDER),autoPlusLine=!hasLine&&line!==void 0&&PLUS_LINE_EDITORS.has(bin.split("/").pop()??bin),target=hasLine||autoPlusLine?{arg:quoteShellArg(absPath),atLine:!0}:fileArg(bin,absPath,line),withLine=(autoPlusLine?`${bin} +${line}${tmpl.slice(bin.length)}`:tmpl).split(LINE_PLACEHOLDER).join(String(line??1)),command=withLine.includes(FILE_PLACEHOLDER)?withLine.split(FILE_PLACEHOLDER).join(target.arg):`${withLine} ${target.arg}`;return line===void 0?{bin,command}:{bin,command,atLine:target.atLine}}function plainEditorCommand(bin,absPath,line){let target=fileArg(bin,absPath,line),command=`${bin} ${target.arg}`;return line===void 0?{bin,command}:{bin,command,atLine:target.atLine}}function fileArg(bin,absPath,line){let file=quoteShellArg(absPath);if(line===void 0)return{arg:file,atLine:!1};let name=bin.split("/").pop()??bin;if(PLUS_LINE_EDITORS.has(name))return{arg:`+${line} ${file}`,atLine:!0};if(SUFFIX_LINE_EDITORS.has(name))return{arg:`${file}:${line}`,atLine:!0};return{arg:file,atLine:!1}}function buildNvimDiffCommand(bin,absPath,relPath){let file=quoteShellArg(absPath);return["f=$(mktemp 2>/dev/null)",`if [ -n "$f" ] && git show ${quoteShellArg(`HEAD:./${relPath}`)} > "$f" 2>/dev/null; then`,` ${bin} -d "$f" ${file} -c 'setlocal nomodifiable' -c 'wincmd l'; r=$?`,"else",` ${bin} ${file}; r=$?`,"fi",'rm -f "$f" 2>/dev/null; exit $r'].join(`
|
|
3
|
+
`)}function relativeToWorktree(worktree,absPath){return pathWithin(worktree,absPath)||null}async function resolveEditorCommand(absPath,line){let kind=normalizeEditorKind(getPersistedString(EDITOR_KIND_KEY)),custom=getPersistedString(EDITOR_CUSTOM_KEY)??"",env=(process.env.VISUAL??process.env.EDITOR??"").trim();if(kind!=="auto")return buildEditorCommand(kind,custom,absPath,env,line);if(env)return buildEditorCommand("custom","",absPath,env,line);for(let bin of AUTO_EDITOR_CANDIDATES)if(await binaryAvailable(bin))return plainEditorCommand(bin,absPath,line);return null}async function binaryAvailable(bin){try{return await Bun.spawn(["sh","-c",`command -v ${quoteShellArg(bin)} >/dev/null 2>&1`],{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).exited===0}catch{return!1}}async function fileHasDiff(worktree,relPath){try{return recordSpawn("tui.fileHasDiff",["git","diff","--quiet","HEAD","--",relPath],worktree),await Bun.spawn(["git","diff","--quiet","HEAD","--",relPath],{cwd:worktree,stdin:"ignore",stdout:"ignore",stderr:"ignore",env:readOnlyGitProcessEnv()}).exited===1}catch{return!1}}async function resolveEditorLaunch(worktree,absPath,line){let resolved=await resolveEditorCommand(absPath,line);if(!resolved)return null;if(!await binaryAvailable(resolved.bin))return null;let command=await maybeDiffCommand(resolved,worktree,absPath),label=editorWindowLabel(absPath);return resolved.atLine===void 0?{command,label}:{command,label,atLine:resolved.atLine}}async function maybeDiffCommand(resolved,worktree,absPath){let{bin,command}=resolved;if(bin!=="nvim"&&bin!=="vim")return command;if(command!==`${bin} ${quoteShellArg(absPath)}`)return command;let rel=relativeToWorktree(worktree,absPath);if(!rel)return command;if(!await fileHasDiff(worktree,rel))return command;return buildNvimDiffCommand(bin,absPath,rel)}function editorWindowLabel(absPath){let base=pathSyntax(absPath).basename(absPath).trim();return base.length>0?base:"edit"}
|
|
4
|
+
export{EDITOR_KINDS,EDITOR_KIND_KEY,EDITOR_CUSTOM_KEY,DEFAULT_EDITOR_KIND,normalizeEditorKind,resolveEditorCommand,binaryAvailable,resolveEditorLaunch};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{acquireWithRetry}from"./chunk-avz72132.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{isObject}from"./chunk-7ghwdjdc.js";import{acquireSync,release,releaseSync}from"./chunk-qk5f6p3e.js";import{roveStateDir}from"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{fileURLToPath}from"url";function roveCliInvocation(){let cliName=ROVE_PRODUCT_NAME;if(import.meta.url.endsWith(".js"))return[cliName];let entry=fileURLToPath(new URL(`./${"rove.ts"}`,import.meta.url));return[process.execPath,"--conditions=browser",entry]}function roveHookInvocation(){if(import.meta.url.endsWith(".js"))return[ROVE_PRODUCT_NAME];if(Bun.which(ROVE_PRODUCT_NAME))return[ROVE_PRODUCT_NAME];return roveCliInvocation()}var ROVE_HOOK_VERSION=1;function roveHookArgs(vendor){return["--engine",vendor,"--hook-version",String(ROVE_HOOK_VERSION)]}var GATED_TOOL_VERBS=new Set(["tool-pre","tool-post","tool-failed"]);function parseHookSettings(raw){if(raw===void 0)return{ok:!0,doc:{}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{ok:!1,reason:`not valid JSON (${err instanceof Error?err.message:String(err)})`}}if(!isObject(parsed))return{ok:!1,reason:"top level is not a JSON object"};if(parsed.hooks===void 0)return{ok:!0,doc:parsed};if(!isObject(parsed.hooks))return{ok:!1,reason:'"hooks" is not an object'};for(let[event,groups]of Object.entries(parsed.hooks)){if(!Array.isArray(groups))return{ok:!1,reason:`"hooks.${event}" is not an array`};let bad=groups.findIndex((group)=>!isObject(group)||!Array.isArray(group.hooks));if(bad>=0)return{ok:!1,reason:`"hooks.${event}[${bad}]" is not an object with a "hooks" array`}}return{ok:!0,doc:parsed}}var HOOK_WORD=String.raw`(?:'(?:[^']|'\\'')*'|"[^"$\x60\\]*"|[A-Za-z0-9_./:=+-]+)`,HOOK_ARGV=new RegExp(`^${HOOK_WORD}(?:[ ]+${HOOK_WORD})*$`),ROVE_HOOK_FLAGS={"--engine":/^[a-z][a-z0-9-]*$/,"--hook-version":/^\d+$/};function isRoveHook(hook,verbs){if(!isObject(hook)||typeof hook.command!=="string")return!1;if(hook.type!==void 0&&hook.type!=="command")return!1;let command=hook.command.replace(/^[ \t]+|[ \t]+$/g,"");if(HOOK_ARGV.exec(command)?.[0]!==command)return!1;let argv=(command.match(new RegExp(HOOK_WORD,"g"))??[]).map((word)=>{if(word.startsWith("'"))return word.slice(1,-1).replaceAll("'\\''","'");if(word.startsWith('"'))return word.slice(1,-1);return word}),executable=argv[0]?.split("/").at(-1),offset=1;if(executable==="bun"||executable==="node"){if(argv[offset]==="--conditions=browser")offset++;let entry=argv[offset]??"";if(!/(?:^|\/)(?:src|dist)\/cli\/(?:rove|rove)\.(?:ts|js)$/.test(entry))return!1;offset++}else if(executable!=="rove"&&executable!=="rove")return!1;if(argv[offset]!=="hook"||!verbs.includes(argv[offset+1]))return!1;let rest=argv.slice(offset+2);for(let i=0;i<rest.length;i+=2){let value=rest[i+1],pattern=ROVE_HOOK_FLAGS[rest[i]??""];if(!pattern||value===void 0||!pattern.test(value))return!1}return!0}function removeRoveHooks(groups,verbs){return groups.flatMap((group)=>{if(!isObject(group)||!Array.isArray(group.hooks))return[group];let kept=group.hooks.filter((hook)=>!isRoveHook(hook,verbs));if(kept.length===group.hooks.length)return[group];return kept.length>0?[{...group,hooks:kept}]:[]})}function hasRoveActivityHooks(current,eventMap){let verbs=eventMap.map((spec)=>spec.verb),hooks=isObject(current.hooks)?current.hooks:{};return Object.values(hooks).some((groups)=>Array.isArray(groups)&&groups.some((group)=>isObject(group)&&Array.isArray(group.hooks)&&group.hooks.some((hook)=>isRoveHook(hook,verbs))))}function hookCommandQuoting(platform=process.platform){return{bareSafe:!0,windows:platform==="win32"}}function buildActivityHooks(eventMap,inv=roveHookInvocation(),opts={}){let out={},quoting=hookCommandQuoting();for(let spec of eventMap){if(opts.buildFilter&&!opts.buildFilter(spec))continue;let{event,matcher,verb}=spec,group={hooks:[{type:"command",command:quoteShellArgv([...inv,"hook",verb,...opts.extraArgs??[]],quoting)}]};if(matcher)group.matcher=matcher;let previous=out[event],groups=Array.isArray(previous)?previous:[];groups.push(group),out[event]=groups}return out}function mergeActivityHooks(current,install,eventMap,inv=roveHookInvocation(),opts={}){let verbs=eventMap.map((spec)=>spec.verb),{hooks:rawHooks,...restSettings}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},built=install?buildActivityHooks(eventMap,inv,opts):{};for(let{event}of eventMap){let groups=hooks[event],prior=Array.isArray(groups)?groups:[],kept=removeRoveHooks(prior,verbs),additions=built[event];if(install&&Array.isArray(additions))kept.push(...additions);if(kept.length>0)hooks[event]=kept;else delete hooks[event]}return Object.keys(hooks).length>0?{...restSettings,hooks}:{...restSettings}}var RETIRED_WATCH_EVENT="PostToolUse";function removeWorktreeWatchHook(current){let{hooks:rawHooks,...restSettings}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},groups=hooks[RETIRED_WATCH_EVENT],prior=Array.isArray(groups)?groups:[],kept=removeRoveHooks(prior,["worktree-created"]);if(kept.length>0)hooks[RETIRED_WATCH_EVENT]=kept;else delete hooks[RETIRED_WATCH_EVENT];return Object.keys(hooks).length>0?{...restSettings,hooks}:{...restSettings}}import{constants,closeSync,fstatSync,openSync,readSync}from"fs";import{open}from"fs/promises";var MAX_ENGINE_FILE_BYTES=104857600,MAX_JSONL_LINE_CHARS=8388608,READ_CHUNK_BYTES=65536,READ_FLAGS=constants.O_RDONLY|constants.O_NONBLOCK;async function readTextFileIfRegular(p,maxBytes=MAX_ENGINE_FILE_BYTES){let file=await open(p,READ_FLAGS);try{let info=await file.stat();if(!info.isFile()||info.size>maxBytes)return null;let chunks=[],total=0;while(total<=maxBytes){let buffer=Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES,maxBytes+1-total)),{bytesRead}=await file.read(buffer);if(bytesRead===0)return Buffer.concat(chunks,total).toString("utf8");chunks.push(buffer.subarray(0,bytesRead)),total+=bytesRead}return null}finally{await file.close()}}async function readTextFileBounded(p,maxBytes=MAX_ENGINE_FILE_BYTES){return await readTextFileIfRegular(p,maxBytes)??""}async function readFirstLineBounded(p,maxBytes=MAX_JSONL_LINE_CHARS){let file=await open(p,READ_FLAGS);try{if(!(await file.stat()).isFile())return"";let chunks=[],total=0,start=0,nonblank=!1;while(total<=maxBytes){let buffer=Buffer.allocUnsafe(Math.min(16384,maxBytes+1-total)),{bytesRead}=await file.read(buffer);if(!bytesRead)return Buffer.concat(chunks,total).subarray(start).toString("utf8");chunks.push(buffer.subarray(0,bytesRead));let segment=0;for(let i=0;i<bytesRead;i++){if(buffer[i]!==10)continue;nonblank||=buffer.subarray(segment,i).toString("utf8").trim().length>0;let end=total+i;if(end>maxBytes)return"";if(nonblank)return Buffer.concat(chunks,total+bytesRead).subarray(start,end).toString("utf8");start=end+1,segment=i+1}nonblank||=buffer.subarray(segment,bytesRead).toString("utf8").trim().length>0,total+=bytesRead}return""}finally{await file.close()}}function readTextFileSyncBounded(p,maxBytes=MAX_ENGINE_FILE_BYTES){try{return readTextFileIfRegularSync(p,maxBytes)}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return null;throw err}}function readTextFileIfRegularSync(p,maxBytes=MAX_ENGINE_FILE_BYTES){let fd=openSync(p,READ_FLAGS);try{let info=fstatSync(fd);if(!info.isFile()||info.size>maxBytes)return null;let chunks=[],total=0;while(total<=maxBytes){let buffer=Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES,maxBytes+1-total)),bytesRead=readSync(fd,buffer);if(!bytesRead)return Buffer.concat(chunks,total).toString("utf8");chunks.push(buffer.subarray(0,bytesRead)),total+=bytesRead}return null}finally{closeSync(fd)}}function isJsonlLineWithinBound(line,maxChars=MAX_JSONL_LINE_CHARS){return line.length<=maxChars}import{createHash,randomBytes}from"crypto";import{mkdirSync,renameSync,unlinkSync,writeFileSync}from"fs";import{mkdir,rename,unlink,writeFile}from"fs/promises";import{dirname,join}from"path";var MAX_SHARED_CONFIG_BYTES=8388608;function stagingPath(file){return`${file}.rove-${process.pid}-${randomBytes(6).toString("hex")}.tmp`}function sharedConfigLockPath(file){return join(roveStateDir(),`shared-config-${createHash("sha256").update(file).digest("hex").slice(0,16)}.lock`)}var MAX_ATTEMPTS=5;function readSharedConfigSync(file){try{let raw=readTextFileIfRegularSync(file,MAX_SHARED_CONFIG_BYTES);if(raw===null)throw Error(`Refusing non-regular or oversized config: ${file}`);return raw}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return;throw err}}async function readRaw(file){try{let raw=await readTextFileIfRegular(file,MAX_SHARED_CONFIG_BYTES);if(raw===null)throw Error(`Refusing non-regular or oversized config: ${file}`);return raw}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return;throw err}}function updateSharedJsonSync(file,load,build){let lockPath=sharedConfigLockPath(file),lockToken=acquireSync(lockPath);try{for(let attempt=0;attempt<MAX_ATTEMPTS;attempt++){let before=readSharedConfigSync(file),doc=load(before);if(!doc)return;let text=build(doc);if(text===void 0)return;let tmp=stagingPath(file);try{if(mkdirSync(dirname(file),{recursive:!0}),writeFileSync(tmp,text,{mode:384,flag:"wx"}),readSharedConfigSync(file)===before){renameSync(tmp,file);return}}finally{try{unlinkSync(tmp)}catch{}}}throw Error(`gave up updating ${file} after ${MAX_ATTEMPTS} concurrent writes`)}finally{releaseSync(lockPath,lockToken)}}async function updateSharedJson(file,load,build){let lockPath=sharedConfigLockPath(file),lockToken=await acquireWithRetry(lockPath);try{for(let attempt=0;attempt<MAX_ATTEMPTS;attempt++){let before=await readRaw(file),doc=load(before);if(!doc)return;let text=build(doc);if(text===void 0)return;let tmp=stagingPath(file);try{if(await mkdir(dirname(file),{recursive:!0}),await writeFile(tmp,text,{mode:384,flag:"wx"}),await readRaw(file)===before){await rename(tmp,file);return}}finally{await unlink(tmp).catch(()=>{})}}throw Error(`gave up updating ${file} after ${MAX_ATTEMPTS} concurrent writes`)}finally{await release(lockPath,lockToken)}}async function editJsonSettings(settingsFilePath,transform,parse=parseHookSettings){let rejected;try{await updateSharedJson(settingsFilePath,(raw)=>{let parsed=parse(raw);if(parsed.ok)return parsed.doc;rejected=parsed.reason;return},(current)=>{let next=transform(current),json=JSON.stringify(next,null,2);return json===JSON.stringify(current,null,2)?void 0:`${json}
|
|
3
|
+
`})}catch(err){return{ok:!1,file:settingsFilePath,reason:err instanceof Error?err.message:String(err)}}if(rejected!==void 0)return{ok:!1,file:settingsFilePath,reason:rejected};return{ok:!0}}class JsonHookAdapter{supportsHooks(){return!0}activityDetailFromPayload(_kind,_payload){return}sessionFromPayload(_payload){return}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(_settingsFilePath){}gatedVerbs(){return GATED_TOOL_VERBS}async installActivityHooks(settingsFilePath,opts={}){let gated=this.gatedVerbs(),outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeActivityHooks(cur,!0,this.eventMap,void 0,{extraArgs:roveHookArgs(this.vendor),buildFilter:(spec)=>opts.toolEvents===!0||!gated.has(spec.verb)}));if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] ${this.vendor}: skipped ${outcome.file}: ${outcome.reason}
|
|
4
|
+
`);return outcome}async removeActivityHooks(settingsFilePath){await editJsonSettings(settingsFilePath,(cur)=>mergeActivityHooks(cur,!1,this.eventMap))}async removeWorktreeWatchHook(settingsFilePath){await editJsonSettings(settingsFilePath,removeWorktreeWatchHook)}hookConfigRefusal(raw){let parsed=parseHookSettings(raw);return parsed.ok?void 0:parsed.reason}}import{homedir}from"os";import path from"path";var VENDOR_HOMES={claude:{envVar:"CLAUDE_CONFIG_DIR",dirName:".claude"},codex:{envVar:"CODEX_HOME",dirName:".codex"},copilot:{envVar:"COPILOT_HOME",dirName:".copilot"},kimi:{envVar:"KIMI_CODE_HOME",dirName:".kimi-code"}},AGENT_DIR_VENDORS={pi:{envVar:"PI_CODING_AGENT_DIR",dirName:".pi"},omp:{envVar:"PI_CODING_AGENT_DIR",dirName:".omp"}},defaultVendorHomeDeps={env:(name)=>process.env[name],home:()=>homedir()};function vendorWriteHomeDeps(home){return home===void 0?defaultVendorHomeDeps:{env:()=>{return},home:()=>home}}function vendorConfigHome(vendor,deps=defaultVendorHomeDeps){let{envVar,dirName}=VENDOR_HOMES[vendor],override=deps.env(envVar)?.trim();if(override)return override;return path.join(deps.home(),dirName)}function vendorAgentDir(vendor,deps=defaultVendorHomeDeps){let{envVar,dirName}=AGENT_DIR_VENDORS[vendor],override=deps.env(envVar)?.trim();if(override)return override;return path.join(deps.home(),dirName,"agent")}function depsOf(env,home){return{env,home:()=>home}}function claudeGlobalConfigPath(env,home){let override=env("CLAUDE_CONFIG_DIR")?.trim();if(override)return path.join(override,".claude.json");return path.join(home,".claude.json")}function codexAuthPath(env,home){return path.join(vendorConfigHome("codex",depsOf(env,home)),"auth.json")}function copilotConfigPath(env,home){return path.join(vendorConfigHome("copilot",depsOf(env,home)),"config.json")}function bobHome(home=homedir()){return path.join(home,".bob")}function bobTrustPath(home){return path.join(bobHome(home),"trustedFolders.json")}function bobDbPath(home){return path.join(bobHome(home),"db","bob.db")}function bobAuthSecretsPath(home){return path.join(bobHome(home),"settings","auth-secrets.json")}function kimiCredentialsPath(env,home){return path.join(vendorConfigHome("kimi",depsOf(env,home)),"credentials","kimi-code.json")}
|
|
5
|
+
export{roveCliInvocation,roveHookInvocation,ROVE_HOOK_VERSION,roveHookArgs,GATED_TOOL_VERBS,isRoveHook,removeRoveHooks,hasRoveActivityHooks,hookCommandQuoting,readTextFileIfRegular,readTextFileBounded,readFirstLineBounded,readTextFileSyncBounded,isJsonlLineWithinBound,readSharedConfigSync,updateSharedJsonSync,editJsonSettings,JsonHookAdapter,vendorWriteHomeDeps,vendorConfigHome,vendorAgentDir,claudeGlobalConfigPath,codexAuthPath,copilotConfigPath,bobTrustPath,bobDbPath,bobAuthSecretsPath,kimiCredentialsPath};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{formatBytes}from"./chunk-my20q579.js";import{hookConfigIssues}from"./chunk-yjk0465m.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-gkdfct7t.js";import"./chunk-9g7gneek.js";import"./chunk-r3s2t9af.js";import"./chunk-a4hsqj1b.js";import"./chunk-dk0hffvd.js";import"./chunk-k67vbszb.js";import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-ffjwgbck.js";import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-mrtfvgb2.js";import"./chunk-4hestsjp.js";import"./chunk-41x1hrqe.js";import"./chunk-5mhvjytn.js";import"./chunk-b18pnmsv.js";import"./chunk-2bgmby1d.js";import"./chunk-admwmjjy.js";import"./chunk-atn06ncf.js";import{resolveNodeBinary}from"./chunk-zmw0v18d.js";import{formatDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-vjvkkrzc.js";import"./chunk-s21t29qn.js";import"./chunk-hm7t9gkb.js";import"./chunk-2tfnscxk.js";import"./chunk-sb2xg6py.js";import"./chunk-w7zv47mp.js";import"./chunk-k3wzznqw.js";import"./chunk-etfh8f4z.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-zsfyj36g.js";import{isStaleInstallError,resolveRoveSpawn}from"./chunk-ad5gbdcf.js";import"./chunk-19h18xca.js";import"./chunk-p98w5ffk.js";import"./chunk-2brn8e1y.js";import"./chunk-q1e0qqmd.js";import"./chunk-gt1vbz3f.js";import{readableLegacyIndexPath}from"./chunk-avz72132.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import{CURRENT_VERSION,package_default}from"./chunk-75zg2k73.js";import{roveSkillState,skillInstallCommand}from"./chunk-p8d9va1w.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import{readPidFile}from"./chunk-b31cte10.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import{t}from"./chunk-b3j5s2jb.js";import"./chunk-r2pd9tv9.js";import"./chunk-cmp64q4j.js";import{RoveDaemonClient,isForeignDaemonHome}from"./chunk-y33j54yr.js";import"./chunk-278sc87n.js";import"./chunk-y55zpren.js";import"./chunk-pn5ygqn6.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-z7zm8h1q.js";import{preRenameStateDir}from"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync as readFileSync2,statSync as statSync2}from"fs";import{join as join2}from"path";var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`ROVE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync}from"fs";var PTY_MARKER="ROVE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
|
|
3
3
|
`)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids,deps={}){let runProbe=deps.run??run,readEnviron=deps.readEnviron??((pid)=>readFileSync(`/proc/${pid}/environ`,"utf8")),marked=new Set;if(pids.length===0)return{marked,failed:null};if((deps.platform??process.platform)==="linux"){let refused=null;for(let pid of pids)try{if(readEnviron(pid).split("\x00").includes(PTY_MARKER))marked.add(pid)}catch(err){let code=err.code;if(code!=="ENOENT"&&code!=="ESRCH")refused??=`/proc/${pid}/environ: ${code??"unreadable"}`}return{marked,failed:refused}}let result=await runProbe(["ps","eww","-o","pid=,command=","-p",pids.join(",")]);if(result.code!==0)return{marked,failed:`ps eww exited ${result.code}`};let marker=new RegExp(`(^|\\s)${PTY_MARKER}(\\s|$)`);for(let line of result.stdout.split(`
|
|
4
4
|
`)){let pid=Number.parseInt(line.trim().split(/\s+/)[0]??"",10);if(Number.isFinite(pid)&&marker.test(line))marked.add(pid)}return{marked,failed:null}}async function ownPgid(runProbe){let result=await runProbe(["ps","-o","pgid=","-p",String(process.pid)]),pgid=Number.parseInt(result.stdout.trim(),10);return Number.isFinite(pgid)?pgid:-1}async function collectOrphans(liveSessionPids,deps={}){let runProbe=deps.run??run;if((deps.platform??process.platform)==="win32")return{orphans:[],error:null};let ps=await runProbe(["ps","-A","-o","pid=,ppid=,pgid=,etime=,rss=,command="]);if(ps.code!==0)return{orphans:[],error:`could not read the process table \u2014 ps exited ${ps.code}`};let rows=parsePsRows(ps.stdout),candidates=orphanCandidates(rows,await ownPgid(runProbe),liveSessionPids),{marked,failed}=await markedPids(candidates.map((row)=>row.pid),deps);if(failed)return{orphans:[],error:`could not read process environments \u2014 ${failed}`};return{orphans:candidates.filter((row)=>marked.has(row.pid)),error:null}}function formatMb(rssKb){return`${(rssKb/1024).toFixed(0)} MB`}function orphanDoctorLines(orphans,error,cliName,killing=!1){if(error)return[`orphans: \u2717 ${error}`];if(orphans.length===0)return["orphans: \u2713 none \u2014 no processes left behind by a dead PTY session"];let totalMb=orphans.reduce((sum,row)=>sum+row.rssKb,0)/1024,lines=[`orphans: \u26A0 ${orphans.length} process(es) outlived the PTY session that spawned them (${totalMb.toFixed(0)} MB RSS)`," each is reparented to init, carries Rove's PTY marker, and its process"," group leader is gone \u2014 no live task owns them"];for(let row of[...orphans].sort((a,b)=>b.rssKb-a.rssKb))lines.push(` pid ${row.pid} (group ${row.pgid}) up ${row.etime}, ${formatMb(row.rssKb)}: ${row.command.slice(0,90)}`);if(!killing)lines.push(` \u2192 \`${cliName} doctor --kill-orphans\` ends those process groups (SIGTERM, then SIGKILL)`," read the list first: something you backgrounded from a Rove terminal and then"," closed the tab on looks exactly like a leak, and doctor cannot tell them apart");return lines}var GROUP_EXIT_GRACE_MS=2000,GROUP_POLL_MS=100;function logOrphanKill(pgid,signal,logPath=defaultDaemonLogPath()){try{appendFileSync(logPath,formatDaemonInfo("doctor-kill-orphans",`${signal} process group ${pgid}`))}catch{}}function groupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(err){return err.code!=="ESRCH"}}async function killOrphanGroups(orphans){let groups=[...new Set(orphans.map((row)=>row.pgid))];for(let pgid of groups)try{process.kill(-pgid,"SIGTERM"),logOrphanKill(pgid,"SIGTERM")}catch{}let deadline=Date.now()+GROUP_EXIT_GRACE_MS,survivors=groups.filter(groupAlive);while(survivors.length>0&&Date.now()<deadline)await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),survivors=survivors.filter(groupAlive);for(let pgid of survivors)try{process.kill(-pgid,"SIGKILL"),logOrphanKill(pgid,"SIGKILL")}catch{}return await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),{groups,survivors:survivors.filter(groupAlive)}}function multiplexerLabel(env){if(env.TMUX)return"tmux";if(env.ZELLIJ)return"zellij";if(env.STY)return"screen";return"no"}function terminalEnvLines(env){let show=(v)=>v&&v.length>0?v:"(unset)",program=env.TERM_PROGRAM?`${env.TERM_PROGRAM}${env.TERM_PROGRAM_VERSION?` v${env.TERM_PROGRAM_VERSION}`:""}`:"(unset)";return[`terminal: TERM=${show(env.TERM)} TERM_PROGRAM=${program} COLORTERM=${show(env.COLORTERM)}`,` running inside a multiplexer: ${multiplexerLabel(env)}`]}function parseKittyProbeReply(data){let kitty=data.match(/\x1b\[\?(\d+)u/);if(kitty?.[1]!==void 0)return{kind:"supported",flags:Number.parseInt(kitty[1],10)};if(/\x1b\[\?[\d;]*c/.test(data))return{kind:"unsupported"};return null}function kittyProbeLine(result){switch(result.kind){case"supported":return` kitty keyboard protocol: \u2713 answered (flags=${result.flags})`;case"unsupported":return[" kitty keyboard protocol: \u2717 not supported \u2014 legacy key path"," (ctrl+h/ctrl+j arrive as C0 backspace/linefeed bytes; the"," split chords ctrl+\\ and ctrl+= cannot be encoded at all)"].join(`
|
|
5
5
|
`);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}async function probeGit(){try{let proc=Bun.spawn(["git","--version"],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),text=(await new Response(proc.stdout).text()).trim();if(await proc.exited===0&&text)return{line:`git: \u2713 ${text}`,found:!0}}catch{}return{line:"git: \u2717 not found on PATH",found:!1}}function binaryLabel(binary){return binary.found?`\u2713 ${binary.path}`:`\u2717 ${binary.error}`}async function probeEngines(){let statuses=await detectEngineStatuses(await probeableEngineIds()),lines=["engines:"];for(let status of statuses){let account=describeAccount(status.account),name=`${status.vendor.padEnd(7)} `;if(lines.push(` ${name}${binaryLabel(status.binary)}${status.binary.found?` \u2014 ${account}`:""}`),status.accountError)lines.push(` \u26A0 ${status.accountError}`)}let{usable,signedOut}=summarizeEngines(statuses);return{lines,anyUsable:usable.length>0,signedOut}}var CLI_NAME=ROVE_PRODUCT_NAME;function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new RoveDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(readFileSync2(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function tailFile(path,count){try{return readFileSync2(path,"utf8").split(`
|
|
@@ -14,5 +14,5 @@ Usage: ${CLI_NAME} doctor [--report] [--fix] [--kill-orphans]
|
|
|
14
14
|
`),process.exit(2);let{lines,fixes,orphans}=await collectDoctor();if(!fix&&fixes.length>0)lines.push("",t("doctor.fix.hint",{count:fixes.length,command:`${CLI_NAME} doctor --fix`}));if(console.log(lines.join(`
|
|
15
15
|
`)),kill)console.log(`
|
|
16
16
|
${(await sweepOrphans(orphans)).join(`
|
|
17
|
-
`)}`);if(fix)await applyFixes(fixes,defaultFixRuntime());if(report){let{writeReportBundle}=await import("./chunk-
|
|
17
|
+
`)}`);if(fix)await applyFixes(fixes,defaultFixRuntime());if(report){let{writeReportBundle}=await import("./chunk-wkk63qck.js"),path=writeReportBundle(lines);console.log(`
|
|
18
18
|
report written: ${path}`),console.log("attach this file to a bug report \u2014 it includes recent daemon + pty-host logs and env.")}}export{runDoctorSubcommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{spawnCapture}from"./chunk-2tfnscxk.js";import{CONTRIB_ENGINE_IDS,contribEngineEntry,detectBobAccount,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectKimiAccount,isContribEngine,mergeFlatHooks,parseFlatHooks,pluginEngineIds}from"./chunk-
|
|
2
|
+
import{spawnCapture}from"./chunk-2tfnscxk.js";import{CONTRIB_ENGINE_IDS,contribEngineEntry,detectBobAccount,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectKimiAccount,isContribEngine,mergeFlatHooks,parseFlatHooks,pluginEngineIds}from"./chunk-sb2xg6py.js";import{TomlError,parse}from"./chunk-w7zv47mp.js";import{ClaudeHookAdapter}from"./chunk-q1e0qqmd.js";import{GATED_TOOL_VERBS,JsonHookAdapter,ROVE_HOOK_VERSION,bobDbPath,bobTrustPath,claudeGlobalConfigPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isJsonlLineWithinBound,readFirstLineBounded,readSharedConfigSync,readTextFileBounded,readTextFileIfRegular,roveHookArgs,roveHookInvocation,updateSharedJsonSync,vendorAgentDir,vendorConfigHome,vendorWriteHomeDeps}from"./chunk-gt1vbz3f.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h2m7em1e.js";import{isObject}from"./chunk-7ghwdjdc.js";import{samePath}from"./chunk-pn5ygqn6.js";import{__require}from"./chunk-91sykzqq.js";var BOB_SCREEN_MANIFEST={rules:[{state:"blocked",any:["complete sign-in in your browser"]},{state:"blocked",all:["do you trust this folder?"],any:["trust folder","don't trust"]},{state:"blocked",all:["approve once"],any:["reject","always allow"]},{state:"working",any:["enter to steer","tab to queue"]},{state:"idle",lineRegex:["^\\s*\\w[\\w ]* mode( \xB7|\\s*$)"]}]};import{homedir}from"os";var TRUSTED="TRUST_FOLDER";function trustBobWorktree(worktreePath,home=homedir()){updateSharedJsonSync(bobTrustPath(home),(raw)=>{if(raw===void 0)return{};try{return JSON.parse(raw)}catch{return{}}},(doc)=>{let folders=doc.folders&&typeof doc.folders==="object"&&!Array.isArray(doc.folders)?doc.folders:{};if(folders[worktreePath]===TRUSTED)return;let merged={...doc,version:doc.version??1,folders:{...folders,[worktreePath]:TRUSTED}};return`${JSON.stringify(merged,null,2)}
|
|
3
3
|
`})}var claudeCapabilities={interruptSequence:"\x1B"},claudeIdentity={shortName:"Claude"};import{homedir as homedir2,userInfo}from"os";import path from"path";var OAUTH_USAGE_URL="https://api.anthropic.com/api/oauth/usage",OAUTH_BETA_HEADER="oauth-2025-04-20",OAUTH_USER_AGENT="claude-cli/2.1.198 (external, cli)",USAGE_TIMEOUT_MS=1e4,KEYCHAIN_SERVICE="Claude Code-credentials";function parseResetsAtMs(value){if(value==null)return null;let numeric=typeof value==="number"?value:/^\d+(?:\.\d+)?$/.test(value.trim())?Number(value):null;if(numeric!=null){if(!Number.isFinite(numeric)||numeric<=0)return null;return numeric<1000000000000?numeric*1000:numeric}let parsed=Date.parse(String(value));return Number.isNaN(parsed)?null:parsed}var clampPercent=(value)=>Math.min(100,Math.max(0,Math.round(value)));function windowLabel(kind,scopeModel){if(kind==="weekly_scoped"&&scopeModel)return scopeModel;return kind.startsWith("weekly")||kind.startsWith("seven_day")?"7d":"5h"}function usageFromClaudePayload(payload,capturedAt){let windows=[];if(payload.limits?.length)for(let limit of payload.limits){if(typeof limit.kind!=="string"||typeof limit.percent!=="number")continue;windows.push({kind:limit.kind,label:windowLabel(limit.kind,limit.scope?.model?.display_name),percent:clampPercent(limit.percent),resetsAt:parseResetsAtMs(limit.resets_at)})}else{if(typeof payload.five_hour?.utilization==="number")windows.push({kind:"session",label:"5h",percent:clampPercent(payload.five_hour.utilization),resetsAt:parseResetsAtMs(payload.five_hour.resets_at)});if(typeof payload.seven_day?.utilization==="number")windows.push({kind:"weekly_all",label:"7d",percent:clampPercent(payload.seven_day.utilization),resetsAt:parseResetsAtMs(payload.seven_day.resets_at)})}return{windows,capturedAt}}function parseCredentials(raw){try{let oauth=JSON.parse(raw)?.claudeAiOauth;if(!oauth||typeof oauth.accessToken!=="string"||!oauth.accessToken)return null;return{accessToken:oauth.accessToken,...typeof oauth.expiresAt==="number"&&Number.isFinite(oauth.expiresAt)?{expiresAt:oauth.expiresAt}:{}}}catch{return null}}var isFresh=(c)=>c.expiresAt===void 0||c.expiresAt>Date.now();async function readFileCredentials(dir){try{return parseCredentials(await readTextFileBounded(path.join(dir,".credentials.json")))}catch{return null}}async function readKeychainCredentials(){if(process.platform!=="darwin")return null;let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),3000);try{let result=await spawnCapture("security",["find-generic-password","-a",userInfo().username,"-w","-s",KEYCHAIN_SERVICE],{cwd:homedir2(),signal:controller.signal});return result.status===0?parseCredentials(result.stdout.trim()):null}finally{clearTimeout(timeout)}}async function readAccessToken(){let configDir=process.env.CLAUDE_CONFIG_DIR?.trim();if(configDir){let fromFile=await readFileCredentials(configDir);return fromFile&&isFresh(fromFile)?fromFile.accessToken:null}return[await readKeychainCredentials(),await readFileCredentials(vendorConfigHome("claude"))].find((c)=>c!=null&&isFresh(c))?.accessToken??null}async function fetchClaudeQuotaUsage(now=Date.now){let token=await readAccessToken().catch(()=>null);if(!token)return null;let controller=new AbortController,timeout=setTimeout(()=>controller.abort(),USAGE_TIMEOUT_MS);try{let response=await fetch(OAUTH_USAGE_URL,{headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json","User-Agent":OAUTH_USER_AGENT,"anthropic-beta":OAUTH_BETA_HEADER},signal:controller.signal});if(!response.ok)return null;return usageFromClaudePayload(await response.json(),now())}catch{return null}finally{clearTimeout(timeout)}}function trustClaudeWorktree(worktreePath,home){let deps=vendorWriteHomeDeps(home);updateSharedJsonSync(claudeGlobalConfigPath(deps.env,deps.home()),(raw)=>{if(raw===void 0)return{};let doc=JSON.parse(raw);if(!isObject(doc))throw Error("Claude trust config must be a JSON object");return doc},(doc)=>{if(doc.projects!==void 0&&!isObject(doc.projects))throw Error("Claude trust projects must be an object");let projects={...doc.projects},existing=Object.hasOwn(projects,worktreePath)?projects[worktreePath]:{};if(!isObject(existing))throw Error("Claude trust project must be an object");if(existing.hasTrustDialogAccepted===!0)return;return projects[worktreePath]={...existing,hasTrustDialogAccepted:!0,hasCompletedProjectOnboarding:!0},JSON.stringify({...doc,projects},null,2)})}function isSyntheticClaudeRecord(record){return record.isMeta===!0||record.isCompactSummary===!0}function isClaudeCommandBreadcrumb(blocks){if(blocks.length===0)return!1;for(let b of blocks){if(b.type!=="text")return!1;let t=b.text.trim();if(!t.startsWith("<command-name>")&&!t.startsWith("<command-message>")&&!t.startsWith("<local-command"))return!1}return!0}function opensTurn(content){if(typeof content==="string")return content.trim().length>0;if(!Array.isArray(content))return!1;return content.some((b)=>!isObject(b)||b.type!=="tool_result")}function num(v){return typeof v==="number"&&Number.isFinite(v)?v:0}function readUsage(v){if(!isObject(v))return;return{input_tokens:num(v.input_tokens),output_tokens:num(v.output_tokens),cache_read_input_tokens:num(v.cache_read_input_tokens),cache_creation_input_tokens:num(v.cache_creation_input_tokens)}}function finish(draft){if(!draft.id)return null;let totals={input_tokens:0,output_tokens:0,cache_read_input_tokens:0,cache_creation_input_tokens:0};for(let u of draft.usageByMessage.values())totals.input_tokens+=u.input_tokens,totals.output_tokens+=u.output_tokens,totals.cache_read_input_tokens+=u.cache_read_input_tokens,totals.cache_creation_input_tokens+=u.cache_creation_input_tokens;return{id:draft.id,sessionId:draft.sessionId,...draft.model?{model:draft.model}:{},startedAt:draft.startedAt,endedAt:draft.endedAt,...draft.usageByMessage.size>0?{usage:totals}:{}}}function parseClaudeTurns(raw,fallbackSessionId=""){let out=[],draft=null;for(let line of raw.split(`
|
|
4
4
|
`)){let trimmed=line.trim();if(!trimmed||!isJsonlLineWithinBound(trimmed))continue;let record;try{record=JSON.parse(trimmed)}catch{continue}if(!isObject(record)||isSyntheticClaudeRecord(record))continue;let inner=isObject(record.message)?record.message:record,at=typeof record.timestamp==="string"?Date.parse(record.timestamp):Number.NaN;if(!Number.isFinite(at))continue;let sessionId=typeof record.sessionId==="string"?record.sessionId:fallbackSessionId;if(inner.role==="user"){if(!opensTurn(inner.content))continue;if(draft){let done=finish(draft);if(done)out.push(done)}draft={id:"",sessionId,startedAt:at,endedAt:at,usageByMessage:new Map};continue}if(inner.role!=="assistant"||!draft)continue;if(draft.endedAt=at,typeof inner.model==="string")draft.model=inner.model;let messageId=typeof inner.id==="string"?inner.id:"";if(messageId)draft.id=messageId;let usage=readUsage(inner.usage);if(usage&&messageId)draft.usageByMessage.set(messageId,usage)}if(draft){let done=finish(draft);if(done)out.push(done)}return out}async function readClaudeTurns(transcriptPath){try{let raw=await readTextFileBounded(transcriptPath);return parseClaudeTurns(raw)}catch{return[]}}var HEX_RE=/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;function parseHex(value){let match=HEX_RE.exec(value);if(!match)return[0,0,0];return[Number.parseInt(match[1],16),Number.parseInt(match[2],16),Number.parseInt(match[3],16)]}function luminance([red,green,blue]){return(red*0.2126+green*0.7152+blue*0.0722)/255}function blend(from,to,amount){return[Math.round(from[0]+(to[0]-from[0])*amount),Math.round(from[1]+(to[1]-from[1])*amount),Math.round(from[2]+(to[2]-from[2])*amount)]}function codexUserMessageBackground(background){return luminance(background)>0.5?blend(background,[0,0,0],0.04):blend(background,[255,255,255],0.12)}function transcriptRewrite(palette){let foreground=parseHex(palette.foreground),background=parseHex(palette.background),backgroundIsLight=luminance(background)>0.5;return{matchBackground:codexUserMessageBackground(background),foreground:backgroundIsLight?foreground:background,background:backgroundIsLight?background:foreground}}var codexTerminalPresentation={alternateScreenStyleRewrites:(palette)=>[transcriptRewrite(palette)]};var codexCapabilities={preparePromptSubmission:(prompt)=>{return/^[\/!]/.test(prompt.trimStart())?prompt:`${prompt} `},beforePromptSubmit:"\x1B[F",terminalPresentation:codexTerminalPresentation,interruptSequence:"\x1B"},codexIdentity={shortName:"Codex"};import{join}from"path";var EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"Stop",verb:"turn-complete"},{event:"SessionEnd",verb:"session-end"},{event:"PreCompact",verb:"pre-compact"},{event:"PostCompact",verb:"post-compact"},{event:"SubagentStart",verb:"subagent-start"},{event:"SubagentStop",verb:"subagent-stop"},{event:"PreToolUse",verb:"tool-pre"},{event:"PostToolUse",verb:"tool-post"}],ROVE_CODEX_HOOK_EVENTS=EVENT_MAP.map((e)=>e.event);function codexHooksPath(){return join(vendorConfigHome("codex"),"hooks.json")}class CodexHookAdapter extends JsonHookAdapter{vendor="codex";setupCommand="/hooks";eventMap=EVENT_MAP;globalSettingsPath(){return codexHooksPath()}activityDetailFromPayload(kind,payload){if(kind==="tool-pre"||kind==="tool-post")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{}}};if(kind==="pre-compact"||kind==="post-compact")return{compact:{trigger:payload.trigger==="manual"?"manual":"auto"}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}}import{createHash}from"crypto";function createAppendParseCache(opts){let maxFiles=opts.maxFiles??8,cache=new Map;function remember(filePath,entry){if(cache.delete(filePath),cache.set(filePath,entry),cache.size>maxFiles){let oldest=cache.keys().next().value;if(oldest!==void 0)cache.delete(oldest)}}return function(filePath,raw,ctx){let stableLength=raw.lastIndexOf(`
|
|
5
5
|
`)+1,entry=cache.get(filePath),verifiedLength=Math.min(entry?.prefixLength??0,stableLength),hash=createHash("sha256").update(raw.slice(0,verifiedLength)),unchanged=entry!==void 0&&Object.is(entry.context,ctx)&&entry.prefixLength<=stableLength&&hash.copy().digest("hex")===entry.prefixHash,prefixState;if(unchanged)prefixState=entry.prefixLength<stableLength?opts.parseChunk(raw.slice(entry.prefixLength,stableLength),entry.state,ctx):entry.state;else prefixState=opts.parseChunk(raw.slice(0,stableLength),opts.initial(ctx),ctx);if(!unchanged||entry.prefixLength!==stableLength||entry.state!==prefixState)remember(filePath,{context:ctx,prefixLength:stableLength,prefixHash:hash.update(raw.slice(verifiedLength,stableLength)).digest("hex"),state:prefixState});let tail=raw.slice(stableLength);return tail.trim().length>0?opts.parseChunk(tail,prefixState,ctx):prefixState}}var sortedMessages=new WeakMap;function sortByTimestamp(messages){let hit=sortedMessages.get(messages);if(hit)return hit;let sorted=[...messages].sort((a,b)=>a.timestamp<b.timestamp?-1:a.timestamp>b.timestamp?1:0);return sortedMessages.set(messages,sorted),sorted}function normalizeCodexContent(raw){if(typeof raw==="string")return raw.length>0?[{type:"text",text:raw}]:[];if(!Array.isArray(raw))return[];let blocks=[];for(let item of raw){if(typeof item==="string"){if(item.length>0)blocks.push({type:"text",text:item});continue}if(!isObject(item))continue;let t=typeof item.type==="string"?item.type:void 0;if(t==="input_text"||t==="output_text"){let text=typeof item.text==="string"?item.text:"";if(text.length>0)blocks.push({type:"text",text});continue}if(t)blocks.push({type:"text",text:`[codex: ${t}]`})}return blocks}function isSyntheticCodexUserRow(blocks){if(blocks.length===0)return!1;for(let b of blocks){if(b.type!=="text")return!1;let t=(b.text??"").trim();if(!isTagEnvelope(t)&&!isInstructionsEnvelope(t))return!1}return!0}var ENVELOPE_TAGS=["environment_context","recommended_plugins","user_instructions"];function isTagEnvelope(text){return ENVELOPE_TAGS.some((tag)=>text.startsWith(`<${tag}>`)&&text.endsWith(`</${tag}>`))}function isInstructionsEnvelope(text){return text.startsWith("# AGENTS.md instructions")&&text.includes("<INSTRUCTIONS>")}function codexUsageToSnapshot(usage,opts={}){let totalInput=numberOr(usage.input_tokens,0),cachedInput=numberOr(usage.cached_input_tokens,0),output=numberOr(usage.output_tokens,0),nonCachedInput=Math.max(0,totalInput-cachedInput);if(totalInput<=0&&output<=0&&cachedInput<=0)return;return{input_tokens:nonCachedInput,output_tokens:output,...cachedInput>0?{cache_read_input_tokens:cachedInput}:{},...validPositive(opts.contextWindowTokens)?{context_window_tokens:opts.contextWindowTokens}:{}}}function numberOr(v,fallback){return typeof v==="number"&&Number.isFinite(v)?v:fallback}function validPositive(v){return typeof v==="number"&&Number.isFinite(v)&&v>0}var emptyState={messages:[],latestUsage:void 0,latestUsageTimestampMs:null},cache=createAppendParseCache({initial:()=>emptyState,parseChunk:foldRolloutChunk});function parseRolloutRaw(filePath,raw,sessionId){let state=cache(filePath,raw,sessionId);return{messages:sortByTimestamp(state.messages),...state.latestUsage?{usageMetrics:state.latestUsage}:{}}}function foldRolloutChunk(chunk,prev,sessionId){let updatedMessages,writableMessages=()=>{return updatedMessages??=[...prev.messages],updatedMessages},latestUsage=prev.latestUsage,latestUsageTimestampMs=prev.latestUsageTimestampMs;for(let line of chunk.split(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{connectIfRunning,connectOrStartDaemon}from"./chunk-
|
|
2
|
+
import{connectIfRunning,connectOrStartDaemon}from"./chunk-ad5gbdcf.js";async function openDaemonSession(opts={}){let client=opts.mode==="require-running"?await connectIfRunning():await connectOrStartDaemon();if(!client)return null;return{client,close:()=>client.close()}}async function resolveActiveTaskId(client){let activeId=null,off=client.onChannel("active-task",(payload)=>{activeId=payload.taskId});try{await client.subscribe()}finally{off()}return activeId}
|
|
3
3
|
export{openDaemonSession,resolveActiveTaskId};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{expandTilde}from"./chunk-ag3txfg2.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{SUBCOMMAND_VERBS}from"./chunk-
|
|
2
|
+
import{expandTilde}from"./chunk-ag3txfg2.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{SUBCOMMAND_VERBS}from"./chunk-1qge84t7.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-pn5ygqn6.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{resolve}from"path";var CLI_NAME=ROVE_PRODUCT_NAME,REPO_USAGE=[`Usage: ${CLI_NAME} repo <show|set|unset> [path] [options]`,"","Manage a repo's per-user init override (state.json fallback for repos","that don't ship .rove/init.sh / .rove/init-prompt.md).","","Commands:"," show [path] Print the override + repo convention files"," set [path] <options> Set the init script and/or first prompt"," unset [path] [--init-script] [--init-prompt] Clear one or both (default: both)","","Set options (later wins; *-file reads from disk):"," --init-script <text> Inline shell to run before the engine"," --init-script-file <path> Read the init script from a file"," --init-prompt <text> Inline first prompt for the engine"," --init-prompt-file <path> Read the first prompt from a file",""," path defaults to the current directory (resolved to its git toplevel).",""].join(`
|
|
3
3
|
`);function usageError(message){process.stderr.write(`${CLI_NAME} repo: ${message}
|
|
4
4
|
|
|
5
5
|
${REPO_USAGE}
|
|
6
6
|
`),process.exit(2)}function readArgFile(path){try{return readFileSync(resolve(process.cwd(),expandTilde(path)),"utf8")}catch(err){usageError(`cannot read ${path}: ${errorMessage(err)}`)}}function parseRepoArgs(args){let out={};for(let i=0;i<args.length;i++){let a=args[i],need=()=>{let v=args[++i];if(v===void 0)usageError(`${a} requires a value`);return v};if(a==="--init-script")out.initScript=need();else if(a==="--init-script-file")out.initScript=readArgFile(need());else if(a==="--init-prompt")out.initPrompt=need();else if(a==="--init-prompt-file")out.initPrompt=readArgFile(need());else if(a.startsWith("-"))usageError(`unknown flag "${a}"`);else if(out.path===void 0)out.path=a;else usageError(`unexpected argument "${a}"`)}return out}function parseUnsetArgs(args){let path,clearScript=!1,clearPrompt=!1;for(let a of args)if(a==="--init-script")clearScript=!0;else if(a==="--init-prompt")clearPrompt=!0;else if(a.startsWith("-"))usageError(`unknown flag "${a}"`);else if(path===void 0)path=a;else usageError(`unexpected argument "${a}"`);if(!clearScript&&!clearPrompt)clearScript=!0,clearPrompt=!0;return{path,clearScript,clearPrompt}}async function runRepoSubcommand(args){let[verb,...rest]=args;if(verb===void 0||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${REPO_USAGE}
|
|
7
|
-
`);return}if(!SUBCOMMAND_VERBS.repo.includes(verb))usageError(`unknown verb "${verb}"`);let{getRepoInitOverride,setRepoInitOverride,resolveRepoRoot}=await import("./chunk-
|
|
7
|
+
`);return}if(!SUBCOMMAND_VERBS.repo.includes(verb))usageError(`unknown verb "${verb}"`);let{getRepoInitOverride,setRepoInitOverride,resolveRepoRoot}=await import("./chunk-afwh7as3.js");if(verb==="show"){let[pathArg]=rest.filter((a)=>!a.startsWith("-")),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(pathArg??"."))),override=getRepoInitOverride(repo),{describeRepoInitSources}=await import("./chunk-bphs6am4.js"),sources=describeRepoInitSources(repo);console.log(`repo: ${repo}`);for(let group of[sources.script,sources.prompt])group.forEach((source,index)=>{console.log(` ${`${source.rel}:`.padEnd(22)}${describeSource(group,index)}`)});console.log(` override initScript: ${override.initScript?quotePreview(override.initScript):"(unset)"}`),console.log(` override initPrompt: ${override.initPrompt?quotePreview(override.initPrompt):"(unset)"}`);return}if(verb==="set"){let flags=parseRepoArgs(rest);if(flags.initScript===void 0&&flags.initPrompt===void 0)usageError("set needs at least one of --init-script(-file) / --init-prompt(-file)");let repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(flags.path??"."))),next=setRepoInitOverride(repo,{...flags.initScript!==void 0?{initScript:flags.initScript}:{},...flags.initPrompt!==void 0?{initPrompt:flags.initPrompt}:{}});console.log(`updated override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}if(verb==="unset"){let{path,clearScript,clearPrompt}=parseUnsetArgs(rest),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(path??"."))),next=setRepoInitOverride(repo,{...clearScript?{initScript:""}:{},...clearPrompt?{initPrompt:""}:{}});console.log(`cleared override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}usageError(`unknown verb "${verb}"`)}function describeSource(group,index){let source=group[index];if(!source)return"absent";if(source.effective)return"present (wins)";if(!source.present)return"absent";return group.slice(0,index).some((earlier)=>earlier.effective)?"present (shadowed)":"present but empty (ignored)"}function quotePreview(value){let oneLine=value.replace(/\s+/g," ").trim();return oneLine.length>60?`"${oneLine.slice(0,57)}\u2026"`:`"${oneLine}"`}export{runRepoSubcommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pluginsOutdatedCachePath}from"./chunk-
|
|
2
|
+
import{pluginsOutdatedCachePath}from"./chunk-admwmjjy.js";import{readFileSync,writeFileSync}from"fs";var OUTDATED_CACHE_TTL_MS=86400000;function writeOutdatedCache(outdatedIds,homeDir){let cache={checkedAt:Date.now(),outdated:outdatedIds};try{writeFileSync(pluginsOutdatedCachePath(homeDir),`${JSON.stringify(cache,null,2)}
|
|
3
3
|
`)}catch{}}function readOutdatedCache(homeDir){try{let cache=JSON.parse(readFileSync(pluginsOutdatedCachePath(homeDir),"utf8"));if(typeof cache.checkedAt!=="number"||!Array.isArray(cache.outdated))return[];if(Date.now()-cache.checkedAt>OUTDATED_CACHE_TTL_MS)return[];return cache.outdated.filter((id)=>typeof id==="string")}catch{return[]}}
|
|
4
4
|
export{writeOutdatedCache,readOutdatedCache};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{launchTui,trackWelcomeWrite}from"./chunk-
|
|
2
|
+
import{launchTui,trackWelcomeWrite}from"./chunk-6r84zkcz.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{stripTerminalControls,terminalRows}from"./chunk-etfh8f4z.js";import{OWNER_ONLY_FILE_MODE}from"./chunk-yt15y085.js";import{defaultPtyExitsPath}from"./chunk-
|
|
2
|
+
import{stripTerminalControls,terminalRows}from"./chunk-etfh8f4z.js";import{OWNER_ONLY_FILE_MODE}from"./chunk-yt15y085.js";import{defaultPtyExitsPath}from"./chunk-z7zm8h1q.js";import{randomUUID}from"crypto";import{mkdirSync,readFileSync,renameSync,writeFileSync}from"fs";import{dirname}from"path";var MAX_RECORDS=50,TAIL_LINES=40,TAIL_LINE_CHARS=500;function plainTail(raw){let lines=terminalRows(raw,TAIL_LINE_CHARS);while(lines.length>0&&(lines[lines.length-1]??"").trim()==="")lines.pop();return lines.slice(-TAIL_LINES)}function engineExitCodeFromTail(tail){for(let i=tail.length-1;i>=0;i--){let m=ENGINE_EXIT_BANNER.exec(tail[i]??"");if(m?.[1])return Number.parseInt(m[1],10)}return null}var ENGINE_EXIT_BANNER=/Engine exited \(code (\d+)\)/;function healTails(records){let out={};for(let[key,record]of Object.entries(records)){let tail=record?.tail;out[key]=Array.isArray(tail)?{...record,tail:tail.map((line)=>stripTerminalControls(String(line)))}:record}return out}function compareByExitAtDesc(a,b){if(a.at===b.at)return 0;return a.at<b.at?1:-1}function readPtyExitStore(path=defaultPtyExitsPath()){let read=(status,records={})=>({records,status,readable:status==="ok"||status==="absent"}),raw;try{raw=readFileSync(path,"utf8")}catch(err){return read(err.code==="ENOENT"?"absent":"unreadable")}try{let parsed=JSON.parse(raw);if(parsed===null||typeof parsed!=="object"||Array.isArray(parsed))return read("unparsable");return read("ok",healTails(parsed))}catch{return read("unparsable")}}function readPtyExitRecords(path=defaultPtyExitsPath()){return readPtyExitStore(path).records}function recordPtyExit(info,path=defaultPtyExitsPath()){if(info.key.startsWith("::"))return;if(info.exit.code===0&&info.exit.signal===null)return;let tail=plainTail(info.tail);writeRecord(info.key,{key:info.key,pid:info.pid,code:info.exit.code??engineExitCodeFromTail(tail),signal:info.exit.signal,at:info.exit.at,tail,layer:"pty"},path)}function recordEngineExit(info,path=defaultPtyExitsPath()){if(info.key.startsWith("::"))return;let tail=plainTail(info.tail);writeRecord(`${info.key}#engine`,{key:info.key,pid:info.pid,code:engineExitCodeFromTail(tail),signal:null,at:info.at,tail,layer:"engine",...info.vendor?{vendor:info.vendor}:{},...info.atApproximate?{atApproximate:!0}:{},parentAlive:!0},path)}function writeRecord(storeKey,record,path){let store=readPtyExitStore(path);if(store.status==="unreadable")throw Error(`pty-exits store is unreadable (${path}) \u2014 refusing to overwrite it`);let records=store.records;records[storeKey]=record;let newest=Object.entries(records).sort(([,a],[,b])=>compareByExitAtDesc(a,b)).slice(0,MAX_RECORDS);mkdirSync(dirname(path),{recursive:!0});let tmp=`${path}.tmp-${process.pid}-${randomUUID()}`;writeFileSync(tmp,JSON.stringify(Object.fromEntries(newest),null,2),{encoding:"utf8",mode:OWNER_ONLY_FILE_MODE}),renameSync(tmp,path)}
|
|
3
3
|
export{plainTail,engineExitCodeFromTail,ENGINE_EXIT_BANNER,compareByExitAtDesc,readPtyExitStore,readPtyExitRecords,recordPtyExit,recordEngineExit};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{runChannelCli,startChatChannels}from"./chunk-
|
|
2
|
+
import{runChannelCli,startChatChannels}from"./chunk-v9avfsxq.js";import"./chunk-91sykzqq.js";export{startChatChannels,runChannelCli};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{SUBCOMMAND_VERBS,TOP_LEVEL_SUBCOMMANDS}from"./chunk-
|
|
2
|
+
import{SUBCOMMAND_VERBS,TOP_LEVEL_SUBCOMMANDS}from"./chunk-1qge84t7.js";import{join}from"path";import{fileURLToPath}from"url";var SHELLS=["bash","zsh","fish"];function isShellKind(value){return SHELLS.some((shell)=>shell===value)}var SHIPPED_COMPLETIONS_DIR=fileURLToPath(new URL("../completions/",import.meta.url));function shippedCompletionsPath(shell,cliName,dir=SHIPPED_COMPLETIONS_DIR){return join(dir,`${cliName}.${shell}`)}function mergeSubVerbs(apiVerbs){let merged={...SUBCOMMAND_VERBS,api:apiVerbs};return Object.keys(merged).sort().map((command)=>[command,merged[command]??[]])}function generateCompletions(shell,cliName,subVerbs){return shell==="bash"?generateBashCompletions(cliName,subVerbs):shell==="zsh"?generateZshCompletions(cliName,subVerbs):generateFishCompletions(cliName,subVerbs)}function generateBashCompletions(cliName,subVerbs){let subcommands=TOP_LEVEL_SUBCOMMANDS.join(" "),fn=`_${cliName}`;return[`# ${cliName} bash completions`,`# Source: ${cliName} completions bash`,"",`${fn}() {`," local cur prev"," COMPREPLY=()",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," if [[ ${COMP_CWORD} -eq 1 ]]; then",` COMPREPLY=( $(compgen -W "${subcommands}" -- "\${cur}") )`," return"," fi"," if [[ ${COMP_CWORD} -eq 2 ]]; then",' case "${prev}" in',...subVerbs.map(([command,verbs])=>` ${command}) COMPREPLY=( $(compgen -W "${verbs.join(" ")}" -- "\${cur}") ) ;;`)," esac"," fi","}",`complete -F ${fn} ${cliName}`,""].join(`
|
|
3
3
|
`)}function generateZshCompletions(cliName,subVerbs){let subcommandsList=TOP_LEVEL_SUBCOMMANDS.map((s)=>`"${s}"`).join(" "),fn=`_${cliName}`;return[`#compdef ${cliName}`,`# ${cliName} zsh completions`,`# Source: ${cliName} completions zsh`,"",`${fn}() {`," local -a subcommands verbs",` subcommands=(${subcommandsList})`,""," if (( CURRENT == 2 )); then"," _describe -t commands 'subcommand' subcommands"," return"," fi",""," verbs=()",' case "${words[2]}" in',...subVerbs.map(([command,verbs])=>` ${command}) verbs=(${verbs.map((v)=>`"${v}"`).join(" ")}) ;;`)," esac"," if (( CURRENT == 3 && ${#verbs} > 0 )); then"," _describe -t verbs 'verb' verbs"," fi","}","","# Autoloaded from $fpath -> run as the completion function;","# sourced directly -> register with compdef instead.",`if [ "\${funcstack[1]}" = "${fn}" ]; then`,` ${fn} "$@"`,"elif (( $+functions[compdef] )); then",` compdef ${fn} ${cliName}`,"fi",""].join(`
|
|
4
4
|
`)}function generateFishCompletions(cliName,subVerbs){let lines=[...TOP_LEVEL_SUBCOMMANDS.map((s)=>`complete -c ${cliName} -f -n __fish_use_subcommand -a ${s}`),...subVerbs.map(([command,verbs])=>`complete -c ${cliName} -f -n "__fish_seen_subcommand_from ${command}" -a "${verbs.join(" ")}"`)];return`# ${cliName} fish completions
|
|
5
5
|
# Source: ${cliName} completions fish
|