@sma1lboy/rove 0.9.304 → 0.9.305-next.430
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-kyddm7xe.js → chunk-06vsvvtr.js} +1 -1
- package/dist/cli/{chunk-jkxn32nk.js → chunk-0s7j1xps.js} +1 -1
- package/dist/cli/{chunk-vk2xz0s4.js → chunk-19n8y9xp.js} +3 -3
- package/dist/cli/{chunk-qnkq7d8z.js → chunk-1bertmzz.js} +3 -3
- package/dist/cli/{chunk-gb2ahsfx.js → chunk-1et3gskx.js} +1 -1
- package/dist/cli/chunk-29e7x3qx.js +2 -0
- package/dist/cli/{chunk-sd6eae1h.js → chunk-2agspgfq.js} +1 -1
- package/dist/cli/{chunk-ga0kvz6j.js → chunk-2gpr5dm4.js} +1 -1
- package/dist/cli/{chunk-d4w91a02.js → chunk-2nddryb2.js} +1 -1
- package/dist/cli/{chunk-q6qmv2jq.js → chunk-37g0yabr.js} +1 -1
- package/dist/cli/{chunk-d3d06a4w.js → chunk-3da0g8md.js} +2 -2
- package/dist/cli/{chunk-mb2tfr2c.js → chunk-3jh1cfdj.js} +1 -1
- package/dist/cli/{chunk-j1rw5jdt.js → chunk-3t3fp5h4.js} +1 -1
- package/dist/cli/{chunk-tr9n297x.js → chunk-4nzf8w3e.js} +2 -2
- package/dist/cli/{chunk-am3vaamq.js → chunk-59ff10tt.js} +1 -1
- package/dist/cli/{chunk-hmfqyvet.js → chunk-5dv7pw3w.js} +2 -2
- package/dist/cli/{chunk-cmbd3s71.js → chunk-6azsw0ry.js} +5 -5
- package/dist/cli/{chunk-vpm8dfyg.js → chunk-6cggsxpr.js} +1 -1
- package/dist/cli/{chunk-p9an6jcq.js → chunk-6jxe4f13.js} +1 -1
- package/dist/cli/{chunk-b7bbnx1x.js → chunk-6wzb9c2x.js} +1 -1
- package/dist/cli/chunk-750rk2xz.js +16 -0
- package/dist/cli/chunk-7dah6dc9.js +2 -0
- package/dist/cli/{chunk-tzf7b25k.js → chunk-7ezpcrkf.js} +1 -1
- package/dist/cli/chunk-7gk8g1ae.js +2 -0
- package/dist/cli/{chunk-22syh28c.js → chunk-7yhekmvy.js} +1 -1
- package/dist/cli/{chunk-mdypt84n.js → chunk-8ag7qs90.js} +1 -1
- package/dist/cli/chunk-8nbvsger.js +2 -0
- package/dist/cli/{chunk-cb3krnqn.js → chunk-8wejvvsz.js} +1 -1
- package/dist/cli/{chunk-akygcre8.js → chunk-9892j1n1.js} +1 -1
- package/dist/cli/{chunk-wh147k4t.js → chunk-9b42t2wf.js} +1 -1
- package/dist/cli/{chunk-ammf7919.js → chunk-9tke0g8m.js} +1 -1
- package/dist/cli/chunk-a5pd9fk3.js +2 -0
- package/dist/cli/{chunk-x4gqyhhv.js → chunk-a6s52zm5.js} +1 -1
- package/dist/cli/{chunk-d4eav2xt.js → chunk-a8j2x5pf.js} +1 -1
- package/dist/cli/chunk-aejb41e3.js +2 -0
- package/dist/cli/{chunk-jx0sfc90.js → chunk-am70fwd0.js} +1 -1
- package/dist/cli/{chunk-gr9555d9.js → chunk-b7rxn7c9.js} +1 -1
- package/dist/cli/chunk-cs7m5f61.js +2 -0
- package/dist/cli/{chunk-s00wwj3a.js → chunk-cvcp1aye.js} +1 -1
- package/dist/cli/{chunk-76433s6v.js → chunk-d35ctfpd.js} +1 -1
- package/dist/cli/chunk-dab3kttb.js +2 -0
- package/dist/cli/{chunk-7w43ktng.js → chunk-ejs6dnxf.js} +1 -1
- package/dist/cli/{chunk-yebkeqj2.js → chunk-er4mc36m.js} +1 -1
- package/dist/cli/{chunk-sqcntdty.js → chunk-etz8f2ny.js} +1 -1
- package/dist/cli/{chunk-g770enx5.js → chunk-fmhnw1nz.js} +2 -2
- package/dist/cli/{chunk-689sfk7h.js → chunk-g70rcpsp.js} +1 -1
- package/dist/cli/{chunk-px91psgc.js → chunk-ga448pv8.js} +1 -1
- package/dist/cli/{chunk-5gw9f1zb.js → chunk-gafj4yp3.js} +4 -4
- package/dist/cli/{chunk-gdjaf50p.js → chunk-ggjg0h5c.js} +1 -1
- package/dist/cli/{chunk-wjz55sc3.js → chunk-gvs8sbp2.js} +1 -1
- package/dist/cli/{chunk-zc7e78mv.js → chunk-gz0x179r.js} +1 -1
- package/dist/cli/chunk-h2xantkm.js +2 -0
- package/dist/cli/{chunk-ytx7x3j8.js → chunk-hct98wxq.js} +1 -1
- package/dist/cli/{chunk-qjr63j9v.js → chunk-kvwneanp.js} +1 -1
- package/dist/cli/chunk-m5ddrj6q.js +2 -0
- package/dist/cli/{chunk-m6ekn4q8.js → chunk-mavyyarb.js} +1 -1
- package/dist/cli/{chunk-6y1jamqn.js → chunk-me70fpec.js} +1 -1
- package/dist/cli/{chunk-ykm19q7h.js → chunk-n15p38e5.js} +1 -1
- package/dist/cli/{chunk-2v2t1a03.js → chunk-nhsem71y.js} +1 -1
- package/dist/cli/{chunk-e04yypye.js → chunk-nyr8zxgd.js} +3 -3
- package/dist/cli/{chunk-q8b6gnc5.js → chunk-p4rhkv3k.js} +1 -1
- package/dist/cli/{chunk-x3c6f2sf.js → chunk-pf3nzz87.js} +1 -1
- package/dist/cli/{chunk-jb63kaer.js → chunk-qaznc1bg.js} +1 -1
- package/dist/cli/{chunk-633beahm.js → chunk-qwqa75g1.js} +1 -1
- package/dist/cli/{chunk-2h58p581.js → chunk-r8xt34nn.js} +1 -1
- package/dist/cli/chunk-ragdpajw.js +6 -0
- package/dist/cli/{chunk-bp3edwby.js → chunk-rnmj5c45.js} +1 -1
- package/dist/cli/{chunk-ahnv378z.js → chunk-s129kc10.js} +1 -1
- package/dist/cli/chunk-s2eezz0a.js +3 -0
- package/dist/cli/{chunk-sfskhmzp.js → chunk-s6wqbs6y.js} +1 -1
- package/dist/cli/{chunk-rz5sspn8.js → chunk-sffdpzfv.js} +1 -1
- package/dist/cli/{chunk-7zawz6sa.js → chunk-sggsdk9s.js} +11 -7
- package/dist/cli/{chunk-16sb3y82.js → chunk-t4reqv8m.js} +1 -1
- package/dist/cli/{chunk-q6q4aram.js → chunk-t7qj639x.js} +1 -1
- package/dist/cli/{chunk-emj5p5k7.js → chunk-t8gt3kq8.js} +1 -1
- package/dist/cli/{chunk-486j02v4.js → chunk-vat1vjkk.js} +1 -1
- package/dist/cli/{chunk-gd8gc37t.js → chunk-vd9670dy.js} +1 -1
- package/dist/cli/chunk-vjejmwzj.js +2 -0
- package/dist/cli/{chunk-rajwag3e.js → chunk-weah9492.js} +1 -1
- package/dist/cli/{chunk-mwbs7818.js → chunk-x5ybfyja.js} +1 -1
- package/dist/cli/{chunk-zpdvfb01.js → chunk-xj3034s1.js} +1 -1
- package/dist/cli/chunk-yk3we30f.js +2 -0
- package/dist/cli/chunk-yzz6vx5j.js +2 -0
- package/dist/cli/{chunk-7d22h7qg.js → chunk-z1fpd4k2.js} +1 -1
- package/dist/cli/{chunk-r9yx4k0q.js → chunk-zc67sqet.js} +1 -1
- package/dist/cli/{chunk-nmfcvtxk.js → chunk-zp4efbtb.js} +1 -1
- package/dist/cli/{chunk-2pc4wpm4.js → chunk-zqftyn6w.js} +1 -1
- package/dist/cli/{chunk-bznee97z.js → chunk-zze1pw22.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/cli/rove.js +3 -3
- package/dist/completions/rove.bash +1 -1
- package/dist/completions/rove.fish +1 -1
- package/dist/completions/rove.zsh +1 -1
- package/dist/web/assets/{index-D9TLg2oV.js → index-7xgjby6F.js} +3 -3
- package/dist/web/assets/{term-mount-Cn86hde_.js → term-mount-OMVJnrk8.js} +1 -1
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/cli/chunk-0qxqk8cr.js +0 -2
- package/dist/cli/chunk-0r64dqy3.js +0 -3
- package/dist/cli/chunk-1fw86kg2.js +0 -2
- package/dist/cli/chunk-1w2dx91w.js +0 -2
- package/dist/cli/chunk-2ze5ss4k.js +0 -2
- package/dist/cli/chunk-46zqt24x.js +0 -2
- package/dist/cli/chunk-8647s43m.js +0 -2
- package/dist/cli/chunk-96jqrzcp.js +0 -2
- package/dist/cli/chunk-czyyrxmf.js +0 -2
- package/dist/cli/chunk-d9e1vx7y.js +0 -15
- package/dist/cli/chunk-fg7kv30n.js +0 -2
- package/dist/cli/chunk-gpmpv5gw.js +0 -2
- package/dist/cli/chunk-pe92nt86.js +0 -4
- package/dist/cli/chunk-scb1g3zf.js +0 -2
- package/dist/cli/chunk-vy5ja578.js +0 -2
- package/dist/cli/chunk-xrg2tc6p.js +0 -2
- package/dist/cli/chunk-zshgx9fp.js +0 -6
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{RELEASE_CHANNELS,channelOf}from"./chunk-
|
|
2
|
+
import{RELEASE_CHANNELS,channelOf}from"./chunk-s2eezz0a.js";import{loadStateFile,patchStateFile}from"./chunk-xasg8z9e.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
|
|
3
3
|
export{UPDATE_CHANNEL_KEY,UPDATE_NOTIFY_KEY,normalizeReleaseChannel,preferredReleaseChannel,updateNotifyEnabled,rememberReleaseChannel,updateDelayHours};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{getGlobalDefaultVendor}from"./chunk-2x6s7z8w.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-
|
|
2
|
+
import{getGlobalDefaultVendor}from"./chunk-2x6s7z8w.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-s2eezz0a.js";import{runAsync}from"./chunk-nw48bskt.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000,GH_TIMEOUT_MS=60000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
|
|
3
3
|
`)}function normalizeText(value,label){let trimmed=value.trim();if(!trimmed)throw Error(`${label} is required`);return trimmed}function issueCreateArgv(slug,title,kind){return["issue","create","-R",slug,"--title",title,"--label",KIND_LABEL[kind],"--body-file","-"]}function newIssueUrl(slug,title,body,kind){let prefilled=body.length>MAX_PREFILL_BODY?`${body.slice(0,MAX_PREFILL_BODY)}
|
|
4
4
|
|
|
5
5
|
[truncated]`:body,query=new URLSearchParams({title,body:prefilled,labels:KIND_LABEL[kind]});return`https://github.com/${slug}/issues/new?${query.toString()}`}var ISSUE_URL=/https:\/\/\S+\/issues\/(\d+)/;async function submitFeedback(input,deps={}){let title=normalizeText(input.title,"feedback title"),kind=input.kind??DEFAULT_FEEDBACK_KIND,body=`${normalizeText(input.body,"feedback body")}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{FINISHED_ALERTS_KEY,MUTED_TASKS_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,TOAST_DURATION_MS,addUnread,armPrefixNow,bindingReachability,bumpKeymapVersion,configurePrefix,currentPrefixConfiguration,dispatchKeyEvent,findBinding,inputPassthroughReachable,insertRegistration,invokeArmedPrefixAction,isCtrlModifierKeyName,isKittyModifierKeyName,mutedTaskIds,osc9,persistedSoundVolume,prefixHudHideDirect,prefixHudShowDirect,readKeybindingsFile,removeUnread,resetKeybindingsFileCache,resetKeymapToDefaults,resetPrefixConfiguration,resetPrefixState,resolveUserKeybindings,shouldAlert,shouldPlaySound,shouldShowToast,writeKeybindingEdits}from"./chunk-b8hd91nv.js";import{$Fragment,$jsx,$jsxs,createRoot2,flushSync2,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{RemoteOrchestrator}from"./chunk-ykm19q7h.js";import{updaterShell,updaterShellFailureHint}from"./chunk-gb2ahsfx.js";import{CURRENT_VERSION}from"./chunk-0r64dqy3.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,applyDisplayOverlay,readPersistedUiPrefs,resolveTheme,resolveThemeMode}from"./chunk-4whghfgg.js";import{loadUserThemes}from"./chunk-gzn14mwk.js";import{TERMINAL_TABS_PREFIX}from"./chunk-xjrkvksc.js";import{connectIfRunning}from"./chunk-k7tdg6kb.js";import{tildify}from"./chunk-1feav1w3.js";import{loadStateFile,readStateFileStrict,replaceStateFile,updateStateFile}from"./chunk-xasg8z9e.js";import{isLocaleId,localeState,setLocaleLang,t}from"./chunk-8xdhw922.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-cmp64q4j.js";import{installClientCrashHandlers,logClient,logClientError,setClientLogContext}from"./chunk-y8hjgmn0.js";import{kvStatePath}from"./chunk-8143k3t6.js";import{__toESM}from"./chunk-91sykzqq.js";import{RGBA}from"@opentui/core";var import_react3=__toESM(require_react_production(),1);var import_react=__toESM(require_react_production(),1);function useAccessor(state){return import_react.useSyncExternalStore(state.subscribe,state.get,state.get)}var store=createStateCell({themes:{...BUNDLED_THEMES},active:DEFAULT_THEME,mode:DEFAULT_THEME_MODE,transparentBackground:!0,focusAccent:"primary"});function listThemes(){return Object.keys(store.get().themes)}function hasTheme(name){return Boolean(store.get().themes[name])}function addTheme(name,theme){if(!name)return!1;if(!theme||typeof theme!=="object"||!theme.theme)return!1;return store.update((s)=>({...s,themes:{...s.themes,[name]:theme}})),!0}function selectedTheme(){return store.get().active}function setTheme(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0}function transparentBackground(){return store.get().transparentBackground}function setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))}function focusAccent(){return store.get().focusAccent}function setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))}function themeMode(){return store.get().mode}function setThemeMode(mode){store.update((s)=>({...s,mode}))}var ThemeContext=import_react3.createContext(null),HOST_PALETTE_QUERY_TIMEOUT_MS=2000;function resolveActive(state,mode){let active=state.themes[state.active];if(active)return resolveTheme(active,mode);let fallback=state.themes[DEFAULT_THEME]??Object.values(state.themes)[0];if(!fallback)return resolveTheme({theme:{background:"#000000",text:"#ffffff"}},mode);return resolveTheme(fallback,mode)}function useHostThemeMode(renderer){let[mode,setMode]=import_react3.useState(()=>renderer?.themeMode??null);return import_react3.useEffect(()=>{if(!renderer)return;let onChange=(next)=>setMode(next);return renderer.on("theme_mode",onChange),setMode(renderer.themeMode),()=>{renderer.off("theme_mode",onChange)}},[renderer]),mode}function ThemeProvider(props){import_react3.useMemo(()=>{store.update((s)=>({...s,mode:props.mode??s.mode,active:props.theme&&s.themes[props.theme]?props.theme:s.active}))},[]);let state=useAccessor(store),renderer=useRenderer(),hostMode=useHostThemeMode(renderer),mode=resolveThemeMode(state.mode,hostMode),[hostBackground,setHostBackground]=import_react3.useState(null);import_react3.useEffect(()=>{if(!state.transparentBackground)return;if(renderer?.screenMode==="split-footer")return;if(!renderer)return;let cancelled=!1;return renderer.getPalette({timeout:HOST_PALETTE_QUERY_TIMEOUT_MS}).then((colors)=>{if(cancelled||!colors.defaultBackground)return;setHostBackground(RGBA.fromHex(colors.defaultBackground))}).catch(()=>{}),()=>{cancelled=!0}},[renderer,state.transparentBackground]);let theme=import_react3.useMemo(()=>applyDisplayOverlay(resolveActive(state,mode),state.focusAccent,state.transparentBackground,hostBackground??void 0),[state,mode,hostBackground]);import_react3.useEffect(()=>{if(renderer?.screenMode==="split-footer")return;renderer?.setBackgroundColor(theme.background??RGBA.fromInts(0,0,0))},[renderer,theme]);let value=import_react3.useMemo(()=>({theme,selected:state.active,transparentBackground:state.transparentBackground,focusAccent:state.focusAccent,modePreference:state.mode,mode:()=>mode,set(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0},setMode(next){store.update((s)=>({...s,mode:next}))},setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))},setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))},preview:(options)=>applyDisplayOverlay(resolveActive({...state,active:options.themeName},resolveThemeMode(options.themeMode,hostMode)),options.focusAccent,options.transparentBackground,hostBackground??void 0),all:listThemes,has:hasTheme}),[theme,state,mode,hostMode,hostBackground]);return $jsx(ThemeContext.Provider,{value,children:props.children})}function useTheme(){let value=import_react3.useContext(ThemeContext);if(!value)throw Error("Theme context must be used within a context provider");return value}var import_react4=__toESM(require_react_production(),1);function useLang(){return useAccessor(localeState())}function useT(){let lang=useLang();return import_react4.useCallback((key,params)=>t(key,params),[lang])}var import_react7=__toESM(require_react_production(),1);var CTRL_HOLD_THRESHOLD_MS=400;function createCtrlHoldDetector(callbacks){let state={kind:"idle"},held=new Set,reset=()=>{if(state.kind==="pending")clearTimeout(state.timer);if(state.kind==="visible")callbacks.onHide();state={kind:"idle"}},cancel=()=>{reset(),held.clear()};return{keypress:(event)=>{if(!isCtrlModifierKeyName(event.name)){cancel();return}if(event.eventType==="repeat"&&held.has(event.name))return;if(event.eventType!=="press")return;if(held.add(event.name),state.kind!=="idle")return;state={kind:"pending",timer:setTimeout(()=>{state={kind:"visible"},callbacks.onReveal()},CTRL_HOLD_THRESHOLD_MS)}},keyrelease:(event)=>{if(!isCtrlModifierKeyName(event.name)||event.eventType!=="release")return;if(held.delete(event.name),held.size===0)reset()},cancel}}function availableActions(stack){let seen=new Set,actions=[],passthrough=inputPassthroughReachable(stack);for(let registration of[...stack].reverse()){let config=registration.config();if(config.enabled===!1)continue;for(let binding of config.bindings){if(binding.prefix&¤tPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}var MODIFIER_GLYPH={ctrl:"\u2303",control:"\u2303",alt:"\u2325",opt:"\u2325",option:"\u2325",shift:"\u21E7",cmd:"\u2318",command:"\u2318",meta:"\u2318",super:"\u2318"},KEY_GLYPH={enter:"\u23CE",return:"\u23CE",esc:"\u238B",escape:"\u238B",space:"\u2423",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",backspace:"\u232B",delete:"\u2326",del:"\u2326",pgup:"\u21DE",pageup:"\u21DE",pgdn:"\u21DF",pagedown:"\u21DF",home:"\u2196",end:"\u2198"};function formatKey(k,upper){if(k.includes("/"))return k.split("/").map((part)=>formatKey(part,upper)).join("/");let low=k.toLowerCase();if(low==="tab")return"tab";let named=KEY_GLYPH[low];if(named)return named;if(/^f\d{1,2}$/.test(low))return low.toUpperCase();if(!upper)return k;if(/^[a-z]$/.test(low))return k.toUpperCase();return k.replace(/[a-z]+/gi,(run)=>run.toUpperCase())}function formatChord(chord,prefixGlyph="\u2303A"){let s=chord.trim();if(!s)return s;let pm=/^prefix\s+(.+)$/i.exec(s);if(pm){let suffix=pm[1]??"";return`${prefixGlyph} ${suffix.includes("+")?formatChord(suffix,prefixGlyph):formatKey(suffix,!0)}`}let parts=s.split("+");if(parts.length===1)return formatKey(parts[0]??"",!1);let key=parts[parts.length-1]??"";return`${parts.slice(0,-1).map((p)=>MODIFIER_GLYPH[p.toLowerCase().trim()]??p).join("")} ${formatKey(key,!0)}`}var DIRECT_GUIDE_PREFIX_ACTION_ID="prefix.moreCommands",CTRL_FOLLOW_UP_CHORD=/^ctrl\+[^+]+$/;function ctrlFollowUpKey(chord){return CTRL_FOLLOW_UP_CHORD.test(chord)?chord.slice(5):null}function shortcutCaption(input){let binding=findBinding(input.bindingId);if(!binding)return null;if(input.reachability.direct.has(input.bindingId)){let direct=binding.keys[0];if(direct)return formatChord(direct)}if(input.prefixKey&&input.reachability.prefix.has(input.bindingId)){let stroke=binding.prefixKeys?.[0];if(stroke)return`${formatChord(input.prefixKey)} ${formatChord(stroke)}`}return null}function directGuideOptions(reachability,prefixKey){let options=RoveKeymap.filter((binding)=>reachability.direct.has(binding.id)).flatMap((binding)=>{let strokes=binding.keys.flatMap((chord)=>ctrlFollowUpKey(chord)??[]);if(strokes.length>2)return[{stroke:`${strokes[0]}-${strokes.at(-1)}`,action:binding.id}];return strokes.map((stroke)=>({stroke,action:binding.id}))}),prefixStroke=prefixKey?ctrlFollowUpKey(prefixKey):null;if(prefixStroke&&reachability.prefix.size>0)options.push({stroke:prefixStroke,action:DIRECT_GUIDE_PREFIX_ACTION_ID});return options}var import_react5=__toESM(require_react_production(),1);function useLatest(value){let ref=import_react5.useRef(value);return ref.current=value,ref}var ModalScopeContext=import_react7.createContext(null),nextId=1,stack=[],installedRenderer=null,installed=null,listener=null,releaseListener=null,ctrlHoldDetector=null,supersededRenderers=new WeakSet;function ensureInstalled(renderer){if(!renderer)throw Error("useBindings: no renderer in scope; call inside a component rendered by @opentui/react.");if(installedRenderer===renderer)return;if(supersededRenderers.has(renderer))return;if(installed&&listener)installed.off("keypress",listener);if(installed&&releaseListener)installed.off("keyrelease",releaseListener);if(ctrlHoldDetector?.cancel(),installedRenderer)supersededRenderers.add(installedRenderer);stack.length=0,resetPrefixState(),installedRenderer=renderer,installed=renderer.keyInput,ctrlHoldDetector=createCtrlHoldDetector({onReveal:()=>{resetPrefixState();let options=directGuideOptions(bindingReachability(stack),currentPrefixConfiguration().key);if(options.length>0)prefixHudShowDirect(options)},onHide:prefixHudHideDirect}),listener=(evt)=>{if(profileTick("key"),keyCapture){evt.preventDefault();let capture=keyCapture;if(!isKittyModifierKeyName(evt.name))flushSync2(()=>capture(evt));return}ctrlHoldDetector?.keypress(evt),dispatchKeyEvent(stack,evt,Date.now(),{flushSync:flushSync2})},releaseListener=(evt)=>ctrlHoldDetector?.keyrelease(evt),installed.on("keypress",listener),installed.on("keyrelease",releaseListener)}var keyCapture=null;function captureKeys(handler){return keyCapture=handler,()=>{if(keyCapture===handler)keyCapture=null}}function modalActive(){return stack.some((r)=>r.modalOwner!==void 0)}function currentBindingReachability(){return bindingReachability(stack)}function armPrefixFromCurrentStack(){return armPrefixNow(stack)}function invokeArmedPrefixActionFromCurrentStack(actionId,stroke){return invokeArmedPrefixAction(stack,actionId,stroke)}var stackVersion=0,stackListeners=new Set;function bumpStackVersion(){prefixHudHideDirect(),stackVersion++;for(let listener2 of stackListeners)listener2()}var bindingTableSignatures=new WeakMap;function bindingReachabilitySignature(config){let bindings=bindingTableSignatures.get(config.bindings);if(bindings===void 0)bindings=config.bindings.map((binding)=>[binding.id??"",binding.key,binding.prefix===!0?"p":"d",binding.passthrough===!0?"i":"u"].join(":")).join("|"),bindingTableSignatures.set(config.bindings,bindings);return`${config.enabled===!1?"off":"on"};${config.modal===!0?"modal":"plain"};${bindings}`}function subscribeBindingStack(listener2){return stackListeners.add(listener2),()=>{stackListeners.delete(listener2)}}function useBindingStackVersion(){return import_react7.useSyncExternalStore((onChange)=>{return stackListeners.add(onChange),()=>stackListeners.delete(onChange)},()=>stackVersion)}function useBindings(config,opts){let renderer=useRenderer();ensureInstalled(renderer);let configRef=useLatest(config),scope=import_react7.useContext(ModalScopeContext),reachabilitySignature=bindingReachabilitySignature(config()),previousReachabilitySignature=import_react7.useRef(reachabilitySignature);import_react7.useEffect(()=>{if(previousReachabilitySignature.current===reachabilitySignature)return;previousReachabilitySignature.current=reachabilitySignature,bumpStackVersion()},[reachabilitySignature]),import_react7.useEffect(()=>{if(supersededRenderers.has(renderer))return;if(opts?.modalOwner!==void 0)resetPrefixState();let reg={config:()=>configRef.current(),id:nextId++,modalOwner:opts?.modalOwner,modalMember:opts?.modalOwner===void 0?scope??void 0:void 0};return insertRegistration(stack,reg),bumpStackVersion(),()=>{let i=stack.findIndex((r)=>r.id===reg.id);if(i>=0)stack.splice(i,1);bumpStackVersion()}},[])}function pageCloseBindings(cmd){return[{key:"escape",cmd},{key:"q",cmd},{key:"ctrl+c",cmd}]}function currentPaletteActions(){return capturePaletteActions(stack)}import{createCliRenderer,setRenderLibPath}from"@opentui/core";var import_react21=__toESM(require_react_production(),1);async function connectPaneOrchestrator(options={}){let tag=options.logTag??"orch-connect",connect=options.connect??connectIfRunning,remote=null;try{let client=await connect();if(!client)return logClient(tag,"no daemon running \u2014 caller degrades"),null;return remote=new RemoteOrchestrator(client,{...options.orchestratorOptions,channels:options.channels}),await remote.init(),remote}catch(err){return logClientError(tag,err),remote?.dispose(),null}}var NARROW_BELOW_KEY="layout.narrowBelow",DEFAULT_NARROW_BELOW=70;function normalizeNarrowBelow(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"&&value.trim()!==""?Number(value.trim()):Number.NaN;if(!Number.isFinite(n))return 70;return Math.min(1000,Math.max(0,Math.floor(n)))}var cached=null;function applyUserKeybindings(){if(cached)return cached;let{report,prefix}=resolveUserKeybindings(readKeybindingsFile(),RoveKeymap,process.platform);if(report.exists)configurePrefix(prefix);for(let w of report.warnings)console.warn(`[rove/keybindings] ${w}`);return cached=report,cached}function pluginKeybindings(){return userKeybindingsReport().plugins}function userKeybindingsReport(){return cached??applyUserKeybindings()}function reloadUserKeybindings(){cached=null,resetKeybindingsFileCache(),resetKeymapToDefaults(),resetPrefixConfiguration();let report=applyUserKeybindings();return bumpKeymapVersion(),report}function saveKeybindingEdits(edits){let result=writeKeybindingEdits(edits);if(result.ok)reloadUserKeybindings();return result}var UI_PREFS_FOCUS_ACCENT_SLOTS=["primary","success","info"];var UI_PREFS_THEME_MODES=["dark","light","auto"];function applyUiPrefs(target,prefs){if(typeof prefs.theme==="string"&&prefs.theme.length>0&&prefs.theme!==target.selectedTheme()){if(!target.hasTheme(prefs.theme))target.reloadUserThemes();if(target.hasTheme(prefs.theme))target.setTheme(prefs.theme)}if(prefs.themeMode===null||typeof prefs.themeMode==="string"){let mode=normalizeThemeMode(prefs.themeMode);if(mode&&mode!==target.themeMode())target.setThemeMode(mode)}if(typeof prefs.transparentBackground==="boolean"&&prefs.transparentBackground!==target.transparentBackground())target.setTransparentBackground(prefs.transparentBackground);if(prefs.focusAccent===null||typeof prefs.focusAccent==="string"){let slot=normalizeFocusAccent(prefs.focusAccent);if(slot&&slot!==target.focusAccent())target.setFocusAccent(slot)}}function normalizeFocusAccent(value){if(value===null)return"primary";return UI_PREFS_FOCUS_ACCENT_SLOTS.includes(value)?value:null}function normalizeThemeMode(value){if(value===null)return"dark";return UI_PREFS_THEME_MODES.includes(value)?value:null}var STALL_HEARTBEAT_MS=1000,STALL_THRESHOLD_MS=2000;function stallReport(gapMs,mem,heartbeatMs=STALL_HEARTBEAT_MS,thresholdMs=STALL_THRESHOLD_MS){let stallMs=gapMs-heartbeatMs;if(stallMs<thresholdMs)return null;let mb=(n)=>Math.round(n/1048576);return`event loop stalled ~${stallMs}ms \u2014 rss=${mb(mem.rss)}MB heapUsed=${mb(mem.heapUsed)}MB`}function installEventLoopStallTelemetry(){let last=Date.now(),timer=setInterval(()=>{let now=Date.now(),gap=now-last;last=now;let report=stallReport(gap,process.memoryUsage());if(report)logClient("stall",report)},STALL_HEARTBEAT_MS);return timer.unref?.(),()=>clearInterval(timer)}var KITTY_KEYBOARD={};function hostTargetFps(){return 60}function hostRenderOptions(onDestroy){let base={backgroundColor:"transparent",externalOutputMode:"passthrough",exitOnCtrlC:!1,screenMode:"alternate-screen",useKittyKeyboard:KITTY_KEYBOARD,targetFps:hostTargetFps()};return onDestroy?{...base,onDestroy}:base}function inlineRenderOptions(heightRows,onDestroy){let base={backgroundColor:"transparent",exitOnCtrlC:!1,screenMode:"split-footer",footerHeight:heightRows,useKittyKeyboard:KITTY_KEYBOARD};return onDestroy?{...base,onDestroy}:base}function installExitRestoreBackstop(renderer){process.on("exit",()=>renderer.destroy())}var BRACKETED_PASTE_ON="\x1B[?2004h",BRACKETED_PASTE_OFF="\x1B[?2004l";function installBracketedPasteMode(stdout=process.stdout){if(!stdout.isTTY)return()=>{};let write=(seq)=>{try{stdout.write(seq)}catch{}};write(BRACKETED_PASTE_ON);let restored=!1,restore=()=>{if(restored)return;restored=!0,write(BRACKETED_PASTE_OFF)};return process.on("exit",restore),restore}var exitCriticalWork=new Set;async function whenExitReady(){while(exitCriticalWork.size>0)await Promise.allSettled([...exitCriticalWork])}function installPaneExitBackstop(opts={}){let ceilingMs=opts.ceilingMs??5000,exit=opts.exit??((code)=>process.exit(code)),exitScheduled=!1,exited=!1,exitOnce=()=>{if(exited)return;exited=!0,exit(0)},scheduleExit=()=>{if(exitScheduled)return;exitScheduled=!0;let ceiling=setTimeout(()=>{console.error(`[rove] exit backstop: ${exitCriticalWork.size} task(s) still in flight after ${ceilingMs}ms \u2014 exiting anyway`),exitOnce()},ceilingMs);ceiling.unref?.(),whenExitReady().then(()=>{clearTimeout(ceiling),exitOnce()})};for(let signal of["SIGHUP","SIGTERM","SIGINT"])process.on(signal,scheduleExit)}function installOrphanExitWatchdog(intervalMs=5000){let timer=setInterval(()=>{if(process.ppid===1)process.exit(0)},intervalMs);return timer.unref?.(),()=>clearInterval(timer)}var SYNC_START=Buffer.from("\x1B[?2026h"),SYNC_END=Buffer.from("\x1B[?2026l");class ImeAnchorController{owner=null;anchor=null;claim(owner,anchor){this.owner=owner,this.anchor={x:Math.max(0,Math.trunc(anchor.x)),y:Math.max(0,Math.trunc(anchor.y))}}release(owner){if(this.owner!==owner)return!1;return this.owner=null,this.anchor=null,!0}current(){return this.anchor}}var imeAnchorController=new ImeAnchorController;class ImeAnchorFrameTransformer{controller;pending=Buffer.alloc(0);frame=Buffer.alloc(0);constructor(controller){this.controller=controller}push(chunk){let data=this.pending.length>0?Buffer.concat([this.pending,chunk]):chunk;this.pending=Buffer.alloc(0);let output=[],offset=0;while(offset<data.length){if(this.frame.length===0){let start=data.indexOf(SYNC_START,offset);if(start<0){let tail2=data.subarray(offset),pendingLength2=longestMarkerPrefixSuffix(tail2,[SYNC_START]),safeLength2=tail2.length-pendingLength2;if(safeLength2>0)output.push(tail2.subarray(0,safeLength2));if(pendingLength2>0)this.pending=Buffer.from(tail2.subarray(safeLength2));break}if(start>offset)output.push(data.subarray(offset,start));this.frame=Buffer.from(SYNC_START),offset=start+SYNC_START.length;continue}let end=data.indexOf(SYNC_END,offset),restart=data.indexOf(SYNC_START,offset);if(restart>=0&&(end<0||restart<end)){this.frame=Buffer.from(SYNC_START),offset=restart+SYNC_START.length;continue}if(end>=0){if(end>offset)this.frame=Buffer.concat([this.frame,data.subarray(offset,end)]);output.push(this.frame);let anchor=this.controller.current();if(anchor)output.push(Buffer.from(`\x1B[${anchor.y+1};${anchor.x+1}H\x1B[?25l`));output.push(SYNC_END),this.frame=Buffer.alloc(0),offset=end+SYNC_END.length;continue}let tail=data.subarray(offset),pendingLength=longestMarkerPrefixSuffix(tail,[SYNC_START,SYNC_END]),safeLength=tail.length-pendingLength;if(safeLength>0)this.frame=Buffer.concat([this.frame,tail.subarray(0,safeLength)]);if(pendingLength>0)this.pending=Buffer.from(tail.subarray(safeLength));break}return output.length>0?Buffer.concat(output):Buffer.alloc(0)}flush(){if(this.frame.length>0)return this.frame=Buffer.alloc(0),this.pending=Buffer.alloc(0),Buffer.alloc(0);let pending=this.pending;return this.pending=Buffer.alloc(0),pending}}function longestMarkerPrefixSuffix(bytes,markers){let max=Math.min(bytes.length,Math.max(...markers.map((marker)=>marker.length-1)));for(let length=max;length>0;length-=1){let suffix=bytes.subarray(bytes.length-length);if(markers.some((marker)=>length<marker.length&&suffix.equals(marker.subarray(0,length))))return length}return 0}function asBuffer(chunk,encodingOrCallback){if(typeof chunk!=="string")return Buffer.from(chunk);let encoding=typeof encodingOrCallback==="string"?encodingOrCallback:void 0;return Buffer.from(chunk,encoding)}function writeCallback(encodingOrCallback,maybeCallback){return typeof encodingOrCallback==="function"?encodingOrCallback:maybeCallback}function createImeAnchoredOutput(target,controller=imeAnchorController){let transformer=new ImeAnchorFrameTransformer(controller),exposedWrite=(chunk,encodingOrCallback,maybeCallback)=>{let transformed=transformer.push(asBuffer(chunk,encodingOrCallback)),callback=writeCallback(encodingOrCallback,maybeCallback);if(transformed.length===0){if(callback)queueMicrotask(()=>callback(null));return!0}return callback?target.write(transformed,callback):target.write(transformed)};return{stdout:new Proxy(target,{get(stream,property){if(property==="write")return exposedWrite;let value=Reflect.get(stream,property,stream);return typeof value==="function"?value.bind(stream):value},set(stream,property,value){if(property==="write")return exposedWrite=value,!0;return Reflect.set(stream,property,value,stream)}}),flush(){let pending=transformer.flush();if(pending.length>0)target.write(pending)}}}var IME_ANCHOR_PLATFORMS=new Set(["darwin","win32"]);function createHostImeOutput(opts){if(!IME_ANCHOR_PLATFORMS.has(opts.platform)||!opts.fullscreen)return{active:!1,rendererOptions:{},attach:()=>()=>{},flush:()=>{}};let output=createImeAnchoredOutput(opts.stdout,opts.controller);return{active:!0,rendererOptions:{stdout:output.stdout,remote:!1},attach:(renderer)=>installRendererResizeForwarder(renderer,opts.stdout),flush:()=>output.flush()}}function installRendererResizeForwarder(renderer,terminal,signals=process){let onResize=()=>{let{columns:width,rows:height}=terminal;if(!width||!height)return;renderer.resize(width,height)};return signals.on("SIGWINCH",onResize),()=>signals.removeListener("SIGWINCH",onResize)}import{readFileSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";var STOCK_OPENTUI_ENV="ROVE_STOCK_OPENTUI";function roveNativeLibPath(probe){if(probe.env[STOCK_OPENTUI_ENV]==="1")return null;try{let manifestPath=probe.resolve(`@sma1lboy/opentui-rove-${probe.platform}-${probe.arch}/package.json`),manifest=JSON.parse(probe.readText(manifestPath)),core=JSON.parse(probe.readText(join(dirname(probe.resolve("@opentui/core")),"package.json")));if(!manifest.lib||!manifest.opentui||manifest.opentui!==core.version)return null;return join(dirname(manifestPath),manifest.lib)}catch{return null}}function installedRoveNativeLibPath(){let require2=createRequire(import.meta.url);return roveNativeLibPath({platform:process.platform,arch:process.arch,env:process.env,resolve:(id)=>require2.resolve(id),readText:(path)=>readFileSync(path,"utf8")})}function needsScreenSelfHeal(platform){return platform==="win32"}function requestFullRepaint(renderer){if(renderer.screenMode!=="alternate-screen")return!1;let internals=renderer;return internals.forceFullRepaintRequested=!0,renderer.requestRender(),!0}function writeThroughRenderer(renderer,chunk,fallback=process.stdout){let writeOut=renderer?.writeOut;try{if(typeof writeOut==="function")writeOut.call(renderer,chunk);else fallback.write(chunk)}catch{}}function redrawScreen(renderer){if(renderer.screenMode!=="alternate-screen")return!1;return writeThroughRenderer(renderer,"\x1B[H\x1B[2J"),requestFullRepaint(renderer)}function installScreenSelfHeal(opts){let platform=opts.platform??process.platform;if(!needsScreenSelfHeal(platform))return()=>{};let{renderer}=opts,repaint=()=>{requestFullRepaint(renderer)};return renderer.on("resize",repaint),renderer.on("focus",repaint),()=>{renderer.off("resize",repaint),renderer.off("focus",repaint)}}var import_react9=__toESM(require_react_production(),1);var PANE_ORDER=["sidebar","workspace","files","terminal"],FocusContext=import_react9.createContext(null);function FocusProvider(props){let[focused,setFocusedState]=import_react9.useState(props.initial??"sidebar"),renderer=useRenderer(),focusedRef=useLatest(focused),setFocused=import_react9.useCallback((pane)=>{if(focusedRef.current===pane)return;let current=renderer?.currentFocusedRenderable;if(current&&!current.isDestroyed)try{current.blur()}catch{}setFocusedState(pane)},[renderer]),cycle=import_react9.useCallback((delta)=>{let next=(PANE_ORDER.indexOf(focusedRef.current)+delta+PANE_ORDER.length)%PANE_ORDER.length;setFocused(PANE_ORDER[next])},[setFocused]),value=import_react9.useMemo(()=>({focused,is:(pane)=>focused===pane,setFocused,cycle}),[focused,setFocused,cycle]);return $jsx(FocusContext.Provider,{value,children:props.children})}function useFocus(){let ctx=import_react9.useContext(FocusContext);if(!ctx)throw Error("useFocus: must be called inside <FocusProvider>. See src/tui-react/context/focus.tsx.");return ctx}function useOptionalFocus(){return import_react9.useContext(FocusContext)}var import_react10=__toESM(require_react_production(),1);var FILES_OPEN_KEY="files.open";var WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,FILES_OPEN_KEY]);function createKvCore(){let store2=createStateCell(loadStateFile(),"kv.snapshot"),dirtyKeys=new Set,pendingUpdates=new Map,quiet=new Map,seeded=new Map,writeTimer=null,errorListeners=new Set,reportedKeys=new Set;function reportWriteError(err,unwritten=new Set([...dirtyKeys,...pendingUpdates.keys()])){let fresh=[...unwritten].filter((key)=>!reportedKeys.has(key));if(fresh.length===0)return;for(let key of fresh)reportedKeys.add(key);let failure={keys:fresh,file:kvStatePath(),error:err};for(let listener2 of errorListeners)listener2(failure)}function writeNow(label){if(dirtyKeys.size===0&&pendingUpdates.size===0)return!0;try{let patch={},snap=store2.get();for(let key of dirtyKeys)patch[key]=quiet.has(key)?quiet.get(key):snap[key];let updated={};updateStateFile((state)=>{for(let[key,value]of Object.entries(patch))if(value===void 0)delete state[key];else state[key]=value;for(let[key,mutations]of pendingUpdates){let value=state[key];for(let mutate of mutations)value=mutate(value);if(updated[key]=value,value===void 0)delete state[key];else state[key]=value}return},"strict"),pendingUpdates.clear();let loud=Object.entries(updated).filter(([key,value])=>{if(!quiet.has(key))return!0;return quiet.set(key,value),!1});if(loud.length>0)store2.update((snapshot)=>{let next={...snapshot};for(let[key,value]of loud)if(value===void 0)delete next[key];else next[key]=value;return next});return dirtyKeys.clear(),reportedKeys.clear(),!0}catch(err){return console.error(`[rove] kv ${label} failed:`,err),reportWriteError(err),!1}}function cancelTimer(){if(writeTimer)clearTimeout(writeTimer),writeTimer=null}function scheduleWrite(){cancelTimer(),writeTimer=setTimeout(()=>{writeTimer=null,writeNow("write")},WRITE_DEBOUNCE_MS)}function merge(fresh,keepQuiet){let before=store2.get(),next={...fresh};for(let[key,value]of seeded)if(next[key]===void 0)next[key]=value;for(let key of new Set([...dirtyKeys,...pendingUpdates.keys()]))if(before[key]===void 0)delete next[key];else next[key]=before[key];let quietChanged=!1;for(let key of[...quiet.keys()]){if(dirtyKeys.has(key)||pendingUpdates.has(key))continue;if(!keepQuiet||JSON.stringify(quiet.get(key))!==JSON.stringify(fresh[key])){quietChanged=!0,quiet.delete(key);continue}if(before[key]===void 0)delete next[key];else next[key]=before[key]}if(dirtyKeys.size>0||pendingUpdates.size>0)scheduleWrite();let changed=0;for(let key of new Set([...Object.keys(before),...Object.keys(next)]))if(JSON.stringify(before[key])!==JSON.stringify(next[key]))changed++;if(changed>0||quietChanged)store2.set(next);return changed}return{snapshot:store2.get,subscribe:store2.subscribe,get(key,defaultValue){return(quiet.has(key)?quiet.get(key):store2.get()[key])??defaultValue},set(key,value){if(key.startsWith(TERMINAL_TABS_PREFIX)){logClientError("kv",Error(`refused a local write of ${key}: tabs go through the daemon`));return}pendingUpdates.delete(key),quiet.delete(key),store2.update((s)=>{if(value!==void 0)return{...s,[key]:value};if(!(key in s))return s;let next={...s};return delete next[key],next}),dirtyKeys.add(key),scheduleWrite()},setQuiet(key,value){pendingUpdates.delete(key),quiet.set(key,value),dirtyKeys.add(key),scheduleWrite()},update(key,mutate,opts){let next=mutate(quiet.has(key)?quiet.get(key):store2.get()[key]),pending=pendingUpdates.get(key)??[];if(pendingUpdates.set(key,[...pending,mutate]),dirtyKeys.delete(key),opts?.quiet)return quiet.set(key,next),scheduleWrite(),!1;quiet.delete(key),store2.update((s)=>{let copy={...s};if(next===void 0)delete copy[key];else copy[key]=next;return copy});let written=writeNow("update");if(!written)scheduleWrite();return written},seed(key,value){if(!seeded.has(key))seeded.set(key,value);if(quiet.has(key)||store2.get()[key]!==void 0)return;store2.update((s)=>({...s,[key]:value}))},flush(){return cancelTimer(),writeNow("flush")},clear(){try{replaceStateFile({})}catch(err){return console.error("[rove] kv clear write failed:",err),!1}return cancelTimer(),dirtyKeys.clear(),pendingUpdates.clear(),reportedKeys.clear(),quiet.clear(),store2.set({}),!0},reload(){try{return readStateFileStrict(),cancelTimer(),writeNow("reload flush"),{ok:!0,changed:merge(readStateFileStrict(),!1)}}catch(error){return{ok:!1,error}}},follow(shared){let next={...shared};for(let key of PER_WINDOW_KEYS)delete next[key];for(let[key,value]of Object.entries(store2.get()))if(isUnpublishedStateKey(key)||PER_WINDOW_KEYS.has(key))next[key]=value;merge(next,!0)},onWriteError(listener2){return errorListeners.add(listener2),()=>{errorListeners.delete(listener2)}}}}var Ctx=import_react10.createContext(null);function KVProvider(props){let[core]=import_react10.useState(createKvCore),snapshot=import_react10.useSyncExternalStore(core.subscribe,core.snapshot,core.snapshot);import_react10.useEffect(()=>{let flush=()=>{core.flush()};return process.on("exit",flush),()=>{process.off("exit",flush)}},[core]);let value=import_react10.useMemo(()=>({ready:!0,store:snapshot,signal(name,defaultValue){return core.seed(name,defaultValue),[()=>core.get(name)??defaultValue,(next)=>core.set(name,next)]},get:core.get,set:core.set,setQuiet:core.setQuiet,update:core.update,flush:core.flush,clear:core.clear,reload:core.reload,follow:core.follow,onWriteError:core.onWriteError}),[core,snapshot]);return $jsx(Ctx.Provider,{value,children:props.children})}function useKV(){let value=import_react10.useContext(Ctx);if(!value)throw Error("KV context must be used within a context provider");return value}function useOptionalKV(){return import_react10.useContext(Ctx)??null}var import_react13=__toESM(require_react_production(),1);var import_react12=__toESM(require_react_production(),1);import{existsSync,mkdirSync}from"fs";import{tmpdir}from"os";import{basename,delimiter,extname,isAbsolute,join as join2,resolve}from"path";var pulse_default="../pulse-ynhb2ave.wav";function scaleWavVolume(wav,volume){let gain=Math.min(1,Math.max(0,volume));if(wav.length<12)return null;if(wav.readUInt32BE(0)!==1380533830||wav.readUInt32BE(8)!==1463899717)return null;let bitsPerSample,format,data;for(let offset=12;offset+8<=wav.length;){let id=wav.readUInt32BE(offset),size=wav.readUInt32LE(offset+4),start=offset+8,end=start+size;if(size<0||end>wav.length)return null;if(id===1718449184){if(size<16)return null;format=wav.readUInt16LE(start),bitsPerSample=wav.readUInt16LE(start+14)}else if(id===1684108385)data={start,end};offset=end+size%2}if(format!==1||bitsPerSample!==16||!data)return null;if((data.end-data.start)%2!==0)return null;let out=Buffer.from(wav);if(gain===1)return out;for(let i=data.start;i<data.end;i+=2){let scaled=Math.round(out.readInt16LE(i)*gain);out.writeInt16LE(Math.min(32767,Math.max(-32768,scaled)),i)}return out}var pulseAsset=isAbsolute(pulse_default)?pulse_default:resolve(import.meta.dir,pulse_default),DIR=join2(tmpdir(),"rove-sfx"),PLAYERS=["ffplay","mpv","mpg123","mpg321","mplayer","afplay","play","omxplayer","aplay","cmdmp3","cvlc","powershell.exe"];function args(player,file){if(player==="ffplay")return[player,"-autoexit","-nodisp",file];if(player==="mpv")return[player,"--no-video","--audio-display=no",file];if(player==="mplayer")return[player,"-vo","null",file];if(player==="cvlc")return[player,"--play-and-exit",file];if(player==="powershell.exe")return[player,"-c",`(New-Object Media.SoundPlayer '${file.replace(/'/g,"''")}').PlaySync()`];return[player,file]}var cachedPlayer,cachedPaths=new Map;function pathDirs(rawPath,delim=delimiter){return rawPath.split(delim).filter(Boolean)}function pickPlayer(){if(cachedPlayer!==void 0)return cachedPlayer;let segments=pathDirs(process.env.PATH??"");return cachedPlayer=PLAYERS.find((p)=>segments.some((dir)=>existsSync(join2(dir,p))))??null,cachedPlayer}function assetNameFor(assetPath,volume){let name=basename(assetPath),ext=extname(name);return`${name.slice(0,name.length-ext.length)}@${Math.round(volume*100)}${ext}`}async function ensureAsset(volume){let cached2=cachedPaths.get(volume);if(cached2)return cached2;let pending=(async()=>{mkdirSync(DIR,{recursive:!0});let dest=join2(DIR,assetNameFor(pulseAsset,volume)),out=Bun.file(dest);if(await out.exists())return dest;let source=Buffer.from(await Bun.file(pulseAsset).arrayBuffer());return await Bun.write(out,scaleWavVolume(source,volume)??source),dest})();return cachedPaths.set(volume,pending),pending}function pulse(volume=persistedSoundVolume()){if(!(volume>0))return;let player=pickPlayer();if(!player)return;ensureAsset(volume).then((path)=>{try{Bun.spawn(args(player,path),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref?.()}catch{}}).catch(()=>{return})}var ctx=import_react12.createContext(null);function NotificationsProvider(props){let[toasts,setToasts]=import_react12.useState([]),[unread,setUnread]=import_react12.useState(new Map),kv=useOptionalKV(),renderer=useRenderer(),snapshot=import_react12.useMemo(()=>loadStateFile(),[]),prefs=import_react12.useMemo(()=>({"notifications.sound.enabled":kv?.get("notifications.sound.enabled")??snapshot["notifications.sound.enabled"],"notifications.toast.enabled":kv?.get("notifications.toast.enabled")??snapshot["notifications.toast.enabled"],[FINISHED_ALERTS_KEY]:kv?.get(FINISHED_ALERTS_KEY)??snapshot[FINISHED_ALERTS_KEY],mutedTasks:mutedTaskIds(kv?kv.get(MUTED_TASKS_KEY):snapshot[MUTED_TASKS_KEY])}),[kv,snapshot]),counter=import_react12.useRef(0),timers=import_react12.useRef(new Set);import_react12.useEffect(()=>()=>{for(let id of timers.current)clearTimeout(id);timers.current.clear()},[]);let dismiss=import_react12.useCallback((id)=>{setToasts((prev)=>prev.filter((t2)=>t2.id!==id))},[]),notify=import_react12.useCallback((input)=>{setUnread((prev)=>addUnread(prev,input));let muted=input.taskId!==""&&prefs.mutedTasks.has(input.taskId);if(!shouldAlert(input,prefs[FINISHED_ALERTS_KEY]!==!1,muted))return;let soundEnabled=prefs["notifications.sound.enabled"]!==!1;if(shouldPlaySound(input,soundEnabled,muted))writeThroughRenderer(renderer,`\x07${osc9(`Rove \u2014 ${input.title}`)}`),pulse();let toastEnabled=prefs["notifications.toast.enabled"]!==!1;if(shouldShowToast(input.kind,toastEnabled)){let id=++counter.current;setToasts((prev)=>[...prev.filter((t2)=>input.key===void 0||t2.key!==input.key),{id,...input}]);let timer=setTimeout(()=>{timers.current.delete(timer),dismiss(id)},TOAST_DURATION_MS);timers.current.add(timer)}},[prefs,dismiss,renderer]),markRead=import_react12.useCallback((taskId,tabId)=>{setUnread((prev)=>removeUnread(prev,taskId,tabId))},[]),value=import_react12.useMemo(()=>({toasts,unread,notify,dismiss,markRead}),[toasts,unread,notify,dismiss,markRead]);return $jsx(ctx.Provider,{value,children:props.children})}function useNotifications(){let value=import_react12.useContext(ctx);if(!value)throw Error("useNotifications must be used within a NotificationsProvider");return value}function useOptionalNotifications(){return import_react12.useContext(ctx)}function KvWriteErrorToasts(){let kv=useOptionalKV(),notifications=useOptionalNotifications();return import_react13.useEffect(()=>{if(!kv||!notifications)return;return kv.onWriteError((failure)=>{notifications.notify({taskId:"",tabId:"",kind:"error",title:t("settings.stateWrite.failedTitle"),body:t("settings.stateWrite.failedBody",{file:tildify(failure.file),keys:failure.keys.join(", ")})})})},[kv,notifications]),null}var import_react17=__toESM(require_react_production(),1);var breakpoint=DEFAULT_NARROW_BELOW;function setNarrowBreakpoint(value){breakpoint=normalizeNarrowBelow(value)}function isNarrowWidth(cols){return cols<breakpoint}function narrowSurface(args2){if(args2.focusedPane==="sidebar")return"sidebar";return args2.hasSelection||args2.hasOpenPage?"content":"sidebar"}var import_react15=__toESM(require_react_production(),1);var stores=new WeakMap;function terminalSizeStore(source){let existing=stores.get(source);if(existing)return existing;let listeners=new Set,size={width:source.width,height:source.height},notify=()=>{for(let listener2 of listeners)listener2()},store2={subscribe(listener2){if(listeners.add(listener2),listeners.size===1)source.on("resize",notify);return()=>{if(listeners.delete(listener2),listeners.size===0)source.off("resize",notify)}},snapshot(){if(size.width!==source.width||size.height!==source.height)size={width:source.width,height:source.height};return size}};return stores.set(source,store2),store2}function useTerminalSize(){let store2=terminalSizeStore(useRenderer());return import_react15.useSyncExternalStore(store2.subscribe,store2.snapshot)}function useDialogPaddingX(){let dims=useTerminalSize();return isNarrowWidth(dims.width)?1:2}var DIALOG_CONTENT_OPACITY=0.5,TRANSPARENT_DIALOG_CONTENT_OPACITY=0.75;function Dialog(props){let dimensions=useTerminalSize(),{theme}=useTheme(),renderer=useRenderer(),dismissRef=import_react17.useRef(!1),width=props.size==="xlarge"?140:props.size==="large"?110:props.size==="small"?50:80,VERTICAL_MARGIN=2,upperFifth=props.placement==="upper-fifth"&&!isNarrowWidth(dimensions.width),headerTop=Math.max(2,Math.floor(dimensions.height/5)),cardTop=upperFifth?Math.max(2,headerTop-1):0,maxCardHeight=Math.max(8,upperFifth?dimensions.height-cardTop-2:dimensions.height-4);return $jsx("box",{onMouseDown:()=>{dismissRef.current=!!renderer?.getSelection()},onMouseUp:()=>{if(dismissRef.current){dismissRef.current=!1;return}props.onClose?.()},width:dimensions.width,height:dimensions.height,alignItems:"center",justifyContent:upperFifth?"flex-start":"center",paddingTop:cardTop,position:"absolute",zIndex:3000,left:0,top:0,shouldFill:!1,children:$jsx("box",{onMouseUp:(e)=>{dismissRef.current=!1,e.stopPropagation()},width,maxWidth:dimensions.width-2,maxHeight:maxCardHeight,flexShrink:1,flexGrow:0,backgroundColor:theme.backgroundDialog,paddingTop:1,children:props.children})})}var entrySeq=0,ctx2=import_react17.createContext(null);function DialogProvider(props){let[stack2,setStack]=import_react17.useState([]),[size,setSize]=import_react17.useState("medium"),[placement,setPlacement]=import_react17.useState("center"),renderer=useRenderer(),{transparentBackground:transparentBackground2}=useTheme(),focusRef=import_react17.useRef(null),refocusTimer=import_react17.useRef(null);import_react17.useEffect(()=>()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current)},[]);let refocus=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);refocusTimer.current=setTimeout(()=>{let focus=focusRef.current;if(!focus||focus.isDestroyed)return;function find(item){for(let child of item.getChildren()){if(child===focus)return!0;if(find(child))return!0}return!1}let root=renderer?.root;if(!root)return;if(!find(root))return;focus.focus()},1)},[renderer]),stackRef=useLatest(stack2),captureFocusIfFirst=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);if(stackRef.current.length===0)focusRef.current=renderer?.currentFocusedRenderable??null,focusRef.current?.blur()},[renderer]),dismissTop=import_react17.useCallback(()=>{let selection=renderer?.getSelection();if(selection){if(renderer?.clearSelection(),selection.getSelectedText())return}stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),refocus()},[renderer,refocus]),value=import_react17.useMemo(()=>({clear(options){for(let item of stackRef.current)item.onClose?.();if(setSize("medium"),setPlacement("center"),setStack([]),options?.refocus===!1)focusRef.current=null;else refocus()},replace(thunk,onClose){captureFocusIfFirst();for(let item of stackRef.current)item.onClose?.();setSize("medium"),setPlacement("center"),setStack([{key:++entrySeq,element:thunk,onClose}])},push(thunk,onClose){captureFocusIfFirst(),setStack((s)=>[...s,{key:++entrySeq,element:thunk,onClose}])},pop(){if(stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),stackRef.current.length<=1)refocus()},get stack(){return stackRef.current},get size(){return size},setSize,get placement(){return placement},setPlacement}),[stack2,size,placement,refocus,captureFocusIfFirst]),top=stack2.at(-1),contentOpacity=top?transparentBackground2?TRANSPARENT_DIALOG_CONTENT_OPACITY:DIALOG_CONTENT_OPACITY:1;return $jsxs(ctx2.Provider,{value,children:[$jsx("box",{flexGrow:1,backgroundColor:top&&!transparentBackground2?"black":"transparent",children:$jsx("box",{flexGrow:1,opacity:contentOpacity,children:props.children})}),$jsx("box",{position:"absolute",zIndex:3000,children:top?$jsxs(ModalScopeContext,{value:MODAL_SCOPE,children:[$jsx(ModalBarrier,{dismissTop}),$jsx(Dialog,{onClose:()=>value.clear(),size,placement,children:top.element()},top.key)]}):null})]})}var MODAL_SCOPE=Symbol("rove.dialog.modal");function ModalBarrier(props){return useBindings(()=>({modal:!0,bindings:[{key:"escape",cmd:props.dismissTop},{key:"ctrl+c",cmd:props.dismissTop}]}),{modalOwner:MODAL_SCOPE}),null}function useDialog(){let value=import_react17.useContext(ctx2);if(!value)throw Error("useDialog must be used within a DialogProvider");return value}function useOptionalDialog(){return import_react17.useContext(ctx2)}function showDialog(dialog,body,opts){return new Promise((resolve2)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve2(value),dialog.clear()};if(dialog.replace(()=>body(finish),()=>{if(settled)return;settled=!0,resolve2(void 0)}),opts?.size)dialog.setSize(opts.size)})}function NarrowLayoutSync(){let kv=useOptionalKV();if(kv)setNarrowBreakpoint(kv.get(NARROW_BELOW_KEY));return null}var import_react18=__toESM(require_react_production(),1);function PaneCrashFallback(props){let{theme}=useTheme(),t2=useT(),sizing=props.width===void 0?{flexGrow:1}:{width:props.width,flexShrink:0};return $jsxs("box",{...sizing,flexDirection:"column",backgroundColor:theme.background,paddingLeft:1,paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:props.region?t2("common.paneCrash.regionTitle",{region:t2(`common.paneCrash.region.${props.region}`)}):t2("common.paneCrash.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t2(props.region?"common.paneCrash.regionHint":"common.paneCrash.hint")}),$jsx("text",{fg:theme.focusAccent,onMouseUp:props.onRetry,children:t2("common.paneCrash.retry")})]})}function formatPaneCrashDiagnostic(region,error,info){let base=error instanceof Error?error.stack??error.message:String(error),componentStack=info.componentStack?.trim()||"(unavailable)",stateChanges=recentStateChangesForDiagnostics();return`region: ${region??"root"}
|
|
2
|
+
import{FINISHED_ALERTS_KEY,MUTED_TASKS_KEY,RoveKeymap,SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,TOAST_DURATION_MS,addUnread,armPrefixNow,bindingReachability,bumpKeymapVersion,configurePrefix,currentPrefixConfiguration,dispatchKeyEvent,findBinding,inputPassthroughReachable,insertRegistration,invokeArmedPrefixAction,isCtrlModifierKeyName,isKittyModifierKeyName,mutedTaskIds,osc9,persistedSoundVolume,prefixHudHideDirect,prefixHudShowDirect,readKeybindingsFile,removeUnread,resetKeybindingsFileCache,resetKeymapToDefaults,resetPrefixConfiguration,resetPrefixState,resolveUserKeybindings,shouldAlert,shouldPlaySound,shouldShowToast,writeKeybindingEdits}from"./chunk-b8hd91nv.js";import{$Fragment,$jsx,$jsxs,createRoot2,flushSync2,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{RemoteOrchestrator}from"./chunk-n15p38e5.js";import{updaterShell,updaterShellFailureHint}from"./chunk-1et3gskx.js";import{CURRENT_VERSION}from"./chunk-s2eezz0a.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,applyDisplayOverlay,readPersistedUiPrefs,resolveTheme,resolveThemeMode}from"./chunk-4whghfgg.js";import{loadUserThemes}from"./chunk-gzn14mwk.js";import{TERMINAL_TABS_PREFIX}from"./chunk-xjrkvksc.js";import{connectIfRunning}from"./chunk-k7tdg6kb.js";import{tildify}from"./chunk-1feav1w3.js";import{loadStateFile,readStateFileStrict,replaceStateFile,updateStateFile}from"./chunk-xasg8z9e.js";import{isLocaleId,localeState,setLocaleLang,t}from"./chunk-8xdhw922.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-cmp64q4j.js";import{installClientCrashHandlers,logClient,logClientError,setClientLogContext}from"./chunk-y8hjgmn0.js";import{kvStatePath}from"./chunk-8143k3t6.js";import{__toESM}from"./chunk-91sykzqq.js";import{RGBA}from"@opentui/core";var import_react3=__toESM(require_react_production(),1);var import_react=__toESM(require_react_production(),1);function useAccessor(state){return import_react.useSyncExternalStore(state.subscribe,state.get,state.get)}var store=createStateCell({themes:{...BUNDLED_THEMES},active:DEFAULT_THEME,mode:DEFAULT_THEME_MODE,transparentBackground:!0,focusAccent:"primary"});function listThemes(){return Object.keys(store.get().themes)}function hasTheme(name){return Boolean(store.get().themes[name])}function addTheme(name,theme){if(!name)return!1;if(!theme||typeof theme!=="object"||!theme.theme)return!1;return store.update((s)=>({...s,themes:{...s.themes,[name]:theme}})),!0}function selectedTheme(){return store.get().active}function setTheme(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0}function transparentBackground(){return store.get().transparentBackground}function setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))}function focusAccent(){return store.get().focusAccent}function setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))}function themeMode(){return store.get().mode}function setThemeMode(mode){store.update((s)=>({...s,mode}))}var ThemeContext=import_react3.createContext(null),HOST_PALETTE_QUERY_TIMEOUT_MS=2000;function resolveActive(state,mode){let active=state.themes[state.active];if(active)return resolveTheme(active,mode);let fallback=state.themes[DEFAULT_THEME]??Object.values(state.themes)[0];if(!fallback)return resolveTheme({theme:{background:"#000000",text:"#ffffff"}},mode);return resolveTheme(fallback,mode)}function useHostThemeMode(renderer){let[mode,setMode]=import_react3.useState(()=>renderer?.themeMode??null);return import_react3.useEffect(()=>{if(!renderer)return;let onChange=(next)=>setMode(next);return renderer.on("theme_mode",onChange),setMode(renderer.themeMode),()=>{renderer.off("theme_mode",onChange)}},[renderer]),mode}function ThemeProvider(props){import_react3.useMemo(()=>{store.update((s)=>({...s,mode:props.mode??s.mode,active:props.theme&&s.themes[props.theme]?props.theme:s.active}))},[]);let state=useAccessor(store),renderer=useRenderer(),hostMode=useHostThemeMode(renderer),mode=resolveThemeMode(state.mode,hostMode),[hostBackground,setHostBackground]=import_react3.useState(null);import_react3.useEffect(()=>{if(!state.transparentBackground)return;if(renderer?.screenMode==="split-footer")return;if(!renderer)return;let cancelled=!1;return renderer.getPalette({timeout:HOST_PALETTE_QUERY_TIMEOUT_MS}).then((colors)=>{if(cancelled||!colors.defaultBackground)return;setHostBackground(RGBA.fromHex(colors.defaultBackground))}).catch(()=>{}),()=>{cancelled=!0}},[renderer,state.transparentBackground]);let theme=import_react3.useMemo(()=>applyDisplayOverlay(resolveActive(state,mode),state.focusAccent,state.transparentBackground,hostBackground??void 0),[state,mode,hostBackground]);import_react3.useEffect(()=>{if(renderer?.screenMode==="split-footer")return;renderer?.setBackgroundColor(theme.background??RGBA.fromInts(0,0,0))},[renderer,theme]);let value=import_react3.useMemo(()=>({theme,selected:state.active,transparentBackground:state.transparentBackground,focusAccent:state.focusAccent,modePreference:state.mode,mode:()=>mode,set(name){if(!hasTheme(name))return!1;return store.update((s)=>({...s,active:name})),!0},setMode(next){store.update((s)=>({...s,mode:next}))},setTransparentBackground(v){store.update((s)=>({...s,transparentBackground:v}))},setFocusAccent(v){store.update((s)=>({...s,focusAccent:v}))},preview:(options)=>applyDisplayOverlay(resolveActive({...state,active:options.themeName},resolveThemeMode(options.themeMode,hostMode)),options.focusAccent,options.transparentBackground,hostBackground??void 0),all:listThemes,has:hasTheme}),[theme,state,mode,hostMode,hostBackground]);return $jsx(ThemeContext.Provider,{value,children:props.children})}function useTheme(){let value=import_react3.useContext(ThemeContext);if(!value)throw Error("Theme context must be used within a context provider");return value}var import_react4=__toESM(require_react_production(),1);function useLang(){return useAccessor(localeState())}function useT(){let lang=useLang();return import_react4.useCallback((key,params)=>t(key,params),[lang])}var import_react7=__toESM(require_react_production(),1);var CTRL_HOLD_THRESHOLD_MS=400;function createCtrlHoldDetector(callbacks){let state={kind:"idle"},held=new Set,reset=()=>{if(state.kind==="pending")clearTimeout(state.timer);if(state.kind==="visible")callbacks.onHide();state={kind:"idle"}},cancel=()=>{reset(),held.clear()};return{keypress:(event)=>{if(!isCtrlModifierKeyName(event.name)){cancel();return}if(event.eventType==="repeat"&&held.has(event.name))return;if(event.eventType!=="press")return;if(held.add(event.name),state.kind!=="idle")return;state={kind:"pending",timer:setTimeout(()=>{state={kind:"visible"},callbacks.onReveal()},CTRL_HOLD_THRESHOLD_MS)}},keyrelease:(event)=>{if(!isCtrlModifierKeyName(event.name)||event.eventType!=="release")return;if(held.delete(event.name),held.size===0)reset()},cancel}}function availableActions(stack){let seen=new Set,actions=[],passthrough=inputPassthroughReachable(stack);for(let registration of[...stack].reverse()){let config=registration.config();if(config.enabled===!1)continue;for(let binding of config.bindings){if(binding.prefix&¤tPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}var MODIFIER_GLYPH={ctrl:"\u2303",control:"\u2303",alt:"\u2325",opt:"\u2325",option:"\u2325",shift:"\u21E7",cmd:"\u2318",command:"\u2318",meta:"\u2318",super:"\u2318"},KEY_GLYPH={enter:"\u23CE",return:"\u23CE",esc:"\u238B",escape:"\u238B",space:"\u2423",up:"\u2191",down:"\u2193",left:"\u2190",right:"\u2192",backspace:"\u232B",delete:"\u2326",del:"\u2326",pgup:"\u21DE",pageup:"\u21DE",pgdn:"\u21DF",pagedown:"\u21DF",home:"\u2196",end:"\u2198"};function formatKey(k,upper){if(k.includes("/"))return k.split("/").map((part)=>formatKey(part,upper)).join("/");let low=k.toLowerCase();if(low==="tab")return"tab";let named=KEY_GLYPH[low];if(named)return named;if(/^f\d{1,2}$/.test(low))return low.toUpperCase();if(!upper)return k;if(/^[a-z]$/.test(low))return k.toUpperCase();return k.replace(/[a-z]+/gi,(run)=>run.toUpperCase())}function formatChord(chord,prefixGlyph="\u2303A"){let s=chord.trim();if(!s)return s;let pm=/^prefix\s+(.+)$/i.exec(s);if(pm){let suffix=pm[1]??"";return`${prefixGlyph} ${suffix.includes("+")?formatChord(suffix,prefixGlyph):formatKey(suffix,!0)}`}let parts=s.split("+");if(parts.length===1)return formatKey(parts[0]??"",!1);let key=parts[parts.length-1]??"";return`${parts.slice(0,-1).map((p)=>MODIFIER_GLYPH[p.toLowerCase().trim()]??p).join("")} ${formatKey(key,!0)}`}var DIRECT_GUIDE_PREFIX_ACTION_ID="prefix.moreCommands",CTRL_FOLLOW_UP_CHORD=/^ctrl\+[^+]+$/;function ctrlFollowUpKey(chord){return CTRL_FOLLOW_UP_CHORD.test(chord)?chord.slice(5):null}function shortcutCaption(input){let binding=findBinding(input.bindingId);if(!binding)return null;if(input.reachability.direct.has(input.bindingId)){let direct=binding.keys[0];if(direct)return formatChord(direct)}if(input.prefixKey&&input.reachability.prefix.has(input.bindingId)){let stroke=binding.prefixKeys?.[0];if(stroke)return`${formatChord(input.prefixKey)} ${formatChord(stroke)}`}return null}function directGuideOptions(reachability,prefixKey){let options=RoveKeymap.filter((binding)=>reachability.direct.has(binding.id)).flatMap((binding)=>{let strokes=binding.keys.flatMap((chord)=>ctrlFollowUpKey(chord)??[]);if(strokes.length>2)return[{stroke:`${strokes[0]}-${strokes.at(-1)}`,action:binding.id}];return strokes.map((stroke)=>({stroke,action:binding.id}))}),prefixStroke=prefixKey?ctrlFollowUpKey(prefixKey):null;if(prefixStroke&&reachability.prefix.size>0)options.push({stroke:prefixStroke,action:DIRECT_GUIDE_PREFIX_ACTION_ID});return options}var import_react5=__toESM(require_react_production(),1);function useLatest(value){let ref=import_react5.useRef(value);return ref.current=value,ref}var ModalScopeContext=import_react7.createContext(null),nextId=1,stack=[],installedRenderer=null,installed=null,listener=null,releaseListener=null,ctrlHoldDetector=null,supersededRenderers=new WeakSet;function ensureInstalled(renderer){if(!renderer)throw Error("useBindings: no renderer in scope; call inside a component rendered by @opentui/react.");if(installedRenderer===renderer)return;if(supersededRenderers.has(renderer))return;if(installed&&listener)installed.off("keypress",listener);if(installed&&releaseListener)installed.off("keyrelease",releaseListener);if(ctrlHoldDetector?.cancel(),installedRenderer)supersededRenderers.add(installedRenderer);stack.length=0,resetPrefixState(),installedRenderer=renderer,installed=renderer.keyInput,ctrlHoldDetector=createCtrlHoldDetector({onReveal:()=>{resetPrefixState();let options=directGuideOptions(bindingReachability(stack),currentPrefixConfiguration().key);if(options.length>0)prefixHudShowDirect(options)},onHide:prefixHudHideDirect}),listener=(evt)=>{if(profileTick("key"),keyCapture){evt.preventDefault();let capture=keyCapture;if(!isKittyModifierKeyName(evt.name))flushSync2(()=>capture(evt));return}ctrlHoldDetector?.keypress(evt),dispatchKeyEvent(stack,evt,Date.now(),{flushSync:flushSync2})},releaseListener=(evt)=>ctrlHoldDetector?.keyrelease(evt),installed.on("keypress",listener),installed.on("keyrelease",releaseListener)}var keyCapture=null;function captureKeys(handler){return keyCapture=handler,()=>{if(keyCapture===handler)keyCapture=null}}function modalActive(){return stack.some((r)=>r.modalOwner!==void 0)}function currentBindingReachability(){return bindingReachability(stack)}function armPrefixFromCurrentStack(){return armPrefixNow(stack)}function invokeArmedPrefixActionFromCurrentStack(actionId,stroke){return invokeArmedPrefixAction(stack,actionId,stroke)}var stackVersion=0,stackListeners=new Set;function bumpStackVersion(){prefixHudHideDirect(),stackVersion++;for(let listener2 of stackListeners)listener2()}var bindingTableSignatures=new WeakMap;function bindingReachabilitySignature(config){let bindings=bindingTableSignatures.get(config.bindings);if(bindings===void 0)bindings=config.bindings.map((binding)=>[binding.id??"",binding.key,binding.prefix===!0?"p":"d",binding.passthrough===!0?"i":"u"].join(":")).join("|"),bindingTableSignatures.set(config.bindings,bindings);return`${config.enabled===!1?"off":"on"};${config.modal===!0?"modal":"plain"};${bindings}`}function subscribeBindingStack(listener2){return stackListeners.add(listener2),()=>{stackListeners.delete(listener2)}}function useBindingStackVersion(){return import_react7.useSyncExternalStore((onChange)=>{return stackListeners.add(onChange),()=>stackListeners.delete(onChange)},()=>stackVersion)}function useBindings(config,opts){let renderer=useRenderer();ensureInstalled(renderer);let configRef=useLatest(config),scope=import_react7.useContext(ModalScopeContext),reachabilitySignature=bindingReachabilitySignature(config()),previousReachabilitySignature=import_react7.useRef(reachabilitySignature);import_react7.useEffect(()=>{if(previousReachabilitySignature.current===reachabilitySignature)return;previousReachabilitySignature.current=reachabilitySignature,bumpStackVersion()},[reachabilitySignature]),import_react7.useEffect(()=>{if(supersededRenderers.has(renderer))return;if(opts?.modalOwner!==void 0)resetPrefixState();let reg={config:()=>configRef.current(),id:nextId++,modalOwner:opts?.modalOwner,modalMember:opts?.modalOwner===void 0?scope??void 0:void 0};return insertRegistration(stack,reg),bumpStackVersion(),()=>{let i=stack.findIndex((r)=>r.id===reg.id);if(i>=0)stack.splice(i,1);bumpStackVersion()}},[])}function pageCloseBindings(cmd){return[{key:"escape",cmd},{key:"q",cmd},{key:"ctrl+c",cmd}]}function currentPaletteActions(){return capturePaletteActions(stack)}import{createCliRenderer,setRenderLibPath}from"@opentui/core";var import_react21=__toESM(require_react_production(),1);async function connectPaneOrchestrator(options={}){let tag=options.logTag??"orch-connect",connect=options.connect??connectIfRunning,remote=null;try{let client=await connect();if(!client)return logClient(tag,"no daemon running \u2014 caller degrades"),null;return remote=new RemoteOrchestrator(client,{...options.orchestratorOptions,channels:options.channels}),await remote.init(),remote}catch(err){return logClientError(tag,err),remote?.dispose(),null}}var NARROW_BELOW_KEY="layout.narrowBelow",DEFAULT_NARROW_BELOW=70;function normalizeNarrowBelow(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"&&value.trim()!==""?Number(value.trim()):Number.NaN;if(!Number.isFinite(n))return 70;return Math.min(1000,Math.max(0,Math.floor(n)))}var cached=null;function applyUserKeybindings(){if(cached)return cached;let{report,prefix}=resolveUserKeybindings(readKeybindingsFile(),RoveKeymap,process.platform);if(report.exists)configurePrefix(prefix);for(let w of report.warnings)console.warn(`[rove/keybindings] ${w}`);return cached=report,cached}function pluginKeybindings(){return userKeybindingsReport().plugins}function userKeybindingsReport(){return cached??applyUserKeybindings()}function reloadUserKeybindings(){cached=null,resetKeybindingsFileCache(),resetKeymapToDefaults(),resetPrefixConfiguration();let report=applyUserKeybindings();return bumpKeymapVersion(),report}function saveKeybindingEdits(edits){let result=writeKeybindingEdits(edits);if(result.ok)reloadUserKeybindings();return result}var UI_PREFS_FOCUS_ACCENT_SLOTS=["primary","success","info"];var UI_PREFS_THEME_MODES=["dark","light","auto"];function applyUiPrefs(target,prefs){if(typeof prefs.theme==="string"&&prefs.theme.length>0&&prefs.theme!==target.selectedTheme()){if(!target.hasTheme(prefs.theme))target.reloadUserThemes();if(target.hasTheme(prefs.theme))target.setTheme(prefs.theme)}if(prefs.themeMode===null||typeof prefs.themeMode==="string"){let mode=normalizeThemeMode(prefs.themeMode);if(mode&&mode!==target.themeMode())target.setThemeMode(mode)}if(typeof prefs.transparentBackground==="boolean"&&prefs.transparentBackground!==target.transparentBackground())target.setTransparentBackground(prefs.transparentBackground);if(prefs.focusAccent===null||typeof prefs.focusAccent==="string"){let slot=normalizeFocusAccent(prefs.focusAccent);if(slot&&slot!==target.focusAccent())target.setFocusAccent(slot)}}function normalizeFocusAccent(value){if(value===null)return"primary";return UI_PREFS_FOCUS_ACCENT_SLOTS.includes(value)?value:null}function normalizeThemeMode(value){if(value===null)return"dark";return UI_PREFS_THEME_MODES.includes(value)?value:null}var STALL_HEARTBEAT_MS=1000,STALL_THRESHOLD_MS=2000;function stallReport(gapMs,mem,heartbeatMs=STALL_HEARTBEAT_MS,thresholdMs=STALL_THRESHOLD_MS){let stallMs=gapMs-heartbeatMs;if(stallMs<thresholdMs)return null;let mb=(n)=>Math.round(n/1048576);return`event loop stalled ~${stallMs}ms \u2014 rss=${mb(mem.rss)}MB heapUsed=${mb(mem.heapUsed)}MB`}function installEventLoopStallTelemetry(){let last=Date.now(),timer=setInterval(()=>{let now=Date.now(),gap=now-last;last=now;let report=stallReport(gap,process.memoryUsage());if(report)logClient("stall",report)},STALL_HEARTBEAT_MS);return timer.unref?.(),()=>clearInterval(timer)}var KITTY_KEYBOARD={};function hostTargetFps(){return 60}function hostRenderOptions(onDestroy){let base={backgroundColor:"transparent",externalOutputMode:"passthrough",exitOnCtrlC:!1,screenMode:"alternate-screen",useKittyKeyboard:KITTY_KEYBOARD,targetFps:hostTargetFps()};return onDestroy?{...base,onDestroy}:base}function inlineRenderOptions(heightRows,onDestroy){let base={backgroundColor:"transparent",exitOnCtrlC:!1,screenMode:"split-footer",footerHeight:heightRows,useKittyKeyboard:KITTY_KEYBOARD};return onDestroy?{...base,onDestroy}:base}function installExitRestoreBackstop(renderer){process.on("exit",()=>renderer.destroy())}var BRACKETED_PASTE_ON="\x1B[?2004h",BRACKETED_PASTE_OFF="\x1B[?2004l";function installBracketedPasteMode(stdout=process.stdout){if(!stdout.isTTY)return()=>{};let write=(seq)=>{try{stdout.write(seq)}catch{}};write(BRACKETED_PASTE_ON);let restored=!1,restore=()=>{if(restored)return;restored=!0,write(BRACKETED_PASTE_OFF)};return process.on("exit",restore),restore}var exitCriticalWork=new Set;async function whenExitReady(){while(exitCriticalWork.size>0)await Promise.allSettled([...exitCriticalWork])}function installPaneExitBackstop(opts={}){let ceilingMs=opts.ceilingMs??5000,exit=opts.exit??((code)=>process.exit(code)),exitScheduled=!1,exited=!1,exitOnce=()=>{if(exited)return;exited=!0,exit(0)},scheduleExit=()=>{if(exitScheduled)return;exitScheduled=!0;let ceiling=setTimeout(()=>{console.error(`[rove] exit backstop: ${exitCriticalWork.size} task(s) still in flight after ${ceilingMs}ms \u2014 exiting anyway`),exitOnce()},ceilingMs);ceiling.unref?.(),whenExitReady().then(()=>{clearTimeout(ceiling),exitOnce()})};for(let signal of["SIGHUP","SIGTERM","SIGINT"])process.on(signal,scheduleExit)}function installOrphanExitWatchdog(intervalMs=5000){let timer=setInterval(()=>{if(process.ppid===1)process.exit(0)},intervalMs);return timer.unref?.(),()=>clearInterval(timer)}var SYNC_START=Buffer.from("\x1B[?2026h"),SYNC_END=Buffer.from("\x1B[?2026l");class ImeAnchorController{owner=null;anchor=null;claim(owner,anchor){this.owner=owner,this.anchor={x:Math.max(0,Math.trunc(anchor.x)),y:Math.max(0,Math.trunc(anchor.y))}}release(owner){if(this.owner!==owner)return!1;return this.owner=null,this.anchor=null,!0}current(){return this.anchor}}var imeAnchorController=new ImeAnchorController;class ImeAnchorFrameTransformer{controller;pending=Buffer.alloc(0);frame=Buffer.alloc(0);constructor(controller){this.controller=controller}push(chunk){let data=this.pending.length>0?Buffer.concat([this.pending,chunk]):chunk;this.pending=Buffer.alloc(0);let output=[],offset=0;while(offset<data.length){if(this.frame.length===0){let start=data.indexOf(SYNC_START,offset);if(start<0){let tail2=data.subarray(offset),pendingLength2=longestMarkerPrefixSuffix(tail2,[SYNC_START]),safeLength2=tail2.length-pendingLength2;if(safeLength2>0)output.push(tail2.subarray(0,safeLength2));if(pendingLength2>0)this.pending=Buffer.from(tail2.subarray(safeLength2));break}if(start>offset)output.push(data.subarray(offset,start));this.frame=Buffer.from(SYNC_START),offset=start+SYNC_START.length;continue}let end=data.indexOf(SYNC_END,offset),restart=data.indexOf(SYNC_START,offset);if(restart>=0&&(end<0||restart<end)){this.frame=Buffer.from(SYNC_START),offset=restart+SYNC_START.length;continue}if(end>=0){if(end>offset)this.frame=Buffer.concat([this.frame,data.subarray(offset,end)]);output.push(this.frame);let anchor=this.controller.current();if(anchor)output.push(Buffer.from(`\x1B[${anchor.y+1};${anchor.x+1}H\x1B[?25l`));output.push(SYNC_END),this.frame=Buffer.alloc(0),offset=end+SYNC_END.length;continue}let tail=data.subarray(offset),pendingLength=longestMarkerPrefixSuffix(tail,[SYNC_START,SYNC_END]),safeLength=tail.length-pendingLength;if(safeLength>0)this.frame=Buffer.concat([this.frame,tail.subarray(0,safeLength)]);if(pendingLength>0)this.pending=Buffer.from(tail.subarray(safeLength));break}return output.length>0?Buffer.concat(output):Buffer.alloc(0)}flush(){if(this.frame.length>0)return this.frame=Buffer.alloc(0),this.pending=Buffer.alloc(0),Buffer.alloc(0);let pending=this.pending;return this.pending=Buffer.alloc(0),pending}}function longestMarkerPrefixSuffix(bytes,markers){let max=Math.min(bytes.length,Math.max(...markers.map((marker)=>marker.length-1)));for(let length=max;length>0;length-=1){let suffix=bytes.subarray(bytes.length-length);if(markers.some((marker)=>length<marker.length&&suffix.equals(marker.subarray(0,length))))return length}return 0}function asBuffer(chunk,encodingOrCallback){if(typeof chunk!=="string")return Buffer.from(chunk);let encoding=typeof encodingOrCallback==="string"?encodingOrCallback:void 0;return Buffer.from(chunk,encoding)}function writeCallback(encodingOrCallback,maybeCallback){return typeof encodingOrCallback==="function"?encodingOrCallback:maybeCallback}function createImeAnchoredOutput(target,controller=imeAnchorController){let transformer=new ImeAnchorFrameTransformer(controller),exposedWrite=(chunk,encodingOrCallback,maybeCallback)=>{let transformed=transformer.push(asBuffer(chunk,encodingOrCallback)),callback=writeCallback(encodingOrCallback,maybeCallback);if(transformed.length===0){if(callback)queueMicrotask(()=>callback(null));return!0}return callback?target.write(transformed,callback):target.write(transformed)};return{stdout:new Proxy(target,{get(stream,property){if(property==="write")return exposedWrite;let value=Reflect.get(stream,property,stream);return typeof value==="function"?value.bind(stream):value},set(stream,property,value){if(property==="write")return exposedWrite=value,!0;return Reflect.set(stream,property,value,stream)}}),flush(){let pending=transformer.flush();if(pending.length>0)target.write(pending)}}}var IME_ANCHOR_PLATFORMS=new Set(["darwin","win32"]);function createHostImeOutput(opts){if(!IME_ANCHOR_PLATFORMS.has(opts.platform)||!opts.fullscreen)return{active:!1,rendererOptions:{},attach:()=>()=>{},flush:()=>{}};let output=createImeAnchoredOutput(opts.stdout,opts.controller);return{active:!0,rendererOptions:{stdout:output.stdout,remote:!1},attach:(renderer)=>installRendererResizeForwarder(renderer,opts.stdout),flush:()=>output.flush()}}function installRendererResizeForwarder(renderer,terminal,signals=process){let onResize=()=>{let{columns:width,rows:height}=terminal;if(!width||!height)return;renderer.resize(width,height)};return signals.on("SIGWINCH",onResize),()=>signals.removeListener("SIGWINCH",onResize)}import{readFileSync}from"fs";import{createRequire}from"module";import{dirname,join}from"path";var STOCK_OPENTUI_ENV="ROVE_STOCK_OPENTUI";function roveNativeLibPath(probe){if(probe.env[STOCK_OPENTUI_ENV]==="1")return null;try{let manifestPath=probe.resolve(`@sma1lboy/opentui-rove-${probe.platform}-${probe.arch}/package.json`),manifest=JSON.parse(probe.readText(manifestPath)),core=JSON.parse(probe.readText(join(dirname(probe.resolve("@opentui/core")),"package.json")));if(!manifest.lib||!manifest.opentui||manifest.opentui!==core.version)return null;return join(dirname(manifestPath),manifest.lib)}catch{return null}}function installedRoveNativeLibPath(){let require2=createRequire(import.meta.url);return roveNativeLibPath({platform:process.platform,arch:process.arch,env:process.env,resolve:(id)=>require2.resolve(id),readText:(path)=>readFileSync(path,"utf8")})}function needsScreenSelfHeal(platform){return platform==="win32"}function requestFullRepaint(renderer){if(renderer.screenMode!=="alternate-screen")return!1;let internals=renderer;return internals.forceFullRepaintRequested=!0,renderer.requestRender(),!0}function writeThroughRenderer(renderer,chunk,fallback=process.stdout){let writeOut=renderer?.writeOut;try{if(typeof writeOut==="function")writeOut.call(renderer,chunk);else fallback.write(chunk)}catch{}}function redrawScreen(renderer){if(renderer.screenMode!=="alternate-screen")return!1;return writeThroughRenderer(renderer,"\x1B[H\x1B[2J"),requestFullRepaint(renderer)}function installScreenSelfHeal(opts){let platform=opts.platform??process.platform;if(!needsScreenSelfHeal(platform))return()=>{};let{renderer}=opts,repaint=()=>{requestFullRepaint(renderer)};return renderer.on("resize",repaint),renderer.on("focus",repaint),()=>{renderer.off("resize",repaint),renderer.off("focus",repaint)}}var import_react9=__toESM(require_react_production(),1);var PANE_ORDER=["sidebar","workspace","files","terminal"],FocusContext=import_react9.createContext(null);function FocusProvider(props){let[focused,setFocusedState]=import_react9.useState(props.initial??"sidebar"),renderer=useRenderer(),focusedRef=useLatest(focused),setFocused=import_react9.useCallback((pane)=>{if(focusedRef.current===pane)return;let current=renderer?.currentFocusedRenderable;if(current&&!current.isDestroyed)try{current.blur()}catch{}setFocusedState(pane)},[renderer]),cycle=import_react9.useCallback((delta)=>{let next=(PANE_ORDER.indexOf(focusedRef.current)+delta+PANE_ORDER.length)%PANE_ORDER.length;setFocused(PANE_ORDER[next])},[setFocused]),value=import_react9.useMemo(()=>({focused,is:(pane)=>focused===pane,setFocused,cycle}),[focused,setFocused,cycle]);return $jsx(FocusContext.Provider,{value,children:props.children})}function useFocus(){let ctx=import_react9.useContext(FocusContext);if(!ctx)throw Error("useFocus: must be called inside <FocusProvider>. See src/tui-react/context/focus.tsx.");return ctx}function useOptionalFocus(){return import_react9.useContext(FocusContext)}var import_react10=__toESM(require_react_production(),1);var FILES_OPEN_KEY="files.open";var WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,FILES_OPEN_KEY]);function createKvCore(){let store2=createStateCell(loadStateFile(),"kv.snapshot"),dirtyKeys=new Set,pendingUpdates=new Map,quiet=new Map,seeded=new Map,writeTimer=null,errorListeners=new Set,reportedKeys=new Set;function reportWriteError(err,unwritten=new Set([...dirtyKeys,...pendingUpdates.keys()])){let fresh=[...unwritten].filter((key)=>!reportedKeys.has(key));if(fresh.length===0)return;for(let key of fresh)reportedKeys.add(key);let failure={keys:fresh,file:kvStatePath(),error:err};for(let listener2 of errorListeners)listener2(failure)}function writeNow(label){if(dirtyKeys.size===0&&pendingUpdates.size===0)return!0;try{let patch={},snap=store2.get();for(let key of dirtyKeys)patch[key]=quiet.has(key)?quiet.get(key):snap[key];let updated={};updateStateFile((state)=>{for(let[key,value]of Object.entries(patch))if(value===void 0)delete state[key];else state[key]=value;for(let[key,mutations]of pendingUpdates){let value=state[key];for(let mutate of mutations)value=mutate(value);if(updated[key]=value,value===void 0)delete state[key];else state[key]=value}return},"strict"),pendingUpdates.clear();let loud=Object.entries(updated).filter(([key,value])=>{if(!quiet.has(key))return!0;return quiet.set(key,value),!1});if(loud.length>0)store2.update((snapshot)=>{let next={...snapshot};for(let[key,value]of loud)if(value===void 0)delete next[key];else next[key]=value;return next});return dirtyKeys.clear(),reportedKeys.clear(),!0}catch(err){return console.error(`[rove] kv ${label} failed:`,err),reportWriteError(err),!1}}function cancelTimer(){if(writeTimer)clearTimeout(writeTimer),writeTimer=null}function scheduleWrite(){cancelTimer(),writeTimer=setTimeout(()=>{writeTimer=null,writeNow("write")},WRITE_DEBOUNCE_MS)}function merge(fresh,keepQuiet){let before=store2.get(),next={...fresh};for(let[key,value]of seeded)if(next[key]===void 0)next[key]=value;for(let key of new Set([...dirtyKeys,...pendingUpdates.keys()]))if(before[key]===void 0)delete next[key];else next[key]=before[key];let quietChanged=!1;for(let key of[...quiet.keys()]){if(dirtyKeys.has(key)||pendingUpdates.has(key))continue;if(!keepQuiet||JSON.stringify(quiet.get(key))!==JSON.stringify(fresh[key])){quietChanged=!0,quiet.delete(key);continue}if(before[key]===void 0)delete next[key];else next[key]=before[key]}if(dirtyKeys.size>0||pendingUpdates.size>0)scheduleWrite();let changed=0;for(let key of new Set([...Object.keys(before),...Object.keys(next)]))if(JSON.stringify(before[key])!==JSON.stringify(next[key]))changed++;if(changed>0||quietChanged)store2.set(next);return changed}return{snapshot:store2.get,subscribe:store2.subscribe,get(key,defaultValue){return(quiet.has(key)?quiet.get(key):store2.get()[key])??defaultValue},set(key,value){if(key.startsWith(TERMINAL_TABS_PREFIX)){logClientError("kv",Error(`refused a local write of ${key}: tabs go through the daemon`));return}pendingUpdates.delete(key),quiet.delete(key),store2.update((s)=>{if(value!==void 0)return{...s,[key]:value};if(!(key in s))return s;let next={...s};return delete next[key],next}),dirtyKeys.add(key),scheduleWrite()},setQuiet(key,value){pendingUpdates.delete(key),quiet.set(key,value),dirtyKeys.add(key),scheduleWrite()},update(key,mutate,opts){let next=mutate(quiet.has(key)?quiet.get(key):store2.get()[key]),pending=pendingUpdates.get(key)??[];if(pendingUpdates.set(key,[...pending,mutate]),dirtyKeys.delete(key),opts?.quiet)return quiet.set(key,next),scheduleWrite(),!1;quiet.delete(key),store2.update((s)=>{let copy={...s};if(next===void 0)delete copy[key];else copy[key]=next;return copy});let written=writeNow("update");if(!written)scheduleWrite();return written},seed(key,value){if(!seeded.has(key))seeded.set(key,value);if(quiet.has(key)||store2.get()[key]!==void 0)return;store2.update((s)=>({...s,[key]:value}))},flush(){return cancelTimer(),writeNow("flush")},clear(){try{replaceStateFile({})}catch(err){return console.error("[rove] kv clear write failed:",err),!1}return cancelTimer(),dirtyKeys.clear(),pendingUpdates.clear(),reportedKeys.clear(),quiet.clear(),store2.set({}),!0},reload(){try{return readStateFileStrict(),cancelTimer(),writeNow("reload flush"),{ok:!0,changed:merge(readStateFileStrict(),!1)}}catch(error){return{ok:!1,error}}},follow(shared){let next={...shared};for(let key of PER_WINDOW_KEYS)delete next[key];for(let[key,value]of Object.entries(store2.get()))if(isUnpublishedStateKey(key)||PER_WINDOW_KEYS.has(key))next[key]=value;merge(next,!0)},onWriteError(listener2){return errorListeners.add(listener2),()=>{errorListeners.delete(listener2)}}}}var Ctx=import_react10.createContext(null);function KVProvider(props){let[core]=import_react10.useState(createKvCore),snapshot=import_react10.useSyncExternalStore(core.subscribe,core.snapshot,core.snapshot);import_react10.useEffect(()=>{let flush=()=>{core.flush()};return process.on("exit",flush),()=>{process.off("exit",flush)}},[core]);let value=import_react10.useMemo(()=>({ready:!0,store:snapshot,signal(name,defaultValue){return core.seed(name,defaultValue),[()=>core.get(name)??defaultValue,(next)=>core.set(name,next)]},get:core.get,set:core.set,setQuiet:core.setQuiet,update:core.update,flush:core.flush,clear:core.clear,reload:core.reload,follow:core.follow,onWriteError:core.onWriteError}),[core,snapshot]);return $jsx(Ctx.Provider,{value,children:props.children})}function useKV(){let value=import_react10.useContext(Ctx);if(!value)throw Error("KV context must be used within a context provider");return value}function useOptionalKV(){return import_react10.useContext(Ctx)??null}var import_react13=__toESM(require_react_production(),1);var import_react12=__toESM(require_react_production(),1);import{existsSync,mkdirSync}from"fs";import{tmpdir}from"os";import{basename,delimiter,extname,isAbsolute,join as join2,resolve}from"path";var pulse_default="../pulse-ynhb2ave.wav";function scaleWavVolume(wav,volume){let gain=Math.min(1,Math.max(0,volume));if(wav.length<12)return null;if(wav.readUInt32BE(0)!==1380533830||wav.readUInt32BE(8)!==1463899717)return null;let bitsPerSample,format,data;for(let offset=12;offset+8<=wav.length;){let id=wav.readUInt32BE(offset),size=wav.readUInt32LE(offset+4),start=offset+8,end=start+size;if(size<0||end>wav.length)return null;if(id===1718449184){if(size<16)return null;format=wav.readUInt16LE(start),bitsPerSample=wav.readUInt16LE(start+14)}else if(id===1684108385)data={start,end};offset=end+size%2}if(format!==1||bitsPerSample!==16||!data)return null;if((data.end-data.start)%2!==0)return null;let out=Buffer.from(wav);if(gain===1)return out;for(let i=data.start;i<data.end;i+=2){let scaled=Math.round(out.readInt16LE(i)*gain);out.writeInt16LE(Math.min(32767,Math.max(-32768,scaled)),i)}return out}var pulseAsset=isAbsolute(pulse_default)?pulse_default:resolve(import.meta.dir,pulse_default),DIR=join2(tmpdir(),"rove-sfx"),PLAYERS=["ffplay","mpv","mpg123","mpg321","mplayer","afplay","play","omxplayer","aplay","cmdmp3","cvlc","powershell.exe"];function args(player,file){if(player==="ffplay")return[player,"-autoexit","-nodisp",file];if(player==="mpv")return[player,"--no-video","--audio-display=no",file];if(player==="mplayer")return[player,"-vo","null",file];if(player==="cvlc")return[player,"--play-and-exit",file];if(player==="powershell.exe")return[player,"-c",`(New-Object Media.SoundPlayer '${file.replace(/'/g,"''")}').PlaySync()`];return[player,file]}var cachedPlayer,cachedPaths=new Map;function pathDirs(rawPath,delim=delimiter){return rawPath.split(delim).filter(Boolean)}function pickPlayer(){if(cachedPlayer!==void 0)return cachedPlayer;let segments=pathDirs(process.env.PATH??"");return cachedPlayer=PLAYERS.find((p)=>segments.some((dir)=>existsSync(join2(dir,p))))??null,cachedPlayer}function assetNameFor(assetPath,volume){let name=basename(assetPath),ext=extname(name);return`${name.slice(0,name.length-ext.length)}@${Math.round(volume*100)}${ext}`}async function ensureAsset(volume){let cached2=cachedPaths.get(volume);if(cached2)return cached2;let pending=(async()=>{mkdirSync(DIR,{recursive:!0});let dest=join2(DIR,assetNameFor(pulseAsset,volume)),out=Bun.file(dest);if(await out.exists())return dest;let source=Buffer.from(await Bun.file(pulseAsset).arrayBuffer());return await Bun.write(out,scaleWavVolume(source,volume)??source),dest})();return cachedPaths.set(volume,pending),pending}function pulse(volume=persistedSoundVolume()){if(!(volume>0))return;let player=pickPlayer();if(!player)return;ensureAsset(volume).then((path)=>{try{Bun.spawn(args(player,path),{stdin:"ignore",stdout:"ignore",stderr:"ignore"}).unref?.()}catch{}}).catch(()=>{return})}var ctx=import_react12.createContext(null);function NotificationsProvider(props){let[toasts,setToasts]=import_react12.useState([]),[unread,setUnread]=import_react12.useState(new Map),kv=useOptionalKV(),renderer=useRenderer(),snapshot=import_react12.useMemo(()=>loadStateFile(),[]),prefs=import_react12.useMemo(()=>({"notifications.sound.enabled":kv?.get("notifications.sound.enabled")??snapshot["notifications.sound.enabled"],"notifications.toast.enabled":kv?.get("notifications.toast.enabled")??snapshot["notifications.toast.enabled"],[FINISHED_ALERTS_KEY]:kv?.get(FINISHED_ALERTS_KEY)??snapshot[FINISHED_ALERTS_KEY],mutedTasks:mutedTaskIds(kv?kv.get(MUTED_TASKS_KEY):snapshot[MUTED_TASKS_KEY])}),[kv,snapshot]),counter=import_react12.useRef(0),timers=import_react12.useRef(new Set);import_react12.useEffect(()=>()=>{for(let id of timers.current)clearTimeout(id);timers.current.clear()},[]);let dismiss=import_react12.useCallback((id)=>{setToasts((prev)=>prev.filter((t2)=>t2.id!==id))},[]),notify=import_react12.useCallback((input)=>{setUnread((prev)=>addUnread(prev,input));let muted=input.taskId!==""&&prefs.mutedTasks.has(input.taskId);if(!shouldAlert(input,prefs[FINISHED_ALERTS_KEY]!==!1,muted))return;let soundEnabled=prefs["notifications.sound.enabled"]!==!1;if(shouldPlaySound(input,soundEnabled,muted))writeThroughRenderer(renderer,`\x07${osc9(`Rove \u2014 ${input.title}`)}`),pulse();let toastEnabled=prefs["notifications.toast.enabled"]!==!1;if(shouldShowToast(input.kind,toastEnabled)){let id=++counter.current;setToasts((prev)=>[...prev.filter((t2)=>input.key===void 0||t2.key!==input.key),{id,...input}]);let timer=setTimeout(()=>{timers.current.delete(timer),dismiss(id)},TOAST_DURATION_MS);timers.current.add(timer)}},[prefs,dismiss,renderer]),markRead=import_react12.useCallback((taskId,tabId)=>{setUnread((prev)=>removeUnread(prev,taskId,tabId))},[]),value=import_react12.useMemo(()=>({toasts,unread,notify,dismiss,markRead}),[toasts,unread,notify,dismiss,markRead]);return $jsx(ctx.Provider,{value,children:props.children})}function useNotifications(){let value=import_react12.useContext(ctx);if(!value)throw Error("useNotifications must be used within a NotificationsProvider");return value}function useOptionalNotifications(){return import_react12.useContext(ctx)}function KvWriteErrorToasts(){let kv=useOptionalKV(),notifications=useOptionalNotifications();return import_react13.useEffect(()=>{if(!kv||!notifications)return;return kv.onWriteError((failure)=>{notifications.notify({taskId:"",tabId:"",kind:"error",title:t("settings.stateWrite.failedTitle"),body:t("settings.stateWrite.failedBody",{file:tildify(failure.file),keys:failure.keys.join(", ")})})})},[kv,notifications]),null}var import_react17=__toESM(require_react_production(),1);var breakpoint=DEFAULT_NARROW_BELOW;function setNarrowBreakpoint(value){breakpoint=normalizeNarrowBelow(value)}function isNarrowWidth(cols){return cols<breakpoint}function narrowSurface(args2){if(args2.focusedPane==="sidebar")return"sidebar";return args2.hasSelection||args2.hasOpenPage?"content":"sidebar"}var import_react15=__toESM(require_react_production(),1);var stores=new WeakMap;function terminalSizeStore(source){let existing=stores.get(source);if(existing)return existing;let listeners=new Set,size={width:source.width,height:source.height},notify=()=>{for(let listener2 of listeners)listener2()},store2={subscribe(listener2){if(listeners.add(listener2),listeners.size===1)source.on("resize",notify);return()=>{if(listeners.delete(listener2),listeners.size===0)source.off("resize",notify)}},snapshot(){if(size.width!==source.width||size.height!==source.height)size={width:source.width,height:source.height};return size}};return stores.set(source,store2),store2}function useTerminalSize(){let store2=terminalSizeStore(useRenderer());return import_react15.useSyncExternalStore(store2.subscribe,store2.snapshot)}function useDialogPaddingX(){let dims=useTerminalSize();return isNarrowWidth(dims.width)?1:2}var DIALOG_CONTENT_OPACITY=0.5,TRANSPARENT_DIALOG_CONTENT_OPACITY=0.75;function Dialog(props){let dimensions=useTerminalSize(),{theme}=useTheme(),renderer=useRenderer(),dismissRef=import_react17.useRef(!1),width=props.size==="xlarge"?140:props.size==="large"?110:props.size==="small"?50:80,VERTICAL_MARGIN=2,upperFifth=props.placement==="upper-fifth"&&!isNarrowWidth(dimensions.width),headerTop=Math.max(2,Math.floor(dimensions.height/5)),cardTop=upperFifth?Math.max(2,headerTop-1):0,maxCardHeight=Math.max(8,upperFifth?dimensions.height-cardTop-2:dimensions.height-4);return $jsx("box",{onMouseDown:()=>{dismissRef.current=!!renderer?.getSelection()},onMouseUp:()=>{if(dismissRef.current){dismissRef.current=!1;return}props.onClose?.()},width:dimensions.width,height:dimensions.height,alignItems:"center",justifyContent:upperFifth?"flex-start":"center",paddingTop:cardTop,position:"absolute",zIndex:3000,left:0,top:0,shouldFill:!1,children:$jsx("box",{onMouseUp:(e)=>{dismissRef.current=!1,e.stopPropagation()},width,maxWidth:dimensions.width-2,maxHeight:maxCardHeight,flexShrink:1,flexGrow:0,backgroundColor:theme.backgroundDialog,paddingTop:1,children:props.children})})}var entrySeq=0,ctx2=import_react17.createContext(null);function DialogProvider(props){let[stack2,setStack]=import_react17.useState([]),[size,setSize]=import_react17.useState("medium"),[placement,setPlacement]=import_react17.useState("center"),renderer=useRenderer(),{transparentBackground:transparentBackground2}=useTheme(),focusRef=import_react17.useRef(null),refocusTimer=import_react17.useRef(null);import_react17.useEffect(()=>()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current)},[]);let refocus=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);refocusTimer.current=setTimeout(()=>{let focus=focusRef.current;if(!focus||focus.isDestroyed)return;function find(item){for(let child of item.getChildren()){if(child===focus)return!0;if(find(child))return!0}return!1}let root=renderer?.root;if(!root)return;if(!find(root))return;focus.focus()},1)},[renderer]),stackRef=useLatest(stack2),captureFocusIfFirst=import_react17.useCallback(()=>{if(refocusTimer.current)clearTimeout(refocusTimer.current);if(stackRef.current.length===0)focusRef.current=renderer?.currentFocusedRenderable??null,focusRef.current?.blur()},[renderer]),dismissTop=import_react17.useCallback(()=>{let selection=renderer?.getSelection();if(selection){if(renderer?.clearSelection(),selection.getSelectedText())return}stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),refocus()},[renderer,refocus]),value=import_react17.useMemo(()=>({clear(options){for(let item of stackRef.current)item.onClose?.();if(setSize("medium"),setPlacement("center"),setStack([]),options?.refocus===!1)focusRef.current=null;else refocus()},replace(thunk,onClose){captureFocusIfFirst();for(let item of stackRef.current)item.onClose?.();setSize("medium"),setPlacement("center"),setStack([{key:++entrySeq,element:thunk,onClose}])},push(thunk,onClose){captureFocusIfFirst(),setStack((s)=>[...s,{key:++entrySeq,element:thunk,onClose}])},pop(){if(stackRef.current.at(-1)?.onClose?.(),setStack((s)=>s.slice(0,-1)),stackRef.current.length<=1)refocus()},get stack(){return stackRef.current},get size(){return size},setSize,get placement(){return placement},setPlacement}),[stack2,size,placement,refocus,captureFocusIfFirst]),top=stack2.at(-1),contentOpacity=top?transparentBackground2?TRANSPARENT_DIALOG_CONTENT_OPACITY:DIALOG_CONTENT_OPACITY:1;return $jsxs(ctx2.Provider,{value,children:[$jsx("box",{flexGrow:1,backgroundColor:top&&!transparentBackground2?"black":"transparent",children:$jsx("box",{flexGrow:1,opacity:contentOpacity,children:props.children})}),$jsx("box",{position:"absolute",zIndex:3000,children:top?$jsxs(ModalScopeContext,{value:MODAL_SCOPE,children:[$jsx(ModalBarrier,{dismissTop}),$jsx(Dialog,{onClose:()=>value.clear(),size,placement,children:top.element()},top.key)]}):null})]})}var MODAL_SCOPE=Symbol("rove.dialog.modal");function ModalBarrier(props){return useBindings(()=>({modal:!0,bindings:[{key:"escape",cmd:props.dismissTop},{key:"ctrl+c",cmd:props.dismissTop}]}),{modalOwner:MODAL_SCOPE}),null}function useDialog(){let value=import_react17.useContext(ctx2);if(!value)throw Error("useDialog must be used within a DialogProvider");return value}function useOptionalDialog(){return import_react17.useContext(ctx2)}function showDialog(dialog,body,opts){return new Promise((resolve2)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve2(value),dialog.clear()};if(dialog.replace(()=>body(finish),()=>{if(settled)return;settled=!0,resolve2(void 0)}),opts?.size)dialog.setSize(opts.size)})}function NarrowLayoutSync(){let kv=useOptionalKV();if(kv)setNarrowBreakpoint(kv.get(NARROW_BELOW_KEY));return null}var import_react18=__toESM(require_react_production(),1);function PaneCrashFallback(props){let{theme}=useTheme(),t2=useT(),sizing=props.width===void 0?{flexGrow:1}:{width:props.width,flexShrink:0};return $jsxs("box",{...sizing,flexDirection:"column",backgroundColor:theme.background,paddingLeft:1,paddingTop:1,gap:1,children:[$jsx("text",{fg:theme.error,wrapMode:"word",children:props.region?t2("common.paneCrash.regionTitle",{region:t2(`common.paneCrash.region.${props.region}`)}):t2("common.paneCrash.title")}),$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t2(props.region?"common.paneCrash.regionHint":"common.paneCrash.hint")}),$jsx("text",{fg:theme.focusAccent,onMouseUp:props.onRetry,children:t2("common.paneCrash.retry")})]})}function formatPaneCrashDiagnostic(region,error,info){let base=error instanceof Error?error.stack??error.message:String(error),componentStack=info.componentStack?.trim()||"(unavailable)",stateChanges=recentStateChangesForDiagnostics();return`region: ${region??"root"}
|
|
3
3
|
${base}
|
|
4
4
|
React component stack:
|
|
5
5
|
${componentStack}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{activityHookAdapters}from"./chunk-
|
|
2
|
+
import{activityHookAdapters}from"./chunk-5dv7pw3w.js";import{readFileSync}from"fs";function hookConfigIssues(){let issues=[];for(let adapter of activityHookAdapters()){if(!adapter.hookConfigRefusal)continue;let file=adapter.globalSettingsPath();if(!file)continue;let raw;try{raw=readFileSync(file,"utf8")}catch{continue}let reason=adapter.hookConfigRefusal(raw);if(reason)issues.push({file,reason})}return issues}
|
|
3
3
|
export{hookConfigIssues};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{shellQuote,xml}from"./chunk-
|
|
2
|
+
import{shellQuote,xml}from"./chunk-rnmj5c45.js";import"./chunk-37g0yabr.js";import{ensureDaemonReachable,resolveRoveSpawn}from"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-xasg8z9e.js";import{roveCliInvocation}from"./chunk-bdmbevk8.js";import"./chunk-y8hjgmn0.js";import"./chunk-pn5ygqn6.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import{readRoveHomeDirEnv}from"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{existsSync,mkdirSync,readFileSync,rmSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";var CLI_NAME=ROVE_PRODUCT_NAME,LAUNCHD_LABEL="run.rove.daemon",SYSTEMD_UNIT="rove.service",RUN_KEY="HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run",RUN_VALUE="Rove";function systemdDaemonUnit(ctx){return["[Unit]","Description=Rove daemon","","[Service]",`ExecStart=${[...ctx.cli,"daemon","start","--resident"].map(shellQuote).join(" ")}`,...Object.entries(ctx.env).map(([name,value])=>`Environment=${shellQuote(`${name}=${value}`)}`),`StandardOutput=append:${ctx.logPath}`,`StandardError=append:${ctx.logPath}`,"Restart=on-failure","","[Install]","WantedBy=default.target",""].join(`
|
|
3
3
|
`)}function launchdDaemonPlist(ctx){let args=[...ctx.cli,"daemon","start","--resident"].map((a)=>` <string>${xml(a)}</string>`).join(`
|
|
4
4
|
`),env=Object.entries(ctx.env).map(([name,value])=>` <key>${xml(name)}</key>
|
|
5
5
|
<string>${xml(value)}</string>`).join(`
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{CURRENT_VERSION}from"./chunk-s2eezz0a.js";import{ensureMcpForwards,isRemoteWorkspace,machineMcp,readRemoteWorkspace,rxPath}from"./chunk-750rk2xz.js";import"./chunk-cw9h73h5.js";import"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import{flagValue}from"./chunk-zsfyj36g.js";import"./chunk-xasg8z9e.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir));else if(args[0]==="mcp-hook"){let ws=readRemoteWorkspace(dir);if(ws)ensureMcpForwards(ws.machine,machineMcp(ws.machine))}}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}var ROVE_COMMAND=/^\s*(?:[A-Za-z_]\w*=\S*\s+)*(?:\S*\/)?rove(?:\s|$)/;function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command)||ROVE_COMMAND.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
|
|
3
|
+
`);if(lines.length<=count+1)return text;return`${lines.slice(0,count).join(`
|
|
4
|
+
`)}
|
|
5
|
+
[cut at line ${from+count-1}; pass offset to read on]`}if(name==="write"){if(typeof a.content!=="string")throw Error("content is required");return write(a.content),`wrote ${path}`}if(name==="edit"){let{old_string:from,new_string:to}=a;if(typeof from!=="string"||typeof to!=="string"||!from)throw Error("old_string and new_string are required");let text=must(run(`cat -- ${file}`)),hits=text.split(from).length-1;if(hits===0)throw Error(`old_string not found in ${path}`);if(hits>1&&a.replace_all!==!0)throw Error(`old_string occurs ${hits} times in ${path}; add context to make it unique, or pass replace_all`);return write(text.split(from).join(to)),`edited ${path} (${hits} replacement${hits===1?"":"s"})`}throw Error(`unknown tool: ${name}`)}function mcpReply(run,msg){if(msg.id===void 0||!msg.method)return null;let result=(value)=>({jsonrpc:"2.0",id:msg.id,result:value});if(msg.method==="initialize")return result({protocolVersion:typeof msg.params?.protocolVersion==="string"?msg.params.protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rove-workspace",version:CURRENT_VERSION}});if(msg.method==="ping")return result({});if(msg.method==="tools/list")return result({tools:TOOLS});if(msg.method==="tools/call"){let args=msg.params?.arguments??{};try{let text=callWorkspaceTool(run,String(msg.params?.name??""),args);return result({content:[{type:"text",text}]})}catch(err){return result({content:[{type:"text",text:err instanceof Error?err.message:String(err)}],isError:!0})}}return{jsonrpc:"2.0",id:msg.id,error:{code:-32601,message:`method not found: ${msg.method}`}}}async function serveMcp(rx){let run=runThrough(rx);for await(let line of createInterface({input:process.stdin})){if(!line.trim())continue;let msg;try{msg=JSON.parse(line)}catch{continue}let reply=mcpReply(run,msg);if(reply)process.stdout.write(`${JSON.stringify(reply)}
|
|
6
|
+
`)}}export{runRemoteWorkspaceSubcommand,mcpReply,fileHookReply,callWorkspaceTool,bashHookReply};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{machineIdentityFile,sshTargetOf}from"./chunk-
|
|
2
|
+
import{machineIdentityFile,sshTargetOf}from"./chunk-37g0yabr.js";import{spawnSync}from"child_process";import{existsSync,mkdirSync,rmSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";function reverseTunnelArgv(config,ports){let argv=["ssh","-N","-o","BatchMode=yes","-o","ExitOnForwardFailure=yes","-o","ServerAliveInterval=15","-o","ServerAliveCountMax=3","-o","StrictHostKeyChecking=accept-new"];if(config.port)argv.push("-p",String(config.port));let identity=machineIdentityFile(config);if(identity)argv.push("-i",identity);return argv.push("-R",`127.0.0.1:${ports.remotePort}:127.0.0.1:${ports.localPort}`,sshTargetOf(config)),argv}var unitName=(alias)=>`rove-tunnel-${alias}`;function tunnelServicePath(alias,platform=process.platform){if(platform==="linux")return join(homedir(),".config","systemd","user",`${unitName(alias)}.service`);if(platform==="darwin")return join(homedir(),"Library","LaunchAgents",`run.rove.tunnel.${alias}.plist`);return null}function absoluteSsh(argv){let which=spawnSync("sh",["-c","command -v ssh"],{encoding:"utf8"});return[which.status===0?which.stdout.trim():"/usr/bin/ssh",...argv.slice(1)]}var shellQuote=(arg)=>/^[\w@%+=:,./-]+$/.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`,xml=(s)=>s.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">");function systemdUnit(alias,argv){return["[Unit]",`Description=Rove reverse tunnel to ${alias}`,"After=network-online.target","","[Service]",`ExecStart=${argv.map(shellQuote).join(" ")}`,"Restart=always","RestartSec=5","","[Install]","WantedBy=default.target",""].join(`
|
|
3
3
|
`)}function launchdPlist(alias,argv){let args=argv.map((a)=>` <string>${xml(a)}</string>`).join(`
|
|
4
4
|
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
5
5
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useT,useTheme}from"./chunk-
|
|
2
|
+
import{ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useT,useTheme}from"./chunk-qaznc1bg.js";import"./chunk-b8hd91nv.js";import{$jsx,$jsxs,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-n15p38e5.js";import"./chunk-6xr1prk6.js";import"./chunk-1et3gskx.js";import"./chunk-mdx18vtz.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{BREAKING_VERSIONS,CURRENT_VERSION,breakingVersionsCrossed,fetchReleaseNotes,fetchReleaseSummaries,updateCommandFor}from"./chunk-s2eezz0a.js";import"./chunk-4whghfgg.js";import"./chunk-rxqdw6s5.js";import"./chunk-gzn14mwk.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-40dgv828.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-xasg8z9e.js";import{currentLang}from"./chunk-8xdhw922.js";import"./chunk-cmp64q4j.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__toESM}from"./chunk-91sykzqq.js";import{TextAttributes}from"@opentui/core";var import_react2=__toESM(require_react_production(),1);var RELEASE_LIMIT=20;function VersionsPage(props){let{theme}=useTheme(),t=useT(),renderer=useRenderer(),[releases,setReleases]=import_react2.useState(null),[cursor,setCursor]=import_react2.useState(0),[notes,setNotes]=import_react2.useState({}),[status,setStatus]=import_react2.useState(null),selected=releases?.[cursor],crossings=selected?breakingVersionsCrossed(CURRENT_VERSION,selected.version):[],loadSummaries=props.fetchSummaries??fetchReleaseSummaries,loadNotes=props.fetchNotes??fetchReleaseNotes;import_react2.useEffect(()=>{loadSummaries(RELEASE_LIMIT).then((fetched)=>setReleases(fetched))},[loadSummaries]);let selectedVersion=selected?.version;import_react2.useEffect(()=>{if(selectedVersion===void 0||notes[selectedVersion]!==void 0)return;setNotes((cache)=>({...cache,[selectedVersion]:"loading"})),loadNotes(selectedVersion,currentLang()).then((fetched)=>{setNotes((cache)=>({...cache,[selectedVersion]:fetched??"missing"}))})},[selectedVersion,notes,loadNotes]);function move(delta){let count=releases?.length??0;if(count===0)return;setCursor((index)=>(index+delta+count)%count)}async function installSelected(){if(!selected)return;setStatus(t("update.statusRunningUpdater")),await new Promise((resolve)=>setTimeout(resolve,30)),await runShellUpdater({renderer,t,targetLabel:selected.version,command:updateCommandFor(selected.version)})}useBindings(()=>({bindings:[{key:"up",cmd:()=>move(-1)},{key:"down",cmd:()=>move(1)},{key:"k",cmd:()=>move(-1)},{key:"j",cmd:()=>move(1)},{key:"return",cmd:()=>void installSelected()},{key:"u",cmd:()=>void installSelected()},...pageCloseBindings(props.onClose)]}));let selectedNotes=selectedVersion===void 0?void 0:notes[selectedVersion];return $jsxs("box",{flexDirection:"column",flexGrow:1,paddingTop:1,paddingLeft:2,paddingRight:2,children:[$jsxs("box",{flexDirection:"row",justifyContent:"space-between",flexShrink:0,children:[$jsx("text",{fg:theme.text,attributes:TextAttributes.BOLD,wrapMode:"none",children:t("update.versions.pageTitle")}),$jsx("text",{fg:theme.textMuted,wrapMode:"none",onMouseUp:props.onClose,children:t("update.versions.closeHint")})]}),$jsxs("box",{flexDirection:"row",flexGrow:1,paddingTop:1,gap:2,children:[$jsxs("box",{flexDirection:"column",width:26,flexShrink:0,children:[releases===null?$jsx("text",{fg:theme.textMuted,children:t("update.versions.loading")}):null,releases!==null&&releases.length===0?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.versions.unavailable")}):null,(releases??[]).map((release,index)=>{let active=index===cursor,tags=[release.version===CURRENT_VERSION?t("update.versions.tagCurrent"):"",index===0?t("update.versions.tagLatest"):"",BREAKING_VERSIONS.includes(release.version)?t("update.versions.tagBreaking"):""].filter(Boolean).join(" ");return $jsxs("box",{flexDirection:"row",gap:1,paddingLeft:1,backgroundColor:active?theme.primary:void 0,onMouseUp:()=>setCursor(index),children:[$jsxs("text",{fg:active?theme.selectedListItemText:theme.text,attributes:release.version===CURRENT_VERSION?TextAttributes.BOLD:void 0,wrapMode:"none",children:["v",release.version]}),tags?$jsx("text",{fg:active?theme.selectedListItemText:theme.textMuted,wrapMode:"none",children:tags}):null]},release.version)})]}),$jsxs("box",{flexDirection:"column",flexGrow:1,flexShrink:1,children:[$jsx("scrollbox",{flexGrow:1,flexShrink:1,stickyScroll:!1,verticalScrollbarOptions:{trackOptions:{foregroundColor:"transparent"}},children:$jsxs("box",{flexDirection:"column",paddingRight:1,paddingBottom:1,gap:0,children:[selectedNotes==="loading"?$jsx("text",{fg:theme.textMuted,children:t("update.loadingNotes")}):null,selectedNotes==="missing"?$jsx("text",{fg:theme.textMuted,wrapMode:"word",children:t("update.notesUnavailable")}):null,selectedNotes!==void 0&&selectedNotes!=="loading"&&selectedNotes!=="missing"?$jsx(ReleaseNotesBody,{body:selectedNotes.body}):null]})}),crossings.length>0?$jsx("text",{fg:theme.warning,wrapMode:"word",children:t("update.versions.breakingWarning",{versions:crossings.join(", ")})}):null]})]}),status?$jsx("text",{fg:theme.info,wrapMode:"word",children:status}):null,$jsx("box",{flexShrink:0,paddingTop:1,children:$jsx("text",{fg:theme.textMuted,attributes:TextAttributes.DIM,wrapMode:"none",children:t("update.versions.footerHint")})})]})}var INLINE_ROWS=24;async function startVersionsHost(){await bootPaneHost({inlineRows:INLINE_ROWS,setup:()=>({root:()=>$jsx(VersionsPage,{onClose:()=>process.exit(0)})})})}export{startVersionsHost,VersionsPage};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{isDev}from"./chunk-8143k3t6.js";import{fileURLToPath}from"url";var package_default={$schema:"https://json.schemastore.org/package.json",name:"@sma1lboy/rove",version:"0.9.305-next.430",description:"Rove: all your coding agents, in one place. An agentic development environment (ADE) for your terminal: Claude Code, Codex, Copilot and more, side by side in isolated worktrees, handing tasks to each other.",keywords:["terminal","tui","cli","ade","agentic-development-environment","multiplexer","ai-agents","coding-agent","ai-coding-assistant","agentic-ai","parallel-agents","git-worktree","claude-code","codex","llm","developer-tools"],type:"module",packageManager:"bun@1.3.13",bin:{rove:"dist/cli/rove.js"},files:["dist/cli","dist/completions","dist/web","dist/web-ui","dist/skills","dist/voice","dist/*.wav","README.md","LICENSE"],publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sma1lboy/rove.git"},homepage:"https://rove.run",bugs:{url:"https://github.com/Sma1lboy/rove/issues"},engines:{bun:">=1.3.11"},scripts:{dev:"ROVE_DEV=1 bun --conditions=browser ./src/cli/rove.ts","dev:mock":"ROVE_DEV=1 bun ./src/tui-react/mock/host.tsx","dev:sandbox":"bun run scripts/dev-sandbox.ts run","dev:sandbox:reset":"bun run scripts/dev-sandbox.ts reset",build:"bun run scripts/build.ts","build:rubric":"bun run scripts/build-tier-rubric.ts",compile:"bun run scripts/compile.ts",typecheck:"tsc --noEmit","check-i18n":"bun run scripts/check-i18n.ts",test:"bun run test:fast && bun run test:socket","perf:golden":"bun scripts/perf-golden.ts","rove-bench":"bun --conditions=browser scripts/rove-bench.ts","pty:soak":"bun scripts/pty-soak.ts","test:fast":"vitest run --passWithNoTests --minWorkers=1 --maxWorkers=8","test:socket":"ROVE_INCLUDE_SOCKET=1 vitest run test/daemon --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:socket:coverage":"ROVE_INCLUDE_SOCKET=1 ROVE_COVERAGE_DAEMON=1 vitest run test/daemon --coverage --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:behavior":"ROVE_INCLUDE_BEHAVIOR=1 vitest run test/behavior --pool forks --minWorkers=1 --maxWorkers=1 --retry=2 --passWithNoTests","test:render":"bun scripts/render-track.mjs",coverage:"vitest run --coverage --passWithNoTests",bench:"vitest bench --run",lint:"biome check .",knip:"knip-bun",postinstall:"bun run scripts/check-preview-deps.ts || true",prepublishOnly:"bun run typecheck && bun run build","plugin-sandbox":"bun run scripts/plugin-sandbox.ts"},"//":"biome.json + bunfig.toml live at the monorepo root since they apply repo-wide; bun.lock also lives at root (workspace-shared).",dependencies:{"@ansi-tools/parser":"^1.0.15","@opentui/core":"0.8.4","@opentui/react":"0.8.4","@xterm/addon-serialize":"^0.14.0","@xterm/addon-unicode11":"^0.9.0","@xterm/headless":"^6.0.0",react:"^19.2.8","smol-toml":"^1.7.1",ws:"^8.21.3",yaml:"^2.9.0"},optionalDependencies:{"@sma1lboy/opentui-rove-darwin-arm64":"0.8.4-rove.1","@sma1lboy/opentui-rove-linux-x64":"0.8.4-rove.1","node-pty":"^1.1.0"},devDependencies:{"@biomejs/biome":"1.9.4","@sma1lboy/rove-daemon":"0.7.23","@tsconfig/bun":"1.0.11","@types/bun":"1.3.14","@types/node":"25.6.2","@types/react":"^19.2.0","@vitest/coverage-v8":"2.1.9",knip:"^6.14.2","react-devtools-core":"^7.0.1","rove-bridge":"0.0.65","rove-weixin":"0.0.65",typescript:"5.8.2",vitest:"2.1.9"},trustedDependencies:[]};var RELEASE_CHANNELS=["latest","next","nightly"],DEFAULT_RELEASE_CHANNEL="latest";function channelFor(version){let dash=version.indexOf("-"),tag=dash===-1?void 0:version.slice(dash+1).split(".")[0];return tag==="nightly"||tag==="next"?tag:"latest"}var CURRENT_VERSION=package_default.version,PACKAGE_NAME=package_default.name;function repoSlug(){let url=package_default.repository?.url;if(!url)return null;let m=url.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(!m||!m[1]||!m[2])return null;return`${m[1]}/${m[2]}`}var UPDATE_SCRIPT_URL="https://raw.githubusercontent.com/Sma1lboy/rove/main/scripts/update.sh",UPDATE_COMMAND=`curl -fsSL ${UPDATE_SCRIPT_URL} | sh`;function updateCommandFor(target){return target===void 0||target===DEFAULT_RELEASE_CHANNEL?UPDATE_COMMAND:`${UPDATE_COMMAND} -s -- ${target}`}function owningNpmPrefix(modulePath=fileURLToPath(import.meta.url)){let at=modulePath.indexOf("/lib/node_modules/");if(at<=0)return null;return modulePath.slice(0,at)}function recommendedGlobalInstallCommand(prefix=owningNpmPrefix()){let target=`${PACKAGE_NAME}@latest`;return prefix===null?`npm install -g ${target}`:`npm install -g --prefix ${prefix} ${target}`}var BREAKING_VERSIONS=[];function breakingVersionsCrossed(from,to,breaking=BREAKING_VERSIONS){let[lo,hi]=compareSemver(from,to)<=0?[from,to]:[to,from];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}var FETCH_TIMEOUT_MS=3000,PACKUMENT_TIMEOUT_MS=15000;function channelOf(version=CURRENT_VERSION){return channelFor(version)}async function fetchLatestFromRegistry(packageName,channel){let ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let encoded=packageName.replace("/","%2F"),res=await fetch(`https://registry.npmjs.org/${encoded}/${channel}`,{signal:ctrl.signal,headers:{accept:"application/json"}});if(!res.ok)return null;let body=await res.json();if(typeof body.version!=="string")return null;return body.version}catch{return null}finally{clearTimeout(timer)}}async function fetchPublishedAt(packageName,version){let ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),PACKUMENT_TIMEOUT_MS);try{let encoded=packageName.replace("/","%2F"),res=await fetch(`https://registry.npmjs.org/${encoded}`,{signal:ctrl.signal,headers:{accept:"application/json"}});if(!res.ok)return null;let stamp=(await res.json()).time?.[version],ms=typeof stamp==="string"?Date.parse(stamp):Number.NaN;return Number.isFinite(ms)?ms:null}catch{return null}finally{clearTimeout(timer)}}function isNewerSemver(latest,current){let core=compareSemver(latest,current);if(core!==0)return core>0;return comparePrerelease(prereleaseOf(latest),prereleaseOf(current))>0}function prereleaseOf(version){let dash=version.indexOf("-");return dash===-1?void 0:version.slice(dash+1)||void 0}function comparePrerelease(a,b){if(a===b)return 0;if(a===void 0)return 1;if(b===void 0)return-1;let aParts=a.split("."),bParts=b.split(".");for(let i=0;i<Math.max(aParts.length,bParts.length);i++){let av=aParts[i],bv=bParts[i];if(av===void 0)return-1;if(bv===void 0)return 1;if(av===bv)continue;let an=/^\d+$/.test(av)?Number.parseInt(av,10):null,bn=/^\d+$/.test(bv)?Number.parseInt(bv,10):null;if(an!==null&&bn!==null)return an>bn?1:-1;if(an!==null)return-1;if(bn!==null)return 1;return av>bv?1:-1}return 0}function compareSemver(aVersion,bVersion){let norm=(v)=>v.split("-")[0]??v,a=norm(aVersion).split(".").map((s)=>Number.parseInt(s,10)),b=norm(bVersion).split(".").map((s)=>Number.parseInt(s,10));for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(Number.isNaN(av)||Number.isNaN(bv))return 0;if(av>bv)return 1;if(av<bv)return-1}return 0}async function checkLatestVersion(opts={}){let channel=opts.channel??channelOf(),fake=process.env.ROVE_FAKE_UPDATE;if(fake)return{current:CURRENT_VERSION,latest:fake,hasUpdate:isNewerSemver(fake,CURRENT_VERSION),channel};if(isDev()&&!opts.force)return null;let latest=await fetchLatestFromRegistry(PACKAGE_NAME,channel);if(!latest)return null;let hasUpdate=isNewerSemver(latest,CURRENT_VERSION),minAgeMs=(opts.minAgeHours??0)*3600000;if(hasUpdate&&minAgeMs>0){let publishedAt=await fetchPublishedAt(PACKAGE_NAME,latest),now=(opts.now??Date.now)();if(publishedAt!==null&&now-publishedAt<minAgeMs)hasUpdate=!1}return{current:CURRENT_VERSION,latest,hasUpdate,channel}}function versionFromTagName(tagName,channel){if(typeof tagName!=="string")return null;let match=tagName.match(/^v\d+\.\d+\.\d+(?:-([a-z]+)\.\d+)?$/);if(!match||match[1]&&match[1]!==channel)return null;return tagName.slice(1)}var ZH_NOTES_ASSET="release-notes.zh.md";async function notesBody(release,locale,signal){if(locale!=="zh"||!Array.isArray(release.assets))return release.body;let asset=release.assets.find((a)=>a.name===ZH_NOTES_ASSET);if(typeof asset?.browser_download_url!=="string")return release.body;try{let res=await fetch(asset.browser_download_url,{signal}),text=res.ok?await res.text():"";return text.trim()?text:release.body}catch{return release.body}}async function fetchReleaseNotes(version,locale="en"){let slug=repoSlug();if(!slug)return null;let tag=`v${version}`,ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let res=await fetch(`https://api.github.com/repos/${slug}/releases/tags/${tag}`,{signal:ctrl.signal,headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return null;let body=await res.json();if(typeof body.body!=="string"||typeof body.html_url!=="string")return null;return{body:await notesBody({...body,body:body.body},locale,ctrl.signal),url:body.html_url,version}}catch{return null}finally{clearTimeout(timer)}}var RELEASES_PER_PAGE=100,MAX_RELEASE_PAGES=10;async function walkReleases(visit){let slug=repoSlug();if(!slug)return;for(let page=1;page<=MAX_RELEASE_PAGES;page++){let body;try{let res=await fetch(`https://api.github.com/repos/${slug}/releases?per_page=${RELEASES_PER_PAGE}&page=${page}`,{signal:AbortSignal.timeout(FETCH_TIMEOUT_MS),headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return;body=await res.json()}catch{return}if(!Array.isArray(body))return;for(let release of body)if(!visit(release))return;if(body.length<RELEASES_PER_PAGE)return}}async function fetchReleaseNotesRange(args){let channel=channelFor(args.latest),inRange=[];await walkReleases((release)=>{let version=versionFromTagName(release.tag_name,channel);if(!version)return!0;if(!isNewerSemver(version,args.current))return!1;if(isNewerSemver(version,args.latest))return!0;if(typeof release.html_url==="string"&&typeof release.body==="string")inRange.push({version,url:release.html_url,release:{...release,body:release.body}});return!0});let signal=AbortSignal.timeout(FETCH_TIMEOUT_MS);return Promise.all(inRange.map(async({version,url,release})=>({version,url,body:await notesBody(release,args.locale??"en",signal)})))}async function fetchReleaseSummaries(limit=12){let summaries=[];return await walkReleases((release)=>{let version=versionFromTagName(release.tag_name);if(version&&typeof release.html_url==="string")summaries.push({version,url:release.html_url});return summaries.length<limit}),summaries}function releasePageUrl(version){let slug=repoSlug();if(!slug)return null;return`https://github.com/${slug}/releases/tag/v${version}`}
|
|
3
|
+
export{package_default,RELEASE_CHANNELS,DEFAULT_RELEASE_CHANNEL,CURRENT_VERSION,PACKAGE_NAME,repoSlug,UPDATE_SCRIPT_URL,UPDATE_COMMAND,updateCommandFor,owningNpmPrefix,recommendedGlobalInstallCommand,BREAKING_VERSIONS,breakingVersionsCrossed,channelOf,isNewerSemver,compareSemver,checkLatestVersion,ZH_NOTES_ASSET,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,releasePageUrl};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{launchTui,trackWelcomeWrite}from"./chunk-
|
|
2
|
+
import{launchTui,trackWelcomeWrite}from"./chunk-9tke0g8m.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{engineEntry,identifiableEngineIds}from"./chunk-
|
|
2
|
+
import{engineEntry,identifiableEngineIds}from"./chunk-5dv7pw3w.js";import{recordSpawn}from"./chunk-40dgv828.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import{PsProbeUnavailableError}from"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.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 customEngineBinaries(){let state=loadStateFile(),ids=state.customEngineIds,out=new Map;if(!Array.isArray(ids))return out;for(let id of ids){if(typeof id!=="string"||id.trim().length===0)continue;let command=state[`engineCommand.${id}`],argv=typeof command==="string"&&command.trim().length>0?command.trim().split(/\s+/):[id],name=executableNameFromArgv(argv);if(name)out.set(name,id)}return out}function findDescendant(rows,rootPid,pick){let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]],visited=new Set;while(queue.length>0){let row=queue.shift();if(!row)break;if(visited.has(row.pid))continue;visited.add(row.pid);let hit=pick(row);if(hit!==null)return hit;queue.push(...kids.get(row.pid)??[])}return null}function walkDescendants(rows,rootPid,identify){return findDescendant(rows,rootPid,(row)=>{let vendor=identify(row.args);return vendor?{vendor,argv:row.args,pid:row.pid}:null})}function foregroundEngineIn(rows,rootPid){let builtin=walkDescendants(rows,rootPid,vendorFromArgv);if(builtin)return builtin;let custom=customEngineBinaries();if(custom.size===0)return null;return walkDescendants(rows,rootPid,(args)=>custom.get(executableNameFromArgv(args.trim().split(/\s+/))??"")??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;return findDescendant(rows,rootPid,(row)=>executableNameFromArgv(row.args.trim().split(/\s+/))===expected?!0:null)===!0}var PS_PROBE_TIMEOUT_MS=5000,bunPsSpawn=()=>{recordSpawn("engine.foregroundWalk",["ps","-A","-o","pid=,ppid=,args="]);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)}}function shareInflight(run){let inflight=null;return()=>{return inflight??=run().finally(()=>{inflight=null}),inflight}}var sharedPs=shareInflight(()=>psSnapshotWith(bunPsSpawn)),psSnapshot=async(anchors)=>{if(process.platform!=="win32")return sharedPs();let{defaultWinProcessProbe,winProcessSnapshot}=await import("./chunk-tv4frx8n.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,shareInflight,psSnapshot,foregroundEngine};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{installReverseTunnel,reverseTunnelArgv,tunnelServicePath,uninstallReverseTunnel}from"./chunk-
|
|
2
|
+
import{installReverseTunnel,reverseTunnelArgv,tunnelServicePath,uninstallReverseTunnel}from"./chunk-rnmj5c45.js";import{defaultFixRuntime}from"./chunk-7z2bmv13.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-d35ctfpd.js";import"./chunk-gafj4yp3.js";import"./chunk-t4reqv8m.js";import"./chunk-8hfkcjxm.js";import"./chunk-h9z9x14k.js";import"./chunk-j2k6f128.js";import"./chunk-38hnq4aq.js";import"./chunk-rset5pt8.js";import"./chunk-17e2tgyg.js";import"./chunk-2xsxcdp6.js";import"./chunk-79wejcs5.js";import"./chunk-6cggsxpr.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-2bgmby1d.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-psxhek7n.js";import"./chunk-pf3nzz87.js";import"./chunk-xj3034s1.js";import"./chunk-mdx18vtz.js";import"./chunk-p4rhkv3k.js";import{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-zc67sqet.js";import"./chunk-ejs6dnxf.js";import{discoverMachine,learnedFrom,remoteRove,sshServerIsWindows}from"./chunk-a6s52zm5.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-2x6s7z8w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION}from"./chunk-s2eezz0a.js";import{SUBCOMMAND_VERBS}from"./chunk-6jxe4f13.js";import"./chunk-06vsvvtr.js";import"./chunk-zze1pw22.js";import"./chunk-0x62tvdk.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-4whghfgg.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-t7qj639x.js";import"./chunk-gz0x179r.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-133c884f.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-ahbw1f8n.js";import"./chunk-sak1tphp.js";import{shQuote}from"./chunk-y1xnjx8x.js";import"./chunk-sffdpzfv.js";import"./chunk-5dv7pw3w.js";import"./chunk-2bapg0v2.js";import{forwardedMcp}from"./chunk-750rk2xz.js";import"./chunk-w7zv47mp.js";import{isWindowsMachine,windowsAuthorizeKeySteps}from"./chunk-cw9h73h5.js";import{addMachine,dedupeMachines,defaultMachineAlias,duplicateAliasOf,getMachine,hubKeyPath,isValidMachineAlias,listMachines,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,removeMachine,sanitizeAlias,setMachineIdentity,sshTargetOf,updateMachine}from"./chunk-37g0yabr.js";import"./chunk-nw48bskt.js";import"./chunk-k7tdg6kb.js";import"./chunk-1pmzr8kr.js";import"./chunk-e5jxbd98.js";import"./chunk-84q9hv7m.js";import"./chunk-96kvwzj8.js";import"./chunk-etfh8f4z.js";import"./chunk-07665jz6.js";import"./chunk-40dgv828.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-yvg46jh9.js";import{loadStateFile}from"./chunk-xasg8z9e.js";import"./chunk-8xdhw922.js";import"./chunk-cmp64q4j.js";import"./chunk-j152pk57.js";import"./chunk-c4dfktv2.js";import"./chunk-bdmbevk8.js";import"./chunk-7kysxgbq.js";import"./chunk-g755p68b.js";import"./chunk-tcmzq86w.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{spawn}from"child_process";import{appendFileSync,chmodSync,existsSync,mkdirSync}from"fs";import{homedir}from"os";import{dirname}from"path";function parseSshG(stdout,home=homedir()){let values=new Map;for(let line of stdout.split(`
|
|
3
3
|
`)){let space=line.indexOf(" ");if(space>0)values.set(line.slice(0,space).toLowerCase(),line.slice(space+1).trim())}let hostname=values.get("hostname")??"",port=Number(values.get("port")??"22")||22,files=(key)=>(values.get(key)??"").split(/\s+/).filter((f)=>f&&f!=="none").map((f)=>f.startsWith("~/")?`${home}${f.slice(1)}`:f),alias=values.get("hostkeyalias"),proxy=(key)=>{let v=values.get(key);return v!==void 0&&v!=="none"};return{knownHostsName:alias&&alias!=="none"?alias:port===22?hostname:`[${hostname}]:${port}`,hostname,port,userKnownHosts:files("userknownhostsfile"),globalKnownHosts:files("globalknownhostsfile"),proxied:proxy("proxyjump")||proxy("proxycommand")}}async function checkHostKey(config){let target=sshTargetOf(config),resolved=await run(["ssh","-G",...config.port?["-p",String(config.port)]:[],target]);if(resolved.code!==0)return{state:"skipped",reason:"ssh -G failed"};let destination=parseSshG(resolved.stdout);if(!destination.hostname)return{state:"skipped",reason:"ssh -G named no host"};if(destination.proxied)return{state:"skipped",reason:"reached through a proxy"};for(let file of[...destination.userKnownHosts,...destination.globalKnownHosts]){if(!existsSync(file))continue;if((await run(["ssh-keygen","-F",destination.knownHostsName,"-f",file])).code===0)return{state:"known"}}let keys=(await run(["ssh-keyscan","-T","5","-p",String(destination.port),destination.hostname])).stdout.split(`
|
|
4
4
|
`).filter((line)=>line.trim()&&!line.startsWith("#"));if(keys.length===0)return{state:"skipped",reason:"the host offered no key"};let named=keys.map((line)=>line.replace(/^\S+/,destination.knownHostsName)),fingerprints=(await run(["ssh-keygen","-l","-f","-"],`${named.join(`
|
|
5
5
|
`)}
|
|
@@ -7,29 +7,33 @@ import{installReverseTunnel,reverseTunnelArgv,tunnelServicePath,uninstallReverse
|
|
|
7
7
|
`).filter((line)=>line.trim());return{state:"unknown",destination,fingerprints,trust(){let file=destination.userKnownHosts[0]??`${homedir()}/.ssh/known_hosts`;mkdirSync(dirname(file),{recursive:!0,mode:448}),appendFileSync(file,`${named.join(`
|
|
8
8
|
`)}
|
|
9
9
|
`,{mode:384});try{chmodSync(file,384)}catch{}}}}function run(argv,stdin){return new Promise((resolve)=>{let stdout="",child=spawn(argv[0]??"ssh",argv.slice(1),{stdio:[stdin===void 0?"ignore":"pipe","pipe","ignore"]}),timer=setTimeout(()=>child.kill("SIGKILL"),15000);if(child.stdout?.on("data",(chunk)=>{stdout+=chunk.toString()}),child.on("error",()=>{clearTimeout(timer),resolve({code:-1,stdout})}),child.on("close",(code)=>{clearTimeout(timer),resolve({code:code??-1,stdout})}),stdin!==void 0)child.stdin?.end(stdin)})}import{existsSync as existsSync2,mkdirSync as mkdirSync2,readFileSync}from"fs";import{hostname}from"os";import{join}from"path";var INSTALL_SCRIPT="curl -fsSL https://rove.run/install.sh | sh";function fixesFor(failure,alias,config,keyPath=hubKeyPath()){let target=sshTargetOf(config),ssh=(cmd,batch=!0)=>[...machineSshArgs(alias,config,{batch}),cmd];if(failure.code==="SSH_FAILED"&&failure.ssh==="auth-denied"&&config.auth.kind==="key"&&failure.windows){if(!existsSync2(`${keyPath}.pub`))return[hubKeyFix(keyPath)];let steps=windowsAuthorizeKeySteps(readFileSync(`${keyPath}.pub`,"utf8"));return[{kind:"manual",id:"windows-authorize-hub-key",label:`Authorize this hub's key on ${target}`,action:[`on ${target}, in PowerShell:`,...steps.map((step)=>` ${step}`),` then: rove machine add ${target}${config.port?` --port ${config.port}`:""} --alias ${alias} --identity ${keyPath}`].join(`
|
|
10
|
-
`)}]}if(failure.code==="SSH_FAILED"&&failure.ssh==="auth-denied"&&config.auth.kind==="key"){let fixes=existsSync2(keyPath)?[]:[hubKeyFix(keyPath)];return fixes.push({kind:"run",id:"install-hub-key",label:`Authorize that key on ${target}`,shown:`ssh ${target} 'append ${keyPath}.pub to ~/.ssh/authorized_keys'`,why:"The one interactive step: ssh asks for your password on that machine once. Rove never sees it.",argv:()=>ssh(authorizeKeyScript(readFileSync(`${keyPath}.pub`,"utf8").trim()),!1),apply:(c)=>({...c,auth:{kind:"key",keyPath}})}),fixes}if(failure.code==="SSH_FAILED")return[];if(failure.code==="NO_ROVE"&&failure.windows)return[{kind:"install",id:"install-rove",label:`Install Rove on ${target}`,shown:`ssh ${target} '${WINDOWS_INSTALL}'`,why:"The Windows install: npm puts rove on that user's PATH (it needs Node.js and Git for Windows there).",argv:()=>ssh(WINDOWS_INSTALL)}];if(failure.code==="NO_ROVE")return[{kind:"install",id:"install-rove",label:`Install Rove on ${target}`,shown:`ssh ${target} '${INSTALL_SCRIPT}'`,why:"The official install script: sets up Bun if needed, then Rove, for that user only.",argv:()=>ssh(INSTALL_SCRIPT)}];if(failure.code==="BAD_STATUS"&&/too old/.test(failure.message))return[{kind:"install",id:"update-rove",label:`Update Rove on ${target}`,shown:`ssh ${target} 'rove update'`,why:"Its Rove is too old for this hub; `rove update` moves it to the current release.",argv:()=>ssh(remoteRove(config.roveBin,["update"]))}];let log=isWindowsMachine(config)?`ssh ${target} 'powershell -NoProfile -Command "Get-Content -Tail 40 $env:USERPROFILE\\.rove\\daemon.log"'`:`ssh ${target} 'tail -n 40 ~/.rove/daemon.log'`;return[{kind:"manual",id:"daemon-log",label:`Rove on ${target} would not start its daemon`,action:log}]}var WINDOWS_INSTALL="npm install -g @sma1lboy/rove";function hubKeyFix(keyPath){return{kind:"run",id:"hub-key",label:"Create a key this hub logs in with",shown:`ssh-keygen -t ed25519 -N "" -C ${hubKeyComment()} -f ${keyPath}`,why:"A dedicated key revokes this hub alone: delete its one line on the machine. No passphrase, so the hub can reconnect unattended; the file is owner-only.",argv:()=>{return mkdirSync2(join(keyPath,".."),{recursive:!0,mode:448}),["ssh-keygen","-q","-t","ed25519","-N","","-C",hubKeyComment(),"-f",keyPath]}}}function hubKeyComment(){return`rove-hub@${hostname()}`}function authorizeKeyScript(publicKey){let line=shQuote(publicKey);return["umask 077","mkdir -p ~/.ssh","touch ~/.ssh/authorized_keys",`grep -qxF ${line} ~/.ssh/authorized_keys || printf '%s\\n' ${line} >> ~/.ssh/authorized_keys`].join(" && ")}async function establishMachine(alias,initial,rt){let discover=rt.discover??discoverMachine,config=initial,tried=new Set;for(;;){let found=await discover(alias,config);if(found.ok)return{ok:!0,found,config:found.roveBin?{...config,roveBin:found.roveBin}:config};rt.out(found.message);let fixes=fixesFor(found,alias,config),runnable=fixes.filter((f)=>f.kind!=="manual"&&!tried.has(f.id));for(let fix of fixes)if(fix.kind==="manual")rt.out(` \u2192 ${fix.action}`);if(runnable.length===0)return{ok:!1,failure:found};for(let fix of runnable){if(fix.kind==="manual")continue;if(tried.add(fix.id),rt.out(` ${fix.label}`),rt.out(` will run: ${fix.shown}`),rt.out(` ${fix.why}`),rt.planOnly)continue;if(rt.ask&&!await rt.confirm(" Run it? [y/N] "))return{ok:!1,failure:found};let code=await rt.exec(fix.argv());if(code!==0)return rt.out(` failed (exit ${code})`),{ok:!1,failure:found};if(fix.apply)config=fix.apply(config)}if(rt.planOnly)return rt.out(" Not a terminal: nothing was run. Re-run in a terminal, or pass --yes."),{ok:!1,failure:found}}}
|
|
10
|
+
`)}]}if(failure.code==="SSH_FAILED"&&failure.ssh==="auth-denied"&&config.auth.kind==="key"){let fixes=existsSync2(keyPath)?[]:[hubKeyFix(keyPath)];return fixes.push({kind:"run",id:"install-hub-key",label:`Authorize that key on ${target}`,shown:`ssh ${target} 'append ${keyPath}.pub to ~/.ssh/authorized_keys'`,why:"The one interactive step: ssh asks for your password on that machine once. Rove never sees it.",argv:()=>ssh(authorizeKeyScript(readFileSync(`${keyPath}.pub`,"utf8").trim()),!1),apply:(c)=>({...c,auth:{kind:"key",keyPath}})}),fixes}if(failure.code==="SSH_FAILED")return[];if(failure.code==="NO_ROVE"&&failure.windows)return[{kind:"install",id:"install-rove",label:`Install Rove on ${target}`,shown:`ssh ${target} '${WINDOWS_INSTALL}'`,why:"The Windows install: npm puts rove on that user's PATH (it needs Node.js and Git for Windows there).",argv:()=>ssh(WINDOWS_INSTALL)}];if(failure.code==="NO_ROVE")return[{kind:"install",id:"install-rove",label:`Install Rove on ${target}`,shown:`ssh ${target} '${INSTALL_SCRIPT}'`,why:"The official install script: sets up Bun if needed, then Rove, for that user only.",argv:()=>ssh(INSTALL_SCRIPT)}];if(failure.code==="BAD_STATUS"&&/too old/.test(failure.message))return[{kind:"install",id:"update-rove",label:`Update Rove on ${target}`,shown:`ssh ${target} 'rove update'`,why:"Its Rove is too old for this hub; `rove update` moves it to the current release.",argv:()=>ssh(remoteRove(config.roveBin,["update"]))}];let log=isWindowsMachine(config)?`ssh ${target} 'powershell -NoProfile -Command "Get-Content -Tail 40 $env:USERPROFILE\\.rove\\daemon.log"'`:`ssh ${target} 'tail -n 40 ~/.rove/daemon.log'`;return[{kind:"manual",id:"daemon-log",label:`Rove on ${target} would not start its daemon`,action:log}]}var WINDOWS_INSTALL="npm install -g @sma1lboy/rove";function hubKeyFix(keyPath){return{kind:"run",id:"hub-key",label:"Create a key this hub logs in with",shown:`ssh-keygen -t ed25519 -N "" -C ${hubKeyComment()} -f ${keyPath}`,why:"A dedicated key revokes this hub alone: delete its one line on the machine. No passphrase, so the hub can reconnect unattended; the file is owner-only.",argv:()=>{return mkdirSync2(join(keyPath,".."),{recursive:!0,mode:448}),["ssh-keygen","-q","-t","ed25519","-N","","-C",hubKeyComment(),"-f",keyPath]}}}function hubKeyComment(){return`rove-hub@${hostname()}`}function authorizeKeyScript(publicKey){let line=shQuote(publicKey);return["umask 077","mkdir -p ~/.ssh","touch ~/.ssh/authorized_keys",`grep -qxF ${line} ~/.ssh/authorized_keys || printf '%s\\n' ${line} >> ~/.ssh/authorized_keys`].join(" && ")}async function establishMachine(alias,initial,rt){let discover=rt.discover??discoverMachine,config=initial,tried=new Set;for(;;){let found=await discover(alias,config);if(found.ok)return{ok:!0,found,config:found.roveBin?{...config,roveBin:found.roveBin}:config};rt.out(found.message);let fixes=fixesFor(found,alias,config),runnable=fixes.filter((f)=>f.kind!=="manual"&&!tried.has(f.id));for(let fix of fixes)if(fix.kind==="manual")rt.out(` \u2192 ${fix.action}`);if(runnable.length===0)return{ok:!1,failure:found};for(let fix of runnable){if(fix.kind==="manual")continue;if(tried.add(fix.id),rt.out(` ${fix.label}`),rt.out(` will run: ${fix.shown}`),rt.out(` ${fix.why}`),rt.planOnly)continue;if(rt.ask&&!await rt.confirm(" Run it? [y/N] "))return{ok:!1,failure:found};let code=await rt.exec(fix.argv());if(code!==0)return rt.out(` failed (exit ${code})`),{ok:!1,failure:found};if(fix.apply)config=fix.apply(config)}if(rt.planOnly)return rt.out(" Not a terminal: nothing was run. Re-run in a terminal, or pass --yes."),{ok:!1,failure:found}}}function machineMcp(argv,fail){let[alias,name,url]=argv.filter((a)=>!a.startsWith("--"));if(!alias)fail("mcp: name the machine: mcp <alias> [<name> <url> | <name> --clear]");let config=getMachine(alias);if(!config)fail(`no machine named "${alias}" (see \`${ROVE_PRODUCT_NAME} machine list\`)`);let servers=config.mcp??[];if(!name){if(servers.length===0)process.stdout.write(`No MCP servers forwarded from ${alias}.
|
|
11
|
+
`);for(let[i,fwd2]of forwardedMcp(alias,servers).entries())process.stdout.write(`${fwd2.server} ${servers[i]?.url} \u2192 ${fwd2.url}
|
|
12
|
+
`);return}if(!/^[A-Za-z0-9_-]+$/.test(name))fail(`mcp: "${name}" is not a server name (letters, digits, _ and -)`);let rest=servers.filter((s)=>s.name!==name);if(argvHasFlag(argv,"--clear")){updateMachine(alias,{mcp:rest}),process.stdout.write(`${ROVE_PRODUCT_NAME} machine: ${alias} no longer forwards ${name}
|
|
13
|
+
`);return}if(!url||forwardedMcp(alias,[{name,url}]).length===0)fail(`mcp: give the server's http(s) URL as ${alias} reaches it, e.g. http://127.0.0.1:12306/mcp`);updateMachine(alias,{mcp:[...rest,{name,url}]});let[fwd]=forwardedMcp(alias,[{name,url}]);process.stdout.write(`${ROVE_PRODUCT_NAME} machine: new sessions with a workspace on ${alias} get ${fwd?.server} (${url} there, ${fwd?.url} here)
|
|
14
|
+
`)}import{resolve}from"path";function machinePrimary(argv,fail){let clear=argvHasFlag(argv,"--clear"),target=argv.find((a)=>!a.startsWith("--"));if(!target){let marks=Object.entries(primaryCheckouts());if(marks.length===0)process.stdout.write(`No primary checkouts marked.
|
|
11
15
|
`);for(let[id2,path2]of marks)process.stdout.write(`${id2} ${path2}
|
|
12
16
|
`);return}let path=resolve(target),id=repoIdOf(repoIdentity(path));if(!id)fail(`primary: ${path} is not a git checkout`);setPrimaryCheckout(id,clear?null:path),process.stdout.write(clear?`${ROVE_PRODUCT_NAME} machine: ${id} has no primary checkout now
|
|
13
17
|
`:`${ROVE_PRODUCT_NAME} machine: ${id} resolves to ${path} here
|
|
14
|
-
`)}var CLI_NAME=ROVE_PRODUCT_NAME,MACHINE_USAGE=[`Usage: ${CLI_NAME} machine <${SUBCOMMAND_VERBS.machine.join("|")}> [options]`,"","Manage the other computers running Rove. Each one is reached over SSH;","its tasks appear in the sidebar under a row of its own.","","Commands:"," add <ssh-target> Register a machine (verifies it, offering fixes, before saving)"," doctor [alias] Re-check registered machines and offer the same fixes"," update [alias] Update Rove on a machine (all of them without an alias) and restart its daemon"," remove <alias> Forget a machine (nothing on it is touched)"," list Show registered machines"," tunnel <alias> Keep a reverse tunnel to <alias> so it can reach THIS machine"," inbound [allow|deny <class>] What other machines' hubs may run here (default: everything)"," primary [<path>] [--clear] The checkout a repo id resolves to here when there are several","","Add options:"," --alias <name> Local name for the machine (default: the target you typed)"," --port <n> SSH port (default: whatever ssh_config says)"," --identity <file> SSH private key (default: ssh-agent / ssh_config)"," --yes Run every offered fix without asking (add, doctor)","","Tunnel options (when <alias> cannot reach this machine, e.g. WSL behind Windows NAT):"," --install Run it as a login service (systemd user unit / launchd agent)"," --uninstall Stop and remove that service"," --print Print the ssh command and service file; change nothing (default)"," --remote-port <n> Port on <alias>'s loopback that leads back here (default 2222)"," --local-port <n> This machine's sshd port (default 22)"," Then on <alias>: machine add <you>@127.0.0.1:<remote-port>",""," <ssh-target> is [user@]host[:port] \u2014 usually just an ssh_config Host alias."," In a terminal, a key the machine rejects or a missing Rove is offered as"," a fix (a dedicated hub key, the install script) instead of an error.",""].join(`
|
|
18
|
+
`)}var CLI_NAME=ROVE_PRODUCT_NAME,MACHINE_USAGE=[`Usage: ${CLI_NAME} machine <${SUBCOMMAND_VERBS.machine.join("|")}> [options]`,"","Manage the other computers running Rove. Each one is reached over SSH;","its tasks appear in the sidebar under a row of its own.","","Commands:"," add <ssh-target> Register a machine (verifies it, offering fixes, before saving)"," doctor [alias] Re-check registered machines and offer the same fixes"," update [alias] Update Rove on a machine (all of them without an alias) and restart its daemon"," remove <alias> Forget a machine (nothing on it is touched)"," list Show registered machines"," tunnel <alias> Keep a reverse tunnel to <alias> so it can reach THIS machine"," inbound [allow|deny <class>] What other machines' hubs may run here (default: everything)"," primary [<path>] [--clear] The checkout a repo id resolves to here when there are several"," mcp <alias> [<name> <url>|<name> --clear] MCP servers on <alias> to forward into sessions whose workspace is there","","Add options:"," --alias <name> Local name for the machine (default: the target you typed)"," --port <n> SSH port (default: whatever ssh_config says)"," --identity <file> SSH private key (default: ssh-agent / ssh_config)"," --yes Run every offered fix without asking (add, doctor)","","Tunnel options (when <alias> cannot reach this machine, e.g. WSL behind Windows NAT):"," --install Run it as a login service (systemd user unit / launchd agent)"," --uninstall Stop and remove that service"," --print Print the ssh command and service file; change nothing (default)"," --remote-port <n> Port on <alias>'s loopback that leads back here (default 2222)"," --local-port <n> This machine's sshd port (default 22)"," Then on <alias>: machine add <you>@127.0.0.1:<remote-port>",""," <ssh-target> is [user@]host[:port] \u2014 usually just an ssh_config Host alias."," In a terminal, a key the machine rejects or a missing Rove is offered as"," a fix (a dedicated hub key, the install script) instead of an error.",""].join(`
|
|
15
19
|
`);function usageError(message){process.stderr.write(`${CLI_NAME} machine: ${message}
|
|
16
20
|
|
|
17
21
|
${MACHINE_USAGE}
|
|
18
22
|
`),process.exit(2)}function fail(message){process.stderr.write(`${CLI_NAME} machine: ${message}
|
|
19
23
|
`),process.exit(1)}function flagValue(argv,name){for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg===void 0)continue;if(arg.startsWith(`--${name}=`))return arg.slice(name.length+3);if(arg!==`--${name}`)continue;let value=argv[i+1];if(value===void 0||value.startsWith("--"))usageError(`--${name} needs a value`);return value}return}async function runMachineSubcommand(argv){let[verb,...rest]=argv;if(!verb||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${MACHINE_USAGE}
|
|
20
|
-
`);return}if(!SUBCOMMAND_VERBS.machine.includes(verb))usageError(`unknown verb "${verb}"`);if(verb==="list")return list();if(verb==="add")return await add(rest);if(verb==="doctor")return await doctor(rest);if(verb==="update")return await update(rest);if(verb==="remove")return remove(rest);if(verb==="tunnel")return tunnel(rest);if(verb==="inbound")return inbound(rest);if(verb==="primary")return machinePrimary(rest,usageError);usageError(`unknown verb "${verb}"`)}async function add(argv){let target=positionalOf(argv);if(!target)usageError("add needs an ssh target, e.g. `machine add narwhal`");let parsed=parseSshTarget(target);if(!parsed)usageError(`"${target}" is not a valid ssh target ([user@]host[:port])`);let portFlag=flagValue(argv,"port"),port=portFlag?Number(portFlag):parsed.port;if(port!==void 0&&(!Number.isInteger(port)||port<1||port>65535))usageError("--port must be 1-65535");let identity=flagValue(argv,"identity"),requested=flagValue(argv,"alias");if(requested&&!isValidMachineAlias(requested))usageError(`--alias must be letters/digits/._- and cannot be "local" (got "${requested}")`);let probeAlias=requested??sanitizeAlias(parsed.host),config={host:parsed.host,...parsed.user?{user:parsed.user}:{},...port?{port}:{},auth:identity?{kind:"key",keyPath:identity}:{kind:"key"}};await confirmHostKey(config),process.stderr.write(`${CLI_NAME} machine: contacting ${sshTargetOf(config)}\u2026
|
|
24
|
+
`);return}if(!SUBCOMMAND_VERBS.machine.includes(verb))usageError(`unknown verb "${verb}"`);if(verb==="list")return list();if(verb==="add")return await add(rest);if(verb==="doctor")return await doctor(rest);if(verb==="update")return await update(rest);if(verb==="remove")return remove(rest);if(verb==="tunnel")return tunnel(rest);if(verb==="inbound")return inbound(rest);if(verb==="primary")return machinePrimary(rest,usageError);if(verb==="mcp")return machineMcp(rest,fail);usageError(`unknown verb "${verb}"`)}async function add(argv){let target=positionalOf(argv);if(!target)usageError("add needs an ssh target, e.g. `machine add narwhal`");let parsed=parseSshTarget(target);if(!parsed)usageError(`"${target}" is not a valid ssh target ([user@]host[:port])`);let portFlag=flagValue(argv,"port"),port=portFlag?Number(portFlag):parsed.port;if(port!==void 0&&(!Number.isInteger(port)||port<1||port>65535))usageError("--port must be 1-65535");let identity=flagValue(argv,"identity"),requested=flagValue(argv,"alias");if(requested&&!isValidMachineAlias(requested))usageError(`--alias must be letters/digits/._- and cannot be "local" (got "${requested}")`);let probeAlias=requested??sanitizeAlias(parsed.host),config={host:parsed.host,...parsed.user?{user:parsed.user}:{},...port?{port}:{},auth:identity?{kind:"key",keyPath:identity}:{kind:"key"}};await confirmHostKey(config),process.stderr.write(`${CLI_NAME} machine: contacting ${sshTargetOf(config)}\u2026
|
|
21
25
|
`);let established=await establishMachine(probeAlias,config,setupRuntime(argv));if(!established.ok)fail("nothing was saved");let{found,config:settled}=established,alias=requested??defaultMachineAlias({typedHost:parsed.host,typedUser:parsed.user,port,remoteHostname:found.status.hostname});if(!isValidMachineAlias(alias))fail(`could not derive a usable alias from "${found.status.hostname}" \u2014 pass --alias`);let identityTriple={hostname:found.status.hostname,homeDir:found.status.homeDir,daemonPid:found.status.daemonPid},duplicate=duplicateAliasOf(readMachines(loadStateFile()),alias,identityTriple),learned=learnedFrom(found),sockets=learned.sockets;if(found.roveBin)process.stderr.write(`${CLI_NAME} machine: rove is not on ${alias}'s non-interactive PATH; using ${found.roveBin}
|
|
22
|
-
`);addMachine(alias,{...settled,...learned,identity:identityTriple}),setMachineIdentity(alias,identityTriple);let{ensureForwards}=await import("./chunk-
|
|
26
|
+
`);addMachine(alias,{...settled,...learned,identity:identityTriple}),setMachineIdentity(alias,identityTriple);let{ensureForwards}=await import("./chunk-9892j1n1.js"),up=await ensureForwards({alias,config:{...settled,...learned},remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(process.stdout.write(`${CLI_NAME} machine: ${alias} \u2192 ${sshTargetOf(settled)} (rove ${found.status.roveVersion||"?"} on ${found.status.hostname||"?"})
|
|
23
27
|
`),!up)process.stderr.write(`${CLI_NAME} machine: registered, but could not forward ${alias}'s socket yet \u2014 it will show as offline until the connection comes up
|
|
24
28
|
`);if(duplicate)process.stdout.write(`${CLI_NAME} machine: ${alias} is the same machine as ${duplicate} (hostname/homeDir/pid match) \u2014 the sidebar shows one row
|
|
25
29
|
`)}function setupRuntime(argv){let yes=argv.includes("--yes"),fixRuntime=defaultFixRuntime();return{confirm:fixRuntime.confirm,exec:fixRuntime.exec,out:(line)=>process.stderr.write(`${line}
|
|
26
30
|
`),ask:!yes,planOnly:!yes&&process.stdin.isTTY!==!0}}async function doctor(argv){let alias=positionalOf(argv),entries=listMachines().filter((m)=>!alias||m.alias===alias);if(alias&&entries.length===0)fail(`no machine named "${alias}" (see \`${CLI_NAME} machine list\`)`);if(entries.length===0){process.stdout.write(`No machines registered. Add one with \`${CLI_NAME} machine add <ssh-target>\`.
|
|
27
|
-
`);return}let rt=setupRuntime(argv),{ensureForwards}=await import("./chunk-
|
|
31
|
+
`);return}let rt=setupRuntime(argv),{ensureForwards}=await import("./chunk-9892j1n1.js"),failed=0;for(let{alias:name,...config}of entries){process.stderr.write(`${CLI_NAME} machine: checking ${name} (${sshTargetOf(config)})\u2026
|
|
28
32
|
`);let established=await establishMachine(name,config,rt);if(!established.ok){failed++,process.stdout.write(`${name} \u2717 ${established.failure.code}
|
|
29
33
|
`);continue}let{found}=established,learned=learnedFrom(found),sockets=learned.sockets,settled={...established.config,...learned};updateMachine(name,settled);let up=await ensureForwards({alias:name,config:settled,remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty}),version=found.status.roveVersion||"?",skew=version!==CURRENT_VERSION?` (this machine runs ${CURRENT_VERSION})`:"";process.stdout.write(`${name} ${up?"\u2713":"\u2717 socket not forwarded"} rove ${version}${skew} on ${found.status.hostname||"?"}
|
|
30
34
|
`);for(let note of await doctorNotes(name,settled,found))process.stdout.write(` ${note}
|
|
31
35
|
`);if(!up)failed++}if(failed>0)process.exitCode=1}async function update(argv){let alias=positionalOf(argv),entries=dedupeMachines(listMachines()).filter((m)=>!alias||m.alias===alias);if(alias&&entries.length===0)fail(`no machine named "${alias}" (see \`${CLI_NAME} machine list\`)`);if(entries.length===0){process.stdout.write(`No machines registered. Add one with \`${CLI_NAME} machine add <ssh-target>\`.
|
|
32
|
-
`);return}let{upgradeMachine}=await import("./chunk-
|
|
36
|
+
`);return}let{upgradeMachine}=await import("./chunk-me70fpec.js"),failed=0;for(let entry of entries){process.stderr.write(`${CLI_NAME} machine: updating ${entry.alias} (${sshTargetOf(entry)})\u2026
|
|
33
37
|
`);try{let done=await upgradeMachine(entry),now=done.to??"?",skew=now!==CURRENT_VERSION?` (this machine runs ${CURRENT_VERSION})`:"";process.stdout.write(done.changed?`${entry.alias} \u2713 rove ${done.from??"?"} \u2192 ${now}${skew}
|
|
34
38
|
`:`${entry.alias} \u2713 already on rove ${now}${skew}
|
|
35
39
|
`)}catch(err){failed++,process.stdout.write(`${entry.alias} \u2717 ${err instanceof Error?err.message:String(err)}
|