@sma1lboy/rove 0.9.110 → 0.9.148
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -1
- package/dist/cli/chunk-003tvywc.js +3 -0
- package/dist/cli/chunk-0b48bpkd.js +2 -0
- package/dist/cli/chunk-0dv2xssg.js +19 -0
- package/dist/cli/chunk-0sm2k04y.js +3 -0
- package/dist/cli/chunk-0vmrteyg.js +3 -0
- package/dist/cli/chunk-13s8rnk5.js +3 -0
- package/dist/cli/chunk-1kktfmtg.js +4 -0
- package/dist/cli/chunk-1rkb0j1j.js +3 -0
- package/dist/cli/chunk-1tx1s5v6.js +2 -0
- package/dist/cli/chunk-1x0vahnn.js +2 -0
- package/dist/cli/chunk-20pt9yqh.js +4 -0
- package/dist/cli/chunk-2brn8e1y.js +3 -0
- package/dist/cli/chunk-2fypr41w.js +3 -0
- package/dist/cli/chunk-2jxdzw4r.js +3 -0
- package/dist/cli/chunk-2pqqvse3.js +2 -0
- package/dist/cli/chunk-39s1ndtm.js +106 -0
- package/dist/cli/chunk-3bfm4hrs.js +3 -0
- package/dist/cli/chunk-3rqa4pyt.js +28 -0
- package/dist/cli/chunk-3ry6prwn.js +3 -0
- package/dist/cli/chunk-3ztek08w.js +4 -0
- package/dist/cli/chunk-49s2zc0h.js +8 -0
- package/dist/cli/chunk-4wwx51m5.js +3 -0
- package/dist/cli/chunk-5ar3vspk.js +9 -0
- package/dist/cli/chunk-5bn91n19.js +3 -0
- package/dist/cli/chunk-5c3d1y0r.js +2 -0
- package/dist/cli/chunk-5hhvrvgm.js +8 -0
- package/dist/cli/chunk-6dn6h640.js +3 -0
- package/dist/cli/chunk-6frfschk.js +2 -0
- package/dist/cli/chunk-6xppe9bj.js +3 -0
- package/dist/cli/chunk-6zwg6me2.js +4 -0
- package/dist/cli/chunk-764bsyb0.js +1 -0
- package/dist/cli/chunk-79gqh5p2.js +5 -0
- package/dist/cli/chunk-7ngv7v9g.js +9 -0
- package/dist/cli/chunk-7nhdvr5v.js +4 -0
- package/dist/cli/chunk-7pfnda5z.js +12 -0
- package/dist/cli/chunk-7q67dz4c.js +3 -0
- package/dist/cli/chunk-8ddjfc2v.js +4 -0
- package/dist/cli/chunk-8g456mmt.js +3 -0
- package/dist/cli/chunk-8sbevss4.js +4 -0
- package/dist/cli/chunk-91j0an0j.js +2 -0
- package/dist/cli/chunk-99devyxr.js +2 -0
- package/dist/cli/chunk-9c1e5z6a.js +3 -0
- package/dist/cli/chunk-a4a4qaa2.js +3 -0
- package/dist/cli/chunk-adez6hq4.js +69 -0
- package/dist/cli/chunk-aq912vvw.js +3 -0
- package/dist/cli/chunk-arf294te.js +2 -0
- package/dist/cli/chunk-awsawfrm.js +2 -0
- package/dist/cli/chunk-aynx3d2a.js +2 -0
- package/dist/cli/chunk-b8d162tf.js +3 -0
- package/dist/cli/chunk-b99tf0jr.js +3 -0
- package/dist/cli/chunk-bj59a9mg.js +3 -0
- package/dist/cli/chunk-c6mthex1.js +5 -0
- package/dist/cli/chunk-cb2fpajx.js +3 -0
- package/dist/cli/chunk-cbkje3aw.js +2 -0
- package/dist/cli/chunk-df7qe9y7.js +4 -0
- package/dist/cli/chunk-dkxhmj9k.js +25 -0
- package/dist/cli/chunk-dqndd97s.js +7 -0
- package/dist/cli/chunk-dvabncrk.js +7 -0
- package/dist/cli/chunk-dvcb6mk4.js +3 -0
- package/dist/cli/chunk-dw853n4w.js +3 -0
- package/dist/cli/chunk-dx6b3dv8.js +7 -0
- package/dist/cli/chunk-e1g9mvww.js +11 -0
- package/dist/cli/chunk-ef11h2am.js +3 -0
- package/dist/cli/chunk-ef39ym8f.js +3 -0
- package/dist/cli/chunk-eq5f3z2f.js +3 -0
- package/dist/cli/chunk-ewdhz3dv.js +2 -0
- package/dist/cli/chunk-f6zsej8e.js +3 -0
- package/dist/cli/chunk-g1ybdgad.js +25 -0
- package/dist/cli/chunk-gbasmvsc.js +4 -0
- package/dist/cli/chunk-gjf604bb.js +3 -0
- package/dist/cli/chunk-gm3vj0fv.js +5 -0
- package/dist/cli/chunk-grh6dvfv.js +5 -0
- package/dist/cli/chunk-gwcneg6c.js +2 -0
- package/dist/cli/chunk-h5j8b87f.js +2 -0
- package/dist/cli/chunk-h79zfebh.js +7 -0
- package/dist/cli/chunk-h82kzdsn.js +3 -0
- package/dist/cli/chunk-hape5vwj.js +3 -0
- package/dist/cli/chunk-hg5x2wr0.js +3 -0
- package/dist/cli/chunk-j4xfsn9g.js +5 -0
- package/dist/cli/chunk-jfqbq12b.js +18 -0
- package/dist/cli/chunk-jsss3ze7.js +11 -0
- package/dist/cli/chunk-jvpzy378.js +3 -0
- package/dist/cli/chunk-jvxh93nz.js +3 -0
- package/dist/cli/chunk-jyv82gf0.js +258 -0
- package/dist/cli/chunk-k3ksts6g.js +3 -0
- package/dist/cli/chunk-kdrrw9tm.js +2 -0
- package/dist/cli/chunk-kg11c1py.js +3 -0
- package/dist/cli/chunk-kwe61yx7.js +3 -0
- package/dist/cli/chunk-m0fz6g32.js +16 -0
- package/dist/cli/chunk-mb5m7ex7.js +2 -0
- package/dist/cli/chunk-me77sx3d.js +3 -0
- package/dist/cli/chunk-mfqjdpd8.js +2 -0
- package/dist/cli/chunk-mggca3k4.js +4 -0
- package/dist/cli/chunk-mjvq39gf.js +4 -0
- package/dist/cli/chunk-mrwee8sj.js +3 -0
- package/dist/cli/chunk-my20q579.js +3 -0
- package/dist/cli/chunk-nceh1q3d.js +12 -0
- package/dist/cli/chunk-ncsgawg7.js +2 -0
- package/dist/cli/chunk-nm6adny4.js +4 -0
- package/dist/cli/chunk-np07kccr.js +4 -0
- package/dist/cli/chunk-nrnjt5b6.js +2 -0
- package/dist/cli/chunk-p7kztgsd.js +4 -0
- package/dist/cli/chunk-pbqwegjy.js +2 -0
- package/dist/cli/chunk-pcvk98rr.js +3 -0
- package/dist/cli/chunk-pdh5w4ht.js +3 -0
- package/dist/cli/chunk-pdj8kqa1.js +74 -0
- package/dist/cli/chunk-pw6yfj10.js +3 -0
- package/dist/cli/chunk-q6579rbz.js +3 -0
- package/dist/cli/chunk-q7dr9eh6.js +3 -0
- package/dist/cli/chunk-qkehg2c1.js +3 -0
- package/dist/cli/chunk-qtke4x42.js +3 -0
- package/dist/cli/chunk-rxvbm4vt.js +7 -0
- package/dist/cli/chunk-s66eh0pw.js +8 -0
- package/dist/cli/chunk-s76r56rj.js +3 -0
- package/dist/cli/chunk-sdyzxayr.js +3 -0
- package/dist/cli/chunk-svpn3av1.js +3 -0
- package/dist/cli/chunk-t0kta7rb.js +5 -0
- package/dist/cli/chunk-v5893dx3.js +2 -0
- package/dist/cli/chunk-vapjtyv9.js +7 -0
- package/dist/cli/chunk-vpzvcxc1.js +3 -0
- package/dist/cli/chunk-vqpa27cf.js +15 -0
- package/dist/cli/chunk-vws0j65e.js +4 -0
- package/dist/cli/chunk-vyb5a2rh.js +4 -0
- package/dist/cli/chunk-vzxbe80f.js +7 -0
- package/dist/cli/chunk-w5xy83ze.js +2 -0
- package/dist/cli/chunk-wqfp8d9w.js +3 -0
- package/dist/cli/chunk-wsvf9eka.js +33 -0
- package/dist/cli/chunk-x760j10f.js +3 -0
- package/dist/cli/chunk-x930m5fs.js +2 -0
- package/dist/cli/chunk-xbc3gcry.js +2 -0
- package/dist/cli/chunk-xy8be792.js +3 -0
- package/dist/cli/chunk-xzrqnpmh.js +4 -0
- package/dist/cli/chunk-y2yq6zca.js +3 -0
- package/dist/cli/chunk-yhcz2d2r.js +34 -0
- package/dist/cli/chunk-yk2ha5yj.js +3 -0
- package/dist/cli/chunk-ykvk2546.js +3 -0
- package/dist/cli/chunk-ympakh8w.js +6 -0
- package/dist/cli/chunk-yn5a7xcv.js +2 -0
- package/dist/cli/chunk-zb56ck5f.js +3 -0
- package/dist/cli/index.js +15 -850
- package/dist/cli/kobe-run.js +1 -858
- package/dist/cli/kobe.js +6 -6
- package/dist/cli/pty-host-node.mjs +167 -50
- package/dist/cli/rove-run.js +1 -858
- package/dist/cli/rove.js +6 -6
- package/dist/skills/rove/SKILL.md +29 -10
- package/dist/skills/rove/references/api-flags.md +35 -13
- package/dist/web-ui/assets/{ChatTerminal-BshL3M8G.js → harness-CYGJ4uoR.js} +19 -20
- package/dist/web-ui/assets/index-BTJ-X_4s.js +10 -0
- package/dist/web-ui/assets/index-Cs2vPLNB.css +1 -0
- package/dist/web-ui/index.html +2 -9
- package/dist/web-ui/pty-server.mjs +4 -5
- package/package.json +1 -1
- package/dist/web-ui/assets/AppShell-BGRIs5hW.js +0 -5
- package/dist/web-ui/assets/AppShell-HiyATJse.css +0 -1
- package/dist/web-ui/assets/Board-Bt3cwp25.js +0 -1
- package/dist/web-ui/assets/BoardPeek-BKR-tpS2.js +0 -2
- package/dist/web-ui/assets/ChatTranscript-B67_nnd6.js +0 -1
- package/dist/web-ui/assets/ConfirmDialog-kyA624OF.js +0 -1
- package/dist/web-ui/assets/IssueIntakePanel-BMP8Vc3E.js +0 -1
- package/dist/web-ui/assets/IssuePeek-C7afOYax.js +0 -1
- package/dist/web-ui/assets/IssuesPage-DwRaBB-m.js +0 -1
- package/dist/web-ui/assets/SettingsPage-CC1sDI8j.js +0 -2
- package/dist/web-ui/assets/SlideOver-B4sEOPyN.css +0 -1
- package/dist/web-ui/assets/SlideOver-Dq0ifiEm.js +0 -173
- package/dist/web-ui/assets/ViewToggle-mNsDLJp8.js +0 -1
- package/dist/web-ui/assets/WorkspaceTabs-DLzL-Tad.css +0 -1
- package/dist/web-ui/assets/WorkspaceTabs-ifAIZ5Fj.js +0 -3
- package/dist/web-ui/assets/active-task-gVYiAkLv.js +0 -1
- package/dist/web-ui/assets/arrow-left-CavMh90a.js +0 -1
- package/dist/web-ui/assets/board-DoArj55z.js +0 -1
- package/dist/web-ui/assets/chips-CS9PLtWy.js +0 -1
- package/dist/web-ui/assets/createLucideIcon-CuIQtyYV.js +0 -1
- package/dist/web-ui/assets/external-link-Du2dMe8S.js +0 -1
- package/dist/web-ui/assets/external-store-BCBJewGi.js +0 -1
- package/dist/web-ui/assets/harness-ClZMF1wx.js +0 -1
- package/dist/web-ui/assets/index-B4xJZEqf.js +0 -10
- package/dist/web-ui/assets/index-BnjD9Q-3.css +0 -1
- package/dist/web-ui/assets/issues-DwrKXp9c.js +0 -4
- package/dist/web-ui/assets/issues-ISAZBras.js +0 -1
- package/dist/web-ui/assets/lazy-issue-panels-DvXQJhKy.js +0 -6
- package/dist/web-ui/assets/rotate-cw-BXdpzm3v.js +0 -1
- package/dist/web-ui/assets/routes-DEEkL5gG.js +0 -1
- package/dist/web-ui/assets/store-BLM6nh6E.js +0 -2
- package/dist/web-ui/assets/tabs-CMZJhcSB.js +0 -1
- package/dist/web-ui/assets/task._taskId-BCIhg4IQ.js +0 -1
- package/dist/web-ui/assets/terminal-DOp1a9g6.js +0 -1
- package/dist/web-ui/assets/text-match-DW3sD-Rt.js +0 -1
- package/dist/web-ui/assets/time-kviT26Tm.js +0 -1
- package/dist/web-ui/assets/toast-C4yXq6hM.js +0 -1
- package/dist/web-ui/assets/web-transport-Beqz2mQ8.js +0 -1
- package/dist/web-ui/assets/worktrees-BGvJOG2b.js +0 -1
- /package/dist/web-ui/assets/{ChatTerminal-BrP-ENHg.css → harness-BrP-ENHg.css} +0 -0
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var ENGINE_ACTIVITY_KINDS=["session-start","turn-start","turn-complete","turn-failed","turn-interrupted","awaiting-input","session-end","tool-pre","tool-post","tool-failed","pre-compact","post-compact","subagent-start","subagent-stop"];function isEngineActivityKind(v){return ENGINE_ACTIVITY_KINDS.includes(v)}var ACTIVITY_STATE_KINDS=["session-start","turn-start","turn-complete","turn-failed","turn-interrupted","awaiting-input","session-end"];function affectsActivityState(kind){return ACTIVITY_STATE_KINDS.includes(kind)}
|
|
3
|
+
export{isEngineActivityKind,affectsActivityState};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{DAEMON_CHANNELS}from"./chunk-kwe61yx7.js";var DAEMON_PROTOCOL_VERSION=4,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;let strip=(value)=>value.replace(/[/\\]+$/,"");return strip(daemonHome)!==strip(clientHome)}function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","prompt_deferred","dead","prompt_expired","routine_failed"];function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(item.state==="routine_failed"&&item.detail?.routine)return`\x00routine\x00${item.detail.routine.automationId}`;let lane=item.state==="prompt_deferred"||item.state==="prompt_expired"?"\x00deferred":"";return`${item.taskId}\x00${item.tabId??""}${lane}`}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var BLOCKING_RPCS=new Set(["ui.prompt","task.land","workitem.start","automation.runNow","deferredPrompt.flush","deferredPrompt.release","task.ensureWorktree","task.ensureMain","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove"]);function displayTaskTitle(task){return task.title||task.branch||task.worktreePath||task.repo||"scratch"}function serializeTask(task){return{id:task.id,title:displayTaskTitle(task),repo:task.repo,branch:task.branch,worktreePath:task.worktreePath,kind:task.kind??"task",...task.scratch?{scratch:!0}:{},...task.routine?{routine:task.routine}:{},status:task.status,pinned:task.pinned??!1,vendor:task.vendor,command:task.command,prStatus:task.prStatus,modelEffort:task.modelEffort,groupId:task.groupId,observedLanguage:task.observedLanguage,deletion:task.deletion,quotaResume:task.quotaResume,linkedWorkItem:task.linkedWorkItem,dispatcher:task.dispatcher,prompt:task.prompt,baseRef:task.baseRef,createdAt:task.createdAt,updatedAt:task.updatedAt}}function frameToLine(frame){return`${JSON.stringify(frame)}
|
|
3
|
+
`}
|
|
4
|
+
export{automationRunNeedsAttention,isAttentionInboxState,attentionInboxItemKey,CHANNEL_NAMES,normalizeChannelFilter,DAEMON_PROTOCOL_VERSION,MIN_COMPATIBLE_PROTOCOL_VERSION,isProtocolCompatible,isDaemonVersionStale,isForeignDaemonHome,BLOCKING_RPCS,displayTaskTitle,serializeTask,frameToLine};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{isEngineActivityKind}from"./chunk-3ry6prwn.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-jyv82gf0.js";import{flagValue}from"./chunk-jvxh93nz.js";import{connectIfRunning}from"./chunk-5bn91n19.js";import{createEngineHookAdapter}from"./chunk-yhcz2d2r.js";import{getPersistedString,setPersistedString}from"./chunk-k3ksts6g.js";import{ALL_VENDORS}from"./chunk-h82kzdsn.js";import{activeCliName}from"./chunk-ef11h2am.js";import{readRoveEnv}from"./chunk-3bfm4hrs.js";import{__require}from"./chunk-wqfp8d9w.js";import{homedir}from"os";import{join,resolve}from"path";var STDIN_READ_TIMEOUT_MS=500;async function readTextWithTimeout(read,timeoutMs=STDIN_READ_TIMEOUT_MS){let raceTimer;try{return await Promise.race([read(),new Promise((resolve2)=>{raceTimer=setTimeout(()=>resolve2(""),timeoutMs)})])}finally{if(raceTimer!==void 0)clearTimeout(raceTimer)}}async function readStdinPayload(){try{let text=await readTextWithTimeout(()=>Bun.stdin.text());if(!text.trim())return{};let parsed=JSON.parse(text);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}async function runHookSubcommand(argv){let[verb,...rest]=argv;if(verb==="setup"){await runHookSetup(rest);return}if(verb==="cleanup"){await runHookCleanup();return}try{if(!verb||!isEngineActivityKind(verb))return;let payload=await readStdinPayload(),taskId=flagValue(rest,"--task-id"),cwd=typeof payload.cwd==="string"&&payload.cwd?payload.cwd:process.cwd(),envTaskId=process.env.KOBE_TASK_ID,envTabId=process.env.KOBE_TAB_ID,engine=flagValue(rest,"--engine"),adapters=activityHookAdapters().filter((a)=>!engine||a.vendor===engine),detail;for(let adapter of adapters)if(detail=adapter.activityDetailFromPayload(verb,payload),detail)break;let session;for(let adapter of adapters)if(session=adapter.sessionFromPayload(payload),session)break;let client=await connectIfRunning();if(!client)return;try{let effectiveTaskId=taskId??envTaskId;await client.request("engine.reportEvent",{...effectiveTaskId?{taskId:effectiveTaskId}:{cwd},kind:verb,...engine?{engine}:{},...envTabId?{tabId:envTabId}:{},...detail?{detail}:{},...session?{sessionId:session.sessionId}:{},...session?.transcriptPath?{transcriptPath:session.transcriptPath}:{}})}finally{client.close()}}catch(err){if(readRoveEnv("HOOK_DEBUG"))console.error(`[rove hook] ${verb} failed:`,err instanceof Error?err.message:String(err))}}var SYNC_SETTING_KEY="externalWorktreeSync";function worktreeSyncAdapters(){return ALL_VENDORS.map((v)=>createEngineHookAdapter(v)).filter((a)=>a.supportsWorktreeSync())}function activityHookAdapters(){return ALL_VENDORS.map((v)=>createEngineHookAdapter(v)).filter((a)=>a.supportsHooks())}function globalSettingsPath(){return join(homedir(),".claude","settings.json")}function persistedSyncPath(stored){if(!stored||stored==="off")return;if(stored==="global")return globalSettingsPath();if(stored.startsWith("repo:"))return join(resolve(stored.slice(5)),".claude","settings.json");return stored}async function ensureGlobalKobeHooks(){try{let{isRovePluginEnabled,detectLegacyInstalls,migrationHint}=await import("./chunk-vws0j65e.js"),pluginMode=isRovePluginEnabled();if(pluginMode){let hint=migrationHint(detectLegacyInstalls(),activeCliName());if(hint)process.stderr.write(`
|
|
3
|
+
${hint}
|
|
4
|
+
`)}let toolEvents=pluginsWantToolEvents();for(let a of activityHookAdapters()){if(pluginMode&&a.vendor==="claude")continue;let enginePath=a.globalSettingsPath();if(!enginePath)continue;await a.installActivityHooks(enginePath,{toolEvents}),await a.removeWorktreeWatchHook(enginePath)}await cleanupWorktreeSyncHook()}catch{}}function pluginsWantToolEvents(){try{for(let entry of loadPluginRegistry().plugins){if(!entry.enabled)continue;try{if(readPluginManifest(entry.root).manifest.events.some((e)=>e.on.startsWith("tool.")))return!0}catch{}}}catch{}return!1}async function cleanupWorktreeSyncHook(){let adapters=worktreeSyncAdapters();if(adapters.length===0)return;let stored=getPersistedString(SYNC_SETTING_KEY),paths=new Set([globalSettingsPath()]),prev=persistedSyncPath(stored);if(prev)paths.add(prev);for(let a of adapters)for(let p of paths)await a.removeWorktreeSyncHook(p);if(stored!=="off")setPersistedString(SYNC_SETTING_KEY,"off")}async function runHookCleanup(){let claude=activityHookAdapters().find((a)=>a.vendor==="claude"),path=claude?.globalSettingsPath();if(!claude||!path){process.stdout.write(`rove hook cleanup: no Claude hook adapter \u2014 nothing to do.
|
|
5
|
+
`);return}await claude.removeActivityHooks(path),await claude.removeWorktreeWatchHook(path),process.stdout.write([`rove hook cleanup: removed Rove's settings-managed hooks from ${path}.`,"Only Rove's own entries were touched; your other hooks are intact.","The Claude Code plugin's hooks.json now carries these events (if the plugin","is not installed, the next Rove launch reinstalls the settings-managed set).",""].join(`
|
|
6
|
+
`))}async function runHookSetup(_argv){await cleanupWorktreeSyncHook(),process.stdout.write(["rove hook setup is deprecated and now a no-op (cleanup only).","","The old external-worktree sync used a global WorktreeCreate hook, which is","a VCS provider hook \u2014 its presence broke `claude --worktree` / EnterWorktree","in every repo. Any hook Rove previously installed has been removed.","","Sync is now automatic: a `claude --worktree` (or any session) started in a","worktree under a repo Rove already tracks is adopted as a task on launch.","To adopt existing worktrees on demand, use the New Task dialog or `rove adopt`.",""].join(`
|
|
7
|
+
`))}
|
|
8
|
+
export{readTextWithTimeout,runHookSubcommand,ensureGlobalKobeHooks};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{isWindowsPipePath}from"./chunk-x760j10f.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-3bfm4hrs.js";import{readFile,stat,unlink}from"fs/promises";import{chmod,mkdir}from"fs/promises";import{join}from"path";var OWNER_ONLY_DIR_MODE=448,OWNER_ONLY_FILE_MODE=384;async function tighten(path,mode){try{await chmod(path,mode)}catch{}}function tightenDirPermissions(dir){return tighten(dir,OWNER_ONLY_DIR_MODE)}function tightenFilePermissions(file){return tighten(file,OWNER_ONLY_FILE_MODE)}async function ensureOwnerOnlyDir(dir){await mkdir(dir,{recursive:!0,mode:OWNER_ONLY_DIR_MODE}),await tightenDirPermissions(dir)}function ensureOwnerOnlyStateDir(homeDir){return ensureOwnerOnlyDir(join(homeDir,ROVE_STATE_DIR_BASENAME))}var DEFAULT_SOCKET_WATCH_MS=5000;async function listenOnUnixSocket(server,socketPath){if(await new Promise((resolve,reject)=>{let evented=server;evented.once("error",reject),server.listen(socketPath,()=>{evented.removeListener("error",reject),resolve()})}),!isWindowsPipePath(socketPath))await tightenFilePermissions(socketPath)}async function readPidFile(pidPath){try{let raw=await readFile(pidPath,"utf8"),pid=Number(raw.trim());return Number.isFinite(pid)?pid:null}catch{return null}}function createSocketOwnershipGuard(options){let watchMs=options.watchMs??DEFAULT_SOCKET_WATCH_MS,stamp=null,lost=!1,timer=null,currentStamp=async()=>{try{let s=await stat(options.socketPath);return{dev:s.dev,ino:s.ino}}catch(err){return err.code==="ENOENT"?null:"error"}},stopTimer=()=>{if(timer)clearInterval(timer);timer=null},verify=async()=>{if(stamp===null||lost)return;let now=await currentStamp();if(now==="error")return;if(now===null||now.dev!==stamp.dev||now.ino!==stamp.ino)lost=!0},check=async()=>{if(stamp===null||lost)return;if(await verify(),!lost)return;stopTimer(),options.onLost()};return{async arm(){let now=await currentStamp();if(now===null||now==="error")return;if(stamp=now,watchMs>0)timer=setInterval(()=>void check(),watchMs),timer.unref?.()},async release(server){if(stopTimer(),await verify(),stamp===null||lost){server.unref();return}await new Promise((resolve)=>server.close(()=>resolve())),await unlink(options.socketPath).catch(()=>{}),await unlink(options.pidPath).catch(()=>{})}}}
|
|
3
|
+
export{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE,ensureOwnerOnlyStateDir,listenOnUnixSocket,readPidFile,createSocketOwnershipGuard};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,deriveTitleFromSession,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,tearDownTaskSessionAdapter}from"./chunk-me77sx3d.js";import{resolvePluginBinPath}from"./chunk-svpn3av1.js";import{affectsActivityState,isEngineActivityKind}from"./chunk-3ry6prwn.js";import{GH_PR_VIEW_FIELDS,Orchestrator,classifyGhFailure,mapGhPrView,nextPrPoll,parseDirtyPaths,samePrStatus}from"./chunk-gm3vj0fv.js";import"./chunk-003tvywc.js";import"./chunk-zb56ck5f.js";import{GitWorktreeManager}from"./chunk-5hhvrvgm.js";import{execHostForWorktreePath}from"./chunk-2jxdzw4r.js";import"./chunk-1kktfmtg.js";import{auditDeletionResidue,auditDeletionSalvaged,auditWorktreeResidue,auditWorktreeSalvaged,parseAheadBehind,startDaemonServer}from"./chunk-0dv2xssg.js";import"./chunk-mrwee8sj.js";import"./chunk-q6579rbz.js";import"./chunk-hg5x2wr0.js";import{installDaemonCrashHandlers}from"./chunk-ympakh8w.js";import"./chunk-f6zsej8e.js";import{parsePorcelain}from"./chunk-mjvq39gf.js";import{DEFAULT_BASE_REF_CANDIDATES,readHeadSha,readRefSha,resolveGitDirs}from"./chunk-vyb5a2rh.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{PLACEHOLDER_TASK_TITLE}from"./chunk-aq912vvw.js";import"./chunk-jyv82gf0.js";import{SUBCOMMAND_VERBS}from"./chunk-s76r56rj.js";import{TaskIndexStore}from"./chunk-6zwg6me2.js";import"./chunk-qkehg2c1.js";import{CURRENT_VERSION,checkLatestVersion}from"./chunk-eq5f3z2f.js";import{autoStatusEnabled,composerGateEnabled}from"./chunk-adez6hq4.js";import"./chunk-hape5vwj.js";import"./chunk-20pt9yqh.js";import{GENERIC_PROTOCOL,engineDisplayName,engineProtocolKey,getEngineProtocol,kobeApiInvocation,protocolEntry,resolveCommandProtocol}from"./chunk-q7dr9eh6.js";import"./chunk-jvxh93nz.js";import"./chunk-7q67dz4c.js";import"./chunk-b99tf0jr.js";import"./chunk-a4a4qaa2.js";import"./chunk-8g456mmt.js";import"./chunk-sdyzxayr.js";import"./chunk-0sm2k04y.js";import{connectOrStartDaemon,probeDaemonSocket}from"./chunk-5bn91n19.js";import{stopDaemonProcess}from"./chunk-pdh5w4ht.js";import{readPidFile}from"./chunk-4wwx51m5.js";import{KobeDaemonClient}from"./chunk-79gqh5p2.js";import"./chunk-3ztek08w.js";import"./chunk-kwe61yx7.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-gbasmvsc.js";import{createEngineTurnDetector,engineEntry,engineTitleTurnHint,vendorsWithQuotaProbe}from"./chunk-yhcz2d2r.js";import{availableEngineIds}from"./chunk-df7qe9y7.js";import{spawnCapture}from"./chunk-gwcneg6c.js";import"./chunk-7nhdvr5v.js";import"./chunk-2fypr41w.js";import{backfillSavedReposFromProjects,getCustomEngineIds,getPersistedString,getRemoteRepoConfig,getSavedRepos,setPersistedString}from"./chunk-k3ksts6g.js";import"./chunk-gjf604bb.js";import{isProcessAlive,releaseSync}from"./chunk-qtke4x42.js";import{DEFAULT_TASK_VENDOR,isTaskStatus}from"./chunk-xy8be792.js";import"./chunk-2brn8e1y.js";import"./chunk-9c1e5z6a.js";import"./chunk-6dn6h640.js";import{BUILTIN_VENDORS,isBuiltinVendor}from"./chunk-h82kzdsn.js";import{activeCliName}from"./chunk-ef11h2am.js";import{migrateRoveDaemonStateLayout}from"./chunk-8ddjfc2v.js";import"./chunk-cb2fpajx.js";import"./chunk-grh6dvfv.js";import{rotateLogIfNeeded}from"./chunk-pw6yfj10.js";import"./chunk-yk2ha5yj.js";import"./chunk-rxvbm4vt.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-x760j10f.js";import{readRoveHomeDirEnv}from"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";function sniffProtocolFromTitle(title){let trimmed=title?.trim();if(!trimmed)return null;let owners=new Map;for(let vendor of BUILTIN_VENDORS)for(let glyph of engineEntry(vendor).terminalTitle?.statusPrefixes??[])owners.set(glyph,[...owners.get(glyph)??[],vendor]);for(let glyph of[...owners.keys()].sort((a,b)=>b.length-a.length)){if(!trimmed.startsWith(glyph))continue;if(trimmed.slice(glyph.length).trim().length===0)continue;let vendors=owners.get(glyph)??[];if(vendors.length===1)return vendors[0];return null}return null}function protocolUpgradeFromLiveSession(task,evidence){let command=task.command?.trim();if(!command)return null;if(task.vendor&&isBuiltinVendor(task.vendor))return null;if(resolveCommandProtocol(command)!==GENERIC_PROTOCOL)return null;let walk=evidence.walkVendor,vendor=walk!==null&&isBuiltinVendor(walk)?walk:sniffProtocolFromTitle(evidence.title);return vendor?{command,vendor}:null}function protocolWriteBackFromLiveSession(task,evidence,customEngineIds){let id=task.vendor?.trim();if(!id)return null;if(getEngineProtocol(id)!==void 0)return null;if(!customEngineIds.includes(id))return null;let walk=evidence.walkVendor;return walk!==null&&isBuiltinVendor(walk)?{id,protocol:walk}:null}async function latestTranscriptMtime(vendor,worktree){if(!worktree)return 0;return protocolEntry(vendor).history.latestTranscriptMtimeForWorktree(worktree)}async function maybeAutoStart(orch,taskId,enabled=autoStatusEnabled){if(!enabled())return"skipped";let task=orch.getTask(taskId);if(!task)return"skipped";if((task.kind??"task")==="main")return"skipped";if(task.status!=="backlog")return"skipped";return await orch.setStatus(taskId,"in_progress"),"moved"}var SYNC_TIMEOUT_MS=60000,SYNC_CONFLICT="SYNC_CONFLICT",SYNC_DIRTY="SYNC_WORKTREE_DIRTY";async function git(cwd,args,signal,write=!1){return spawnCapture("git",args,{cwd,env:write?process.env:readOnlyGitProcessEnv(),signal})}function parseConflictedPaths(stdout){return stdout.split(`
|
|
3
|
+
`).map((line)=>line.trim()).filter((line)=>line.length>0)}async function syncWorktreeWithBase(worktreePath,baseRef,signal){let status=await git(worktreePath,["status","--porcelain=v1"],signal);if(status.status!==0)throw Error("git status failed");let dirty=parseDirtyPaths(status.stdout);if(dirty.length>0)throw Error(`${SYNC_DIRTY}: ${dirty.join(", ")}`);let before=await git(worktreePath,["rev-parse","HEAD"],signal),merge=await git(worktreePath,["merge","--no-edit",baseRef],signal,!0);if(merge.status!==0){let conflicted=await git(worktreePath,["diff","--name-only","--diff-filter=U"],signal),paths=parseConflictedPaths(conflicted.stdout);if(paths.length>0)throw Error(`${SYNC_CONFLICT}: ${paths.join(", ")}`);let detail=merge.stderr?.trim();throw Error(detail?`git merge ${baseRef} failed \u2014 ${detail}`:`git merge ${baseRef} failed`)}let after=await git(worktreePath,["rev-parse","HEAD"],signal);return{baseRef,alreadyCurrent:before.status===0&&before.stdout.trim()===after.stdout.trim()}}import{readFileSync}from"fs";import{join}from"path";var BASE_REF_TTL_MS=300000,cache=new Map;async function git2(worktreePath,args,signal){return await spawnCapture("git",[...args],{cwd:worktreePath,env:readOnlyGitProcessEnv(),signal})}async function refExists(worktreePath,ref,signal){return(await git2(worktreePath,["rev-parse","--verify","--quiet",ref],signal)).status===0}async function sharesHistory(worktreePath,ref,signal){return(await git2(worktreePath,["merge-base",ref,"HEAD"],signal)).status===0}async function baseCheckoutBranchFromGit(worktreePath,signal){let out=await git2(worktreePath,["worktree","list","--porcelain"],signal);if(out.status!==0)return null;return(out.stdout.split(`
|
|
4
|
+
|
|
5
|
+
`,1)[0]??"").split(`
|
|
6
|
+
`).find((l)=>l.startsWith("branch "))?.slice(7).trim().replace(/^refs\/heads\//,"")||null}function readRefSymbolic(dirs,ref){for(let dir of[dirs.gitDir,dirs.commonDir])try{let target=readFileSync(join(dir,ref),"utf8").trim().match(/^ref:\s*(.+)$/)?.[1]?.trim();if(target)return target}catch{}return null}function ladderFromFiles(worktreePath){let dirs=resolveGitDirs(worktreePath);if(!dirs)return;let originHead=readRefSymbolic(dirs,"refs/remotes/origin/HEAD")?.replace(/^refs\/remotes\//,""),baseCheckout=readRefSymbolic({gitDir:dirs.commonDir,commonDir:dirs.commonDir},"HEAD")?.replace(/^refs\/heads\//,""),names=[],head=readHeadSha(dirs),parts=[`HEAD=${head}`];for(let guess of[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]]){if(names.includes(guess))continue;let sha=readRefSha(dirs,guess);if(sha===null)continue;names.push(guess),parts.push(`${guess}=${sha}`)}return{names,fingerprint:head===null?null:parts.join(",")}}async function ladderFromGit(worktreePath,signal){let head=await git2(worktreePath,["symbolic-ref","--short","refs/remotes/origin/HEAD"],signal),originHead=head.status===0?head.stdout.trim():"",baseCheckout=await baseCheckoutBranchFromGit(worktreePath,signal),names=[],candidates=[...originHead?[originHead]:[],...DEFAULT_BASE_REF_CANDIDATES,...baseCheckout?[baseCheckout]:[]];for(let guess of candidates){if(names.includes(guess))continue;if(await refExists(worktreePath,guess,signal))names.push(guess)}return{names,fingerprint:null}}async function resolveBaseRefCached(worktreePath,recordedBaseRef,signal,now=Date.now()){if(recordedBaseRef){let dirs=resolveGitDirs(worktreePath);if(dirs&&readRefSha(dirs,recordedBaseRef)!==null)return recordedBaseRef;if(await refExists(worktreePath,recordedBaseRef,signal))return recordedBaseRef}let hit=cache.get(worktreePath);if(hit&&now-hit.at<BASE_REF_TTL_MS)return hit.ref;let ladder=ladderFromFiles(worktreePath)??await ladderFromGit(worktreePath,signal);if(hit&&ladder.fingerprint!==null&&hit.fingerprint===ladder.fingerprint)return cache.set(worktreePath,{...hit,at:now}),hit.ref;let ref=null;for(let candidate of ladder.names)if(await sharesHistory(worktreePath,candidate,signal)){ref=candidate;break}return cache.set(worktreePath,{ref,at:now,fingerprint:ladder.fingerprint}),ref}var cache2=new Map;function readShas(worktreePath,baseRef){let dirs=resolveGitDirs(worktreePath);if(!dirs)return null;let head=readHeadSha(dirs),base=readRefSha(dirs,baseRef);return head&&base?{head,base}:null}async function driftCached(worktreePath,baseRef,compute){let shas=readShas(worktreePath,baseRef),hit=shas?cache2.get(worktreePath):void 0;if(shas&&hit&&hit.head===shas.head&&hit.base===shas.base)return hit.value;let value=await compute();if(shas&&value!==null)cache2.set(worktreePath,{...shas,value});return value}import{statSync}from"fs";function judgeWorktree(signals,nowMs){if(signals.dirty)return{verdict:"active",reason:"dirty"};if(signals.prState==="open")return{verdict:"active",reason:"prOpen"};if(signals.prState==="merged")return{verdict:"merged",reason:"prMerged"};if(signals.aheadOfDefault===0)return{verdict:"merged",reason:"inMain"};if(signals.prState==="closed")return{verdict:"stale",reason:"prClosed"};if(signals.lastActivityMs>0&&nowMs-signals.lastActivityMs>1209600000)return{verdict:"stale",reason:"idle"};return{verdict:"fresh",reason:"fresh"}}function parseGhPrList(stdout){let entries;try{entries=JSON.parse(stdout)}catch{return null}if(!Array.isArray(entries))return null;let rank={open:3,merged:2,closed:1},map=new Map;for(let entry of entries){let branch=entry?.headRefName,rawState=entry?.state;if(typeof branch!=="string"||typeof rawState!=="string")continue;let state=rawState.toLowerCase();if(state!=="open"&&state!=="merged"&&state!=="closed")continue;let cur=map.get(branch);if(!cur||rank[state]>rank[cur])map.set(branch,state)}return map}var TIMEOUT_MS=4000,manager=new GitWorktreeManager;function createdAt(path){try{let stat=statSync(path);return stat.birthtimeMs||stat.mtimeMs}catch{return 0}}async function run(path,argv){return execHostForWorktreePath(path).run(argv,{cwd:path,signal:AbortSignal.timeout(TIMEOUT_MS)})}async function branchOnRemote(path,branch){try{let out=await run(path,["git","ls-remote","--exit-code","--heads","origin",branch]);return out.exitCode===0?!0:out.exitCode===2?!1:null}catch{return null}}async function defaultRef(repo){try{let out=await run(repo,["git","symbolic-ref","--short","refs/remotes/origin/HEAD"]);if(out.exitCode===0&&out.stdout.trim())return out.stdout.trim()}catch{}for(let guess of["origin/main","origin/master"])try{if((await run(repo,["git","rev-parse","--verify","--quiet",guess])).exitCode===0)return guess}catch{}return null}async function prStates(repo){try{let origin=await run(repo,["git","remote","get-url","origin"]);if(origin.exitCode!==0||!origin.stdout.includes("github.com"))return null;let out=await run(repo,["gh","pr","list","--state","all","--limit","200","--json","headRefName,state"]);return out.exitCode===0?parseGhPrList(out.stdout):null}catch{return null}}async function ahead(path,ref){if(!ref)return null;try{let out=await run(path,["git","rev-list","--count",`${ref}..HEAD`]),value=Number.parseInt(out.stdout.trim(),10);return out.exitCode===0&&!Number.isNaN(value)?value:null}catch{return null}}async function listWorktreeProjectsAdapter(network){let repos=getSavedRepos().filter((repo)=>!getRemoteRepoConfig(repo)),now=Date.now();return Promise.all(repos.map(async(repo)=>{let[worktrees,states,ref]=await Promise.all([manager.listAll(repo),network?prStates(repo):null,defaultRef(repo)]),rows=await Promise.all(worktrees.map(async(worktree)=>{let[remote,aheadBy]=await Promise.all([network?branchOnRemote(worktree.path,worktree.branch):null,ahead(worktree.path,ref)]),judgement=judgeWorktree({dirty:worktree.dirty===!0,prState:states?.get(worktree.branch)??null,aheadOfDefault:aheadBy,lastActivityMs:worktree.lastActivityMs},now);return{...worktree,repo,createdAtMs:createdAt(worktree.path),branchOnRemote:remote,verdict:judgement.verdict,verdictReason:judgement.reason}}));return{repo,worktrees:rows}}))}async function listUnreadableWorktreesAdapter(repo){return manager.listUnreadableWorktrees(repo)}async function removeWorktreeAdapter(path,force){let residue=null;return await manager.remove(path,{force,onSalvage:(record)=>{if(record)auditWorktreeSalvaged(path,record.ref,record.commit,record.uncaptured)},onResidue:(r)=>{residue={path:r.path,reason:r.reason},auditWorktreeResidue(r.path,r.reason)}}),residue}function resolveProtocolUpgradeAndLearnPreset(task,evidence){let preset=protocolWriteBackFromLiveSession(task,evidence,getCustomEngineIds());if(preset)setPersistedString(engineProtocolKey(preset.id),preset.protocol);return protocolUpgradeFromLiveSession(task,evidence)}var daemonRuntime={currentVersion:CURRENT_VERSION,defaultTaskVendor:DEFAULT_TASK_VENDOR,placeholderTaskTitle:PLACEHOLDER_TASK_TITLE,isTaskStatus,isEngineActivityKind,affectsActivityState,async foregroundEngines(pids){let rows=parsePsSnapshot(await psSnapshot()),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:engineTitleTurnHint,resolveProtocolUpgrade:resolveProtocolUpgradeAndLearnPreset,readEngineTurns:async(vendor,transcriptPath)=>await engineEntry(vendor).readTurns?.(transcriptPath)??[],checkLatestVersion,latestTranscriptMtime,deriveTitleFromSession,createEngineTurnDetector,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,kobeApiInvocation,engineEntry,ensureTaskSession:ensureTaskSessionAdapter,startTaskSessionWithPrompt:startTaskSessionWithPromptAdapter,tearDownTaskSession:tearDownTaskSessionAdapter,async readEngineContextUsage(vendor,sessionId){let read=engineEntry(vendor).history.readUsageSnapshot;if(!read)return null;let snapshot=await read(sessionId);if(snapshot?.context_tokens===void 0)return null;return{contextTokens:snapshot.context_tokens,...snapshot.context_window_tokens===void 0?{}:{contextWindowTokens:snapshot.context_window_tokens},...snapshot.context_tokens_approximate?{approximate:!0}:{},...snapshot.input_tokens===void 0?{}:{inputTokens:snapshot.input_tokens},...snapshot.output_tokens===void 0?{}:{outputTokens:snapshot.output_tokens},...snapshot.cache_read_input_tokens===void 0?{}:{cacheReadTokens:snapshot.cache_read_input_tokens},...snapshot.cache_creation_input_tokens===void 0?{}:{cacheCreationTokens:snapshot.cache_creation_input_tokens}}},quotaUsage:(vendor)=>engineEntry(vendor).quotaUsage?.()??Promise.resolve(null),vendorsWithQuotaProbe,deliverPromptToLiveEngine:deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailed:deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailed:deliverPromptToLiveEngineTabDetailedAdapter,composerGateEnabled,getPersistedString,setPersistedString,getSavedRepos:()=>[...getSavedRepos()],prStatus:{viewFields:GH_PR_VIEW_FIELDS,mapView:(view,at)=>mapGhPrView(view,at),sameStatus:samePrStatus,nextPoll:(outcome,failures,now,config,random)=>nextPrPoll(outcome,failures,now,config,random),classify:classifyGhFailure}};import{homedir}from"os";async function createKobeCore(options={}){let homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),store=new TaskIndexStore({homeDir});await store.load();let worktrees=new GitWorktreeManager,orchestrator=new Orchestrator({store,worktrees,onSalvage:(taskId,salvage)=>auditDeletionSalvaged(String(taskId),salvage.ref,salvage.commit,store.get(taskId)?.repo,salvage.uncaptured),onWorktreeResidue:(taskId,residue)=>auditDeletionResidue(String(taskId),residue.path,residue.reason),tearDownSession:(taskId)=>tearDownTaskSessionAdapter(String(taskId))}),backfilled=backfillSavedReposFromProjects(store.list().filter((task)=>task.kind==="main").map((task)=>task.repo));if(backfilled.length>0)console.error(`[rove] added ${backfilled.length} existing project(s) to the new-task picker`);return{homeDir,orchestrator,store,worktrees,async close(){orchestrator.dispose()}}}import{existsSync,readFileSync as readFileSync2,readdirSync,statSync as statSync2,unlinkSync}from"fs";import{join as join2}from"path";var TMP_MAX_AGE_MS=300000;function sweepIndexLeftovers(stateDir,now=Date.now()){let tmp=[],tmpBytes=0,entries;try{entries=readdirSync(stateDir)}catch{return{tmp,tmpBytes,lock:!1}}for(let name of entries){if(!name.startsWith("tasks.json.")||!name.endsWith(".tmp"))continue;let path=join2(stateDir,name);try{let stat=statSync2(path);if(now-stat.mtimeMs<TMP_MAX_AGE_MS)continue;unlinkSync(path),tmp.push(path),tmpBytes+=stat.size}catch{}}return{tmp,tmpBytes,lock:clearStaleLock(join2(stateDir,"tasks.json.lock"))}}function clearStaleLock(lockPath){let holder;try{holder=readFileSync2(lockPath,"utf8").trim()}catch{return!1}let pid=Number.parseInt(holder,10);if(Number.isFinite(pid)&&pid>0&&isProcessAlive(pid))return!1;return releaseSync(lockPath,holder),!existsSync(lockPath)}var CLI_NAME=activeCliName();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)"," stop Ask the running daemon to shut down"," restart Stop the daemon (graceful \u2192 SIGTERM \u2192 SIGKILL) and respawn it",""].join(`
|
|
7
|
+
`))}async function runDaemonSubcommand(argv){let[command="status"]=argv,socketPath=defaultDaemonSocketPath(),pidPath=defaultDaemonPidPath();if(command==="--help"||command==="-h"||command==="help"){printDaemonUsage(process.stdout);return}if(!SUBCOMMAND_VERBS.daemon.includes(command))process.stderr.write(`${CLI_NAME} daemon: unknown command "${command}"
|
|
8
|
+
|
|
9
|
+
`),printDaemonUsage(process.stderr),process.exit(2);if(command==="status"){let client=new KobeDaemonClient(socketPath);try{let status=await client.request("daemon.status");console.log(JSON.stringify(status,null,2))}catch{let pid=await readPidFile(pidPath);if(pid)console.log(`${CLI_NAME} daemon: no daemon socket at ${socketPath} (stale pidfile pid=${pid})`);else console.log(`${CLI_NAME} daemon: no daemon running at ${socketPath}`);process.exitCode=1}finally{client.close()}return}if(command==="stop"){let client=new KobeDaemonClient(socketPath);try{await client.request("daemon.stop"),console.log(`${CLI_NAME} daemon: stop requested`)}catch{console.log(`${CLI_NAME} daemon: no daemon running at ${socketPath}`)}finally{client.close()}return}if(command==="restart"){await stopDaemonProcess(socketPath,pidPath),(await connectOrStartDaemon()).close(),console.log(`${CLI_NAME} daemon: restarted, listening on ${socketPath}`);return}rotateLogIfNeeded(defaultDaemonLogPath()),installDaemonCrashHandlers();let socketState=await probeDaemonSocket(socketPath);if(socketState!=="absent")throw Error(`${CLI_NAME} daemon: ${socketState} daemon still owns ${socketPath}; run \`${CLI_NAME} daemon restart\``);let migration=migrateRoveDaemonStateLayout();for(let warning of migration.warnings)console.error(`[rove] daemon state migration will retry: ${warning}`);let core=await createKobeCore(),swept=sweepIndexLeftovers(core.store.stateDir);if(swept.lock||swept.tmp.length>0)console.error(`[rove] swept crash leftovers in ${core.store.stateDir}: ${swept.tmp.length} orphaned staging file(s) (${swept.tmpBytes} bytes)${swept.lock?", stale task-index lockfile":""}`);let server=await startDaemonServer(core.orchestrator,{runtime:daemonRuntime,socketPath,pidPath,homeDir:core.homeDir,plugins:{binPath:resolvePluginBinPath()},onStop:async()=>{await core.close()}});console.log(`${CLI_NAME} daemon: listening on ${server.socketPath}`);let shutdown=async()=>{await server.close(),await core.close(),process.exit(0)};process.once("SIGINT",()=>void shutdown()),process.once("SIGTERM",()=>void shutdown())}export{runDaemonSubcommand};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{isProcessAlive,stopDaemonProcess}from"./chunk-pdh5w4ht.js";import{readPidFile}from"./chunk-4wwx51m5.js";import{KobeDaemonClient}from"./chunk-79gqh5p2.js";import{DAEMON_PROTOCOL_VERSION}from"./chunk-3ztek08w.js";import{defaultDaemonLogPath,defaultDaemonPidPath,defaultDaemonSocketPath}from"./chunk-x760j10f.js";import{LEGACY_KOBE_PRODUCT_NAME,ROVE_PRODUCT_NAME}from"./chunk-3bfm4hrs.js";import{spawn}from"child_process";import{closeSync,existsSync,mkdirSync,openSync,statSync,unlinkSync}from"fs";import{dirname,resolve}from"path";import{fileURLToPath}from"url";var DAEMON_START_ARGS=["daemon","start"],DAEMON_HELLO_TIMEOUT_MS=3000,BUSY_DAEMON_GRACE_MS=15000;function detachOptions(platform=process.platform){return platform==="win32"?{windowsHide:!0}:{detached:!0}}function spawnDetachedDaemon(command,args,env,logPath){let stdio="ignore",logFd;try{mkdirSync(dirname(logPath),{recursive:!0}),logFd=openSync(logPath,"a"),stdio=["ignore",logFd,logFd]}catch{stdio="ignore"}if(spawn(command,[...args],{...detachOptions(),stdio,env}).unref(),logFd!==void 0)try{closeSync(logFd)}catch{}}function insideEngineSession(env=process.env){return typeof env.KOBE_TASK_ID==="string"&&env.KOBE_TASK_ID!==""}function autospawnDaemonEnv(env=process.env){let{KOBE_TASK_ID:_task,KOBE_TAB_ID:_tab,KOBE_TUI:_tui,KOBE_TERMINAL_PTY:_pty,ROVE_TASK_ID:_roveTask,ROVE_TAB_ID:_roveTab,ROVE_TUI:_roveTui,ROVE_TERMINAL_PTY:_rovePty,...rest}=env;return{...rest,KOBE_DAEMON_AUTOSPAWNED:"1",ROVE_DAEMON_AUTOSPAWNED:"1"}}var SPAWN_LOCK_STALE_MS=40000,SPAWN_LOCK_WAIT_MS=30000;function tryAcquireSpawnLock(lockPath,staleMs=SPAWN_LOCK_STALE_MS){let create=()=>{return mkdirSync(dirname(lockPath),{recursive:!0}),closeSync(openSync(lockPath,"wx")),!0};try{return create()}catch{try{if(Date.now()-statSync(lockPath).mtimeMs<=staleMs)return!1;return unlinkSync(lockPath),create()}catch{return!1}}}async function ensureDaemonReachable(resolveSpawn=resolveKobeSpawn){let socketPath=defaultDaemonSocketPath(),state=await probeDaemonSocket(socketPath);if(state==="alive")return socketPath;if(state==="wedged"&&insideEngineSession())throw Error(`rove: daemon at ${socketPath} is not answering hello (busy or wedged); not restarting it from inside an engine session \u2014 retry, or run \`rove daemon restart\` from a regular shell`);let lockPath=`${defaultDaemonPidPath()}.spawn-lock`;if(!tryAcquireSpawnLock(lockPath)){let deadline=Date.now()+SPAWN_LOCK_WAIT_MS;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,150))}throw Error(`rove: another process is starting the daemon but it never became reachable at ${socketPath}; check ${defaultDaemonLogPath()} or run \`rove doctor\``)}try{if(await probeDaemonSocket(socketPath)==="alive")return socketPath;let livePid=await readPidFile(defaultDaemonPidPath());if(livePid!==null&&livePid!==process.pid&&isProcessAlive(livePid)){let deadline2=Date.now()+BUSY_DAEMON_GRACE_MS;while(Date.now()<deadline2){if(await new Promise((resolveTimer)=>setTimeout(resolveTimer,250)),await testDaemonResponds(socketPath))return socketPath;if(!isProcessAlive(livePid))break}}let[command,...args]=resolveSpawn(DAEMON_START_ARGS);await stopDaemonProcess(socketPath,defaultDaemonPidPath()).catch(()=>{}),spawnDetachedDaemon(command,args,autospawnDaemonEnv(),defaultDaemonLogPath());let deadline=Date.now()+5000;while(Date.now()<deadline){if(await testDaemonResponds(socketPath))return socketPath;await new Promise((resolveTimer)=>setTimeout(resolveTimer,100))}throw Error(`rove: daemon did not start (or stayed wedged) at ${socketPath}; check ${defaultDaemonLogPath()} or run \`rove doctor\``)}finally{try{unlinkSync(lockPath)}catch{}}}async function connectOrStartDaemon(){let socketPath=await ensureDaemonReachable(),client=new KobeDaemonClient(socketPath);return await client.connect(),client}async function connectIfRunning(){let socketPath=defaultDaemonSocketPath();if(!await testDaemonResponds(socketPath))return null;let client=new KobeDaemonClient(socketPath);return await client.connect(),client}async function probeDaemonSocket(socketPath,timeoutMs=DAEMON_HELLO_TIMEOUT_MS){let probe=new KobeDaemonClient(socketPath);try{await probe.connect()}catch{return probe.close(),"absent"}let droppedByPeer=!1,offClose=probe.onLifecycle("close",()=>{droppedByPeer=!0}),replied=probe.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION}).then(()=>!0).catch(()=>!0),timer,timedOut=new Promise((resolve2)=>{timer=setTimeout(()=>resolve2(!1),timeoutMs)}),settled=await Promise.race([replied,timedOut]);if(timer)clearTimeout(timer);if(offClose(),probe.close(),droppedByPeer)return"absent";return settled?"alive":"wedged"}async function testDaemonResponds(socketPath,timeoutMs=DAEMON_HELLO_TIMEOUT_MS){return await probeDaemonSocket(socketPath,timeoutMs)==="alive"}class StaleInstallError extends Error{candidates;constructor(cliName,dir,candidates){super(`${cliName}: this process is running from an install that no longer exists on disk \u2014 no ${cliName} entry near ${dir} (checked ${candidates.join(", ")}). Reinstall (\`npm install -g @sma1lboy/rove\`) and relaunch Rove.`);this.name="StaleInstallError",this.candidates=candidates}}function isStaleInstallError(err){return err instanceof Error&&err.name==="StaleInstallError"}function resolveKobeSpawn(subcommand,env=process.env,moduleFile=fileURLToPath(import.meta.url)){let here=moduleFile;if(here.startsWith("/$bunfs")||here.startsWith("B:\\~BUN"))return[process.execPath,...subcommand];let dir=dirname(here),cliName=env.ROVE_INVOKED_AS===ROVE_PRODUCT_NAME?ROVE_PRODUCT_NAME:LEGACY_KOBE_PRODUCT_NAME,candidates=[resolve(dir,`../cli/${cliName}.ts`),resolve(dir,`../../../kobe/src/cli/${cliName}.ts`),resolve(dir,`../cli/${cliName}.js`),resolve(dir,"../cli/index.ts"),resolve(dir,"../../../kobe/src/cli/index.ts"),resolve(dir,"../cli/index.js")],entry=candidates.find((candidate)=>existsSync(candidate));if(entry)return[process.execPath,entry,...subcommand];throw new StaleInstallError(cliName,dir,candidates)}
|
|
3
|
+
export{detachOptions,spawnDetachedDaemon,autospawnDaemonEnv,tryAcquireSpawnLock,ensureDaemonReachable,connectOrStartDaemon,connectIfRunning,probeDaemonSocket,testDaemonResponds,StaleInstallError,isStaleInstallError,resolveKobeSpawn};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ENGINE_EXIT_BANNER,engineExitCodeFromTail,plainTail,readPtyExitRecords,readPtyExitStore,recordEngineExit,recordPtyExit}from"./chunk-yk2ha5yj.js";import"./chunk-rxvbm4vt.js";import"./chunk-x760j10f.js";import"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";export{recordPtyExit,recordEngineExit,readPtyExitStore,readPtyExitRecords,plainTail,engineExitCodeFromTail,ENGINE_EXIT_BANNER};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{canonicalize,execHostForRepo,execHostForWorktreePath,isKobeManagedPath,isUnderManagedWorktreesRoot,managedWorktreeRootForPath,remoteManagedRootForPath,remoteWorktreePathFor,requireAbsolute,worktreePathFor}from"./chunk-2jxdzw4r.js";import{READ_ONLY_GIT_ENV}from"./chunk-6xppe9bj.js";import{getRemoteRepoConfig}from"./chunk-k3ksts6g.js";import path3 from"path";var defaultExecDeps={execForRepo:execHostForRepo,execForPath:execHostForWorktreePath,remoteBasePath(repoKey){return getRemoteRepoConfig(repoKey)?.basePath??null}};class GitCommandError extends Error{args;cwd;exitCode;stdout;stderr;constructor(args,cwd,result){super(`git ${args.join(" ")} (cwd=${cwd}) exited with code ${result.exitCode}: ${result.stderr.trim()||result.stdout.trim()}`);this.name="GitCommandError",this.args=args,this.cwd=cwd,this.exitCode=result.exitCode,this.stdout=result.stdout,this.stderr=result.stderr}}var MAX_IGNORED_ENTRY_KB=65536;function parseIgnoredPaths(stdoutZ){return stdoutZ.split("\x00").filter((entry)=>entry.startsWith("!! ")).map((entry)=>entry.slice(3)).filter((p)=>p.length>0)}function parseDuKb(stdout){let sizes=new Map;for(let line of stdout.split(`
|
|
3
|
+
`)){let m=/^(\d+)\s+(.+)$/.exec(line.trim());if(m?.[1]&&m[2])sizes.set(m[2],Number.parseInt(m[1],10))}return sizes}async function smallIgnoredPaths(exec,worktreePath){try{let status=await exec.run(["git","status","--porcelain","-z","--ignored"],{cwd:worktreePath,env:READ_ONLY_GIT_ENV});if(status.exitCode!==0)return[];let paths=parseIgnoredPaths(status.stdout);if(paths.length===0)return[];let du=await exec.run(["du","-sk",...paths],{cwd:worktreePath}),sizes=parseDuKb(du.stdout);return paths.filter((p)=>{let kb=sizes.get(p);return kb!==void 0&&kb<=MAX_IGNORED_ENTRY_KB})}catch{return[]}}async function gitlinkPaths(git,tree){let out=await git(["ls-tree","-r",tree]);if(out.exitCode!==0)return[];return out.stdout.split(`
|
|
4
|
+
`).filter((line)=>line.startsWith("160000 ")).map((line)=>line.slice(line.indexOf("\t")+1)).filter((p)=>p.length>0)}function salvageRef(branch,now){let stamp=now.toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");return`refs/rove/salvage/${(branch??"detached").replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"")||"detached"}-${stamp}`}async function salvageWorktree(deps,exec,worktreePath,now=new Date){let git=(args)=>deps.runGit(exec,args,{cwd:worktreePath,allowFail:!0});try{let status=await git(["status","--porcelain"]);if(status.exitCode!==0)return null;let ignored=await smallIgnoredPaths(exec,worktreePath);if(status.stdout.trim().length===0&&ignored.length===0)return null;let indexPath=(await git(["rev-parse","--git-path","rove-salvage-index"])).stdout.trim();if(!indexPath)return null;let withIndex=(args)=>deps.runGit(exec,args,{cwd:worktreePath,allowFail:!0,env:{GIT_INDEX_FILE:indexPath}});try{if((await withIndex(["add","-A"])).exitCode!==0)return null;if(ignored.length>0)await withIndex(["add","-f","--",...ignored]);let tree=(await withIndex(["write-tree"])).stdout.trim();if(!tree)return null;let head=(await git(["rev-parse","HEAD"])).stdout.trim(),branch=(await git(["rev-parse","--abbrev-ref","HEAD"])).stdout.trim(),message=`rove salvage: force-removed worktree ${worktreePath}`,commit=(await withIndex(head?["commit-tree",tree,"-p",head,"-m",message]:["commit-tree",tree,"-m",message])).stdout.trim();if(!commit)return null;let ref=salvageRef(branch&&branch!=="HEAD"?branch:null,now);if((await git(["update-ref",ref,commit])).exitCode!==0)return null;return{ref,commit,uncaptured:await gitlinkPaths(git,tree)}}finally{await exec.run(["rm","-f",indexPath],{cwd:worktreePath}).catch(()=>{return})}}catch{return null}}async function anchorBranchTip(deps,exec,repo,branch,now=new Date){if(!branch||branch==="HEAD")return null;let git=(args)=>deps.runGit(exec,args,{cwd:repo,allowFail:!0});try{let tipOut=await git(["rev-parse","--verify",`refs/heads/${branch}`]),tip=tipOut.stdout.trim();if(tipOut.exitCode!==0||!tip)return null;let holders=await git(["for-each-ref","--contains",tip,"--format=%(refname)"]);if(holders.exitCode===0){if(holders.stdout.split(`
|
|
5
|
+
`).map((l)=>l.trim()).filter((l)=>l.length>0&&l!==`refs/heads/${branch}`).length>0)return null}let ref=salvageRef(branch,now);if((await git(["update-ref",ref,tip])).exitCode!==0)return null;return{ref,commit:tip,uncaptured:[]}}catch{return null}}async function branchExists(deps,ctx,branch){return(await deps.runGit(ctx.exec,["show-ref","--verify","--quiet",`refs/heads/${branch}`],{cwd:ctx.dir,allowFail:!0,readOnly:!0})).exitCode===0}async function deleteBranchIn(deps,exec,repo,branch,force){if(!branch||branch==="HEAD")return;await deps.runGit(exec,["branch",force?"-D":"-d",branch],{cwd:repo,allowFail:!0})}async function deleteBranchAnchored(deps,exec,repo,branch,opts){if(opts.force)opts.onAnchor?.(await anchorBranchTip(deps,exec,repo,branch));await deleteBranchIn(deps,exec,repo,branch,opts.force)}async function branchHasUpstream(deps,worktreePath,branch){return(await deps.runGit(deps.execAt(worktreePath),["for-each-ref","--format=%(upstream)",`refs/heads/${branch}`],{cwd:worktreePath,readOnly:!0})).stdout.trim().length>0}async function hasLocalBranch(deps,worktreePath,branch){return(await deps.runGit(deps.execAt(worktreePath),["show-ref","--verify","--quiet",`refs/heads/${branch}`],{cwd:worktreePath,allowFail:!0,readOnly:!0})).exitCode===0}async function renameBranch(deps,worktreePath,from,to){let exec=deps.execAt(worktreePath);if(from===to)return;let repo=await deps.findRepoFor(exec,worktreePath);if(!repo)throw Error(`renameBranch(): ${worktreePath} is not a git worktree`);let out=await deps.runGit(exec,["branch","-m",from,to],{cwd:repo,allowFail:!0});if(out.exitCode===0)return;let ctx={exec,dir:repo,remote:exec.isRemote};if(!await branchExists(deps,ctx,from)&&await branchExists(deps,ctx,to))return;throw new GitCommandError(["branch","-m",from,to],repo,out)}import fs from"fs";import path from"path";async function mapWithLimit(items,limit,fn){let results=Array(items.length),next=0,worker=async()=>{for(;;){let i=next++;if(i>=items.length)return;results[i]=await fn(items[i])}},width=Math.max(1,Math.min(limit,items.length));return await Promise.all(Array.from({length:width},worker)),results}var PROBE_CONCURRENCY=6;function parseWorktreeListPorcelain(out){let records=[],current=null;for(let rawLine of out.split(`
|
|
6
|
+
`)){let line=rawLine.replace(/\r$/,"");if(line===""){if(current)records.push(current);current=null;continue}if(!current)current={};if(line.startsWith("worktree "))current.path=line.slice(9);else if(line.startsWith("HEAD "))current.head=line.slice(5);else if(line.startsWith("branch ")){let ref=line.slice(7);current.branch=ref.startsWith("refs/heads/")?ref.slice(11):ref}else if(line==="detached")current.detached=!0;else if(line==="bare")current.bare=!0}if(current)records.push(current);return records}async function lastActivityMs(deps,ctx,worktreePath){try{let stdout=await deps.runGitStdoutAt(ctx,worktreePath,["log","-1","--format=%ct"]),secs=Number.parseInt(stdout.trim(),10);if(Number.isFinite(secs)&&secs>0)return secs*1000}catch{}if(!ctx.exec.isRemote)try{return fs.statSync(worktreePath).mtimeMs}catch{}return 0}async function listBranchNames(deps,repo){let ctx=deps.ctxFor(repo);requireAbsolute("repo",ctx.dir);let stdout;try{stdout=await deps.runGitStdout(ctx,["for-each-ref","--format=%(refname:short)","refs/heads","refs/remotes/origin"])}catch{return[]}let names=new Set;for(let line of stdout.split(`
|
|
7
|
+
`)){let name=line.trim().replace(/^origin\//,"");if(name&&name!=="HEAD")names.add(name)}return[...names]}async function listManaged(deps,repo){let ctx=deps.ctxFor(repo);requireAbsolute("repo",ctx.dir);let all=parseWorktreeListPorcelain(await deps.runGitStdout(ctx,["worktree","list","--porcelain"])),kept=[];for(let entry of all){if(!entry.path)continue;let callerRoot=ctx.remote?remoteManagedRootForPath(ctx.dir,entry.path):managedWorktreeRootForPath(repo,entry.path);if(!callerRoot)continue;if(!entry.branch||entry.detached)continue;let rel=path.relative(canonicalize(callerRoot),canonicalize(entry.path));kept.push({callerPath:path.join(callerRoot,rel),probePath:entry.path,branch:entry.branch,head:entry.head??""})}return mapWithLimit(kept,PROBE_CONCURRENCY,async(e)=>({path:e.callerPath,branch:e.branch,head:e.head,dirty:await deps.isDirty(e.probePath).catch(()=>null)}))}async function listAllAdoptable(deps,repo){let ctx=deps.ctxFor(repo),adoptable=await adoptablePaths(deps,ctx),infos=await mapWithLimit(adoptable,PROBE_CONCURRENCY,async(entry)=>{let[dirty,activityMs]=await Promise.all([deps.isDirty(entry.path).catch(()=>null),lastActivityMs(deps,ctx,entry.path)]);return{path:entry.path,branch:entry.branch,head:entry.head,dirty,kobeManaged:ctx.remote?remoteManagedRootForPath(ctx.dir,entry.path)!==null:isKobeManagedPath(repo,entry.path),lastActivityMs:activityMs}});return infos.sort((a,b)=>b.lastActivityMs-a.lastActivityMs),infos}async function adoptablePaths(deps,ctx){requireAbsolute("repo",ctx.dir);let all=parseWorktreeListPorcelain(await deps.runGitStdout(ctx,["worktree","list","--porcelain"])),canon=(p)=>ctx.remote?p:canonicalize(p),canonRepo=canon(ctx.dir),canonMain=all.find((entry)=>entry.path)?.path,canonMainPath=canonMain?canon(canonMain):null,kept=[];for(let entry of all){if(!entry.path)continue;if(entry.bare)continue;if(!entry.branch||entry.detached)continue;let canonEntry=canon(entry.path);if(canonMainPath!==null&&canonEntry===canonMainPath)continue;if(canonEntry===canonRepo)continue;kept.push({path:entry.path,branch:entry.branch,head:entry.head??""})}return kept}async function unreadableWorktreeNames(deps,ctx){if(ctx.remote)return[];requireAbsolute("repo",ctx.dir);let adminRoot;try{let common=(await deps.runGitStdout(ctx,["rev-parse","--git-common-dir"])).trim();if(!common)return[];adminRoot=path.join(path.resolve(ctx.dir,common),"worktrees")}catch{return[]}let names;try{names=fs.readdirSync(adminRoot,{withFileTypes:!0}).filter((entry)=>entry.isDirectory()).map((entry)=>entry.name)}catch{return[]}if(names.length===0)return[];let listed;try{listed=await deps.runGitStdout(ctx,["worktree","list","--porcelain"])}catch{return[]}let reported=new Set(parseWorktreeListPorcelain(listed).filter((entry)=>entry.path).map((entry)=>canonicalize(entry.path))),missing=[];for(let name of names){let gitdir;try{gitdir=fs.readFileSync(path.join(adminRoot,name,"gitdir"),"utf8").trim()}catch{missing.push(name);continue}if(gitdir&&!reported.has(canonicalize(path.dirname(gitdir))))missing.push(name)}return missing}import path2 from"path";async function isRegisteredWorktree(deps,exec,repo,worktreePath){let out=await deps.runGit(exec,["worktree","list","--porcelain"],{cwd:repo,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return!1;let same=(a,b)=>exec.isRemote?a===b:canonicalize(a)===canonicalize(b);return parseWorktreeListPorcelain(out.stdout).some((e)=>e.path!==void 0&&same(e.path,worktreePath))}async function deregisteredWorktreeResidue(exec,worktreePath){let pointer=(await exec.readFile(`${worktreePath}/.git`))?.trim().match(/^gitdir:\s*(.+)$/)?.[1]?.trim();if(!pointer)return!1;let marker="/worktrees/",at=pointer.lastIndexOf(marker);if(at<0)return!1;return await exec.exists(pointer.slice(0,at))}async function removeWorktree(deps,worktreePath,opts){requireAbsolute("path",worktreePath);let exec=deps.execForPath(worktreePath),force=opts?.force===!0;if(!await exec.exists(worktreePath)){let goneRepo=opts?.repo??await deps.findRepoFor(exec,path2.dirname(worktreePath));if(goneRepo){if(await deps.runGit(exec,["worktree","prune"],{cwd:goneRepo,allowFail:!0}),opts?.deleteBranch===!0&&opts.branch)await deleteBranchAnchored(deps.branchDeps(),exec,goneRepo,opts.branch,{force})}return}let repo=await deps.findRepoFor(exec,worktreePath);if(repo===null||!await isRegisteredWorktree(deps,exec,repo,worktreePath)){if(await deregisteredWorktreeResidue(exec,worktreePath)){opts?.onResidue?.({path:worktreePath,reason:"a previous removal deregistered the worktree"});return}if(repo){opts?.onResidue?.({path:worktreePath,reason:"a previous removal deregistered the worktree"});return}if(!force)throw Error(`remove(): ${worktreePath} is not a git worktree`);if(!isUnderManagedWorktreesRoot(worktreePath))throw Error(`remove(): ${worktreePath} has no reachable git repo and is not under a Rove worktrees root; refusing to delete it`);if(opts?.onSalvage?.(null),await exec.run(["rm","-rf",worktreePath]),await exec.exists(worktreePath))opts?.onResidue?.({path:worktreePath,reason:"the directory could not be deleted"});return}let branch=opts?.deleteBranch?await deps.currentBranch(worktreePath).catch(()=>null)??opts.branch??null:null;if(force){let salvaged=await salvageWorktree({runGit:(e,a,o)=>deps.runGit(e,a,o)},exec,worktreePath);opts?.onSalvage?.(salvaged)}else{if(await deps.isDirty(worktreePath))throw Error(`remove(): refusing to remove dirty worktree at ${worktreePath} (pass { force: true } to override)`);let ignored=await deps.ignoredWork(worktreePath).catch(()=>[]);if(ignored.length>0)throw Error(`remove(): refusing to remove worktree at ${worktreePath} \u2014 it holds gitignored work git status cannot see: ${ignored.join(", ")} (pass { force: true } to override)`)}let args=force?["worktree","remove","--force",worktreePath]:["worktree","remove",worktreePath],result=await deps.runGit(exec,args,{cwd:repo,allowFail:!0});if(result.exitCode!==0){if(await isRegisteredWorktree(deps,exec,repo,worktreePath))throw new GitCommandError(args,repo,result);opts?.onResidue?.({path:worktreePath,reason:result.stderr.trim()||result.stdout.trim()||"unknown"})}if(await deps.runGit(exec,["worktree","prune"],{cwd:repo,allowFail:!0}),branch)await deleteBranchAnchored(deps.branchDeps(),exec,repo,branch,{force})}class GitWorktreeManager{execDeps;constructor(execDeps=defaultExecDeps){this.execDeps=execDeps}ctxFor(repoKey){let basePath=this.execDeps.remoteBasePath(repoKey);return basePath?{exec:this.execDeps.execForRepo(repoKey),dir:basePath,remote:!0}:{exec:this.execDeps.execForRepo(repoKey),dir:repoKey,remote:!1}}async runGit(exec,args,opts){if(!opts.cwd)throw Error("runGit(): cwd is required; refusing to inherit from process.cwd()");let env=opts.readOnly?{...opts.env,...READ_ONLY_GIT_ENV}:opts.env,r=await exec.run(["git",...args],{cwd:opts.cwd,env}),result={stdout:r.stdout,stderr:r.stderr,exitCode:r.exitCode};if(result.exitCode!==0&&!opts.allowFail)throw new GitCommandError(args,opts.cwd,result);return result}async create(repo,branch,worktreePath,baseRef){let ctx=this.ctxFor(repo);if(requireAbsolute("repo",ctx.dir),requireAbsolute("path",worktreePath),!branch)throw Error("create(): branch must be a non-empty string");if(await ctx.exec.exists(worktreePath)){let existing=await this.tryDescribe(ctx,worktreePath);if(existing){if(existing.branch!==branch)throw Error(`worktree at ${worktreePath} is on branch '${existing.branch}', refusing to hijack to '${branch}'`);return existing}throw Error(`create(): ${worktreePath} exists but is not a registered git worktree`)}await ctx.exec.mkdirp(path3.dirname(worktreePath));let args=await branchExists(this.branchDeps(),ctx,branch)?["worktree","add",worktreePath,branch]:baseRef?["worktree","add","-b",branch,worktreePath,baseRef]:["worktree","add","-b",branch,worktreePath];await this.runGit(ctx.exec,args,{cwd:ctx.dir});let info=await this.tryDescribe(ctx,worktreePath);if(!info)throw Error(`create(): git reported success but ${worktreePath} is not a worktree`);if(info.branch!==branch)throw Error(`create(): post-condition failed \u2014 expected branch '${branch}' at ${worktreePath}, got '${info.branch}'`);return info}async createForTask(args){let basePath=this.execDeps.remoteBasePath(args.repo),target=basePath?remoteWorktreePathFor(basePath,args.slug):worktreePathFor(args.repo,args.slug);return this.create(args.repo,args.branch,target,args.baseRef)}async remove(worktreePath,opts){await removeWorktree({runGit:(exec,args,runOpts)=>this.runGit(exec,args,runOpts),execForPath:(p)=>this.execDeps.execForPath(p),findRepoFor:(exec,p)=>this.findRepoFor(exec,p),currentBranch:(p)=>this.currentBranch(p),isDirty:(p)=>this.isDirty(p),ignoredWork:(p)=>this.ignoredWork(p),branchDeps:()=>this.branchDeps()},worktreePath,opts)}async deleteBranch(repo,branch,opts){let ctx=this.ctxFor(repo);requireAbsolute("repo",ctx.dir),await deleteBranchAnchored(this.branchDeps(),ctx.exec,ctx.dir,branch,{force:opts?.force===!0,onAnchor:opts?.onAnchor})}execAt(worktreePath){return requireAbsolute("path",worktreePath),this.execDeps.execForPath(worktreePath)}branchDeps(){return{runGit:(exec,args,opts)=>this.runGit(exec,args,opts),execAt:(worktreePath)=>this.execAt(worktreePath),findRepoFor:(exec,worktreePath)=>this.findRepoFor(exec,worktreePath)}}listDeps(){return{ctxFor:(repoKey)=>this.ctxFor(repoKey),runGitStdout:async(ctx,args)=>(await this.runGit(ctx.exec,args,{cwd:ctx.dir,readOnly:!0})).stdout,runGitStdoutAt:async(ctx,cwd,args)=>(await this.runGit(ctx.exec,args,{cwd,readOnly:!0})).stdout,isDirty:(worktreePath)=>this.isDirty(worktreePath)}}list(repo){return listManaged(this.listDeps(),repo)}listAll(repo){return listAllAdoptable(this.listDeps(),repo)}listAdoptablePaths(repo){return adoptablePaths(this.listDeps(),this.ctxFor(repo))}listUnreadableWorktrees(repo){return unreadableWorktreeNames(this.listDeps(),this.ctxFor(repo))}listBranchNames(repo){return listBranchNames(this.listDeps(),repo)}async pathExists(worktreePath){return this.execAt(worktreePath).exists(worktreePath)}async pruneWorktrees(repo){let ctx=this.ctxFor(repo);requireAbsolute("repo",ctx.dir),await this.runGit(ctx.exec,["worktree","prune"],{cwd:ctx.dir,allowFail:!0})}async isDirty(worktreePath){return(await this.runGit(this.execAt(worktreePath),["status","--porcelain"],{cwd:worktreePath,readOnly:!0})).stdout.length>0}async ignoredWork(worktreePath){return smallIgnoredPaths(this.execAt(worktreePath),worktreePath)}async currentBranch(worktreePath){let name=(await this.runGit(this.execAt(worktreePath),["rev-parse","--abbrev-ref","HEAD"],{cwd:worktreePath,readOnly:!0})).stdout.trim();if(!name||name==="HEAD")throw Error(`currentBranch(): ${worktreePath} is in detached-HEAD state`);return name}branchHasUpstream(worktreePath,branch){return branchHasUpstream(this.branchDeps(),worktreePath,branch)}hasLocalBranch(worktreePath,branch){return hasLocalBranch(this.branchDeps(),worktreePath,branch)}renameBranch(worktreePath,from,to){return renameBranch(this.branchDeps(),worktreePath,from,to)}async tryDescribe(ctx,worktreePath){let out=await this.runGit(ctx.exec,["worktree","list","--porcelain"],{cwd:ctx.dir,readOnly:!0}),entries=parseWorktreeListPorcelain(out.stdout),norm=(p)=>ctx.remote?p:canonicalize(p),target=norm(worktreePath),match=entries.find((e)=>e.path&&norm(e.path)===target);if(!match||!match.path||!match.branch||match.detached)return null;return{path:worktreePath,branch:match.branch,head:match.head??"",dirty:await this.isDirty(match.path)}}async findRepoFor(exec,worktreePath){try{let out=await this.runGit(exec,["rev-parse","--git-common-dir"],{cwd:worktreePath,allowFail:!0,readOnly:!0});if(out.exitCode!==0)return null;let gitDir=out.stdout.trim();if(!gitDir)return null;let absolute=path3.isAbsolute(gitDir)?gitDir:path3.resolve(worktreePath,gitDir);return path3.basename(absolute)===".git"?path3.dirname(absolute):absolute}catch(err){if(err instanceof GitCommandError)return null;throw err}}}
|
|
8
|
+
export{defaultExecDeps,GitWorktreeManager};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{LEGACY_KOBE_CONFIG_DIR_BASENAME,LEGACY_KOBE_STATE_DIR_BASENAME,ROVE_STATE_DIR_BASENAME as ROVE_STATE_DIR_BASENAME2}from"./chunk-cb2fpajx.js";import{ROVE_CONFIG_DIR_BASENAME,ROVE_STATE_DIR_BASENAME,readRoveEnv,readRoveHomeDirEnv}from"./chunk-3bfm4hrs.js";import{createHash}from"crypto";import{join as join2}from"path";import{homedir}from"os";import{join}from"path";function resolveProductHomeDir(){return readRoveHomeDirEnv()??homedir()}function defaultUiPrefsStatePath(homeDir=resolveProductHomeDir()){return join(homeDir,".config",ROVE_CONFIG_DIR_BASENAME,"state.json")}function defaultKeybindingsPath(homeDir=resolveProductHomeDir()){return join(homeDir,ROVE_STATE_DIR_BASENAME,"settings","keybindings.yaml")}function isDev(){return readRoveEnv("DEV")==="1"}function homeDir(){return resolveProductHomeDir()}function roveStateDir(){return join2(homeDir(),ROVE_STATE_DIR_BASENAME2)}function legacyKobeStateDir(){return join2(homeDir(),LEGACY_KOBE_STATE_DIR_BASENAME)}function kvStatePath(){return defaultUiPrefsStatePath(homeDir())}function legacyKobeKvStatePath(){return join2(homeDir(),".config",LEGACY_KOBE_CONFIG_DIR_BASENAME,"state.json")}function keybindingsConfigPath(){return defaultKeybindingsPath(homeDir())}function promptAttachmentsDir(){return join2(roveStateDir(),"attachments")}function remoteControlSocketPath(host,user,port){let hash=createHash("sha1").update(`${user}@${host}:${port??22}`).digest("hex").slice(0,16);return join2(roveStateDir(),"ssh",`${hash}.sock`)}function worktreeInitMarkerPath(worktreePath){let hash=createHash("sha1").update(worktreePath).digest("hex").slice(0,16);return join2(roveStateDir(),"worktree-init",hash)}
|
|
3
|
+
export{defaultUiPrefsStatePath,defaultKeybindingsPath,isDev,homeDir,roveStateDir,legacyKobeStateDir,kvStatePath,legacyKobeKvStatePath,keybindingsConfigPath,promptAttachmentsDir,remoteControlSocketPath,worktreeInitMarkerPath};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ulid}from"./chunk-qkehg2c1.js";import{acquireWithRetry,mergeTasksWithDisk,readDiskIndex,recoverIndexFromDisk,release}from"./chunk-qtke4x42.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{LEGACY_KOBE_STATE_DIR_BASENAME,ROVE_STATE_DIR_BASENAME}from"./chunk-cb2fpajx.js";import{readRoveHomeDirEnv}from"./chunk-3bfm4hrs.js";import{mkdir,open,rename,unlink}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var CURRENT_VERSION=3;class TaskIndexStore{homeDir;roveDir;path;legacyPath;lockPath;cache={version:CURRENT_VERSION,tasks:[]};loaded=!1;listeners=new Set;saveChain=Promise.resolve();dirtyIds=new Set;removedIds=new Map;constructor(options={}){this.homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),this.roveDir=join(this.homeDir,ROVE_STATE_DIR_BASENAME),this.path=join(this.roveDir,"tasks.json"),this.legacyPath=join(this.homeDir,LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),this.lockPath=`${this.path}.lock`}subscribe(listener){if(this.listeners.add(listener),this.loaded)try{listener(this.cache.tasks.slice())}catch(err){console.error("[rove TaskIndexStore] listener threw on subscribe:",err)}return()=>{this.listeners.delete(listener)}}get filePath(){return this.path}get stateDir(){return this.roveDir}async load(){return this.dirtyIds.clear(),this.removedIds.clear(),this.cache=await recoverIndexFromDisk(this.path,this.legacyPath),this.loaded=!0,this.notifyListeners(),this.snapshot()}async save(){this.assertLoaded();let next=this.saveChain.then(()=>this.doSave());return this.saveChain=next.catch(()=>{}),next}async saveOrRollback(id,undo){try{await this.save()}catch(err){if(undo())this.dirtyIds.delete(id),this.notifyListeners();throw err}}async doSave(){await mkdir(dirname(this.path),{recursive:!0});let dirty=new Set(this.dirtyIds),removed=new Map(this.removedIds),lockToken=await acquireWithRetry(this.lockPath),cacheChanged=!1;try{let disk=await readDiskIndex(this.path,this.legacyPath),merged=mergeTasksWithDisk(this.cache.tasks,disk.tasks,dirty,removed,disk.removed),payload={version:CURRENT_VERSION,tasks:merged.tasks,...merged.removed.length>0?{removed:merged.removed}:{}},json=`${JSON.stringify(payload)}
|
|
3
|
+
`,tmpPath=`${this.path}.${process.pid}.${ulid()}.tmp`;try{let handle=await open(tmpPath,"w",384);try{await handle.writeFile(json,"utf8"),await handle.sync()}finally{await handle.close()}await rename(tmpPath,this.path)}catch(err){throw await unlink(tmpPath).catch(()=>{}),err}for(let id of dirty)this.dirtyIds.delete(id);for(let id of removed.keys())this.removedIds.delete(id);let present=new Set(this.cache.tasks.map((t)=>t.id));for(let task of merged.tasks){if(present.has(task.id))continue;this.cache.tasks.push(task),cacheChanged=!0}let tombstoned=new Set(merged.removed.map((t)=>t.id));if(tombstoned.size>0)for(let i=this.cache.tasks.length-1;i>=0;i--){let entry=this.cache.tasks[i];if(!entry||!tombstoned.has(entry.id))continue;this.cache.tasks.splice(i,1),cacheChanged=!0}}finally{await release(this.lockPath,lockToken).catch((err)=>{console.error("[rove TaskIndexStore] index lock release failed:",err)})}if(cacheChanged)this.notifyListeners()}get(id){return this.assertLoaded(),this.cache.tasks.find((t)=>t.id===id)}list(){return this.assertLoaded(),this.cache.tasks.slice()}async create(partial){this.assertLoaded();let now=new Date().toISOString(),task={vendor:partial.vendor??DEFAULT_TASK_VENDOR,...partial,id:toTaskId(ulid()),createdAt:now,updatedAt:now};return this.cache.tasks.push(task),this.dirtyIds.add(task.id),await this.saveOrRollback(task.id,()=>{let at=this.cache.tasks.indexOf(task);if(at<0)return!1;return this.cache.tasks.splice(at,1),!0}),this.notifyListeners(),task}async update(id,patch){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)throw Error(`task not found: ${id}`);let existing=this.cache.tasks[idx];if(!existing)throw Error(`task not found: ${id}`);let{id:_id,createdAt:_createdAt,...mutable}=patch,next={...existing,...mutable,id:existing.id,createdAt:existing.createdAt,updatedAt:new Date().toISOString()};return this.cache.tasks[idx]=next,this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks[at]=existing,!0}),this.notifyListeners(),next}touchRecency(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return;let existing=this.cache.tasks[idx];if(!existing)return;this.cache.tasks[idx]={...existing,updatedAt:new Date().toISOString()},this.dirtyIds.add(String(id)),this.notifyListeners()}async move(id,delta,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);let ids=withinIds?.length?withinIds:this.cache.tasks.map((t)=>t.id),pos=ids.indexOf(String(id));if(pos<0)throw Error(`task not movable in current group: ${id}`);let targetId=ids[pos+delta];if(!targetId)return task;let fromIdx=this.cache.tasks.findIndex((t)=>t.id===id),toIdx=this.cache.tasks.findIndex((t)=>t.id===targetId);if(fromIdx<0||toIdx<0||fromIdx===toIdx)return task;let[moved]=this.cache.tasks.splice(fromIdx,1);if(!moved)return task;let adjustedToIdx=fromIdx<toIdx?toIdx-1:toIdx,insertAt=delta>0?adjustedToIdx+1:adjustedToIdx,next={...moved,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(insertAt,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,moved),!0}),this.notifyListeners(),next}async remove(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return!1;return this.cache.tasks.splice(idx,1),this.dirtyIds.delete(String(id)),this.removedIds.set(String(id),new Date().toISOString()),await this.save(),this.notifyListeners(),!0}async _unlinkForTests(){try{await unlink(this.path)}catch(err){if(err.code!=="ENOENT")throw err}this.cache={version:CURRENT_VERSION,tasks:[]},this.loaded=!1,this.dirtyIds.clear(),this.removedIds.clear()}assertLoaded(){if(!this.loaded)throw Error("TaskIndexStore: call load() before any other method")}snapshot(){return{version:CURRENT_VERSION,tasks:this.cache.tasks.slice()}}notifyListeners(){if(this.listeners.size===0)return;let snapshot=this.cache.tasks.slice();for(let listener of this.listeners)try{listener(snapshot)}catch(err){console.error("[rove TaskIndexStore] listener threw on notify:",err)}}}
|
|
4
|
+
export{TaskIndexStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
// @bun
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{BLOCKING_RPCS,frameToLine}from"./chunk-3ztek08w.js";import{logClientError}from"./chunk-grh6dvfv.js";import{readRoveEnv}from"./chunk-3bfm4hrs.js";import{connect}from"net";import{StringDecoder}from"string_decoder";class RpcTimeoutError extends Error{constructor(name,timeoutMs){super(`daemon rpc "${name}" timed out after ${timeoutMs}ms (daemon wedged?)`);this.name="RpcTimeoutError"}}function rpcTimeoutMs(){let raw=readRoveEnv("RPC_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 20000}class KobeDaemonClient{socketPath;socket=null;buffer="";nextId=1;pending=new Map;handlers=new Map;lifecycleHandlers=new Map;connecting=null;disposed=!1;constructor(socketPath){this.socketPath=socketPath}connect(){if(this.socket)return Promise.resolve();if(this.disposed)return Promise.reject(Error("daemon client disposed"));if(this.connecting)return this.connecting;let p=this.openSocket();this.connecting=p;let cleanup=()=>{if(this.connecting===p)this.connecting=null};return p.then(cleanup,cleanup),p}get isDisposed(){return this.disposed}close(){this.disposed=!0,this.socket?.end(),this.socket=null,this.failPending()}forceDisconnect(){let socket=this.socket;if(!socket)return;this.socket=null,socket.destroy(),this.failPending()}failPending(){if(this.pending.size===0)return;let err=Error("daemon connection closed");for(let pending of this.pending.values()){if(pending.timer)clearTimeout(pending.timer);pending.reject(err)}this.pending.clear()}on(name,handler){let set=this.handlers.get(name);if(!set)set=new Set,this.handlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.handlers.delete(name)}}onChannel(channel,handler){return this.on(channel,(frame)=>handler(frame.payload))}subscribe(opts={}){let payload={};if(opts.channels)payload.channels=opts.channels;if(opts.role)payload.role=opts.role;return this.request("subscribe",payload)}onLifecycle(name,handler){let set=this.lifecycleHandlers.get(name);if(!set)set=new Set,this.lifecycleHandlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.lifecycleHandlers.delete(name)}}async request(name,payload){await this.connect();let socket=this.socket;if(!socket)throw Error("daemon connection is not open");let id=String(this.nextId++),promise=new Promise((resolve,reject)=>{let entry={resolve:(value)=>resolve(value),reject},timeoutMs=rpcTimeoutMs();if(timeoutMs>0&&!BLOCKING_RPCS.has(name))entry.timer=setTimeout(()=>this.onRequestTimeout(id,name,timeoutMs),timeoutMs);this.pending.set(id,entry)});return socket.write(frameToLine({type:"request",id,name,payload})),promise}onRequestTimeout(id,name,timeoutMs){let pending=this.pending.get(id);if(!pending)return;this.pending.delete(id),pending.reject(new RpcTimeoutError(name,timeoutMs)),this.forceDisconnect(),this.emitLifecycle("close")}openSocket(){return new Promise((resolve,reject)=>{let socket=connect(this.socketPath);this.socket=socket;let onConnect=()=>{socket.off("error",onError),socket.on("error",()=>socket.destroy()),resolve()},onError=(err)=>{if(socket.off("connect",onConnect),this.socket===socket)this.socket=null;reject(err)};socket.once("connect",onConnect),socket.once("error",onError);let decoder=new StringDecoder("utf8");this.buffer="",socket.on("data",(chunk)=>this.onData(decoder.write(chunk))),socket.on("close",()=>this.onSocketClose(socket))})}onSocketClose(which){if(this.socket!==which)return;this.socket=null,this.failPending(),this.emitLifecycle("close")}emitLifecycle(name){for(let handler of this.lifecycleHandlers.get(name)??[])try{handler()}catch(err){console.error(`[rove] lifecycle handler for "${name}" threw:`,err)}}onData(chunk){this.buffer+=chunk;let nl=this.buffer.indexOf(`
|
|
3
|
+
`);while(nl!==-1){let line=this.buffer.slice(0,nl);if(this.buffer=this.buffer.slice(nl+1),line.trim().length>0)this.onLine(line);nl=this.buffer.indexOf(`
|
|
4
|
+
`)}}onLine(line){let frame;try{frame=JSON.parse(line)}catch(err){logClientError("client-frame",err);return}if(frame.type==="event"){this.emit(frame);return}if(frame.type!=="response")return;let pending=this.pending.get(frame.id);if(!pending)return;if(this.pending.delete(frame.id),pending.timer)clearTimeout(pending.timer);if(frame.error){let err=Error(frame.error.message);if(frame.error.name)err.name=frame.error.name;pending.reject(err)}else pending.resolve(frame.payload)}emit(frame){for(let handler of this.handlers.get(frame.name)??[])try{handler(frame)}catch(err){logClientError("client-event",err)}for(let handler of this.handlers.get("*")??[])try{handler(frame)}catch(err){logClientError("client-event",err)}}}
|
|
5
|
+
export{RpcTimeoutError,KobeDaemonClient};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{stampResetGate}from"./chunk-mggca3k4.js";import{stopLegacyTmux}from"./chunk-dqndd97s.js";import"./chunk-eq5f3z2f.js";import{stopDaemonProcess}from"./chunk-pdh5w4ht.js";import"./chunk-4wwx51m5.js";import"./chunk-79gqh5p2.js";import"./chunk-3ztek08w.js";import"./chunk-kwe61yx7.js";import"./chunk-gjf604bb.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{kvStatePath,legacyKobeKvStatePath,legacyKobeStateDir,roveStateDir}from"./chunk-6dn6h640.js";import{activeCliName}from"./chunk-ef11h2am.js";import"./chunk-8ddjfc2v.js";import"./chunk-cb2fpajx.js";import"./chunk-grh6dvfv.js";import"./chunk-pw6yfj10.js";import{defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-x760j10f.js";import"./chunk-3bfm4hrs.js";import"./chunk-wqfp8d9w.js";import{readFileSync}from"fs";import{unlink}from"fs/promises";import{join}from"path";import{createInterface}from"readline";var CLI_NAME=activeCliName();function printUsage(out){out.write([`Usage: ${CLI_NAME} reset [--hard] [--yes]`,"","Recover a wedged install: stop the daemon, Hosted PTY host, and any pre-v0.8 tmux sessions.","This ends background terminal and engine sessions; the next launch starts fresh.","Never touches your git worktrees.","","Options:"," --hard Also wipe the task index + UI state"," -y, --yes Skip the interactive confirmation"," -h, --help Print this help",""].join(`
|
|
3
|
+
`))}function taskCount(path){try{let parsed=JSON.parse(readFileSync(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}async function confirmTty(prompt){let readline=createInterface({input:process.stdin,output:process.stdout});try{let answer=await new Promise((resolve)=>readline.question(prompt,resolve));return/^y(es)?$/i.test(answer.trim())}finally{readline.close()}}async function removeStateFile(path,label){try{await unlink(path),console.log(` removed ${label} (${path})`)}catch(err){if(err.code==="ENOENT")console.log(` ${label}: already absent`);else throw Error(`failed to remove ${label} (${path}): ${errorMessage(err)}`)}}async function runResetSubcommand(argv){if(argv.some((arg)=>arg==="--help"||arg==="-h"||arg==="help")){printUsage(process.stdout);return}let known=new Set(["--hard","--yes","-y"]),unknown=argv.find((arg)=>!known.has(arg));if(unknown!==void 0)process.stderr.write(`${CLI_NAME} reset: unknown argument "${unknown}"
|
|
4
|
+
|
|
5
|
+
`),printUsage(process.stderr),process.exit(2);let hard=argv.includes("--hard"),yes=argv.includes("--yes")||argv.includes("-y"),daemonSocket=defaultDaemonSocketPath(),tasksPath=join(roveStateDir(),"tasks.json"),legacyTasksPath=join(legacyKobeStateDir(),"tasks.json"),statePath=kvStatePath(),legacyStatePath=legacyKobeKvStatePath();if(console.log(`${CLI_NAME} reset will:`),console.log(" \u2022 stop the Rove daemon (graceful \u2192 SIGTERM \u2192 SIGKILL)"),console.log(` \u2022 remove its socket + pidfile (${daemonSocket})`),console.log(" \u2022 stop the standalone Hosted PTY host and all background terminal/engine sessions"),console.log(" \u2022 stop any pre-v0.8 tmux sessions after SIGTERM-ing their pane process groups"),hard){let count=taskCount(tasksPath)??taskCount(legacyTasksPath);console.log(` \u2022 DELETE the task index${count===null?"":` (${count} task(s))`} \u2014 ${tasksPath}`),console.log(` \u2022 DELETE the UI state \u2014 ${statePath}`),console.log(" \u2022 DELETE the pre-Rove task/UI indexes too, so migration cannot restore reset state")}if(console.log(" \u2022 NOT touch your git worktrees under ~/.rove/worktrees/, ~/.kobe/worktrees/, or repo-local roots"),!hard)console.log(" (your task list & worktrees are kept \u2014 add --hard to also wipe task and UI state)");if(!yes){if(!process.stdin.isTTY){console.log(`
|
|
6
|
+
re-run with --yes to proceed (no interactive terminal for a y/N prompt)`);return}if(!await confirmTty(hard?`
|
|
7
|
+
Stop runtimes and wipe task/UI state? [y/N] `:`
|
|
8
|
+
Stop runtimes? [y/N] `)){console.log("aborted \u2014 nothing changed");return}}console.log("");let daemon=await stopDaemonProcess(daemonSocket,defaultDaemonPidPath());console.log(daemon.method==="absent"?" daemon: was not running (cleared any stale socket/pidfile)":` daemon: stopped via ${daemon.method}${daemon.pid?` (pid ${daemon.pid})`:""}`);let ptyHost=await stopDaemonProcess(defaultPtyHostSocketPath(),defaultPtyHostPidPath());console.log(ptyHost.method==="absent"?" pty host: was not running (cleared any stale socket/pidfile)":` pty host: stopped via ${ptyHost.method}${ptyHost.pid?` (pid ${ptyHost.pid})`:""}`);let legacyTmux=await stopLegacyTmux();if(legacyTmux.status==="failed"){console.error(` legacy tmux: cleanup failed \u2014 ${legacyTmux.error??"unknown error"}`),process.exitCode=1;return}if(console.log(legacyTmux.status==="absent"?" legacy tmux: no pre-v0.8 sessions found":` legacy tmux: stopped ${legacyTmux.sessions} session(s) after signalling ${legacyTmux.signalledGroups} pane group(s)`),hard)await removeStateFile(tasksPath,"task index"),await removeStateFile(legacyTasksPath,"legacy task index"),await removeStateFile(statePath,"UI state"),await removeStateFile(legacyStatePath,"legacy UI state");else stampResetGate();console.log(`
|
|
9
|
+
${CLI_NAME}: reset complete. Relaunch Rove to start fresh.`)}export{runResetSubcommand};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{quoteShellArgv}from"./chunk-2fypr41w.js";import{acquireSync,acquireWithRetry,release,releaseSync}from"./chunk-qtke4x42.js";import{roveStateDir}from"./chunk-6dn6h640.js";import{activeCliName}from"./chunk-ef11h2am.js";import{LEGACY_KOBE_PRODUCT_NAME,ROVE_PRODUCT_NAME}from"./chunk-cb2fpajx.js";import{fileURLToPath}from"url";function roveCliInvocation(){let cliName=activeCliName();if(import.meta.url.endsWith(".js"))return[cliName];let entry=fileURLToPath(new URL(`./${cliName===ROVE_PRODUCT_NAME?"rove.ts":"kobe.ts"}`,import.meta.url));return[process.execPath,"--conditions=browser",entry]}function kobeHookInvocation(){if(import.meta.url.endsWith(".js"))return[LEGACY_KOBE_PRODUCT_NAME];if(Bun.which(LEGACY_KOBE_PRODUCT_NAME))return[LEGACY_KOBE_PRODUCT_NAME];return roveCliInvocation()}var GATED_TOOL_VERBS=new Set(["tool-pre","tool-post","tool-failed"]);function isObject(v){return!!v&&typeof v==="object"&&!Array.isArray(v)}function activityMarkers(eventMap){return eventMap.flatMap((e)=>[quoteShellArgv(["hook",e.verb]),`hook ${e.verb}`])}function isKobeActivityGroup(group,markers){if(!isObject(group)||!Array.isArray(group.hooks))return!1;return group.hooks.some((h)=>isObject(h)&&typeof h.command==="string"&&markers.some((m)=>h.command.includes(m)))}function hasKobeActivityHooks(current,eventMap){let markers=activityMarkers(eventMap),hooks=isObject(current.hooks)?current.hooks:{};return Object.values(hooks).some((groups)=>Array.isArray(groups)&&groups.some((g)=>isKobeActivityGroup(g,markers)))}function buildActivityHooks(eventMap,inv=kobeHookInvocation(),opts={}){let out={};for(let spec of eventMap){if(opts.buildFilter&&!opts.buildFilter(spec))continue;let{event,matcher,verb}=spec,group={hooks:[{type:"command",command:quoteShellArgv([...inv,"hook",verb,...opts.extraArgs??[]])}]};if(matcher)group.matcher=matcher;let groups=out[event]??[];groups.push(group),out[event]=groups}return out}function mergeActivityHooks(current,install,eventMap,inv=kobeHookInvocation(),opts={}){let markers=activityMarkers(eventMap),{hooks:rawHooks,...restSettings}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},built=install?buildActivityHooks(eventMap,inv,opts):{};for(let{event}of eventMap){let kept=(Array.isArray(hooks[event])?hooks[event]:[]).filter((g)=>!isKobeActivityGroup(g,markers));if(install&&Array.isArray(built[event]))kept.push(...built[event]);if(kept.length>0)hooks[event]=kept;else delete hooks[event]}return Object.keys(hooks).length>0?{...restSettings,hooks}:{...restSettings}}var RETIRED_WATCH_EVENT="PostToolUse",WORKTREE_WATCH_MARKER="worktree-created";function isRetiredWatchGroup(group){if(!isObject(group)||!Array.isArray(group.hooks))return!1;return group.hooks.some((h)=>isObject(h)&&typeof h.command==="string"&&h.command.includes(WORKTREE_WATCH_MARKER))}function removeWorktreeWatchHook(current){let{hooks:rawHooks,...restSettings}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},kept=(Array.isArray(hooks[RETIRED_WATCH_EVENT])?hooks[RETIRED_WATCH_EVENT]:[]).filter((g)=>!isRetiredWatchGroup(g));if(kept.length>0)hooks[RETIRED_WATCH_EVENT]=kept;else delete hooks[RETIRED_WATCH_EVENT];return Object.keys(hooks).length>0?{...restSettings,hooks}:{...restSettings}}import{homedir}from"os";import{join as join2}from"path";import{createHash,randomBytes}from"crypto";import{mkdirSync,readFileSync,renameSync,unlinkSync,writeFileSync}from"fs";import{mkdir,readFile,rename,unlink,writeFile}from"fs/promises";import{dirname,join}from"path";function stagingPath(file){return`${file}.rove-${process.pid}-${randomBytes(6).toString("hex")}.tmp`}function sharedConfigLockPath(file){return join(roveStateDir(),`shared-config-${createHash("sha256").update(file).digest("hex").slice(0,16)}.lock`)}var MAX_ATTEMPTS=5;function readRawSync(file){try{return readFileSync(file,"utf8")}catch(err){if(err.code==="ENOENT")return;throw err}}async function readRaw(file){try{return await readFile(file,"utf8")}catch(err){if(err.code==="ENOENT")return;throw err}}function updateSharedJsonSync(file,load,build){let lockPath=sharedConfigLockPath(file),lockToken=acquireSync(lockPath);try{for(let attempt=0;attempt<MAX_ATTEMPTS;attempt++){let before=readRawSync(file),doc=load(before);if(!doc)return;let text=build(doc);if(text===void 0)return;let tmp=stagingPath(file);try{if(mkdirSync(dirname(file),{recursive:!0}),writeFileSync(tmp,text),readRawSync(file)===before){renameSync(tmp,file);return}}finally{try{unlinkSync(tmp)}catch{}}}throw Error(`gave up updating ${file} after ${MAX_ATTEMPTS} concurrent writes`)}finally{releaseSync(lockPath,lockToken)}}async function updateSharedJson(file,load,build){let lockPath=sharedConfigLockPath(file),lockToken=await acquireWithRetry(lockPath);try{for(let attempt=0;attempt<MAX_ATTEMPTS;attempt++){let before=await readRaw(file),doc=load(before);if(!doc)return;let text=build(doc);if(text===void 0)return;let tmp=stagingPath(file);try{if(await mkdir(dirname(file),{recursive:!0}),await writeFile(tmp,text),await readRaw(file)===before){await rename(tmp,file);return}}finally{await unlink(tmp).catch(()=>{})}}throw Error(`gave up updating ${file} after ${MAX_ATTEMPTS} concurrent writes`)}finally{await release(lockPath,lockToken)}}async function editJsonSettings(settingsFilePath,transform){try{await updateSharedJson(settingsFilePath,(raw)=>{if(raw===void 0)return{};try{let parsed=JSON.parse(raw);return isObject(parsed)?parsed:void 0}catch{return}},(current)=>{let next=transform(current),json=JSON.stringify(next,null,2);return json===JSON.stringify(current,null,2)?void 0:`${json}
|
|
3
|
+
`})}catch{}}class JsonHookAdapter{supportsHooks(){return!0}activityDetailFromPayload(_kind,_payload){return}sessionFromPayload(_payload){return}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(_settingsFilePath){}gatedVerbs(){return GATED_TOOL_VERBS}async installActivityHooks(settingsFilePath,opts={}){let gated=this.gatedVerbs();await editJsonSettings(settingsFilePath,(cur)=>mergeActivityHooks(cur,!0,this.eventMap,void 0,{extraArgs:["--engine",this.vendor],buildFilter:(spec)=>opts.toolEvents===!0||!gated.has(spec.verb)}))}async removeActivityHooks(settingsFilePath){await editJsonSettings(settingsFilePath,(cur)=>mergeActivityHooks(cur,!1,this.eventMap))}async removeWorktreeWatchHook(settingsFilePath){await editJsonSettings(settingsFilePath,removeWorktreeWatchHook)}}var CLAUDE_HOOK_EVENT_MAP=[{event:"SessionStart",verb:"session-start"},{event:"UserPromptSubmit",verb:"turn-start"},{event:"Stop",verb:"turn-complete"},{event:"StopFailure",verb:"turn-failed"},{event:"Notification",matcher:"permission_prompt",verb:"awaiting-input"},{event:"Notification",matcher:"elicitation_dialog",verb:"awaiting-input"},{event:"SessionEnd",verb:"session-end"},{event:"PreCompact",verb:"pre-compact"},{event:"PostCompact",verb:"post-compact"},{event:"SubagentStart",verb:"subagent-start"},{event:"SubagentStop",verb:"subagent-stop"},{event:"PreToolUse",verb:"tool-pre"},{event:"PostToolUse",verb:"tool-post"},{event:"PostToolUseFailure",verb:"tool-failed"}],KOBE_HOOK_EVENTS=[...new Set(CLAUDE_HOOK_EVENT_MAP.map((e)=>e.event))];function failureFromErrorType(errorType){if(typeof errorType!=="string")return"other";if(errorType==="rate_limit"||errorType==="overloaded")return"rate_limit";if(errorType==="billing_error")return"billing";return"other"}function claudeSettingsPath(){return join2(homedir(),".claude","settings.json")}var WORKTREE_SYNC_MARKER="worktree-created";function isKobeWorktreeSyncGroup(group){if(!isObject(group)||!Array.isArray(group.hooks))return!1;return group.hooks.some((h)=>isObject(h)&&typeof h.command==="string"&&h.command.includes(WORKTREE_SYNC_MARKER))}function mergeWorktreeSyncHook(current,command){let{hooks:rawHooks,...restSettings}=current,{WorktreeCreate,...otherHooks}=isObject(rawHooks)?rawHooks:{},kept=(Array.isArray(WorktreeCreate)?WorktreeCreate:[]).filter((g)=>!isKobeWorktreeSyncGroup(g));if(command!==null)kept.push({hooks:[{type:"command",command}]});let nextHooks={...otherHooks};if(kept.length>0)nextHooks.WorktreeCreate=kept;return Object.keys(nextHooks).length>0?{...restSettings,hooks:nextHooks}:{...restSettings}}class ClaudeHookAdapter extends JsonHookAdapter{vendor="claude";eventMap=CLAUDE_HOOK_EVENT_MAP;globalSettingsPath(){return claudeSettingsPath()}activityDetailFromPayload(kind,payload){if(kind==="turn-failed")return{failure:failureFromErrorType(payload.error_type)};if(kind==="awaiting-input")return{waiting:payload.notification_type==="elicitation_dialog"?"input":"permission"};if(kind==="tool-pre"||kind==="tool-post"||kind==="tool-failed")return{tool:{...typeof payload.tool_name==="string"?{name:payload.tool_name}:{},...typeof payload.tool_use_id==="string"?{id:payload.tool_use_id}:{}}};if(kind==="pre-compact"||kind==="post-compact")return{compact:{trigger:payload.trigger==="manual"?"manual":"auto"}};if(kind==="subagent-start"||kind==="subagent-stop")return{subagent:{...typeof payload.agent_type==="string"?{type:payload.agent_type}:{},...typeof payload.agent_id==="string"?{id:payload.agent_id}:{}}};return}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}supportsWorktreeSync(){return!0}async removeWorktreeSyncHook(settingsFilePath){await editJsonSettings(settingsFilePath,(cur)=>mergeWorktreeSyncHook(cur,null))}}
|
|
4
|
+
export{roveCliInvocation,kobeHookInvocation,GATED_TOOL_VERBS,isObject,hasKobeActivityHooks,updateSharedJsonSync,JsonHookAdapter,CLAUDE_HOOK_EVENT_MAP,claudeSettingsPath,ClaudeHookAdapter};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{SUBCOMMAND_VERBS,TOP_LEVEL_SUBCOMMANDS}from"./chunk-s76r56rj.js";import{activeCliName}from"./chunk-ef11h2am.js";import"./chunk-8ddjfc2v.js";import"./chunk-cb2fpajx.js";import"./chunk-3bfm4hrs.js";import{__require}from"./chunk-wqfp8d9w.js";async function collectSubVerbs(){let{API_VERBS}=await import("./chunk-x930m5fs.js"),merged={...SUBCOMMAND_VERBS,api:API_VERBS};return Object.keys(merged).sort().map((command)=>[command,merged[command]??[]])}function completionUsage(cliName){return[`Usage: ${cliName} completions <bash|zsh|fish>`,"",`Generate a shell completion script for ${cliName} and print it to stdout.`,"","Install:",` zsh source <(${cliName} completions zsh) # one-off, or in ~/.zshrc after compinit`," # or the fpath way:",` # ${cliName} completions zsh > ~/.zsh/completions/_${cliName}`," # fpath=(~/.zsh/completions $fpath) # in ~/.zshrc, BEFORE compinit"," # rm -f ~/.zcompdump && exec zsh # rebuild the completion cache",` bash ${cliName} completions bash > ~/.bash_completion.d/${cliName} # source it from ~/.bashrc`,` fish ${cliName} completions fish > ~/.config/fish/completions/${cliName}.fish`,""].join(`
|
|
3
|
+
`)}function generateBashCompletions(cliName,subVerbs){let subcommands=TOP_LEVEL_SUBCOMMANDS.join(" "),fn=`_${cliName}`;return[`# ${cliName} bash completions`,`# Source: ${cliName} completions bash`,"",`${fn}() {`," local cur prev"," COMPREPLY=()",' cur="${COMP_WORDS[COMP_CWORD]}"',' prev="${COMP_WORDS[COMP_CWORD-1]}"'," if [[ ${COMP_CWORD} -eq 1 ]]; then",` COMPREPLY=( $(compgen -W "${subcommands}" -- "\${cur}") )`," return"," fi"," if [[ ${COMP_CWORD} -eq 2 ]]; then",' case "${prev}" in',...subVerbs.map(([command,verbs])=>` ${command}) COMPREPLY=( $(compgen -W "${verbs.join(" ")}" -- "\${cur}") ) ;;`)," esac"," fi","}",`complete -F ${fn} ${cliName}`,""].join(`
|
|
4
|
+
`)}function generateZshCompletions(cliName,subVerbs){let subcommandsList=TOP_LEVEL_SUBCOMMANDS.map((s)=>`"${s}"`).join(" "),fn=`_${cliName}`;return[`#compdef ${cliName}`,`# ${cliName} zsh completions`,`# Source: ${cliName} completions zsh`,"",`${fn}() {`," local -a subcommands verbs",` subcommands=(${subcommandsList})`,""," if (( CURRENT == 2 )); then"," _describe -t commands 'subcommand' subcommands"," return"," fi",""," verbs=()",' case "${words[2]}" in',...subVerbs.map(([command,verbs])=>` ${command}) verbs=(${verbs.map((v)=>`"${v}"`).join(" ")}) ;;`)," esac"," if (( CURRENT == 3 && ${#verbs} > 0 )); then"," _describe -t verbs 'verb' verbs"," fi","}","","# Autoloaded from $fpath -> run as the completion function;","# sourced directly -> register with compdef instead.",`if [ "\${funcstack[1]}" = "${fn}" ]; then`,` ${fn} "$@"`,"elif (( $+functions[compdef] )); then",` compdef ${fn} ${cliName}`,"fi",""].join(`
|
|
5
|
+
`)}function generateFishCompletions(cliName,subVerbs){let lines=[...TOP_LEVEL_SUBCOMMANDS.map((s)=>`complete -c ${cliName} -f -n __fish_use_subcommand -a ${s}`),...subVerbs.map(([command,verbs])=>`complete -c ${cliName} -f -n "__fish_seen_subcommand_from ${command}" -a "${verbs.join(" ")}"`)];return`# ${cliName} fish completions
|
|
6
|
+
# Source: ${cliName} completions fish
|
|
7
|
+
|
|
8
|
+
${lines.join(`
|
|
9
|
+
`)}
|
|
10
|
+
`}async function runCompletionsSubcommand(rest,cliName=activeCliName()){let shell=rest[0],usage=completionUsage(cliName);if(shell==="--help"||shell==="-h"||shell==="help"){process.stdout.write(usage);return}if(!shell||shell!=="bash"&&shell!=="zsh"&&shell!=="fish")process.stderr.write(`${cliName} completions: unknown shell "${shell}"
|
|
11
|
+
|
|
12
|
+
${usage}`),process.exit(2);let subVerbs=await collectSubVerbs(),script;if(shell==="bash")script=generateBashCompletions(cliName,subVerbs);else if(shell==="zsh")script=generateZshCompletions(cliName,subVerbs);else script=generateFishCompletions(cliName,subVerbs);process.stdout.write(script)}export{runCompletionsSubcommand};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
var DEFAULT_TERMINAL_COLORS={foreground:"#eae7df",background:"#141413"},HEX_COLOR_RE=/^#[0-9a-f]{6}$/i,DEFAULT_COLOR_QUERY_RE=/\x1b\](10|11);\?(?:\x07|\x1b\\)/g,QUERY_PREFIXES=["\x1B]10;?","\x1B]11;?"];function normalizeColor(value){return typeof value==="string"&&HEX_COLOR_RE.test(value)?value.toLowerCase():null}function parseTerminalDefaultColors(value){if(typeof value!=="object"||value===null||Array.isArray(value))return null;let raw=value,foreground=normalizeColor(raw.foreground),background=normalizeColor(raw.background);return foreground&&background?{foreground,background}:null}function oscRgb(color){let hex=color.slice(1);return[hex.slice(0,2),hex.slice(2,4),hex.slice(4,6)].map((component)=>component.repeat(2)).join("/")}function formatDefaultColorReply(slot,colors){let color=slot===10?colors.foreground:colors.background;return`\x1B]${slot};rgb:${oscRgb(color)}\x1B\\`}function trailingQueryPrefix(text){let maxLength=QUERY_PREFIXES[0].length+1,start=Math.max(0,text.length-maxLength);for(let index=start;index<text.length;index++){let suffix=text.slice(index);if(QUERY_PREFIXES.some((prefix)=>prefix.startsWith(suffix)||suffix===`${prefix}\x1B`))return suffix}return""}function foldDefaultColorQueries(previousCarry,chunkText){let text=previousCarry+chunkText,slots=[],end=0;DEFAULT_COLOR_QUERY_RE.lastIndex=0;for(let match=DEFAULT_COLOR_QUERY_RE.exec(text);match;match=DEFAULT_COLOR_QUERY_RE.exec(text))slots.push(match[1]==="10"?10:11),end=match.index+match[0].length;return{slots,carry:trailingQueryPrefix(text.slice(end))}}
|
|
3
|
+
export{DEFAULT_TERMINAL_COLORS,parseTerminalDefaultColors,formatDefaultColorReply,foldDefaultColorQueries};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{LEGACY_KOBE_CONFIG_DIR_BASENAME,LEGACY_KOBE_STATE_DIR_BASENAME,ROVE_CONFIG_DIR_BASENAME,ROVE_STATE_DIR_BASENAME}from"./chunk-cb2fpajx.js";import{readRoveEnv}from"./chunk-3bfm4hrs.js";import{randomUUID}from"crypto";import{constants,closeSync,copyFileSync,fsyncSync,linkSync,lstatSync,mkdirSync,openSync,readdirSync,readlinkSync,renameSync,symlinkSync,unlinkSync,writeFileSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";var CLIENT_MIGRATION_MARKER=".layout-client-migration-v1",PLUGIN_MIGRATION_MARKER=".layout-plugins-migration-v1",DAEMON_MIGRATION_MARKER=".layout-daemon-migration-v1",CLIENT_STATE_ENTRIES=["attachments","settings","themes"],DAEMON_STATE_ENTRIES=["attention-inbox.json","automations.json","issue-assets","issues.json","notes","notes.json","tasks.json","worktree-init"];function errorText(err){return err instanceof Error?err.message:String(err)}function lstatIfExists(path){try{return lstatSync(path)}catch(err){if(err.code==="ENOENT")return;throw err}}function removeTemp(path){try{unlinkSync(path)}catch(err){if(err.code!=="ENOENT")throw err}}function syncFile(path){let handle=openSync(path,"r");try{fsyncSync(handle)}finally{closeSync(handle)}}function publishTemp(temp,destination){try{return linkSync(temp,destination),!0}catch(err){if(err.code==="EEXIST")return!1;throw err}}function copyRegularFile(source,destination){let temp=`${destination}.migration-${process.pid}-${randomUUID()}.tmp`;try{return copyFileSync(source,temp,constants.COPYFILE_EXCL),syncFile(temp),publishTemp(temp,destination)?1:0}finally{removeTemp(temp)}}function writeMarker(destination){let temp=`${destination}.migration-${process.pid}-${randomUUID()}.tmp`;try{writeFileSync(temp,`legacy kobe state copied without overwrite
|
|
3
|
+
`,{flag:"wx"}),syncFile(temp),publishTemp(temp,destination)}finally{removeTemp(temp)}}function copyMissing(source,destination){let sourceStat=lstatIfExists(source);if(!sourceStat)return 0;let destinationStat=lstatIfExists(destination);if(destinationStat){if(!sourceStat.isDirectory()||!destinationStat.isDirectory())return 0;let copied=0;for(let name of readdirSync(source))copied+=copyMissing(join(source,name),join(destination,name));return copied}if(mkdirSync(dirname(destination),{recursive:!0}),sourceStat.isDirectory()){mkdirSync(destination,{recursive:!0,mode:sourceStat.mode});let copied=0;for(let name of readdirSync(source))copied+=copyMissing(join(source,name),join(destination,name));return copied}if(sourceStat.isSymbolicLink())try{return symlinkSync(readlinkSync(source),destination),1}catch(err){if(err.code==="EEXIST")return 0;throw err}return copyRegularFile(source,destination)}function migrateStateEntries(entries,markerName,includeConfig,env){let home=readRoveEnv("HOME_DIR",env)??homedir(),legacyState=join(home,LEGACY_KOBE_STATE_DIR_BASENAME),roveState=join(home,ROVE_STATE_DIR_BASENAME),legacyConfig=join(home,".config",LEGACY_KOBE_CONFIG_DIR_BASENAME,"state.json"),roveConfig=join(home,".config",ROVE_CONFIG_DIR_BASENAME,"state.json"),marker=join(roveState,markerName),hasSource;try{if(lstatIfExists(marker))return{attempted:!1,copied:0,warnings:[]};hasSource=Boolean(lstatIfExists(legacyState)||includeConfig&&lstatIfExists(legacyConfig))}catch(err){return{attempted:!0,copied:0,warnings:[`migration preflight: ${err instanceof Error?err.message:String(err)}`]}}if(!hasSource)return{attempted:!1,copied:0,warnings:[]};let copied=0,warnings=[];for(let name of entries)try{copied+=copyMissing(join(legacyState,name),join(roveState,name))}catch(err){warnings.push(`${name}: ${err instanceof Error?err.message:String(err)}`)}if(includeConfig)try{copied+=copyMissing(legacyConfig,roveConfig)}catch(err){warnings.push(`state.json: ${err instanceof Error?err.message:String(err)}`)}if(warnings.length===0){mkdirSync(roveState,{recursive:!0});try{writeMarker(marker)}catch(err){warnings.push(`migration marker: ${err instanceof Error?err.message:String(err)}`)}}return{attempted:!0,copied,warnings}}var PLUGIN_ENTRIES=["plugins.json","plugins","plugins-outdated.json"];function migrateLegacyPluginTree(env){let home=readRoveEnv("HOME_DIR",env)??homedir(),legacyState=join(home,LEGACY_KOBE_STATE_DIR_BASENAME),roveState=join(home,ROVE_STATE_DIR_BASENAME),marker=join(roveState,PLUGIN_MIGRATION_MARKER);try{if(lstatIfExists(marker)||lstatIfExists(join(roveState,"plugins.json")))return{attempted:!1,copied:0,warnings:[]};if(!lstatIfExists(join(legacyState,"plugins.json")))return{attempted:!1,copied:0,warnings:[]}}catch(err){return{attempted:!0,copied:0,warnings:[`plugin migration preflight: ${errorText(err)}`]}}mkdirSync(roveState,{recursive:!0});let moved=0,warnings=[];for(let name of PLUGIN_ENTRIES){let source=join(legacyState,name),destination=join(roveState,name);try{if(!lstatIfExists(source)||lstatIfExists(destination))continue;renameSync(source,destination),moved+=1;try{symlinkSync(destination,source)}catch{}}catch(err){warnings.push(`${name}: ${errorText(err)}`)}}if(warnings.length===0)try{writeMarker(marker)}catch(err){warnings.push(`plugin migration marker: ${errorText(err)}`)}return{attempted:!0,copied:moved,warnings}}function migrateRoveClientStateLayout(env=process.env){return migrateStateEntries(CLIENT_STATE_ENTRIES,CLIENT_MIGRATION_MARKER,!0,env)}function migrateRoveDaemonStateLayout(env=process.env){let state=migrateStateEntries(DAEMON_STATE_ENTRIES,DAEMON_MIGRATION_MARKER,!1,env),plugins=migrateLegacyPluginTree(env);return{attempted:state.attempted||plugins.attempted,copied:state.copied+plugins.copied,warnings:[...state.warnings,...plugins.warnings]}}
|
|
4
|
+
export{DAEMON_MIGRATION_MARKER,migrateRoveClientStateLayout,migrateRoveDaemonStateLayout};
|