@sma1lboy/rove 0.9.298 → 0.9.299-next.350

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/cli/{chunk-2dqehs3f.js → chunk-0rej9424.js} +1 -1
  2. package/dist/cli/{chunk-8yy7fc41.js → chunk-1hnbnxhe.js} +2 -2
  3. package/dist/cli/{chunk-39vztkqm.js → chunk-28tvafwq.js} +1 -1
  4. package/dist/cli/{chunk-r6saf9dt.js → chunk-3zwsswac.js} +1 -1
  5. package/dist/cli/{chunk-fv7spng6.js → chunk-4wbfjryf.js} +1 -1
  6. package/dist/cli/{chunk-8589r785.js → chunk-5b82kjq0.js} +1 -1
  7. package/dist/cli/{chunk-9ebvw6eg.js → chunk-644ccxmv.js} +1 -1
  8. package/dist/cli/{chunk-mbdkgrrf.js → chunk-6d4hv0hf.js} +1 -1
  9. package/dist/cli/{chunk-0zq1tbqv.js → chunk-6k4j9ytr.js} +2 -2
  10. package/dist/cli/{chunk-qrw7kvmq.js → chunk-6rr7kymr.js} +1 -1
  11. package/dist/cli/{chunk-w4vdwk7e.js → chunk-8neqhjcv.js} +1 -1
  12. package/dist/cli/{chunk-b7pd9z99.js → chunk-8q862yj3.js} +1 -1
  13. package/dist/cli/{chunk-19qr6bav.js → chunk-8t96facn.js} +2 -2
  14. package/dist/cli/{chunk-tgwmatng.js → chunk-9bw1f9bd.js} +1 -1
  15. package/dist/cli/{chunk-xs9hq40h.js → chunk-9dkhhbsq.js} +1 -1
  16. package/dist/cli/{chunk-ass6nz7y.js → chunk-9p688s60.js} +1 -1
  17. package/dist/cli/{chunk-2krjdb8e.js → chunk-acqm3741.js} +1 -1
  18. package/dist/cli/{chunk-tybkb1fg.js → chunk-btyf688g.js} +1 -1
  19. package/dist/cli/{chunk-rf3crfe7.js → chunk-c8dv6zb8.js} +1 -1
  20. package/dist/cli/{chunk-8819htkr.js → chunk-cr1sewh0.js} +1 -1
  21. package/dist/cli/{chunk-j1sqakvq.js → chunk-ct7zwqhe.js} +1 -1
  22. package/dist/cli/{chunk-9r2asvyg.js → chunk-ctvxh4z3.js} +1 -1
  23. package/dist/cli/{chunk-je72jjg7.js → chunk-dc1bdnht.js} +1 -1
  24. package/dist/cli/{chunk-axtdwfmc.js → chunk-dj9q2n51.js} +1 -1
  25. package/dist/cli/{chunk-6r295bx7.js → chunk-drjb1574.js} +1 -1
  26. package/dist/cli/{chunk-tk7vt5ma.js → chunk-f23sj7ca.js} +1 -1
  27. package/dist/cli/{chunk-kjjeqr7q.js → chunk-f2ext04j.js} +2 -2
  28. package/dist/cli/{chunk-e7jd88yf.js → chunk-f6wry6k9.js} +1 -1
  29. package/dist/cli/{chunk-24a47bhn.js → chunk-fkfkpq8j.js} +1 -1
  30. package/dist/cli/{chunk-kbqy98n7.js → chunk-gqy4qy6x.js} +1 -1
  31. package/dist/cli/{chunk-tkbsw9yh.js → chunk-hpdyr0hc.js} +1 -1
  32. package/dist/cli/{chunk-wxhy3jtn.js → chunk-k5pa9a14.js} +1 -1
  33. package/dist/cli/{chunk-jrkwfnc4.js → chunk-kpqpjyz4.js} +1 -1
  34. package/dist/cli/{chunk-3evhqh88.js → chunk-kxhvgkv8.js} +1 -1
  35. package/dist/cli/{chunk-hg63k0fr.js → chunk-n5ax8ybp.js} +1 -1
  36. package/dist/cli/{chunk-0g1m2028.js → chunk-px6gfeqj.js} +1 -1
  37. package/dist/cli/{chunk-befzgpr5.js → chunk-r59vb238.js} +1 -1
  38. package/dist/cli/{chunk-0gfzxgyk.js → chunk-se3eb4gr.js} +1 -1
  39. package/dist/cli/{chunk-g2sv686y.js → chunk-t121qjfy.js} +1 -1
  40. package/dist/cli/chunk-txer3py2.js +3 -0
  41. package/dist/cli/{chunk-f1nt5hgz.js → chunk-v3nehs05.js} +1 -1
  42. package/dist/cli/{chunk-n9d8jvk0.js → chunk-v80k4mmn.js} +1 -1
  43. package/dist/cli/{chunk-pstbvztv.js → chunk-vsy6m1w1.js} +1 -1
  44. package/dist/cli/{chunk-m517kk34.js → chunk-z66cjwsm.js} +5 -5
  45. package/dist/cli/{chunk-kk1kgzmt.js → chunk-zsnaz3gw.js} +1 -1
  46. package/dist/cli/{chunk-2e6b866m.js → chunk-zz99wtfr.js} +1 -1
  47. package/dist/cli/index.js +2 -2
  48. package/dist/cli/rove.js +3 -3
  49. package/dist/web/assets/index-CypS69AH.js +83 -0
  50. package/dist/web/assets/index-rzwi8QsB.css +1 -0
  51. package/dist/web/assets/{term-mount-Bl4ANEVH.js → term-mount-7l6RWJFo.js} +1 -1
  52. package/dist/web/index.html +2 -2
  53. package/dist/web/relay/index.html +2 -2
  54. package/package.json +1 -1
  55. package/dist/cli/chunk-rmx8jrcj.js +0 -3
  56. package/dist/web/assets/index-Cqsf4NxE.js +0 -83
  57. package/dist/web/assets/index-DhgJsv9c.css +0 -1
@@ -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,ZEN_ACTIVE_KEY,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-3kfwrpjf.js";import{$Fragment,$jsx,$jsxs,createRoot2,flushSync2,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import{RemoteOrchestrator}from"./chunk-3evhqh88.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{updaterShell,updaterShellFailureHint}from"./chunk-9ebvw6eg.js";import{CURRENT_VERSION}from"./chunk-rmx8jrcj.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,applyDisplayOverlay,readPersistedUiPrefs,resolveTheme,resolveThemeMode}from"./chunk-xvr8g6jc.js";import{loadUserThemes}from"./chunk-gzn14mwk.js";import{TERMINAL_TABS_PREFIX}from"./chunk-dvpjthdf.js";import{tildify}from"./chunk-1feav1w3.js";import{isLocaleId,localeState,setLocaleLang,t}from"./chunk-7y9dy9sa.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-cmp64q4j.js";import{connectIfRunning}from"./chunk-3spvd3vw.js";import{loadStateFile,readStateFileStrict,replaceStateFile,updateStateFile}from"./chunk-8trtyc98.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&&currentPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}var 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 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 WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,ZEN_ACTIVE_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();for(let key of Object.keys(updated))quiet.delete(key);if(Object.keys(updated).length>0)store2.update((snapshot)=>{let next={...snapshot};for(let[key,value]of Object.entries(updated))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))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){let next=mutate(quiet.has(key)?quiet.get(key):store2.get()[key]),pending=pendingUpdates.get(key)??[];pendingUpdates.set(key,[...pending,mutate]),dirtyKeys.delete(key),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);function isNarrowWidth(cols){return cols<70}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)})}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,ZEN_ACTIVE_KEY,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-3kfwrpjf.js";import{$Fragment,$jsx,$jsxs,createRoot2,flushSync2,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import{RemoteOrchestrator}from"./chunk-kxhvgkv8.js";import{isUnpublishedStateKey}from"./chunk-cpgnm1xr.js";import{updaterShell,updaterShellFailureHint}from"./chunk-644ccxmv.js";import{CURRENT_VERSION}from"./chunk-txer3py2.js";import{BUNDLED_THEMES,DEFAULT_THEME,DEFAULT_THEME_MODE,applyDisplayOverlay,readPersistedUiPrefs,resolveTheme,resolveThemeMode}from"./chunk-xvr8g6jc.js";import{loadUserThemes}from"./chunk-gzn14mwk.js";import{TERMINAL_TABS_PREFIX}from"./chunk-dvpjthdf.js";import{tildify}from"./chunk-1feav1w3.js";import{isLocaleId,localeState,setLocaleLang,t}from"./chunk-7y9dy9sa.js";import{createStateCell,profileMark,profileTick,recentStateChangesForDiagnostics,renderProfileOn}from"./chunk-cmp64q4j.js";import{connectIfRunning}from"./chunk-3spvd3vw.js";import{loadStateFile,readStateFileStrict,replaceStateFile,updateStateFile}from"./chunk-8trtyc98.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&&currentPrefixConfiguration().key===null)continue;if(binding.yieldToPassthrough&&passthrough)continue;let chord=`${binding.prefix===!0}:${binding.key}`;if(seen.has(chord))continue;if(seen.add(chord),binding.id&&binding.action)actions.push({owner:registration.id,binding})}if(config.modal)break}return actions}function capturePaletteActions(stack){let seen=new Set;return availableActions(stack).flatMap(({owner,binding})=>{let id=binding.id;if(!id||id==="palette.open"||seen.has(id))return[];return seen.add(id),[{id,key:binding.key,prefix:binding.prefix===!0,run:()=>{let live=availableActions(stack).find((entry)=>entry.owner===owner&&entry.binding.id===id&&entry.binding.key===binding.key&&entry.binding.prefix===binding.prefix);if(!live?.binding.action)return!1;return live.binding.action.run(),!0}}]})}var 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 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 WRITE_DEBOUNCE_MS=250,PER_WINDOW_KEYS=new Set([SIDEBAR_COLLAPSED_KEY,SIDEBAR_WIDTH_KEY,ZEN_ACTIVE_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();for(let key of Object.keys(updated))quiet.delete(key);if(Object.keys(updated).length>0)store2.update((snapshot)=>{let next={...snapshot};for(let[key,value]of Object.entries(updated))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))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){let next=mutate(quiet.has(key)?quiet.get(key):store2.get()[key]),pending=pendingUpdates.get(key)??[];pendingUpdates.set(key,[...pending,mutate]),dirtyKeys.delete(key),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);function isNarrowWidth(cols){return cols<70}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)})}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,9 +1,9 @@
1
1
  // @bun
2
- import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,stopTaskEngineTabAdapter,tearDownTaskSessionAdapter}from"./chunk-nmjnk2rg.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{Orchestrator}from"./chunk-vcn8ktz9.js";import{GH_PR_VIEW_FIELDS,classifyGhFailure,mapGhPrView,nextPrPoll,samePrStatus}from"./chunk-ybwqj9mp.js";import"./chunk-n8z4nb8v.js";import{GitWorktreeManager,parseDirtyPaths}from"./chunk-4gt29avz.js";import"./chunk-4rebycv9.js";import"./chunk-4dt1gfb3.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{startChatChannels}from"./chunk-axtdwfmc.js";import{auditDeletionBranchKept,auditDeletionResidue,auditDeletionSalvaged,auditWorktreeResidue,auditWorktreeSalvaged,parseAheadBehind,startDaemonServer}from"./chunk-h0nd99vq.js";import"./chunk-vdgtsda7.js";import"./chunk-a4hsqj1b.js";import"./chunk-m2bb81cp.js";import"./chunk-rmnm3f9n.js";import{refreshOutdatedSkills}from"./chunk-5qz5h54p.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{cancelAllLogins}from"./chunk-rset5pt8.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import{affectsActivityState,isEngineActivityKind}from"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel,updateDelayHours}from"./chunk-kk1kgzmt.js";import"./chunk-jdfz6n5s.js";import{RELAY_PREAMBLE}from"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import{TaskIndexStore}from"./chunk-w2g26k38.js";import"./chunk-qkehg2c1.js";import"./chunk-eaav6ajz.js";import"./chunk-xxz504p6.js";import{parsePorcelain}from"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import{DEFAULT_BASE_REF_CANDIDATES,readHeadSha,readRefSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import"./chunk-xmwp6je4.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion}from"./chunk-rmx8jrcj.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import{installDaemonCrashHandlers,logDaemonError,logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import{autoStatusEnabled,protocolUpgradeFromLiveSession,protocolWriteBackFromLiveSession}from"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import{engineDisplayName,engineProtocolKey,protocolEntry,roveApiInvocation,sessionProtocol}from"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import{teardownScope}from"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import{stateFileTabsPersistence}from"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import{execHostForWorktreePath}from"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag,switchFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-1dxpkpqv.js";import{createEngineTurnDetector,engineEntry,engineTitleTurnHint,spawnCapture,vendorsWithQuotaProbe}from"./chunk-76gh55cc.js";import{availableEngineIds}from"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import{daemonSpawnReason,restartDaemon}from"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import{RoveDaemonClient}from"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import{backfillSavedReposFromProjects,getCustomEngineIds,getPersistedString,getRemoteRepoConfig,getSavedRepos,setPersistedString}from"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.js";import{rotateLogIfNeeded}from"./chunk-y8hjgmn0.js";import{DEFAULT_TASK_VENDOR,isTaskStatus}from"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import{migrateRoveDaemonStateLayout}from"./chunk-m5nd44st.js";import{releaseSync}from"./chunk-jt9n8k7z.js";import{isProcessAlive,readPidFile}from"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}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-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";async function latestTranscriptMtime(vendor,worktree){if(!worktree)return 0;return protocolEntry(vendor).history.latestTranscriptMtimeForWorktree(worktree)}async function maybeAutoStart(orch,taskId,enabled=autoStatusEnabled){if(!enabled())return"skipped";let task=orch.getTask(taskId);if(!task)return"skipped";if(task.status!=="backlog")return"skipped";return await orch.setStatus(taskId,"in_progress"),"moved"}var SYNC_TIMEOUT_MS=60000,SYNC_CONFLICT="SYNC_CONFLICT",SYNC_DIRTY="SYNC_WORKTREE_DIRTY";async function git(cwd,args,signal,write=!1){return spawnCapture("git",args,{cwd,env:write?process.env:readOnlyGitProcessEnv(),signal})}function parseConflictedPaths(stdout){return stdout.split(`
2
+ import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,stopTaskEngineTabAdapter,tearDownTaskSessionAdapter}from"./chunk-nmjnk2rg.js";import{buildCIPromptForWorktree}from"./chunk-vkz6kkmm.js";import{Orchestrator}from"./chunk-vcn8ktz9.js";import{GH_PR_VIEW_FIELDS,classifyGhFailure,mapGhPrView,nextPrPoll,samePrStatus}from"./chunk-ybwqj9mp.js";import"./chunk-n8z4nb8v.js";import{GitWorktreeManager,parseDirtyPaths}from"./chunk-4gt29avz.js";import"./chunk-4rebycv9.js";import"./chunk-4dt1gfb3.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{startChatChannels}from"./chunk-dj9q2n51.js";import{auditDeletionBranchKept,auditDeletionResidue,auditDeletionSalvaged,auditWorktreeResidue,auditWorktreeSalvaged,parseAheadBehind,startDaemonServer}from"./chunk-h0nd99vq.js";import"./chunk-vdgtsda7.js";import"./chunk-a4hsqj1b.js";import"./chunk-m2bb81cp.js";import"./chunk-rmnm3f9n.js";import{refreshOutdatedSkills}from"./chunk-5qz5h54p.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import{cancelAllLogins}from"./chunk-rset5pt8.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import{affectsActivityState,isEngineActivityKind}from"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel,updateDelayHours}from"./chunk-zsnaz3gw.js";import"./chunk-jdfz6n5s.js";import{RELAY_PREAMBLE}from"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import{TaskIndexStore}from"./chunk-w2g26k38.js";import"./chunk-qkehg2c1.js";import"./chunk-eaav6ajz.js";import"./chunk-xxz504p6.js";import{parsePorcelain}from"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import{DEFAULT_BASE_REF_CANDIDATES,readHeadSha,readRefSha,resolveGitDirs}from"./chunk-kg9kmwt9.js";import"./chunk-xmwp6je4.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion}from"./chunk-txer3py2.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import{installDaemonCrashHandlers,logDaemonError,logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import{autoStatusEnabled,protocolUpgradeFromLiveSession,protocolWriteBackFromLiveSession}from"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import{engineDisplayName,engineProtocolKey,protocolEntry,roveApiInvocation,sessionProtocol}from"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import{teardownScope}from"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import{stateFileTabsPersistence}from"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import{execHostForWorktreePath}from"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag,switchFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-1dxpkpqv.js";import{createEngineTurnDetector,engineEntry,engineTitleTurnHint,spawnCapture,vendorsWithQuotaProbe}from"./chunk-76gh55cc.js";import{availableEngineIds}from"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import{daemonSpawnReason,restartDaemon}from"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import{RoveDaemonClient}from"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import{backfillSavedReposFromProjects,getCustomEngineIds,getPersistedString,getRemoteRepoConfig,getSavedRepos,setPersistedString}from"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.js";import{rotateLogIfNeeded}from"./chunk-y8hjgmn0.js";import{DEFAULT_TASK_VENDOR,isTaskStatus}from"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import{migrateRoveDaemonStateLayout}from"./chunk-m5nd44st.js";import{releaseSync}from"./chunk-jt9n8k7z.js";import{isProcessAlive,readPidFile}from"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}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-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";async function latestTranscriptMtime(vendor,worktree){if(!worktree)return 0;return protocolEntry(vendor).history.latestTranscriptMtimeForWorktree(worktree)}async function maybeAutoStart(orch,taskId,enabled=autoStatusEnabled){if(!enabled())return"skipped";let task=orch.getTask(taskId);if(!task)return"skipped";if(task.status!=="backlog")return"skipped";return await orch.setStatus(taskId,"in_progress"),"moved"}var SYNC_TIMEOUT_MS=60000,SYNC_CONFLICT="SYNC_CONFLICT",SYNC_DIRTY="SYNC_WORKTREE_DIRTY";async function git(cwd,args,signal,write=!1){return spawnCapture("git",args,{cwd,env:write?process.env:readOnlyGitProcessEnv(),signal})}function parseConflictedPaths(stdout){return stdout.split(`
3
3
  `).map((line)=>line.trim()).filter((line)=>line.length>0)}async function syncWorktreeWithBase(worktreePath,baseRef,signal){let status=await git(worktreePath,["status","--porcelain=v1"],signal);if(status.status!==0)throw Error("git status failed");let dirty=parseDirtyPaths(status.stdout);if(dirty.length>0)throw Error(`${SYNC_DIRTY}: ${dirty.join(", ")}`);let before=await git(worktreePath,["rev-parse","HEAD"],signal),merge=await git(worktreePath,["merge","--no-edit",baseRef],signal,!0);if(merge.status!==0){let conflicted=await git(worktreePath,["diff","--name-only","--diff-filter=U"],signal),paths=parseConflictedPaths(conflicted.stdout);if(paths.length>0)throw Error(`${SYNC_CONFLICT}: ${paths.join(", ")}`);let detail=merge.stderr?.trim();throw Error(detail?`git merge ${baseRef} failed \u2014 ${detail}`:`git merge ${baseRef} failed`)}let after=await git(worktreePath,["rev-parse","HEAD"],signal);return{baseRef,alreadyCurrent:before.status===0&&before.stdout.trim()===after.stdout.trim()}}import{readFileSync}from"fs";import{join}from"path";var BASE_REF_TTL_MS=300000,cache=new Map;async function git2(worktreePath,args,signal){return await spawnCapture("git",[...args],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal})}async function refExists(worktreePath,ref,signal){return(await git2(worktreePath,["rev-parse","--verify","--quiet",ref],signal)).status===0}async function sharesHistory(worktreePath,ref,signal){return(await git2(worktreePath,["merge-base",ref,"HEAD"],signal)).status===0}async function baseCheckoutBranchFromGit(worktreePath,signal){let out=await git2(worktreePath,["worktree","list","--porcelain"],signal);if(out.status!==0)return null;return(out.stdout.split(`
4
4
 
5
5
  `,1)[0]??"").split(`
6
- `).find((l)=>l.startsWith("branch "))?.slice(7).trim().replace(/^refs\/heads\//,"")||null}function readRefSymbolic(dirs,ref){for(let dir of[dirs.gitDir,dirs.commonDir])try{let target=readFileSync(join(dir,ref),"utf8").trim().match(/^ref:\s*(.+)$/)?.[1]?.trim();if(target)return target}catch{}return null}function ladderFromFiles(worktreePath){let dirs=resolveGitDirs(worktreePath);if(!dirs)return;let originHead=readRefSymbolic(dirs,"refs/remotes/origin/HEAD")?.replace(/^refs\/remotes\//,""),baseCheckout=readRefSymbolic({gitDir:dirs.commonDir,commonDir:dirs.commonDir},"HEAD")?.replace(/^refs\/heads\//,""),names=[],head=readHeadSha(dirs),parts=[`HEAD=${head}`];for(let guess of[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]]){if(names.includes(guess))continue;let sha=readRefSha(dirs,guess);if(sha===null)continue;names.push(guess),parts.push(`${guess}=${sha}`)}return{names,fingerprint:head===null?null:parts.join(",")}}async function ladderFromGit(worktreePath,signal){let head=await git2(worktreePath,["symbolic-ref","--short","refs/remotes/origin/HEAD"],signal),originHead=head.status===0?head.stdout.trim():"",baseCheckout=await baseCheckoutBranchFromGit(worktreePath,signal),names=[],candidates=[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]];for(let guess of candidates){if(names.includes(guess))continue;if(await refExists(worktreePath,guess,signal))names.push(guess)}return{names,fingerprint:null}}async function resolveBaseRefCached(worktreePath,recordedBaseRef,signal,now=Date.now()){if(recordedBaseRef){let dirs=resolveGitDirs(worktreePath);if(dirs&&readRefSha(dirs,recordedBaseRef)!==null)return recordedBaseRef;if(await refExists(worktreePath,recordedBaseRef,signal))return recordedBaseRef}let hit=cache.get(worktreePath);if(hit&&now-hit.at<BASE_REF_TTL_MS)return hit.ref;let ladder=ladderFromFiles(worktreePath)??await ladderFromGit(worktreePath,signal);if(hit&&ladder.fingerprint!==null&&hit.fingerprint===ladder.fingerprint)return cache.set(worktreePath,{...hit,at:now}),hit.ref;let ref=null;for(let candidate of ladder.names)if(await sharesHistory(worktreePath,candidate,signal)){ref=candidate;break}return cache.set(worktreePath,{ref,at:now,fingerprint:ladder.fingerprint}),ref}var cache2=new Map;function readShas(worktreePath,baseRef){let dirs=resolveGitDirs(worktreePath);if(!dirs)return null;let head=readHeadSha(dirs),base=readRefSha(dirs,baseRef);return head&&base?{head,base}:null}async function driftCached(worktreePath,baseRef,compute){let shas=readShas(worktreePath,baseRef),hit=shas?cache2.get(worktreePath):void 0;if(shas&&hit&&hit.head===shas.head&&hit.base===shas.base)return hit.value;let value=await compute();if(shas&&value!==null)cache2.set(worktreePath,{...shas,value});return value}import{statSync}from"fs";function judgeWorktree(signals,nowMs){if(signals.dirty)return{verdict:"active",reason:"dirty"};if(signals.prState==="open")return{verdict:"active",reason:"prOpen"};if(signals.prState==="merged")return{verdict:"merged",reason:"prMerged"};if(signals.aheadOfDefault===0)return{verdict:"merged",reason:"inMain"};if(signals.prState==="closed")return{verdict:"stale",reason:"prClosed"};if(signals.lastActivityMs>0&&nowMs-signals.lastActivityMs>1209600000)return{verdict:"stale",reason:"idle"};return{verdict:"fresh",reason:"fresh"}}function parseGhPrList(stdout){let entries;try{entries=JSON.parse(stdout)}catch{return null}if(!Array.isArray(entries))return null;let rank={open:3,merged:2,closed:1},map=new Map;for(let entry of entries){let branch=entry?.headRefName,rawState=entry?.state;if(typeof branch!=="string"||typeof rawState!=="string")continue;let state=rawState.toLowerCase();if(state!=="open"&&state!=="merged"&&state!=="closed")continue;let cur=map.get(branch);if(!cur||rank[state]>rank[cur])map.set(branch,state)}return map}var TIMEOUT_MS=4000,manager=new GitWorktreeManager;function createdAt(path){try{let stat=statSync(path);return stat.birthtimeMs||stat.mtimeMs}catch{return 0}}async function run(path,argv){return execHostForWorktreePath(path).run(argv,{cwd:path,signal:AbortSignal.timeout(TIMEOUT_MS)})}async function branchOnRemote(path,branch){try{let out=await run(path,["git","ls-remote","--exit-code","--heads","origin",branch]);return out.exitCode===0?!0:out.exitCode===2?!1:null}catch{return null}}async function defaultRef(repo){try{let out=await run(repo,["git","symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(out.exitCode===0&&out.stdout.trim())return out.stdout.trim()}catch{}for(let guess of["origin/main","origin/master"])try{if((await run(repo,["git","rev-parse","--verify","--quiet",guess])).exitCode===0)return guess}catch{}return null}async function prStates(repo){try{let origin=await run(repo,["git","remote","get-url","origin"]);if(origin.exitCode!==0||!origin.stdout.includes("github.com"))return null;let out=await run(repo,["gh","pr","list","--state","all","--limit","200","--json","headRefName,state"]);return out.exitCode===0?parseGhPrList(out.stdout):null}catch{return null}}async function ahead(path,ref){if(!ref)return null;try{let out=await run(path,["git","rev-list","--count",`${ref}..HEAD`]),value=Number.parseInt(out.stdout.trim(),10);return out.exitCode===0&&!Number.isNaN(value)?value:null}catch{return null}}async function listWorktreeProjectsAdapter(network){let repos=getSavedRepos().filter((repo)=>!getRemoteRepoConfig(repo)),now=Date.now();return Promise.all(repos.map(async(repo)=>{let[worktrees,states,ref]=await Promise.all([manager.listAll(repo),network?prStates(repo):null,defaultRef(repo)]),rows=await Promise.all(worktrees.map(async(worktree)=>{let[remote,aheadBy]=await Promise.all([network?branchOnRemote(worktree.path,worktree.branch):null,ahead(worktree.path,ref)]),judgement=judgeWorktree({dirty:worktree.dirty===!0,prState:states?.get(worktree.branch)??null,aheadOfDefault:aheadBy,lastActivityMs:worktree.lastActivityMs},now);return{...worktree,repo,createdAtMs:createdAt(worktree.path),branchOnRemote:remote,verdict:judgement.verdict,verdictReason:judgement.reason}}));return{repo,worktrees:rows}}))}async function listUnreadableWorktreesAdapter(repo){return manager.listUnreadableWorktrees(repo)}async function removeWorktreeAdapter(path,force){let residue=null;return await manager.remove(path,{force,onSalvage:(record)=>{if(record)auditWorktreeSalvaged(path,record.ref,record.commit,record.uncaptured)},onResidue:(r)=>{residue={path:r.path,reason:r.reason},auditWorktreeResidue(r.path,r.reason)}}),residue}function resolveProtocolUpgradeAndLearnPreset(task,evidence){let preset=protocolWriteBackFromLiveSession(task,evidence,getCustomEngineIds());if(preset)setPersistedString(engineProtocolKey(preset.id),preset.protocol);return protocolUpgradeFromLiveSession(task,evidence)}var daemonRuntime={currentVersion:CURRENT_VERSION,tabsPersistence:stateFileTabsPersistence,startMachineHub(bus){let stop=null,stopped=!1;return import("./chunk-9r2asvyg.js").then(({startDaemonMachineHub})=>{if(!stopped)stop=startDaemonMachineHub(bus)}),()=>{stopped=!0,stop?.()}},async invokeApi(verb,params,socketPath,route){let[{executeVerb,errorEnvelope},{daemonCaller},{RoveDaemonClient:RoveDaemonClient2}]=await Promise.all([import("./chunk-wxhy3jtn.js"),import("./chunk-mvfg1593.js"),import("./chunk-db0kdm4z.js")]);if(route?.forwarded){let{inboundRefusal}=await import("./chunk-n9d8jvk0.js"),denied=inboundRefusal(verb);if(denied){let{ApiError}=await import("./chunk-mvfg1593.js");return errorEnvelope(new ApiError(`this machine refuses "${denied}" verbs from other machines (${verb} from ${route.from??"a hub"})`,"INBOUND_DENIED",{hint:`on this machine: rove machine inbound allow ${denied}`}))}}let client=new RoveDaemonClient2(socketPath);try{await client.connect();let{invokeRouted}=await import("./chunk-vdy1s9ge.js");return await invokeRouted({verb,params,machine:route?.machine,forwarded:route?.forwarded,isLocalTask:(id)=>client.request("task.get",{taskId:id}).then(()=>!0,()=>!1),runHere:(p)=>executeVerb(verb,{params:p},{client,caller:daemonCaller(route?.forwarded===!0)})})}catch(err){return errorEnvelope(err)}finally{client.close()}},defaultTaskVendor:DEFAULT_TASK_VENDOR,placeholderTaskTitle:PLACEHOLDER_TASK_TITLE,isTaskStatus,isEngineActivityKind,affectsActivityState,async foregroundEngines(pids){let rows=parsePsSnapshot(await psSnapshot([...pids])),out=new Map;for(let pid of pids){let found=foregroundEngineIn(rows,pid);out.set(pid,found?{vendor:found.vendor,pid:found.pid}:null)}return out},titleTurnHint:(vendor,title)=>engineTitleTurnHint(sessionProtocol(vendor),title),sessionProtocol,resolveProtocolUpgrade:resolveProtocolUpgradeAndLearnPreset,readEngineTurns:async(vendor,transcriptPath)=>await protocolEntry(vendor).readTurns?.(transcriptPath)??[],checkLatestVersion:()=>{let state=loadStateFile();return checkLatestVersion({channel:preferredReleaseChannel(state),minAgeHours:updateDelayHours(state)})},latestTranscriptMtime,deriveTitleFromSession,deriveTitleFromSessionId,createEngineTurnDetector:(vendor)=>createEngineTurnDetector(sessionProtocol(vendor)),async runWorktreeStatus(worktreePath,signal,baseRef){let result=await spawnCapture("git",["status","--porcelain=v1"],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});if(result.status!==0)throw Error("git status failed");let counts=parsePorcelain(result.stdout),base=await resolveBaseRefCached(worktreePath,baseRef,signal);if(!base)return counts;let drift=await driftCached(worktreePath,base,async()=>{let out=await spawnCapture("git",["rev-list","--left-right","--count",`${base}...HEAD`],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});return out.status===0?parseAheadBehind(out.stdout):null});return drift===null?counts:{...counts,...drift}},maybeAutoStart:(orch,taskId)=>maybeAutoStart(orch,taskId),listWorktreeProjects:listWorktreeProjectsAdapter,listUnreadableWorktrees:listUnreadableWorktreesAdapter,removeWorktree:removeWorktreeAdapter,async syncWorktreeWithBase(worktreePath,recordedBaseRef){let controller=new AbortController,timer=setTimeout(()=>controller.abort(),SYNC_TIMEOUT_MS);try{let baseRef=await resolveBaseRefCached(worktreePath,recordedBaseRef,controller.signal);if(!baseRef)throw Error("no base ref resolves for this worktree");return await syncWorktreeWithBase(worktreePath,baseRef,controller.signal)}finally{clearTimeout(timer)}},availableEngineIds,engineDisplayName,roveApiInvocation,engineEntry,ensureTaskSession:ensureTaskSessionAdapter,startTaskSessionWithPrompt:startTaskSessionWithPromptAdapter,tearDownTaskSession:tearDownTaskSessionAdapter,stopTaskEngineTab:stopTaskEngineTabAdapter,async readEngineContextUsage(vendor,sessionId){let read=protocolEntry(vendor).history.readUsageSnapshot;if(!read)return null;let snapshot=await read(sessionId);if(snapshot?.context_tokens===void 0)return null;return{contextTokens:snapshot.context_tokens,...snapshot.context_window_tokens===void 0?{}:{contextWindowTokens:snapshot.context_window_tokens},...snapshot.context_tokens_approximate?{approximate:!0}:{},...snapshot.input_tokens===void 0?{}:{inputTokens:snapshot.input_tokens},...snapshot.output_tokens===void 0?{}:{outputTokens:snapshot.output_tokens},...snapshot.cache_read_input_tokens===void 0?{}:{cacheReadTokens:snapshot.cache_read_input_tokens},...snapshot.cache_creation_input_tokens===void 0?{}:{cacheCreationTokens:snapshot.cache_creation_input_tokens},...snapshot.context_parts?{parts:snapshot.context_parts}:{}}},probeEngineContext:async(vendor,sessionId)=>protocolEntry(vendor).history.probeContext?.(sessionId),quotaUsage:(vendor)=>engineEntry(vendor).quotaUsage?.()??Promise.resolve(null),vendorsWithQuotaProbe,deliverPromptToLiveEngine:deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailed:deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailed:deliverPromptToLiveEngineTabDetailedAdapter,getPersistedString,buildCIPrompt:(worktree,state)=>buildCIPromptForWorktree(worktree,state),setPersistedString,getSavedRepos:()=>[...getSavedRepos()],prStatus:{viewFields:GH_PR_VIEW_FIELDS,mapView:(view,at)=>mapGhPrView(view,at),sameStatus:samePrStatus,nextPoll:(outcome,failures,now,config,random)=>nextPrPoll(outcome,failures,now,config,random),classify:classifyGhFailure}};import{homedir}from"os";async function createRoveCore(options={}){let homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),store=new TaskIndexStore({homeDir});await store.load();let worktrees=new GitWorktreeManager,orchestrator=new Orchestrator({store,worktrees,onSalvage:(taskId,salvage,repo)=>auditDeletionSalvaged(String(taskId),salvage.ref,salvage.commit,repo,salvage.uncaptured),onWorktreeResidue:(taskId,residue)=>auditDeletionResidue(String(taskId),residue.path,residue.reason),onBranchKept:(taskId,kept)=>auditDeletionBranchKept(String(taskId),kept.branch,kept.reason),tearDownSession:(taskId)=>tearDownTaskSessionAdapter(String(taskId),teardownScope(store.list(),String(taskId),new Set([String(taskId)])))}),backfilled=backfillSavedReposFromProjects(store.list().filter((task)=>task.fromProjectRow).map((task)=>task.repo));if(backfilled.length>0)console.error(`[rove] added ${backfilled.length} existing project(s) to the new-task picker`);return{homeDir,orchestrator,store,worktrees,async close(){orchestrator.dispose()}}}import{existsSync,readFileSync as readFileSync2,readdirSync,statSync as statSync2,unlinkSync}from"fs";import{join as join2}from"path";var TMP_MAX_AGE_MS=300000;function sweepIndexLeftovers(stateDir,now=Date.now()){let tmp=[],tmpBytes=0,entries;try{entries=readdirSync(stateDir)}catch{return{tmp,tmpBytes,lock:!1}}for(let name of entries){if(!name.startsWith("tasks.json.")||!name.endsWith(".tmp"))continue;let path=join2(stateDir,name);try{let stat=statSync2(path);if(now-stat.mtimeMs<TMP_MAX_AGE_MS)continue;unlinkSync(path),tmp.push(path),tmpBytes+=stat.size}catch{}}return{tmp,tmpBytes,lock:clearStaleLock(join2(stateDir,"tasks.json.lock"))}}function clearStaleLock(lockPath){let holder;try{holder=readFileSync2(lockPath,"utf8").trim()}catch{return!1}let pid=Number.parseInt(holder,10);if(Number.isFinite(pid)&&pid>0&&isProcessAlive(pid))return!1;return releaseSync(lockPath,holder),!existsSync(lockPath)}var CLI_NAME=ROVE_PRODUCT_NAME;function printDaemonUsage(out){out.write([`Usage: ${CLI_NAME} daemon <command>`,"","Commands:"," status Print the running daemon's status JSON (default)"," start Run the daemon in the foreground (this process becomes it)"," --resident: never idle-stop when the last TUI leaves (headless host)"," stop Ask the running daemon to shut down"," restart Stop the daemon (graceful \u2192 SIGTERM \u2192 SIGKILL) and respawn it",""].join(`
6
+ `).find((l)=>l.startsWith("branch "))?.slice(7).trim().replace(/^refs\/heads\//,"")||null}function readRefSymbolic(dirs,ref){for(let dir of[dirs.gitDir,dirs.commonDir])try{let target=readFileSync(join(dir,ref),"utf8").trim().match(/^ref:\s*(.+)$/)?.[1]?.trim();if(target)return target}catch{}return null}function ladderFromFiles(worktreePath){let dirs=resolveGitDirs(worktreePath);if(!dirs)return;let originHead=readRefSymbolic(dirs,"refs/remotes/origin/HEAD")?.replace(/^refs\/remotes\//,""),baseCheckout=readRefSymbolic({gitDir:dirs.commonDir,commonDir:dirs.commonDir},"HEAD")?.replace(/^refs\/heads\//,""),names=[],head=readHeadSha(dirs),parts=[`HEAD=${head}`];for(let guess of[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]]){if(names.includes(guess))continue;let sha=readRefSha(dirs,guess);if(sha===null)continue;names.push(guess),parts.push(`${guess}=${sha}`)}return{names,fingerprint:head===null?null:parts.join(",")}}async function ladderFromGit(worktreePath,signal){let head=await git2(worktreePath,["symbolic-ref","--short","refs/remotes/origin/HEAD"],signal),originHead=head.status===0?head.stdout.trim():"",baseCheckout=await baseCheckoutBranchFromGit(worktreePath,signal),names=[],candidates=[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]];for(let guess of candidates){if(names.includes(guess))continue;if(await refExists(worktreePath,guess,signal))names.push(guess)}return{names,fingerprint:null}}async function resolveBaseRefCached(worktreePath,recordedBaseRef,signal,now=Date.now()){if(recordedBaseRef){let dirs=resolveGitDirs(worktreePath);if(dirs&&readRefSha(dirs,recordedBaseRef)!==null)return recordedBaseRef;if(await refExists(worktreePath,recordedBaseRef,signal))return recordedBaseRef}let hit=cache.get(worktreePath);if(hit&&now-hit.at<BASE_REF_TTL_MS)return hit.ref;let ladder=ladderFromFiles(worktreePath)??await ladderFromGit(worktreePath,signal);if(hit&&ladder.fingerprint!==null&&hit.fingerprint===ladder.fingerprint)return cache.set(worktreePath,{...hit,at:now}),hit.ref;let ref=null;for(let candidate of ladder.names)if(await sharesHistory(worktreePath,candidate,signal)){ref=candidate;break}return cache.set(worktreePath,{ref,at:now,fingerprint:ladder.fingerprint}),ref}var cache2=new Map;function readShas(worktreePath,baseRef){let dirs=resolveGitDirs(worktreePath);if(!dirs)return null;let head=readHeadSha(dirs),base=readRefSha(dirs,baseRef);return head&&base?{head,base}:null}async function driftCached(worktreePath,baseRef,compute){let shas=readShas(worktreePath,baseRef),hit=shas?cache2.get(worktreePath):void 0;if(shas&&hit&&hit.head===shas.head&&hit.base===shas.base)return hit.value;let value=await compute();if(shas&&value!==null)cache2.set(worktreePath,{...shas,value});return value}import{statSync}from"fs";function judgeWorktree(signals,nowMs){if(signals.dirty)return{verdict:"active",reason:"dirty"};if(signals.prState==="open")return{verdict:"active",reason:"prOpen"};if(signals.prState==="merged")return{verdict:"merged",reason:"prMerged"};if(signals.aheadOfDefault===0)return{verdict:"merged",reason:"inMain"};if(signals.prState==="closed")return{verdict:"stale",reason:"prClosed"};if(signals.lastActivityMs>0&&nowMs-signals.lastActivityMs>1209600000)return{verdict:"stale",reason:"idle"};return{verdict:"fresh",reason:"fresh"}}function parseGhPrList(stdout){let entries;try{entries=JSON.parse(stdout)}catch{return null}if(!Array.isArray(entries))return null;let rank={open:3,merged:2,closed:1},map=new Map;for(let entry of entries){let branch=entry?.headRefName,rawState=entry?.state;if(typeof branch!=="string"||typeof rawState!=="string")continue;let state=rawState.toLowerCase();if(state!=="open"&&state!=="merged"&&state!=="closed")continue;let cur=map.get(branch);if(!cur||rank[state]>rank[cur])map.set(branch,state)}return map}var TIMEOUT_MS=4000,manager=new GitWorktreeManager;function createdAt(path){try{let stat=statSync(path);return stat.birthtimeMs||stat.mtimeMs}catch{return 0}}async function run(path,argv){return execHostForWorktreePath(path).run(argv,{cwd:path,signal:AbortSignal.timeout(TIMEOUT_MS)})}async function branchOnRemote(path,branch){try{let out=await run(path,["git","ls-remote","--exit-code","--heads","origin",branch]);return out.exitCode===0?!0:out.exitCode===2?!1:null}catch{return null}}async function defaultRef(repo){try{let out=await run(repo,["git","symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(out.exitCode===0&&out.stdout.trim())return out.stdout.trim()}catch{}for(let guess of["origin/main","origin/master"])try{if((await run(repo,["git","rev-parse","--verify","--quiet",guess])).exitCode===0)return guess}catch{}return null}async function prStates(repo){try{let origin=await run(repo,["git","remote","get-url","origin"]);if(origin.exitCode!==0||!origin.stdout.includes("github.com"))return null;let out=await run(repo,["gh","pr","list","--state","all","--limit","200","--json","headRefName,state"]);return out.exitCode===0?parseGhPrList(out.stdout):null}catch{return null}}async function ahead(path,ref){if(!ref)return null;try{let out=await run(path,["git","rev-list","--count",`${ref}..HEAD`]),value=Number.parseInt(out.stdout.trim(),10);return out.exitCode===0&&!Number.isNaN(value)?value:null}catch{return null}}async function listWorktreeProjectsAdapter(network){let repos=getSavedRepos().filter((repo)=>!getRemoteRepoConfig(repo)),now=Date.now();return Promise.all(repos.map(async(repo)=>{let[worktrees,states,ref]=await Promise.all([manager.listAll(repo),network?prStates(repo):null,defaultRef(repo)]),rows=await Promise.all(worktrees.map(async(worktree)=>{let[remote,aheadBy]=await Promise.all([network?branchOnRemote(worktree.path,worktree.branch):null,ahead(worktree.path,ref)]),judgement=judgeWorktree({dirty:worktree.dirty===!0,prState:states?.get(worktree.branch)??null,aheadOfDefault:aheadBy,lastActivityMs:worktree.lastActivityMs},now);return{...worktree,repo,createdAtMs:createdAt(worktree.path),branchOnRemote:remote,verdict:judgement.verdict,verdictReason:judgement.reason}}));return{repo,worktrees:rows}}))}async function listUnreadableWorktreesAdapter(repo){return manager.listUnreadableWorktrees(repo)}async function removeWorktreeAdapter(path,force){let residue=null;return await manager.remove(path,{force,onSalvage:(record)=>{if(record)auditWorktreeSalvaged(path,record.ref,record.commit,record.uncaptured)},onResidue:(r)=>{residue={path:r.path,reason:r.reason},auditWorktreeResidue(r.path,r.reason)}}),residue}function resolveProtocolUpgradeAndLearnPreset(task,evidence){let preset=protocolWriteBackFromLiveSession(task,evidence,getCustomEngineIds());if(preset)setPersistedString(engineProtocolKey(preset.id),preset.protocol);return protocolUpgradeFromLiveSession(task,evidence)}var daemonRuntime={currentVersion:CURRENT_VERSION,tabsPersistence:stateFileTabsPersistence,startMachineHub(bus){let stop=null,stopped=!1;return import("./chunk-ctvxh4z3.js").then(({startDaemonMachineHub})=>{if(!stopped)stop=startDaemonMachineHub(bus)}),()=>{stopped=!0,stop?.()}},async invokeApi(verb,params,socketPath,route){let[{executeVerb,errorEnvelope},{daemonCaller},{RoveDaemonClient:RoveDaemonClient2}]=await Promise.all([import("./chunk-k5pa9a14.js"),import("./chunk-mvfg1593.js"),import("./chunk-db0kdm4z.js")]);if(route?.forwarded){let{inboundRefusal}=await import("./chunk-v80k4mmn.js"),denied=inboundRefusal(verb);if(denied){let{ApiError}=await import("./chunk-mvfg1593.js");return errorEnvelope(new ApiError(`this machine refuses "${denied}" verbs from other machines (${verb} from ${route.from??"a hub"})`,"INBOUND_DENIED",{hint:`on this machine: rove machine inbound allow ${denied}`}))}}let client=new RoveDaemonClient2(socketPath);try{await client.connect();let{invokeRouted}=await import("./chunk-vdy1s9ge.js");return await invokeRouted({verb,params,machine:route?.machine,forwarded:route?.forwarded,isLocalTask:(id)=>client.request("task.get",{taskId:id}).then(()=>!0,()=>!1),runHere:(p)=>executeVerb(verb,{params:p},{client,caller:daemonCaller(route?.forwarded===!0)})})}catch(err){return errorEnvelope(err)}finally{client.close()}},defaultTaskVendor:DEFAULT_TASK_VENDOR,placeholderTaskTitle:PLACEHOLDER_TASK_TITLE,isTaskStatus,isEngineActivityKind,affectsActivityState,async foregroundEngines(pids){let rows=parsePsSnapshot(await psSnapshot([...pids])),out=new Map;for(let pid of pids){let found=foregroundEngineIn(rows,pid);out.set(pid,found?{vendor:found.vendor,pid:found.pid}:null)}return out},titleTurnHint:(vendor,title)=>engineTitleTurnHint(sessionProtocol(vendor),title),sessionProtocol,resolveProtocolUpgrade:resolveProtocolUpgradeAndLearnPreset,readEngineTurns:async(vendor,transcriptPath)=>await protocolEntry(vendor).readTurns?.(transcriptPath)??[],checkLatestVersion:()=>{let state=loadStateFile();return checkLatestVersion({channel:preferredReleaseChannel(state),minAgeHours:updateDelayHours(state)})},latestTranscriptMtime,deriveTitleFromSession,deriveTitleFromSessionId,createEngineTurnDetector:(vendor)=>createEngineTurnDetector(sessionProtocol(vendor)),async runWorktreeStatus(worktreePath,signal,baseRef){let result=await spawnCapture("git",["status","--porcelain=v1"],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});if(result.status!==0)throw Error("git status failed");let counts=parsePorcelain(result.stdout),base=await resolveBaseRefCached(worktreePath,baseRef,signal);if(!base)return counts;let drift=await driftCached(worktreePath,base,async()=>{let out=await spawnCapture("git",["rev-list","--left-right","--count",`${base}...HEAD`],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal});return out.status===0?parseAheadBehind(out.stdout):null});return drift===null?counts:{...counts,...drift}},maybeAutoStart:(orch,taskId)=>maybeAutoStart(orch,taskId),listWorktreeProjects:listWorktreeProjectsAdapter,listUnreadableWorktrees:listUnreadableWorktreesAdapter,removeWorktree:removeWorktreeAdapter,async syncWorktreeWithBase(worktreePath,recordedBaseRef){let controller=new AbortController,timer=setTimeout(()=>controller.abort(),SYNC_TIMEOUT_MS);try{let baseRef=await resolveBaseRefCached(worktreePath,recordedBaseRef,controller.signal);if(!baseRef)throw Error("no base ref resolves for this worktree");return await syncWorktreeWithBase(worktreePath,baseRef,controller.signal)}finally{clearTimeout(timer)}},availableEngineIds,engineDisplayName,roveApiInvocation,engineEntry,ensureTaskSession:ensureTaskSessionAdapter,startTaskSessionWithPrompt:startTaskSessionWithPromptAdapter,tearDownTaskSession:tearDownTaskSessionAdapter,stopTaskEngineTab:stopTaskEngineTabAdapter,async readEngineContextUsage(vendor,sessionId){let read=protocolEntry(vendor).history.readUsageSnapshot;if(!read)return null;let snapshot=await read(sessionId);if(snapshot?.context_tokens===void 0)return null;return{contextTokens:snapshot.context_tokens,...snapshot.context_window_tokens===void 0?{}:{contextWindowTokens:snapshot.context_window_tokens},...snapshot.context_tokens_approximate?{approximate:!0}:{},...snapshot.input_tokens===void 0?{}:{inputTokens:snapshot.input_tokens},...snapshot.output_tokens===void 0?{}:{outputTokens:snapshot.output_tokens},...snapshot.cache_read_input_tokens===void 0?{}:{cacheReadTokens:snapshot.cache_read_input_tokens},...snapshot.cache_creation_input_tokens===void 0?{}:{cacheCreationTokens:snapshot.cache_creation_input_tokens},...snapshot.context_parts?{parts:snapshot.context_parts}:{}}},probeEngineContext:async(vendor,sessionId)=>protocolEntry(vendor).history.probeContext?.(sessionId),quotaUsage:(vendor)=>engineEntry(vendor).quotaUsage?.()??Promise.resolve(null),vendorsWithQuotaProbe,deliverPromptToLiveEngine:deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailed:deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailed:deliverPromptToLiveEngineTabDetailedAdapter,getPersistedString,buildCIPrompt:(worktree,state)=>buildCIPromptForWorktree(worktree,state),setPersistedString,getSavedRepos:()=>[...getSavedRepos()],prStatus:{viewFields:GH_PR_VIEW_FIELDS,mapView:(view,at)=>mapGhPrView(view,at),sameStatus:samePrStatus,nextPoll:(outcome,failures,now,config,random)=>nextPrPoll(outcome,failures,now,config,random),classify:classifyGhFailure}};import{homedir}from"os";async function createRoveCore(options={}){let homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),store=new TaskIndexStore({homeDir});await store.load();let worktrees=new GitWorktreeManager,orchestrator=new Orchestrator({store,worktrees,onSalvage:(taskId,salvage,repo)=>auditDeletionSalvaged(String(taskId),salvage.ref,salvage.commit,repo,salvage.uncaptured),onWorktreeResidue:(taskId,residue)=>auditDeletionResidue(String(taskId),residue.path,residue.reason),onBranchKept:(taskId,kept)=>auditDeletionBranchKept(String(taskId),kept.branch,kept.reason),tearDownSession:(taskId)=>tearDownTaskSessionAdapter(String(taskId),teardownScope(store.list(),String(taskId),new Set([String(taskId)])))}),backfilled=backfillSavedReposFromProjects(store.list().filter((task)=>task.fromProjectRow).map((task)=>task.repo));if(backfilled.length>0)console.error(`[rove] added ${backfilled.length} existing project(s) to the new-task picker`);return{homeDir,orchestrator,store,worktrees,async close(){orchestrator.dispose()}}}import{existsSync,readFileSync as readFileSync2,readdirSync,statSync as statSync2,unlinkSync}from"fs";import{join as join2}from"path";var TMP_MAX_AGE_MS=300000;function sweepIndexLeftovers(stateDir,now=Date.now()){let tmp=[],tmpBytes=0,entries;try{entries=readdirSync(stateDir)}catch{return{tmp,tmpBytes,lock:!1}}for(let name of entries){if(!name.startsWith("tasks.json.")||!name.endsWith(".tmp"))continue;let path=join2(stateDir,name);try{let stat=statSync2(path);if(now-stat.mtimeMs<TMP_MAX_AGE_MS)continue;unlinkSync(path),tmp.push(path),tmpBytes+=stat.size}catch{}}return{tmp,tmpBytes,lock:clearStaleLock(join2(stateDir,"tasks.json.lock"))}}function clearStaleLock(lockPath){let holder;try{holder=readFileSync2(lockPath,"utf8").trim()}catch{return!1}let pid=Number.parseInt(holder,10);if(Number.isFinite(pid)&&pid>0&&isProcessAlive(pid))return!1;return releaseSync(lockPath,holder),!existsSync(lockPath)}var CLI_NAME=ROVE_PRODUCT_NAME;function printDaemonUsage(out){out.write([`Usage: ${CLI_NAME} daemon <command>`,"","Commands:"," status Print the running daemon's status JSON (default)"," start Run the daemon in the foreground (this process becomes it)"," --resident: never idle-stop when the last TUI leaves (headless host)"," stop Ask the running daemon to shut down"," restart Stop the daemon (graceful \u2192 SIGTERM \u2192 SIGKILL) and respawn it",""].join(`
7
7
  `))}async function runDaemonSubcommand(argv){let[command="status",...flags]=argv,socketPath=defaultDaemonSocketPath(),pidPath=defaultDaemonPidPath();if(command==="--help"||command==="-h"||command==="help"){printDaemonUsage(process.stdout);return}if(!SUBCOMMAND_VERBS.daemon.includes(command))process.stderr.write(`${CLI_NAME} daemon: unknown command "${command}"
8
8
 
9
9
  `),printDaemonUsage(process.stderr),process.exit(2);if(command==="relay"){let pty=argvHasFlag(flags,"--pty"),{ensureDaemonReachable}=await import("./chunk-7ay57tgs.js"),{ensurePtyHostReachable}=await import("./chunk-kcta89jz.js"),target=pty?await ensurePtyHostReachable():await ensureDaemonReachable(void 0,"autospawn"),{connect}=await import("net"),socket=connect(target);if(argvHasFlag(flags,"--preamble"))process.stdout.write(RELAY_PREAMBLE);process.stdin.pipe(socket),socket.pipe(process.stdout),await new Promise((resolve)=>{socket.on("close",()=>resolve()),process.stdin.on("end",()=>socket.end())}),process.exit(0)}let badFlag=flags.find((flag)=>!(command==="start"&&argvHasFlag([flag],"--resident"))&&!(command==="status"&&flag==="--json")&&!(command==="relay"&&flag==="--pty")),resident=switchFlag(flags,"--resident");if(badFlag!==void 0||resident===void 0)process.stderr.write(`${CLI_NAME} daemon ${command}: bad option "${badFlag??flags.join(" ")}"
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{invokeVerb,runApiSubcommand}from"./chunk-ass6nz7y.js";import{executeVerb,toApiError}from"./chunk-tkbsw9yh.js";import{API_SCHEMA_VERSION,API_VERBS,VERBS,VERB_GROUPS,VerbArgs,apiUsage,buildCountPlan,defaultApiRuntime,deliverPrompt,findVerb,fullSchema,parseAgentsSpec,parseFlags,schemaIndex,validateAgainstSpec,verbHelp,verbSchema}from"./chunk-6r295bx7.js";import"./chunk-et4r09jp.js";import"./chunk-3yx9cd91.js";import"./chunk-znknvm7g.js";import"./chunk-38hnq4aq.js";import"./chunk-md3xyfxb.js";import"./chunk-t1vbw2me.js";import"./chunk-tybkb1fg.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-kk1kgzmt.js";import"./chunk-0gfzxgyk.js";import"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-xxz504p6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-rmx8jrcj.js";import"./chunk-16nn288h.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import{ApiError}from"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.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-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{verbSchema,verbHelp,validateAgainstSpec,toApiError,schemaIndex,runApiSubcommand,parseFlags,parseAgentsSpec,invokeVerb,fullSchema,findVerb,executeVerb,deliverPrompt,defaultApiRuntime,buildCountPlan,apiUsage,VerbArgs,VERB_GROUPS,VERBS,ApiError,API_VERBS,API_SCHEMA_VERSION};
2
+ import{invokeVerb,runApiSubcommand}from"./chunk-9p688s60.js";import{executeVerb,toApiError}from"./chunk-hpdyr0hc.js";import{API_SCHEMA_VERSION,API_VERBS,VERBS,VERB_GROUPS,VerbArgs,apiUsage,buildCountPlan,defaultApiRuntime,deliverPrompt,findVerb,fullSchema,parseAgentsSpec,parseFlags,schemaIndex,validateAgainstSpec,verbHelp,verbSchema}from"./chunk-drjb1574.js";import"./chunk-et4r09jp.js";import"./chunk-3yx9cd91.js";import"./chunk-znknvm7g.js";import"./chunk-38hnq4aq.js";import"./chunk-md3xyfxb.js";import"./chunk-t1vbw2me.js";import"./chunk-btyf688g.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-zsnaz3gw.js";import"./chunk-se3eb4gr.js";import"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-xxz504p6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-txer3py2.js";import"./chunk-16nn288h.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import{ApiError}from"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.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-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{verbSchema,verbHelp,validateAgainstSpec,toApiError,schemaIndex,runApiSubcommand,parseFlags,parseAgentsSpec,invokeVerb,fullSchema,findVerb,executeVerb,deliverPrompt,defaultApiRuntime,buildCountPlan,apiUsage,VerbArgs,VERB_GROUPS,VERBS,ApiError,API_VERBS,API_SCHEMA_VERSION};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{MachineFeed,decodeMachines}from"./chunk-hg63k0fr.js";import"./chunk-pstbvztv.js";import"./chunk-3evhqh88.js";import"./chunk-6xr1prk6.js";import"./chunk-mdx18vtz.js";import"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-rmx8jrcj.js";import"./chunk-y1xnjx8x.js";import"./chunk-cmp64q4j.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-40dgv828.js";import"./chunk-8trtyc98.js";import"./chunk-7kysxgbq.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-pn5ygqn6.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.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";export{decodeMachines,MachineFeed};
2
+ import{MachineFeed,decodeMachines}from"./chunk-n5ax8ybp.js";import"./chunk-vsy6m1w1.js";import"./chunk-kxhvgkv8.js";import"./chunk-6xr1prk6.js";import"./chunk-mdx18vtz.js";import"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-txer3py2.js";import"./chunk-y1xnjx8x.js";import"./chunk-cmp64q4j.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-40dgv828.js";import"./chunk-8trtyc98.js";import"./chunk-7kysxgbq.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-pn5ygqn6.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.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";export{decodeMachines,MachineFeed};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useT,useTheme}from"./chunk-2dqehs3f.js";import"./chunk-3kfwrpjf.js";import{$jsx,$jsxs,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import"./chunk-3evhqh88.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import"./chunk-9ebvw6eg.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-rmx8jrcj.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-gzn14mwk.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-1feav1w3.js";import{currentLang}from"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-8trtyc98.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.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};
2
+ import{ReleaseNotesBody,bootPaneHost,pageCloseBindings,runShellUpdater,useBindings,useT,useTheme}from"./chunk-0rej9424.js";import"./chunk-3kfwrpjf.js";import{$jsx,$jsxs,useRenderer}from"./chunk-preza5s4.js";import{require_react_production}from"./chunk-2wd4744g.js";import"./chunk-kxhvgkv8.js";import"./chunk-cpgnm1xr.js";import"./chunk-r3s2t9af.js";import"./chunk-6xr1prk6.js";import"./chunk-644ccxmv.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-txer3py2.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-gzn14mwk.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-1feav1w3.js";import{currentLang}from"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-8trtyc98.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.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};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-rmx8jrcj.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-txer3py2.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{recommendedGlobalInstallCommand}from"./chunk-rmx8jrcj.js";import{resolveLoginShell}from"./chunk-tn9gtf18.js";function updaterShell(deps={}){let platform=deps.platform??process.platform;if(platform!=="win32")return"sh";return resolveLoginShell({fallback:"/bin/sh",platform,env:deps.env,exists:deps.exists})}function updaterShellFailureHint(deps={}){if((deps.platform??process.platform)!=="win32")return null;return["The update script is POSIX shell. Rove runs it through Git for Windows'","bash \u2014 the same shell every engine and terminal tab launches through.","Install Git for Windows (https://git-scm.com/download/win), or update","by hand:",` ${recommendedGlobalInstallCommand()}`,""].join(`
2
+ import{recommendedGlobalInstallCommand}from"./chunk-txer3py2.js";import{resolveLoginShell}from"./chunk-tn9gtf18.js";function updaterShell(deps={}){let platform=deps.platform??process.platform;if(platform!=="win32")return"sh";return resolveLoginShell({fallback:"/bin/sh",platform,env:deps.env,exists:deps.exists})}function updaterShellFailureHint(deps={}){if((deps.platform??process.platform)!=="win32")return null;return["The update script is POSIX shell. Rove runs it through Git for Windows'","bash \u2014 the same shell every engine and terminal tab launches through.","Install Git for Windows (https://git-scm.com/download/win), or update","by hand:",` ${recommendedGlobalInstallCommand()}`,""].join(`
3
3
  `)}
4
4
  export{updaterShell,updaterShellFailureHint};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{__require}from"./chunk-91sykzqq.js";var welcomeWrite=Promise.resolve();function trackWelcomeWrite(write){welcomeWrite=write}async function launchTui(){let{startTui}=await import("./chunk-2e6b866m.js");await startTui(),await welcomeWrite;let{runPendingWelcomeInstalls}=await import("./chunk-xhjgdsaw.js");runPendingWelcomeInstalls()}
2
+ import{__require}from"./chunk-91sykzqq.js";var welcomeWrite=Promise.resolve();function trackWelcomeWrite(write){welcomeWrite=write}async function launchTui(){let{startTui}=await import("./chunk-zz99wtfr.js");await startTui(),await welcomeWrite;let{runPendingWelcomeInstalls}=await import("./chunk-xhjgdsaw.js");runPendingWelcomeInstalls()}
3
3
  export{trackWelcomeWrite,launchTui};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{defaultFixRuntime}from"./chunk-qzx5rm6s.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-w4vdwk7e.js";import"./chunk-6r295bx7.js";import"./chunk-et4r09jp.js";import"./chunk-3yx9cd91.js";import"./chunk-znknvm7g.js";import"./chunk-38hnq4aq.js";import"./chunk-md3xyfxb.js";import"./chunk-t1vbw2me.js";import"./chunk-tybkb1fg.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-kk1kgzmt.js";import"./chunk-0gfzxgyk.js";import{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import{addMachine,dedupeMachines,defaultMachineAlias,discoverMachine,duplicateAliasOf,getMachine,hubKeyPath,isValidMachineAlias,isWindowsMachine,learnedFrom,listMachines,machineIdentityFile,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,remoteRove,removeMachine,sanitizeAlias,setMachineIdentity,sshServerIsWindows,sshTargetOf,updateMachine,windowsAuthorizeKeySteps}from"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-xxz504p6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION}from"./chunk-rmx8jrcj.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-16nn288h.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import{shQuote}from"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.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-jt9n8k7z.js";import"./chunk-apaw34c5.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(`
2
+ import{defaultFixRuntime}from"./chunk-qzx5rm6s.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-8neqhjcv.js";import"./chunk-drjb1574.js";import"./chunk-et4r09jp.js";import"./chunk-3yx9cd91.js";import"./chunk-znknvm7g.js";import"./chunk-38hnq4aq.js";import"./chunk-md3xyfxb.js";import"./chunk-t1vbw2me.js";import"./chunk-btyf688g.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-zsnaz3gw.js";import"./chunk-se3eb4gr.js";import{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import{addMachine,dedupeMachines,defaultMachineAlias,discoverMachine,duplicateAliasOf,getMachine,hubKeyPath,isValidMachineAlias,isWindowsMachine,learnedFrom,listMachines,machineIdentityFile,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,remoteRove,removeMachine,sanitizeAlias,setMachineIdentity,sshServerIsWindows,sshTargetOf,updateMachine,windowsAuthorizeKeySteps}from"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-xxz504p6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION}from"./chunk-txer3py2.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-16nn288h.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import{shQuote}from"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.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-jt9n8k7z.js";import"./chunk-apaw34c5.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
  `)}
@@ -49,7 +49,7 @@ ${MACHINE_USAGE}
49
49
  `);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||"?"}
50
50
  `);for(let note of await doctorNotes(name,settled,found))process.stdout.write(` ${note}
51
51
  `);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>\`.
52
- `);return}let{upgradeMachine}=await import("./chunk-jrkwfnc4.js"),failed=0;for(let entry of entries){process.stderr.write(`${CLI_NAME} machine: updating ${entry.alias} (${sshTargetOf(entry)})\u2026
52
+ `);return}let{upgradeMachine}=await import("./chunk-kpqpjyz4.js"),failed=0;for(let entry of entries){process.stderr.write(`${CLI_NAME} machine: updating ${entry.alias} (${sshTargetOf(entry)})\u2026
53
53
  `);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}
54
54
  `:`${entry.alias} \u2713 already on rove ${now}${skew}
55
55
  `)}catch(err){failed++,process.stdout.write(`${entry.alias} \u2717 ${err instanceof Error?err.message:String(err)}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-6r295bx7.js";import"./chunk-et4r09jp.js";import"./chunk-3yx9cd91.js";import"./chunk-znknvm7g.js";import"./chunk-38hnq4aq.js";import"./chunk-md3xyfxb.js";import"./chunk-t1vbw2me.js";import"./chunk-tybkb1fg.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-kk1kgzmt.js";import"./chunk-0gfzxgyk.js";import"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-xxz504p6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-rmx8jrcj.js";import"./chunk-16nn288h.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.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-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
2
+ import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-drjb1574.js";import"./chunk-et4r09jp.js";import"./chunk-3yx9cd91.js";import"./chunk-znknvm7g.js";import"./chunk-38hnq4aq.js";import"./chunk-md3xyfxb.js";import"./chunk-t1vbw2me.js";import"./chunk-btyf688g.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-mavz1h73.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-zsnaz3gw.js";import"./chunk-se3eb4gr.js";import"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-xxz504p6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-txer3py2.js";import"./chunk-16nn288h.js";import"./chunk-erwqdw0g.js";import"./chunk-jmfxkahq.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-xvr8g6jc.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.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-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{findVerb}from"./chunk-6r295bx7.js";import{VERB_GROUP_IDS}from"./chunk-jz1kj4sf.js";import{loadStateFile,updateStateFile}from"./chunk-8trtyc98.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
2
+ import{findVerb}from"./chunk-drjb1574.js";import{VERB_GROUP_IDS}from"./chunk-jz1kj4sf.js";import{loadStateFile,updateStateFile}from"./chunk-8trtyc98.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land","credentials"],LAND_VERBS=new Set(["land","publish"]),CREDENTIAL_VERBS={"github-login":!0,"github-logout":!0,"github-sync":!0,"github-apply":!0};function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";if(Object.hasOwn(CREDENTIAL_VERBS,verb))return"credentials";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
3
3
  export{INBOUND_KEY,INBOUND_CLASSES,inboundClassOf,deniedClasses,inboundRefusal,setInbound};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{CURRENT_VERSION}from"./chunk-rmx8jrcj.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-6jcmdxza.js";import"./chunk-han0d078.js";import{flagValue}from"./chunk-zsfyj36g.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir))}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
2
+ import{CURRENT_VERSION}from"./chunk-txer3py2.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-6jcmdxza.js";import"./chunk-han0d078.js";import{flagValue}from"./chunk-zsfyj36g.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir))}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
3
3
  `);if(lines.length<=count+1)return text;return`${lines.slice(0,count).join(`
4
4
  `)}
5
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)}