@sma1lboy/rove 0.9.311-next.680 → 0.9.311-next.682

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/cli/{chunk-x8f92qn5.js → chunk-0bpkrvq6.js} +1 -1
  2. package/dist/cli/{chunk-8a75vjnz.js → chunk-0y8w07nr.js} +1 -1
  3. package/dist/cli/{chunk-05pjh1wg.js → chunk-1dfksk5s.js} +1 -1
  4. package/dist/cli/{chunk-1d1xtdt3.js → chunk-22t7edqd.js} +1 -1
  5. package/dist/cli/{chunk-f8fenjfs.js → chunk-2msfzb8d.js} +1 -1
  6. package/dist/cli/{chunk-9ypcs2qt.js → chunk-2t5qas7n.js} +1 -1
  7. package/dist/cli/{chunk-gnmnttr8.js → chunk-4eyw6g6q.js} +1 -1
  8. package/dist/cli/{chunk-d3rmdpcr.js → chunk-4mb8f70m.js} +1 -1
  9. package/dist/cli/{chunk-y5r9ja0b.js → chunk-4mzr32gs.js} +1 -1
  10. package/dist/cli/{chunk-ha312q39.js → chunk-5m01rpg9.js} +1 -1
  11. package/dist/cli/{chunk-js38xfmz.js → chunk-6ep60xg2.js} +1 -1
  12. package/dist/cli/{chunk-g6hgk5rj.js → chunk-756wh3xt.js} +1 -1
  13. package/dist/cli/{chunk-mfwtv144.js → chunk-7786gkb9.js} +1 -1
  14. package/dist/cli/{chunk-crznvfz8.js → chunk-94596bj0.js} +2 -2
  15. package/dist/cli/{chunk-7epyx5hp.js → chunk-9m76dk8f.js} +1 -1
  16. package/dist/cli/{chunk-tm5mt531.js → chunk-a2x91bdf.js} +2 -2
  17. package/dist/cli/{chunk-yjgtmjps.js → chunk-bcwzrs76.js} +1 -1
  18. package/dist/cli/{chunk-jvr74tfv.js → chunk-bprghzgx.js} +1 -1
  19. package/dist/cli/{chunk-n7r05qsm.js → chunk-bvgyqe7j.js} +1 -1
  20. package/dist/cli/{chunk-hev1gfqk.js → chunk-ch25ypyf.js} +1 -1
  21. package/dist/cli/{chunk-xtdyc03e.js → chunk-dc69mzx1.js} +1 -1
  22. package/dist/cli/{chunk-2qq845rq.js → chunk-ej59gecm.js} +1 -1
  23. package/dist/cli/{chunk-5jzyrbzb.js → chunk-eynv3yw1.js} +1 -1
  24. package/dist/cli/{chunk-jc9k5kmh.js → chunk-f0cpvpky.js} +1 -1
  25. package/dist/cli/{chunk-41x2efc9.js → chunk-f3c2q4k0.js} +1 -1
  26. package/dist/cli/{chunk-pn6wksrr.js → chunk-fdsp8ndf.js} +1 -1
  27. package/dist/cli/{chunk-7998de5k.js → chunk-fedby3c7.js} +1 -1
  28. package/dist/cli/chunk-fnp25wtq.js +6 -0
  29. package/dist/cli/{chunk-eb2m2sf8.js → chunk-g875xaf6.js} +1 -1
  30. package/dist/cli/{chunk-fmzmja4e.js → chunk-h3czhgd3.js} +1 -1
  31. package/dist/cli/{chunk-sqpaqvk8.js → chunk-jkxve6gr.js} +1 -1
  32. package/dist/cli/{chunk-7y9n0rdq.js → chunk-jps50xyw.js} +1 -1
  33. package/dist/cli/{chunk-2tg124ex.js → chunk-jrr4cd50.js} +1 -1
  34. package/dist/cli/{chunk-kzbrn9cq.js → chunk-k1z2qahp.js} +2 -2
  35. package/dist/cli/{chunk-rwge3ysd.js → chunk-k26y5a38.js} +1 -1
  36. package/dist/cli/{chunk-23q9rkba.js → chunk-khc0z802.js} +2 -2
  37. package/dist/cli/chunk-ky29smpr.js +3 -0
  38. package/dist/cli/{chunk-trfm70p5.js → chunk-ms220a8e.js} +1 -1
  39. package/dist/cli/{chunk-d8p0nf6d.js → chunk-nhvzfyd4.js} +1 -1
  40. package/dist/cli/{chunk-2p94134z.js → chunk-p3ysqq4a.js} +1 -1
  41. package/dist/cli/chunk-r9g2sm7c.js +2 -0
  42. package/dist/cli/{chunk-wk50fzgj.js → chunk-rxe3ht09.js} +1 -1
  43. package/dist/cli/{chunk-yf1zp95d.js → chunk-sn65djjx.js} +1 -1
  44. package/dist/cli/{chunk-q327ea05.js → chunk-v2vtgw8p.js} +1 -1
  45. package/dist/cli/{chunk-8qsa99g8.js → chunk-vkfbsv19.js} +1 -1
  46. package/dist/cli/{chunk-vhd2cxem.js → chunk-vmw3qj3e.js} +1 -1
  47. package/dist/cli/chunk-vnq3sat3.js +5 -0
  48. package/dist/cli/{chunk-y5cbdjea.js → chunk-vp4946s7.js} +1 -1
  49. package/dist/cli/{chunk-rwjvdf9f.js → chunk-xcmjbh99.js} +1 -1
  50. package/dist/cli/{chunk-rjxy2wpq.js → chunk-xmecr0nz.js} +1 -1
  51. package/dist/cli/{chunk-mmhmg56x.js → chunk-yb2dy5w3.js} +2 -2
  52. package/dist/cli/index.js +2 -2
  53. package/dist/cli/rove.js +1 -1
  54. package/dist/web/assets/{index-Bh4nCsyA.js → index-C1XLVubq.js} +40 -40
  55. package/dist/web/assets/{index-B1YXHxkx.css → index-wwdBvBD3.css} +1 -1
  56. package/dist/web/assets/{term-mount-DhMoYALr.js → term-mount-Dx2GA8ze.js} +1 -1
  57. package/dist/web/index.html +2 -2
  58. package/dist/web/relay-client/assets/{index-C6lFPT3I.js → index-DPU_b_0j.js} +60 -60
  59. package/dist/web/relay-client/assets/{index-BiAAipbT.css → index-PK2MqnTT.css} +1 -1
  60. package/dist/web/relay-client/index.html +2 -2
  61. package/package.json +1 -1
  62. package/dist/cli/chunk-8ktqtv5p.js +0 -2
  63. package/dist/cli/chunk-v2zdpec1.js +0 -6
  64. package/dist/cli/chunk-zjfjqf1m.js +0 -5
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-7epyx5hp.js";import{VerbArgs,apiUsage,findVerb,normalizeWebArgv,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-trfm70p5.js";import{ensurePluginEnginesLoaded}from"./chunk-nsza72e4.js";import{openDaemonSession}from"./chunk-wje59khj.js";import{requireVerbInstalled,verbInstalled}from"./chunk-z0wnws9w.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-dscbf17z.js";import{ApiError}from"./chunk-3vm6e0cf.js";import{errorMessage}from"./chunk-0zs13rdq.js";import{ROVE_API_VERSION}from"./chunk-37nrg1nc.js";import{argvHasFlag}from"./chunk-78y80xe8.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
2
+ import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-9m76dk8f.js";import{VerbArgs,apiUsage,findVerb,normalizeWebArgv,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-ms220a8e.js";import{ensurePluginEnginesLoaded}from"./chunk-nsza72e4.js";import{openDaemonSession}from"./chunk-wje59khj.js";import{requireVerbInstalled,verbInstalled}from"./chunk-z0wnws9w.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-dscbf17z.js";import{ApiError}from"./chunk-3vm6e0cf.js";import{errorMessage}from"./chunk-0zs13rdq.js";import{ROVE_API_VERSION}from"./chunk-37nrg1nc.js";import{argvHasFlag}from"./chunk-78y80xe8.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
3
3
  `)}function emit(value,pretty){let warning=takeIdentityWarning(),payload=warning&&value&&typeof value==="object"&&!Array.isArray(value)?{...value,identityWarning:warning}:value;writeJson(envelopeMode?successEnvelope(payload):payload,pretty)}function fail(message,code,exitCode=1,data){let error=errorBody(new ApiError(message,code,data));if(envelopeMode)writeJson({apiVersion:ROVE_API_VERSION,ok:!1,error},!1);else writeJson({error},!1,process.stderr);process.exit(exitCode)}var USAGE_ERROR_CODES=new Set(["BAD_VERB","UNKNOWN_VERB","BAD_FLAG","MISSING_FLAG","MISSING_VERB","BAD_DAEMON","UNKNOWN_MACHINE"]);async function invokeVerb(verbName,argv,deps){return runVerb(verbName,{argv},deps)}async function runApiSubcommand(argv){let[verbName,...withMachine]=argv,{machine,rest}=takeMachineFlag(withMachine);if(envelopeMode=argvHasFlag(rest,"--envelope"),!verbName||verbName==="--help"||verbName==="-h"||verbName==="help"){if(!verbName)fail(apiUsage(),"MISSING_VERB",2);process.stdout.write(`${apiUsage()}
4
4
  `);return}ensurePluginEnginesLoaded();let verb=findVerb(verbName);if(!verb){let err=unknownVerbError(verbName);fail(`${err.message}
5
5
  ${apiUsage()}`,err.code,2,err.data)}let parsed;try{let verbArgv=verb.name==="web"?normalizeWebArgv(rest):rest;parsed=parseFlags(verbArgv,booleanFlagsOf(verb),repeatableFlagsOf(verb))}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(parsed.help){if(!verbInstalled(verb))try{requireVerbInstalled(verb)}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data)}process.stdout.write(`${verbHelp(verb)}
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{invokeVerb}from"./chunk-x8f92qn5.js";import"./chunk-7epyx5hp.js";import{defaultApiRuntime,loadContext}from"./chunk-trfm70p5.js";import"./chunk-bzjef20g.js";import"./chunk-nsza72e4.js";import"./chunk-zsh70aef.js";import"./chunk-wje59khj.js";import"./chunk-8xsnpyer.js";import"./chunk-7fw390kp.js";import"./chunk-h58qkv3b.js";import"./chunk-pyzbrnnp.js";import"./chunk-4kepb278.js";import"./chunk-zcywdm3y.js";import"./chunk-36qsn2v8.js";import"./chunk-8ca4esh6.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-hdea2ss8.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-3h9psc5w.js";import"./chunk-5mhvjytn.js";import"./chunk-5p2hhjje.js";import"./chunk-zknvzer3.js";import"./chunk-tv0pxap3.js";import"./chunk-7998de5k.js";import"./chunk-sqpaqvk8.js";import"./chunk-z0wnws9w.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-6t1yxx9x.js";import"./chunk-mdx18vtz.js";import"./chunk-1d1xtdt3.js";import"./chunk-dscbf17z.js";import"./chunk-y0e28qha.js";import"./chunk-gze092t3.js";import"./chunk-wjmte4f0.js";import"./chunk-3vm6e0cf.js";import"./chunk-f1csqde7.js";import"./chunk-hy6b9ktj.js";import"./chunk-xtdr7b5h.js";import"./chunk-svtby8tp.js";import"./chunk-69cqwz53.js";import"./chunk-mqfvzdpr.js";import"./chunk-eeajq8px.js";import"./chunk-kpq28cbh.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-n5zdhshy.js";import"./chunk-ahfvmf90.js";import"./chunk-rxqdw6s5.js";import"./chunk-z9c475xb.js";import"./chunk-tn9gtf18.js";import"./chunk-ygdxgp8r.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-34bf7mnm.js";import"./chunk-2mcgd0ym.js";import"./chunk-f60hmm20.js";import"./chunk-w7zv47mp.js";import"./chunk-rr97z89e.js";import"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-navavqt2.js";import"./chunk-etfh8f4z.js";import"./chunk-ez623zqp.js";import"./chunk-w70anvs6.js";import"./chunk-4csg29es.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-h8qg9v95.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-grbrh92f.js";import"./chunk-0zs13rdq.js";import"./chunk-1wpwxcg9.js";import"./chunk-ypbh8ra4.js";import"./chunk-n6s1sba5.js";import"./chunk-cf0kpsdm.js";import"./chunk-nmt8peyf.js";import{RoveDaemonClient}from"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import"./chunk-eb2m2sf8.js";import"./chunk-78y80xe8.js";import"./chunk-wx77yjhc.js";import{SUBCOMMAND_VERBS}from"./chunk-8byrmc70.js";import"./chunk-12qq8r81.js";import"./chunk-t9n6n7dy.js";import"./chunk-7b2x6nkj.js";import"./chunk-8acw5rmt.js";import"./chunk-96wm6gt4.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-jykxdtad.js";import"./chunk-65nm1v5h.js";import"./chunk-sckqk79z.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-8rxg12aj.js";import"./chunk-bzqjk9fb.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{execFile}from"child_process";var LARK_CLI="lark-cli";function larkCli(args,timeoutMs=30000){return new Promise((resolve)=>{execFile(LARK_CLI,[...args],{timeout:timeoutMs,encoding:"utf8"},(err,stdout,stderr)=>resolve({ok:!err,stdout:stdout??"",stderr:stderr||(err?err.message:"")}))})}function json(stdout){try{let value=JSON.parse(stdout);return value&&typeof value==="object"?value:null}catch{return null}}async function botInfo(){let res=await larkCli(["api","GET","/open-apis/bot/v3/info","--as","bot"]),data=json(res.stdout)?.data??json(res.stdout)?.bot;return typeof data?.open_id==="string"&&data.open_id?{openId:data.open_id,name:typeof data.app_name==="string"?data.app_name:""}:null}async function authStatus(){let raw=json((await larkCli(["auth","status"])).stdout),user=raw?.identities?.user;return{...typeof raw?.appId==="string"&&raw.appId?{appId:raw.appId}:{},...typeof user?.openId==="string"&&user.openId?{userOpenId:user.openId}:{},...typeof user?.userName==="string"?{userName:user.userName}:{}}}async function react(messageId,emoji){return await larkCli(["im","reactions","create","--as","bot","--message-id",messageId,"--data",JSON.stringify({reaction_type:{emoji_type:emoji}})])}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var SEEN_CAP=500,DEFAULT_TONE="\u7B80\u77ED\u76F4\u63A5\uFF0C\u50CF\u540C\u4E8B\u804A\u5929\uFF0C\u7ED3\u8BBA\u5148\u8BF4\uFF0C\u4E0D\u5BA2\u5957",strings=(value)=>Array.isArray(value)?value.filter((v)=>typeof v==="string"):[];function readJson(path){try{let value=JSON.parse(readFileSync(path,"utf8"));return value&&typeof value==="object"?value:null}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
2
+ import{invokeVerb}from"./chunk-0bpkrvq6.js";import"./chunk-9m76dk8f.js";import{defaultApiRuntime,loadContext}from"./chunk-ms220a8e.js";import"./chunk-bzjef20g.js";import"./chunk-nsza72e4.js";import"./chunk-zsh70aef.js";import"./chunk-wje59khj.js";import"./chunk-8xsnpyer.js";import"./chunk-7fw390kp.js";import"./chunk-h58qkv3b.js";import"./chunk-pyzbrnnp.js";import"./chunk-4kepb278.js";import"./chunk-zcywdm3y.js";import"./chunk-36qsn2v8.js";import"./chunk-8ca4esh6.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-hdea2ss8.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-3h9psc5w.js";import"./chunk-5mhvjytn.js";import"./chunk-5p2hhjje.js";import"./chunk-zknvzer3.js";import"./chunk-tv0pxap3.js";import"./chunk-fedby3c7.js";import"./chunk-jkxve6gr.js";import"./chunk-z0wnws9w.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-6t1yxx9x.js";import"./chunk-mdx18vtz.js";import"./chunk-22t7edqd.js";import"./chunk-dscbf17z.js";import"./chunk-y0e28qha.js";import"./chunk-gze092t3.js";import"./chunk-wjmte4f0.js";import"./chunk-3vm6e0cf.js";import"./chunk-f1csqde7.js";import"./chunk-hy6b9ktj.js";import"./chunk-xtdr7b5h.js";import"./chunk-svtby8tp.js";import"./chunk-69cqwz53.js";import"./chunk-mqfvzdpr.js";import"./chunk-eeajq8px.js";import"./chunk-kpq28cbh.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-n5zdhshy.js";import"./chunk-ahfvmf90.js";import"./chunk-rxqdw6s5.js";import"./chunk-z9c475xb.js";import"./chunk-tn9gtf18.js";import"./chunk-ygdxgp8r.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-34bf7mnm.js";import"./chunk-2mcgd0ym.js";import"./chunk-f60hmm20.js";import"./chunk-w7zv47mp.js";import"./chunk-rr97z89e.js";import"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-navavqt2.js";import"./chunk-etfh8f4z.js";import"./chunk-ez623zqp.js";import"./chunk-w70anvs6.js";import"./chunk-4csg29es.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-h8qg9v95.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-grbrh92f.js";import"./chunk-0zs13rdq.js";import"./chunk-1wpwxcg9.js";import"./chunk-ypbh8ra4.js";import"./chunk-n6s1sba5.js";import"./chunk-cf0kpsdm.js";import"./chunk-nmt8peyf.js";import{RoveDaemonClient}from"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import"./chunk-g875xaf6.js";import"./chunk-78y80xe8.js";import"./chunk-wx77yjhc.js";import{SUBCOMMAND_VERBS}from"./chunk-8byrmc70.js";import"./chunk-12qq8r81.js";import"./chunk-t9n6n7dy.js";import"./chunk-7b2x6nkj.js";import"./chunk-8acw5rmt.js";import"./chunk-96wm6gt4.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-jykxdtad.js";import"./chunk-65nm1v5h.js";import"./chunk-sckqk79z.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-8rxg12aj.js";import"./chunk-bzqjk9fb.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{execFile}from"child_process";var LARK_CLI="lark-cli";function larkCli(args,timeoutMs=30000){return new Promise((resolve)=>{execFile(LARK_CLI,[...args],{timeout:timeoutMs,encoding:"utf8"},(err,stdout,stderr)=>resolve({ok:!err,stdout:stdout??"",stderr:stderr||(err?err.message:"")}))})}function json(stdout){try{let value=JSON.parse(stdout);return value&&typeof value==="object"?value:null}catch{return null}}async function botInfo(){let res=await larkCli(["api","GET","/open-apis/bot/v3/info","--as","bot"]),data=json(res.stdout)?.data??json(res.stdout)?.bot;return typeof data?.open_id==="string"&&data.open_id?{openId:data.open_id,name:typeof data.app_name==="string"?data.app_name:""}:null}async function authStatus(){let raw=json((await larkCli(["auth","status"])).stdout),user=raw?.identities?.user;return{...typeof raw?.appId==="string"&&raw.appId?{appId:raw.appId}:{},...typeof user?.openId==="string"&&user.openId?{userOpenId:user.openId}:{},...typeof user?.userName==="string"?{userName:user.userName}:{}}}async function react(messageId,emoji){return await larkCli(["im","reactions","create","--as","bot","--message-id",messageId,"--data",JSON.stringify({reaction_type:{emoji_type:emoji}})])}import{mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var SEEN_CAP=500,DEFAULT_TONE="\u7B80\u77ED\u76F4\u63A5\uFF0C\u50CF\u540C\u4E8B\u804A\u5929\uFF0C\u7ED3\u8BBA\u5148\u8BF4\uFF0C\u4E0D\u5BA2\u5957",strings=(value)=>Array.isArray(value)?value.filter((v)=>typeof v==="string"):[];function readJson(path){try{let value=JSON.parse(readFileSync(path,"utf8"));return value&&typeof value==="object"?value:null}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
3
3
  `,{mode:384}),renameSync(tmp,path)}class LarkStore{dir;constructor(homeDir){this.dir=join(resolveDaemonHomeDir(homeDir),ROVE_STATE_DIR_BASENAME,"lark")}get agentDir(){return join(this.dir,"agent")}ensureDir(){mkdirSync(this.dir,{recursive:!0,mode:448})}readConfig(){let raw=readJson(join(this.dir,"config.json"));if(!raw||typeof raw.botOpenId!=="string"||!raw.botOpenId)return null;return{botOpenId:raw.botOpenId,botName:typeof raw.botName==="string"?raw.botName:"",...typeof raw.ownerOpenId==="string"&&raw.ownerOpenId?{ownerOpenId:raw.ownerOpenId}:{},...typeof raw.ownerName==="string"&&raw.ownerName?{ownerName:raw.ownerName}:{},allow:strings(raw.allow),tone:typeof raw.tone==="string"&&raw.tone?raw.tone:DEFAULT_TONE,savedAt:typeof raw.savedAt==="string"?raw.savedAt:""}}writeConfig(config){this.ensureDir(),writeJson(join(this.dir,"config.json"),config)}clearConfig(){let had=this.readConfig()!==null;return rmSync(join(this.dir,"config.json"),{force:!0}),rmSync(join(this.dir,"state.json"),{force:!0}),had}readState(){let raw=readJson(join(this.dir,"state.json")),agent=raw?.agent;return{...typeof agent?.taskId==="string"&&typeof agent.tab==="string"?{agent:{taskId:agent.taskId,tab:agent.tab}}:{},...typeof raw?.tone==="string"?{tone:raw.tone}:{},seen:strings(raw?.seen),pending:strings(raw?.pending)}}writeState(state){this.ensureDir(),writeJson(join(this.dir,"state.json"),{...state,seen:state.seen.slice(-SEEN_CAP)})}}var run=(args)=>spawnSync(LARK_CLI,[...args],{stdio:"inherit"}).status===0;async function connectLark(store,opts){let say=opts.say??(()=>{}),terminal={ok:!1,message:"rove lark connect"};if(spawnSync(LARK_CLI,["--version"],{stdio:"ignore"}).error)return{ok:!1,message:"npm i -g @larksuite/cli && rove lark connect"};if(!(await authStatus()).appId){if(!opts.interactive)return terminal;if(say("No Lark app yet: lark-cli will create one in your browser."),!run(["config","init","--new",...opts.brand?["--brand",opts.brand]:[]]))return{ok:!1,message:"lark-cli config init did not finish"}}let bot=await botInfo();if(!bot)return{ok:!1,message:`${LARK_CLI} api GET /open-apis/bot/v3/info --as bot`};let owner=await authStatus();if(!owner.userOpenId){if(!opts.interactive)return terminal;if(say("Sign in to Lark as yourself, so the bot knows who you are."),!run(["auth","login","--scope","auth:user.id:read"]))return{ok:!1,message:"lark-cli auth login did not finish"};owner=await authStatus()}let previous=store.readConfig(),config={botOpenId:bot.openId,botName:bot.name,...owner.userOpenId?{ownerOpenId:owner.userOpenId}:{},...owner.userName?{ownerName:owner.userName}:{},allow:(previous?.allow??[]).filter((id)=>id!==owner.userOpenId),tone:previous?.tone??DEFAULT_TONE,savedAt:previous?.savedAt||new Date().toISOString()};return store.writeConfig(config),{ok:!0,config}}var CLI_NAME=ROVE_PRODUCT_NAME,LARK_USAGE=[`Usage: ${CLI_NAME} lark <connect|disconnect|status|allow|deny|tone>`,"","Talk to your own Rove agent from Lark (\u98DE\u4E66): DM the bot or @ it in a group. The agent","answers in the thread and starts Rove tasks for real work. The daemon must be running.","Lark is reached through lark-cli (npm i -g @larksuite/cli), which keeps the app's credentials.","","Commands:"," connect [--brand feishu|lark] Set up lark-cli's app if there is none (opens the browser),"," check its bot, and let you (lark-cli's signed-in user) talk to it"," disconnect Stop listening; the agent's project and the lark-cli app stay"," status The bot, allowed senders and tone"," allow <open_id> Let another person talk to the agent (ids: the daemon log's refusals)"," deny <open_id> Revoke a person added with allow",` tone [text] How the agent sounds; no text resets it to "${DEFAULT_TONE}"`,""].join(`
4
4
  `);function fail(message){process.stderr.write(`${CLI_NAME} lark: ${message}
5
5
  `),process.exit(1)}async function connect(store,argv){let at=argv.indexOf("--brand"),brand=at>=0?argv[at+1]:void 0,say=(line)=>process.stdout.write(`${line}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-trfm70p5.js";import"./chunk-bzjef20g.js";import"./chunk-nsza72e4.js";import"./chunk-zsh70aef.js";import"./chunk-wje59khj.js";import"./chunk-8xsnpyer.js";import"./chunk-7fw390kp.js";import"./chunk-h58qkv3b.js";import"./chunk-pyzbrnnp.js";import"./chunk-4kepb278.js";import"./chunk-zcywdm3y.js";import"./chunk-36qsn2v8.js";import"./chunk-8ca4esh6.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-hdea2ss8.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-3h9psc5w.js";import"./chunk-5mhvjytn.js";import"./chunk-5p2hhjje.js";import"./chunk-zknvzer3.js";import"./chunk-tv0pxap3.js";import"./chunk-7998de5k.js";import"./chunk-sqpaqvk8.js";import"./chunk-z0wnws9w.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-6t1yxx9x.js";import"./chunk-mdx18vtz.js";import"./chunk-1d1xtdt3.js";import"./chunk-dscbf17z.js";import"./chunk-y0e28qha.js";import"./chunk-gze092t3.js";import"./chunk-wjmte4f0.js";import"./chunk-3vm6e0cf.js";import"./chunk-f1csqde7.js";import"./chunk-hy6b9ktj.js";import"./chunk-xtdr7b5h.js";import"./chunk-svtby8tp.js";import"./chunk-69cqwz53.js";import"./chunk-mqfvzdpr.js";import"./chunk-eeajq8px.js";import"./chunk-kpq28cbh.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-n5zdhshy.js";import"./chunk-ahfvmf90.js";import"./chunk-rxqdw6s5.js";import"./chunk-z9c475xb.js";import"./chunk-tn9gtf18.js";import"./chunk-ygdxgp8r.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-34bf7mnm.js";import"./chunk-2mcgd0ym.js";import"./chunk-f60hmm20.js";import"./chunk-w7zv47mp.js";import"./chunk-rr97z89e.js";import"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-navavqt2.js";import"./chunk-etfh8f4z.js";import"./chunk-ez623zqp.js";import"./chunk-w70anvs6.js";import"./chunk-4csg29es.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-h8qg9v95.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-grbrh92f.js";import"./chunk-0zs13rdq.js";import"./chunk-1wpwxcg9.js";import"./chunk-ypbh8ra4.js";import"./chunk-n6s1sba5.js";import"./chunk-cf0kpsdm.js";import"./chunk-nmt8peyf.js";import"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import"./chunk-eb2m2sf8.js";import"./chunk-78y80xe8.js";import"./chunk-wx77yjhc.js";import"./chunk-12qq8r81.js";import"./chunk-t9n6n7dy.js";import"./chunk-7b2x6nkj.js";import"./chunk-8acw5rmt.js";import"./chunk-96wm6gt4.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-jykxdtad.js";import"./chunk-65nm1v5h.js";import"./chunk-sckqk79z.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-8rxg12aj.js";import"./chunk-bzqjk9fb.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
2
+ import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-ms220a8e.js";import"./chunk-bzjef20g.js";import"./chunk-nsza72e4.js";import"./chunk-zsh70aef.js";import"./chunk-wje59khj.js";import"./chunk-8xsnpyer.js";import"./chunk-7fw390kp.js";import"./chunk-h58qkv3b.js";import"./chunk-pyzbrnnp.js";import"./chunk-4kepb278.js";import"./chunk-zcywdm3y.js";import"./chunk-36qsn2v8.js";import"./chunk-8ca4esh6.js";import"./chunk-q8ffd1pc.js";import"./chunk-rh5024pb.js";import"./chunk-hdea2ss8.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-3h9psc5w.js";import"./chunk-5mhvjytn.js";import"./chunk-5p2hhjje.js";import"./chunk-zknvzer3.js";import"./chunk-tv0pxap3.js";import"./chunk-fedby3c7.js";import"./chunk-jkxve6gr.js";import"./chunk-z0wnws9w.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-6t1yxx9x.js";import"./chunk-mdx18vtz.js";import"./chunk-22t7edqd.js";import"./chunk-dscbf17z.js";import"./chunk-y0e28qha.js";import"./chunk-gze092t3.js";import"./chunk-wjmte4f0.js";import"./chunk-3vm6e0cf.js";import"./chunk-f1csqde7.js";import"./chunk-hy6b9ktj.js";import"./chunk-xtdr7b5h.js";import"./chunk-svtby8tp.js";import"./chunk-69cqwz53.js";import"./chunk-mqfvzdpr.js";import"./chunk-eeajq8px.js";import"./chunk-kpq28cbh.js";import"./chunk-hpay0ax8.js";import"./chunk-tteswdyf.js";import"./chunk-n5zdhshy.js";import"./chunk-ahfvmf90.js";import"./chunk-rxqdw6s5.js";import"./chunk-z9c475xb.js";import"./chunk-tn9gtf18.js";import"./chunk-ygdxgp8r.js";import"./chunk-drhwacg1.js";import"./chunk-wrqv141p.js";import"./chunk-34bf7mnm.js";import"./chunk-2mcgd0ym.js";import"./chunk-f60hmm20.js";import"./chunk-w7zv47mp.js";import"./chunk-rr97z89e.js";import"./chunk-03ab55aq.js";import"./chunk-ve196r2v.js";import"./chunk-nr7c9q0j.js";import"./chunk-r478tzjz.js";import"./chunk-navavqt2.js";import"./chunk-etfh8f4z.js";import"./chunk-ez623zqp.js";import"./chunk-w70anvs6.js";import"./chunk-4csg29es.js";import"./chunk-fxpbaff2.js";import"./chunk-dmzg9zdc.js";import"./chunk-h8qg9v95.js";import"./chunk-kg9kmwt9.js";import"./chunk-9k0r47z3.js";import"./chunk-grbrh92f.js";import"./chunk-0zs13rdq.js";import"./chunk-1wpwxcg9.js";import"./chunk-ypbh8ra4.js";import"./chunk-n6s1sba5.js";import"./chunk-cf0kpsdm.js";import"./chunk-nmt8peyf.js";import"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import"./chunk-g875xaf6.js";import"./chunk-78y80xe8.js";import"./chunk-wx77yjhc.js";import"./chunk-12qq8r81.js";import"./chunk-t9n6n7dy.js";import"./chunk-7b2x6nkj.js";import"./chunk-8acw5rmt.js";import"./chunk-96wm6gt4.js";import"./chunk-6hjt5an9.js";import"./chunk-ptyqj15s.js";import"./chunk-jykxdtad.js";import"./chunk-65nm1v5h.js";import"./chunk-sckqk79z.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-8rxg12aj.js";import"./chunk-bzqjk9fb.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import"./chunk-a6z2ggxd.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-ksx55wt3.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RELEASE_CHANNELS,channelOf}from"./chunk-eb2m2sf8.js";import{loadStateFile,patchStateFile}from"./chunk-12qq8r81.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
2
+ import{RELEASE_CHANNELS,channelOf}from"./chunk-g875xaf6.js";import{loadStateFile,patchStateFile}from"./chunk-12qq8r81.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
3
3
  export{UPDATE_CHANNEL_KEY,UPDATE_NOTIFY_KEY,normalizeReleaseChannel,preferredReleaseChannel,updateNotifyEnabled,rememberReleaseChannel,updateDelayHours};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{stampResetGate}from"./chunk-7y9n0rdq.js";import{stopLegacyTmux}from"./chunk-gkdfct7t.js";import{clearFrozenSessions}from"./chunk-69cqwz53.js";import"./chunk-mqfvzdpr.js";import{errorMessage}from"./chunk-0zs13rdq.js";import{stopDaemonProcess}from"./chunk-cf0kpsdm.js";import"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import"./chunk-eb2m2sf8.js";import"./chunk-12qq8r81.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import{defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyFreezeDir,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-gvxchzch.js";import{kvStatePath,legacyRoveKvStatePath,legacyRoveStateDir,roveStateDir}from"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{unlink}from"fs/promises";import{join}from"path";import{createInterface}from"readline";var CLI_NAME=ROVE_PRODUCT_NAME;function printUsage(out){out.write([`Usage: ${CLI_NAME} reset [--hard] [--yes]`,"","Recover a wedged install: stop the daemon, Hosted PTY host, and any pre-v0.8 tmux sessions.","This ends background terminal and engine sessions; the next launch starts fresh.","Never touches your git worktrees.","","Options:"," --hard Also DELETE the task index and the whole settings file"," (saved projects, custom engines, theme, language, onboarding)"," -y, --yes Skip the interactive confirmation. REQUIRED without a terminal;"," a non-interactive run without it exits 2 and changes nothing."," -h, --help Print this help",""].join(`
2
+ import{stampResetGate}from"./chunk-jps50xyw.js";import{stopLegacyTmux}from"./chunk-gkdfct7t.js";import{clearFrozenSessions}from"./chunk-69cqwz53.js";import"./chunk-mqfvzdpr.js";import{errorMessage}from"./chunk-0zs13rdq.js";import{stopDaemonProcess}from"./chunk-cf0kpsdm.js";import"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import"./chunk-g875xaf6.js";import"./chunk-12qq8r81.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import{defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyFreezeDir,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-gvxchzch.js";import{kvStatePath,legacyRoveKvStatePath,legacyRoveStateDir,roveStateDir}from"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";import{unlink}from"fs/promises";import{join}from"path";import{createInterface}from"readline";var CLI_NAME=ROVE_PRODUCT_NAME;function printUsage(out){out.write([`Usage: ${CLI_NAME} reset [--hard] [--yes]`,"","Recover a wedged install: stop the daemon, Hosted PTY host, and any pre-v0.8 tmux sessions.","This ends background terminal and engine sessions; the next launch starts fresh.","Never touches your git worktrees.","","Options:"," --hard Also DELETE the task index and the whole settings file"," (saved projects, custom engines, theme, language, onboarding)"," -y, --yes Skip the interactive confirmation. REQUIRED without a terminal;"," a non-interactive run without it exits 2 and changes nothing."," -h, --help Print this help",""].join(`
3
3
  `))}function taskCount(path){try{let parsed=JSON.parse(readFileSync(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function stateSummary(path){let parsed;try{parsed=JSON.parse(readFileSync(path,"utf8"))}catch{return[]}let count=(key)=>Array.isArray(parsed[key])?parsed[key].length:0,lines=[` saved projects: ${count("savedRepos")}`,` custom engines: ${count("customEngineIds")} (their launch commands live here and nowhere else)`],present=[["activeTheme","theme"],["defaultVendor","default engine"],["locale","language"],["onboarded","onboarding (the wizard runs again)"]].filter(([key])=>parsed[key]!==void 0).map(([,label])=>label);if(present.length>0)lines.push(` also set: ${present.join(", ")}`);return lines.push(` ${Object.keys(parsed).length} setting(s) in total`),lines}async function confirmTty(prompt){let readline=createInterface({input:process.stdin,output:process.stdout});try{let answer=await new Promise((resolve)=>readline.question(prompt,resolve));return/^y(es)?$/i.test(answer.trim())}finally{readline.close()}}async function removeStateFile(path,label){try{await unlink(path),console.log(` removed ${label} (${path})`)}catch(err){if(err.code==="ENOENT")console.log(` ${label}: already absent`);else throw Error(`failed to remove ${label} (${path}): ${errorMessage(err)}`)}}async function runResetSubcommand(argv){if(argv.some((arg)=>arg==="--help"||arg==="-h"||arg==="help")){printUsage(process.stdout);return}let known=new Set(["--hard","--yes","-y"]),unknown=argv.find((arg)=>!known.has(arg));if(unknown!==void 0)process.stderr.write(`${CLI_NAME} reset: unknown argument "${unknown}"
4
4
 
5
5
  `),printUsage(process.stderr),process.exit(2);let hard=argv.includes("--hard"),yes=argv.includes("--yes")||argv.includes("-y"),daemonSocket=defaultDaemonSocketPath(),tasksPath=join(roveStateDir(),"tasks.json"),legacyTasksPath=join(legacyRoveStateDir(),"tasks.json"),statePath=kvStatePath(),legacyStatePath=legacyRoveKvStatePath();if(console.log(`${CLI_NAME} reset will:`),console.log(" \u2022 stop the Rove daemon (graceful \u2192 SIGTERM \u2192 SIGKILL)"),console.log(` \u2022 remove its socket + pidfile (${daemonSocket})`),console.log(" \u2022 stop the standalone Hosted PTY host and all background terminal/engine sessions"),console.log(" \u2022 stop any pre-v0.8 tmux sessions after SIGTERM-ing their pane process groups"),hard){let count=taskCount(tasksPath)??taskCount(legacyTasksPath);console.log(` \u2022 DELETE the task index${count===null?"":` (${count} task(s))`} \u2014 ${tasksPath}`),console.log(` \u2022 DELETE the whole settings file \u2014 ${statePath}`);for(let line of stateSummary(statePath))console.log(line);console.log(" \u2022 DELETE the pre-Rove task/UI indexes too, so migration cannot restore reset state")}if(console.log(" \u2022 NOT touch your git worktrees under ~/.rove/worktrees/ or existing repo-local roots"),!hard)console.log(" (your task list, settings & worktrees are kept \u2014 add --hard to also delete the task index and settings file)");if(!yes){if(!process.stdin.isTTY){console.log(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ACP_PROTOCOL_VERSION,acpSessionFilePath,activityFromAcpStopReason,activityFromAcpUpdate,appendAcpTranscriptRecord,extractAcpText}from"./chunk-ypbh8ra4.js";import{connectIfRunning}from"./chunk-n6s1sba5.js";import"./chunk-cf0kpsdm.js";import"./chunk-nmt8peyf.js";import"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import{CURRENT_VERSION}from"./chunk-eb2m2sf8.js";import{flagValue,switchFlag}from"./chunk-78y80xe8.js";import"./chunk-bzqjk9fb.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import{isObject}from"./chunk-a6z2ggxd.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawn}from"child_process";import{existsSync}from"fs";import{createInterface}from"readline";class AcpClient{input;output;callbacks;nextId=1;buffer="";closed=!1;pending=new Map;onData;onEnd;onError;constructor(input,output,callbacks={}){this.input=input;this.output=output;this.callbacks=callbacks;this.onData=(chunk)=>this.consume(typeof chunk==="string"?chunk:chunk.toString("utf8")),this.onEnd=()=>this.finish(),this.onError=(err)=>this.finish(err),this.input.on("data",this.onData),this.input.on("end",this.onEnd),this.input.on("close",this.onEnd),this.input.on("error",this.onError)}initialize(clientInfo={name:"rove",version:CURRENT_VERSION}){return this.request("initialize",{protocolVersion:ACP_PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo})}newSession(cwd,mcpServers=[]){return this.request("session/new",{cwd,mcpServers})}async loadSession(sessionId,cwd,mcpServers=[]){await this.request("session/load",{sessionId,cwd,mcpServers})}async setModel(sessionId,modelId){await this.request("session/set_model",{sessionId,modelId})}prompt(sessionId,text){return this.request("session/prompt",{sessionId,prompt:[{type:"text",text}]})}cancel(sessionId){this.notify("session/cancel",{sessionId})}request(method,params){if(this.closed)return Promise.reject(Error(`ACP client is closed (${method})`));let id=this.nextId++;return new Promise((resolve,reject)=>{this.pending.set(id,{resolve:(v)=>resolve(v),reject}),this.writeLine({jsonrpc:"2.0",id,method,...params!==void 0?{params}:{}})})}notify(method,params){if(this.closed)return;this.writeLine({jsonrpc:"2.0",method,...params!==void 0?{params}:{}})}close(){this.finish()}writeLine(frame){try{this.output.write(`${JSON.stringify(frame)}
2
+ import{ACP_PROTOCOL_VERSION,acpSessionFilePath,activityFromAcpStopReason,activityFromAcpUpdate,appendAcpTranscriptRecord,extractAcpText}from"./chunk-ypbh8ra4.js";import{connectIfRunning}from"./chunk-n6s1sba5.js";import"./chunk-cf0kpsdm.js";import"./chunk-nmt8peyf.js";import"./chunk-k34h9e47.js";import"./chunk-37nrg1nc.js";import{CURRENT_VERSION}from"./chunk-g875xaf6.js";import{flagValue,switchFlag}from"./chunk-78y80xe8.js";import"./chunk-bzqjk9fb.js";import"./chunk-4y536nwm.js";import"./chunk-pn5ygqn6.js";import{isObject}from"./chunk-a6z2ggxd.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawn}from"child_process";import{existsSync}from"fs";import{createInterface}from"readline";class AcpClient{input;output;callbacks;nextId=1;buffer="";closed=!1;pending=new Map;onData;onEnd;onError;constructor(input,output,callbacks={}){this.input=input;this.output=output;this.callbacks=callbacks;this.onData=(chunk)=>this.consume(typeof chunk==="string"?chunk:chunk.toString("utf8")),this.onEnd=()=>this.finish(),this.onError=(err)=>this.finish(err),this.input.on("data",this.onData),this.input.on("end",this.onEnd),this.input.on("close",this.onEnd),this.input.on("error",this.onError)}initialize(clientInfo={name:"rove",version:CURRENT_VERSION}){return this.request("initialize",{protocolVersion:ACP_PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo})}newSession(cwd,mcpServers=[]){return this.request("session/new",{cwd,mcpServers})}async loadSession(sessionId,cwd,mcpServers=[]){await this.request("session/load",{sessionId,cwd,mcpServers})}async setModel(sessionId,modelId){await this.request("session/set_model",{sessionId,modelId})}prompt(sessionId,text){return this.request("session/prompt",{sessionId,prompt:[{type:"text",text}]})}cancel(sessionId){this.notify("session/cancel",{sessionId})}request(method,params){if(this.closed)return Promise.reject(Error(`ACP client is closed (${method})`));let id=this.nextId++;return new Promise((resolve,reject)=>{this.pending.set(id,{resolve:(v)=>resolve(v),reject}),this.writeLine({jsonrpc:"2.0",id,method,...params!==void 0?{params}:{}})})}notify(method,params){if(this.closed)return;this.writeLine({jsonrpc:"2.0",method,...params!==void 0?{params}:{}})}close(){this.finish()}writeLine(frame){try{this.output.write(`${JSON.stringify(frame)}
3
3
  `)}catch(err){this.finish(err instanceof Error?err:Error(String(err)))}}consume(text){this.buffer+=text;for(;;){let nl=this.buffer.indexOf(`
4
4
  `);if(nl<0)break;let line=this.buffer.slice(0,nl).trim();if(this.buffer=this.buffer.slice(nl+1),!line)continue;this.handleLine(line)}}handleLine(line){let raw;try{raw=JSON.parse(line)}catch{return}if(!isObject(raw))return;let hasId=typeof raw.id==="number"||typeof raw.id==="string",hasMethod=typeof raw.method==="string";if(hasId&&!hasMethod){let pending=this.pending.get(raw.id);if(!pending)return;if(this.pending.delete(raw.id),isObject(raw.error)){let msg=typeof raw.error.message==="string"?raw.error.message:"ACP RPC error",code=typeof raw.error.code==="number"?raw.error.code:-32000;pending.reject(Error(`ACP error ${code}: ${msg}`))}else pending.resolve(raw.result);return}if(hasMethod&&!hasId){if(raw.method==="session/update"&&isObject(raw.params)){let sessionId=typeof raw.params.sessionId==="string"?raw.params.sessionId:"",update=raw.params.update;if(isObject(update)&&typeof update.sessionUpdate==="string")this.callbacks.onUpdate?.(sessionId,update)}return}if(hasMethod&&hasId)this.handleInboundRequest(raw.id,raw.method,raw.params)}async handleInboundRequest(id,method,params){if(method==="session/request_permission"&&isObject(params)){let req={sessionId:typeof params.sessionId==="string"?params.sessionId:"",...isObject(params.toolCall)?{toolCall:params.toolCall}:{},options:Array.isArray(params.options)?params.options:[]};try{let outcome=this.callbacks.onPermissionRequest?await this.callbacks.onPermissionRequest(req):{outcome:"cancelled"};this.writeLine({jsonrpc:"2.0",id,result:{outcome}})}catch(err){this.writeLine({jsonrpc:"2.0",id,error:{code:-32000,message:err instanceof Error?err.message:String(err)}})}return}this.writeLine({jsonrpc:"2.0",id,error:{code:-32601,message:`Method not supported by Rove ACP client: ${method}`}})}finish(err){if(this.closed)return;this.closed=!0,this.input.off("data",this.onData),this.input.off("end",this.onEnd),this.input.off("close",this.onEnd),this.input.off("error",this.onError);let reason=err??Error("ACP agent closed the connection");for(let pending of this.pending.values())pending.reject(reason);this.pending.clear(),this.callbacks.onClose?.(err)}}var TRANSCRIPT_UPDATES=new Set(["agent_message_chunk","agent_thought_chunk","user_message_chunk","tool_call","tool_call_update"]);function parseAcpBridgeArgs(argv){let sep=argv.findIndex((token)=>token==="--"),bridgeFlags=sep>=0?argv.slice(0,sep):[],agentArgv=sep>=0?argv.slice(sep+1):argv,resumeSessionId=flagValue(bridgeFlags,"--resume"),initialPrompt=flagValue(bridgeFlags,"--prompt"),model=flagValue(bridgeFlags,"--model"),bypassPermissions=switchFlag(bridgeFlags,"--bypass-permissions")===!0;return{...resumeSessionId?{resumeSessionId}:{},...initialPrompt?{initialPrompt}:{},...model?{model}:{},bypassPermissions,agentArgv}}function isTranscriptAcpUpdate(update){return TRANSCRIPT_UPDATES.has(update.sessionUpdate)}function pickAutoApproveOption(options){let preferred=options.find((o)=>o.kind==="allow_always")??options.find((o)=>o.kind==="allow_once")??options[0];return preferred?{outcome:"selected",optionId:preferred.optionId}:{outcome:"cancelled"}}function osc7501(state,extra=""){process.stdout.write(`\x1B]7501;state=${state}${extra}\x07`)}function oscTitle(title){process.stdout.write(`\x1B]0;${title}\x07`)}function createDaemonReporter(cwd){let taskId=process.env.ROVE_TASK_ID?.trim(),tabId=process.env.ROVE_TAB_ID?.trim(),rpc=null,connecting=null,ensureClient=async()=>{if(!taskId)return null;if(rpc)return rpc;if(!connecting)connecting=connectIfRunning().then((client)=>{return rpc=client,client}).catch(()=>null).finally(()=>{connecting=null});return connecting};return{async report(kind,sessionId,transcriptPath,detail){let client=await ensureClient();if(!client||!taskId)return;try{await client.request("engine.reportEvent",{taskId,...tabId?{tabId}:{},cwd,engine:"acp",kind,...sessionId?{sessionId}:{},...transcriptPath?{transcriptPath}:{},...detail?{detail}:{}})}catch{rpc?.close(),rpc=null}},close(){rpc?.close(),rpc=null}}}async function runAcpBridgeSubcommand(argv){let parsed=parseAcpBridgeArgs(argv),[cmd,...cmdArgs]=parsed.agentArgv;if(!cmd)process.stderr.write("rove _acp-bridge: missing agent command after `--`\n"),process.exit(2);let cwd=process.cwd(),child=spawn(cmd,cmdArgs,{cwd,stdio:["pipe","pipe","inherit"],env:process.env});if(!child.stdout||!child.stdin)process.stderr.write(`rove _acp-bridge: failed to open stdio pipes for ${cmd}
5
5
  `),process.exit(1);let reporter=createDaemonReporter(cwd),activeSessionId="",transcriptPath="",turnActive=!1,suppressReplay=!1,awaitingPermission=null,streamedNewline=!0,writeOut=(text)=>{if(!text)return;process.stdout.write(text),streamedNewline=text.endsWith(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{FEEDBACK_KINDS,isFeedbackKind,submitFeedback}from"./chunk-7998de5k.js";import"./chunk-ve196r2v.js";import"./chunk-ez623zqp.js";import"./chunk-w70anvs6.js";import"./chunk-4csg29es.js";import"./chunk-h8qg9v95.js";import"./chunk-1wpwxcg9.js";import"./chunk-eb2m2sf8.js";import"./chunk-12qq8r81.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.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>) [--kind bug|idea|question]`,"","File a GitHub issue on the Rove repository using the GitHub CLI. Rove appends its","version, OS, install kind and default engine to the body.","","Requires:"," gh auth login","Without a signed-in gh, prints a prefilled new-issue link to open instead.","","Options:"," --title <text> Issue title"," --body <text> Issue body"," --body-file <path> Read the issue body from a file; use - for stdin"," --kind <kind> bug (default, label bug), idea (enhancement) or question"," -h, --help Print this help",""].join(`
2
+ import{FEEDBACK_KINDS,isFeedbackKind,submitFeedback}from"./chunk-fedby3c7.js";import"./chunk-ve196r2v.js";import"./chunk-ez623zqp.js";import"./chunk-w70anvs6.js";import"./chunk-4csg29es.js";import"./chunk-h8qg9v95.js";import"./chunk-1wpwxcg9.js";import"./chunk-g875xaf6.js";import"./chunk-12qq8r81.js";import"./chunk-w2czjjxy.js";import"./chunk-8q0nmdh3.js";import"./chunk-pn5ygqn6.js";import"./chunk-spr6z826.js";import"./chunk-ydxq51g3.js";import"./chunk-yt15y085.js";import"./chunk-gvxchzch.js";import"./chunk-pzbcbmm4.js";import{ROVE_PRODUCT_NAME}from"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.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>) [--kind bug|idea|question]`,"","File a GitHub issue on the Rove repository using the GitHub CLI. Rove appends its","version, OS, install kind and default engine to the body.","","Requires:"," gh auth login","Without a signed-in gh, prints a prefilled new-issue link to open instead.","","Options:"," --title <text> Issue title"," --body <text> Issue body"," --body-file <path> Read the issue body from a file; use - for stdin"," --kind <kind> bug (default, label bug), idea (enhancement) or question"," -h, --help Print this help",""].join(`
3
3
  `);function usageError(message){process.stderr.write(`${CLI_NAME} feedback: ${message}
4
4
 
5
5
  ${FEEDBACK_USAGE}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{isPathLikeArg,runOpenDirectory}from"./chunk-5jzyrbzb.js";import"./chunk-grbrh92f.js";import"./chunk-pn5ygqn6.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runOpenDirectory,isPathLikeArg};
2
+ import{isPathLikeArg,runOpenDirectory}from"./chunk-eynv3yw1.js";import"./chunk-grbrh92f.js";import"./chunk-pn5ygqn6.js";import"./chunk-pzbcbmm4.js";import"./chunk-4ctx6hst.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{runOpenDirectory,isPathLikeArg};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{FINISHED_ALERTS_KEY,MUTED_TASKS_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,TOAST_DURATION_MS,addUnread,armPrefixNow,bindingReachability,bumpKeymapVersion,configurePrefix,currentPrefixConfiguration,dispatchKeyEvent,ensureContrastInts,findBinding,inputPassthroughReachable,insertRegistration,invokeArmedPrefixAction,isCtrlModifierKeyName,isKittyModifierKeyName,mutedTaskIds,osc9,persistedSoundVolume,prefixHudHideDirect,prefixHudShowDirect,readKeybindingsFile,removeUnread,resetKeybindingsFileCache,resetKeymapToDefaults,resetPrefixConfiguration,resetPrefixState,resolveUserKeybindings,restoreTerminal,shouldAlert,shouldPlaySound,shouldShowToast,turnHueInts,writeKeybindingEdits}from"./chunk-z98zs1h3.js";import{$Fragment,$jsx,$jsxs,createRoot2,flushSync2,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{RemoteOrchestrator}from"./chunk-ha312q39.js";import{updaterShell,updaterShellFailureHint}from"./chunk-41x2efc9.js";import{TERMINAL_TABS_PREFIX}from"./chunk-6t1yxx9x.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,readPersistedUiPrefs,resolveThemeMode}from"./chunk-n5zdhshy.js";import{isThemePackage,loadUserThemes,parseRgbLiteral}from"./chunk-ahfvmf90.js";import{tildify}from"./chunk-grbrh92f.js";import{connectIfRunning}from"./chunk-n6s1sba5.js";import{CURRENT_VERSION}from"./chunk-eb2m2sf8.js";import{loadStateFile,readStateFileStrict,replaceStateFile,updateStateFile}from"./chunk-12qq8r81.js";import{localeState,setLocaleLang,t}from"./chunk-t9n6n7dy.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-7b2x6nkj.js";import{isLocaleId}from"./chunk-8acw5rmt.js";import{installClientCrashHandlers,logClient,logClientError,setClientLogContext}from"./chunk-4y536nwm.js";import{kvStatePath}from"./chunk-pzbcbmm4.js";import{__toESM}from"./chunk-91sykzqq.js";import{RGBA as RGBA4}from"@opentui/core";var import_react3=__toESM(require_react_production(),1);import{RGBA as RGBA3}from"@opentui/core";import{RGBA}from"@opentui/core";var BREATH_TICKS=30,SPEED_MIN=0.2,SPEED_SWING=0.9333333333333333,INK_FLOOR=0.3;function breathLevel(tick){return 0.5-0.5*Math.cos(2*Math.PI*tick/BREATH_TICKS)}function breathPhase(tick){let wave=tick/2-BREATH_TICKS/(4*Math.PI)*Math.sin(2*Math.PI*tick/BREATH_TICKS);return SPEED_MIN*tick+SPEED_SWING*wave}function breathGlyph(frames,tick){let index=Math.floor(breathPhase(tick)+0.000000001)%frames.length;return frames[index]??frames[0]??""}function mixInk(accent,muted,share){if(accent.intent!=="rgb"||muted.intent!=="rgb")return accent;let[ar,ag,ab,aa]=accent.toInts(),[mr,mg,mb]=muted.toInts(),mix=(a,m)=>Math.round(m+(a-m)*share);return RGBA.fromInts(mix(ar,mr),mix(ag,mg),mix(ab,mb),aa)}function breathColor(accent,muted,tick){return mixInk(accent,muted,INK_FLOOR+(1-INK_FLOOR)*breathLevel(tick))}var ints=(c)=>c.toInts(),rgba=([r,g,b,a])=>RGBA.fromInts(r,g,b,a);function turnHue(accent,deg,lightness=1,chroma=1){if(accent.intent!=="rgb")return accent;return rgba(turnHueInts(ints(accent),deg,lightness,chroma))}import{RGBA as RGBA2}from"@opentui/core";var HOST_TEXT_MIN_CONTRAST=4.5;function ensureContrast(fg,bg,minRatio=HOST_TEXT_MIN_CONTRAST){let from=fg.toInts(),to=ensureContrastInts(from,bg.toInts(),minRatio);return to===from?fg:RGBA2.fromInts(to[0],to[1],to[2],to[3])}function resolveTheme(theme,mode="dark"){let defs=theme.defs??{};function resolve(c,chain=[]){if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA3.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA3.fromHex(c);let rgb=parseRgbLiteral(c);if(rgb)return RGBA3.fromInts(rgb.r,rgb.g,rgb.b,rgb.a);if(chain.includes(c))return RGBA3.fromInts(0,0,0);let next=defs[c]??theme.theme[c];if(next===void 0)return RGBA3.fromInts(0,0,0);return resolve(next,[...chain,c])}return resolve(c[mode],chain)}let out={};for(let[k,v]of Object.entries(theme.theme))out[k]=resolve(v);let text=out.text??RGBA3.fromHex("#ffffff"),background=out.background??RGBA3.fromHex("#000000");return{...{primary:out.primary??text,secondary:out.secondary??text,accent:out.accent??out.primary??text,error:out.error??text,warning:out.warning??text,warningOnHost:out.warning??text,success:out.success??text,info:out.info??text,text,textMuted:out.textMuted??text,background,backgroundPanel:out.backgroundPanel??background,backgroundElement:out.backgroundElement??background,backgroundMenu:out.backgroundMenu??out.backgroundElement??background,backgroundDialog:out.backgroundDialog??out.backgroundPanel??background,border:out.border??text,borderActive:out.borderActive??out.border??text,borderSubtle:out.borderSubtle??out.border??text,diffAdded:out.diffAdded??out.success??text,diffRemoved:out.diffRemoved??out.error??text,diffContext:out.diffContext??out.textMuted??text,diffHunkHeader:out.diffHunkHeader??out.textMuted??text,diffAddedBg:out.diffAddedBg??background,diffRemovedBg:out.diffRemovedBg??background,selectedListItemText:out.selectedListItemText??background},...out}}function applyDisplayOverlay(base,focusAccent,transparentBackground,hostBackground){let v={...base,focusAccent:base[focusAccent]??base.primary,warningOnHost:base.warning};if(!transparentBackground)return v;let[backgroundR,backgroundG,backgroundB]=base.background.toInts(),[panelR,panelG,panelB]=base.backgroundPanel.toInts(),transparent={...v,background:RGBA3.fromInts(backgroundR,backgroundG,backgroundB,0),backgroundPanel:RGBA3.fromInts(panelR,panelG,panelB,0)};if(!hostBackground)return transparent;return{...transparent,text:ensureContrast(transparent.text,hostBackground),textMuted:ensureContrast(transparent.textMuted,hostBackground),warningOnHost:ensureContrast(transparent.warning,hostBackground)}}function diffInks(theme,colorblind){let added=(ink)=>colorblind?turnHue(ink,60,1,0.71):ink;return{added:added(theme.diffAdded),removed:theme.diffRemoved,addedBg:added(theme.diffAddedBg),removedBg:theme.diffRemovedBg}}var import_react=__toESM(require_react_production(),1);function useAccessor(state){return import_react.useSyncExternalStore(state.subscribe,state.get,state.get)}var noSubscribe=()=>()=>{};function useAccessorWhile(state,live){return import_react.useSyncExternalStore(live?state.subscribe:noSubscribe,state.get,state.get)}var store=createStateCell({themes:{...BUNDLED_THEMES},active:DEFAULT_THEME,mode:DEFAULT_THEME_MODE,transparentBackground:!0,focusAccent:"primary"});function listThemes(){return Object.keys(store.get().themes)}function themePackageNames(){return Object.entries(store.get().themes).filter(([,theme])=>isThemePackage(theme)).map(([name])=>name)}function hasTheme(name){return Boolean(store.get().themes[name])}function addTheme(name,theme){if(!name)return!1;if(!theme||typeof theme!=="object"||!theme.theme)return!1;return store.update((s)=>({...s,themes:{...s.themes,[name]:theme}})),!0}function selectedTheme(){return store.get().active}function setTheme(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0}function transparentBackground(){return store.get().transparentBackground}function setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))}function focusAccent(){return store.get().focusAccent}function setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))}function themeMode(){return store.get().mode}function setThemeMode(mode){store.update((s)=>({...s,mode}))}var ThemeContext=import_react3.createContext(null),HOST_PALETTE_QUERY_TIMEOUT_MS=2000;function resolveActive(state,mode){let active=state.themes[state.active];if(active)return resolveTheme(active,mode);let fallback=state.themes[DEFAULT_THEME]??Object.values(state.themes)[0];if(!fallback)return resolveTheme({theme:{background:"#000000",text:"#ffffff"}},mode);return resolveTheme(fallback,mode)}function useHostThemeMode(renderer){let[mode,setMode]=import_react3.useState(()=>renderer?.themeMode??null);return import_react3.useEffect(()=>{if(!renderer)return;let onChange=(next)=>setMode(next);return renderer.on("theme_mode",onChange),setMode(renderer.themeMode),()=>{renderer.off("theme_mode",onChange)}},[renderer]),mode}function ThemeProvider(props){import_react3.useMemo(()=>{store.update((s)=>({...s,mode:props.mode??s.mode,active:props.theme&&s.themes[props.theme]?props.theme:s.active}))},[]);let state=useAccessor(store),renderer=useRenderer(),hostMode=useHostThemeMode(renderer),mode=resolveThemeMode(state.mode,hostMode),[hostBackground,setHostBackground]=import_react3.useState(null);import_react3.useEffect(()=>{if(!state.transparentBackground)return;if(renderer?.screenMode==="split-footer")return;if(!renderer)return;let cancelled=!1;return renderer.getPalette({timeout:HOST_PALETTE_QUERY_TIMEOUT_MS}).then((colors)=>{if(cancelled||!colors.defaultBackground)return;setHostBackground(RGBA4.fromHex(colors.defaultBackground))}).catch(()=>{}),()=>{cancelled=!0}},[renderer,state.transparentBackground]);let theme=import_react3.useMemo(()=>applyDisplayOverlay(resolveActive(state,mode),state.focusAccent,state.transparentBackground,hostBackground??void 0),[state,mode,hostBackground]);import_react3.useEffect(()=>{if(renderer?.screenMode==="split-footer")return;renderer?.setBackgroundColor(theme.background??RGBA4.fromInts(0,0,0))},[renderer,theme]);let value=import_react3.useMemo(()=>({theme,selected:state.active,transparentBackground:state.transparentBackground,focusAccent:state.focusAccent,modePreference:state.mode,mode:()=>mode,set(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0},setMode(next){store.update((s)=>({...s,mode:next}))},setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))},setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))},preview:(options)=>{let resolvedMode=resolveThemeMode(options.themeMode,hostMode),base=options.themeOverride?resolveTheme(options.themeOverride,resolvedMode):resolveActive({...state,active:options.themeName},resolvedMode);return applyDisplayOverlay(base,options.focusAccent,options.transparentBackground,hostBackground??void 0)},all:listThemes,has:hasTheme}),[theme,state,mode,hostMode,hostBackground]);return $jsx(ThemeContext.Provider,{value,children:props.children})}function useTheme(){let value=import_react3.useContext(ThemeContext);if(!value)throw Error("Theme context must be used within a context provider");return value}var import_react4=__toESM(require_react_production(),1);function useLang(){return useAccessor(localeState())}function useT(){let lang=useLang();return import_react4.useCallback((key,params)=>t(key,params),[lang])}var CTRL_HOLD_THRESHOLD_MS=400;function createCtrlHoldDetector(callbacks){let state={kind:"idle"},held=new Set,reset=()=>{if(state.kind==="pending")clearTimeout(state.timer);if(state.kind==="visible")callbacks.onHide();state={kind:"idle"}},cancel=()=>{reset(),held.clear()};return{keypress:(event)=>{if(!isCtrlModifierKeyName(event.name)){cancel();return}if(event.eventType==="repeat"&&held.has(event.name))return;if(event.eventType!=="press")return;if(held.add(event.name),state.kind!=="idle")return;state={kind:"pending",timer:setTimeout(()=>{state={kind:"visible"},callbacks.onReveal()},CTRL_HOLD_THRESHOLD_MS)}},keyrelease:(event)=>{if(!isCtrlModifierKeyName(event.name)||event.eventType!=="release")return;if(held.delete(event.name),held.size===0)reset()},cancel}}var MODIFIER_GLYPH={ctrl:"\u2303",control:"\u2303",alt:"\u2325",opt:"\u2325",option:"\u2325",shift:"\u21E7",cmd:"\u2318",command:"\u2318",meta:"\u2318",super:"\u2318"},KEY_GLYPH={enter:"\u23CE",return:"\u23CE",esc:"\u238B",escape:"\u238B",space:"\u2423",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",backspace:"\u232B",delete:"\u2326",del:"\u2326",pgup:"\u21DE",pageup:"\u21DE",pgdn:"\u21DF",pagedown:"\u21DF",home:"\u2196",end:"\u2198"};function formatKey(k,upper){if(k.includes("/"))return k.split("/").map((part)=>formatKey(part,upper)).join("/");let low=k.toLowerCase();if(low==="tab")return"tab";let named=KEY_GLYPH[low];if(named)return named;if(/^f\d{1,2}$/.test(low))return low.toUpperCase();if(!upper)return k;if(/^[a-z]$/.test(low))return k.toUpperCase();return k.replace(/[a-z]+/gi,(run)=>run.toUpperCase())}function formatChord(chord,prefixGlyph="\u2303A"){let s=chord.trim();if(!s)return s;let pm=/^prefix\s+(.+)$/i.exec(s);if(pm){let suffix=pm[1]??"";return`${prefixGlyph} ${suffix.includes("+")?formatChord(suffix,prefixGlyph):formatKey(suffix,!0)}`}let parts=s.split("+");if(parts.length===1)return formatKey(parts[0]??"",!1);let key=parts[parts.length-1]??"";return`${parts.slice(0,-1).map((p)=>MODIFIER_GLYPH[p.toLowerCase().trim()]??p).join("")} ${formatKey(key,!0)}`}var DIRECT_GUIDE_PREFIX_ACTION_ID="prefix.moreCommands",CTRL_FOLLOW_UP_CHORD=/^ctrl\+[^+]+$/;function ctrlFollowUpKey(chord){return CTRL_FOLLOW_UP_CHORD.test(chord)?chord.slice(5):null}function shortcutCaption(input){let binding=findBinding(input.bindingId);if(!binding)return null;if(input.reachability.direct.has(input.bindingId)){let direct=binding.keys[0];if(direct)return formatChord(direct)}if(input.prefixKey&&input.reachability.prefix.has(input.bindingId)){let stroke=binding.prefixKeys?.[0];if(stroke)return`${formatChord(input.prefixKey)} ${formatChord(stroke)}`}return null}function directGuideOptions(reachability,prefixKey){let options=RoveKeymap.filter((binding)=>reachability.direct.has(binding.id)).flatMap((binding)=>{let strokes=binding.keys.flatMap((chord)=>ctrlFollowUpKey(chord)??[]);if(strokes.length>2)return[{stroke:`${strokes[0]}-${strokes.at(-1)}`,action:binding.id}];return strokes.map((stroke)=>({stroke,action:binding.id}))}),prefixStroke=prefixKey?ctrlFollowUpKey(prefixKey):null;if(prefixStroke&&reachability.prefix.size>0)options.push({stroke:prefixStroke,action:DIRECT_GUIDE_PREFIX_ACTION_ID});return options}var import_react7=__toESM(require_react_production(),1);function availableActions(stack){let seen=new Set,actions=[],passthrough=inputPassthroughReachable(stack);for(let registration of[...stack].reverse()){let config=registration.config();if(config.enabled===!1)continue;for(let binding of config.bindings){if(binding.prefix&&currentPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}var import_react5=__toESM(require_react_production(),1);function useLatest(value){let ref=import_react5.useRef(value);return ref.current=value,ref}var ModalScopeContext=import_react7.createContext(null),nextId=1,stack=[],installedRenderer=null,installed=null,listener=null,releaseListener=null,ctrlHoldDetector=null,supersededRenderers=new WeakSet;function ensureInstalled(renderer){if(!renderer)throw Error("useBindings: no renderer in scope; call inside a component rendered by @opentui/react.");if(installedRenderer===renderer)return;if(supersededRenderers.has(renderer))return;if(installed&&listener)installed.off("keypress",listener);if(installed&&releaseListener)installed.off("keyrelease",releaseListener);if(ctrlHoldDetector?.cancel(),installedRenderer)supersededRenderers.add(installedRenderer);stack.length=0,resetPrefixState(),installedRenderer=renderer,installed=renderer.keyInput,ctrlHoldDetector=createCtrlHoldDetector({onReveal:()=>{resetPrefixState();let options=directGuideOptions(bindingReachability(stack),currentPrefixConfiguration().key);if(options.length>0)prefixHudShowDirect(options)},onHide:prefixHudHideDirect}),listener=(evt)=>{if(profileTick("key"),keyCapture){evt.preventDefault();let capture=keyCapture;if(!isKittyModifierKeyName(evt.name))flushSync2(()=>capture(evt));return}ctrlHoldDetector?.keypress(evt),dispatchKeyEvent(stack,evt,Date.now(),{flushSync:flushSync2})},releaseListener=(evt)=>ctrlHoldDetector?.keyrelease(evt),installed.on("keypress",listener),installed.on("keyrelease",releaseListener)}var keyCapture=null;function captureKeys(handler){return keyCapture=handler,()=>{if(keyCapture===handler)keyCapture=null}}function modalActive(){return stack.some((r)=>r.modalOwner!==void 0)}function currentBindingReachability(){return bindingReachability(stack)}function armPrefixFromCurrentStack(){return armPrefixNow(stack)}function invokeArmedPrefixActionFromCurrentStack(actionId,stroke){return invokeArmedPrefixAction(stack,actionId,stroke)}var stackVersion=0,stackListeners=new Set;function bumpStackVersion(){prefixHudHideDirect(),stackVersion++;for(let listener2 of stackListeners)listener2()}var bindingTableSignatures=new WeakMap;function bindingReachabilitySignature(config){let bindings=bindingTableSignatures.get(config.bindings);if(bindings===void 0)bindings=config.bindings.map((binding)=>[binding.id??"",binding.key,binding.prefix===!0?"p":"d",binding.passthrough===!0?"i":"u"].join(":")).join("|"),bindingTableSignatures.set(config.bindings,bindings);return`${config.enabled===!1?"off":"on"};${config.modal===!0?"modal":"plain"};${bindings}`}function subscribeBindingStack(listener2){return stackListeners.add(listener2),()=>{stackListeners.delete(listener2)}}function useBindingStackVersion(){return import_react7.useSyncExternalStore((onChange)=>{return stackListeners.add(onChange),()=>stackListeners.delete(onChange)},()=>stackVersion)}function useBindings(config,opts){let renderer=useRenderer();ensureInstalled(renderer);let configRef=useLatest(config),scope=import_react7.useContext(ModalScopeContext),reachabilitySignature=bindingReachabilitySignature(config()),previousReachabilitySignature=import_react7.useRef(reachabilitySignature);import_react7.useEffect(()=>{if(previousReachabilitySignature.current===reachabilitySignature)return;previousReachabilitySignature.current=reachabilitySignature,bumpStackVersion()},[reachabilitySignature]),import_react7.useEffect(()=>{if(supersededRenderers.has(renderer))return;if(opts?.modalOwner!==void 0)resetPrefixState();let reg={config:()=>configRef.current(),id:nextId++,modalOwner:opts?.modalOwner,modalMember:opts?.modalOwner===void 0?scope??void 0:void 0};return insertRegistration(stack,reg),bumpStackVersion(),()=>{let i=stack.findIndex((r)=>r.id===reg.id);if(i>=0)stack.splice(i,1);bumpStackVersion()}},[])}function pageCloseBindings(cmd){return[{key:"escape",cmd},{key:"q",cmd},{key:"ctrl+c",cmd}]}function currentPaletteActions(){return capturePaletteActions(stack)}import{createCliRenderer,setRenderLibPath}from"@opentui/core";var NARROW_BELOW_KEY="layout.narrowBelow",DEFAULT_NARROW_BELOW=70;function normalizeNarrowBelow(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"&&value.trim()!==""?Number(value.trim()):Number.NaN;if(!Number.isFinite(n))return 70;return Math.min(1000,Math.max(0,Math.floor(n)))}var breakpoint=DEFAULT_NARROW_BELOW;function setNarrowBreakpoint(value){breakpoint=normalizeNarrowBelow(value)}function isNarrowWidth(cols){return cols<breakpoint}function narrowSurface(args){if(args.focusedPane==="sidebar")return"sidebar";return args.hasSelection||args.hasOpenPage?"content":"sidebar"}var import_react21=__toESM(require_react_production(),1);async function connectPaneOrchestrator(options={}){let tag=options.logTag??"orch-connect",connect=options.connect??connectIfRunning,remote=null;try{let client=await connect();if(!client)return logClient(tag,"no daemon running \u2014 caller degrades"),null;return remote=new RemoteOrchestrator(client,{...options.orchestratorOptions,channels:options.channels}),await remote.init(),remote}catch(err){return logClientError(tag,err),remote?.dispose(),null}}var cached=null;function applyUserKeybindings(){if(cached)return cached;let{report,prefix}=resolveUserKeybindings(readKeybindingsFile(),RoveKeymap,process.platform);if(report.exists)configurePrefix(prefix);for(let w of report.warnings)console.warn(`[rove/keybindings] ${w}`);return cached=report,cached}function pluginKeybindings(){return userKeybindingsReport().plugins}function userKeybindingsReport(){return cached??applyUserKeybindings()}function reloadUserKeybindings(){cached=null,resetKeybindingsFileCache(),resetKeymapToDefaults(),resetPrefixConfiguration();let report=applyUserKeybindings();return bumpKeymapVersion(),report}function saveKeybindingEdits(edits){let result=writeKeybindingEdits(edits);if(result.ok)reloadUserKeybindings();return result}var UI_PREFS_FOCUS_ACCENT_SLOTS=["primary","success","info"];var UI_PREFS_THEME_MODES=["dark","light","auto"];function applyUiPrefs(target,prefs){if(typeof prefs.theme==="string"&&prefs.theme.length>0&&prefs.theme!==target.selectedTheme()){if(!target.hasTheme(prefs.theme))target.reloadUserThemes();if(target.hasTheme(prefs.theme))target.setTheme(prefs.theme)}if(prefs.themeMode===null||typeof prefs.themeMode==="string"){let mode=normalizeThemeMode(prefs.themeMode);if(mode&&mode!==target.themeMode())target.setThemeMode(mode)}if(typeof prefs.transparentBackground==="boolean"&&prefs.transparentBackground!==target.transparentBackground())target.setTransparentBackground(prefs.transparentBackground);if(prefs.focusAccent===null||typeof prefs.focusAccent==="string"){let slot=normalizeFocusAccent(prefs.focusAccent);if(slot&&slot!==target.focusAccent())target.setFocusAccent(slot)}}function normalizeFocusAccent(value){if(value===null)return"primary";return UI_PREFS_FOCUS_ACCENT_SLOTS.includes(value)?value:null}function normalizeThemeMode(value){if(value===null)return"dark";return UI_PREFS_THEME_MODES.includes(value)?value:null}var STALL_HEARTBEAT_MS=1000,STALL_THRESHOLD_MS=2000;function stallReport(gapMs,mem,heartbeatMs=STALL_HEARTBEAT_MS,thresholdMs=STALL_THRESHOLD_MS){let stallMs=gapMs-heartbeatMs;if(stallMs<thresholdMs)return null;let mb=(n)=>Math.round(n/1048576);return`event loop stalled ~${stallMs}ms \u2014 rss=${mb(mem.rss)}MB heapUsed=${mb(mem.heapUsed)}MB`}function installEventLoopStallTelemetry(){let last=Date.now(),timer=setInterval(()=>{let now=Date.now(),gap=now-last;last=now;let report=stallReport(gap,process.memoryUsage());if(report)logClient("stall",report)},STALL_HEARTBEAT_MS);return timer.unref?.(),()=>clearInterval(timer)}var KITTY_KEYBOARD={};function hostTargetFps(){return 60}function hostRenderOptions(onDestroy){let base={backgroundColor:"transparent",externalOutputMode:"passthrough",exitOnCtrlC:!1,screenMode:"alternate-screen",useKittyKeyboard:KITTY_KEYBOARD,targetFps:hostTargetFps()};return onDestroy?{...base,onDestroy}:base}function inlineRenderOptions(heightRows,onDestroy){let base={backgroundColor:"transparent",exitOnCtrlC:!1,screenMode:"split-footer",footerHeight:heightRows,useKittyKeyboard:KITTY_KEYBOARD};return onDestroy?{...base,onDestroy}:base}function installExitRestoreBackstop(renderer){process.on("exit",()=>renderer.destroy())}var BRACKETED_PASTE_ON="\x1B[?2004h",BRACKETED_PASTE_OFF="\x1B[?2004l";function installBracketedPasteMode(stdout=process.stdout){if(!stdout.isTTY)return()=>{};let write=(seq)=>{try{stdout.write(seq)}catch{}};write(BRACKETED_PASTE_ON);let restored=!1,restore=()=>{if(restored)return;restored=!0,write(BRACKETED_PASTE_OFF)};return process.on("exit",restore),restore}var exitCriticalWork=new Set;async function whenExitReady(){while(exitCriticalWork.size>0)await Promise.allSettled([...exitCriticalWork])}function installPaneExitBackstop(opts={}){let ceilingMs=opts.ceilingMs??5000,exit=opts.exit??((code)=>process.exit(code)),exitScheduled=!1,exited=!1,exitOnce=()=>{if(exited)return;exited=!0,exit(0)},scheduleExit=()=>{if(exitScheduled)return;exitScheduled=!0;let ceiling=setTimeout(()=>{console.error(`[rove] exit backstop: ${exitCriticalWork.size} task(s) still in flight after ${ceilingMs}ms \u2014 exiting anyway`),exitOnce()},ceilingMs);ceiling.unref?.(),whenExitReady().then(()=>{clearTimeout(ceiling),exitOnce()})};for(let signal of["SIGHUP","SIGTERM","SIGINT"])process.on(signal,scheduleExit)}function installOrphanExitWatchdog(intervalMs=5000){let timer=setInterval(()=>{if(process.ppid===1)process.exit(0)},intervalMs);return timer.unref?.(),()=>clearInterval(timer)}var SYNC_START=Buffer.from("\x1B[?2026h"),SYNC_END=Buffer.from("\x1B[?2026l");class ImeAnchorController{owner=null;anchor=null;claim(owner,anchor){this.owner=owner,this.anchor={x:Math.max(0,Math.trunc(anchor.x)),y:Math.max(0,Math.trunc(anchor.y))}}release(owner){if(this.owner!==owner)return!1;return this.owner=null,this.anchor=null,!0}current(){return this.anchor}}var imeAnchorController=new ImeAnchorController;class ImeAnchorFrameTransformer{controller;pending=Buffer.alloc(0);frame=Buffer.alloc(0);constructor(controller){this.controller=controller}push(chunk){let data=this.pending.length>0?Buffer.concat([this.pending,chunk]):chunk;this.pending=Buffer.alloc(0);let output=[],offset=0;while(offset<data.length){if(this.frame.length===0){let start=data.indexOf(SYNC_START,offset);if(start<0){let tail2=data.subarray(offset),pendingLength2=longestMarkerPrefixSuffix(tail2,[SYNC_START]),safeLength2=tail2.length-pendingLength2;if(safeLength2>0)output.push(tail2.subarray(0,safeLength2));if(pendingLength2>0)this.pending=Buffer.from(tail2.subarray(safeLength2));break}if(start>offset)output.push(data.subarray(offset,start));this.frame=Buffer.from(SYNC_START),offset=start+SYNC_START.length;continue}let end=data.indexOf(SYNC_END,offset),restart=data.indexOf(SYNC_START,offset);if(restart>=0&&(end<0||restart<end)){this.frame=Buffer.from(SYNC_START),offset=restart+SYNC_START.length;continue}if(end>=0){if(end>offset)this.frame=Buffer.concat([this.frame,data.subarray(offset,end)]);output.push(this.frame);let anchor=this.controller.current();if(anchor)output.push(Buffer.from(`\x1B[${anchor.y+1};${anchor.x+1}H\x1B[?25l`));output.push(SYNC_END),this.frame=Buffer.alloc(0),offset=end+SYNC_END.length;continue}let tail=data.subarray(offset),pendingLength=longestMarkerPrefixSuffix(tail,[SYNC_START,SYNC_END]),safeLength=tail.length-pendingLength;if(safeLength>0)this.frame=Buffer.concat([this.frame,tail.subarray(0,safeLength)]);if(pendingLength>0)this.pending=Buffer.from(tail.subarray(safeLength));break}return output.length>0?Buffer.concat(output):Buffer.alloc(0)}flush(){if(this.frame.length>0)return this.frame=Buffer.alloc(0),this.pending=Buffer.alloc(0),Buffer.alloc(0);let pending=this.pending;return this.pending=Buffer.alloc(0),pending}}function longestMarkerPrefixSuffix(bytes,markers){let max=Math.min(bytes.length,Math.max(...markers.map((marker)=>marker.length-1)));for(let length=max;length>0;length-=1){let suffix=bytes.subarray(bytes.length-length);if(markers.some((marker)=>length<marker.length&&suffix.equals(marker.subarray(0,length))))return length}return 0}function asBuffer(chunk,encodingOrCallback){if(typeof chunk!=="string")return Buffer.from(chunk);let encoding=typeof encodingOrCallback==="string"?encodingOrCallback:void 0;return Buffer.from(chunk,encoding)}function writeCallback(encodingOrCallback,maybeCallback){return typeof encodingOrCallback==="function"?encodingOrCallback:maybeCallback}function createImeAnchoredOutput(target,controller=imeAnchorController){let transformer=new ImeAnchorFrameTransformer(controller),exposedWrite=(chunk,encodingOrCallback,maybeCallback)=>{let transformed=transformer.push(asBuffer(chunk,encodingOrCallback)),callback=writeCallback(encodingOrCallback,maybeCallback);if(transformed.length===0){if(callback)queueMicrotask(()=>callback(null));return!0}return callback?target.write(transformed,callback):target.write(transformed)};return{stdout:new Proxy(target,{get(stream,property){if(property==="write")return exposedWrite;let value=Reflect.get(stream,property,stream);return typeof value==="function"?value.bind(stream):value},set(stream,property,value){if(property==="write")return exposedWrite=value,!0;return Reflect.set(stream,property,value,stream)}}),flush(){let pending=transformer.flush();if(pending.length>0)target.write(pending)}}}var IME_ANCHOR_PLATFORMS=new Set(["darwin","win32"]);function createHostImeOutput(opts){if(!IME_ANCHOR_PLATFORMS.has(opts.platform)||!opts.fullscreen)return{active:!1,rendererOptions:{},attach:()=>()=>{},flush:()=>{}};let output=createImeAnchoredOutput(opts.stdout,opts.controller);return{active:!0,rendererOptions:{stdout:output.stdout,remote:!1},attach:(renderer)=>installRendererResizeForwarder(renderer,opts.stdout),flush:()=>output.flush()}}function installRendererResizeForwarder(renderer,terminal,signals=process){let onResize=()=>{let{columns:width,rows:height}=terminal;if(!width||!height)return;renderer.resize(width,height)};return signals.on("SIGWINCH",onResize),()=>signals.removeListener("SIGWINCH",onResize)}import{readFileSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";var STOCK_OPENTUI_ENV="ROVE_STOCK_OPENTUI";function roveNativeLibPath(probe){if(probe.env[STOCK_OPENTUI_ENV]==="1")return null;try{let manifestPath=probe.resolve(`@sma1lboy/opentui-rove-${probe.platform}-${probe.arch}/package.json`),manifest=JSON.parse(probe.readText(manifestPath)),core=JSON.parse(probe.readText(join(dirname(probe.resolve("@opentui/core")),"package.json")));if(!manifest.lib||!manifest.opentui||manifest.opentui!==core.version)return null;return join(dirname(manifestPath),manifest.lib)}catch{return null}}function installedRoveNativeLibPath(){let require2=createRequire(import.meta.url);return roveNativeLibPath({platform:process.platform,arch:process.arch,env:process.env,resolve:(id)=>require2.resolve(id),readText:(path)=>readFileSync(path,"utf8")})}function needsScreenSelfHeal(platform){return platform==="win32"}function requestFullRepaint(renderer){if(renderer.screenMode!=="alternate-screen")return!1;let internals=renderer;return internals.forceFullRepaintRequested=!0,renderer.requestRender(),!0}function writeThroughRenderer(renderer,chunk,fallback=process.stdout){let writeOut=renderer?.writeOut;try{if(typeof writeOut==="function")writeOut.call(renderer,chunk);else fallback.write(chunk)}catch{}}function redrawScreen(renderer){if(renderer.screenMode!=="alternate-screen")return!1;return writeThroughRenderer(renderer,"\x1B[H\x1B[2J"),requestFullRepaint(renderer)}function installScreenSelfHeal(opts){let platform=opts.platform??process.platform;if(!needsScreenSelfHeal(platform))return()=>{};let{renderer}=opts,repaint=()=>{requestFullRepaint(renderer)};return renderer.on("resize",repaint),renderer.on("focus",repaint),()=>{renderer.off("resize",repaint),renderer.off("focus",repaint)}}var import_react9=__toESM(require_react_production(),1);var PANE_ORDER=["sidebar","workspace","files","terminal"],FocusContext=import_react9.createContext(null);function FocusProvider(props){let[focused,setFocusedState]=import_react9.useState(props.initial??"sidebar"),renderer=useRenderer(),focusedRef=useLatest(focused),setFocused=import_react9.useCallback((pane)=>{if(focusedRef.current===pane)return;let current=renderer?.currentFocusedRenderable;if(current&&!current.isDestroyed)try{current.blur()}catch{}setFocusedState(pane)},[renderer]),cycle=import_react9.useCallback((delta)=>{let next=(PANE_ORDER.indexOf(focusedRef.current)+delta+PANE_ORDER.length)%PANE_ORDER.length;setFocused(PANE_ORDER[next])},[setFocused]),value=import_react9.useMemo(()=>({focused,is:(pane)=>focused===pane,setFocused,cycle}),[focused,setFocused,cycle]);return $jsx(FocusContext.Provider,{value,children:props.children})}function useFocus(){let ctx=import_react9.useContext(FocusContext);if(!ctx)throw Error("useFocus: must be called inside <FocusProvider>. See src/tui-react/context/focus.tsx.");return ctx}function useOptionalFocus(){return import_react9.useContext(FocusContext)}var import_react10=__toESM(require_react_production(),1);var FILES_OPEN_KEY="files.open";var WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,FILES_OPEN_KEY]);function createKvCore(){let store2=createStateCell(loadStateFile(),"kv.snapshot"),dirtyKeys=new Set,pendingUpdates=new Map,quiet=new Map,seeded=new Map,writeTimer=null,errorListeners=new Set,reportedKeys=new Set;function reportWriteError(err,unwritten=new Set([...dirtyKeys,...pendingUpdates.keys()])){let fresh=[...unwritten].filter((key)=>!reportedKeys.has(key));if(fresh.length===0)return;for(let key of fresh)reportedKeys.add(key);let failure={keys:fresh,file:kvStatePath(),error:err};for(let listener2 of errorListeners)listener2(failure)}function writeNow(label){if(dirtyKeys.size===0&&pendingUpdates.size===0)return!0;try{let patch={},snap=store2.get();for(let key of dirtyKeys)patch[key]=quiet.has(key)?quiet.get(key):snap[key];let updated={};updateStateFile((state)=>{for(let[key,value]of Object.entries(patch))if(value===void 0)delete state[key];else state[key]=value;for(let[key,mutations]of pendingUpdates){let value=state[key];for(let mutate of mutations)value=mutate(value);if(updated[key]=value,value===void 0)delete state[key];else state[key]=value}return},"strict"),pendingUpdates.clear();let loud=Object.entries(updated).filter(([key,value])=>{if(!quiet.has(key))return!0;return quiet.set(key,value),!1});if(loud.length>0)store2.update((snapshot)=>{let next={...snapshot};for(let[key,value]of loud)if(value===void 0)delete next[key];else next[key]=value;return next});return dirtyKeys.clear(),reportedKeys.clear(),!0}catch(err){return console.error(`[rove] kv ${label} failed:`,err),reportWriteError(err),!1}}function cancelTimer(){if(writeTimer)clearTimeout(writeTimer),writeTimer=null}function scheduleWrite(){cancelTimer(),writeTimer=setTimeout(()=>{writeTimer=null,writeNow("write")},WRITE_DEBOUNCE_MS)}function merge(fresh,keepQuiet){let before=store2.get(),next={...fresh};for(let[key,value]of seeded)if(next[key]===void 0)next[key]=value;for(let key of new Set([...dirtyKeys,...pendingUpdates.keys()]))if(before[key]===void 0)delete next[key];else next[key]=before[key];let quietChanged=!1;for(let key of[...quiet.keys()]){if(dirtyKeys.has(key)||pendingUpdates.has(key))continue;if(!keepQuiet||JSON.stringify(quiet.get(key))!==JSON.stringify(fresh[key])){quietChanged=!0,quiet.delete(key);continue}if(before[key]===void 0)delete next[key];else next[key]=before[key]}if(dirtyKeys.size>0||pendingUpdates.size>0)scheduleWrite();let changed=0;for(let key of new Set([...Object.keys(before),...Object.keys(next)]))if(JSON.stringify(before[key])!==JSON.stringify(next[key]))changed++;if(changed>0||quietChanged)store2.set(next);return changed}return{snapshot:store2.get,subscribe:store2.subscribe,get(key,defaultValue){return(quiet.has(key)?quiet.get(key):store2.get()[key])??defaultValue},set(key,value){if(key.startsWith(TERMINAL_TABS_PREFIX)){logClientError("kv",Error(`refused a local write of ${key}: tabs go through the daemon`));return}pendingUpdates.delete(key),quiet.delete(key),store2.update((s)=>{if(value!==void 0)return{...s,[key]:value};if(!(key in s))return s;let next={...s};return delete next[key],next}),dirtyKeys.add(key),scheduleWrite()},setQuiet(key,value){pendingUpdates.delete(key),quiet.set(key,value),dirtyKeys.add(key),scheduleWrite()},update(key,mutate,opts){let next=mutate(quiet.has(key)?quiet.get(key):store2.get()[key]),pending=pendingUpdates.get(key)??[];if(pendingUpdates.set(key,[...pending,mutate]),dirtyKeys.delete(key),opts?.quiet)return quiet.set(key,next),scheduleWrite(),!1;quiet.delete(key),store2.update((s)=>{let copy={...s};if(next===void 0)delete copy[key];else copy[key]=next;return copy});let written=writeNow("update");if(!written)scheduleWrite();return written},seed(key,value){if(!seeded.has(key))seeded.set(key,value);if(quiet.has(key)||store2.get()[key]!==void 0)return;store2.update((s)=>({...s,[key]:value}))},flush(){return cancelTimer(),writeNow("flush")},clear(){try{replaceStateFile({})}catch(err){return console.error("[rove] kv clear write failed:",err),!1}return cancelTimer(),dirtyKeys.clear(),pendingUpdates.clear(),reportedKeys.clear(),quiet.clear(),store2.set({}),!0},reload(){try{return readStateFileStrict(),cancelTimer(),writeNow("reload flush"),{ok:!0,changed:merge(readStateFileStrict(),!1)}}catch(error){return{ok:!1,error}}},follow(shared){let next={...shared};for(let key of PER_WINDOW_KEYS)delete next[key];for(let[key,value]of Object.entries(store2.get()))if(isUnpublishedStateKey(key)||PER_WINDOW_KEYS.has(key))next[key]=value;merge(next,!0)},onWriteError(listener2){return errorListeners.add(listener2),()=>{errorListeners.delete(listener2)}}}}var Ctx=import_react10.createContext(null);function KVProvider(props){let[core]=import_react10.useState(createKvCore),snapshot=import_react10.useSyncExternalStore(core.subscribe,core.snapshot,core.snapshot);import_react10.useEffect(()=>{let flush=()=>{core.flush()};return process.on("exit",flush),()=>{process.off("exit",flush)}},[core]);let value=import_react10.useMemo(()=>({ready:!0,store:snapshot,signal(name,defaultValue){return core.seed(name,defaultValue),[()=>core.get(name)??defaultValue,(next)=>core.set(name,next)]},get:core.get,set:core.set,setQuiet:core.setQuiet,update:core.update,flush:core.flush,clear:core.clear,reload:core.reload,follow:core.follow,onWriteError:core.onWriteError}),[core,snapshot]);return $jsx(Ctx.Provider,{value,children:props.children})}function useKV(){let value=import_react10.useContext(Ctx);if(!value)throw Error("KV context must be used within a context provider");return value}function useOptionalKV(){return import_react10.useContext(Ctx)??null}var import_react13=__toESM(require_react_production(),1);var import_react12=__toESM(require_react_production(),1);import{existsSync,mkdirSync}from"fs";import{tmpdir}from"os";import{basename,delimiter,extname,isAbsolute,join as join2,resolve}from"path";var pulse_default="../pulse-ynhb2ave.wav";function scaleWavVolume(wav,volume){let gain=Math.min(1,Math.max(0,volume));if(wav.length<12)return null;if(wav.readUInt32BE(0)!==1380533830||wav.readUInt32BE(8)!==1463899717)return null;let bitsPerSample,format,data;for(let offset=12;offset+8<=wav.length;){let id=wav.readUInt32BE(offset),size=wav.readUInt32LE(offset+4),start=offset+8,end=start+size;if(size<0||end>wav.length)return null;if(id===1718449184){if(size<16)return null;format=wav.readUInt16LE(start),bitsPerSample=wav.readUInt16LE(start+14)}else if(id===1684108385)data={start,end};offset=end+size%2}if(format!==1||bitsPerSample!==16||!data)return null;if((data.end-data.start)%2!==0)return null;let out=Buffer.from(wav);if(gain===1)return out;for(let i=data.start;i<data.end;i+=2){let scaled=Math.round(out.readInt16LE(i)*gain);out.writeInt16LE(Math.min(32767,Math.max(-32768,scaled)),i)}return out}var pulseAsset=isAbsolute(pulse_default)?pulse_default:resolve(import.meta.dir,pulse_default),DIR=join2(tmpdir(),"rove-sfx"),PLAYERS=["ffplay","mpv","mpg123","mpg321","mplayer","afplay","play","omxplayer","aplay","cmdmp3","cvlc","powershell.exe"];function args(player,file){if(player==="ffplay")return[player,"-autoexit","-nodisp",file];if(player==="mpv")return[player,"--no-video","--audio-display=no",file];if(player==="mplayer")return[player,"-vo","null",file];if(player==="cvlc")return[player,"--play-and-exit",file];if(player==="powershell.exe")return[player,"-c",`(New-Object Media.SoundPlayer '${file.replace(/'/g,"''")}').PlaySync()`];return[player,file]}var cachedPlayer,cachedPaths=new Map;function pathDirs(rawPath,delim=delimiter){return rawPath.split(delim).filter(Boolean)}function pickPlayer(){if(cachedPlayer!==void 0)return cachedPlayer;let segments=pathDirs(process.env.PATH??"");return cachedPlayer=PLAYERS.find((p)=>segments.some((dir)=>existsSync(join2(dir,p))))??null,cachedPlayer}function assetNameFor(assetPath,volume){let name=basename(assetPath),ext=extname(name);return`${name.slice(0,name.length-ext.length)}@${Math.round(volume*100)}${ext}`}async function ensureAsset(volume){let cached2=cachedPaths.get(volume);if(cached2)return cached2;let pending=(async()=>{mkdirSync(DIR,{recursive:!0});let dest=join2(DIR,assetNameFor(pulseAsset,volume)),out=Bun.file(dest);if(await out.exists())return dest;let source=Buffer.from(await Bun.file(pulseAsset).arrayBuffer());return await Bun.write(out,scaleWavVolume(source,volume)??source),dest})();return cachedPaths.set(volume,pending),pending}function pulse(volume=persistedSoundVolume()){if(!(volume>0))return;let player=pickPlayer();if(!player)return;ensureAsset(volume).then((path)=>{try{Bun.spawn(args(player,path),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref?.()}catch{}}).catch(()=>{return})}var ctx=import_react12.createContext(null);function NotificationsProvider(props){let[toasts,setToasts]=import_react12.useState([]),[unread,setUnread]=import_react12.useState(new Map),kv=useOptionalKV(),renderer=useRenderer(),snapshot=import_react12.useMemo(()=>loadStateFile(),[]),prefs=import_react12.useMemo(()=>({"notifications.sound.enabled":kv?.get("notifications.sound.enabled")??snapshot["notifications.sound.enabled"],"notifications.toast.enabled":kv?.get("notifications.toast.enabled")??snapshot["notifications.toast.enabled"],[FINISHED_ALERTS_KEY]:kv?.get(FINISHED_ALERTS_KEY)??snapshot[FINISHED_ALERTS_KEY],mutedTasks:mutedTaskIds(kv?kv.get(MUTED_TASKS_KEY):snapshot[MUTED_TASKS_KEY])}),[kv,snapshot]),counter=import_react12.useRef(0),timers=import_react12.useRef(new Set);import_react12.useEffect(()=>()=>{for(let id of timers.current)clearTimeout(id);timers.current.clear()},[]);let dismiss=import_react12.useCallback((id)=>{setToasts((prev)=>prev.filter((t2)=>t2.id!==id))},[]),notify=import_react12.useCallback((input)=>{setUnread((prev)=>addUnread(prev,input));let muted=input.taskId!==""&&prefs.mutedTasks.has(input.taskId);if(!shouldAlert(input,prefs[FINISHED_ALERTS_KEY]!==!1,muted))return;let soundEnabled=prefs["notifications.sound.enabled"]!==!1;if(shouldPlaySound(input,soundEnabled,muted))writeThroughRenderer(renderer,`\x07${osc9(`Rove \u2014 ${input.title}`)}`),pulse();let toastEnabled=prefs["notifications.toast.enabled"]!==!1;if(shouldShowToast(input.kind,toastEnabled)){let id=++counter.current;setToasts((prev)=>[...prev.filter((t2)=>input.key===void 0||t2.key!==input.key),{id,...input}]);let timer=setTimeout(()=>{timers.current.delete(timer),dismiss(id)},TOAST_DURATION_MS);timers.current.add(timer)}},[prefs,dismiss,renderer]),markRead=import_react12.useCallback((taskId,tabId)=>{setUnread((prev)=>removeUnread(prev,taskId,tabId))},[]),value=import_react12.useMemo(()=>({toasts,unread,notify,dismiss,markRead}),[toasts,unread,notify,dismiss,markRead]);return $jsx(ctx.Provider,{value,children:props.children})}function useNotifications(){let value=import_react12.useContext(ctx);if(!value)throw Error("useNotifications must be used within a NotificationsProvider");return value}function useOptionalNotifications(){return import_react12.useContext(ctx)}function KvWriteErrorToasts(){let kv=useOptionalKV(),notifications=useOptionalNotifications();return import_react13.useEffect(()=>{if(!kv||!notifications)return;return kv.onWriteError((failure)=>{notifications.notify({taskId:"",tabId:"",kind:"error",title:t("settings.stateWrite.failedTitle"),body:t("settings.stateWrite.failedBody",{file:tildify(failure.file),keys:failure.keys.join(", ")})})})},[kv,notifications]),null}var import_react17=__toESM(require_react_production(),1);var import_react15=__toESM(require_react_production(),1);var stores=new WeakMap;function terminalSizeStore(source){let existing=stores.get(source);if(existing)return existing;let listeners=new Set,size={width:source.width,height:source.height},notify=()=>{for(let listener2 of listeners)listener2()},store2={subscribe(listener2){if(listeners.add(listener2),listeners.size===1)source.on("resize",notify);return()=>{if(listeners.delete(listener2),listeners.size===0)source.off("resize",notify)}},snapshot(){if(size.width!==source.width||size.height!==source.height)size={width:source.width,height:source.height};return size}};return stores.set(source,store2),store2}function useTerminalSize(){let store2=terminalSizeStore(useRenderer());return import_react15.useSyncExternalStore(store2.subscribe,store2.snapshot)}function useDialogPaddingX(){let dims=useTerminalSize();return isNarrowWidth(dims.width)?1:2}var DIALOG_CONTENT_OPACITY=0.5,TRANSPARENT_DIALOG_CONTENT_OPACITY=0.75;function Dialog(props){let dimensions=useTerminalSize(),{theme}=useTheme(),renderer=useRenderer(),dismissRef=import_react17.useRef(!1),width=props.size==="xlarge"?140:props.size==="large"?110:props.size==="small"?50:80,VERTICAL_MARGIN=2,upperFifth=props.placement==="upper-fifth"&&!isNarrowWidth(dimensions.width),headerTop=Math.max(2,Math.floor(dimensions.height/5)),cardTop=upperFifth?Math.max(2,headerTop-1):0,maxCardHeight=Math.max(8,upperFifth?dimensions.height-cardTop-2:dimensions.height-4);return $jsx("box",{onMouseDown:()=>{dismissRef.current=!!renderer?.getSelection()},onMouseUp:()=>{if(dismissRef.current){dismissRef.current=!1;return}props.onClose?.()},width:dimensions.width,height:dimensions.height,alignItems:"center",justifyContent:upperFifth?"flex-start":"center",paddingTop:cardTop,position:"absolute",zIndex:3000,left:0,top:0,shouldFill:!1,children:$jsx("box",{onMouseUp:(e)=>{dismissRef.current=!1,e.stopPropagation()},width,maxWidth:dimensions.width-2,maxHeight:maxCardHeight,flexShrink:1,flexGrow:0,backgroundColor:theme.backgroundDialog,paddingTop:1,children:props.children})})}var entrySeq=0,ctx2=import_react17.createContext(null);function DialogProvider(props){let[stack2,setStack]=import_react17.useState([]),[size,setSize]=import_react17.useState("medium"),[placement,setPlacement]=import_react17.useState("center"),renderer=useRenderer(),{transparentBackground:transparentBackground2}=useTheme(),focusRef=import_react17.useRef(null),refocusTimer=import_react17.useRef(null);import_react17.useEffect(()=>()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current)},[]);let refocus=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);refocusTimer.current=setTimeout(()=>{let focus=focusRef.current;if(!focus||focus.isDestroyed)return;function find(item){for(let child of item.getChildren()){if(child===focus)return!0;if(find(child))return!0}return!1}let root=renderer?.root;if(!root)return;if(!find(root))return;focus.focus()},1)},[renderer]),stackRef=useLatest(stack2),captureFocusIfFirst=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);if(stackRef.current.length===0)focusRef.current=renderer?.currentFocusedRenderable??null,focusRef.current?.blur()},[renderer]),dismissTop=import_react17.useCallback(()=>{let selection=renderer?.getSelection();if(selection){if(renderer?.clearSelection(),selection.getSelectedText())return}stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),refocus()},[renderer,refocus]),value=import_react17.useMemo(()=>({clear(options){for(let item of stackRef.current)item.onClose?.();if(setSize("medium"),setPlacement("center"),setStack([]),options?.refocus===!1)focusRef.current=null;else refocus()},replace(thunk,onClose){captureFocusIfFirst();for(let item of stackRef.current)item.onClose?.();setSize("medium"),setPlacement("center"),setStack([{key:++entrySeq,element:thunk,onClose}])},push(thunk,onClose){captureFocusIfFirst(),setStack((s)=>[...s,{key:++entrySeq,element:thunk,onClose}])},pop(){if(stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),stackRef.current.length<=1)refocus()},get stack(){return stackRef.current},get size(){return size},setSize,get placement(){return placement},setPlacement}),[stack2,size,placement,refocus,captureFocusIfFirst]),top=stack2.at(-1),contentOpacity=top?transparentBackground2?TRANSPARENT_DIALOG_CONTENT_OPACITY:DIALOG_CONTENT_OPACITY:1;return $jsxs(ctx2.Provider,{value,children:[$jsx("box",{flexGrow:1,backgroundColor:top&&!transparentBackground2?"black":"transparent",children:$jsx("box",{flexGrow:1,opacity:contentOpacity,children:props.children})}),$jsx("box",{position:"absolute",zIndex:3000,children:top?$jsxs(ModalScopeContext,{value:MODAL_SCOPE,children:[$jsx(ModalBarrier,{dismissTop}),$jsx(Dialog,{onClose:()=>value.clear(),size,placement,children:top.element()},top.key)]}):null})]})}var MODAL_SCOPE=Symbol("rove.dialog.modal");function ModalBarrier(props){return useBindings(()=>({modal:!0,bindings:[{key:"escape",cmd:props.dismissTop},{key:"ctrl+c",cmd:props.dismissTop}]}),{modalOwner:MODAL_SCOPE}),null}function useDialog(){let value=import_react17.useContext(ctx2);if(!value)throw Error("useDialog must be used within a DialogProvider");return value}function useOptionalDialog(){return import_react17.useContext(ctx2)}function showDialog(dialog,body,opts){return new Promise((resolve2)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve2(value),dialog.clear()};if(dialog.replace(()=>body(finish),()=>{if(settled)return;settled=!0,resolve2(void 0)}),opts?.size)dialog.setSize(opts.size)})}function NarrowLayoutSync(){let kv=useOptionalKV();if(kv)setNarrowBreakpoint(kv.get(NARROW_BELOW_KEY));return null}var import_react18=__toESM(require_react_production(),1);function PaneCrashFallback(props){let{theme}=useTheme(),t2=useT(),sizing=props.width===void 0?{flexGrow:1}:{width:props.width,flexShrink:0};return $jsxs("box",{...sizing,flexDirection:"column",backgroundColor:theme.background,paddingLeft:1,paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:props.region?t2("common.paneCrash.regionTitle",{region:t2(`common.paneCrash.region.${props.region}`)}):t2("common.paneCrash.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t2(props.region?"common.paneCrash.regionHint":"common.paneCrash.hint")}),$jsx("text",{fg:theme.focusAccent,onMouseUp:props.onRetry,children:t2("common.paneCrash.retry")})]})}function formatPaneCrashDiagnostic(region,error,info){let base=error instanceof Error?error.stack??error.message:String(error),componentStack=info.componentStack?.trim()||"(unavailable)",stateChanges=recentStateChangesForDiagnostics();return`region: ${region??"root"}
2
+ import{FINISHED_ALERTS_KEY,MUTED_TASKS_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,TOAST_DURATION_MS,addUnread,armPrefixNow,bindingReachability,bumpKeymapVersion,configurePrefix,currentPrefixConfiguration,dispatchKeyEvent,ensureContrastInts,findBinding,inputPassthroughReachable,insertRegistration,invokeArmedPrefixAction,isCtrlModifierKeyName,isKittyModifierKeyName,mutedTaskIds,osc9,persistedSoundVolume,prefixHudHideDirect,prefixHudShowDirect,readKeybindingsFile,removeUnread,resetKeybindingsFileCache,resetKeymapToDefaults,resetPrefixConfiguration,resetPrefixState,resolveUserKeybindings,restoreTerminal,shouldAlert,shouldPlaySound,shouldShowToast,turnHueInts,writeKeybindingEdits}from"./chunk-z98zs1h3.js";import{$Fragment,$jsx,$jsxs,createRoot2,flushSync2,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{RemoteOrchestrator}from"./chunk-5m01rpg9.js";import{updaterShell,updaterShellFailureHint}from"./chunk-f3c2q4k0.js";import{TERMINAL_TABS_PREFIX}from"./chunk-6t1yxx9x.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,readPersistedUiPrefs,resolveThemeMode}from"./chunk-n5zdhshy.js";import{isThemePackage,loadUserThemes,parseRgbLiteral}from"./chunk-ahfvmf90.js";import{tildify}from"./chunk-grbrh92f.js";import{connectIfRunning}from"./chunk-n6s1sba5.js";import{CURRENT_VERSION}from"./chunk-g875xaf6.js";import{loadStateFile,readStateFileStrict,replaceStateFile,updateStateFile}from"./chunk-12qq8r81.js";import{localeState,setLocaleLang,t}from"./chunk-t9n6n7dy.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-7b2x6nkj.js";import{isLocaleId}from"./chunk-8acw5rmt.js";import{installClientCrashHandlers,logClient,logClientError,setClientLogContext}from"./chunk-4y536nwm.js";import{kvStatePath}from"./chunk-pzbcbmm4.js";import{__toESM}from"./chunk-91sykzqq.js";import{RGBA as RGBA4}from"@opentui/core";var import_react3=__toESM(require_react_production(),1);import{RGBA as RGBA3}from"@opentui/core";import{RGBA}from"@opentui/core";var BREATH_TICKS=30,SPEED_MIN=0.2,SPEED_SWING=0.9333333333333333,INK_FLOOR=0.3;function breathLevel(tick){return 0.5-0.5*Math.cos(2*Math.PI*tick/BREATH_TICKS)}function breathPhase(tick){let wave=tick/2-BREATH_TICKS/(4*Math.PI)*Math.sin(2*Math.PI*tick/BREATH_TICKS);return SPEED_MIN*tick+SPEED_SWING*wave}function breathGlyph(frames,tick){let index=Math.floor(breathPhase(tick)+0.000000001)%frames.length;return frames[index]??frames[0]??""}function mixInk(accent,muted,share){if(accent.intent!=="rgb"||muted.intent!=="rgb")return accent;let[ar,ag,ab,aa]=accent.toInts(),[mr,mg,mb]=muted.toInts(),mix=(a,m)=>Math.round(m+(a-m)*share);return RGBA.fromInts(mix(ar,mr),mix(ag,mg),mix(ab,mb),aa)}function breathColor(accent,muted,tick){return mixInk(accent,muted,INK_FLOOR+(1-INK_FLOOR)*breathLevel(tick))}var ints=(c)=>c.toInts(),rgba=([r,g,b,a])=>RGBA.fromInts(r,g,b,a);function turnHue(accent,deg,lightness=1,chroma=1){if(accent.intent!=="rgb")return accent;return rgba(turnHueInts(ints(accent),deg,lightness,chroma))}import{RGBA as RGBA2}from"@opentui/core";var HOST_TEXT_MIN_CONTRAST=4.5;function ensureContrast(fg,bg,minRatio=HOST_TEXT_MIN_CONTRAST){let from=fg.toInts(),to=ensureContrastInts(from,bg.toInts(),minRatio);return to===from?fg:RGBA2.fromInts(to[0],to[1],to[2],to[3])}function resolveTheme(theme,mode="dark"){let defs=theme.defs??{};function resolve(c,chain=[]){if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA3.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA3.fromHex(c);let rgb=parseRgbLiteral(c);if(rgb)return RGBA3.fromInts(rgb.r,rgb.g,rgb.b,rgb.a);if(chain.includes(c))return RGBA3.fromInts(0,0,0);let next=defs[c]??theme.theme[c];if(next===void 0)return RGBA3.fromInts(0,0,0);return resolve(next,[...chain,c])}return resolve(c[mode],chain)}let out={};for(let[k,v]of Object.entries(theme.theme))out[k]=resolve(v);let text=out.text??RGBA3.fromHex("#ffffff"),background=out.background??RGBA3.fromHex("#000000");return{...{primary:out.primary??text,secondary:out.secondary??text,accent:out.accent??out.primary??text,error:out.error??text,warning:out.warning??text,warningOnHost:out.warning??text,success:out.success??text,info:out.info??text,text,textMuted:out.textMuted??text,background,backgroundPanel:out.backgroundPanel??background,backgroundElement:out.backgroundElement??background,backgroundMenu:out.backgroundMenu??out.backgroundElement??background,backgroundDialog:out.backgroundDialog??out.backgroundPanel??background,border:out.border??text,borderActive:out.borderActive??out.border??text,borderSubtle:out.borderSubtle??out.border??text,diffAdded:out.diffAdded??out.success??text,diffRemoved:out.diffRemoved??out.error??text,diffContext:out.diffContext??out.textMuted??text,diffHunkHeader:out.diffHunkHeader??out.textMuted??text,diffAddedBg:out.diffAddedBg??background,diffRemovedBg:out.diffRemovedBg??background,selectedListItemText:out.selectedListItemText??background},...out}}function applyDisplayOverlay(base,focusAccent,transparentBackground,hostBackground){let v={...base,focusAccent:base[focusAccent]??base.primary,warningOnHost:base.warning};if(!transparentBackground)return v;let[backgroundR,backgroundG,backgroundB]=base.background.toInts(),[panelR,panelG,panelB]=base.backgroundPanel.toInts(),transparent={...v,background:RGBA3.fromInts(backgroundR,backgroundG,backgroundB,0),backgroundPanel:RGBA3.fromInts(panelR,panelG,panelB,0)};if(!hostBackground)return transparent;return{...transparent,text:ensureContrast(transparent.text,hostBackground),textMuted:ensureContrast(transparent.textMuted,hostBackground),warningOnHost:ensureContrast(transparent.warning,hostBackground)}}function diffInks(theme,colorblind){let added=(ink)=>colorblind?turnHue(ink,60,1,0.71):ink;return{added:added(theme.diffAdded),removed:theme.diffRemoved,addedBg:added(theme.diffAddedBg),removedBg:theme.diffRemovedBg}}var import_react=__toESM(require_react_production(),1);function useAccessor(state){return import_react.useSyncExternalStore(state.subscribe,state.get,state.get)}var noSubscribe=()=>()=>{};function useAccessorWhile(state,live){return import_react.useSyncExternalStore(live?state.subscribe:noSubscribe,state.get,state.get)}var store=createStateCell({themes:{...BUNDLED_THEMES},active:DEFAULT_THEME,mode:DEFAULT_THEME_MODE,transparentBackground:!0,focusAccent:"primary"});function listThemes(){return Object.keys(store.get().themes)}function themePackageNames(){return Object.entries(store.get().themes).filter(([,theme])=>isThemePackage(theme)).map(([name])=>name)}function hasTheme(name){return Boolean(store.get().themes[name])}function addTheme(name,theme){if(!name)return!1;if(!theme||typeof theme!=="object"||!theme.theme)return!1;return store.update((s)=>({...s,themes:{...s.themes,[name]:theme}})),!0}function selectedTheme(){return store.get().active}function setTheme(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0}function transparentBackground(){return store.get().transparentBackground}function setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))}function focusAccent(){return store.get().focusAccent}function setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))}function themeMode(){return store.get().mode}function setThemeMode(mode){store.update((s)=>({...s,mode}))}var ThemeContext=import_react3.createContext(null),HOST_PALETTE_QUERY_TIMEOUT_MS=2000;function resolveActive(state,mode){let active=state.themes[state.active];if(active)return resolveTheme(active,mode);let fallback=state.themes[DEFAULT_THEME]??Object.values(state.themes)[0];if(!fallback)return resolveTheme({theme:{background:"#000000",text:"#ffffff"}},mode);return resolveTheme(fallback,mode)}function useHostThemeMode(renderer){let[mode,setMode]=import_react3.useState(()=>renderer?.themeMode??null);return import_react3.useEffect(()=>{if(!renderer)return;let onChange=(next)=>setMode(next);return renderer.on("theme_mode",onChange),setMode(renderer.themeMode),()=>{renderer.off("theme_mode",onChange)}},[renderer]),mode}function ThemeProvider(props){import_react3.useMemo(()=>{store.update((s)=>({...s,mode:props.mode??s.mode,active:props.theme&&s.themes[props.theme]?props.theme:s.active}))},[]);let state=useAccessor(store),renderer=useRenderer(),hostMode=useHostThemeMode(renderer),mode=resolveThemeMode(state.mode,hostMode),[hostBackground,setHostBackground]=import_react3.useState(null);import_react3.useEffect(()=>{if(!state.transparentBackground)return;if(renderer?.screenMode==="split-footer")return;if(!renderer)return;let cancelled=!1;return renderer.getPalette({timeout:HOST_PALETTE_QUERY_TIMEOUT_MS}).then((colors)=>{if(cancelled||!colors.defaultBackground)return;setHostBackground(RGBA4.fromHex(colors.defaultBackground))}).catch(()=>{}),()=>{cancelled=!0}},[renderer,state.transparentBackground]);let theme=import_react3.useMemo(()=>applyDisplayOverlay(resolveActive(state,mode),state.focusAccent,state.transparentBackground,hostBackground??void 0),[state,mode,hostBackground]);import_react3.useEffect(()=>{if(renderer?.screenMode==="split-footer")return;renderer?.setBackgroundColor(theme.background??RGBA4.fromInts(0,0,0))},[renderer,theme]);let value=import_react3.useMemo(()=>({theme,selected:state.active,transparentBackground:state.transparentBackground,focusAccent:state.focusAccent,modePreference:state.mode,mode:()=>mode,set(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0},setMode(next){store.update((s)=>({...s,mode:next}))},setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))},setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))},preview:(options)=>{let resolvedMode=resolveThemeMode(options.themeMode,hostMode),base=options.themeOverride?resolveTheme(options.themeOverride,resolvedMode):resolveActive({...state,active:options.themeName},resolvedMode);return applyDisplayOverlay(base,options.focusAccent,options.transparentBackground,hostBackground??void 0)},all:listThemes,has:hasTheme}),[theme,state,mode,hostMode,hostBackground]);return $jsx(ThemeContext.Provider,{value,children:props.children})}function useTheme(){let value=import_react3.useContext(ThemeContext);if(!value)throw Error("Theme context must be used within a context provider");return value}var import_react4=__toESM(require_react_production(),1);function useLang(){return useAccessor(localeState())}function useT(){let lang=useLang();return import_react4.useCallback((key,params)=>t(key,params),[lang])}var CTRL_HOLD_THRESHOLD_MS=400;function createCtrlHoldDetector(callbacks){let state={kind:"idle"},held=new Set,reset=()=>{if(state.kind==="pending")clearTimeout(state.timer);if(state.kind==="visible")callbacks.onHide();state={kind:"idle"}},cancel=()=>{reset(),held.clear()};return{keypress:(event)=>{if(!isCtrlModifierKeyName(event.name)){cancel();return}if(event.eventType==="repeat"&&held.has(event.name))return;if(event.eventType!=="press")return;if(held.add(event.name),state.kind!=="idle")return;state={kind:"pending",timer:setTimeout(()=>{state={kind:"visible"},callbacks.onReveal()},CTRL_HOLD_THRESHOLD_MS)}},keyrelease:(event)=>{if(!isCtrlModifierKeyName(event.name)||event.eventType!=="release")return;if(held.delete(event.name),held.size===0)reset()},cancel}}var MODIFIER_GLYPH={ctrl:"\u2303",control:"\u2303",alt:"\u2325",opt:"\u2325",option:"\u2325",shift:"\u21E7",cmd:"\u2318",command:"\u2318",meta:"\u2318",super:"\u2318"},KEY_GLYPH={enter:"\u23CE",return:"\u23CE",esc:"\u238B",escape:"\u238B",space:"\u2423",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",backspace:"\u232B",delete:"\u2326",del:"\u2326",pgup:"\u21DE",pageup:"\u21DE",pgdn:"\u21DF",pagedown:"\u21DF",home:"\u2196",end:"\u2198"};function formatKey(k,upper){if(k.includes("/"))return k.split("/").map((part)=>formatKey(part,upper)).join("/");let low=k.toLowerCase();if(low==="tab")return"tab";let named=KEY_GLYPH[low];if(named)return named;if(/^f\d{1,2}$/.test(low))return low.toUpperCase();if(!upper)return k;if(/^[a-z]$/.test(low))return k.toUpperCase();return k.replace(/[a-z]+/gi,(run)=>run.toUpperCase())}function formatChord(chord,prefixGlyph="\u2303A"){let s=chord.trim();if(!s)return s;let pm=/^prefix\s+(.+)$/i.exec(s);if(pm){let suffix=pm[1]??"";return`${prefixGlyph} ${suffix.includes("+")?formatChord(suffix,prefixGlyph):formatKey(suffix,!0)}`}let parts=s.split("+");if(parts.length===1)return formatKey(parts[0]??"",!1);let key=parts[parts.length-1]??"";return`${parts.slice(0,-1).map((p)=>MODIFIER_GLYPH[p.toLowerCase().trim()]??p).join("")} ${formatKey(key,!0)}`}var DIRECT_GUIDE_PREFIX_ACTION_ID="prefix.moreCommands",CTRL_FOLLOW_UP_CHORD=/^ctrl\+[^+]+$/;function ctrlFollowUpKey(chord){return CTRL_FOLLOW_UP_CHORD.test(chord)?chord.slice(5):null}function shortcutCaption(input){let binding=findBinding(input.bindingId);if(!binding)return null;if(input.reachability.direct.has(input.bindingId)){let direct=binding.keys[0];if(direct)return formatChord(direct)}if(input.prefixKey&&input.reachability.prefix.has(input.bindingId)){let stroke=binding.prefixKeys?.[0];if(stroke)return`${formatChord(input.prefixKey)} ${formatChord(stroke)}`}return null}function directGuideOptions(reachability,prefixKey){let options=RoveKeymap.filter((binding)=>reachability.direct.has(binding.id)).flatMap((binding)=>{let strokes=binding.keys.flatMap((chord)=>ctrlFollowUpKey(chord)??[]);if(strokes.length>2)return[{stroke:`${strokes[0]}-${strokes.at(-1)}`,action:binding.id}];return strokes.map((stroke)=>({stroke,action:binding.id}))}),prefixStroke=prefixKey?ctrlFollowUpKey(prefixKey):null;if(prefixStroke&&reachability.prefix.size>0)options.push({stroke:prefixStroke,action:DIRECT_GUIDE_PREFIX_ACTION_ID});return options}var import_react7=__toESM(require_react_production(),1);function availableActions(stack){let seen=new Set,actions=[],passthrough=inputPassthroughReachable(stack);for(let registration of[...stack].reverse()){let config=registration.config();if(config.enabled===!1)continue;for(let binding of config.bindings){if(binding.prefix&&currentPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}var import_react5=__toESM(require_react_production(),1);function useLatest(value){let ref=import_react5.useRef(value);return ref.current=value,ref}var ModalScopeContext=import_react7.createContext(null),nextId=1,stack=[],installedRenderer=null,installed=null,listener=null,releaseListener=null,ctrlHoldDetector=null,supersededRenderers=new WeakSet;function ensureInstalled(renderer){if(!renderer)throw Error("useBindings: no renderer in scope; call inside a component rendered by @opentui/react.");if(installedRenderer===renderer)return;if(supersededRenderers.has(renderer))return;if(installed&&listener)installed.off("keypress",listener);if(installed&&releaseListener)installed.off("keyrelease",releaseListener);if(ctrlHoldDetector?.cancel(),installedRenderer)supersededRenderers.add(installedRenderer);stack.length=0,resetPrefixState(),installedRenderer=renderer,installed=renderer.keyInput,ctrlHoldDetector=createCtrlHoldDetector({onReveal:()=>{resetPrefixState();let options=directGuideOptions(bindingReachability(stack),currentPrefixConfiguration().key);if(options.length>0)prefixHudShowDirect(options)},onHide:prefixHudHideDirect}),listener=(evt)=>{if(profileTick("key"),keyCapture){evt.preventDefault();let capture=keyCapture;if(!isKittyModifierKeyName(evt.name))flushSync2(()=>capture(evt));return}ctrlHoldDetector?.keypress(evt),dispatchKeyEvent(stack,evt,Date.now(),{flushSync:flushSync2})},releaseListener=(evt)=>ctrlHoldDetector?.keyrelease(evt),installed.on("keypress",listener),installed.on("keyrelease",releaseListener)}var keyCapture=null;function captureKeys(handler){return keyCapture=handler,()=>{if(keyCapture===handler)keyCapture=null}}function modalActive(){return stack.some((r)=>r.modalOwner!==void 0)}function currentBindingReachability(){return bindingReachability(stack)}function armPrefixFromCurrentStack(){return armPrefixNow(stack)}function invokeArmedPrefixActionFromCurrentStack(actionId,stroke){return invokeArmedPrefixAction(stack,actionId,stroke)}var stackVersion=0,stackListeners=new Set;function bumpStackVersion(){prefixHudHideDirect(),stackVersion++;for(let listener2 of stackListeners)listener2()}var bindingTableSignatures=new WeakMap;function bindingReachabilitySignature(config){let bindings=bindingTableSignatures.get(config.bindings);if(bindings===void 0)bindings=config.bindings.map((binding)=>[binding.id??"",binding.key,binding.prefix===!0?"p":"d",binding.passthrough===!0?"i":"u"].join(":")).join("|"),bindingTableSignatures.set(config.bindings,bindings);return`${config.enabled===!1?"off":"on"};${config.modal===!0?"modal":"plain"};${bindings}`}function subscribeBindingStack(listener2){return stackListeners.add(listener2),()=>{stackListeners.delete(listener2)}}function useBindingStackVersion(){return import_react7.useSyncExternalStore((onChange)=>{return stackListeners.add(onChange),()=>stackListeners.delete(onChange)},()=>stackVersion)}function useBindings(config,opts){let renderer=useRenderer();ensureInstalled(renderer);let configRef=useLatest(config),scope=import_react7.useContext(ModalScopeContext),reachabilitySignature=bindingReachabilitySignature(config()),previousReachabilitySignature=import_react7.useRef(reachabilitySignature);import_react7.useEffect(()=>{if(previousReachabilitySignature.current===reachabilitySignature)return;previousReachabilitySignature.current=reachabilitySignature,bumpStackVersion()},[reachabilitySignature]),import_react7.useEffect(()=>{if(supersededRenderers.has(renderer))return;if(opts?.modalOwner!==void 0)resetPrefixState();let reg={config:()=>configRef.current(),id:nextId++,modalOwner:opts?.modalOwner,modalMember:opts?.modalOwner===void 0?scope??void 0:void 0};return insertRegistration(stack,reg),bumpStackVersion(),()=>{let i=stack.findIndex((r)=>r.id===reg.id);if(i>=0)stack.splice(i,1);bumpStackVersion()}},[])}function pageCloseBindings(cmd){return[{key:"escape",cmd},{key:"q",cmd},{key:"ctrl+c",cmd}]}function currentPaletteActions(){return capturePaletteActions(stack)}import{createCliRenderer,setRenderLibPath}from"@opentui/core";var NARROW_BELOW_KEY="layout.narrowBelow",DEFAULT_NARROW_BELOW=70;function normalizeNarrowBelow(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"&&value.trim()!==""?Number(value.trim()):Number.NaN;if(!Number.isFinite(n))return 70;return Math.min(1000,Math.max(0,Math.floor(n)))}var breakpoint=DEFAULT_NARROW_BELOW;function setNarrowBreakpoint(value){breakpoint=normalizeNarrowBelow(value)}function isNarrowWidth(cols){return cols<breakpoint}function narrowSurface(args){if(args.focusedPane==="sidebar")return"sidebar";return args.hasSelection||args.hasOpenPage?"content":"sidebar"}var import_react21=__toESM(require_react_production(),1);async function connectPaneOrchestrator(options={}){let tag=options.logTag??"orch-connect",connect=options.connect??connectIfRunning,remote=null;try{let client=await connect();if(!client)return logClient(tag,"no daemon running \u2014 caller degrades"),null;return remote=new RemoteOrchestrator(client,{...options.orchestratorOptions,channels:options.channels}),await remote.init(),remote}catch(err){return logClientError(tag,err),remote?.dispose(),null}}var cached=null;function applyUserKeybindings(){if(cached)return cached;let{report,prefix}=resolveUserKeybindings(readKeybindingsFile(),RoveKeymap,process.platform);if(report.exists)configurePrefix(prefix);for(let w of report.warnings)console.warn(`[rove/keybindings] ${w}`);return cached=report,cached}function pluginKeybindings(){return userKeybindingsReport().plugins}function userKeybindingsReport(){return cached??applyUserKeybindings()}function reloadUserKeybindings(){cached=null,resetKeybindingsFileCache(),resetKeymapToDefaults(),resetPrefixConfiguration();let report=applyUserKeybindings();return bumpKeymapVersion(),report}function saveKeybindingEdits(edits){let result=writeKeybindingEdits(edits);if(result.ok)reloadUserKeybindings();return result}var UI_PREFS_FOCUS_ACCENT_SLOTS=["primary","success","info"];var UI_PREFS_THEME_MODES=["dark","light","auto"];function applyUiPrefs(target,prefs){if(typeof prefs.theme==="string"&&prefs.theme.length>0&&prefs.theme!==target.selectedTheme()){if(!target.hasTheme(prefs.theme))target.reloadUserThemes();if(target.hasTheme(prefs.theme))target.setTheme(prefs.theme)}if(prefs.themeMode===null||typeof prefs.themeMode==="string"){let mode=normalizeThemeMode(prefs.themeMode);if(mode&&mode!==target.themeMode())target.setThemeMode(mode)}if(typeof prefs.transparentBackground==="boolean"&&prefs.transparentBackground!==target.transparentBackground())target.setTransparentBackground(prefs.transparentBackground);if(prefs.focusAccent===null||typeof prefs.focusAccent==="string"){let slot=normalizeFocusAccent(prefs.focusAccent);if(slot&&slot!==target.focusAccent())target.setFocusAccent(slot)}}function normalizeFocusAccent(value){if(value===null)return"primary";return UI_PREFS_FOCUS_ACCENT_SLOTS.includes(value)?value:null}function normalizeThemeMode(value){if(value===null)return"dark";return UI_PREFS_THEME_MODES.includes(value)?value:null}var STALL_HEARTBEAT_MS=1000,STALL_THRESHOLD_MS=2000;function stallReport(gapMs,mem,heartbeatMs=STALL_HEARTBEAT_MS,thresholdMs=STALL_THRESHOLD_MS){let stallMs=gapMs-heartbeatMs;if(stallMs<thresholdMs)return null;let mb=(n)=>Math.round(n/1048576);return`event loop stalled ~${stallMs}ms \u2014 rss=${mb(mem.rss)}MB heapUsed=${mb(mem.heapUsed)}MB`}function installEventLoopStallTelemetry(){let last=Date.now(),timer=setInterval(()=>{let now=Date.now(),gap=now-last;last=now;let report=stallReport(gap,process.memoryUsage());if(report)logClient("stall",report)},STALL_HEARTBEAT_MS);return timer.unref?.(),()=>clearInterval(timer)}var KITTY_KEYBOARD={};function hostTargetFps(){return 60}function hostRenderOptions(onDestroy){let base={backgroundColor:"transparent",externalOutputMode:"passthrough",exitOnCtrlC:!1,screenMode:"alternate-screen",useKittyKeyboard:KITTY_KEYBOARD,targetFps:hostTargetFps()};return onDestroy?{...base,onDestroy}:base}function inlineRenderOptions(heightRows,onDestroy){let base={backgroundColor:"transparent",exitOnCtrlC:!1,screenMode:"split-footer",footerHeight:heightRows,useKittyKeyboard:KITTY_KEYBOARD};return onDestroy?{...base,onDestroy}:base}function installExitRestoreBackstop(renderer){process.on("exit",()=>renderer.destroy())}var BRACKETED_PASTE_ON="\x1B[?2004h",BRACKETED_PASTE_OFF="\x1B[?2004l";function installBracketedPasteMode(stdout=process.stdout){if(!stdout.isTTY)return()=>{};let write=(seq)=>{try{stdout.write(seq)}catch{}};write(BRACKETED_PASTE_ON);let restored=!1,restore=()=>{if(restored)return;restored=!0,write(BRACKETED_PASTE_OFF)};return process.on("exit",restore),restore}var exitCriticalWork=new Set;async function whenExitReady(){while(exitCriticalWork.size>0)await Promise.allSettled([...exitCriticalWork])}function installPaneExitBackstop(opts={}){let ceilingMs=opts.ceilingMs??5000,exit=opts.exit??((code)=>process.exit(code)),exitScheduled=!1,exited=!1,exitOnce=()=>{if(exited)return;exited=!0,exit(0)},scheduleExit=()=>{if(exitScheduled)return;exitScheduled=!0;let ceiling=setTimeout(()=>{console.error(`[rove] exit backstop: ${exitCriticalWork.size} task(s) still in flight after ${ceilingMs}ms \u2014 exiting anyway`),exitOnce()},ceilingMs);ceiling.unref?.(),whenExitReady().then(()=>{clearTimeout(ceiling),exitOnce()})};for(let signal of["SIGHUP","SIGTERM","SIGINT"])process.on(signal,scheduleExit)}function installOrphanExitWatchdog(intervalMs=5000){let timer=setInterval(()=>{if(process.ppid===1)process.exit(0)},intervalMs);return timer.unref?.(),()=>clearInterval(timer)}var SYNC_START=Buffer.from("\x1B[?2026h"),SYNC_END=Buffer.from("\x1B[?2026l");class ImeAnchorController{owner=null;anchor=null;claim(owner,anchor){this.owner=owner,this.anchor={x:Math.max(0,Math.trunc(anchor.x)),y:Math.max(0,Math.trunc(anchor.y))}}release(owner){if(this.owner!==owner)return!1;return this.owner=null,this.anchor=null,!0}current(){return this.anchor}}var imeAnchorController=new ImeAnchorController;class ImeAnchorFrameTransformer{controller;pending=Buffer.alloc(0);frame=Buffer.alloc(0);constructor(controller){this.controller=controller}push(chunk){let data=this.pending.length>0?Buffer.concat([this.pending,chunk]):chunk;this.pending=Buffer.alloc(0);let output=[],offset=0;while(offset<data.length){if(this.frame.length===0){let start=data.indexOf(SYNC_START,offset);if(start<0){let tail2=data.subarray(offset),pendingLength2=longestMarkerPrefixSuffix(tail2,[SYNC_START]),safeLength2=tail2.length-pendingLength2;if(safeLength2>0)output.push(tail2.subarray(0,safeLength2));if(pendingLength2>0)this.pending=Buffer.from(tail2.subarray(safeLength2));break}if(start>offset)output.push(data.subarray(offset,start));this.frame=Buffer.from(SYNC_START),offset=start+SYNC_START.length;continue}let end=data.indexOf(SYNC_END,offset),restart=data.indexOf(SYNC_START,offset);if(restart>=0&&(end<0||restart<end)){this.frame=Buffer.from(SYNC_START),offset=restart+SYNC_START.length;continue}if(end>=0){if(end>offset)this.frame=Buffer.concat([this.frame,data.subarray(offset,end)]);output.push(this.frame);let anchor=this.controller.current();if(anchor)output.push(Buffer.from(`\x1B[${anchor.y+1};${anchor.x+1}H\x1B[?25l`));output.push(SYNC_END),this.frame=Buffer.alloc(0),offset=end+SYNC_END.length;continue}let tail=data.subarray(offset),pendingLength=longestMarkerPrefixSuffix(tail,[SYNC_START,SYNC_END]),safeLength=tail.length-pendingLength;if(safeLength>0)this.frame=Buffer.concat([this.frame,tail.subarray(0,safeLength)]);if(pendingLength>0)this.pending=Buffer.from(tail.subarray(safeLength));break}return output.length>0?Buffer.concat(output):Buffer.alloc(0)}flush(){if(this.frame.length>0)return this.frame=Buffer.alloc(0),this.pending=Buffer.alloc(0),Buffer.alloc(0);let pending=this.pending;return this.pending=Buffer.alloc(0),pending}}function longestMarkerPrefixSuffix(bytes,markers){let max=Math.min(bytes.length,Math.max(...markers.map((marker)=>marker.length-1)));for(let length=max;length>0;length-=1){let suffix=bytes.subarray(bytes.length-length);if(markers.some((marker)=>length<marker.length&&suffix.equals(marker.subarray(0,length))))return length}return 0}function asBuffer(chunk,encodingOrCallback){if(typeof chunk!=="string")return Buffer.from(chunk);let encoding=typeof encodingOrCallback==="string"?encodingOrCallback:void 0;return Buffer.from(chunk,encoding)}function writeCallback(encodingOrCallback,maybeCallback){return typeof encodingOrCallback==="function"?encodingOrCallback:maybeCallback}function createImeAnchoredOutput(target,controller=imeAnchorController){let transformer=new ImeAnchorFrameTransformer(controller),exposedWrite=(chunk,encodingOrCallback,maybeCallback)=>{let transformed=transformer.push(asBuffer(chunk,encodingOrCallback)),callback=writeCallback(encodingOrCallback,maybeCallback);if(transformed.length===0){if(callback)queueMicrotask(()=>callback(null));return!0}return callback?target.write(transformed,callback):target.write(transformed)};return{stdout:new Proxy(target,{get(stream,property){if(property==="write")return exposedWrite;let value=Reflect.get(stream,property,stream);return typeof value==="function"?value.bind(stream):value},set(stream,property,value){if(property==="write")return exposedWrite=value,!0;return Reflect.set(stream,property,value,stream)}}),flush(){let pending=transformer.flush();if(pending.length>0)target.write(pending)}}}var IME_ANCHOR_PLATFORMS=new Set(["darwin","win32"]);function createHostImeOutput(opts){if(!IME_ANCHOR_PLATFORMS.has(opts.platform)||!opts.fullscreen)return{active:!1,rendererOptions:{},attach:()=>()=>{},flush:()=>{}};let output=createImeAnchoredOutput(opts.stdout,opts.controller);return{active:!0,rendererOptions:{stdout:output.stdout,remote:!1},attach:(renderer)=>installRendererResizeForwarder(renderer,opts.stdout),flush:()=>output.flush()}}function installRendererResizeForwarder(renderer,terminal,signals=process){let onResize=()=>{let{columns:width,rows:height}=terminal;if(!width||!height)return;renderer.resize(width,height)};return signals.on("SIGWINCH",onResize),()=>signals.removeListener("SIGWINCH",onResize)}import{readFileSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";var STOCK_OPENTUI_ENV="ROVE_STOCK_OPENTUI";function roveNativeLibPath(probe){if(probe.env[STOCK_OPENTUI_ENV]==="1")return null;try{let manifestPath=probe.resolve(`@sma1lboy/opentui-rove-${probe.platform}-${probe.arch}/package.json`),manifest=JSON.parse(probe.readText(manifestPath)),core=JSON.parse(probe.readText(join(dirname(probe.resolve("@opentui/core")),"package.json")));if(!manifest.lib||!manifest.opentui||manifest.opentui!==core.version)return null;return join(dirname(manifestPath),manifest.lib)}catch{return null}}function installedRoveNativeLibPath(){let require2=createRequire(import.meta.url);return roveNativeLibPath({platform:process.platform,arch:process.arch,env:process.env,resolve:(id)=>require2.resolve(id),readText:(path)=>readFileSync(path,"utf8")})}function needsScreenSelfHeal(platform){return platform==="win32"}function requestFullRepaint(renderer){if(renderer.screenMode!=="alternate-screen")return!1;let internals=renderer;return internals.forceFullRepaintRequested=!0,renderer.requestRender(),!0}function writeThroughRenderer(renderer,chunk,fallback=process.stdout){let writeOut=renderer?.writeOut;try{if(typeof writeOut==="function")writeOut.call(renderer,chunk);else fallback.write(chunk)}catch{}}function redrawScreen(renderer){if(renderer.screenMode!=="alternate-screen")return!1;return writeThroughRenderer(renderer,"\x1B[H\x1B[2J"),requestFullRepaint(renderer)}function installScreenSelfHeal(opts){let platform=opts.platform??process.platform;if(!needsScreenSelfHeal(platform))return()=>{};let{renderer}=opts,repaint=()=>{requestFullRepaint(renderer)};return renderer.on("resize",repaint),renderer.on("focus",repaint),()=>{renderer.off("resize",repaint),renderer.off("focus",repaint)}}var import_react9=__toESM(require_react_production(),1);var PANE_ORDER=["sidebar","workspace","files","terminal"],FocusContext=import_react9.createContext(null);function FocusProvider(props){let[focused,setFocusedState]=import_react9.useState(props.initial??"sidebar"),renderer=useRenderer(),focusedRef=useLatest(focused),setFocused=import_react9.useCallback((pane)=>{if(focusedRef.current===pane)return;let current=renderer?.currentFocusedRenderable;if(current&&!current.isDestroyed)try{current.blur()}catch{}setFocusedState(pane)},[renderer]),cycle=import_react9.useCallback((delta)=>{let next=(PANE_ORDER.indexOf(focusedRef.current)+delta+PANE_ORDER.length)%PANE_ORDER.length;setFocused(PANE_ORDER[next])},[setFocused]),value=import_react9.useMemo(()=>({focused,is:(pane)=>focused===pane,setFocused,cycle}),[focused,setFocused,cycle]);return $jsx(FocusContext.Provider,{value,children:props.children})}function useFocus(){let ctx=import_react9.useContext(FocusContext);if(!ctx)throw Error("useFocus: must be called inside <FocusProvider>. See src/tui-react/context/focus.tsx.");return ctx}function useOptionalFocus(){return import_react9.useContext(FocusContext)}var import_react10=__toESM(require_react_production(),1);var FILES_OPEN_KEY="files.open";var WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,FILES_OPEN_KEY]);function createKvCore(){let store2=createStateCell(loadStateFile(),"kv.snapshot"),dirtyKeys=new Set,pendingUpdates=new Map,quiet=new Map,seeded=new Map,writeTimer=null,errorListeners=new Set,reportedKeys=new Set;function reportWriteError(err,unwritten=new Set([...dirtyKeys,...pendingUpdates.keys()])){let fresh=[...unwritten].filter((key)=>!reportedKeys.has(key));if(fresh.length===0)return;for(let key of fresh)reportedKeys.add(key);let failure={keys:fresh,file:kvStatePath(),error:err};for(let listener2 of errorListeners)listener2(failure)}function writeNow(label){if(dirtyKeys.size===0&&pendingUpdates.size===0)return!0;try{let patch={},snap=store2.get();for(let key of dirtyKeys)patch[key]=quiet.has(key)?quiet.get(key):snap[key];let updated={};updateStateFile((state)=>{for(let[key,value]of Object.entries(patch))if(value===void 0)delete state[key];else state[key]=value;for(let[key,mutations]of pendingUpdates){let value=state[key];for(let mutate of mutations)value=mutate(value);if(updated[key]=value,value===void 0)delete state[key];else state[key]=value}return},"strict"),pendingUpdates.clear();let loud=Object.entries(updated).filter(([key,value])=>{if(!quiet.has(key))return!0;return quiet.set(key,value),!1});if(loud.length>0)store2.update((snapshot)=>{let next={...snapshot};for(let[key,value]of loud)if(value===void 0)delete next[key];else next[key]=value;return next});return dirtyKeys.clear(),reportedKeys.clear(),!0}catch(err){return console.error(`[rove] kv ${label} failed:`,err),reportWriteError(err),!1}}function cancelTimer(){if(writeTimer)clearTimeout(writeTimer),writeTimer=null}function scheduleWrite(){cancelTimer(),writeTimer=setTimeout(()=>{writeTimer=null,writeNow("write")},WRITE_DEBOUNCE_MS)}function merge(fresh,keepQuiet){let before=store2.get(),next={...fresh};for(let[key,value]of seeded)if(next[key]===void 0)next[key]=value;for(let key of new Set([...dirtyKeys,...pendingUpdates.keys()]))if(before[key]===void 0)delete next[key];else next[key]=before[key];let quietChanged=!1;for(let key of[...quiet.keys()]){if(dirtyKeys.has(key)||pendingUpdates.has(key))continue;if(!keepQuiet||JSON.stringify(quiet.get(key))!==JSON.stringify(fresh[key])){quietChanged=!0,quiet.delete(key);continue}if(before[key]===void 0)delete next[key];else next[key]=before[key]}if(dirtyKeys.size>0||pendingUpdates.size>0)scheduleWrite();let changed=0;for(let key of new Set([...Object.keys(before),...Object.keys(next)]))if(JSON.stringify(before[key])!==JSON.stringify(next[key]))changed++;if(changed>0||quietChanged)store2.set(next);return changed}return{snapshot:store2.get,subscribe:store2.subscribe,get(key,defaultValue){return(quiet.has(key)?quiet.get(key):store2.get()[key])??defaultValue},set(key,value){if(key.startsWith(TERMINAL_TABS_PREFIX)){logClientError("kv",Error(`refused a local write of ${key}: tabs go through the daemon`));return}pendingUpdates.delete(key),quiet.delete(key),store2.update((s)=>{if(value!==void 0)return{...s,[key]:value};if(!(key in s))return s;let next={...s};return delete next[key],next}),dirtyKeys.add(key),scheduleWrite()},setQuiet(key,value){pendingUpdates.delete(key),quiet.set(key,value),dirtyKeys.add(key),scheduleWrite()},update(key,mutate,opts){let next=mutate(quiet.has(key)?quiet.get(key):store2.get()[key]),pending=pendingUpdates.get(key)??[];if(pendingUpdates.set(key,[...pending,mutate]),dirtyKeys.delete(key),opts?.quiet)return quiet.set(key,next),scheduleWrite(),!1;quiet.delete(key),store2.update((s)=>{let copy={...s};if(next===void 0)delete copy[key];else copy[key]=next;return copy});let written=writeNow("update");if(!written)scheduleWrite();return written},seed(key,value){if(!seeded.has(key))seeded.set(key,value);if(quiet.has(key)||store2.get()[key]!==void 0)return;store2.update((s)=>({...s,[key]:value}))},flush(){return cancelTimer(),writeNow("flush")},clear(){try{replaceStateFile({})}catch(err){return console.error("[rove] kv clear write failed:",err),!1}return cancelTimer(),dirtyKeys.clear(),pendingUpdates.clear(),reportedKeys.clear(),quiet.clear(),store2.set({}),!0},reload(){try{return readStateFileStrict(),cancelTimer(),writeNow("reload flush"),{ok:!0,changed:merge(readStateFileStrict(),!1)}}catch(error){return{ok:!1,error}}},follow(shared){let next={...shared};for(let key of PER_WINDOW_KEYS)delete next[key];for(let[key,value]of Object.entries(store2.get()))if(isUnpublishedStateKey(key)||PER_WINDOW_KEYS.has(key))next[key]=value;merge(next,!0)},onWriteError(listener2){return errorListeners.add(listener2),()=>{errorListeners.delete(listener2)}}}}var Ctx=import_react10.createContext(null);function KVProvider(props){let[core]=import_react10.useState(createKvCore),snapshot=import_react10.useSyncExternalStore(core.subscribe,core.snapshot,core.snapshot);import_react10.useEffect(()=>{let flush=()=>{core.flush()};return process.on("exit",flush),()=>{process.off("exit",flush)}},[core]);let value=import_react10.useMemo(()=>({ready:!0,store:snapshot,signal(name,defaultValue){return core.seed(name,defaultValue),[()=>core.get(name)??defaultValue,(next)=>core.set(name,next)]},get:core.get,set:core.set,setQuiet:core.setQuiet,update:core.update,flush:core.flush,clear:core.clear,reload:core.reload,follow:core.follow,onWriteError:core.onWriteError}),[core,snapshot]);return $jsx(Ctx.Provider,{value,children:props.children})}function useKV(){let value=import_react10.useContext(Ctx);if(!value)throw Error("KV context must be used within a context provider");return value}function useOptionalKV(){return import_react10.useContext(Ctx)??null}var import_react13=__toESM(require_react_production(),1);var import_react12=__toESM(require_react_production(),1);import{existsSync,mkdirSync}from"fs";import{tmpdir}from"os";import{basename,delimiter,extname,isAbsolute,join as join2,resolve}from"path";var pulse_default="../pulse-ynhb2ave.wav";function scaleWavVolume(wav,volume){let gain=Math.min(1,Math.max(0,volume));if(wav.length<12)return null;if(wav.readUInt32BE(0)!==1380533830||wav.readUInt32BE(8)!==1463899717)return null;let bitsPerSample,format,data;for(let offset=12;offset+8<=wav.length;){let id=wav.readUInt32BE(offset),size=wav.readUInt32LE(offset+4),start=offset+8,end=start+size;if(size<0||end>wav.length)return null;if(id===1718449184){if(size<16)return null;format=wav.readUInt16LE(start),bitsPerSample=wav.readUInt16LE(start+14)}else if(id===1684108385)data={start,end};offset=end+size%2}if(format!==1||bitsPerSample!==16||!data)return null;if((data.end-data.start)%2!==0)return null;let out=Buffer.from(wav);if(gain===1)return out;for(let i=data.start;i<data.end;i+=2){let scaled=Math.round(out.readInt16LE(i)*gain);out.writeInt16LE(Math.min(32767,Math.max(-32768,scaled)),i)}return out}var pulseAsset=isAbsolute(pulse_default)?pulse_default:resolve(import.meta.dir,pulse_default),DIR=join2(tmpdir(),"rove-sfx"),PLAYERS=["ffplay","mpv","mpg123","mpg321","mplayer","afplay","play","omxplayer","aplay","cmdmp3","cvlc","powershell.exe"];function args(player,file){if(player==="ffplay")return[player,"-autoexit","-nodisp",file];if(player==="mpv")return[player,"--no-video","--audio-display=no",file];if(player==="mplayer")return[player,"-vo","null",file];if(player==="cvlc")return[player,"--play-and-exit",file];if(player==="powershell.exe")return[player,"-c",`(New-Object Media.SoundPlayer '${file.replace(/'/g,"''")}').PlaySync()`];return[player,file]}var cachedPlayer,cachedPaths=new Map;function pathDirs(rawPath,delim=delimiter){return rawPath.split(delim).filter(Boolean)}function pickPlayer(){if(cachedPlayer!==void 0)return cachedPlayer;let segments=pathDirs(process.env.PATH??"");return cachedPlayer=PLAYERS.find((p)=>segments.some((dir)=>existsSync(join2(dir,p))))??null,cachedPlayer}function assetNameFor(assetPath,volume){let name=basename(assetPath),ext=extname(name);return`${name.slice(0,name.length-ext.length)}@${Math.round(volume*100)}${ext}`}async function ensureAsset(volume){let cached2=cachedPaths.get(volume);if(cached2)return cached2;let pending=(async()=>{mkdirSync(DIR,{recursive:!0});let dest=join2(DIR,assetNameFor(pulseAsset,volume)),out=Bun.file(dest);if(await out.exists())return dest;let source=Buffer.from(await Bun.file(pulseAsset).arrayBuffer());return await Bun.write(out,scaleWavVolume(source,volume)??source),dest})();return cachedPaths.set(volume,pending),pending}function pulse(volume=persistedSoundVolume()){if(!(volume>0))return;let player=pickPlayer();if(!player)return;ensureAsset(volume).then((path)=>{try{Bun.spawn(args(player,path),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref?.()}catch{}}).catch(()=>{return})}var ctx=import_react12.createContext(null);function NotificationsProvider(props){let[toasts,setToasts]=import_react12.useState([]),[unread,setUnread]=import_react12.useState(new Map),kv=useOptionalKV(),renderer=useRenderer(),snapshot=import_react12.useMemo(()=>loadStateFile(),[]),prefs=import_react12.useMemo(()=>({"notifications.sound.enabled":kv?.get("notifications.sound.enabled")??snapshot["notifications.sound.enabled"],"notifications.toast.enabled":kv?.get("notifications.toast.enabled")??snapshot["notifications.toast.enabled"],[FINISHED_ALERTS_KEY]:kv?.get(FINISHED_ALERTS_KEY)??snapshot[FINISHED_ALERTS_KEY],mutedTasks:mutedTaskIds(kv?kv.get(MUTED_TASKS_KEY):snapshot[MUTED_TASKS_KEY])}),[kv,snapshot]),counter=import_react12.useRef(0),timers=import_react12.useRef(new Set);import_react12.useEffect(()=>()=>{for(let id of timers.current)clearTimeout(id);timers.current.clear()},[]);let dismiss=import_react12.useCallback((id)=>{setToasts((prev)=>prev.filter((t2)=>t2.id!==id))},[]),notify=import_react12.useCallback((input)=>{setUnread((prev)=>addUnread(prev,input));let muted=input.taskId!==""&&prefs.mutedTasks.has(input.taskId);if(!shouldAlert(input,prefs[FINISHED_ALERTS_KEY]!==!1,muted))return;let soundEnabled=prefs["notifications.sound.enabled"]!==!1;if(shouldPlaySound(input,soundEnabled,muted))writeThroughRenderer(renderer,`\x07${osc9(`Rove \u2014 ${input.title}`)}`),pulse();let toastEnabled=prefs["notifications.toast.enabled"]!==!1;if(shouldShowToast(input.kind,toastEnabled)){let id=++counter.current;setToasts((prev)=>[...prev.filter((t2)=>input.key===void 0||t2.key!==input.key),{id,...input}]);let timer=setTimeout(()=>{timers.current.delete(timer),dismiss(id)},TOAST_DURATION_MS);timers.current.add(timer)}},[prefs,dismiss,renderer]),markRead=import_react12.useCallback((taskId,tabId)=>{setUnread((prev)=>removeUnread(prev,taskId,tabId))},[]),value=import_react12.useMemo(()=>({toasts,unread,notify,dismiss,markRead}),[toasts,unread,notify,dismiss,markRead]);return $jsx(ctx.Provider,{value,children:props.children})}function useNotifications(){let value=import_react12.useContext(ctx);if(!value)throw Error("useNotifications must be used within a NotificationsProvider");return value}function useOptionalNotifications(){return import_react12.useContext(ctx)}function KvWriteErrorToasts(){let kv=useOptionalKV(),notifications=useOptionalNotifications();return import_react13.useEffect(()=>{if(!kv||!notifications)return;return kv.onWriteError((failure)=>{notifications.notify({taskId:"",tabId:"",kind:"error",title:t("settings.stateWrite.failedTitle"),body:t("settings.stateWrite.failedBody",{file:tildify(failure.file),keys:failure.keys.join(", ")})})})},[kv,notifications]),null}var import_react17=__toESM(require_react_production(),1);var import_react15=__toESM(require_react_production(),1);var stores=new WeakMap;function terminalSizeStore(source){let existing=stores.get(source);if(existing)return existing;let listeners=new Set,size={width:source.width,height:source.height},notify=()=>{for(let listener2 of listeners)listener2()},store2={subscribe(listener2){if(listeners.add(listener2),listeners.size===1)source.on("resize",notify);return()=>{if(listeners.delete(listener2),listeners.size===0)source.off("resize",notify)}},snapshot(){if(size.width!==source.width||size.height!==source.height)size={width:source.width,height:source.height};return size}};return stores.set(source,store2),store2}function useTerminalSize(){let store2=terminalSizeStore(useRenderer());return import_react15.useSyncExternalStore(store2.subscribe,store2.snapshot)}function useDialogPaddingX(){let dims=useTerminalSize();return isNarrowWidth(dims.width)?1:2}var DIALOG_CONTENT_OPACITY=0.5,TRANSPARENT_DIALOG_CONTENT_OPACITY=0.75;function Dialog(props){let dimensions=useTerminalSize(),{theme}=useTheme(),renderer=useRenderer(),dismissRef=import_react17.useRef(!1),width=props.size==="xlarge"?140:props.size==="large"?110:props.size==="small"?50:80,VERTICAL_MARGIN=2,upperFifth=props.placement==="upper-fifth"&&!isNarrowWidth(dimensions.width),headerTop=Math.max(2,Math.floor(dimensions.height/5)),cardTop=upperFifth?Math.max(2,headerTop-1):0,maxCardHeight=Math.max(8,upperFifth?dimensions.height-cardTop-2:dimensions.height-4);return $jsx("box",{onMouseDown:()=>{dismissRef.current=!!renderer?.getSelection()},onMouseUp:()=>{if(dismissRef.current){dismissRef.current=!1;return}props.onClose?.()},width:dimensions.width,height:dimensions.height,alignItems:"center",justifyContent:upperFifth?"flex-start":"center",paddingTop:cardTop,position:"absolute",zIndex:3000,left:0,top:0,shouldFill:!1,children:$jsx("box",{onMouseUp:(e)=>{dismissRef.current=!1,e.stopPropagation()},width,maxWidth:dimensions.width-2,maxHeight:maxCardHeight,flexShrink:1,flexGrow:0,backgroundColor:theme.backgroundDialog,paddingTop:1,children:props.children})})}var entrySeq=0,ctx2=import_react17.createContext(null);function DialogProvider(props){let[stack2,setStack]=import_react17.useState([]),[size,setSize]=import_react17.useState("medium"),[placement,setPlacement]=import_react17.useState("center"),renderer=useRenderer(),{transparentBackground:transparentBackground2}=useTheme(),focusRef=import_react17.useRef(null),refocusTimer=import_react17.useRef(null);import_react17.useEffect(()=>()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current)},[]);let refocus=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);refocusTimer.current=setTimeout(()=>{let focus=focusRef.current;if(!focus||focus.isDestroyed)return;function find(item){for(let child of item.getChildren()){if(child===focus)return!0;if(find(child))return!0}return!1}let root=renderer?.root;if(!root)return;if(!find(root))return;focus.focus()},1)},[renderer]),stackRef=useLatest(stack2),captureFocusIfFirst=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);if(stackRef.current.length===0)focusRef.current=renderer?.currentFocusedRenderable??null,focusRef.current?.blur()},[renderer]),dismissTop=import_react17.useCallback(()=>{let selection=renderer?.getSelection();if(selection){if(renderer?.clearSelection(),selection.getSelectedText())return}stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),refocus()},[renderer,refocus]),value=import_react17.useMemo(()=>({clear(options){for(let item of stackRef.current)item.onClose?.();if(setSize("medium"),setPlacement("center"),setStack([]),options?.refocus===!1)focusRef.current=null;else refocus()},replace(thunk,onClose){captureFocusIfFirst();for(let item of stackRef.current)item.onClose?.();setSize("medium"),setPlacement("center"),setStack([{key:++entrySeq,element:thunk,onClose}])},push(thunk,onClose){captureFocusIfFirst(),setStack((s)=>[...s,{key:++entrySeq,element:thunk,onClose}])},pop(){if(stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),stackRef.current.length<=1)refocus()},get stack(){return stackRef.current},get size(){return size},setSize,get placement(){return placement},setPlacement}),[stack2,size,placement,refocus,captureFocusIfFirst]),top=stack2.at(-1),contentOpacity=top?transparentBackground2?TRANSPARENT_DIALOG_CONTENT_OPACITY:DIALOG_CONTENT_OPACITY:1;return $jsxs(ctx2.Provider,{value,children:[$jsx("box",{flexGrow:1,backgroundColor:top&&!transparentBackground2?"black":"transparent",children:$jsx("box",{flexGrow:1,opacity:contentOpacity,children:props.children})}),$jsx("box",{position:"absolute",zIndex:3000,children:top?$jsxs(ModalScopeContext,{value:MODAL_SCOPE,children:[$jsx(ModalBarrier,{dismissTop}),$jsx(Dialog,{onClose:()=>value.clear(),size,placement,children:top.element()},top.key)]}):null})]})}var MODAL_SCOPE=Symbol("rove.dialog.modal");function ModalBarrier(props){return useBindings(()=>({modal:!0,bindings:[{key:"escape",cmd:props.dismissTop},{key:"ctrl+c",cmd:props.dismissTop}]}),{modalOwner:MODAL_SCOPE}),null}function useDialog(){let value=import_react17.useContext(ctx2);if(!value)throw Error("useDialog must be used within a DialogProvider");return value}function useOptionalDialog(){return import_react17.useContext(ctx2)}function showDialog(dialog,body,opts){return new Promise((resolve2)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve2(value),dialog.clear()};if(dialog.replace(()=>body(finish),()=>{if(settled)return;settled=!0,resolve2(void 0)}),opts?.size)dialog.setSize(opts.size)})}function NarrowLayoutSync(){let kv=useOptionalKV();if(kv)setNarrowBreakpoint(kv.get(NARROW_BELOW_KEY));return null}var import_react18=__toESM(require_react_production(),1);function PaneCrashFallback(props){let{theme}=useTheme(),t2=useT(),sizing=props.width===void 0?{flexGrow:1}:{width:props.width,flexShrink:0};return $jsxs("box",{...sizing,flexDirection:"column",backgroundColor:theme.background,paddingLeft:1,paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:props.region?t2("common.paneCrash.regionTitle",{region:t2(`common.paneCrash.region.${props.region}`)}):t2("common.paneCrash.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t2(props.region?"common.paneCrash.regionHint":"common.paneCrash.hint")}),$jsx("text",{fg:theme.focusAccent,onMouseUp:props.onRetry,children:t2("common.paneCrash.retry")})]})}function formatPaneCrashDiagnostic(region,error,info){let base=error instanceof Error?error.stack??error.message:String(error),componentStack=info.componentStack?.trim()||"(unavailable)",stateChanges=recentStateChangesForDiagnostics();return`region: ${region??"root"}
3
3
  ${base}
4
4
  React component stack:
5
5
  ${componentStack}