@sma1lboy/rove 0.9.166 → 0.9.168
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{chunk-f2w2c77j.js → chunk-01w901sf.js} +1 -1
- package/dist/cli/{chunk-mn1c17zf.js → chunk-12gr0411.js} +1 -1
- package/dist/cli/{chunk-svfheeb2.js → chunk-1825qgp2.js} +1 -1
- package/dist/cli/{chunk-v027zrx5.js → chunk-2e572bj0.js} +2 -2
- package/dist/cli/{chunk-w0m1q23m.js → chunk-3p2e2ry4.js} +1 -1
- package/dist/cli/{chunk-p8bj0t7j.js → chunk-58rxg1df.js} +1 -1
- package/dist/cli/{chunk-3v1hzr8z.js → chunk-5agemmmn.js} +1 -1
- package/dist/cli/{chunk-m4vgx1sc.js → chunk-5jbj7b9t.js} +1 -1
- package/dist/cli/{chunk-pkzyrwhv.js → chunk-5t914d0v.js} +3 -3
- package/dist/cli/{chunk-jw134zg6.js → chunk-7af7g1sj.js} +2 -2
- package/dist/cli/chunk-8d8q901q.js +7 -0
- package/dist/cli/{chunk-sq5kj4za.js → chunk-8wrzdj5x.js} +1 -1
- package/dist/cli/{chunk-jjt118jt.js → chunk-ahrjn20k.js} +1 -1
- package/dist/cli/{chunk-b82bc173.js → chunk-ann3wt0v.js} +1 -1
- package/dist/cli/{chunk-dqse88xv.js → chunk-av4fw4ny.js} +1 -1
- package/dist/cli/{chunk-3try2twp.js → chunk-bggpzxk2.js} +1 -1
- package/dist/cli/{chunk-fw6nqqpg.js → chunk-bn1ta0qc.js} +1 -1
- package/dist/cli/{chunk-hnesjhs0.js → chunk-bz9mqybr.js} +2 -2
- package/dist/cli/chunk-c4rng97h.js +2 -0
- package/dist/cli/{chunk-4wajaa3z.js → chunk-c562kjgk.js} +1 -1
- package/dist/cli/{chunk-dqx9n8mn.js → chunk-cec5fc4d.js} +1 -1
- package/dist/cli/chunk-dt51afhh.js +5 -0
- package/dist/cli/{chunk-3g5qzq5g.js → chunk-dx6v0yw8.js} +1 -1
- package/dist/cli/{chunk-hnktpxpj.js → chunk-ex03xpcs.js} +2 -2
- package/dist/cli/{chunk-sp7jf5mx.js → chunk-fg6wc4bh.js} +6 -6
- package/dist/cli/{chunk-pnzk2rhm.js → chunk-h22qmj1w.js} +1 -1
- package/dist/cli/{chunk-zhzpmdd5.js → chunk-hmzjmhhj.js} +1 -1
- package/dist/cli/{chunk-zdtq90cz.js → chunk-ht4saept.js} +1 -1
- package/dist/cli/{chunk-qs80x1cd.js → chunk-hxfj85yw.js} +1 -1
- package/dist/cli/{chunk-apdy1yh2.js → chunk-jb7hgakq.js} +1 -1
- package/dist/cli/{chunk-avf82zmm.js → chunk-jn5dd6bv.js} +1 -1
- package/dist/cli/{chunk-g3vn40x3.js → chunk-k8w362qx.js} +1 -1
- package/dist/cli/{chunk-da9tb8av.js → chunk-m0g17ckn.js} +1 -1
- package/dist/cli/{chunk-bzhtt3sq.js → chunk-m66t4fvt.js} +1 -1
- package/dist/cli/{chunk-7mx1xz2b.js → chunk-mjmfr8de.js} +1 -1
- package/dist/cli/{chunk-ggaad0r0.js → chunk-p3qnztxm.js} +1 -1
- package/dist/cli/{chunk-130kknp8.js → chunk-pea31je5.js} +1 -1
- package/dist/cli/{chunk-n5c3k1dg.js → chunk-phftxm0p.js} +1 -1
- package/dist/cli/{chunk-0mzgrnqb.js → chunk-ppeav4ns.js} +4 -4
- package/dist/cli/{chunk-pabqr39m.js → chunk-qqw3p4fc.js} +1 -1
- package/dist/cli/{chunk-12z4a3j8.js → chunk-qs63g8qa.js} +1 -1
- package/dist/cli/{chunk-97z6a25c.js → chunk-rzme162d.js} +1 -1
- package/dist/cli/{chunk-r79ht9kg.js → chunk-skysscx4.js} +1 -1
- package/dist/cli/{chunk-wfwaa4n8.js → chunk-srn281km.js} +1 -1
- package/dist/cli/chunk-v2cpe974.js +3 -0
- package/dist/cli/{chunk-7rx93fhy.js → chunk-vfarq0sq.js} +1 -1
- package/dist/cli/{chunk-mg4r96nk.js → chunk-w9gzjcja.js} +1 -1
- package/dist/cli/{chunk-bgnvgcsp.js → chunk-ws17t64k.js} +1 -1
- package/dist/cli/{chunk-d4xhc9th.js → chunk-xhw8s2es.js} +3 -3
- package/dist/cli/{chunk-rvybphrq.js → chunk-xwekyjat.js} +1 -1
- package/dist/cli/chunk-xyf8qy8m.js +2 -0
- package/dist/cli/{chunk-ym78sw9a.js → chunk-y0nq7amn.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/cli/kobe.js +1 -1
- package/dist/cli/pty-host-node.mjs +6 -6
- package/dist/cli/rove.js +1 -1
- package/dist/skills/rove/references/api-flags.md +1 -1
- package/package.json +1 -1
- package/dist/cli/chunk-6tvrvekq.js +0 -4
- package/dist/cli/chunk-a56ygbrm.js +0 -2
- package/dist/cli/chunk-kemnxd03.js +0 -7
- package/dist/cli/chunk-tsmzqp49.js +0 -2
- package/dist/cli/chunk-xhb03ybc.js +0 -3
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{findBinding,formatChord}from"./chunk-
|
|
2
|
+
import{findBinding,formatChord}from"./chunk-5t914d0v.js";function capOf(row){return row.hint?.keys??row.keys[0]}function legendCap(id){let row=findBinding(id);if(!row)return null;let cap=capOf(row);return cap&&cap.length>0?cap:null}function directCap(row){if(row.keys.length>0)return row.hint?.keys??row.keys[0]??null;return row.prefixKeys?.length?null:row.hint?.keys??null}function availableOn(row,surface){if(row.scope==="global")return!0;if(surface===null)return!1;if(row.scope===surface)return!0;return surface==="terminal"&&row.scope==="workspace"}function grammarHelpSections(keymap,surface,prefixKey,reachability){let here=[],direct=[],prefix=[],other=new Map;for(let binding of keymap){let cap=directCap(binding),staticallyAvailable=availableOn(binding,surface),directAvailable=reachability?reachability.direct.has(binding.id):staticallyAvailable,prefixAvailable=reachability?reachability.prefix.has(binding.id):staticallyAvailable;if(cap){let row={binding,primary:cap,aliases:binding.keys.filter((key)=>key!==cap)};if(directAvailable&&(staticallyAvailable||binding.presentation==="onePress"))if(binding.presentation==="onePress")direct.push(row);else here.push(row);else if(!staticallyAvailable&&binding.scope!=="global"){let rows=other.get(binding.scope);if(rows)rows.push(row);else other.set(binding.scope,[row])}}if(prefixKey&&prefixAvailable&&binding.prefixKeys?.length)prefix.push({binding,primary:`${prefixKey} + ${binding.prefixKeys[0]}`,aliases:binding.prefixKeys.slice(1).map((key)=>`${prefixKey} + ${key}`)})}let sections=[];if(here.length)sections.push({kind:"here",scope:surface??void 0,rows:here});if(direct.length)sections.push({kind:"direct",rows:direct});if(prefix.length)sections.push({kind:"prefix",rows:prefix});for(let[scope,rows]of other)sections.push({kind:"other",scope,rows});return sections}var SCOPE_CATEGORY={global:"Global",sidebar:"Sidebar",workspace:"Workspace",files:"Files",inbox:"Inbox",terminal:"Terminal"};function scopeCategory(scope){return scope?SCOPE_CATEGORY[scope]:"Global"}function guideCategory(action){if(["kanban.open","automations.open","workItems.open"].includes(action))return"Views";if(action.startsWith("focus."))return"Navigation";if(action.startsWith("inbox.")||action.startsWith("attention."))return"Attention";if(action.startsWith("chat.tab.")||action.startsWith("chat.session."))return"Sessions";if(action.startsWith("chat.fork.")||action.startsWith("task."))return"Tasks";if(action.startsWith("settings.")||action==="workspace.zenToggle")return"Tools";return findBinding(action)?.category??"Global"}var KEY_HINTS_ENABLED_KEY="hints.keyboard.enabled",PANE_HINT_USED_KEYS={sidebar:"hints.sidebar.used",files:"hints.files.used"};function keyHintsEnabled(raw){return raw!==!1}function keyHintsToggleOn(kv){return keyHintsEnabled(kv.get(KEY_HINTS_ENABLED_KEY,!0))}function toggleKeyHints(kv){let next=!keyHintsToggleOn(kv);if(kv.set(KEY_HINTS_ENABLED_KEY,next),next)for(let key of Object.values(PANE_HINT_USED_KEYS))kv.set(key,!1)}function paneHintVisible(enabledRaw,usedRaw){return keyHintsEnabled(enabledRaw)&&usedRaw!==!0}function statusHintTokens(reach,prefixKey){let tokens=[];if(prefixKey!==null&&reach.prefix.size>0)tokens.push({chord:prefixKey,msg:"commands"});else if(reach.inputPassthrough){let cap=reach.direct.has("focus.sidebar")?legendCap("focus.sidebar"):null;if(cap)tokens.push({chord:cap,msg:"sidebar"})}if(reach.direct.has("help.open")){let cap=legendCap("help.open");if(cap)tokens.push({chord:cap,msg:"help"})}return tokens}var PANE_HINT_ROWS={sidebar:[{id:"sidebar.nav",msg:"move"},{id:"sidebar.select",msg:"open"}],files:[{id:"files.nav",msg:"move"},{id:"files.hierarchy",msg:"collapse"},{id:"files.open",msg:"open",always:!0},{id:"files.diff",msg:"diff",always:!0}]};function paneHintTokens(pane,mode){return PANE_HINT_ROWS[pane].flatMap((row)=>{if(mode==="always"&&row.always!==!0)return[];let cap=legendCap(row.id);return cap?[{cap,msg:row.msg}]:[]})}function wizardKeyLines(prefixKey){let lines=[],nav=legendCap("sidebar.nav"),open=legendCap("sidebar.select");if(nav&&open)lines.push({msg:"keysBare",params:{nav:formatChord(nav),open:formatChord(open)}});let newTab=legendCap("chat.tab.new"),focusNext=legendCap("focus.next");if(newTab&&focusNext)lines.push({msg:"keysOnePress",params:{newTab:formatChord(newTab),focusNext:formatChord(focusNext)}});if(prefixKey!==null)lines.push({msg:"keysPrefix",params:{prefix:formatChord(prefixKey)}});let help=legendCap("help.open");if(help)lines.push({msg:"keysHelp",params:{help:formatChord(help)}});return lines}
|
|
3
3
|
export{legendCap,grammarHelpSections,scopeCategory,guideCategory,KEY_HINTS_ENABLED_KEY,PANE_HINT_USED_KEYS,keyHintsEnabled,keyHintsToggleOn,toggleKeyHints,paneHintVisible,statusHintTokens,paneHintTokens,wizardKeyLines};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{SUBCOMMAND_VERBS,TOP_LEVEL_SUBCOMMANDS}from"./chunk-s76r56rj.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";async function collectSubVerbs(){let{API_VERBS}=await import("./chunk-
|
|
2
|
+
import{SUBCOMMAND_VERBS,TOP_LEVEL_SUBCOMMANDS}from"./chunk-s76r56rj.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";async function collectSubVerbs(){let{API_VERBS}=await import("./chunk-ht4saept.js"),merged={...SUBCOMMAND_VERBS,api:API_VERBS};return Object.keys(merged).sort().map((command)=>[command,merged[command]??[]])}function completionUsage(cliName){return[`Usage: ${cliName} completions <bash|zsh|fish>`,"",`Generate a shell completion script for ${cliName} and print it to stdout.`,"","Install:",` zsh source <(${cliName} completions zsh) # one-off, or in ~/.zshrc after compinit`," # or the fpath way:",` # ${cliName} completions zsh > ~/.zsh/completions/_${cliName}`," # fpath=(~/.zsh/completions $fpath) # in ~/.zshrc, BEFORE compinit"," # rm -f ~/.zcompdump && exec zsh # rebuild the completion cache",` bash ${cliName} completions bash > ~/.bash_completion.d/${cliName} # source it from ~/.bashrc`,` fish ${cliName} completions fish > ~/.config/fish/completions/${cliName}.fish`,""].join(`
|
|
3
3
|
`)}function generateBashCompletions(cliName,subVerbs){let subcommands=TOP_LEVEL_SUBCOMMANDS.join(" "),fn=`_${cliName}`;return[`# ${cliName} bash completions`,`# Source: ${cliName} completions bash`,"",`${fn}() {`," local cur prev"," COMPREPLY=()",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," if [[ ${COMP_CWORD} -eq 1 ]]; then",` COMPREPLY=( $(compgen -W "${subcommands}" -- "\${cur}") )`," return"," fi"," if [[ ${COMP_CWORD} -eq 2 ]]; then",' case "${prev}" in',...subVerbs.map(([command,verbs])=>` ${command}) COMPREPLY=( $(compgen -W "${verbs.join(" ")}" -- "\${cur}") ) ;;`)," esac"," fi","}",`complete -F ${fn} ${cliName}`,""].join(`
|
|
4
4
|
`)}function generateZshCompletions(cliName,subVerbs){let subcommandsList=TOP_LEVEL_SUBCOMMANDS.map((s)=>`"${s}"`).join(" "),fn=`_${cliName}`;return[`#compdef ${cliName}`,`# ${cliName} zsh completions`,`# Source: ${cliName} completions zsh`,"",`${fn}() {`," local -a subcommands verbs",` subcommands=(${subcommandsList})`,""," if (( CURRENT == 2 )); then"," _describe -t commands 'subcommand' subcommands"," return"," fi",""," verbs=()",' case "${words[2]}" in',...subVerbs.map(([command,verbs])=>` ${command}) verbs=(${verbs.map((v)=>`"${v}"`).join(" ")}) ;;`)," esac"," if (( CURRENT == 3 && ${#verbs} > 0 )); then"," _describe -t verbs 'verb' verbs"," fi","}","","# Autoloaded from $fpath -> run as the completion function;","# sourced directly -> register with compdef instead.",`if [ "\${funcstack[1]}" = "${fn}" ]; then`,` ${fn} "$@"`,"elif (( $+functions[compdef] )); then",` compdef ${fn} ${cliName}`,"fi",""].join(`
|
|
5
5
|
`)}function generateFishCompletions(cliName,subVerbs){let lines=[...TOP_LEVEL_SUBCOMMANDS.map((s)=>`complete -c ${cliName} -f -n __fish_use_subcommand -a ${s}`),...subVerbs.map(([command,verbs])=>`complete -c ${cliName} -f -n "__fish_seen_subcommand_from ${command}" -a "${verbs.join(" ")}"`)];return`# ${cliName} fish completions
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{API_VERBS,RETIRED_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-
|
|
2
|
+
import{API_VERBS,RETIRED_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-8d8q901q.js";import"./chunk-vhhzk3xj.js";import"./chunk-6tfx7mra.js";import"./chunk-pea31je5.js";import"./chunk-9kefy6ev.js";import"./chunk-3e5n28t6.js";import"./chunk-me23en52.js";import"./chunk-r2pztgm6.js";import"./chunk-38272eqv.js";import"./chunk-5f80ggc3.js";import"./chunk-qkehg2c1.js";import"./chunk-msr1xtay.js";import"./chunk-5jbj7b9t.js";import"./chunk-ahrjn20k.js";import"./chunk-srn281km.js";import"./chunk-ann3wt0v.js";import"./chunk-rhsvvdcn.js";import"./chunk-bkba9c4n.js";import"./chunk-g2advs8t.js";import"./chunk-zhbws9n3.js";import"./chunk-qqw3p4fc.js";import"./chunk-rcyasw34.js";import"./chunk-b99tf0jr.js";import"./chunk-7q67dz4c.js";import"./chunk-h8m37225.js";import"./chunk-hape5vwj.js";import"./chunk-5agemmmn.js";import"./chunk-y0nq7amn.js";import"./chunk-zqfbyq0a.js";import"./chunk-xwekyjat.js";import"./chunk-v2cpe974.js";import"./chunk-sdyzxayr.js";import"./chunk-w25b7xxz.js";import"./chunk-jvxh93nz.js";import"./chunk-h9mqdxvs.js";import"./chunk-8wv8526c.js";import"./chunk-0gepyh6e.js";import"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import"./chunk-jn5dd6bv.js";import"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-pxk2c2vj.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,RETIRED_VERBS,API_VERBS};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{ulid}from"./chunk-qkehg2c1.js";import{acquireWithRetry,mergeTasksWithDisk,readDiskIndex,recoverIndexFromDisk}from"./chunk-k1qe5qqa.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{release}from"./chunk-ayhhgfsz.js";import{LEGACY_KOBE_STATE_DIR_BASENAME,ROVE_STATE_DIR_BASENAME}from"./chunk-g56kvet6.js";import{readRoveHomeDirEnv}from"./chunk-r3k9rbwm.js";import{mkdir,open,rename,unlink}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var CURRENT_VERSION=3;class TaskIndexStore{homeDir;roveDir;path;legacyPath;lockPath;cache={version:CURRENT_VERSION,tasks:[]};loaded=!1;listeners=new Set;saveChain=Promise.resolve();dirtyIds=new Set;removedIds=new Map;constructor(options={}){this.homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),this.roveDir=join(this.homeDir,ROVE_STATE_DIR_BASENAME),this.path=join(this.roveDir,"tasks.json"),this.legacyPath=join(this.homeDir,LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),this.lockPath=`${this.path}.lock`}subscribe(listener){if(this.listeners.add(listener),this.loaded)try{listener(this.cache.tasks.slice())}catch(err){console.error("[rove TaskIndexStore] listener threw on subscribe:",err)}return()=>{this.listeners.delete(listener)}}get filePath(){return this.path}get stateDir(){return this.roveDir}async load(){return this.dirtyIds.clear(),this.removedIds.clear(),this.cache=await recoverIndexFromDisk(this.path,this.legacyPath),this.loaded=!0,this.notifyListeners(),this.snapshot()}async save(){this.assertLoaded();let next=this.saveChain.then(()=>this.doSave());return this.saveChain=next.catch(()=>{}),next}async saveOrRollback(id,undo){try{await this.save()}catch(err){if(undo())this.dirtyIds.delete(id),this.notifyListeners();throw err}}async doSave(){await mkdir(dirname(this.path),{recursive:!0});let dirty=new Set(this.dirtyIds),removed=new Map(this.removedIds),lockToken=await acquireWithRetry(this.lockPath),cacheChanged=!1;try{let disk=await readDiskIndex(this.path,this.legacyPath),merged=mergeTasksWithDisk(this.cache.tasks,disk.tasks,dirty,removed,disk.removed),payload={version:CURRENT_VERSION,tasks:merged.tasks,...merged.removed.length>0?{removed:merged.removed}:{}},json=`${JSON.stringify(payload)}
|
|
3
|
-
`,tmpPath=`${this.path}.${process.pid}.${ulid()}.tmp`;try{let handle=await open(tmpPath,"w",384);try{await handle.writeFile(json,"utf8"),await handle.sync()}finally{await handle.close()}await rename(tmpPath,this.path)}catch(err){throw await unlink(tmpPath).catch(()=>{}),err}for(let id of dirty)this.dirtyIds.delete(id);for(let id of removed.keys())this.removedIds.delete(id);let present=new Set(this.cache.tasks.map((t)=>t.id));for(let task of merged.tasks){if(present.has(task.id))continue;this.cache.tasks.push(task),cacheChanged=!0}let tombstoned=new Set(merged.removed.map((t)=>t.id));if(tombstoned.size>0)for(let i=this.cache.tasks.length-1;i>=0;i--){let entry=this.cache.tasks[i];if(!entry||!tombstoned.has(entry.id))continue;this.cache.tasks.splice(i,1),cacheChanged=!0}}finally{await release(this.lockPath,lockToken).catch((err)=>{console.error("[rove TaskIndexStore] index lock release failed:",err)})}if(cacheChanged)this.notifyListeners()}get(id){return this.assertLoaded(),this.cache.tasks.find((t)=>t.id===id)}list(){return this.assertLoaded(),this.cache.tasks.slice()}async create(partial){this.assertLoaded();let now=new Date().toISOString(),task={vendor:partial.vendor??DEFAULT_TASK_VENDOR,...partial,id:toTaskId(ulid()),createdAt:now,updatedAt:now};return this.cache.tasks.push(task),this.dirtyIds.add(task.id),await this.saveOrRollback(task.id,()=>{let at=this.cache.tasks.indexOf(task);if(at<0)return!1;return this.cache.tasks.splice(at,1),!0}),this.notifyListeners(),task}async update(id,patch){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)throw Error(`task not found: ${id}`);let existing=this.cache.tasks[idx];if(!existing)throw Error(`task not found: ${id}`);let{id:_id,createdAt:_createdAt,...mutable}=patch,next={...existing,...mutable,id:existing.id,createdAt:existing.createdAt,updatedAt:new Date().toISOString()};return this.cache.tasks[idx]=next,this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks[at]=existing,!0}),this.notifyListeners(),next}touchRecency(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return;let existing=this.cache.tasks[idx];if(!existing)return;this.cache.tasks[idx]={...existing,updatedAt:new Date().toISOString()},this.dirtyIds.add(String(id)),this.notifyListeners()}async move(id,delta,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);let ids=withinIds?.length?withinIds:this.cache.tasks.map((t)=>t.id),pos=ids.indexOf(String(id));if(pos<0)throw Error(`task not movable in current group: ${id}`);let targetId=ids[pos+delta];if(!targetId)return task;let fromIdx=this.cache.tasks.findIndex((t)=>t.id===id),toIdx=this.cache.tasks.findIndex((t)=>t.id===targetId);if(fromIdx<0||toIdx<0||fromIdx===toIdx)return task;let[moved]=this.cache.tasks.splice(fromIdx,1);if(!moved)return task;let adjustedToIdx=fromIdx<toIdx?toIdx-1:toIdx,insertAt=delta>0?adjustedToIdx+1:adjustedToIdx,next={...moved,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(insertAt,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,moved),!0}),this.notifyListeners(),next}async remove(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return!1;return this.cache.tasks.splice(idx,1),this.dirtyIds.delete(String(id)),this.removedIds.set(String(id),new Date().toISOString()),await this.
|
|
3
|
+
`,tmpPath=`${this.path}.${process.pid}.${ulid()}.tmp`;try{let handle=await open(tmpPath,"w",384);try{await handle.writeFile(json,"utf8"),await handle.sync()}finally{await handle.close()}await rename(tmpPath,this.path)}catch(err){throw await unlink(tmpPath).catch(()=>{}),err}for(let id of dirty)this.dirtyIds.delete(id);for(let id of removed.keys())this.removedIds.delete(id);let present=new Set(this.cache.tasks.map((t)=>t.id));for(let task of merged.tasks){if(present.has(task.id))continue;this.cache.tasks.push(task),cacheChanged=!0}let tombstoned=new Set(merged.removed.map((t)=>t.id));if(tombstoned.size>0)for(let i=this.cache.tasks.length-1;i>=0;i--){let entry=this.cache.tasks[i];if(!entry||!tombstoned.has(entry.id))continue;this.cache.tasks.splice(i,1),cacheChanged=!0}}finally{await release(this.lockPath,lockToken).catch((err)=>{console.error("[rove TaskIndexStore] index lock release failed:",err)})}if(cacheChanged)this.notifyListeners()}get(id){return this.assertLoaded(),this.cache.tasks.find((t)=>t.id===id)}list(){return this.assertLoaded(),this.cache.tasks.slice()}async create(partial){this.assertLoaded();let now=new Date().toISOString(),task={vendor:partial.vendor??DEFAULT_TASK_VENDOR,...partial,id:toTaskId(ulid()),createdAt:now,updatedAt:now};return this.cache.tasks.push(task),this.dirtyIds.add(task.id),await this.saveOrRollback(task.id,()=>{let at=this.cache.tasks.indexOf(task);if(at<0)return!1;return this.cache.tasks.splice(at,1),!0}),this.notifyListeners(),task}async update(id,patch){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)throw Error(`task not found: ${id}`);let existing=this.cache.tasks[idx];if(!existing)throw Error(`task not found: ${id}`);let{id:_id,createdAt:_createdAt,...mutable}=patch,next={...existing,...mutable,id:existing.id,createdAt:existing.createdAt,updatedAt:new Date().toISOString()};return this.cache.tasks[idx]=next,this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks[at]=existing,!0}),this.notifyListeners(),next}touchRecency(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return;let existing=this.cache.tasks[idx];if(!existing)return;this.cache.tasks[idx]={...existing,updatedAt:new Date().toISOString()},this.dirtyIds.add(String(id)),this.notifyListeners()}async move(id,delta,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);let ids=withinIds?.length?withinIds:this.cache.tasks.map((t)=>t.id),pos=ids.indexOf(String(id));if(pos<0)throw Error(`task not movable in current group: ${id}`);let targetId=ids[pos+delta];if(!targetId)return task;let fromIdx=this.cache.tasks.findIndex((t)=>t.id===id),toIdx=this.cache.tasks.findIndex((t)=>t.id===targetId);if(fromIdx<0||toIdx<0||fromIdx===toIdx)return task;let[moved]=this.cache.tasks.splice(fromIdx,1);if(!moved)return task;let adjustedToIdx=fromIdx<toIdx?toIdx-1:toIdx,insertAt=delta>0?adjustedToIdx+1:adjustedToIdx,next={...moved,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(insertAt,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,moved),!0}),this.notifyListeners(),next}async remove(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id),removed=this.cache.tasks[idx];if(idx<0||!removed)return!1;return this.cache.tasks.splice(idx,1),this.dirtyIds.delete(String(id)),this.removedIds.set(String(id),new Date().toISOString()),await this.saveOrRollback(String(id),()=>{if(this.cache.tasks.some((t)=>t.id===removed.id))return!1;return this.removedIds.delete(String(id)),this.cache.tasks.splice(Math.min(idx,this.cache.tasks.length),0,removed),!0}),this.notifyListeners(),!0}async _unlinkForTests(){try{await unlink(this.path)}catch(err){if(err.code!=="ENOENT")throw err}this.cache={version:CURRENT_VERSION,tasks:[]},this.loaded=!1,this.dirtyIds.clear(),this.removedIds.clear()}assertLoaded(){if(!this.loaded)throw Error("TaskIndexStore: call load() before any other method")}snapshot(){return{version:CURRENT_VERSION,tasks:this.cache.tasks.slice()}}notifyListeners(){if(this.listeners.size===0)return;let snapshot=this.cache.tasks.slice();for(let listener of this.listeners)try{listener(snapshot)}catch(err){console.error("[rove TaskIndexStore] listener threw on notify:",err)}}}
|
|
4
4
|
export{TaskIndexStore};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ensureGlobalKobeHooks,readTextWithTimeout,runHookSubcommand}from"./chunk-
|
|
2
|
+
import{ensureGlobalKobeHooks,readTextWithTimeout,runHookSubcommand}from"./chunk-c562kjgk.js";import"./chunk-3e5n28t6.js";import"./chunk-r2pztgm6.js";import"./chunk-38272eqv.js";import"./chunk-jvxh93nz.js";import"./chunk-h9mqdxvs.js";import"./chunk-8wv8526c.js";import"./chunk-0gepyh6e.js";import"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";export{runHookSubcommand,readTextWithTimeout,ensureGlobalKobeHooks};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{engineEntry,identifiableEngineIds}from"./chunk-
|
|
2
|
+
import{engineEntry,identifiableEngineIds}from"./chunk-xhw8s2es.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import{__require}from"./chunk-wqfp8d9w.js";import{basename}from"path";var WRAPPERS=new Set(["node","bun","npx","deno","sh","zsh","bash","env","script"]);function binaryName(token){return basename(token).replace(/\.(exe|js|mjs|cjs)$/,"")}function executableNameFromArgv(argv){for(let token of argv.slice(0,8)){if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))continue;let name=binaryName(token);if(WRAPPERS.has(name))continue;return name||null}return null}function vendorFromArgv(commandLine){let name=executableNameFromArgv(commandLine.trim().split(/\s+/));if(!name)return null;return identifiableEngineIds().find((v)=>{let entry=engineEntry(v);return entry.defaultCommand[0]===name||entry.processNames?.includes(name)===!0})??null}function parsePsSnapshot(text){let rows=[];for(let line of text.split(`
|
|
3
3
|
`)){let m=/^\s*(\d+)\s+(\d+)\s+(\S.*)$/.exec(line);if(m)rows.push({pid:Number(m[1]),ppid:Number(m[2]),args:m[3]})}return rows}function childrenIndex(rows){let kids=new Map;for(let row of rows){let list=kids.get(row.ppid);if(list)list.push(row);else kids.set(row.ppid,[row])}return kids}function hasAncestor(rows,pid,ancestorPid){let parents=new Map(rows.map((r)=>[r.pid,r.ppid])),cur=pid;for(let hops=0;hops<=rows.length;hops++){if(cur===ancestorPid)return!0;let next=parents.get(cur);if(next===void 0||next<=1)return!1;cur=next}return!1}function foregroundEngineIn(rows,rootPid){let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;let vendor=vendorFromArgv(row.args);if(vendor)return{vendor,argv:row.args,pid:row.pid};queue.push(...kids.get(row.pid)??[])}return null}function engineProcessIn(rows,rootPid,extraLaunch){if(foregroundEngineIn(rows,rootPid))return!0;let expected=extraLaunch?executableNameFromArgv(typeof extraLaunch==="string"?[extraLaunch]:extraLaunch):null;if(!expected)return!1;let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;if(executableNameFromArgv(row.args.trim().split(/\s+/))===expected)return!0;queue.push(...kids.get(row.pid)??[])}return!1}var PS_PROBE_TIMEOUT_MS=5000,bunPsSpawn=()=>{let proc=Bun.spawn(["ps","-A","-o","pid=,ppid=,args="],{stdout:"pipe",stderr:"ignore"});return{text:new Response(proc.stdout).text(),kill:()=>proc.kill()}};async function psSnapshotWith(spawn,timeoutMs=PS_PROBE_TIMEOUT_MS){let proc=spawn(),timer;try{let text=await Promise.race([proc.text,new Promise((_resolve,reject)=>{timer=setTimeout(()=>{try{proc.kill()}catch{}reject(new PsProbeUnavailableError(`ps did not answer within ${timeoutMs}ms`))},timeoutMs)})]);if(parsePsSnapshot(text).length===0)throw new PsProbeUnavailableError("ps returned no usable rows");return text}finally{if(timer)clearTimeout(timer)}}var psSnapshot=async(anchors)=>{if(process.platform!=="win32")return psSnapshotWith(bunPsSpawn);let{defaultWinProcessProbe,winProcessSnapshot}=await import("./chunk-qqxw72nh.js");return winProcessSnapshot(anchors??[],defaultWinProcessProbe())};async function foregroundEngine(rootPid,snapshot=psSnapshot){try{return foregroundEngineIn(parsePsSnapshot(await snapshot([rootPid])),rootPid)}catch{return null}}
|
|
4
4
|
export{vendorFromArgv,parsePsSnapshot,hasAncestor,foregroundEngineIn,engineProcessIn,PS_PROBE_TIMEOUT_MS,psSnapshotWith,psSnapshot,foregroundEngine};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{publishKobeTerminalTitle}from"./chunk-dw853n4w.js";import{ensureGlobalKobeHooks}from"./chunk-
|
|
2
|
+
import{publishKobeTerminalTitle}from"./chunk-dw853n4w.js";import{ensureGlobalKobeHooks}from"./chunk-c562kjgk.js";import{maybeHintSkillInstall}from"./chunk-m0g17ckn.js";import{enforceResetGate}from"./chunk-dx6v0yw8.js";import"./chunk-3e5n28t6.js";import"./chunk-r2pztgm6.js";import"./chunk-38272eqv.js";import"./chunk-5jbj7b9t.js";import"./chunk-jvxh93nz.js";import"./chunk-h9mqdxvs.js";import"./chunk-8wv8526c.js";import"./chunk-0gepyh6e.js";import"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";async function startTui(){enforceResetGate(),publishKobeTerminalTitle(),await maybeHintSkillInstall(),await ensureGlobalKobeHooks();let{loadPluginEngines}=await import("./chunk-655y4wyd.js");loadPluginEngines();let{startWorkspaceHost}=await import("./chunk-fg6wc4bh.js");await startWorkspaceHost()}export{startTui};
|
|
@@ -3,7 +3,7 @@ import{getPersistedString,setPersistedString}from"./chunk-6wpege0h.js";import{ac
|
|
|
3
3
|
Install Node.js (https://nodejs.org) and run it again \u2014 the Rove installer only installs Bun and Rove.`}async function runNpxSkillsInstall(agent,global){if(isNpxMissing())return process.stderr.write(`
|
|
4
4
|
${npxMissingMessage()}
|
|
5
5
|
|
|
6
|
-
`),NPX_MISSING_EXIT;return await Bun.spawn(["npx",...npxSkillsArgv({...agent===void 0?{}:{agent},global})],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}var HINT_SEEN_KEY="skillHintSeen";function markSkillHintSeen(){setPersistedString(HINT_SEEN_KEY,"1")}function kobeSkillPaths(opts={}){let home=opts.home??homedir(),cwd=opts.cwd??process.cwd();return[home,cwd].flatMap((root)=>SKILL_REL_PATHS.map((rel)=>join(root,rel)))}function parseSkillVersion(content){let m=content.match(/(?:rove|kobe)-skill-version:\s*(\d+)/);return m?Number.parseInt(m[1],10):null}function skillVersionAt(path){try{return parseSkillVersion(readFileSync(path,"utf8"))}catch{return null}}function inodeKey(path){try{let stat=statSync(path);return`${stat.dev}:${stat.ino}`}catch{return path}}function distinctSkillFiles(roots,rels){let seen=new Set,out=[];for(let root of roots)for(let rel of rels){let path=join(root,rel);if(!existsSync(path))continue;let key=inodeKey(path);if(seen.has(key))continue;seen.add(key),out.push(path)}return out}function installedSkillDirs(home=homedir()){return distinctSkillFiles([home],SKILL_REL_PATHS).map((path)=>dirname(path))}function kobeSkillState(opts={}){let roots=[opts.home??homedir(),opts.cwd??process.cwd()],roveCopies=distinctSkillFiles(roots,ROVE_SKILL_REL_PATHS).map((path)=>({path,version:skillVersionAt(path)})),legacy=distinctSkillFiles(roots,LEGACY_SKILL_REL_PATHS).map((path)=>({path,version:skillVersionAt(path)})),best=[...roveCopies].sort((a,b)=>(b.version??-1)-(a.version??-1))[0]??legacy[0];if(!best)return{installed:!1,installedVersion:null,currentVersion:KOBE_SKILL_VERSION,stale:!1,legacyCopies:[]};let stale=best.version===null||best.version<KOBE_SKILL_VERSION;return{installed:!0,installedVersion:best.version,currentVersion:KOBE_SKILL_VERSION,stale,legacyCopies:legacy.filter((copy)=>copy.path!==best.path)}}function describeLegacyCopies(copies){return copies.map((c)=>`${c.path}${c.version===null?"":` (v${c.version})`}`).join(", ")}function promptLine(){return new Promise((resolve2)=>{process.stdin.resume(),process.stdin.once("data",(d)=>{process.stdin.pause(),resolve2(String(d))})})}async function maybeHintSkillInstall(io={}){let{isRovePluginEnabled}=await import("./chunk-
|
|
6
|
+
`),NPX_MISSING_EXIT;return await Bun.spawn(["npx",...npxSkillsArgv({...agent===void 0?{}:{agent},global})],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}var HINT_SEEN_KEY="skillHintSeen";function markSkillHintSeen(){setPersistedString(HINT_SEEN_KEY,"1")}function kobeSkillPaths(opts={}){let home=opts.home??homedir(),cwd=opts.cwd??process.cwd();return[home,cwd].flatMap((root)=>SKILL_REL_PATHS.map((rel)=>join(root,rel)))}function parseSkillVersion(content){let m=content.match(/(?:rove|kobe)-skill-version:\s*(\d+)/);return m?Number.parseInt(m[1],10):null}function skillVersionAt(path){try{return parseSkillVersion(readFileSync(path,"utf8"))}catch{return null}}function inodeKey(path){try{let stat=statSync(path);return`${stat.dev}:${stat.ino}`}catch{return path}}function distinctSkillFiles(roots,rels){let seen=new Set,out=[];for(let root of roots)for(let rel of rels){let path=join(root,rel);if(!existsSync(path))continue;let key=inodeKey(path);if(seen.has(key))continue;seen.add(key),out.push(path)}return out}function installedSkillDirs(home=homedir()){return distinctSkillFiles([home],SKILL_REL_PATHS).map((path)=>dirname(path))}function kobeSkillState(opts={}){let roots=[opts.home??homedir(),opts.cwd??process.cwd()],roveCopies=distinctSkillFiles(roots,ROVE_SKILL_REL_PATHS).map((path)=>({path,version:skillVersionAt(path)})),legacy=distinctSkillFiles(roots,LEGACY_SKILL_REL_PATHS).map((path)=>({path,version:skillVersionAt(path)})),best=[...roveCopies].sort((a,b)=>(b.version??-1)-(a.version??-1))[0]??legacy[0];if(!best)return{installed:!1,installedVersion:null,currentVersion:KOBE_SKILL_VERSION,stale:!1,legacyCopies:[]};let stale=best.version===null||best.version<KOBE_SKILL_VERSION;return{installed:!0,installedVersion:best.version,currentVersion:KOBE_SKILL_VERSION,stale,legacyCopies:legacy.filter((copy)=>copy.path!==best.path)}}function describeLegacyCopies(copies){return copies.map((c)=>`${c.path}${c.version===null?"":` (v${c.version})`}`).join(", ")}function promptLine(){return new Promise((resolve2)=>{process.stdin.resume(),process.stdin.once("data",(d)=>{process.stdin.pause(),resolve2(String(d))})})}async function maybeHintSkillInstall(io={}){let{isRovePluginEnabled}=await import("./chunk-bggpzxk2.js");if(isRovePluginEnabled())return;let cliName=activeCliName(),installCommand=skillInstallCommand(),state=kobeSkillState();if(!state.installed){if(getPersistedString(HINT_SEEN_KEY)==="1")return;setPersistedString(HINT_SEEN_KEY,"1"),process.stderr.write(`
|
|
7
7
|
${cliName}: the Rove agent skill isn't installed \u2014 install it so your coding agent can drive Rove via \`${cliName} api\`:
|
|
8
8
|
${installCommand}
|
|
9
9
|
(wraps \`${npxSkillsCommand()}\`; check anytime with \`${cliName} doctor\`)
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{TaskDeletingError,deriveTitleFromPrompt}from"./chunk-9kefy6ev.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp,sessionHasEngine,trustEngineWorktree}from"./chunk-
|
|
2
|
+
import{TaskDeletingError,deriveTitleFromPrompt}from"./chunk-9kefy6ev.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp,sessionHasEngine,trustEngineWorktree}from"./chunk-ann3wt0v.js";import{engineLaunchArgv,protocolEntry}from"./chunk-qqw3p4fc.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";var MAX_SESSIONS_SCANNED=8;function titleFromMessages(messages){let firstUser=messages.find((m)=>m.role==="user");if(!firstUser)return"";let text=firstUser.blocks.filter((b)=>b.type==="text").map((b)=>b.text).join(" "),title=deriveTitleFromPrompt(text);return title.length>0?Buffer.from(title,"utf8").toString("utf8"):title}async function deriveTitleFromSession(worktree,vendor=DEFAULT_TASK_VENDOR){if(!worktree)return"";let{history}=protocolEntry(vendor),ids=await history.listSessionIdsForWorktree(worktree);for(let sessionId of ids.slice(0,MAX_SESSIONS_SCANNED)){let title=titleFromMessages(await history.readHistory(sessionId));if(title)return title}return""}async function deriveTitleFromSessionId(vendor,sessionId){if(!sessionId)return"";try{return titleFromMessages(await protocolEntry(vendor).history.readHistory(sessionId))}catch{return""}}async function getTask(link,taskId){let{task}=await link.request("task.get",{taskId});return task}async function ensureTaskWorktree(link,taskId){let task=await getTask(link,taskId);if(task.deletion)throw new TaskDeletingError(taskId);if(task.worktreePath)return{task,worktreePath:task.worktreePath};let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"}),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)throw Error(`failed to start hosted engine session for ${taskId}`);if(launch.firstMessage){let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort})[0];await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs}).catch(()=>!1)}}finally{host.close()}return{session:launch.key,worktreePath}}async function startTaskSessionWithPromptAdapter(link,taskId,prompt){let{task,worktreePath}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt}),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)return{started:!1,error:"hosted session did not open"};let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort})[0],wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs};if(launch.firstMessage){if(await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,wait)!==null)return{started:!0};return{started:!1,error:await startFailureReason(host.rpc,launch.key)}}if(await awaitEngineProcess(host.rpc,launch.key,engineBin,wait)!==null)return{started:!0};return{started:!1,error:await startFailureReason(host.rpc,launch.key)}}finally{host.close()}}async function startFailureReason(rpc,key){let tail=await hostedSessionFailureLine(rpc,key),base="engine process never started";return tail?`engine process never started; last session output: ${tail}`:"engine process never started"}function taskEngineLaunch(task,worktreePath,promptIntent){return trustEngineWorktree(task.vendor,worktreePath),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo},worktreePath,shell:resolveLoginShell({fallback:"/bin/zsh"}),argv:engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort}),promptIntent})}async function deliverPromptToLiveEngineAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return!1;try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0]);if(!key)return!1;if(!await sessionHasEngine(sessions.find((s)=>s.key===key)?.pid,engineArgv))return!1;let manifest=task.vendor?protocolEntry(task.vendor).screenManifest:void 0;return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})!==null}catch(err){if(err instanceof ComposerBusyError)throw err;return!1}finally{host.close()}}function tabIdFromHostedKey(key){return key.split("::")[1]??"tab-1"}async function deliverPromptToLiveEngineDetailedAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0]);if(!key)return{outcome:"no-session"};if(!await sessionHasEngine(sessions.find((s)=>s.key===key)?.pid,engineArgv))return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};let manifest=task.vendor?protocolEntry(task.vendor).screenManifest:void 0;try{return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}catch(err){if(err instanceof ComposerBusyError)return{outcome:"busy",tabId:tabIdFromHostedKey(key),layer:err.layer};throw err}}catch{return{outcome:"no-session"}}finally{host.close()}}async function deliverPromptToLiveEngineTabDetailedAdapter(target,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let key=`${target.id}::${target.tabId}`,sessions;try{sessions=await listHostedSessions(host.rpc)}catch{return{outcome:"no-session"}}let session=sessions.find((candidate)=>candidate.alive&&candidate.key===key);if(!session)return{outcome:"no-session"};let engineArgv=engineLaunchArgv({command:target.command,vendor:target.vendor});if(!await sessionHasEngine(session.pid,engineArgv))return{outcome:"no-engine",tabId:target.tabId};let manifest=target.vendor?protocolEntry(target.vendor).screenManifest:void 0;try{return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}catch(err){if(err instanceof ComposerBusyError)return{outcome:"busy",tabId:target.tabId,layer:err.layer};throw err}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId){let host=await openHostedSessionHost();if(!host)return;try{await killHostedSessions(host.rpc,hostedTaskKeys(await listHostedSessions(host.rpc),taskId))}catch{}finally{host.close()}}
|
|
3
3
|
export{deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,tearDownTaskSessionAdapter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{submitFeedback}from"./chunk-
|
|
2
|
+
import{submitFeedback}from"./chunk-pea31je5.js";import"./chunk-5jbj7b9t.js";import"./chunk-ch9b1d5y.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";import{readFileSync}from"fs";var CLI_NAME=activeCliName(),FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--category <slug>]`,"","Create a GitHub Discussion in the Rove repository using the GitHub CLI.","","Requires:"," gh auth login","","Options:"," --title <text> Discussion title"," --body <text> Discussion body"," --body-file <path> Read the Discussion body from a file; use - for stdin"," --category <slug> Discussion category slug (default: feedback)"," -h, --help Print this help",""].join(`
|
|
3
3
|
`);function usageError(message){process.stderr.write(`${CLI_NAME} feedback: ${message}
|
|
4
4
|
|
|
5
5
|
${FEEDBACK_USAGE}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Orchestrator}from"./chunk-6wfwskxn.js";import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,tearDownTaskSessionAdapter}from"./chunk-
|
|
2
|
+
import{Orchestrator}from"./chunk-6wfwskxn.js";import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,tearDownTaskSessionAdapter}from"./chunk-m66t4fvt.js";import{GH_PR_VIEW_FIELDS,classifyGhFailure,mapGhPrView,nextPrPoll,samePrStatus}from"./chunk-zfqm8rmp.js";import"./chunk-tqat428f.js";import{resolvePluginBinPath}from"./chunk-d4vadrmy.js";import{GitWorktreeManager,parseDirtyPaths}from"./chunk-cwnwj3r8.js";import{auditDeletionBranchKept,auditDeletionResidue,auditDeletionSalvaged,auditWorktreeResidue,auditWorktreeSalvaged,parseAheadBehind,startDaemonServer}from"./chunk-sd4f9che.js";import"./chunk-044s3zc5.js";import"./chunk-rz8zs7j8.js";import"./chunk-41ahvk51.js";import{TaskIndexStore}from"./chunk-hxfj85yw.js";import"./chunk-4rabzw5d.js";import"./chunk-kn3pgymw.js";import{parsePorcelain}from"./chunk-xqw5d5rv.js";import"./chunk-h4n8ffqy.js";import{DEFAULT_BASE_REF_CANDIDATES,readHeadSha,readRefSha,resolveGitDirs}from"./chunk-vyb5a2rh.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-9kefy6ev.js";import{affectsActivityState,isEngineActivityKind}from"./chunk-3e5n28t6.js";import"./chunk-me23en52.js";import"./chunk-r2pztgm6.js";import"./chunk-38272eqv.js";import"./chunk-5f80ggc3.js";import"./chunk-qkehg2c1.js";import{SUBCOMMAND_VERBS}from"./chunk-s76r56rj.js";import{CURRENT_VERSION,checkLatestVersion}from"./chunk-5jbj7b9t.js";import{autoStatusEnabled,deliveryGuard}from"./chunk-ann3wt0v.js";import{execHostForWorktreePath}from"./chunk-rhsvvdcn.js";import"./chunk-bkba9c4n.js";import"./chunk-g2advs8t.js";import"./chunk-zhbws9n3.js";import{GENERIC_PROTOCOL,engineProtocolKey,getEngineProtocol,protocolEntry,resolveCommandProtocol,sessionProtocol}from"./chunk-qqw3p4fc.js";import{installDaemonCrashHandlers,logDaemonInfo}from"./chunk-rcyasw34.js";import"./chunk-b99tf0jr.js";import"./chunk-7q67dz4c.js";import"./chunk-h8m37225.js";import"./chunk-hape5vwj.js";import{engineDisplayName,kobeApiInvocation}from"./chunk-5agemmmn.js";import"./chunk-y0nq7amn.js";import"./chunk-zqfbyq0a.js";import"./chunk-v2cpe974.js";import"./chunk-sdyzxayr.js";import"./chunk-w25b7xxz.js";import"./chunk-jvxh93nz.js";import{connectOrStartDaemon,daemonSpawnReason}from"./chunk-h9mqdxvs.js";import{stopDaemonProcess}from"./chunk-8wv8526c.js";import{KobeDaemonClient}from"./chunk-0gepyh6e.js";import"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-jn5dd6bv.js";import{createEngineTurnDetector,engineEntry,engineTitleTurnHint,vendorsWithQuotaProbe}from"./chunk-xhw8s2es.js";import{spawnCapture}from"./chunk-khj0apc7.js";import{availableEngineIds}from"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import{DEFAULT_TASK_VENDOR,isTaskStatus}from"./chunk-xy8be792.js";import{backfillSavedReposFromProjects,getCustomEngineIds,getPersistedString,getRemoteRepoConfig,getSavedRepos,setPersistedString}from"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import{releaseSync}from"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import{isProcessAlive,readPidFile}from"./chunk-mv7ptt5w.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import{migrateRoveDaemonStateLayout}from"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-pxk2c2vj.js";import"./chunk-k2ckx8zw.js";import{rotateLogIfNeeded}from"./chunk-pw6yfj10.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-mcdv19rs.js";import{readRoveHomeDirEnv}from"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";function sniffProtocolFromTitle(title){let trimmed=title?.trim();if(!trimmed)return null;let owners=new Map;for(let vendor of BUILTIN_VENDORS)for(let glyph of engineEntry(vendor).terminalTitle?.statusPrefixes??[])owners.set(glyph,[...owners.get(glyph)??[],vendor]);for(let glyph of[...owners.keys()].sort((a,b)=>b.length-a.length)){if(!trimmed.startsWith(glyph))continue;if(trimmed.slice(glyph.length).trim().length===0)continue;let vendors=owners.get(glyph)??[];if(vendors.length===1)return vendors[0];return null}return null}function protocolUpgradeFromLiveSession(task,evidence){let command=task.command?.trim();if(!command)return null;if(task.vendor&&isBuiltinVendor(task.vendor))return null;if(resolveCommandProtocol(command)!==GENERIC_PROTOCOL)return null;let walk=evidence.walkVendor,vendor=walk!==null&&isBuiltinVendor(walk)?walk:sniffProtocolFromTitle(evidence.title);return vendor?{command,vendor}:null}function protocolWriteBackFromLiveSession(task,evidence,customEngineIds){let id=task.vendor?.trim();if(!id)return null;if(getEngineProtocol(id)!==void 0)return null;if(!customEngineIds.includes(id))return null;let walk=evidence.walkVendor;return walk!==null&&isBuiltinVendor(walk)?{id,protocol:walk}:null}async function latestTranscriptMtime(vendor,worktree){if(!worktree)return 0;return protocolEntry(vendor).history.latestTranscriptMtimeForWorktree(worktree)}async function maybeAutoStart(orch,taskId,enabled=autoStatusEnabled){if(!enabled())return"skipped";let task=orch.getTask(taskId);if(!task)return"skipped";if((task.kind??"task")==="main")return"skipped";if(task.status!=="backlog")return"skipped";return await orch.setStatus(taskId,"in_progress"),"moved"}var SYNC_TIMEOUT_MS=60000,SYNC_CONFLICT="SYNC_CONFLICT",SYNC_DIRTY="SYNC_WORKTREE_DIRTY";async function git(cwd,args,signal,write=!1){return spawnCapture("git",args,{cwd,env:write?process.env:readOnlyGitProcessEnv(),signal})}function parseConflictedPaths(stdout){return stdout.split(`
|
|
3
3
|
`).map((line)=>line.trim()).filter((line)=>line.length>0)}async function syncWorktreeWithBase(worktreePath,baseRef,signal){let status=await git(worktreePath,["status","--porcelain=v1"],signal);if(status.status!==0)throw Error("git status failed");let dirty=parseDirtyPaths(status.stdout);if(dirty.length>0)throw Error(`${SYNC_DIRTY}: ${dirty.join(", ")}`);let before=await git(worktreePath,["rev-parse","HEAD"],signal),merge=await git(worktreePath,["merge","--no-edit",baseRef],signal,!0);if(merge.status!==0){let conflicted=await git(worktreePath,["diff","--name-only","--diff-filter=U"],signal),paths=parseConflictedPaths(conflicted.stdout);if(paths.length>0)throw Error(`${SYNC_CONFLICT}: ${paths.join(", ")}`);let detail=merge.stderr?.trim();throw Error(detail?`git merge ${baseRef} failed \u2014 ${detail}`:`git merge ${baseRef} failed`)}let after=await git(worktreePath,["rev-parse","HEAD"],signal);return{baseRef,alreadyCurrent:before.status===0&&before.stdout.trim()===after.stdout.trim()}}import{readFileSync}from"fs";import{join}from"path";var BASE_REF_TTL_MS=300000,cache=new Map;async function git2(worktreePath,args,signal){return await spawnCapture("git",[...args],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal})}async function refExists(worktreePath,ref,signal){return(await git2(worktreePath,["rev-parse","--verify","--quiet",ref],signal)).status===0}async function sharesHistory(worktreePath,ref,signal){return(await git2(worktreePath,["merge-base",ref,"HEAD"],signal)).status===0}async function baseCheckoutBranchFromGit(worktreePath,signal){let out=await git2(worktreePath,["worktree","list","--porcelain"],signal);if(out.status!==0)return null;return(out.stdout.split(`
|
|
4
4
|
|
|
5
5
|
`,1)[0]??"").split(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{CURRENT_VERSION,repoSlug}from"./chunk-
|
|
2
|
+
import{CURRENT_VERSION,repoSlug}from"./chunk-5jbj7b9t.js";import{spawnSync}from"child_process";var DEFAULT_FEEDBACK_CATEGORY_SLUG="feedback",DISCUSSION_CATEGORY_QUERY=`
|
|
3
3
|
query($owner: String!, $name: String!) {
|
|
4
4
|
repository(owner: $owner, name: $name) {
|
|
5
5
|
id
|
|
@@ -6,6 +6,6 @@ ${EXPORT_USAGE}
|
|
|
6
6
|
`),process.exit(2)}function parseFormat(args){let format="json";for(let i=0;i<args.length;i++){let a=args[i];if(a==="--json")format="json";else if(a==="--csv")format="csv";else if(a==="--format"){let v=args[++i];if(v===void 0)usageError("--format requires a value (json, csv, or table)");format=coerceFormat(v)}else if(a.startsWith("--format="))format=coerceFormat(a.slice(9));else usageError(`unexpected argument "${a}"`)}return format}function coerceFormat(value){if(value==="json"||value==="csv"||value==="table")return value;usageError(`unknown format "${value}" (expected json, csv, or table)`)}function csvCell(value){if(/[",\r\n]/.test(value))return`"${value.replace(/"/g,'""')}"`;return value}function renderCsv(rows){let lines=[COLUMNS.join(",")];for(let row of rows)lines.push(COLUMNS.map((c)=>csvCell(row[c])).join(","));return lines.join(`
|
|
7
7
|
`)}function padCell(cell,width){return cell+" ".repeat(Math.max(0,width-displayWidth(cell)))}function renderTable(rows){let widths={};for(let c of COLUMNS)widths[c]=Math.max(displayWidth(c),...rows.map((r)=>displayWidth(r[c])));let line=(cells)=>COLUMNS.map((c)=>padCell(cells[c],widths[c])).join(" ").trimEnd(),header={};for(let c of COLUMNS)header[c]=c;return[line(header),...rows.map(line)].join(`
|
|
8
8
|
`)}function renderExport(tasks,format){let rows=tasks.map(toRow);if(format==="json")return JSON.stringify(rows,null,2);if(format==="csv")return renderCsv(rows);return renderTable(rows)}async function runExportSubcommand(args){if(args.includes("--help")||args.includes("-h")||args.includes("help")){process.stdout.write(`${EXPORT_USAGE}
|
|
9
|
-
`);return}let format=parseFormat(args),{TaskIndexStore}=await import("./chunk-
|
|
9
|
+
`);return}let format=parseFormat(args),{TaskIndexStore}=await import("./chunk-skysscx4.js"),store=new TaskIndexStore;await store.load();let tasks=store.list();if(tasks.length===0&&format==="table"){process.stdout.write(`no tasks
|
|
10
10
|
`);return}process.stdout.write(`${renderExport(tasks,format)}
|
|
11
11
|
`)}export{runExportSubcommand,renderExport};
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,probeEngines,probeGit,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-
|
|
3
|
-
`)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids,deps={}){let runProbe=deps.run??run,readEnviron=deps.readEnviron??((pid)=>
|
|
2
|
+
import{applyFixes,daemonRestartFix,defaultFixRuntime,engineTabsManualFix,humanOnlyFix,killOrphansManualFix,noEngineFix,probeEngines,probeGit,reinstallManualFix,resetManualFix,skillInstallFix,spawnHelperFix}from"./chunk-8wrzdj5x.js";import{formatBytes}from"./chunk-my20q579.js";import"./chunk-3p2e2ry4.js";import"./chunk-sd4f9che.js";import"./chunk-044s3zc5.js";import"./chunk-rz8zs7j8.js";import"./chunk-41ahvk51.js";import{kobeSkillState,skillInstallCommand}from"./chunk-m0g17ckn.js";import{inspectLegacyTmux,legacyTmuxDoctorLines}from"./chunk-dqndd97s.js";import"./chunk-4rabzw5d.js";import"./chunk-h4n8ffqy.js";import"./chunk-vyb5a2rh.js";import"./chunk-r2pztgm6.js";import"./chunk-38272eqv.js";import"./chunk-5f80ggc3.js";import{CURRENT_VERSION,package_default}from"./chunk-5jbj7b9t.js";import{resolveNodeBinary}from"./chunk-zhbws9n3.js";import"./chunk-qqw3p4fc.js";import{formatDaemonInfo}from"./chunk-rcyasw34.js";import"./chunk-b99tf0jr.js";import"./chunk-5agemmmn.js";import{t}from"./chunk-xwekyjat.js";import"./chunk-v2cpe974.js";import"./chunk-sdyzxayr.js";import"./chunk-w25b7xxz.js";import"./chunk-jvxh93nz.js";import{isStaleInstallError,resolveKobeSpawn}from"./chunk-h9mqdxvs.js";import"./chunk-8wv8526c.js";import{KobeDaemonClient}from"./chunk-0gepyh6e.js";import{isForeignDaemonHome}from"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import"./chunk-jn5dd6bv.js";import{createEngineHookAdapter}from"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import{parseHookSettings}from"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import{readableLegacyIndexPath}from"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import{ALL_VENDORS}from"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import{homeDir,kvStatePath,roveStateDir}from"./chunk-ch9b1d5y.js";import{readPidFile}from"./chunk-mv7ptt5w.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import{LEGACY_KOBE_STATE_DIR_BASENAME}from"./chunk-g56kvet6.js";import"./chunk-pxk2c2vj.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostLogPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";import{existsSync,readFileSync as readFileSync3,statSync as statSync2}from"fs";import{join as join2}from"path";import{readFileSync}from"fs";function hookConfigIssues(){let issues=[];for(let vendor of ALL_VENDORS){let adapter=createEngineHookAdapter(vendor);if(!adapter.supportsHooks())continue;let file=adapter.globalSettingsPath();if(!file||!file.endsWith(".json"))continue;let raw;try{raw=readFileSync(file,"utf8")}catch{continue}let parsed=parseHookSettings(raw);if(!parsed.ok)issues.push({file,reason:parsed.reason})}return issues}var MIN_BUN_VERSION=package_default.engines.bun.match(/\d+\.\d+\.\d+/)?.[0]??"0.0.0";function parseBunVersion(raw){return raw.trim().match(/^v?(\d+\.\d+\.\d+)/)?.[1]??null}function isBunAtLeast(raw,minimum=MIN_BUN_VERSION){let found=parseBunVersion(raw),floor=parseBunVersion(minimum);if(!found||!floor)return!0;let a=found.split(".").map(Number),b=floor.split(".").map(Number);for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(av!==bv)return av>bv}return!0}function classifyHookChannel(input){let total=0,hooked=0;for(let tabs of Object.values(input.tabs))for(let entry of Object.values(tabs))if(total++,entry.source==="hook")hooked++;if(total===0)return{kind:"no-tabs"};if(hooked===0)return{kind:"down",totalTabs:total};return{kind:"live",hookTabs:hooked,totalTabs:total}}function hookChannelDoctorLines(verdict,input,cliName){let configLines=(input.configIssues??[]).flatMap((issue)=>[` \u26A0 hook install skipped: ${issue.file}`,` ${issue.reason} \u2014 fix the file, then relaunch Rove`]);if(verdict.kind==="no-tabs")return["hooks: \u2014 no engine tabs yet (nothing to check)",...configLines];if(verdict.kind==="live")return[`hooks: \u2713 engine hook channel live (${verdict.hookTabs}/${verdict.totalTabs} tab(s) hook-sourced)`,...configLines];let out=[`hooks: \u2717 NO hook events reaching the daemon (0/${verdict.totalTabs} tab(s) hook-sourced)`," badges fall back to a ~10s poll, so activity looks seconds late",` daemon socket: ${input.socketPath}`,...configLines];return out.push(' \u2192 compare with an engine tab\'s own path: `ps eww -p <engine-pid> | tr " " "\\n" | grep DAEMON_SOCKET_PATH`',` \u2192 restart the engine tabs (they may hold a stale socket path), or run \`${cliName} daemon restart\``,` \u2192 debug one hook directly: \`KOBE_HOOK_DEBUG=1 echo '{}' | ${cliName} hook turn-start --engine claude\``),out}import{readdirSync,statSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";function installedSpawnHelpers(){let pkg;try{pkg=dirname(createRequire(import.meta.url).resolve("node-pty/package.json"))}catch{return[]}let prebuilds=join(pkg,"prebuilds"),arches;try{arches=readdirSync(prebuilds).filter((name)=>name.startsWith("darwin-"))}catch{return[]}let helpers=[];for(let arch of arches){let path=join(prebuilds,arch,"spawn-helper");try{helpers.push({path,executable:(statSync(path).mode&64)!==0})}catch{}}return helpers}function spawnHelperDoctorLines(helpers){let broken=helpers.filter((helper)=>!helper.executable).map((helper)=>helper.path);if(helpers.length===0)return{lines:["node-pty: ? no darwin spawn-helper found next to node-pty"],broken};if(broken.length===0)return{lines:[`node-pty: \u2713 spawn-helper executable (${helpers.length} arch)`],broken};return{lines:["node-pty: \u2717 spawn-helper is not executable \u2014 every node-pty PTY spawn fails",...broken.map((path)=>` ${path}`),` \u2192 chmod 755 ${broken.join(" ")}`],broken}}import{appendFileSync,readFileSync as readFileSync2}from"fs";var PTY_MARKER="KOBE_TERMINAL_PTY=1",run=async(argv)=>{try{let proc=Bun.spawn([...argv],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),[stdout,code]=await Promise.all([new Response(proc.stdout).text().catch(()=>""),proc.exited]);return{code,stdout}}catch{return{code:127,stdout:""}}};function parsePsRows(output){let rows=[];for(let line of output.split(`
|
|
3
|
+
`)){let parts=line.trim().split(/\s+/);if(parts.length<6)continue;let[pid,ppid,pgid]=[parts[0],parts[1],parts[2]].map((value)=>Number.parseInt(value??"",10)),rssKb=Number.parseInt(parts[4]??"",10);if(!Number.isFinite(pid)||!Number.isFinite(ppid)||!Number.isFinite(pgid)||!Number.isFinite(rssKb))continue;rows.push({pid,ppid,pgid,etime:parts[3]??"",rssKb,command:parts.slice(5).join(" ")})}return rows}function pidAlive(pid,rows){return rows.some((row)=>row.pid===pid)}function orphanCandidates(rows,selfPgid,liveSessionPids){return rows.filter((row)=>row.ppid===1&&row.pgid!==selfPgid&&!liveSessionPids.has(row.pgid)&&!pidAlive(row.pgid,rows))}async function markedPids(pids,deps={}){let runProbe=deps.run??run,readEnviron=deps.readEnviron??((pid)=>readFileSync2(`/proc/${pid}/environ`,"utf8")),marked=new Set;if(pids.length===0)return{marked,failed:null};if((deps.platform??process.platform)==="linux"){let refused=null;for(let pid of pids)try{if(readEnviron(pid).split("\x00").includes(PTY_MARKER))marked.add(pid)}catch(err){let code=err.code;if(code!=="ENOENT"&&code!=="ESRCH")refused??=`/proc/${pid}/environ: ${code??"unreadable"}`}return{marked,failed:refused}}let result=await runProbe(["ps","eww","-o","pid=,command=","-p",pids.join(",")]);if(result.code!==0)return{marked,failed:`ps eww exited ${result.code}`};let marker=new RegExp(`(^|\\s)${PTY_MARKER}(\\s|$)`);for(let line of result.stdout.split(`
|
|
4
4
|
`)){let pid=Number.parseInt(line.trim().split(/\s+/)[0]??"",10);if(Number.isFinite(pid)&&marker.test(line))marked.add(pid)}return{marked,failed:null}}async function ownPgid(runProbe){let result=await runProbe(["ps","-o","pgid=","-p",String(process.pid)]),pgid=Number.parseInt(result.stdout.trim(),10);return Number.isFinite(pgid)?pgid:-1}async function collectOrphans(liveSessionPids,deps={}){let runProbe=deps.run??run;if((deps.platform??process.platform)==="win32")return{orphans:[],error:null};let ps=await runProbe(["ps","-A","-o","pid=,ppid=,pgid=,etime=,rss=,command="]);if(ps.code!==0)return{orphans:[],error:`could not read the process table \u2014 ps exited ${ps.code}`};let rows=parsePsRows(ps.stdout),candidates=orphanCandidates(rows,await ownPgid(runProbe),liveSessionPids),{marked,failed}=await markedPids(candidates.map((row)=>row.pid),deps);if(failed)return{orphans:[],error:`could not read process environments \u2014 ${failed}`};return{orphans:candidates.filter((row)=>marked.has(row.pid)),error:null}}function formatMb(rssKb){return`${(rssKb/1024).toFixed(0)} MB`}function orphanDoctorLines(orphans,error,cliName,killing=!1){if(error)return[`orphans: \u2717 ${error}`];if(orphans.length===0)return["orphans: \u2713 none \u2014 no processes left behind by a dead PTY session"];let totalMb=orphans.reduce((sum,row)=>sum+row.rssKb,0)/1024,lines=[`orphans: \u26A0 ${orphans.length} process(es) outlived the PTY session that spawned them (${totalMb.toFixed(0)} MB RSS)`," each is reparented to init, carries Rove's PTY marker, and its process"," group leader is gone \u2014 no live task owns them"];for(let row of[...orphans].sort((a,b)=>b.rssKb-a.rssKb))lines.push(` pid ${row.pid} (group ${row.pgid}) up ${row.etime}, ${formatMb(row.rssKb)}: ${row.command.slice(0,90)}`);if(!killing)lines.push(` \u2192 \`${cliName} doctor --kill-orphans\` ends those process groups (SIGTERM, then SIGKILL)`," read the list first: something you backgrounded from a Rove terminal and then"," closed the tab on looks exactly like a leak, and doctor cannot tell them apart");return lines}var GROUP_EXIT_GRACE_MS=2000,GROUP_POLL_MS=100;function logOrphanKill(pgid,signal,logPath=defaultDaemonLogPath()){try{appendFileSync(logPath,formatDaemonInfo("doctor-kill-orphans",`${signal} process group ${pgid}`))}catch{}}function groupAlive(pgid){try{return process.kill(-pgid,0),!0}catch(err){return err.code!=="ESRCH"}}async function killOrphanGroups(orphans){let groups=[...new Set(orphans.map((row)=>row.pgid))];for(let pgid of groups)try{process.kill(-pgid,"SIGTERM"),logOrphanKill(pgid,"SIGTERM")}catch{}let deadline=Date.now()+GROUP_EXIT_GRACE_MS,survivors=groups.filter(groupAlive);while(survivors.length>0&&Date.now()<deadline)await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),survivors=survivors.filter(groupAlive);for(let pgid of survivors)try{process.kill(-pgid,"SIGKILL"),logOrphanKill(pgid,"SIGKILL")}catch{}return await new Promise((resolve)=>setTimeout(resolve,GROUP_POLL_MS)),{groups,survivors:survivors.filter(groupAlive)}}function multiplexerLabel(env){if(env.TMUX)return"tmux";if(env.ZELLIJ)return"zellij";if(env.STY)return"screen";return"no"}function terminalEnvLines(env){let show=(v)=>v&&v.length>0?v:"(unset)",program=env.TERM_PROGRAM?`${env.TERM_PROGRAM}${env.TERM_PROGRAM_VERSION?` v${env.TERM_PROGRAM_VERSION}`:""}`:"(unset)";return[`terminal: TERM=${show(env.TERM)} TERM_PROGRAM=${program} COLORTERM=${show(env.COLORTERM)}`,` running inside a multiplexer: ${multiplexerLabel(env)}`]}function parseKittyProbeReply(data){let kitty=data.match(/\x1b\[\?(\d+)u/);if(kitty?.[1]!==void 0)return{kind:"supported",flags:Number.parseInt(kitty[1],10)};if(/\x1b\[\?[\d;]*c/.test(data))return{kind:"unsupported"};return null}function kittyProbeLine(result){switch(result.kind){case"supported":return` kitty keyboard protocol: \u2713 answered (flags=${result.flags})`;case"unsupported":return[" kitty keyboard protocol: \u2717 not supported \u2014 legacy key path"," (ctrl+h/ctrl+j arrive as C0 backspace/linefeed bytes; the"," split chords ctrl+\\ and ctrl+= cannot be encoded at all)"].join(`
|
|
5
|
-
`);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}var CLI_NAME=activeCliName();function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new KobeDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(
|
|
5
|
+
`);case"no-response":return" kitty keyboard protocol: ? no reply (terminal ignored both the kitty query and DA1)";case"skipped":return` kitty keyboard protocol: skipped (${result.reason})`}}async function probeKittyKeyboard(timeoutMs=300){let stdin=process.stdin;if(!stdin.isTTY||!process.stdout.isTTY)return{kind:"skipped",reason:"not an interactive terminal"};let wasRaw=stdin.isRaw===!0,buffer="";return await new Promise((resolve)=>{let done=!1,finish=(result)=>{if(done)return;if(done=!0,clearTimeout(timer),stdin.off("data",onData),stdin.pause(),!wasRaw)stdin.setRawMode(!1);resolve(result)},onData=(chunk)=>{buffer+=chunk.toString("latin1");let decided=parseKittyProbeReply(buffer);if(decided)finish(decided)},timer=setTimeout(()=>finish({kind:"no-response"}),timeoutMs);stdin.setRawMode(!0),stdin.resume(),stdin.on("data",onData),process.stdout.write("\x1B[?u\x1B[c")})}async function terminalDoctorLines(){return[...terminalEnvLines(process.env),kittyProbeLine(await probeKittyKeyboard())]}var CLI_NAME=activeCliName();function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}async function requestIfReachable(socketPath,name){let client=new KobeDaemonClient(socketPath);try{return await client.request(name,{})}catch{return null}finally{client.close()}}function fmtDuration(ms){let seconds=Math.floor(ms/1000);if(seconds<60)return`${seconds}s`;let minutes=Math.floor(seconds/60);if(minutes<60)return`${minutes}m ${seconds%60}s`;return`${Math.floor(minutes/60)}h ${minutes%60}m`}function describeFile(path){try{let stat=statSync2(path);return`present (${formatBytes(stat.size)}, modified ${stat.mtime.toISOString()})`}catch{return"absent"}}function taskCount(path){try{let parsed=JSON.parse(readFileSync3(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function tailFile(path,count){try{return readFileSync3(path,"utf8").split(`
|
|
6
6
|
`).filter((line)=>line.trim().length>0).slice(-count).join(`
|
|
7
7
|
`)}catch{return""}}function describeInstall(){try{let[,entry]=resolveKobeSpawn([]);return{line:`install: \u2713 ${entry??process.execPath}`,ok:!0}}catch(err){if(!isStaleInstallError(err))return{line:`install: ? could not check (${String(err)})`,ok:!0};return{line:["install: \u2717 GONE \u2014 this process is running from an install that no longer exists on disk"," it cannot start a daemon; every reconnect fails the same way until you reinstall"," \u2192 npm install -g @sma1lboy/rove (then relaunch Rove)"].join(`
|
|
8
|
-
`),ok:!1}}}async function appendUnavailableProcess(out,label,pidPath,socketPath){let pid=await readPidFile(pidPath),wedged=pid!==null&&pid!==void 0&&isProcessAlive(pid);if(wedged)out.push(`${label}: \u2717 WEDGED \u2014 process alive (pid ${pid}) but socket is unreachable`);else if(pid)out.push(`${label}: \u2717 not running (stale pidfile \u2192 pid ${pid} is gone)`);else out.push(`${label}: \u2717 not running (no pidfile)`);if(existsSync(socketPath))out.push(` orphan socket file present: ${socketPath}`);return wedged?"wedged":"down"}async function collectDoctor(){let daemonSocket=defaultDaemonSocketPath(),daemonLog=defaultDaemonLogPath(),ptySocket=defaultPtyHostSocketPath(),ptyLog=defaultPtyHostLogPath(),canonicalTasks=join2(roveStateDir(),"tasks.json"),legacyTasks=join2(homeDir(),LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),readableLegacy=readableLegacyIndexPath(canonicalTasks,legacyTasks),usingLegacyTasks=!existsSync(canonicalTasks)&&readableLegacy!==void 0&&existsSync(readableLegacy),tasksPath=usingLegacyTasks?legacyTasks:canonicalTasks,statePath=kvStatePath(),fixes=[],git=await probeGit();if(!git.found)fixes.push(humanOnlyFix("git"));let engines=await probeEngines();if(!engines.anyUsable)fixes.push(noEngineFix(engines.signedOut));let install=describeInstall();if(!install.ok)fixes.push(reinstallManualFix());let staleBun=!isBunAtLeast(Bun.version);if(staleBun)fixes.push(humanOnlyFix("staleBun"));let out=["Rove doctor",` build: v${CURRENT_VERSION} (${process.platform} ${process.arch}, bun ${Bun.version})`,...staleBun?[` \u26A0 bun ${Bun.version} is below the ${MIN_BUN_VERSION} Rove needs \u2014 terminals will not paint`]:[],` home: ${homeDir()}`,"",...await terminalDoctorLines(),git.line,"",...engines.lines,"",install.line,""],daemon=await requestIfReachable(daemonSocket,"daemon.status");if(daemon){let pid=typeof daemon.daemonPid==="number"?daemon.daemonPid:"?",uptime=typeof daemon.uptimeMs==="number"?fmtDuration(daemon.uptimeMs):"?",tasks=typeof daemon.taskCount==="number"?daemon.taskCount:"?",clients=typeof daemon.attachedClients==="number"?daemon.attachedClients:"?";out.push(`daemon: \u2713 running (pid ${pid}, up ${uptime}, ${tasks} task(s), ${clients} client(s))`);let version=typeof daemon.kobeVersion==="string"?daemon.kobeVersion:void 0;if(version&&version!==CURRENT_VERSION)out.push(` \u26A0 stale build: daemon is v${version}, you launched v${CURRENT_VERSION}`),out.push(` \u2192 run \`${CLI_NAME} daemon restart\`, then relaunch Rove`),fixes.push(daemonRestartFix(CLI_NAME,"daemonStale"));else if(version)out.push(` build: v${version}`);if(isForeignDaemonHome(typeof daemon.homeDir==="string"?daemon.homeDir:void 0,homeDir()))out.push(` \u26A0 foreign home: daemon serves ${String(daemon.homeDir)}, you are reading ${homeDir()}`),out.push(` \u2192 clear ROVE_HOME_DIR/KOBE_HOME_DIR, then \`${CLI_NAME} daemon restart\``);let tabs=(await requestIfReachable(daemonSocket,"debug.inspect"))?.activity?.tabs;if(tabs){let hookInput={socketPath:daemonSocket},verdict=classifyHookChannel({tabs,...hookInput});if(out.push("",...hookChannelDoctorLines(verdict,hookInput,CLI_NAME)),verdict.kind==="down")fixes.push(daemonRestartFix(CLI_NAME,"hooksDown"),engineTabsManualFix())}else out.push("","hooks: ? could not read the daemon's activity registry (debug.inspect unavailable)"),fixes.push(daemonRestartFix(CLI_NAME,"inspectStale"))}else{let state=await appendUnavailableProcess(out,"daemon ",defaultDaemonPidPath(),daemonSocket);fixes.push(state==="wedged"?resetManualFix(CLI_NAME,"resetDaemonWedged"):daemonRestartFix(CLI_NAME,"daemonDown"));let tail=tailFile(daemonLog,8);if(tail){out.push(" last lines of daemon.log:");for(let line of tail.split(`
|
|
8
|
+
`),ok:!1}}}async function appendUnavailableProcess(out,label,pidPath,socketPath){let pid=await readPidFile(pidPath),wedged=pid!==null&&pid!==void 0&&isProcessAlive(pid);if(wedged)out.push(`${label}: \u2717 WEDGED \u2014 process alive (pid ${pid}) but socket is unreachable`);else if(pid)out.push(`${label}: \u2717 not running (stale pidfile \u2192 pid ${pid} is gone)`);else out.push(`${label}: \u2717 not running (no pidfile)`);if(existsSync(socketPath))out.push(` orphan socket file present: ${socketPath}`);return wedged?"wedged":"down"}async function collectDoctor(){let daemonSocket=defaultDaemonSocketPath(),daemonLog=defaultDaemonLogPath(),ptySocket=defaultPtyHostSocketPath(),ptyLog=defaultPtyHostLogPath(),canonicalTasks=join2(roveStateDir(),"tasks.json"),legacyTasks=join2(homeDir(),LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),readableLegacy=readableLegacyIndexPath(canonicalTasks,legacyTasks),usingLegacyTasks=!existsSync(canonicalTasks)&&readableLegacy!==void 0&&existsSync(readableLegacy),tasksPath=usingLegacyTasks?legacyTasks:canonicalTasks,statePath=kvStatePath(),fixes=[],git=await probeGit();if(!git.found)fixes.push(humanOnlyFix("git"));let engines=await probeEngines();if(!engines.anyUsable)fixes.push(noEngineFix(engines.signedOut));let install=describeInstall();if(!install.ok)fixes.push(reinstallManualFix());let staleBun=!isBunAtLeast(Bun.version);if(staleBun)fixes.push(humanOnlyFix("staleBun"));let out=["Rove doctor",` build: v${CURRENT_VERSION} (${process.platform} ${process.arch}, bun ${Bun.version})`,...staleBun?[` \u26A0 bun ${Bun.version} is below the ${MIN_BUN_VERSION} Rove needs \u2014 terminals will not paint`]:[],` home: ${homeDir()}`,"",...await terminalDoctorLines(),git.line,"",...engines.lines,"",install.line,""],daemon=await requestIfReachable(daemonSocket,"daemon.status");if(daemon){let pid=typeof daemon.daemonPid==="number"?daemon.daemonPid:"?",uptime=typeof daemon.uptimeMs==="number"?fmtDuration(daemon.uptimeMs):"?",tasks=typeof daemon.taskCount==="number"?daemon.taskCount:"?",clients=typeof daemon.attachedClients==="number"?daemon.attachedClients:"?";out.push(`daemon: \u2713 running (pid ${pid}, up ${uptime}, ${tasks} task(s), ${clients} client(s))`);let version=typeof daemon.kobeVersion==="string"?daemon.kobeVersion:void 0;if(version&&version!==CURRENT_VERSION)out.push(` \u26A0 stale build: daemon is v${version}, you launched v${CURRENT_VERSION}`),out.push(` \u2192 run \`${CLI_NAME} daemon restart\`, then relaunch Rove`),fixes.push(daemonRestartFix(CLI_NAME,"daemonStale"));else if(version)out.push(` build: v${version}`);if(isForeignDaemonHome(typeof daemon.homeDir==="string"?daemon.homeDir:void 0,homeDir()))out.push(` \u26A0 foreign home: daemon serves ${String(daemon.homeDir)}, you are reading ${homeDir()}`),out.push(` \u2192 clear ROVE_HOME_DIR/KOBE_HOME_DIR, then \`${CLI_NAME} daemon restart\``);let tabs=(await requestIfReachable(daemonSocket,"debug.inspect"))?.activity?.tabs;if(tabs){let hookInput={socketPath:daemonSocket,configIssues:hookConfigIssues()},verdict=classifyHookChannel({tabs,...hookInput});if(out.push("",...hookChannelDoctorLines(verdict,hookInput,CLI_NAME)),verdict.kind==="down")fixes.push(daemonRestartFix(CLI_NAME,"hooksDown"),engineTabsManualFix())}else out.push("","hooks: ? could not read the daemon's activity registry (debug.inspect unavailable)"),fixes.push(daemonRestartFix(CLI_NAME,"inspectStale"))}else{let state=await appendUnavailableProcess(out,"daemon ",defaultDaemonPidPath(),daemonSocket);fixes.push(state==="wedged"?resetManualFix(CLI_NAME,"resetDaemonWedged"):daemonRestartFix(CLI_NAME,"daemonDown"));let tail=tailFile(daemonLog,8);if(tail){out.push(" last lines of daemon.log:");for(let line of tail.split(`
|
|
9
9
|
`))out.push(` \u2502 ${line}`)}}out.push("");let inventory=await requestIfReachable(ptySocket,"pty.list");if(inventory){let sessions=inventory.sessions??[],parked=inventory.stats?.parkedSessions??sessions.filter((session)=>session.parked).length;if(out.push(`pty host: \u2713 running (${sessions.length} session(s), ${sessions.filter((session)=>session.alive).length} live, ${parked} parked)`),typeof inventory.pid==="number"&&typeof inventory.rssBytes==="number")out.push(` pid ${inventory.pid}, ${formatBytes(inventory.rssBytes)} RSS`);let hostVersion=typeof inventory.version==="string"?inventory.version:void 0;if(hostVersion===void 0)out.push(" build: unknown \u2014 this host predates the version check, so it is at least that old"),out.push(` \u2192 \`${CLI_NAME} reset\` replaces it (ends every live terminal and engine session)`);else if(hostVersion!==CURRENT_VERSION)out.push(` \u26A0 stale build: pty host is v${hostVersion}, you launched v${CURRENT_VERSION}`),out.push(` \u2192 \`${CLI_NAME} reset\` replaces it (ends every live terminal and engine session)`),fixes.push(resetManualFix(CLI_NAME,"resetPtyStale"));else out.push(` build: v${hostVersion}`);let stats=inventory.stats;if(stats&&typeof stats.ringBytes==="number"&&typeof stats.ringCapacityBytes==="number")out.push(` ring: ${formatBytes(stats.ringBytes)} / ${formatBytes(stats.ringCapacityBytes)}`);if(stats&&typeof stats.parkedScreenBytes==="number")out.push(` parked screens: ${formatBytes(stats.parkedScreenBytes)}`);if(stats&&typeof stats.parkRestoreDeltas==="number"&&typeof stats.parkRestoreFallbacks==="number")out.push(` park wakes: ${stats.parkRestoreDeltas} delta, ${stats.parkRestoreFallbacks} full replay fallback`)}else if(await appendUnavailableProcess(out,"pty host",defaultPtyHostPidPath(),ptySocket)==="wedged")fixes.push(resetManualFix(CLI_NAME,"resetPty"));else out.push(" starts on demand \u2014 the first task tab launches it; nothing to fix");if(process.platform==="win32"){let node=resolveNodeBinary();if(out.push(node?` node: \u2713 ${node} (the Windows PTY host runs under it)`:` node: \u2717 not found on PATH \u2014 the Windows PTY host cannot start
|
|
10
10
|
\u2192 install Node.js from https://nodejs.org`),!node)fixes.push(humanOnlyFix("windowsNode"))}if(process.platform==="darwin"){let helpers=spawnHelperDoctorLines(installedSpawnHelpers());if(out.push(...helpers.lines),helpers.broken.length>0)fixes.push(spawnHelperFix(helpers.broken))}out.push("");let liveSessionPids=new Set;for(let session of inventory?.sessions??[])if(session.alive&&typeof session.pid==="number")liveSessionPids.add(session.pid);let orphaned=await collectOrphans(liveSessionPids);if(out.push(...orphanDoctorLines(orphaned.orphans,orphaned.error,CLI_NAME),""),orphaned.orphans.length>0)fixes.push(killOrphansManualFix(CLI_NAME,orphaned.orphans.length));let legacy=await inspectLegacyTmux();if(out.push(...legacyTmuxDoctorLines(legacy),""),legacy.sessions.length>0)fixes.push(resetManualFix(CLI_NAME,"resetLegacy"));let skill=kobeSkillState(),installCommand=skillInstallCommand();if(!skill.installed)out.push("skill: \u2717 Rove agent skill not installed",` \u2192 ${installCommand}`),fixes.push(skillInstallFix(installCommand,!1));else if(skill.stale){let installed=skill.installedVersion===null?"unstamped":`v${skill.installedVersion}`;out.push(`skill: \u26A0 Rove agent skill out of date (${installed}; this Rove wants v${skill.currentVersion})`),out.push(` \u2192 ${installCommand}`),fixes.push(skillInstallFix(installCommand,!0))}else out.push(`skill: \u2713 Rove agent skill installed (v${skill.installedVersion})`);out.push("");let count=taskCount(tasksPath);return out.push(`tasks.json: ${describeFile(tasksPath)}${count===null?"":` \u2014 ${count} task(s)`}${usingLegacyTasks?` (legacy ${tasksPath}, not yet migrated)`:""}`),out.push(`state.json: ${describeFile(statePath)}`),out.push(`daemon.log: ${describeFile(daemonLog)}`),out.push(`pty.log: ${describeFile(ptyLog)}`),{lines:out,fixes,orphans:orphaned.orphans}}async function sweepOrphans(orphans){if(orphans.length===0)return["orphans: nothing to kill"];let{groups,survivors}=await killOrphanGroups(orphans),lines=[`orphans: signalled ${groups.length} process group(s) covering ${orphans.length} process(es)`];if(survivors.length>0)lines.push(` \u2717 still alive after SIGKILL: group(s) ${survivors.join(", ")} \u2014 inspect with \`ps -g <pgid>\``);else lines.push(" \u2713 all of them are gone");return lines}async function runDoctorSubcommand(argv=[]){if(argv.some((arg)=>arg==="--help"||arg==="-h"||arg==="help")){process.stdout.write([`Usage: ${CLI_NAME} doctor [--report] [--fix] [--kill-orphans]`,"","Read-only diagnosis of the daemon / Hosted PTY / engines / git / legacy tmux / state.","","Options:"," --report Also write a bug bundle (diagnosis + recent logs + env) to a file"," --fix Review the fixes one by one: safe ones run after a per-fix y/N,"," risky ones (kill sessions, install software) are printed only"," --kill-orphans End the process groups listed under `orphans:` (SIGTERM, then"," SIGKILL). Not undoable \u2014 run plain `doctor` and read the list first"," -h, --help Print this help",""].join(`
|
|
11
11
|
`));return}let report=argv.some((arg)=>arg==="--report"),fix=argv.some((arg)=>arg==="--fix"),kill=argv.some((arg)=>arg==="--kill-orphans"),known=new Set(["--report","--fix","--kill-orphans"]),unknown=argv.find((arg)=>arg.length>0&&!known.has(arg));if(unknown!==void 0)process.stderr.write(`${CLI_NAME} doctor: unexpected argument "${unknown}"
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{defaultEngineCommand,engineCommandKey,engineDisplayName,interactiveEngineCommand,parseEngineCommand,withEngineEffort,withEngineTerminalTitle}from"./chunk-
|
|
2
|
+
import{defaultEngineCommand,engineCommandKey,engineDisplayName,interactiveEngineCommand,parseEngineCommand,withEngineEffort,withEngineTerminalTitle}from"./chunk-5agemmmn.js";import{vendorFromArgv}from"./chunk-jn5dd6bv.js";import{engineEntry}from"./chunk-xhw8s2es.js";import{isContribEngine}from"./chunk-nzscq4yf.js";import{getCustomEngineIds,getPersistedString}from"./chunk-6wpege0h.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-bq3fyc0p.js";import{randomUUID}from"crypto";function hasFlag(argv,flag){return argv.some((a)=>a===flag||a.startsWith(`${flag}=`))}function controlsOwnSession(identity,argv){return(identity?.sessionControlFlags??[]).some((flag)=>hasFlag(argv,flag))}function pinSessionArgv(identity,argv,sessionId){if(!identity?.pinFlag)return argv;if(controlsOwnSession(identity,argv))return argv;return[...argv,identity.pinFlag,sessionId]}function acceptsPinnedSession(identity,argv){return!!identity?.pinFlag&&!controlsOwnSession(identity,argv)}function resumeSessionArgv(identity,base,sessionId){if(!sessionId||!identity?.resumeArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.resumeArgv(base,sessionId)}function pickUnclaimedSessionId(ids,claimed){for(let i=ids.length-1;i>=0;i--){let id=ids[i];if(id&&!claimed.has(id))return id}return null}function forkSessionArgvFor(identity,base,sourceId,newId){if(!sourceId||!identity?.forkArgv)return null;if(controlsOwnSession(identity,base))return null;return identity.forkArgv(base,sourceId,newId)}function acceptsSessionFork(identity){return!!identity?.forkArgv}var GENERIC_PROTOCOL="generic",ENGINE_PROTOCOLS=BUILTIN_VENDORS;function engineProtocolKey(id){return`engineProtocol.${id}`}function getEngineProtocol(id){if(isBuiltinVendor(id)||isContribEngine(id))return id;let raw=getPersistedString(engineProtocolKey(id))?.trim();return raw&&ENGINE_PROTOCOLS.includes(raw)?raw:void 0}function isPresetId(id){return isBuiltinVendor(id)||isContribEngine(id)||getCustomEngineIds().includes(id)}function listPresetIds(){return[...BUILTIN_VENDORS,...getCustomEngineIds()]}function describePreset(id){let command=getPersistedString(engineCommandKey(id))?.trim()||defaultEngineCommand(id).join(" ");return{id,name:engineDisplayName(id),command,protocol:getEngineProtocol(id)??GENERIC_PROTOCOL,builtin:isBuiltinVendor(id)}}function listEnginePresets(){return listPresetIds().map(describePreset)}function resolveCommandProtocol(command){let trimmed=command?.trim();if(!trimmed)return GENERIC_PROTOCOL;if(isPresetId(trimmed))return getEngineProtocol(trimmed)??GENERIC_PROTOCOL;let fromArgv=vendorFromArgv(trimmed);if(fromArgv)return fromArgv;let argv0=parseEngineCommand(trimmed)[0];if(argv0)for(let id of getCustomEngineIds()){let preset=getPersistedString(engineCommandKey(id))?.trim();if(preset&&parseEngineCommand(preset)[0]===argv0)return getEngineProtocol(id)??GENERIC_PROTOCOL}return GENERIC_PROTOCOL}function engineLaunchArgv(spec){let command=spec.command?.trim();if(!command)return interactiveEngineCommand(spec.vendor,spec.effort);let vendor=(isPresetId(command)?getEngineProtocol(command):void 0)??resolveCommandProtocol(command),base=isPresetId(command)?presetBaseArgv(command):(()=>{let argv=parseEngineCommand(command);return argv.length>0?argv:null})();if(!base)return interactiveEngineCommand(spec.vendor,spec.effort);return withEngineTerminalTitle(withEngineEffort(base,vendor,spec.effort),vendor)}function presetBaseArgv(id){let override=getPersistedString(engineCommandKey(id))?.trim();if(override){let argv=parseEngineCommand(override);if(argv.length>0)return argv}return defaultEngineCommand(id)}function sessionProtocol(vendor){let id=vendor?.trim();if(!id)return"claude";return getEngineProtocol(id)??id}function protocolEntry(vendor){return engineEntry(sessionProtocol(vendor))}function withPinnedSessionId(argv,vendor,newId=randomUUID){let identity=engineEntry(sessionProtocol(vendor)).sessionIdentity;if(!acceptsPinnedSession(identity,argv))return{argv,sessionId:null};let sessionId=newId();return{argv:pinSessionArgv(identity,argv,sessionId),sessionId}}function engineResumeArgv(base,vendor,sessionId){return resumeSessionArgv(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sessionId)}function engineCanFork(vendor){return acceptsSessionFork(engineEntry(sessionProtocol(vendor)).sessionIdentity)}function engineForkArgv(base,vendor,sourceId,newId){return forkSessionArgvFor(engineEntry(sessionProtocol(vendor)).sessionIdentity,base,sourceId,newId)}
|
|
3
3
|
export{pickUnclaimedSessionId,GENERIC_PROTOCOL,ENGINE_PROTOCOLS,engineProtocolKey,getEngineProtocol,listPresetIds,describePreset,listEnginePresets,resolveCommandProtocol,engineLaunchArgv,sessionProtocol,protocolEntry,withPinnedSessionId,engineResumeArgv,engineCanFork,engineForkArgv};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{applyOnboardingChoices,detectShell,envReadyForTasks,installCompletions,maybeRunOnboarding}from"./chunk-
|
|
2
|
+
import{applyOnboardingChoices,detectShell,envReadyForTasks,installCompletions,maybeRunOnboarding}from"./chunk-2e572bj0.js";import"./chunk-8wrzdj5x.js";import"./chunk-3p2e2ry4.js";import"./chunk-m0g17ckn.js";import"./chunk-dx6v0yw8.js";import"./chunk-5jbj7b9t.js";import"./chunk-qqw3p4fc.js";import"./chunk-5agemmmn.js";import"./chunk-xwekyjat.js";import"./chunk-v2cpe974.js";import"./chunk-sdyzxayr.js";import"./chunk-jvxh93nz.js";import"./chunk-jn5dd6bv.js";import"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-pxk2c2vj.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";export{maybeRunOnboarding,installCompletions,envReadyForTasks,detectShell,applyOnboardingChoices};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{PLUGIN_MANIFEST_FILENAMES,currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginCheckoutDir,pluginConfigDir,pluginManifestPath,pluginStateDir,pluginsRootDir,savePluginRegistry,supportsPlatform,upsertPluginEntry}from"./chunk-38272eqv.js";import{CURRENT_VERSION,compareSemver}from"./chunk-
|
|
2
|
+
import{PLUGIN_MANIFEST_FILENAMES,currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginCheckoutDir,pluginConfigDir,pluginManifestPath,pluginStateDir,pluginsRootDir,savePluginRegistry,supportsPlatform,upsertPluginEntry}from"./chunk-38272eqv.js";import{CURRENT_VERSION,compareSemver}from"./chunk-5jbj7b9t.js";import{spawnSync}from"child_process";import{cpSync,existsSync,mkdirSync,readFileSync,renameSync,rmSync}from"fs";import{mkdtempSync}from"fs";import{basename,join,resolve}from"path";import{createInterface}from"readline/promises";var GITHUB_SPEC_RE=/^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)(\/.+)?$/;class PluginCliError extends Error{}function fail(message){throw new PluginCliError(message)}function readManifestAt(root){let path=pluginManifestPath(root);if(!path)fail(`no ${PLUGIN_MANIFEST_FILENAMES.join(" or ")} found at ${root}`);let source=readFileSync(path,"utf8");return{...parsePluginManifest(source,basename(path)),manifestPath:path,manifestSource:source}}function checkVersionGate(parsed){let min=parsed.manifest.minKobeVersion;if(compareSemver(CURRENT_VERSION,min)<0)fail(`plugin requires Rove >= ${min} (this is ${CURRENT_VERSION}); update Rove first`)}function printPreview(parsed,source){let m=parsed.manifest;console.log(`
|
|
3
3
|
${m.name} (${m.id}) v${m.version} \u2014 ${m.description??"no description"}`),console.log(`source: ${source}`);let show=(label,commands)=>{for(let c of commands)console.log(` ${label}: ${c.command.join(" ")}`)};show("build",m.build),show("startup",m.startup);for(let a of m.actions)console.log(` action ${a.id}: ${a.command.join(" ")}`);for(let e of m.events)console.log(` on ${e.on}: ${e.command.join(" ")}`);for(let w of parsed.warnings)console.log(` warning: ${w}`);console.log("")}async function confirmOrBail(yes){if(yes)return;if(!process.stdin.isTTY)fail("refusing to install without confirmation in a non-interactive terminal; pass --yes");let rl=createInterface({input:process.stdin,output:process.stdout}),answer=(await rl.question("Install this plugin and run its build commands? [y/N] ")).trim().toLowerCase();if(rl.close(),answer!=="y"&&answer!=="yes")fail("aborted")}function git(args,cwd){if(spawnSync("git",args,{cwd,stdio:["ignore","inherit","inherit"]}).status!==0)fail(`git ${args[0]} failed`)}function runBuildCommands(parsed,root){let platform=currentPluginPlatform();for(let[i,step]of parsed.manifest.build.entries()){if(!supportsPlatform(step,parsed.manifest,platform))continue;let[cmd,...args]=step.command;console.log(`build[${i}]: ${step.command.join(" ")}`);let res=spawnSync(cmd,args,{cwd:root,stdio:["ignore","inherit","inherit"]});if(res.status!==0)fail(`build[${i}] failed (exit ${res.status??"spawn error"}); plugin not registered`)}}function makeStagingDir(){let root=pluginsRootDir();return mkdirSync(root,{recursive:!0}),mkdtempSync(join(root,".staging-"))}function movePluginTree(from,to){try{renameSync(from,to)}catch(err){if(err.code!=="EXDEV")throw err;cpSync(from,to,{recursive:!0,verbatimSymlinks:!0}),rmSync(from,{recursive:!0,force:!0})}}function register(entry){savePluginRegistry(upsertPluginEntry(loadPluginRegistry(),entry)),mkdirSync(pluginConfigDir(entry.id),{recursive:!0,mode:448}),mkdirSync(pluginStateDir(entry.id),{recursive:!0,mode:448})}async function installPlugin(spec,opts){let match=spec.match(GITHUB_SPEC_RE);if(!match)fail(`install takes GitHub shorthand (owner/repo[/subdir]), got \`${spec}\``);let[,owner,repo,subdirRaw]=match,subdir=subdirRaw?.replace(/^\//,""),tmp=makeStagingDir();try{let url=`https://github.com/${owner}/${repo}.git`;if(console.log(`cloning ${url}${opts.ref?` @ ${opts.ref}`:""}`),opts.ref)git(["clone","--quiet",url,tmp]),git(["checkout","--quiet",opts.ref],tmp);else git(["clone","--quiet","--depth","1",url,tmp]);let rootInClone=subdir?join(tmp,subdir):tmp,parsed=readManifestAt(rootInClone);checkVersionGate(parsed);let id=parsed.manifest.id,existing=loadPluginRegistry().plugins.find((p)=>p.id===id);if(existing?.source.kind==="link")fail(`\`${id}\` is locally linked at ${existing.root}; unlink it first`);if(!supportsPlatform({},parsed.manifest,currentPluginPlatform()))fail(`plugin declares platforms [${parsed.manifest.platforms?.join(", ")}]; this machine is unsupported`);printPreview(parsed,`github.com/${owner}/${repo}${subdir?`/${subdir}`:""}`),await confirmOrBail(opts.yes),runBuildCommands(parsed,rootInClone);let manifestPath=pluginManifestPath(rootInClone);if(!manifestPath)fail("manifest disappeared during build; aborting");if(manifestPath!==parsed.manifestPath)fail("manifest changed during build; aborting");if(readFileSync(manifestPath,"utf8")!==parsed.manifestSource)fail("manifest changed during build; aborting");let checkout=pluginCheckoutDir(id);return rmSync(checkout,{recursive:!0,force:!0}),mkdirSync(join(checkout,".."),{recursive:!0}),movePluginTree(tmp,checkout),register({id,source:{kind:"github",spec},root:subdir?join(checkout,subdir):checkout,enabled:!0,version:parsed.manifest.version,installedAt:Date.now()}),console.log(`installed ${id} v${parsed.manifest.version}`),id}finally{rmSync(tmp,{recursive:!0,force:!0})}}function linkPlugin(dir){let root=resolve(dir);if(!existsSync(root))fail(`no such directory: ${root}`);let parsed=readManifestAt(root);checkVersionGate(parsed);let id=parsed.manifest.id;if(loadPluginRegistry().plugins.find((p)=>p.id===id)?.source.kind==="github")fail(`\`${id}\` is installed from GitHub; uninstall it before linking a local copy`);for(let w of parsed.warnings)console.log(`warning: ${w}`);if(!supportsPlatform({},parsed.manifest,currentPluginPlatform()))console.log(`warning: declares platforms [${parsed.manifest.platforms?.join(", ")}]; nothing will run on this machine`);register({id,source:{kind:"link"},root,enabled:!0,version:parsed.manifest.version,installedAt:Date.now()}),console.log(`linked ${id} v${parsed.manifest.version} \u2192 ${root}`)}
|
|
4
4
|
export{PluginCliError,installPlugin,linkPlugin};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{TaskIndexStore}from"./chunk-
|
|
2
|
+
import{TaskIndexStore}from"./chunk-hxfj85yw.js";import"./chunk-qkehg2c1.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-ayhhgfsz.js";import"./chunk-bq3fyc0p.js";import"./chunk-mv7ptt5w.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";export{TaskIndexStore};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{buildEngineSessionLaunch,trustEngineWorktree}from"./chunk-b82bc173.js";import{engineForkArgv,engineResumeArgv,withPinnedSessionId}from"./chunk-pabqr39m.js";import{t}from"./chunk-rvybphrq.js";import{engineEntry,engineStatusPrefixes,isEnginePlaceholderTitle,stripEngineStatusPrefix}from"./chunk-d4xhc9th.js";import*as fs from"fs";import*as os from"os";function pathLeaf(p){return p.slice(p.lastIndexOf("/")+1)}function expandHome(p){if(p==="~")return os.homedir();if(p.startsWith("~/"))return os.homedir()+p.slice(1);return p}function stripTrailingSlash(p){return p.length>1&&p.endsWith("/")?p.slice(0,-1):p}function splitPathForDirSuggest(value){if(!value)return{base:"",filter:""};let expanded=expandHome(value==="~"?"~/":value);if(expanded.endsWith("/"))return{base:expanded,filter:""};let lastSlash=expanded.lastIndexOf("/");if(lastSlash===-1)return{base:"",filter:expanded};return{base:expanded.slice(0,lastSlash+1),filter:expanded.slice(lastSlash+1)}}function listSubdirs(base){if(!base)return[];try{let entries=fs.readdirSync(base,{withFileTypes:!0}),out=[];for(let e of entries)if(e.isDirectory())out.push(e.name);return out.sort((a,b)=>a.localeCompare(b))}catch{return[]}}function filterSubdirs(all,filter){let f=filter.toLowerCase(),visible=f.startsWith(".")?all:all.filter((n)=>!n.startsWith("."));if(!f)return visible;return visible.filter((n)=>n.toLowerCase().startsWith(f))}function joinDrill(typedValue,baseExpanded,name){let out=`${baseExpanded+name}/`;if(typedValue.startsWith("~")){let home=os.homedir();if(out===`${home}/`)return"~/";if(out.startsWith(`${home}/`))return`~${out.slice(home.length)}`}return out}function joinPicked(typedValue,baseExpanded,name){let out=baseExpanded+name;if(typedValue.startsWith("~")){let home=os.homedir();if(out===home)return"~";if(out.startsWith(`${home}/`))return`~${out.slice(home.length)}`}return out}function depth(node){return node.kind==="leaf"?0:1+Math.max(...node.children.map(depth))}function siblingCount(root,id,orientation){let find=(node)=>{if(node.kind==="leaf")return null;if(node.orientation===orientation&&node.children.some((c)=>c.kind==="leaf"&&c.id===id))return node.children.length;for(let child of node.children){let n=find(child);if(n!==null)return n}return null};return find(root)??1}function splitFits(state,orientation,activeSize){let extent=orientation==="row"?activeSize.cols:activeSize.rows,min=orientation==="row"?20:6,n=siblingCount(state.root,state.activeLeafId,orientation);return Math.floor(extent*n/(n+1))-1>=min}function initialSplit(content){return{root:{kind:"leaf",id:"leaf-1",content},activeLeafId:"leaf-1",nextOrdinal:2}}function leaves(node){return node.kind==="leaf"?[node]:node.children.flatMap(leaves)}function splitActive(state,orientation,content,activeSize){if(activeSize&&!splitFits(state,orientation,activeSize))return state;let leaf={kind:"leaf",id:`leaf-${state.nextOrdinal}`,content},insert=(node)=>{if(node.kind==="leaf"){if(node.id!==state.activeLeafId)return node;return{kind:"group",orientation,children:[node,leaf]}}if(node.orientation===orientation){let i=node.children.findIndex((c)=>c.kind==="leaf"&&c.id===state.activeLeafId);if(i>=0){let children=[...node.children.slice(0,i+1),leaf,...node.children.slice(i+1)];return{...node,children}}}return{...node,children:node.children.map(insert)}},root=insert(state.root);if(!activeSize&&depth(root)>4)return state;return{root,activeLeafId:leaf.id,nextOrdinal:state.nextOrdinal+1}}function removeLeaf(state,id){let all=leaves(state.root);if(all.length<=1)return null;let prune=(node)=>{if(node.kind==="leaf")return node.id===id?null:node;let children=node.children.map(prune).filter((c)=>c!==null);if(children.length===0)return null;if(children.length===1)return children[0];return{...node,children}},root=prune(state.root);if(root===null)return null;if(leaves(root).length===all.length)return state;let order=all.map((l)=>l.id),removedIdx=order.indexOf(id),fallback=order[removedIdx>0?removedIdx-1:removedIdx+1],activeLeafId=state.activeLeafId===id?fallback:state.activeLeafId;return{...state,root,activeLeafId}}function renameLeaf(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,walk=(node)=>node.kind==="leaf"?node.id===id?{...node,title:next}:node:{...node,children:node.children.map(walk)};if(!leaves(state.root).some((l)=>l.id===id))return state;return{...state,root:walk(state.root)}}function cycleLeaf(state,delta){let order=leaves(state.root).map((l)=>l.id);if(order.length<=1)return state;let i=order.indexOf(state.activeLeafId),next=order[(i+delta+order.length)%order.length];return{...state,activeLeafId:next}}function hasEngineLeaf(tree){return!tree||leaves(tree.root).some((l)=>l.id==="leaf-1")}function isTabSplit(tree){return tree?leaves(tree.root).length>1:!1}function collapseSplit(next){let ls=leaves(next.root);return ls.length===1&&ls[0]?.id==="leaf-1"?null:next}function splitLeafPtyKey(tabKey,leafId){return leafId==="leaf-1"?tabKey:`${tabKey}::${leafId}`}var SHELL_LEAF_NAME="shell";function splitLeafNames(leafList,tabCommand,engineTitle,liveTitles){let basename=(argv)=>{let head=(argv??tabCommand)[0]??"",name=pathLeaf(head);return name.length>0?name:"?"},seen=new Map,out=new Map;for(let leaf of leafList){if(leaf.title){out.set(leaf.id,leaf.title);continue}let name=leaf.content===null?engineTitle||liveTitles?.get(leaf.id)||basename(leaf.content):liveTitles?.get(leaf.id)||SHELL_LEAF_NAME,n=(seen.get(name)??0)+1;seen.set(name,n),out.set(leaf.id,n===1?name:`${name} ${n}`)}return out}function meaningfulAutoTitle(autoTitle){let trimmed=(autoTitle??"").trim();if(trimmed.length<3)return null;if(/^[\d\s\p{P}\p{S}]+$/u.test(trimmed))return null;return trimmed}function stableRecordedTitle(raw,vendor){let recorded=raw?.trim();if(!recorded)return null;let cleaned=stripEngineStatusPrefix(recorded,vendor);if(cleaned===recorded&&isEngineDecoration(recorded,vendor))return null;if(isEnginePlaceholderTitle(cleaned,vendor))return null;return cleaned||null}function isEngineDecoration(text,vendor){let glyphs=new Set(engineStatusPrefixes(vendor));return[...text].every((ch)=>ch.trim().length===0||glyphs.has(ch))}function tabTitleStable(tab,taskVendor,liveVendor,liveTitle){if(liveVendor===null&&tab.kind==="engine")return tabTitle({...tab,kind:"command",lastTitle:null},taskVendor);let vendor=liveVendor??tab.liveVendor??(tab.kind==="engine"?tab.vendor??taskVendor:void 0)??void 0,source=liveTitle?.trim()||tab.lastTitle,named=vendor?stableRecordedTitle(source,vendor):source??null;if(!vendor||engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return tabTitle({...tab,lastTitle:named},taskVendor);return tabTitle({...tab,kind:"engine",vendor,lastTitle:named},taskVendor)}function titleVendor(tab,taskVendor){return tab.liveVendor??(tab.kind==="engine"?tab.vendor:void 0)??taskVendor}function tabTitle(tab,taskVendor,liveName){if(tab.title)return tab.title;let ls=tab.splitTree?leaves(tab.splitTree.root):[];if(ls.length>1)return t("terminal.tab.groupTitle",{n:tab.ordinal});let sole=ls.length===1?ls[0]:void 0;if(sole&&sole.id!=="leaf-1")return sole.title??`${liveName??SHELL_LEAF_NAME} ${tab.ordinal}`;let vendor=titleVendor(tab,taskVendor);if(liveName&&!isEnginePlaceholderTitle(liveName,vendor))return`${liveName} ${tab.ordinal}`;if(tab.lastTitle&&!isEnginePlaceholderTitle(tab.lastTitle,vendor))return`${tab.lastTitle} ${tab.ordinal}`;let auto=meaningfulAutoTitle(tab.autoTitle);if(auto)return auto;return`${tab.kind==="engine"?engineEntry(tab.vendor??taskVendor).defaultCommand[0]??SHELL_LEAF_NAME:SHELL_LEAF_NAME} ${tab.ordinal}`}function visibleNativeStatus(tab,taskVendor,vendor,liveName){if(!vendor||!liveName)return!1;if(engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return!1;return tabTitle(tab,taskVendor,liveName)===`${liveName} ${tab.ordinal}`}function initialTabs(){return{tabs:[{kind:"engine",id:"tab-1",title:null,ordinal:1}],activeId:"tab-1",nextOrdinal:2}}function reopenHintFor(closed){if(closed?.kind==="command")return{kind:"command"};if(closed?.kind==="engine"&&closed.vendor)return{kind:"engine",vendor:closed.vendor};return{kind:"engine"}}function reopenTabs(state,shell){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,next=state.nextOrdinal+1;if(state.reopenAs?.kind==="command")return{tabs:[{kind:"command",id,title:null,ordinal,command:[shell]}],activeId:id,nextOrdinal:next};let vendor=state.reopenAs?.kind==="engine"?state.reopenAs.vendor:void 0;return{tabs:[{kind:"engine",id,title:null,ordinal,...vendor?{vendor}:{}}],activeId:id,nextOrdinal:next}}function initialShellTabs(shell){return{tabs:[{kind:"command",id:"tab-1",title:null,ordinal:1,command:[shell]}],activeId:"tab-1",nextOrdinal:2}}function rehydrateTabs(persisted,shell,opts={}){let tabs=persisted.tabs.map((t2)=>t2.kind==="command"?{...t2,command:shell,purpose:void 0}:t2);if(tabs.length===0)return opts.allowEmpty?persisted:initialTabs();let activeId=tabs.some((t2)=>t2.id===persisted.activeId)?persisted.activeId:tabs[0].id,maxOrdinal=tabs.reduce((max,t2)=>Math.max(max,t2.ordinal),0);return{tabs,activeId,nextOrdinal:Math.max(persisted.nextOrdinal,maxOrdinal+1)}}function recycleTabs(state,prev){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,pinned=prev.kind==="engine"?prev:void 0;return{tabs:[{kind:"engine",id,ordinal,title:prev.title,autoTitle:prev.autoTitle,...pinned?.vendor?{vendor:pinned.vendor}:{},...pinned?.engineCommand?{engineCommand:pinned.engineCommand}:{}}],activeId:id,nextOrdinal:ordinal+1}}function engineTabArgv(tab,base,live,fallbackVendor){if(tab.forkFrom&&!tab.spawned&&!live){let forked=tab.vendor?engineForkArgv(base,tab.vendor,tab.forkFrom,tab.sessionId??null):null;if(forked)return forked}if(!tab.sessionId)return base;let vendor=tab.vendor??fallbackVendor;if(tab.spawned&&!live)return engineResumeArgv(base,vendor,tab.sessionId)??base;return withPinnedSessionId(base,vendor,()=>tab.sessionId).argv}function engineTabSpawnFor(state,tab,base,opts){let{live,shell,prompt}=opts,firstEngine=state.tabs.find((t2)=>t2.kind==="engine"),fresh=!tab.spawned&&!live,tabPrompt=fresh?tab.initialPrompt?.trim():void 0,wantsPrompt=!!prompt&&tab.id===firstEngine?.id&&fresh,isFreshFirstEngine=tab.id===firstEngine?.id&&fresh,promptIntent=tabPrompt?{kind:"explicit",prompt:tabPrompt}:wantsPrompt?{kind:"new-task",prompt}:isFreshFirstEngine?{kind:"repo-init"}:{kind:"none"},ref=tab.ptyTask;trustEngineWorktree(tab.vendor??opts.task.vendor,ref?.worktree??opts.worktreePath);let launch=buildEngineSessionLaunch({task:ref?{...opts.task,id:ref.id,kind:"task"}:opts.task,worktreePath:ref?.worktree??opts.worktreePath,shell,argv:engineTabArgv(tab,base,live,opts.task.vendor),promptIntent,protocolGates:opts.protocolGates,tabId:ref?"tab-1":tab.id});return{command:launch.command,...launch.firstMessage?{firstMessage:launch.firstMessage,engineBin:base[0]}:{}}}function tabExitAction(tab,deadOnAttach,resumeTried){if(tab.kind==="engine"&&deadOnAttach&&!!tab.sessionId&&tab.spawned&&!resumeTried)return"resume";return"close"}var SHELL_SAFE_ARG=/^[A-Za-z0-9@%+=:,./_-]+$/;function shellCommandLine(argv){return argv.map((a)=>SHELL_SAFE_ARG.test(a)?a:`'${a.replaceAll("'","'\\''")}'`).join(" ")}function shellIdentityInput(taskId,tabId){let task=shellCommandLine([taskId]),tab=shellCommandLine([tabId]);return` export ROVE_TASK_ID=${task} KOBE_TASK_ID=${task} ROVE_TAB_ID=${tab} KOBE_TAB_ID=${tab} && clear\r`}function insertAfterActive(state,tab){let i=state.tabs.findIndex((t2)=>t2.id===state.activeId);return{tabs:[...state.tabs.slice(0,i+1),tab,...state.tabs.slice(i+1)],activeId:tab.id,nextOrdinal:state.nextOrdinal+1}}function addTab(state,vendor){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"engine",id:`tab-${ordinal}`,title:null,ordinal,vendor})}function openCommandTab(state,command,label){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command})}function findEditorTab(state){return state.tabs.find((tab)=>tab.kind==="command"&&tab.purpose==="editor")}function openEditorTab(state,command,label){let existing=findEditorTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command,purpose:"editor"})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,command,splitTree:null}:tab);return{...state,tabs,activeId:existing.id}}function findContentTab(state){return state.tabs.find((tab)=>tab.kind==="content")}function openContentTab(state,relPath,label,base){let existing=findContentTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"content",id:`tab-${ordinal}`,title:label,ordinal,relPath,base})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,relPath,base}:tab);return{...state,tabs,activeId:existing.id}}function closeTab(state,id,opts={}){if(state.tabs.length<=1&&!opts.allowEmpty)return{state,closedId:null};let i=state.tabs.findIndex((t2)=>t2.id===id);if(i<0)return{state,closedId:null};let tabs=state.tabs.filter((t2)=>t2.id!==id);if(state.activeId!==id)return{state:{...state,tabs},closedId:id};if(tabs.length===0)return{state:{...state,tabs,activeId:id,reopenAs:reopenHintFor(state.tabs[i])},closedId:id};let next=tabs[Math.max(0,i-1)];return{state:{...state,tabs,activeId:(next??tabs[0]).id},closedId:id}}function closeActiveTab(state){return closeTab(state,state.activeId)}function renameActiveTab(state,title){return setTabTitle(state,state.activeId,title)}function setTabTitle(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.title??null)===next)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,title:next}:t2);return{...state,tabs}}function setTabSessionId(state,id,sessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,sessionId}:t2);return{...state,tabs}}function setTabForkFrom(state,id,sourceSessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,forkFrom:sourceSessionId}:t2);return{...state,tabs}}function setTabEngineCommand(state,id,command){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,engineCommand:command}:t2);return{...state,tabs}}function setTabInitialPrompt(state,id,prompt){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,initialPrompt:prompt}:t2);return{...state,tabs}}function setTabLastTitle(state,id,lastTitle){if(lastTitle.length===0)return state;let current=state.tabs.find((t2)=>t2.id===id);if(!current||current.lastTitle===lastTitle)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,lastTitle}:t2);return{...state,tabs}}function setTabLiveVendor(state,id,liveVendor){let current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.liveVendor??null)===liveVendor)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,liveVendor}:t2);return{...state,tabs}}function setTabAutoTitle(state,id,autoTitle){let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,autoTitle}:t2);return{...state,tabs}}function setTabSpawned(state,id,spawned){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"&&!t2.spawned!==!spawned?{...t2,spawned}:t2);return{...state,tabs}}function cycleTab(state,delta){let n=state.tabs.length;if(n<=1)return state;let i=state.tabs.findIndex((t2)=>t2.id===state.activeId),next=state.tabs[(i+delta+n)%n];return{...state,activeId:next.id}}function moveTab(state,id,delta){let i=state.tabs.findIndex((t2)=>t2.id===id),j=i+delta;if(i<0||j<0||j>=state.tabs.length)return state;let tabs=[...state.tabs],a=tabs[i];return tabs[i]=tabs[j],tabs[j]=a,{...state,tabs}}function selectTab(state,id){if(state.activeId===id||!state.tabs.some((t2)=>t2.id===id))return state;return{...state,activeId:id}}function setTabSplit(state,id,tree){if(!state.tabs.some((t2)=>t2.id===id))return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,splitTree:tree}:t2);return{...state,tabs}}function tabPtyKey(taskId,tabId){return`${taskId}::${tabId}`}function tabPtyKeyFor(taskId,tab){if(tab.kind==="engine"&&tab.ptyTask)return tabPtyKey(tab.ptyTask.id,"tab-1");return tabPtyKey(taskId,tab.id)}function tabCwdFor(tab,taskWorktree){if(tab.kind==="engine"&&tab.ptyTask)return tab.ptyTask.worktree;return taskWorktree}function terminalTabsKey(taskId){return`terminalTabs.${taskId}`}function forgetTaskTabsSnapshot(kv,taskId){let key=terminalTabsKey(taskId);if(kv.store[key]===void 0)return;kv.set(key,void 0)}function sweepOrphanTabsSnapshots(kv,liveTaskIds){let live=new Set(liveTaskIds),swept=0;for(let key of Object.keys(kv.store)){if(!key.startsWith("terminalTabs."))continue;let taskId=key.slice(13);if(live.has(taskId))continue;kv.set(key,void 0),swept++}return swept}
|
|
2
|
+
import{buildEngineSessionLaunch,trustEngineWorktree}from"./chunk-ann3wt0v.js";import{engineForkArgv,engineResumeArgv,withPinnedSessionId}from"./chunk-qqw3p4fc.js";import{t}from"./chunk-xwekyjat.js";import{engineEntry,engineStatusPrefixes,isEnginePlaceholderTitle,stripEngineStatusPrefix}from"./chunk-xhw8s2es.js";import*as fs from"fs";import*as os from"os";function pathLeaf(p){return p.slice(p.lastIndexOf("/")+1)}function expandHome(p){if(p==="~")return os.homedir();if(p.startsWith("~/"))return os.homedir()+p.slice(1);return p}function stripTrailingSlash(p){return p.length>1&&p.endsWith("/")?p.slice(0,-1):p}function splitPathForDirSuggest(value){if(!value)return{base:"",filter:""};let expanded=expandHome(value==="~"?"~/":value);if(expanded.endsWith("/"))return{base:expanded,filter:""};let lastSlash=expanded.lastIndexOf("/");if(lastSlash===-1)return{base:"",filter:expanded};return{base:expanded.slice(0,lastSlash+1),filter:expanded.slice(lastSlash+1)}}function listSubdirs(base){if(!base)return[];try{let entries=fs.readdirSync(base,{withFileTypes:!0}),out=[];for(let e of entries)if(e.isDirectory())out.push(e.name);return out.sort((a,b)=>a.localeCompare(b))}catch{return[]}}function filterSubdirs(all,filter){let f=filter.toLowerCase(),visible=f.startsWith(".")?all:all.filter((n)=>!n.startsWith("."));if(!f)return visible;return visible.filter((n)=>n.toLowerCase().startsWith(f))}function joinDrill(typedValue,baseExpanded,name){let out=`${baseExpanded+name}/`;if(typedValue.startsWith("~")){let home=os.homedir();if(out===`${home}/`)return"~/";if(out.startsWith(`${home}/`))return`~${out.slice(home.length)}`}return out}function joinPicked(typedValue,baseExpanded,name){let out=baseExpanded+name;if(typedValue.startsWith("~")){let home=os.homedir();if(out===home)return"~";if(out.startsWith(`${home}/`))return`~${out.slice(home.length)}`}return out}function depth(node){return node.kind==="leaf"?0:1+Math.max(...node.children.map(depth))}function siblingCount(root,id,orientation){let find=(node)=>{if(node.kind==="leaf")return null;if(node.orientation===orientation&&node.children.some((c)=>c.kind==="leaf"&&c.id===id))return node.children.length;for(let child of node.children){let n=find(child);if(n!==null)return n}return null};return find(root)??1}function splitFits(state,orientation,activeSize){let extent=orientation==="row"?activeSize.cols:activeSize.rows,min=orientation==="row"?20:6,n=siblingCount(state.root,state.activeLeafId,orientation);return Math.floor(extent*n/(n+1))-1>=min}function initialSplit(content){return{root:{kind:"leaf",id:"leaf-1",content},activeLeafId:"leaf-1",nextOrdinal:2}}function leaves(node){return node.kind==="leaf"?[node]:node.children.flatMap(leaves)}function splitActive(state,orientation,content,activeSize){if(activeSize&&!splitFits(state,orientation,activeSize))return state;let leaf={kind:"leaf",id:`leaf-${state.nextOrdinal}`,content},insert=(node)=>{if(node.kind==="leaf"){if(node.id!==state.activeLeafId)return node;return{kind:"group",orientation,children:[node,leaf]}}if(node.orientation===orientation){let i=node.children.findIndex((c)=>c.kind==="leaf"&&c.id===state.activeLeafId);if(i>=0){let children=[...node.children.slice(0,i+1),leaf,...node.children.slice(i+1)];return{...node,children}}}return{...node,children:node.children.map(insert)}},root=insert(state.root);if(!activeSize&&depth(root)>4)return state;return{root,activeLeafId:leaf.id,nextOrdinal:state.nextOrdinal+1}}function removeLeaf(state,id){let all=leaves(state.root);if(all.length<=1)return null;let prune=(node)=>{if(node.kind==="leaf")return node.id===id?null:node;let children=node.children.map(prune).filter((c)=>c!==null);if(children.length===0)return null;if(children.length===1)return children[0];return{...node,children}},root=prune(state.root);if(root===null)return null;if(leaves(root).length===all.length)return state;let order=all.map((l)=>l.id),removedIdx=order.indexOf(id),fallback=order[removedIdx>0?removedIdx-1:removedIdx+1],activeLeafId=state.activeLeafId===id?fallback:state.activeLeafId;return{...state,root,activeLeafId}}function renameLeaf(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,walk=(node)=>node.kind==="leaf"?node.id===id?{...node,title:next}:node:{...node,children:node.children.map(walk)};if(!leaves(state.root).some((l)=>l.id===id))return state;return{...state,root:walk(state.root)}}function cycleLeaf(state,delta){let order=leaves(state.root).map((l)=>l.id);if(order.length<=1)return state;let i=order.indexOf(state.activeLeafId),next=order[(i+delta+order.length)%order.length];return{...state,activeLeafId:next}}function hasEngineLeaf(tree){return!tree||leaves(tree.root).some((l)=>l.id==="leaf-1")}function isTabSplit(tree){return tree?leaves(tree.root).length>1:!1}function collapseSplit(next){let ls=leaves(next.root);return ls.length===1&&ls[0]?.id==="leaf-1"?null:next}function splitLeafPtyKey(tabKey,leafId){return leafId==="leaf-1"?tabKey:`${tabKey}::${leafId}`}var SHELL_LEAF_NAME="shell";function splitLeafNames(leafList,tabCommand,engineTitle,liveTitles){let basename=(argv)=>{let head=(argv??tabCommand)[0]??"",name=pathLeaf(head);return name.length>0?name:"?"},seen=new Map,out=new Map;for(let leaf of leafList){if(leaf.title){out.set(leaf.id,leaf.title);continue}let name=leaf.content===null?engineTitle||liveTitles?.get(leaf.id)||basename(leaf.content):liveTitles?.get(leaf.id)||SHELL_LEAF_NAME,n=(seen.get(name)??0)+1;seen.set(name,n),out.set(leaf.id,n===1?name:`${name} ${n}`)}return out}function meaningfulAutoTitle(autoTitle){let trimmed=(autoTitle??"").trim();if(trimmed.length<3)return null;if(/^[\d\s\p{P}\p{S}]+$/u.test(trimmed))return null;return trimmed}function stableRecordedTitle(raw,vendor){let recorded=raw?.trim();if(!recorded)return null;let cleaned=stripEngineStatusPrefix(recorded,vendor);if(cleaned===recorded&&isEngineDecoration(recorded,vendor))return null;if(isEnginePlaceholderTitle(cleaned,vendor))return null;return cleaned||null}function isEngineDecoration(text,vendor){let glyphs=new Set(engineStatusPrefixes(vendor));return[...text].every((ch)=>ch.trim().length===0||glyphs.has(ch))}function tabTitleStable(tab,taskVendor,liveVendor,liveTitle){if(liveVendor===null&&tab.kind==="engine")return tabTitle({...tab,kind:"command",lastTitle:null},taskVendor);let vendor=liveVendor??tab.liveVendor??(tab.kind==="engine"?tab.vendor??taskVendor:void 0)??void 0,source=liveTitle?.trim()||tab.lastTitle,named=vendor?stableRecordedTitle(source,vendor):source??null;if(!vendor||engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return tabTitle({...tab,lastTitle:named},taskVendor);return tabTitle({...tab,kind:"engine",vendor,lastTitle:named},taskVendor)}function titleVendor(tab,taskVendor){return tab.liveVendor??(tab.kind==="engine"?tab.vendor:void 0)??taskVendor}function tabTitle(tab,taskVendor,liveName){if(tab.title)return tab.title;let ls=tab.splitTree?leaves(tab.splitTree.root):[];if(ls.length>1)return t("terminal.tab.groupTitle",{n:tab.ordinal});let sole=ls.length===1?ls[0]:void 0;if(sole&&sole.id!=="leaf-1")return sole.title??`${liveName??SHELL_LEAF_NAME} ${tab.ordinal}`;let vendor=titleVendor(tab,taskVendor);if(liveName&&!isEnginePlaceholderTitle(liveName,vendor))return`${liveName} ${tab.ordinal}`;if(tab.lastTitle&&!isEnginePlaceholderTitle(tab.lastTitle,vendor))return`${tab.lastTitle} ${tab.ordinal}`;let auto=meaningfulAutoTitle(tab.autoTitle);if(auto)return auto;return`${tab.kind==="engine"?engineEntry(tab.vendor??taskVendor).defaultCommand[0]??SHELL_LEAF_NAME:SHELL_LEAF_NAME} ${tab.ordinal}`}function visibleNativeStatus(tab,taskVendor,vendor,liveName){if(!vendor||!liveName)return!1;if(engineEntry(vendor).terminalTitle?.ownsStatus!==!0)return!1;return tabTitle(tab,taskVendor,liveName)===`${liveName} ${tab.ordinal}`}function initialTabs(){return{tabs:[{kind:"engine",id:"tab-1",title:null,ordinal:1}],activeId:"tab-1",nextOrdinal:2}}function reopenHintFor(closed){if(closed?.kind==="command")return{kind:"command"};if(closed?.kind==="engine"&&closed.vendor)return{kind:"engine",vendor:closed.vendor};return{kind:"engine"}}function reopenTabs(state,shell){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,next=state.nextOrdinal+1;if(state.reopenAs?.kind==="command")return{tabs:[{kind:"command",id,title:null,ordinal,command:[shell]}],activeId:id,nextOrdinal:next};let vendor=state.reopenAs?.kind==="engine"?state.reopenAs.vendor:void 0;return{tabs:[{kind:"engine",id,title:null,ordinal,...vendor?{vendor}:{}}],activeId:id,nextOrdinal:next}}function initialShellTabs(shell){return{tabs:[{kind:"command",id:"tab-1",title:null,ordinal:1,command:[shell]}],activeId:"tab-1",nextOrdinal:2}}function rehydrateTabs(persisted,shell,opts={}){let tabs=persisted.tabs.map((t2)=>t2.kind==="command"?{...t2,command:shell,purpose:void 0}:t2);if(tabs.length===0)return opts.allowEmpty?persisted:initialTabs();let activeId=tabs.some((t2)=>t2.id===persisted.activeId)?persisted.activeId:tabs[0].id,maxOrdinal=tabs.reduce((max,t2)=>Math.max(max,t2.ordinal),0);return{tabs,activeId,nextOrdinal:Math.max(persisted.nextOrdinal,maxOrdinal+1)}}function recycleTabs(state,prev){let ordinal=state.nextOrdinal,id=`tab-${ordinal}`,pinned=prev.kind==="engine"?prev:void 0;return{tabs:[{kind:"engine",id,ordinal,title:prev.title,autoTitle:prev.autoTitle,...pinned?.vendor?{vendor:pinned.vendor}:{},...pinned?.engineCommand?{engineCommand:pinned.engineCommand}:{}}],activeId:id,nextOrdinal:ordinal+1}}function engineTabArgv(tab,base,live,fallbackVendor){if(tab.forkFrom&&!tab.spawned&&!live){let forked=tab.vendor?engineForkArgv(base,tab.vendor,tab.forkFrom,tab.sessionId??null):null;if(forked)return forked}if(!tab.sessionId)return base;let vendor=tab.vendor??fallbackVendor;if(tab.spawned&&!live)return engineResumeArgv(base,vendor,tab.sessionId)??base;return withPinnedSessionId(base,vendor,()=>tab.sessionId).argv}function engineTabSpawnFor(state,tab,base,opts){let{live,shell,prompt}=opts,firstEngine=state.tabs.find((t2)=>t2.kind==="engine"),fresh=!tab.spawned&&!live,tabPrompt=fresh?tab.initialPrompt?.trim():void 0,wantsPrompt=!!prompt&&tab.id===firstEngine?.id&&fresh,isFreshFirstEngine=tab.id===firstEngine?.id&&fresh,promptIntent=tabPrompt?{kind:"explicit",prompt:tabPrompt}:wantsPrompt?{kind:"new-task",prompt}:isFreshFirstEngine?{kind:"repo-init"}:{kind:"none"},ref=tab.ptyTask;trustEngineWorktree(tab.vendor??opts.task.vendor,ref?.worktree??opts.worktreePath);let launch=buildEngineSessionLaunch({task:ref?{...opts.task,id:ref.id,kind:"task"}:opts.task,worktreePath:ref?.worktree??opts.worktreePath,shell,argv:engineTabArgv(tab,base,live,opts.task.vendor),promptIntent,protocolGates:opts.protocolGates,tabId:ref?"tab-1":tab.id});return{command:launch.command,...launch.firstMessage?{firstMessage:launch.firstMessage,engineBin:base[0]}:{}}}function tabExitAction(tab,deadOnAttach,resumeTried){if(tab.kind==="engine"&&deadOnAttach&&!!tab.sessionId&&tab.spawned&&!resumeTried)return"resume";return"close"}var SHELL_SAFE_ARG=/^[A-Za-z0-9@%+=:,./_-]+$/;function shellCommandLine(argv){return argv.map((a)=>SHELL_SAFE_ARG.test(a)?a:`'${a.replaceAll("'","'\\''")}'`).join(" ")}function shellIdentityInput(taskId,tabId){let task=shellCommandLine([taskId]),tab=shellCommandLine([tabId]);return` export ROVE_TASK_ID=${task} KOBE_TASK_ID=${task} ROVE_TAB_ID=${tab} KOBE_TAB_ID=${tab} && clear\r`}function insertAfterActive(state,tab){let i=state.tabs.findIndex((t2)=>t2.id===state.activeId);return{tabs:[...state.tabs.slice(0,i+1),tab,...state.tabs.slice(i+1)],activeId:tab.id,nextOrdinal:state.nextOrdinal+1}}function addTab(state,vendor){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"engine",id:`tab-${ordinal}`,title:null,ordinal,vendor})}function openCommandTab(state,command,label){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command})}function findEditorTab(state){return state.tabs.find((tab)=>tab.kind==="command"&&tab.purpose==="editor")}function openEditorTab(state,command,label){let existing=findEditorTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"command",id:`tab-${ordinal}`,title:label,ordinal,command,purpose:"editor"})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,command,splitTree:null}:tab);return{...state,tabs,activeId:existing.id}}function findContentTab(state){return state.tabs.find((tab)=>tab.kind==="content")}function openContentTab(state,relPath,label,base){let existing=findContentTab(state);if(!existing){let ordinal=state.nextOrdinal;return insertAfterActive(state,{kind:"content",id:`tab-${ordinal}`,title:label,ordinal,relPath,base})}let tabs=state.tabs.map((tab)=>tab.id===existing.id?{...existing,title:label,relPath,base}:tab);return{...state,tabs,activeId:existing.id}}function closeTab(state,id,opts={}){if(state.tabs.length<=1&&!opts.allowEmpty)return{state,closedId:null};let i=state.tabs.findIndex((t2)=>t2.id===id);if(i<0)return{state,closedId:null};let tabs=state.tabs.filter((t2)=>t2.id!==id);if(state.activeId!==id)return{state:{...state,tabs},closedId:id};if(tabs.length===0)return{state:{...state,tabs,activeId:id,reopenAs:reopenHintFor(state.tabs[i])},closedId:id};let next=tabs[Math.max(0,i-1)];return{state:{...state,tabs,activeId:(next??tabs[0]).id},closedId:id}}function closeActiveTab(state){return closeTab(state,state.activeId)}function renameActiveTab(state,title){return setTabTitle(state,state.activeId,title)}function setTabTitle(state,id,title){let trimmed=title.trim(),next=trimmed.length>0?trimmed:null,current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.title??null)===next)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,title:next}:t2);return{...state,tabs}}function setTabSessionId(state,id,sessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,sessionId}:t2);return{...state,tabs}}function setTabForkFrom(state,id,sourceSessionId){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,forkFrom:sourceSessionId}:t2);return{...state,tabs}}function setTabEngineCommand(state,id,command){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,engineCommand:command}:t2);return{...state,tabs}}function setTabInitialPrompt(state,id,prompt){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"?{...t2,initialPrompt:prompt}:t2);return{...state,tabs}}function setTabLastTitle(state,id,lastTitle){if(lastTitle.length===0)return state;let current=state.tabs.find((t2)=>t2.id===id);if(!current||current.lastTitle===lastTitle)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,lastTitle}:t2);return{...state,tabs}}function setTabLiveVendor(state,id,liveVendor){let current=state.tabs.find((t2)=>t2.id===id);if(!current||(current.liveVendor??null)===liveVendor)return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,liveVendor}:t2);return{...state,tabs}}function setTabAutoTitle(state,id,autoTitle){let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,autoTitle}:t2);return{...state,tabs}}function setTabSpawned(state,id,spawned){let tabs=state.tabs.map((t2)=>t2.id===id&&t2.kind==="engine"&&!t2.spawned!==!spawned?{...t2,spawned}:t2);return{...state,tabs}}function cycleTab(state,delta){let n=state.tabs.length;if(n<=1)return state;let i=state.tabs.findIndex((t2)=>t2.id===state.activeId),next=state.tabs[(i+delta+n)%n];return{...state,activeId:next.id}}function moveTab(state,id,delta){let i=state.tabs.findIndex((t2)=>t2.id===id),j=i+delta;if(i<0||j<0||j>=state.tabs.length)return state;let tabs=[...state.tabs],a=tabs[i];return tabs[i]=tabs[j],tabs[j]=a,{...state,tabs}}function selectTab(state,id){if(state.activeId===id||!state.tabs.some((t2)=>t2.id===id))return state;return{...state,activeId:id}}function setTabSplit(state,id,tree){if(!state.tabs.some((t2)=>t2.id===id))return state;let tabs=state.tabs.map((t2)=>t2.id===id?{...t2,splitTree:tree}:t2);return{...state,tabs}}function tabPtyKey(taskId,tabId){return`${taskId}::${tabId}`}function tabPtyKeyFor(taskId,tab){if(tab.kind==="engine"&&tab.ptyTask)return tabPtyKey(tab.ptyTask.id,"tab-1");return tabPtyKey(taskId,tab.id)}function tabCwdFor(tab,taskWorktree){if(tab.kind==="engine"&&tab.ptyTask)return tab.ptyTask.worktree;return taskWorktree}function terminalTabsKey(taskId){return`terminalTabs.${taskId}`}function forgetTaskTabsSnapshot(kv,taskId){let key=terminalTabsKey(taskId);if(kv.store[key]===void 0)return;kv.set(key,void 0)}function sweepOrphanTabsSnapshots(kv,liveTaskIds){let live=new Set(liveTaskIds),swept=0;for(let key of Object.keys(kv.store)){if(!key.startsWith("terminalTabs."))continue;let taskId=key.slice(13);if(live.has(taskId))continue;kv.set(key,void 0),swept++}return swept}
|
|
3
3
|
export{pathLeaf,expandHome,stripTrailingSlash,splitPathForDirSuggest,listSubdirs,filterSubdirs,joinDrill,joinPicked,initialSplit,leaves,splitActive,removeLeaf,renameLeaf,cycleLeaf,hasEngineLeaf,isTabSplit,collapseSplit,splitLeafPtyKey,splitLeafNames,tabTitleStable,tabTitle,visibleNativeStatus,initialTabs,reopenTabs,initialShellTabs,rehydrateTabs,recycleTabs,engineTabArgv,engineTabSpawnFor,tabExitAction,shellIdentityInput,addTab,openCommandTab,findEditorTab,openEditorTab,openContentTab,closeTab,closeActiveTab,renameActiveTab,setTabTitle,setTabSessionId,setTabForkFrom,setTabEngineCommand,setTabInitialPrompt,setTabLastTitle,setTabLiveVendor,setTabAutoTitle,setTabSpawned,cycleTab,moveTab,selectTab,setTabSplit,tabPtyKey,tabPtyKeyFor,tabCwdFor,terminalTabsKey,forgetTaskTabsSnapshot,sweepOrphanTabsSnapshots};
|