@sma1lboy/rove 0.9.165 → 0.9.167
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{chunk-jtft7vt4.js → chunk-0a9q2xth.js} +1 -1
- package/dist/cli/{chunk-t50g8fm5.js → chunk-0cgyvz39.js} +1 -1
- package/dist/cli/{chunk-7bdeahgv.js → chunk-0vzkkqrd.js} +2 -2
- package/dist/cli/{chunk-b0f0jdnb.js → chunk-12gr0411.js} +1 -1
- package/dist/cli/{chunk-efnhyt0e.js → chunk-1jfgkqde.js} +1 -1
- package/dist/cli/{chunk-avrs60rp.js → chunk-35v7w059.js} +1 -1
- package/dist/cli/{chunk-edeh4d1v.js → chunk-3p2e2ry4.js} +1 -1
- package/dist/cli/{chunk-d9zpbywp.js → chunk-45s720ck.js} +1 -1
- package/dist/cli/{chunk-zg3wezj6.js → chunk-5agemmmn.js} +1 -1
- package/dist/cli/{chunk-yqcsjw9c.js → chunk-5m4ke0aw.js} +3 -3
- package/dist/cli/{chunk-cjrq979n.js → chunk-8q3rz5tp.js} +1 -1
- package/dist/cli/{chunk-xywb33k2.js → chunk-8rtv3zya.js} +1 -1
- package/dist/cli/chunk-9njpbswp.js +7 -0
- package/dist/cli/{chunk-mbb0pp66.js → chunk-aqsbef90.js} +1 -1
- package/dist/cli/{chunk-5ekr8x6h.js → chunk-av4fw4ny.js} +1 -1
- package/dist/cli/{chunk-3try2twp.js → chunk-bggpzxk2.js} +1 -1
- package/dist/cli/{chunk-4ba5m3ek.js → chunk-bn1ta0qc.js} +1 -1
- package/dist/cli/{chunk-hnesjhs0.js → chunk-bz9mqybr.js} +2 -2
- package/dist/cli/{chunk-m4j20c64.js → chunk-c562kjgk.js} +1 -1
- package/dist/cli/{chunk-s4tvt1xg.js → chunk-d5ggjjhc.js} +1 -1
- package/dist/cli/{chunk-a20p202a.js → chunk-d89r3kx9.js} +1 -1
- package/dist/cli/{chunk-tvgvbq0p.js → chunk-detd3r88.js} +1 -1
- package/dist/cli/{chunk-dwvqnbqg.js → chunk-dgamtyqq.js} +1 -1
- package/dist/cli/chunk-dt51afhh.js +5 -0
- package/dist/cli/{chunk-kmby478q.js → chunk-e6q7r473.js} +2 -2
- package/dist/cli/{chunk-es6kqdjf.js → chunk-eb3bdewe.js} +1 -1
- package/dist/cli/{chunk-q4428qws.js → chunk-ek7dxj78.js} +1 -1
- package/dist/cli/{chunk-ym78sw9a.js → chunk-ffx2r3a1.js} +1 -1
- package/dist/cli/{chunk-dj5q2ta4.js → chunk-gfajrpaz.js} +1 -1
- package/dist/cli/{chunk-qs80x1cd.js → chunk-hxfj85yw.js} +1 -1
- package/dist/cli/{chunk-5jq3dvmn.js → chunk-j0cdebr3.js} +1 -1
- package/dist/cli/{chunk-bfpvywwr.js → chunk-jb7hgakq.js} +1 -1
- package/dist/cli/{chunk-v89n12j1.js → chunk-jn4cnt83.js} +1 -1
- package/dist/cli/{chunk-etnnwbdx.js → chunk-jn5dd6bv.js} +1 -1
- package/dist/cli/{chunk-g3nyhgxe.js → chunk-jngvv89s.js} +4 -4
- package/dist/cli/{chunk-gj6q5mvv.js → chunk-jxdva3mz.js} +1 -1
- package/dist/cli/{chunk-8mmycqkp.js → chunk-k5va2jt8.js} +1 -1
- package/dist/cli/{chunk-da9tb8av.js → chunk-m0g17ckn.js} +1 -1
- package/dist/cli/chunk-mmjcb6te.js +2 -0
- package/dist/cli/{chunk-mqcnntym.js → chunk-p7et3a90.js} +2 -2
- package/dist/cli/{chunk-n5c3k1dg.js → chunk-phftxm0p.js} +1 -1
- package/dist/cli/{chunk-nrafk2b7.js → chunk-pj0zmjvc.js} +1 -1
- package/dist/cli/chunk-qe41gemd.js +2 -0
- package/dist/cli/{chunk-vhrfe63r.js → chunk-qqw3p4fc.js} +1 -1
- package/dist/cli/{chunk-r79ht9kg.js → chunk-skysscx4.js} +1 -1
- package/dist/cli/chunk-vx1yfc9c.js +3 -0
- package/dist/cli/{chunk-mzmsbfsk.js → chunk-vy6pgy6w.js} +1 -1
- package/dist/cli/{chunk-crdag2rc.js → chunk-xhw8s2es.js} +4 -4
- package/dist/cli/{chunk-xqhcr66s.js → chunk-xqfyt9vm.js} +1 -1
- package/dist/cli/{chunk-2ywxqv7x.js → chunk-y18gtptb.js} +1 -1
- package/dist/cli/{chunk-rvybphrq.js → chunk-z490gs8g.js} +1 -1
- package/dist/cli/{chunk-99kgdgns.js → chunk-zhrytwnp.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/cli/kobe.js +1 -1
- package/dist/cli/pty-host-node.mjs +6 -6
- package/dist/cli/rove.js +1 -1
- package/dist/skills/rove/references/api-flags.md +1 -1
- package/package.json +1 -1
- package/dist/cli/chunk-6tvrvekq.js +0 -4
- package/dist/cli/chunk-c8520k12.js +0 -2
- package/dist/cli/chunk-x2gepvfj.js +0 -7
- package/dist/cli/chunk-xhb03ybc.js +0 -3
- package/dist/cli/chunk-z1c2d91p.js +0 -2
|
@@ -4,4 +4,4 @@ import{SUBCOMMAND_VERBS}from"./chunk-s76r56rj.js";import{expandTilde}from"./chun
|
|
|
4
4
|
|
|
5
5
|
${REPO_USAGE}
|
|
6
6
|
`),process.exit(2)}function readArgFile(path){try{return readFileSync(resolve(process.cwd(),expandTilde(path)),"utf8")}catch(err){usageError(`cannot read ${path}: ${errorMessage(err)}`)}}function parseRepoArgs(args){let out={};for(let i=0;i<args.length;i++){let a=args[i],need=()=>{let v=args[++i];if(v===void 0)usageError(`${a} requires a value`);return v};if(a==="--init-script")out.initScript=need();else if(a==="--init-script-file")out.initScript=readArgFile(need());else if(a==="--init-prompt")out.initPrompt=need();else if(a==="--init-prompt-file")out.initPrompt=readArgFile(need());else if(a.startsWith("-"))usageError(`unknown flag "${a}"`);else if(out.path===void 0)out.path=a;else usageError(`unexpected argument "${a}"`)}return out}function parseUnsetArgs(args){let path,clearScript=!1,clearPrompt=!1;for(let a of args)if(a==="--init-script")clearScript=!0;else if(a==="--init-prompt")clearPrompt=!0;else if(a.startsWith("-"))usageError(`unknown flag "${a}"`);else if(path===void 0)path=a;else usageError(`unexpected argument "${a}"`);if(!clearScript&&!clearPrompt)clearScript=!0,clearPrompt=!0;return{path,clearScript,clearPrompt}}async function runRepoSubcommand(args){let[verb,...rest]=args;if(verb===void 0||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${REPO_USAGE}
|
|
7
|
-
`);return}if(!SUBCOMMAND_VERBS.repo.includes(verb))usageError(`unknown verb "${verb}"`);let{getRepoInitOverride,setRepoInitOverride,resolveRepoRoot}=await import("./chunk-mmg7m9x2.js");if(verb==="show"){let[pathArg]=rest.filter((a)=>!a.startsWith("-")),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(pathArg??"."))),override=getRepoInitOverride(repo),{describeRepoInitSources}=await import("./chunk-
|
|
7
|
+
`);return}if(!SUBCOMMAND_VERBS.repo.includes(verb))usageError(`unknown verb "${verb}"`);let{getRepoInitOverride,setRepoInitOverride,resolveRepoRoot}=await import("./chunk-mmg7m9x2.js");if(verb==="show"){let[pathArg]=rest.filter((a)=>!a.startsWith("-")),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(pathArg??"."))),override=getRepoInitOverride(repo),{describeRepoInitSources}=await import("./chunk-12gr0411.js"),sources=describeRepoInitSources(repo);console.log(`repo: ${repo}`);for(let group of[sources.script,sources.prompt])group.forEach((source,index)=>{console.log(` ${`${source.rel}:`.padEnd(22)}${describeSource(group,index)}`)});console.log(` override initScript: ${override.initScript?quotePreview(override.initScript):"(unset)"}`),console.log(` override initPrompt: ${override.initPrompt?quotePreview(override.initPrompt):"(unset)"}`);return}if(verb==="set"){let flags=parseRepoArgs(rest);if(flags.initScript===void 0&&flags.initPrompt===void 0)usageError("set needs at least one of --init-script(-file) / --init-prompt(-file)");let repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(flags.path??"."))),next=setRepoInitOverride(repo,{...flags.initScript!==void 0?{initScript:flags.initScript}:{},...flags.initPrompt!==void 0?{initPrompt:flags.initPrompt}:{}});console.log(`updated override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}if(verb==="unset"){let{path,clearScript,clearPrompt}=parseUnsetArgs(rest),repo=resolveRepoRoot(resolve(process.cwd(),expandTilde(path??"."))),next=setRepoInitOverride(repo,{...clearScript?{initScript:""}:{},...clearPrompt?{initPrompt:""}:{}});console.log(`cleared override for ${repo}`),console.log(` initScript: ${next.initScript?quotePreview(next.initScript):"(unset)"}`),console.log(` initPrompt: ${next.initPrompt?quotePreview(next.initPrompt):"(unset)"}`);return}usageError(`unknown verb "${verb}"`)}function describeSource(group,index){let source=group[index];if(!source)return"absent";if(source.effective)return"present (wins)";if(!source.present)return"absent";return group.slice(0,index).some((earlier)=>earlier.effective)?"present (shadowed)":"present but empty (ignored)"}function quotePreview(value){let oneLine=value.replace(/\s+/g," ").trim();return oneLine.length>60?`"${oneLine.slice(0,57)}\u2026"`:`"${oneLine}"`}export{runRepoSubcommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{installedSkillDirs}from"./chunk-
|
|
2
|
+
import{installedSkillDirs}from"./chunk-m0g17ckn.js";import{CLAUDE_HOOK_EVENT_MAP,claudeSettingsPath,hasKobeActivityHooks,isObject}from"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";import{readFileSync}from"fs";import{homedir}from"os";var PLUGIN_NAME="rove";function readSettings(path){try{let parsed=JSON.parse(readFileSync(path,"utf8"));return isObject(parsed)?parsed:null}catch{return null}}function isRovePluginEnabled(settingsFilePath=claudeSettingsPath()){let settings=readSettings(settingsFilePath);if(!settings||!isObject(settings.enabledPlugins))return!1;return Object.entries(settings.enabledPlugins).some(([key,on])=>on===!0&&key.split("@")[0]===PLUGIN_NAME)}function detectLegacyInstalls(opts={}){let settingsFilePath=opts.settingsFilePath??claudeSettingsPath(),home=opts.home??homedir(),settings=readSettings(settingsFilePath),legacyHooks=settings!==null&&(hasKobeActivityHooks(settings,CLAUDE_HOOK_EVENT_MAP)||settingsHasWorktreeWatch(settings)),legacySkillDirs=installedSkillDirs(home);return{legacyHooks,legacySkillDirs}}function settingsHasWorktreeWatch(settings){let hooks=isObject(settings.hooks)?settings.hooks:{};return Object.values(hooks).some((groups)=>Array.isArray(groups)&&groups.some((g)=>isObject(g)&&Array.isArray(g.hooks)&&g.hooks.some((h)=>isObject(h)&&typeof h.command==="string"&&h.command.includes("worktree-created")&&!h.command.includes("CLAUDE_PLUGIN_ROOT"))))}function migrationHint(findings,cliName){if(!findings.legacyHooks&&findings.legacySkillDirs.length===0)return null;let lines=[`${cliName}: the Rove Claude Code plugin is enabled, but legacy installs remain:`];if(findings.legacyHooks)lines.push(" \u2022 ~/.claude/settings.json still has the settings-managed Rove hooks (every event fires TWICE).",` Run \`${cliName} hook cleanup\` to remove them (only Rove's own entries are touched).`);for(let dir of findings.legacySkillDirs)lines.push(` \u2022 legacy skill copy at ${dir} (the plugin bundles the skill \u2014 two copies double-register).`," Remove that directory to keep the plugin's copy only.");return lines.push(" Reading this inside a session? Just ask your agent to run the cleanup for you."),`${lines.join(`
|
|
3
3
|
`)}
|
|
4
4
|
`}export{migrationHint,isRovePluginEnabled,detectLegacyInstalls};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,vendorFromArgv}from"./chunk-
|
|
2
|
+
import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,vendorFromArgv}from"./chunk-jn5dd6bv.js";import"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";export{vendorFromArgv,psSnapshotWith,psSnapshot,parsePsSnapshot,hasAncestor,foregroundEngineIn,foregroundEngine,engineProcessIn,PsProbeUnavailableError,PS_PROBE_TIMEOUT_MS};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{NPX_MISSING_EXIT,bundledSkillDir,kobeSkillPaths,kobeSkillState,npxSkillsCommand,runNpxSkillsInstall}from"./chunk-
|
|
2
|
+
import{NPX_MISSING_EXIT,bundledSkillDir,kobeSkillPaths,kobeSkillState,npxSkillsCommand,runNpxSkillsInstall}from"./chunk-m0g17ckn.js";import{SUBCOMMAND_VERBS}from"./chunk-s76r56rj.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";import{existsSync,readFileSync}from"fs";import{join}from"path";var CLI_NAME=activeCliName(),SKILL_VERBS=SUBCOMMAND_VERBS.skill;function skillUsage(){return[`usage: ${CLI_NAME} skill <verb>`,"","verbs:"," install [--global|-g | --project|-p] [--agent NAME]\u2026 Install the Rove agent skill (wraps `npx skills add`)"," status Show whether the skill is installed"," command [--global|-g | --project|-p] [--agent NAME]\u2026 Print the underlying npx command without running it",` print Print the bundled SKILL.md (also: \`${CLI_NAME} --skill\`)`,"",`The skill teaches a coding agent how to drive \`${CLI_NAME} api\`. Installs are`,"global (user-level) by default; --global/-g says so explicitly, --project/-p","installs into the current project instead. With no --agent, the agent-skills","CLI detects your installed agents and asks; repeat --agent to name them","(e.g. --agent claude-code --agent codex)."].join(`
|
|
3
3
|
`)}function parseInstallFlags(rest){let global=!0,agents=[];for(let i=0;i<rest.length;i++){let arg=rest[i];if(arg==="--project"||arg==="-p")global=!1;else if(arg==="--global"||arg==="-g")global=!0;else if(arg==="--agent"){let v=rest[i+1];if(!v||v.startsWith("--"))process.stderr.write(`${CLI_NAME} skill: --agent requires a value
|
|
4
4
|
`),process.exit(2);agents.push(v),i++}else if(arg.startsWith("--agent="))agents.push(arg.slice(8));else process.stderr.write(`${CLI_NAME} skill: unknown flag "${arg}"
|
|
5
5
|
|
|
@@ -11,7 +11,7 @@ ${skillUsage()}
|
|
|
11
11
|
|
|
12
12
|
${skillUsage()}
|
|
13
13
|
`),process.exit(2);if(verb==="print"){let bundled2=bundledSkillDir(),path=bundled2?join(bundled2,"SKILL.md"):kobeSkillPaths().find((p)=>existsSync(p));if(!path)process.stderr.write(`${CLI_NAME} skill: no SKILL.md found (not bundled, not installed) \u2014 run \`${CLI_NAME} skill install\`
|
|
14
|
-
`),process.exit(1);process.stdout.write(readFileSync(path,"utf8"));return}if(verb==="status"){let{isRovePluginEnabled}=await import("./chunk-
|
|
14
|
+
`),process.exit(1);process.stdout.write(readFileSync(path,"utf8"));return}if(verb==="status"){let{isRovePluginEnabled}=await import("./chunk-bggpzxk2.js"),state=kobeSkillState(),paths=kobeSkillPaths(),pluginNote=isRovePluginEnabled()?` note: the Rove Claude Code plugin is enabled \u2014 for Claude Code the skill ships
|
|
15
15
|
inside the plugin and versions with it (staleness prompts are suppressed).
|
|
16
16
|
`:"",head=!state.installed?"\u2717 not installed":state.stale?`\u26A0 out of date (installed ${state.installedVersion===null?"unstamped":`v${state.installedVersion}`}, this Rove wants v${state.currentVersion})`:`\u2713 installed (v${state.installedVersion})`;process.stdout.write([`${CLI_NAME} skill: ${head}`,...state.legacyCopies.map((copy)=>` \u26A0 stale duplicate: ${copy.path}${copy.version===null?"":` (v${copy.version})`} \u2014 remove it; agents load both`),` looked in: ${paths.join(`
|
|
17
17
|
`)}`,state.installed&&!state.stale?"":` \u2192 run \`${CLI_NAME} skill install\` to install / refresh`,""].join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isEngineActivityKind}from"./chunk-3e5n28t6.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-38272eqv.js";import{flagValue}from"./chunk-jvxh93nz.js";import{connectIfRunning}from"./chunk-h9mqdxvs.js";import{createEngineHookAdapter}from"./chunk-
|
|
2
|
+
import{isEngineActivityKind}from"./chunk-3e5n28t6.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-38272eqv.js";import{flagValue}from"./chunk-jvxh93nz.js";import{connectIfRunning}from"./chunk-h9mqdxvs.js";import{createEngineHookAdapter}from"./chunk-xhw8s2es.js";import{getPersistedString,setPersistedString}from"./chunk-6wpege0h.js";import{ALL_VENDORS}from"./chunk-bq3fyc0p.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import{readRoveEnv}from"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";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 worktreeSyncAdapters()[0]?.globalSettingsPath()}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-bggpzxk2.js"),pluginMode=isRovePluginEnabled();if(pluginMode){let hint=migrationHint(detectLegacyInstalls(),activeCliName());if(hint)process.stderr.write(`
|
|
3
3
|
${hint}
|
|
4
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;for(let adapter of adapters){let file=adapter.globalSettingsPath();if(file)paths.add(file)}let 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
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(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{submitFeedback}from"./chunk-
|
|
2
|
+
import{submitFeedback}from"./chunk-j0cdebr3.js";import"./chunk-d89r3kx9.js";import"./chunk-ch9b1d5y.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";import{readFileSync}from"fs";var CLI_NAME=activeCliName(),FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--category <slug>]`,"","Create a GitHub Discussion in the Rove repository using the GitHub CLI.","","Requires:"," gh auth login","","Options:"," --title <text> Discussion title"," --body <text> Discussion body"," --body-file <path> Read the Discussion body from a file; use - for stdin"," --category <slug> Discussion category slug (default: feedback)"," -h, --help Print this help",""].join(`
|
|
3
3
|
`);function usageError(message){process.stderr.write(`${CLI_NAME} feedback: ${message}
|
|
4
4
|
|
|
5
5
|
${FEEDBACK_USAGE}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{isDev}from"./chunk-ch9b1d5y.js";import{fileURLToPath}from"url";var package_default={$schema:"https://json.schemastore.org/package.json",name:"@sma1lboy/rove",version:"0.9.
|
|
2
|
+
import{isDev}from"./chunk-ch9b1d5y.js";import{fileURLToPath}from"url";var package_default={$schema:"https://json.schemastore.org/package.json",name:"@sma1lboy/rove",version:"0.9.167",description:"Rove \u2014 the agent multiplexer for your terminal. Run coding agents on parallel tasks with isolated worktrees and persistent sessions.",keywords:["terminal","tui","cli","multiplexer","ai-agents","coding-agent","ai-coding-assistant","agentic-ai","parallel-agents","git-worktree","claude-code","codex","llm","developer-tools"],type:"module",packageManager:"bun@1.3.13",bin:{kobe:"dist/cli/kobe.js",rove:"dist/cli/rove.js"},files:["dist/cli","dist/web-ui","dist/skills","dist/*.wav","README.md","LICENSE"],publishConfig:{access:"public"},repository:{type:"git",url:"git+https://github.com/Sma1lboy/rove.git"},homepage:"https://rove.run",bugs:{url:"https://github.com/Sma1lboy/rove/issues"},engines:{bun:">=1.3.11"},scripts:{dev:"ROVE_DEV=1 bun --conditions=browser ./src/cli/rove.ts","dev:kobe":"KOBE_DEV=1 bun --conditions=browser ./src/cli/kobe.ts","dev:mock":"KOBE_DEV=1 bun ./src/tui-react/mock/host.tsx","dev:sandbox":"bun run scripts/dev-sandbox.ts run","dev:sandbox:reset":"bun run scripts/dev-sandbox.ts reset",build:"bun run scripts/build.ts",compile:"bun run scripts/compile.ts",typecheck:"tsc --noEmit","check-i18n":"bun run scripts/check-i18n.ts",test:"bun run test:fast && bun run test:socket","perf:golden":"bun scripts/perf-golden.ts","pty:soak":"bun scripts/pty-soak.ts","test:fast":"vitest run --passWithNoTests --minWorkers=1 --maxWorkers=8","test:socket":"KOBE_INCLUDE_SOCKET=1 vitest run test/daemon --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:socket:coverage":"KOBE_INCLUDE_SOCKET=1 KOBE_COVERAGE_DAEMON=1 vitest run test/daemon --coverage --pool forks --minWorkers=1 --maxWorkers=4 --passWithNoTests","test:behavior":"KOBE_INCLUDE_BEHAVIOR=1 vitest run test/behavior --pool forks --minWorkers=1 --maxWorkers=1 --retry=2 --passWithNoTests","test:render":"bun test test/render --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage-render",coverage:"vitest run --coverage --passWithNoTests",bench:"vitest bench --run",lint:"biome check .",knip:"knip-bun",postinstall:"bun run scripts/check-preview-deps.ts || true",prepublishOnly:"bun run typecheck && bun run build","plugin-sandbox":"bun run scripts/plugin-sandbox.ts"},"//":"biome.json + bunfig.toml live at the monorepo root since they apply repo-wide; bun.lock also lives at root (workspace-shared).",dependencies:{"@ansi-tools/parser":"^1.0.15","@opentui/core":"0.4.3","@opentui/react":"0.4.3","@xterm/addon-serialize":"^0.14.0","@xterm/addon-unicode11":"^0.9.0","@xterm/headless":"^6.0.0","node-pty":"^1.1.0",react:"^19.2.8","smol-toml":"^1.7.1",ws:"^8.18.0"},devDependencies:{"@biomejs/biome":"1.9.4","@sma1lboy/kobe-daemon":"0.7.19","@tsconfig/bun":"1.0.10","@types/bun":"1.3.14","@types/node":"25.6.2","@types/react":"^19.2.0","@vitest/coverage-v8":"2.1.9",knip:"^6.14.2","react-devtools-core":"^7.0.1",typescript:"5.8.2",vitest:"2.1.9"},trustedDependencies:[]};var CURRENT_VERSION=package_default.version,PACKAGE_NAME=package_default.name;function repoSlug(){let url=package_default.repository?.url;if(!url)return null;let m=url.match(/github\.com[:/]([^/]+)\/([^/.]+)/);if(!m||!m[1]||!m[2])return null;return`${m[1]}/${m[2]}`}var UPDATE_SCRIPT_URL="https://raw.githubusercontent.com/Sma1lboy/rove/main/scripts/update.sh",UPDATE_COMMAND=`curl -fsSL ${UPDATE_SCRIPT_URL} | sh`;function owningNpmPrefix(modulePath=fileURLToPath(import.meta.url)){let at=modulePath.indexOf("/lib/node_modules/");if(at<=0)return null;return modulePath.slice(0,at)}function recommendedGlobalInstallCommand(prefix=owningNpmPrefix()){let target=`${PACKAGE_NAME}@latest`;return prefix===null?`npm install -g ${target}`:`npm install -g --prefix ${prefix} ${target}`}var BREAKING_VERSIONS=[];function breakingVersionsCrossed(from,to,breaking=BREAKING_VERSIONS){let[lo,hi]=compareSemver(from,to)<=0?[from,to]:[to,from];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}var FETCH_TIMEOUT_MS=3000,RELEASE_CHANNELS=["latest","nightly"],DEFAULT_RELEASE_CHANNEL="latest";function channelOf(version=CURRENT_VERSION){return prereleaseOf(version)?.split(".")[0]==="nightly"?"nightly":DEFAULT_RELEASE_CHANNEL}async function fetchLatestFromRegistry(packageName,channel){let ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let encoded=packageName.replace("/","%2F"),res=await fetch(`https://registry.npmjs.org/${encoded}/${channel}`,{signal:ctrl.signal,headers:{accept:"application/json"}});if(!res.ok)return null;let body=await res.json();if(typeof body.version!=="string")return null;return body.version}catch{return null}finally{clearTimeout(timer)}}function isNewerSemver(latest,current){let core=compareSemver(latest,current);if(core!==0)return core>0;return comparePrerelease(prereleaseOf(latest),prereleaseOf(current))>0}function prereleaseOf(version){let dash=version.indexOf("-");return dash===-1?void 0:version.slice(dash+1)||void 0}function comparePrerelease(a,b){if(a===b)return 0;if(a===void 0)return 1;if(b===void 0)return-1;let aParts=a.split("."),bParts=b.split(".");for(let i=0;i<Math.max(aParts.length,bParts.length);i++){let av=aParts[i],bv=bParts[i];if(av===void 0)return-1;if(bv===void 0)return 1;if(av===bv)continue;let an=/^\d+$/.test(av)?Number.parseInt(av,10):null,bn=/^\d+$/.test(bv)?Number.parseInt(bv,10):null;if(an!==null&&bn!==null)return an>bn?1:-1;if(an!==null)return-1;if(bn!==null)return 1;return av>bv?1:-1}return 0}function compareSemver(aVersion,bVersion){let norm=(v)=>v.split("-")[0]??v,a=norm(aVersion).split(".").map((s)=>Number.parseInt(s,10)),b=norm(bVersion).split(".").map((s)=>Number.parseInt(s,10));for(let i=0;i<3;i++){let av=a[i]??0,bv=b[i]??0;if(Number.isNaN(av)||Number.isNaN(bv))return 0;if(av>bv)return 1;if(av<bv)return-1}return 0}async function checkLatestVersion(opts={}){let channel=opts.channel??channelOf(),fake=process.env.KOBE_FAKE_UPDATE;if(fake)return{current:CURRENT_VERSION,latest:fake,hasUpdate:isNewerSemver(fake,CURRENT_VERSION),channel};if(isDev()&&!opts.force)return null;let latest=await fetchLatestFromRegistry(PACKAGE_NAME,channel);if(!latest)return null;return{current:CURRENT_VERSION,latest,hasUpdate:isNewerSemver(latest,CURRENT_VERSION),channel}}function versionFromTagName(tagName){if(typeof tagName!=="string")return null;return tagName.match(/^v(\d+\.\d+\.\d+)$/)?.[1]??null}async function fetchReleaseNotes(version){let slug=repoSlug();if(!slug)return null;let tag=`v${version}`,ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let res=await fetch(`https://api.github.com/repos/${slug}/releases/tags/${tag}`,{signal:ctrl.signal,headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return null;let body=await res.json();if(typeof body.body!=="string"||typeof body.html_url!=="string")return null;return{body:body.body,url:body.html_url,version}}catch{return null}finally{clearTimeout(timer)}}async function fetchReleaseNotesRange(args){let slug=repoSlug();if(!slug)return[];let limit=args.limit??100,ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let res=await fetch(`https://api.github.com/repos/${slug}/releases?per_page=${limit}`,{signal:ctrl.signal,headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return[];let body=await res.json();if(!Array.isArray(body))return[];return body.map((release)=>{let version=versionFromTagName(release.tag_name);if(!version||typeof release.html_url!=="string"||typeof release.body!=="string")return null;if(compareSemver(version,args.current)<=0)return null;if(compareSemver(version,args.latest)>0)return null;return{version,url:release.html_url,body:release.body}}).filter((release)=>release!==null)}catch{return[]}finally{clearTimeout(timer)}}async function fetchReleaseSummaries(limit=12){let slug=repoSlug();if(!slug)return[];let ctrl=new AbortController,timer=setTimeout(()=>ctrl.abort(),FETCH_TIMEOUT_MS);try{let res=await fetch(`https://api.github.com/repos/${slug}/releases?per_page=${limit}`,{signal:ctrl.signal,headers:{accept:"application/vnd.github+json","x-github-api-version":"2022-11-28"}});if(!res.ok)return[];let body=await res.json();if(!Array.isArray(body))return[];return body.map((release)=>{let version=versionFromTagName(release.tag_name);if(!version||typeof release.html_url!=="string")return null;return{version,url:release.html_url}}).filter((release)=>release!==null)}catch{return[]}finally{clearTimeout(timer)}}function releasePageUrl(version){let slug=repoSlug();if(!slug)return null;return`https://github.com/${slug}/releases/tag/v${version}`}
|
|
3
3
|
export{package_default,CURRENT_VERSION,PACKAGE_NAME,repoSlug,UPDATE_SCRIPT_URL,UPDATE_COMMAND,owningNpmPrefix,recommendedGlobalInstallCommand,BREAKING_VERSIONS,breakingVersionsCrossed,RELEASE_CHANNELS,DEFAULT_RELEASE_CHANNEL,channelOf,isNewerSemver,compareSemver,checkLatestVersion,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,releasePageUrl};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{findBinding,formatChord}from"./chunk-
|
|
2
|
+
import{findBinding,formatChord}from"./chunk-5m4ke0aw.js";function capOf(row){return row.hint?.keys??row.keys[0]}function legendCap(id){let row=findBinding(id);if(!row)return null;let cap=capOf(row);return cap&&cap.length>0?cap:null}function directCap(row){if(row.keys.length>0)return row.hint?.keys??row.keys[0]??null;return row.prefixKeys?.length?null:row.hint?.keys??null}function availableOn(row,surface){if(row.scope==="global")return!0;if(surface===null)return!1;if(row.scope===surface)return!0;return surface==="terminal"&&row.scope==="workspace"}function grammarHelpSections(keymap,surface,prefixKey,reachability){let here=[],direct=[],prefix=[],other=new Map;for(let binding of keymap){let cap=directCap(binding),staticallyAvailable=availableOn(binding,surface),directAvailable=reachability?reachability.direct.has(binding.id):staticallyAvailable,prefixAvailable=reachability?reachability.prefix.has(binding.id):staticallyAvailable;if(cap){let row={binding,primary:cap,aliases:binding.keys.filter((key)=>key!==cap)};if(directAvailable&&(staticallyAvailable||binding.presentation==="onePress"))if(binding.presentation==="onePress")direct.push(row);else here.push(row);else if(!staticallyAvailable&&binding.scope!=="global"){let rows=other.get(binding.scope);if(rows)rows.push(row);else other.set(binding.scope,[row])}}if(prefixKey&&prefixAvailable&&binding.prefixKeys?.length)prefix.push({binding,primary:`${prefixKey} + ${binding.prefixKeys[0]}`,aliases:binding.prefixKeys.slice(1).map((key)=>`${prefixKey} + ${key}`)})}let sections=[];if(here.length)sections.push({kind:"here",scope:surface??void 0,rows:here});if(direct.length)sections.push({kind:"direct",rows:direct});if(prefix.length)sections.push({kind:"prefix",rows:prefix});for(let[scope,rows]of other)sections.push({kind:"other",scope,rows});return sections}var SCOPE_CATEGORY={global:"Global",sidebar:"Sidebar",workspace:"Workspace",files:"Files",inbox:"Inbox",terminal:"Terminal"};function scopeCategory(scope){return scope?SCOPE_CATEGORY[scope]:"Global"}function guideCategory(action){if(["kanban.open","automations.open","workItems.open"].includes(action))return"Views";if(action.startsWith("focus."))return"Navigation";if(action.startsWith("inbox.")||action.startsWith("attention."))return"Attention";if(action.startsWith("chat.tab.")||action.startsWith("chat.session."))return"Sessions";if(action.startsWith("chat.fork.")||action.startsWith("task."))return"Tasks";if(action.startsWith("settings.")||action==="workspace.zenToggle")return"Tools";return findBinding(action)?.category??"Global"}var KEY_HINTS_ENABLED_KEY="hints.keyboard.enabled",PANE_HINT_USED_KEYS={sidebar:"hints.sidebar.used",files:"hints.files.used"};function keyHintsEnabled(raw){return raw!==!1}function keyHintsToggleOn(kv){return keyHintsEnabled(kv.get(KEY_HINTS_ENABLED_KEY,!0))}function toggleKeyHints(kv){let next=!keyHintsToggleOn(kv);if(kv.set(KEY_HINTS_ENABLED_KEY,next),next)for(let key of Object.values(PANE_HINT_USED_KEYS))kv.set(key,!1)}function paneHintVisible(enabledRaw,usedRaw){return keyHintsEnabled(enabledRaw)&&usedRaw!==!0}function statusHintTokens(reach,prefixKey){let tokens=[];if(prefixKey!==null&&reach.prefix.size>0)tokens.push({chord:prefixKey,msg:"commands"});else if(reach.inputPassthrough){let cap=reach.direct.has("focus.sidebar")?legendCap("focus.sidebar"):null;if(cap)tokens.push({chord:cap,msg:"sidebar"})}if(reach.direct.has("help.open")){let cap=legendCap("help.open");if(cap)tokens.push({chord:cap,msg:"help"})}return tokens}var PANE_HINT_ROWS={sidebar:[{id:"sidebar.nav",msg:"move"},{id:"sidebar.select",msg:"open"}],files:[{id:"files.nav",msg:"move"},{id:"files.hierarchy",msg:"collapse"},{id:"files.open",msg:"open",always:!0},{id:"files.diff",msg:"diff",always:!0}]};function paneHintTokens(pane,mode){return PANE_HINT_ROWS[pane].flatMap((row)=>{if(mode==="always"&&row.always!==!0)return[];let cap=legendCap(row.id);return cap?[{cap,msg:row.msg}]:[]})}function wizardKeyLines(prefixKey){let lines=[],nav=legendCap("sidebar.nav"),open=legendCap("sidebar.select");if(nav&&open)lines.push({msg:"keysBare",params:{nav:formatChord(nav),open:formatChord(open)}});let newTab=legendCap("chat.tab.new"),focusNext=legendCap("focus.next");if(newTab&&focusNext)lines.push({msg:"keysOnePress",params:{newTab:formatChord(newTab),focusNext:formatChord(focusNext)}});if(prefixKey!==null)lines.push({msg:"keysPrefix",params:{prefix:formatChord(prefixKey)}});let help=legendCap("help.open");if(help)lines.push({msg:"keysHelp",params:{help:formatChord(help)}});return lines}
|
|
3
3
|
export{legendCap,grammarHelpSections,scopeCategory,guideCategory,KEY_HINTS_ENABLED_KEY,PANE_HINT_USED_KEYS,keyHintsEnabled,keyHintsToggleOn,toggleKeyHints,paneHintVisible,statusHintTokens,paneHintTokens,wizardKeyLines};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{TaskDeletingError,deriveTitleFromPrompt}from"./chunk-9kefy6ev.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp,sessionHasEngine,trustEngineWorktree}from"./chunk-
|
|
2
|
+
import{TaskDeletingError,deriveTitleFromPrompt}from"./chunk-9kefy6ev.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,ensureHostedEngine,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,killHostedSessions,listHostedSessions,openHostedSessionHost,pastePromptWhenEngineUp,sessionHasEngine,trustEngineWorktree}from"./chunk-aqsbef90.js";import{engineLaunchArgv,protocolEntry}from"./chunk-qqw3p4fc.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";var MAX_SESSIONS_SCANNED=8;function titleFromMessages(messages){let firstUser=messages.find((m)=>m.role==="user");if(!firstUser)return"";let text=firstUser.blocks.filter((b)=>b.type==="text").map((b)=>b.text).join(" "),title=deriveTitleFromPrompt(text);return title.length>0?Buffer.from(title,"utf8").toString("utf8"):title}async function deriveTitleFromSession(worktree,vendor=DEFAULT_TASK_VENDOR){if(!worktree)return"";let{history}=protocolEntry(vendor),ids=await history.listSessionIdsForWorktree(worktree);for(let sessionId of ids.slice(0,MAX_SESSIONS_SCANNED)){let title=titleFromMessages(await history.readHistory(sessionId));if(title)return title}return""}async function deriveTitleFromSessionId(vendor,sessionId){if(!sessionId)return"";try{return titleFromMessages(await protocolEntry(vendor).history.readHistory(sessionId))}catch{return""}}async function getTask(link,taskId){let{task}=await link.request("task.get",{taskId});return task}async function ensureTaskWorktree(link,taskId){let task=await getTask(link,taskId);if(task.deletion)throw new TaskDeletingError(taskId);if(task.worktreePath)return{task,worktreePath:task.worktreePath};let{worktreePath}=await link.request("task.ensureWorktree",{taskId});if(!worktreePath)throw Error(`task ${taskId} has no worktree`);return{task,worktreePath}}async function ensureTaskSessionAdapter(link,taskId){let{task,worktreePath}=await ensureTaskWorktree(link,taskId),launch=taskEngineLaunch(task,worktreePath,{kind:"repo-init"}),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)throw Error(`failed to start hosted engine session for ${taskId}`);if(launch.firstMessage){let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort})[0];await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs}).catch(()=>!1)}}finally{host.close()}return{session:launch.key,worktreePath}}async function startTaskSessionWithPromptAdapter(link,taskId,prompt){let{task,worktreePath}=await ensureTaskWorktree(link,taskId);await link.request("task.observeLanguage",{taskId,text:prompt}).catch(()=>{});let launch=taskEngineLaunch(task,worktreePath,{kind:"new-task",prompt}),host=await ensureHostedSessionHost();try{if(!(await ensureHostedEngine(host.rpc,worktreePath,launch)).alive)return{started:!1,error:"hosted session did not open"};let engineBin=engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort})[0],wait={initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs};if(launch.firstMessage){if(await pastePromptWhenEngineUp(host.rpc,launch.key,engineBin,launch.firstMessage,wait)!==null)return{started:!0};return{started:!1,error:await startFailureReason(host.rpc,launch.key)}}if(await awaitEngineProcess(host.rpc,launch.key,engineBin,wait)!==null)return{started:!0};return{started:!1,error:await startFailureReason(host.rpc,launch.key)}}finally{host.close()}}async function startFailureReason(rpc,key){let tail=await hostedSessionFailureLine(rpc,key),base="engine process never started";return tail?`engine process never started; last session output: ${tail}`:"engine process never started"}function taskEngineLaunch(task,worktreePath,promptIntent){return trustEngineWorktree(task.vendor,worktreePath),buildEngineSessionLaunch({task:{id:task.id,kind:task.kind,vendor:task.vendor,repo:task.repo},worktreePath,shell:resolveLoginShell({fallback:"/bin/zsh"}),argv:engineLaunchArgv({command:task.command,vendor:task.vendor,effort:task.modelEffort}),promptIntent})}async function deliverPromptToLiveEngineAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return!1;try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0]);if(!key)return!1;if(!await sessionHasEngine(sessions.find((s)=>s.key===key)?.pid,engineArgv))return!1;let manifest=task.vendor?protocolEntry(task.vendor).screenManifest:void 0;return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})!==null}catch(err){if(err instanceof ComposerBusyError)throw err;return!1}finally{host.close()}}function tabIdFromHostedKey(key){return key.split("::")[1]??"tab-1"}async function deliverPromptToLiveEngineDetailedAdapter(task,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let sessions=await listHostedSessions(host.rpc),engineArgv=engineLaunchArgv({command:task.command,vendor:task.vendor}),key=findHostedEngineKey(sessions,task.id,engineArgv[0]);if(!key)return{outcome:"no-session"};if(!await sessionHasEngine(sessions.find((s)=>s.key===key)?.pid,engineArgv))return{outcome:"no-engine",tabId:tabIdFromHostedKey(key)};let manifest=task.vendor?protocolEntry(task.vendor).screenManifest:void 0;try{return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:tabIdFromHostedKey(key)}}catch(err){if(err instanceof ComposerBusyError)return{outcome:"busy",tabId:tabIdFromHostedKey(key),layer:err.layer};throw err}}catch{return{outcome:"no-session"}}finally{host.close()}}async function deliverPromptToLiveEngineTabDetailedAdapter(target,prompt){let host=await openHostedSessionHost();if(!host)return{outcome:"no-session"};try{let key=`${target.id}::${target.tabId}`,sessions;try{sessions=await listHostedSessions(host.rpc)}catch{return{outcome:"no-session"}}let session=sessions.find((candidate)=>candidate.alive&&candidate.key===key);if(!session)return{outcome:"no-session"};let engineArgv=engineLaunchArgv({command:target.command,vendor:target.vendor});if(!await sessionHasEngine(session.pid,engineArgv))return{outcome:"no-engine",tabId:target.tabId};let manifest=target.vendor?protocolEntry(target.vendor).screenManifest:void 0;try{return await deliverToHostedKey(host.rpc,key,prompt,{screenManifest:manifest})===null?{outcome:"no-session"}:{outcome:"delivered",tabId:target.tabId}}catch(err){if(err instanceof ComposerBusyError)return{outcome:"busy",tabId:target.tabId,layer:err.layer};throw err}}finally{host.close()}}async function tearDownTaskSessionAdapter(taskId){let host=await openHostedSessionHost();if(!host)return;try{await killHostedSessions(host.rpc,hostedTaskKeys(await listHostedSessions(host.rpc),taskId))}catch{}finally{host.close()}}
|
|
3
3
|
export{deriveTitleFromSession,deriveTitleFromSessionId,ensureTaskSessionAdapter,startTaskSessionWithPromptAdapter,deliverPromptToLiveEngineAdapter,deliverPromptToLiveEngineDetailedAdapter,deliverPromptToLiveEngineTabDetailedAdapter,tearDownTaskSessionAdapter};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{readTextFileIfRegular,readTextFileIfRegularSync,vendorConfigHome}from"./chunk-7jkf3tvr.js";import{quoteShellArgv}from"./chunk-2fypr41w.js";import{acquireWithRetry}from"./chunk-k1qe5qqa.js";import{acquireSync,release,releaseSync}from"./chunk-ayhhgfsz.js";import{roveStateDir}from"./chunk-ch9b1d5y.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import{LEGACY_KOBE_PRODUCT_NAME,ROVE_PRODUCT_NAME}from"./chunk-g56kvet6.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 parseHookSettings(raw){if(raw===void 0)return{ok:!0,doc:{}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{ok:!1,reason:`not valid JSON (${err instanceof Error?err.message:String(err)})`}}if(!isObject(parsed))return{ok:!1,reason:"top level is not a JSON object"};if(parsed.hooks===void 0)return{ok:!0,doc:parsed};if(!isObject(parsed.hooks))return{ok:!1,reason:'"hooks" is not an object'};for(let[event,groups]of Object.entries(parsed.hooks)){if(!Array.isArray(groups))return{ok:!1,reason:`"hooks.${event}" is not an array`};let bad=groups.findIndex((group)=>!isObject(group)||!Array.isArray(group.hooks));if(bad>=0)return{ok:!1,reason:`"hooks.${event}[${bad}]" is not an object with a "hooks" array`}}return{ok:!0,doc:parsed}}var HOOK_WORD=String.raw`(?:'(?:[^']|'\\'')*'|"[^"$\x60\\]*"|[A-Za-z0-9_./:=+-]+)`,HOOK_ARGV=new RegExp(`^${HOOK_WORD}(?:[ ]+${HOOK_WORD})*$`);function isRoveHook(hook,verbs){if(!isObject(hook)||hook.type!=="command"||typeof hook.command!=="string")return!1;let command=hook.command.replace(/^[ \t]+|[ \t]+$/g,"");if(HOOK_ARGV.exec(command)?.[0]!==command)return!1;let argv=(command.match(new RegExp(HOOK_WORD,"g"))??[]).map((word)=>{if(word.startsWith("'"))return word.slice(1,-1).replaceAll("'\\''","'");if(word.startsWith('"'))return word.slice(1,-1);return word}),executable=argv[0]?.split("/").at(-1),offset=1;if(executable==="bun"||executable==="node"){if(argv[offset]==="--conditions=browser")offset++;let entry=argv[offset]??"";if(!/(?:^|\/)(?:src|dist)\/cli\/(?:rove|kobe)\.(?:ts|js)$/.test(entry))return!1;offset++}else if(executable!=="rove"&&executable!=="kobe")return!1;if(argv[offset]!=="hook"||!verbs.includes(argv[offset+1]))return!1;let rest=argv.slice(offset+2);return rest.length===0||rest.length===2&&rest[0]==="--engine"&&/^[a-z][a-z0-9-]*$/.test(rest[1])}function removeRoveHooks(groups,verbs){return groups.flatMap((group)=>{if(!isObject(group)||!Array.isArray(group.hooks))return[group];let kept=group.hooks.filter((hook)=>!isRoveHook(hook,verbs));if(kept.length===group.hooks.length)return[group];return kept.length>0?[{...group,hooks:kept}]:[]})}function hasKobeActivityHooks(current,eventMap){let verbs=eventMap.map((spec)=>spec.verb),hooks=isObject(current.hooks)?current.hooks:{};return Object.values(hooks).some((groups)=>Array.isArray(groups)&&groups.some((group)=>isObject(group)&&Array.isArray(group.hooks)&&group.hooks.some((hook)=>isRoveHook(hook,verbs))))}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 previous=out[event],groups=Array.isArray(previous)?previous:[];groups.push(group),out[event]=groups}return out}function mergeActivityHooks(current,install,eventMap,inv=kobeHookInvocation(),opts={}){let verbs=eventMap.map((spec)=>spec.verb),{hooks:rawHooks,...restSettings}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},built=install?buildActivityHooks(eventMap,inv,opts):{};for(let{event}of eventMap){let groups=hooks[event],prior=Array.isArray(groups)?groups:[],kept=removeRoveHooks(prior,verbs),additions=built[event];if(install&&Array.isArray(additions))kept.push(...additions);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";function removeWorktreeWatchHook(current){let{hooks:rawHooks,...restSettings}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},groups=hooks[RETIRED_WATCH_EVENT],prior=Array.isArray(groups)?groups:[],kept=removeRoveHooks(prior,["worktree-created"]);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{join as join2}from"path";import{createHash,randomBytes}from"crypto";import{mkdirSync,renameSync,unlinkSync,writeFileSync}from"fs";import{mkdir,rename,unlink,writeFile}from"fs/promises";import{dirname,join}from"path";var MAX_SHARED_CONFIG_BYTES=8388608;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 readSharedConfigSync(file){try{let raw=readTextFileIfRegularSync(file,MAX_SHARED_CONFIG_BYTES);if(raw===null)throw Error(`Refusing non-regular or oversized config: ${file}`);return raw}catch(err){if(err instanceof Error&&"code"in err&&err.code==="ENOENT")return;throw err}}async function readRaw(file){try{let raw=await readTextFileIfRegular(file,MAX_SHARED_CONFIG_BYTES);if(raw===null)throw Error(`Refusing non-regular or oversized config: ${file}`);return raw}catch(err){if(err instanceof Error&&"code"in err&&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=readSharedConfigSync(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,{mode:384,flag:"wx"}),readSharedConfigSync(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,{mode:384,flag:"wx"}),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){let rejected;try{await updateSharedJson(settingsFilePath,(raw)=>{let parsed=parseHookSettings(raw);if(parsed.ok)return parsed.doc;rejected=parsed.reason;return},(current)=>{let next=transform(current),json=JSON.stringify(next,null,2);return json===JSON.stringify(current,null,2)?void 0:`${json}
|
|
3
|
+
`})}catch(err){return{ok:!1,file:settingsFilePath,reason:err instanceof Error?err.message:String(err)}}if(rejected!==void 0)return{ok:!1,file:settingsFilePath,reason:rejected};return{ok:!0}}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(),outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeActivityHooks(cur,!0,this.eventMap,void 0,{extraArgs:["--engine",this.vendor],buildFilter:(spec)=>opts.toolEvents===!0||!gated.has(spec.verb)}));if(!outcome.ok)process.stderr.write(`[rove hooks] ${this.vendor}: skipped ${outcome.file}: ${outcome.reason}
|
|
4
|
+
`);return outcome}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(vendorConfigHome("claude"),"settings.json")}var WORKTREE_SYNC_VERB="worktree-created";function mergeWorktreeSyncHook(current,command){let{hooks:rawHooks,...restSettings}=current,{WorktreeCreate,...otherHooks}=isObject(rawHooks)?rawHooks:{},prior=Array.isArray(WorktreeCreate)?WorktreeCreate:[],kept=removeRoveHooks(prior,[WORKTREE_SYNC_VERB]);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))}}
|
|
5
|
+
export{roveCliInvocation,kobeHookInvocation,GATED_TOOL_VERBS,isObject,parseHookSettings,hasKobeActivityHooks,readSharedConfigSync,updateSharedJsonSync,JsonHookAdapter,CLAUDE_HOOK_EVENT_MAP,claudeSettingsPath,ClaudeHookAdapter};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{BREAKING_VERSIONS,CURRENT_VERSION,DEFAULT_RELEASE_CHANNEL,RELEASE_CHANNELS,UPDATE_COMMAND,UPDATE_SCRIPT_URL,breakingVersionsCrossed,channelOf,checkLatestVersion,fetchReleaseSummaries,recommendedGlobalInstallCommand}from"./chunk-
|
|
2
|
+
import{BREAKING_VERSIONS,CURRENT_VERSION,DEFAULT_RELEASE_CHANNEL,RELEASE_CHANNELS,UPDATE_COMMAND,UPDATE_SCRIPT_URL,breakingVersionsCrossed,channelOf,checkLatestVersion,fetchReleaseSummaries,recommendedGlobalInstallCommand}from"./chunk-d89r3kx9.js";import"./chunk-ch9b1d5y.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-r3k9rbwm.js";import{__require}from"./chunk-wqfp8d9w.js";import{spawnSync}from"child_process";var CLI_NAME=activeCliName();function updatePlan(target){let shell=target===void 0?UPDATE_COMMAND:`${UPDATE_COMMAND} -s -- ${target}`;return{command:"sh",args:["-c",shell],display:shell}}var VERSION_SHAPE=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;function isReleaseChannel(value){return RELEASE_CHANNELS.includes(value)}function parseUpdateArgs(args){let dryRun=!1,list=!1,version,channel;for(let i=0;i<args.length;i+=1){let arg=args[i];if(arg===void 0)continue;if(arg==="--help"||arg==="-h"||arg==="help")return{help:!0,dryRun,list,version,channel};if(arg==="dry-run"||arg==="--dry-run"){dryRun=!0;continue}if(arg==="list"||arg==="--list"){list=!0;continue}if(arg==="--channel"||arg.startsWith("--channel=")){let value=(arg.startsWith("--channel=")?arg.slice(10):void 0)??args[++i];if(value===void 0||!isReleaseChannel(value))process.stderr.write(`${CLI_NAME} update: --channel expects one of ${RELEASE_CHANNELS.join(", ")}${value===void 0?"":` (got "${value}")`}
|
|
3
3
|
|
|
4
4
|
`),printUsage(process.stderr),process.exit(2);channel=value;continue}if(channel===void 0&&isReleaseChannel(arg)){channel=arg;continue}if(version===void 0&&VERSION_SHAPE.test(arg)){version=arg;continue}process.stderr.write(`${CLI_NAME} update: unknown argument "${arg}"
|
|
5
5
|
|
|
@@ -10,7 +10,7 @@ import{BREAKING_VERSIONS,CURRENT_VERSION,DEFAULT_RELEASE_CHANNEL,RELEASE_CHANNEL
|
|
|
10
10
|
install one with: ${CLI_NAME} update <version>
|
|
11
11
|
`)}async function warnBreakingCrossings(target,channel,io){if(BREAKING_VERSIONS.length===0)return;let resolved=target??(await checkLatestVersion({force:!0,channel}))?.latest;if(!resolved)return;let crossed=breakingVersionsCrossed(CURRENT_VERSION,resolved);if(crossed.length===0)return;io.stderr.write([`warning: ${CURRENT_VERSION} -> ${resolved} crosses breaking version(s): ${crossed.join(", ")}.`,`After this update, Rove will refuse to start until you run \`${CLI_NAME} reset\``,"(worktrees are never touched; add --hard only to also wipe the task index).",""].join(`
|
|
12
12
|
`))}var FOLLOW_UP_NOTE=["",`${CLI_NAME}: installed. Two background processes are still running the old build:`,` daemon \u2192 \`${CLI_NAME} daemon restart\` (safe; never touches live sessions)`,` pty host \u2192 only \`${CLI_NAME} reset\` replaces it, and that ends every live`," terminal and engine session \u2014 do it when you can afford to.",`Run \`${CLI_NAME} doctor\` to see which of the two is actually stale.`,""].join(`
|
|
13
|
-
`);async function runUpdateSubcommand(args,deps){let io={spawn:deps?.spawn??spawnSync,stdout:deps?.stdout??process.stdout,stderr:deps?.stderr??process.stderr,exit:deps?.exit??((code)=>process.exit(code))},parsed=parseUpdateArgs(args);if(parsed.help){printUsage(io.stdout);return}if(parsed.list){if(deps===void 0&&process.stdout.isTTY){let{startVersionsHost}=await import("./chunk-
|
|
13
|
+
`);async function runUpdateSubcommand(args,deps){let io={spawn:deps?.spawn??spawnSync,stdout:deps?.stdout??process.stdout,stderr:deps?.stderr??process.stderr,exit:deps?.exit??((code)=>process.exit(code))},parsed=parseUpdateArgs(args);if(parsed.help){printUsage(io.stdout);return}if(parsed.list){if(deps===void 0&&process.stdout.isTTY){let{startVersionsHost}=await import("./chunk-mmjcb6te.js");await startVersionsHost();return}await printVersionList(io);return}let channel=parsed.channel??channelOf(),target=parsed.version??(channel===DEFAULT_RELEASE_CHANNEL?void 0:channel),plan=updatePlan(target),switching=parsed.channel!==void 0&&parsed.channel!==channelOf();if(io.stdout.write(`${CLI_NAME} ${CURRENT_VERSION} -> ${target??channel}
|
|
14
14
|
`),switching)io.stdout.write(`switching channel: ${channelOf()} -> ${channel}
|
|
15
15
|
`);if(io.stdout.write(`running: ${plan.display}
|
|
16
16
|
`),await warnBreakingCrossings(parsed.version,channel,io),parsed.dryRun)return;let result=io.spawn(plan.command,plan.args,{stdio:"inherit"});if(result.error)io.stderr.write(`${CLI_NAME} update: failed to run ${plan.command}: ${result.error.message}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-
|
|
2
|
+
import{BREAKING_VERSIONS,CURRENT_VERSION,compareSemver}from"./chunk-d89r3kx9.js";import{loadStateFile,patchStateFile}from"./chunk-j75axe29.js";import{activeCliName}from"./chunk-v0zxyqrq.js";var LAST_RUN_VERSION_KEY="app.lastRunVersion";function resetGateBlockers(lastRun,current=CURRENT_VERSION,breaking=BREAKING_VERSIONS){if(typeof lastRun!=="string"||lastRun.length===0)return[];let[lo,hi]=compareSemver(lastRun,current)<=0?[lastRun,current]:[current,lastRun];return breaking.filter((b)=>compareSemver(b,lo)>0&&compareSemver(b,hi)<=0)}function enforceResetGate(){let cliName=activeCliName(),lastRun=loadStateFile()[LAST_RUN_VERSION_KEY],blockers=resetGateBlockers(lastRun);if(blockers.length>0){let from=typeof lastRun==="string"?lastRun:"unknown";console.error([`${cliName} ${CURRENT_VERSION}: cannot start \u2014 version ${blockers.join(", ")} introduced breaking changes`,`(last run: ${from}). Your daemon/session state may be incompatible.`,"","Run:",` ${cliName} reset # stop daemon + PTY host + sessions (tasks kept)`,` ${cliName} reset --hard # additionally wipe the task index + UI state`,"","Then relaunch Rove. Worktrees are never touched."].join(`
|
|
3
3
|
`)),process.exit(1)}if(lastRun!==CURRENT_VERSION)stampResetGate()}function stampResetGate(){try{patchStateFile({[LAST_RUN_VERSION_KEY]:CURRENT_VERSION})}catch{}}
|
|
4
4
|
export{LAST_RUN_VERSION_KEY,enforceResetGate,stampResetGate};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-
|
|
2
|
+
import{describeAccount,detectEngineStatuses,probeableEngineIds,summarizeEngines}from"./chunk-3p2e2ry4.js";import{t}from"./chunk-z490gs8g.js";import{createInterface}from"readline";function daemonRestartFix(cliName,reason){return{kind:"run",id:"daemon-restart",label:t(`doctor.fix.${reason}`),command:[cliName,"daemon","restart"],why:t("doctor.fix.daemonRestartWhy")}}function skillInstallFix(installCommand,stale){return{kind:"run",id:"skill-install",label:t(stale?"doctor.fix.skillStale":"doctor.fix.skillMissing"),command:installCommand.split(" "),why:t("doctor.fix.skillInstallWhy")}}function resetManualFix(cliName,reason){return{kind:"manual",id:`reset:${reason}`,label:t(`doctor.fix.${reason}`),action:`${cliName} reset`,why:t("doctor.fix.resetWhy")}}function killOrphansManualFix(cliName,count){return{kind:"manual",id:"kill-orphans",label:t("doctor.fix.orphans",{count}),action:`${cliName} doctor --kill-orphans`,why:t("doctor.fix.orphansWhy")}}function engineTabsManualFix(){return{kind:"manual",id:"engine-tabs",label:t("doctor.fix.engineTabs"),action:t("doctor.fix.engineTabsAction"),why:t("doctor.fix.engineTabsWhy")}}function reinstallManualFix(){return{kind:"manual",id:"reinstall",label:t("doctor.fix.staleInstall"),action:t("doctor.fix.staleInstallAction"),why:t("doctor.fix.staleInstallWhy")}}function spawnHelperFix(paths){return{kind:"run",id:"spawn-helper-chmod",label:t("doctor.fix.spawnHelper"),command:["chmod","755",...paths],why:t("doctor.fix.spawnHelperWhy")}}function humanOnlyFix(reason,vars){return{kind:"manual",id:reason,label:t(`doctor.fix.${reason}`),action:t(`doctor.fix.${reason}Action`,vars),why:t("doctor.fix.humanOnlyWhy")}}function noEngineFix(signedOut){return signedOut.length>0?humanOnlyFix("noEngineLogin",{list:signedOut.join(", ")}):humanOnlyFix("noEngine")}function noEngineAction(signedOut){return signedOut.length>0?t("doctor.fix.noEngineLoginAction",{list:signedOut.join(", ")}):t("doctor.fix.noEngineAction")}function dedupeFixes(fixes){let seen=new Set;return fixes.filter((fix)=>{if(seen.has(fix.id))return!1;return seen.add(fix.id),!0})}async function applyFixes(collected,rt){let fixes=dedupeFixes(collected);if(fixes.length===0){rt.out(""),rt.out(t("doctor.fix.none"));return}let runnable=fixes.filter((fix)=>fix.kind==="run");if(runnable.length>0){rt.out(""),rt.out(t("doctor.fix.header"));for(let fix of runnable){if(rt.out(` ${fix.label}`),rt.out(` ${t("doctor.fix.willRun",{command:fix.command.join(" ")})}`),rt.out(` ${fix.why}`),!rt.interactive)continue;if(!await rt.confirm(` ${t("doctor.fix.confirmPrompt")}`)){rt.out(` ${t("doctor.fix.skipped")}`);continue}let code=await rt.exec(fix.command);rt.out(code===0?` ${t("doctor.fix.done")}`:` ${t("doctor.fix.failed",{code})}`)}if(!rt.interactive)rt.out(` ${t("doctor.fix.nonInteractive")}`)}let manual=fixes.filter((fix)=>fix.kind==="manual");if(manual.length>0){rt.out(""),rt.out(t("doctor.fix.manualHeader"));for(let fix of manual)rt.out(` ${fix.label}`),rt.out(` \u2192 ${fix.action}`),rt.out(` ${fix.why}`)}}async function confirmTty(question){let readline=createInterface({input:process.stdin,output:process.stdout});try{let answer=await new Promise((resolve)=>readline.question(question,resolve));return answer.trim().toLowerCase()==="y"||answer.trim().toLowerCase()==="yes"}finally{readline.close()}}async function execInherited(command){try{return await Bun.spawn([...command],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited}catch{return 127}}function defaultFixRuntime(){return{confirm:confirmTty,exec:execInherited,out:(line)=>console.log(line),interactive:process.stdin.isTTY===!0}}async function probeGit(){try{let proc=Bun.spawn(["git","--version"],{stdin:"ignore",stdout:"pipe",stderr:"ignore"}),text=(await new Response(proc.stdout).text()).trim();if(await proc.exited===0&&text)return{line:`git: \u2713 ${text}`,found:!0}}catch{}return{line:"git: \u2717 not found on PATH",found:!1}}function binaryLabel(binary){return binary.found?`\u2713 ${binary.path}`:`\u2717 ${binary.error}`}async function probeEngines(){let statuses=await detectEngineStatuses(await probeableEngineIds()),lines=["engines:"];for(let status of statuses){let account=describeAccount(status.account),name=`${status.vendor.padEnd(7)} `;if(lines.push(` ${name}${binaryLabel(status.binary)}${status.binary.found?` \u2014 ${account}`:""}`),status.accountError)lines.push(` \u26A0 ${status.accountError}`)}let{usable,signedOut}=summarizeEngines(statuses);return{lines,anyUsable:usable.length>0,signedOut}}async function checkOnboardingEnv(){let[git,engines]=await Promise.all([probeGit(),probeEngines()]);return{git,engines}}
|
|
3
3
|
export{daemonRestartFix,skillInstallFix,resetManualFix,killOrphansManualFix,engineTabsManualFix,reinstallManualFix,spawnHelperFix,humanOnlyFix,noEngineFix,noEngineAction,applyFixes,defaultFixRuntime,probeGit,probeEngines,checkOnboardingEnv};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{BUNDLED_THEME_JSONS}from"./chunk-zqfbyq0a.js";import{DEFAULT_LOCALE,isLocaleId}from"./chunk-
|
|
2
|
+
import{BUNDLED_THEME_JSONS}from"./chunk-zqfbyq0a.js";import{DEFAULT_LOCALE,isLocaleId}from"./chunk-vx1yfc9c.js";import{kvStatePath}from"./chunk-ch9b1d5y.js";import{RGBA as RGBA2}from"@opentui/core";import{RGBA}from"@opentui/core";var HOST_TEXT_MIN_CONTRAST=4.5;function srgbChannelToLinear(c){let v=c/255;return v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4}function relativeLuminance([r,g,b]){return 0.2126*srgbChannelToLinear(r)+0.7152*srgbChannelToLinear(g)+0.0722*srgbChannelToLinear(b)}function contrastRatioTriplet(fg,bg){let l1=relativeLuminance(fg),l2=relativeLuminance(bg),lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+0.05)/(darker+0.05)}function rgbToHsl([r,g,b]){let rn=r/255,gn=g/255,bn=b/255,max=Math.max(rn,gn,bn),min=Math.min(rn,gn,bn),l=(max+min)/2;if(max===min)return[0,0,l];let d=max-min,s=l>0.5?d/(2-max-min):d/(max+min),h;if(max===rn)h=((gn-bn)/d+(gn<bn?6:0))*60;else if(max===gn)h=((bn-rn)/d+2)*60;else h=((rn-gn)/d+4)*60;return[h,s,l]}function hslToRgb(h,s,l){if(s===0){let v=Math.round(l*255);return[v,v,v]}let q=l<0.5?l*(1+s):l+s-l*s,p=2*l-q,channel=(t)=>{let tn=t;if(tn<0)tn+=1;if(tn>1)tn-=1;let c=tn<0.16666666666666666?p+(q-p)*6*tn:tn<0.5?q:tn<0.6666666666666666?p+(q-p)*(0.6666666666666666-tn)*6:p;return Math.round(c*255)};return[channel(h/360+0.3333333333333333),channel(h/360),channel(h/360-0.3333333333333333)]}var MID_HOST_LUMINANCE=0.5;function ensureContrast(fg,bg,minRatio=HOST_TEXT_MIN_CONTRAST){let fgInts=fg.toInts(),bgInts=bg.toInts(),fgTriplet=[fgInts[0],fgInts[1],fgInts[2]],bgTriplet=[bgInts[0],bgInts[1],bgInts[2]];if(contrastRatioTriplet(fgTriplet,bgTriplet)>=minRatio)return fg;let[h,s,l]=rgbToHsl(fgTriplet),lighten=relativeLuminance(bgTriplet)<=MID_HOST_LUMINANCE,at=(lightness)=>contrastRatioTriplet(hslToRgb(h,s,lightness),bgTriplet),lo=lighten?l:0,hi=lighten?1:l;for(let i=0;i<32;i++){let mid=(lo+hi)/2;if(at(mid)>=minRatio)if(lighten)hi=mid;else lo=mid;else if(lighten)lo=mid;else hi=mid}let[r,g,b]=hslToRgb(h,s,lighten?hi:lo);return RGBA.fromInts(r,g,b,fgInts[3])}var BUNDLED_THEMES=BUNDLED_THEME_JSONS,DEFAULT_THEME="claude";function hasBundledTheme(name){return Boolean(BUNDLED_THEMES[name])}var FOCUS_ACCENT_SLOTS=["primary","success","info"];function resolveTheme(theme,mode="dark"){let defs=theme.defs??{};function resolve(c,chain=[]){if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA2.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA2.fromHex(c);if(chain.includes(c))return RGBA2.fromInts(0,0,0);let next=defs[c]??theme.theme[c];if(next===void 0)return RGBA2.fromInts(0,0,0);return resolve(next,[...chain,c])}return resolve(c[mode],chain)}let out={};for(let[k,v]of Object.entries(theme.theme))out[k]=resolve(v);let text=out.text??RGBA2.fromHex("#ffffff"),background=out.background??RGBA2.fromHex("#000000");return{...{primary:out.primary??text,secondary:out.secondary??text,accent:out.accent??out.primary??text,error:out.error??text,warning:out.warning??text,warningOnHost:out.warning??text,success:out.success??text,info:out.info??text,text,textMuted:out.textMuted??text,background,backgroundPanel:out.backgroundPanel??background,backgroundElement:out.backgroundElement??background,backgroundMenu:out.backgroundMenu??out.backgroundElement??background,backgroundDialog:out.backgroundDialog??out.backgroundPanel??background,border:out.border??text,borderActive:out.borderActive??out.border??text,borderSubtle:out.borderSubtle??out.border??text,diffAdded:out.diffAdded??out.success??text,diffRemoved:out.diffRemoved??out.error??text,diffContext:out.diffContext??out.textMuted??text,diffHunkHeader:out.diffHunkHeader??out.textMuted??text,diffAddedBg:out.diffAddedBg??background,diffRemovedBg:out.diffRemovedBg??background,selectedListItemText:out.selectedListItemText??background},...out}}function applyDisplayOverlay(base,focusAccent,transparentBackground,hostBackground){let v={...base,focusAccent:base[focusAccent]??base.primary,warningOnHost:base.warning};if(!transparentBackground)return v;let[backgroundR,backgroundG,backgroundB]=base.background.toInts(),[panelR,panelG,panelB]=base.backgroundPanel.toInts(),transparent={...v,background:RGBA2.fromInts(backgroundR,backgroundG,backgroundB,0),backgroundPanel:RGBA2.fromInts(panelR,panelG,panelB,0)};if(!hostBackground)return transparent;return{...transparent,text:ensureContrast(transparent.text,hostBackground),textMuted:ensureContrast(transparent.textMuted,hostBackground),warningOnHost:ensureContrast(transparent.warning,hostBackground)}}import{readFileSync}from"fs";var LOCALE_KEY="locale";function defaultTransparentBackground(platform=process.platform){return platform!=="win32"}function readPersistedUiPrefs(fallbackTheme,isKnownTheme=hasBundledTheme){try{let parsed=JSON.parse(readFileSync(kvStatePath(),"utf8")),theme=typeof parsed.activeTheme==="string"&&isKnownTheme(parsed.activeTheme)?parsed.activeTheme:fallbackTheme,transparent=typeof parsed.transparentBackground==="boolean"?parsed.transparentBackground:defaultTransparentBackground(),focusAccent=typeof parsed.focusAccent==="string"&&FOCUS_ACCENT_SLOTS.includes(parsed.focusAccent)?parsed.focusAccent:null,locale=isLocaleId(parsed[LOCALE_KEY])?parsed[LOCALE_KEY]:DEFAULT_LOCALE;return{theme,transparent,focusAccent,locale}}catch{return{theme:fallbackTheme,transparent:defaultTransparentBackground(),focusAccent:null,locale:DEFAULT_LOCALE}}}
|
|
3
3
|
export{BUNDLED_THEMES,DEFAULT_THEME,FOCUS_ACCENT_SLOTS,resolveTheme,applyDisplayOverlay,LOCALE_KEY,readPersistedUiPrefs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{stampResetGate}from"./chunk-
|
|
2
|
+
import{stampResetGate}from"./chunk-eb3bdewe.js";import{clearFrozenSessions}from"./chunk-t2v3ad8y.js";import{stopLegacyTmux}from"./chunk-dqndd97s.js";import"./chunk-d89r3kx9.js";import"./chunk-7q67dz4c.js";import{stopDaemonProcess}from"./chunk-8wv8526c.js";import"./chunk-0gepyh6e.js";import"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{kvStatePath,legacyKobeKvStatePath,legacyKobeStateDir,roveStateDir}from"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import{activeCliName}from"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import{defaultDaemonPidPath,defaultDaemonSocketPath,defaultPtyFreezeDir,defaultPtyHostPidPath,defaultPtyHostSocketPath}from"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.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 DELETE the task index and the whole settings file"," (saved projects, custom engines, theme, language, onboarding)"," -y, --yes Skip the interactive confirmation. REQUIRED without a terminal;"," a non-interactive run without it exits 2 and changes nothing."," -h, --help Print this help",""].join(`
|
|
3
3
|
`))}function taskCount(path){try{let parsed=JSON.parse(readFileSync(path,"utf8"));return Array.isArray(parsed.tasks)?parsed.tasks.length:null}catch{return null}}function stateSummary(path){let parsed;try{parsed=JSON.parse(readFileSync(path,"utf8"))}catch{return[]}let count=(key)=>Array.isArray(parsed[key])?parsed[key].length:0,lines=[` saved projects: ${count("savedRepos")}`,` custom engines: ${count("customEngineIds")} (their launch commands live here and nowhere else)`],present=[["activeTheme","theme"],["defaultVendor","default engine"],["locale","language"],["onboarded","onboarding (the wizard runs again)"]].filter(([key])=>parsed[key]!==void 0).map(([,label])=>label);if(present.length>0)lines.push(` also set: ${present.join(", ")}`);return lines.push(` ${Object.keys(parsed).length} setting(s) in total`),lines}async function confirmTty(prompt){let readline=createInterface({input:process.stdin,output:process.stdout});try{let answer=await new Promise((resolve)=>readline.question(prompt,resolve));return/^y(es)?$/i.test(answer.trim())}finally{readline.close()}}async function removeStateFile(path,label){try{await unlink(path),console.log(` removed ${label} (${path})`)}catch(err){if(err.code==="ENOENT")console.log(` ${label}: already absent`);else throw Error(`failed to remove ${label} (${path}): ${errorMessage(err)}`)}}async function runResetSubcommand(argv){if(argv.some((arg)=>arg==="--help"||arg==="-h"||arg==="help")){printUsage(process.stdout);return}let known=new Set(["--hard","--yes","-y"]),unknown=argv.find((arg)=>!known.has(arg));if(unknown!==void 0)process.stderr.write(`${CLI_NAME} reset: unknown argument "${unknown}"
|
|
4
4
|
|
|
5
5
|
`),printUsage(process.stderr),process.exit(2);let hard=argv.includes("--hard"),yes=argv.includes("--yes")||argv.includes("-y"),daemonSocket=defaultDaemonSocketPath(),tasksPath=join(roveStateDir(),"tasks.json"),legacyTasksPath=join(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 whole settings file \u2014 ${statePath}`);for(let line of stateSummary(statePath))console.log(line);console.log(" \u2022 DELETE the pre-Rove task/UI indexes too, so migration cannot restore reset state")}if(console.log(" \u2022 NOT touch your git worktrees under ~/.rove/worktrees/, ~/.kobe/worktrees/, or repo-local roots"),!hard)console.log(" (your task list, settings & worktrees are kept \u2014 add --hard to also delete the task index and settings file)");if(!yes){if(!process.stdin.isTTY){console.log(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{ulid}from"./chunk-qkehg2c1.js";import{acquireWithRetry,mergeTasksWithDisk,readDiskIndex,recoverIndexFromDisk}from"./chunk-k1qe5qqa.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{release}from"./chunk-ayhhgfsz.js";import{LEGACY_KOBE_STATE_DIR_BASENAME,ROVE_STATE_DIR_BASENAME}from"./chunk-g56kvet6.js";import{readRoveHomeDirEnv}from"./chunk-r3k9rbwm.js";import{mkdir,open,rename,unlink}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var CURRENT_VERSION=3;class TaskIndexStore{homeDir;roveDir;path;legacyPath;lockPath;cache={version:CURRENT_VERSION,tasks:[]};loaded=!1;listeners=new Set;saveChain=Promise.resolve();dirtyIds=new Set;removedIds=new Map;constructor(options={}){this.homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),this.roveDir=join(this.homeDir,ROVE_STATE_DIR_BASENAME),this.path=join(this.roveDir,"tasks.json"),this.legacyPath=join(this.homeDir,LEGACY_KOBE_STATE_DIR_BASENAME,"tasks.json"),this.lockPath=`${this.path}.lock`}subscribe(listener){if(this.listeners.add(listener),this.loaded)try{listener(this.cache.tasks.slice())}catch(err){console.error("[rove TaskIndexStore] listener threw on subscribe:",err)}return()=>{this.listeners.delete(listener)}}get filePath(){return this.path}get stateDir(){return this.roveDir}async load(){return this.dirtyIds.clear(),this.removedIds.clear(),this.cache=await recoverIndexFromDisk(this.path,this.legacyPath),this.loaded=!0,this.notifyListeners(),this.snapshot()}async save(){this.assertLoaded();let next=this.saveChain.then(()=>this.doSave());return this.saveChain=next.catch(()=>{}),next}async saveOrRollback(id,undo){try{await this.save()}catch(err){if(undo())this.dirtyIds.delete(id),this.notifyListeners();throw err}}async doSave(){await mkdir(dirname(this.path),{recursive:!0});let dirty=new Set(this.dirtyIds),removed=new Map(this.removedIds),lockToken=await acquireWithRetry(this.lockPath),cacheChanged=!1;try{let disk=await readDiskIndex(this.path,this.legacyPath),merged=mergeTasksWithDisk(this.cache.tasks,disk.tasks,dirty,removed,disk.removed),payload={version:CURRENT_VERSION,tasks:merged.tasks,...merged.removed.length>0?{removed:merged.removed}:{}},json=`${JSON.stringify(payload)}
|
|
3
|
-
`,tmpPath=`${this.path}.${process.pid}.${ulid()}.tmp`;try{let handle=await open(tmpPath,"w",384);try{await handle.writeFile(json,"utf8"),await handle.sync()}finally{await handle.close()}await rename(tmpPath,this.path)}catch(err){throw await unlink(tmpPath).catch(()=>{}),err}for(let id of dirty)this.dirtyIds.delete(id);for(let id of removed.keys())this.removedIds.delete(id);let present=new Set(this.cache.tasks.map((t)=>t.id));for(let task of merged.tasks){if(present.has(task.id))continue;this.cache.tasks.push(task),cacheChanged=!0}let tombstoned=new Set(merged.removed.map((t)=>t.id));if(tombstoned.size>0)for(let i=this.cache.tasks.length-1;i>=0;i--){let entry=this.cache.tasks[i];if(!entry||!tombstoned.has(entry.id))continue;this.cache.tasks.splice(i,1),cacheChanged=!0}}finally{await release(this.lockPath,lockToken).catch((err)=>{console.error("[rove TaskIndexStore] index lock release failed:",err)})}if(cacheChanged)this.notifyListeners()}get(id){return this.assertLoaded(),this.cache.tasks.find((t)=>t.id===id)}list(){return this.assertLoaded(),this.cache.tasks.slice()}async create(partial){this.assertLoaded();let now=new Date().toISOString(),task={vendor:partial.vendor??DEFAULT_TASK_VENDOR,...partial,id:toTaskId(ulid()),createdAt:now,updatedAt:now};return this.cache.tasks.push(task),this.dirtyIds.add(task.id),await this.saveOrRollback(task.id,()=>{let at=this.cache.tasks.indexOf(task);if(at<0)return!1;return this.cache.tasks.splice(at,1),!0}),this.notifyListeners(),task}async update(id,patch){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)throw Error(`task not found: ${id}`);let existing=this.cache.tasks[idx];if(!existing)throw Error(`task not found: ${id}`);let{id:_id,createdAt:_createdAt,...mutable}=patch,next={...existing,...mutable,id:existing.id,createdAt:existing.createdAt,updatedAt:new Date().toISOString()};return this.cache.tasks[idx]=next,this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks[at]=existing,!0}),this.notifyListeners(),next}touchRecency(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return;let existing=this.cache.tasks[idx];if(!existing)return;this.cache.tasks[idx]={...existing,updatedAt:new Date().toISOString()},this.dirtyIds.add(String(id)),this.notifyListeners()}async move(id,delta,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);let ids=withinIds?.length?withinIds:this.cache.tasks.map((t)=>t.id),pos=ids.indexOf(String(id));if(pos<0)throw Error(`task not movable in current group: ${id}`);let targetId=ids[pos+delta];if(!targetId)return task;let fromIdx=this.cache.tasks.findIndex((t)=>t.id===id),toIdx=this.cache.tasks.findIndex((t)=>t.id===targetId);if(fromIdx<0||toIdx<0||fromIdx===toIdx)return task;let[moved]=this.cache.tasks.splice(fromIdx,1);if(!moved)return task;let adjustedToIdx=fromIdx<toIdx?toIdx-1:toIdx,insertAt=delta>0?adjustedToIdx+1:adjustedToIdx,next={...moved,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(insertAt,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,moved),!0}),this.notifyListeners(),next}async remove(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return!1;return this.cache.tasks.splice(idx,1),this.dirtyIds.delete(String(id)),this.removedIds.set(String(id),new Date().toISOString()),await this.
|
|
3
|
+
`,tmpPath=`${this.path}.${process.pid}.${ulid()}.tmp`;try{let handle=await open(tmpPath,"w",384);try{await handle.writeFile(json,"utf8"),await handle.sync()}finally{await handle.close()}await rename(tmpPath,this.path)}catch(err){throw await unlink(tmpPath).catch(()=>{}),err}for(let id of dirty)this.dirtyIds.delete(id);for(let id of removed.keys())this.removedIds.delete(id);let present=new Set(this.cache.tasks.map((t)=>t.id));for(let task of merged.tasks){if(present.has(task.id))continue;this.cache.tasks.push(task),cacheChanged=!0}let tombstoned=new Set(merged.removed.map((t)=>t.id));if(tombstoned.size>0)for(let i=this.cache.tasks.length-1;i>=0;i--){let entry=this.cache.tasks[i];if(!entry||!tombstoned.has(entry.id))continue;this.cache.tasks.splice(i,1),cacheChanged=!0}}finally{await release(this.lockPath,lockToken).catch((err)=>{console.error("[rove TaskIndexStore] index lock release failed:",err)})}if(cacheChanged)this.notifyListeners()}get(id){return this.assertLoaded(),this.cache.tasks.find((t)=>t.id===id)}list(){return this.assertLoaded(),this.cache.tasks.slice()}async create(partial){this.assertLoaded();let now=new Date().toISOString(),task={vendor:partial.vendor??DEFAULT_TASK_VENDOR,...partial,id:toTaskId(ulid()),createdAt:now,updatedAt:now};return this.cache.tasks.push(task),this.dirtyIds.add(task.id),await this.saveOrRollback(task.id,()=>{let at=this.cache.tasks.indexOf(task);if(at<0)return!1;return this.cache.tasks.splice(at,1),!0}),this.notifyListeners(),task}async update(id,patch){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)throw Error(`task not found: ${id}`);let existing=this.cache.tasks[idx];if(!existing)throw Error(`task not found: ${id}`);let{id:_id,createdAt:_createdAt,...mutable}=patch,next={...existing,...mutable,id:existing.id,createdAt:existing.createdAt,updatedAt:new Date().toISOString()};return this.cache.tasks[idx]=next,this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks[at]=existing,!0}),this.notifyListeners(),next}touchRecency(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)return;let existing=this.cache.tasks[idx];if(!existing)return;this.cache.tasks[idx]={...existing,updatedAt:new Date().toISOString()},this.dirtyIds.add(String(id)),this.notifyListeners()}async move(id,delta,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);let ids=withinIds?.length?withinIds:this.cache.tasks.map((t)=>t.id),pos=ids.indexOf(String(id));if(pos<0)throw Error(`task not movable in current group: ${id}`);let targetId=ids[pos+delta];if(!targetId)return task;let fromIdx=this.cache.tasks.findIndex((t)=>t.id===id),toIdx=this.cache.tasks.findIndex((t)=>t.id===targetId);if(fromIdx<0||toIdx<0||fromIdx===toIdx)return task;let[moved]=this.cache.tasks.splice(fromIdx,1);if(!moved)return task;let adjustedToIdx=fromIdx<toIdx?toIdx-1:toIdx,insertAt=delta>0?adjustedToIdx+1:adjustedToIdx,next={...moved,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(insertAt,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,moved),!0}),this.notifyListeners(),next}async remove(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id),removed=this.cache.tasks[idx];if(idx<0||!removed)return!1;return this.cache.tasks.splice(idx,1),this.dirtyIds.delete(String(id)),this.removedIds.set(String(id),new Date().toISOString()),await this.saveOrRollback(String(id),()=>{if(this.cache.tasks.some((t)=>t.id===removed.id))return!1;return this.removedIds.delete(String(id)),this.cache.tasks.splice(Math.min(idx,this.cache.tasks.length),0,removed),!0}),this.notifyListeners(),!0}async _unlinkForTests(){try{await unlink(this.path)}catch(err){if(err.code!=="ENOENT")throw err}this.cache={version:CURRENT_VERSION,tasks:[]},this.loaded=!1,this.dirtyIds.clear(),this.removedIds.clear()}assertLoaded(){if(!this.loaded)throw Error("TaskIndexStore: call load() before any other method")}snapshot(){return{version:CURRENT_VERSION,tasks:this.cache.tasks.slice()}}notifyListeners(){if(this.listeners.size===0)return;let snapshot=this.cache.tasks.slice();for(let listener of this.listeners)try{listener(snapshot)}catch(err){console.error("[rove TaskIndexStore] listener threw on notify:",err)}}}
|
|
4
4
|
export{TaskIndexStore};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{CURRENT_VERSION,repoSlug}from"./chunk-
|
|
2
|
+
import{CURRENT_VERSION,repoSlug}from"./chunk-d89r3kx9.js";import{spawnSync}from"child_process";var DEFAULT_FEEDBACK_CATEGORY_SLUG="feedback",DISCUSSION_CATEGORY_QUERY=`
|
|
3
3
|
query($owner: String!, $name: String!) {
|
|
4
4
|
repository(owner: $owner, name: $name) {
|
|
5
5
|
id
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ensureGlobalKobeHooks,readTextWithTimeout,runHookSubcommand}from"./chunk-
|
|
2
|
+
import{ensureGlobalKobeHooks,readTextWithTimeout,runHookSubcommand}from"./chunk-c562kjgk.js";import"./chunk-3e5n28t6.js";import"./chunk-r2pztgm6.js";import"./chunk-38272eqv.js";import"./chunk-jvxh93nz.js";import"./chunk-h9mqdxvs.js";import"./chunk-8wv8526c.js";import"./chunk-0gepyh6e.js";import"./chunk-bkvr06xn.js";import"./chunk-mnqxgvyb.js";import"./chunk-xhw8s2es.js";import"./chunk-khj0apc7.js";import"./chunk-nzscq4yf.js";import"./chunk-w7zv47mp.js";import"./chunk-dt51afhh.js";import"./chunk-7jkf3tvr.js";import"./chunk-2fypr41w.js";import"./chunk-k1qe5qqa.js";import"./chunk-xy8be792.js";import"./chunk-6wpege0h.js";import"./chunk-j75axe29.js";import"./chunk-ayhhgfsz.js";import"./chunk-2brn8e1y.js";import"./chunk-bq3fyc0p.js";import"./chunk-3wj69b0a.js";import"./chunk-ch9b1d5y.js";import"./chunk-mv7ptt5w.js";import"./chunk-v0zxyqrq.js";import"./chunk-e29hx18x.js";import"./chunk-g56kvet6.js";import"./chunk-k2ckx8zw.js";import"./chunk-pw6yfj10.js";import"./chunk-mcdv19rs.js";import"./chunk-r3k9rbwm.js";import"./chunk-wqfp8d9w.js";export{runHookSubcommand,readTextWithTimeout,ensureGlobalKobeHooks};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{closeTab,engineTabArgv,initialTabs,setTabTitle,terminalTabsKey}from"./chunk-nrafk2b7.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,enginePresence,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,initMarkerSaysFinished,isHostedTaskKey,killHostedSessions,listHostedSessions,listHostedSessionsOrNull,openHostedSessionHost,pastePromptWhenEngineUp,readPersistedTerminalDefaultColors,writeHostedPromptIfClear}from"./chunk-mbb0pp66.js";import{engineLaunchArgv,protocolEntry}from"./chunk-vhrfe63r.js";import{loadStateFile,patchStateFile,updateStateFile}from"./chunk-j75axe29.js";function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function closeTabsSnapshot(taskId,tabId){let closing,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return!1;let{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return closing=void 0,!1;store[key]=next;return}),closing}function renameTabsSnapshot(taskId,tabId,title){let found=!1,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(!state.tabs.some((tab)=>tab.id===tabId))return!1;found=!0;let next=setTabTitle(state,tabId,title);if(next===state)return!1;store[key]=next;return}),found}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t)=>t.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t)=>{let key=`${taskId}::${t.id}`,isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:walked!==void 0?walked:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0))rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,autoTitle:null,alive:!0,engineAlive:engineAliveOf(`${taskId}::${tabId}`,!0,engineAlive),exit:null,unregistered:!0});return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}function publishCliTabSnapshot(taskId,sessionId){if(!taskId)return;try{let key=terminalTabsKey(taskId);if(loadStateFile()[key]!==void 0)return;let seeded=initialTabs();patchStateFile({[key]:sessionId?{...seeded,tabs:seeded.tabs.map((t)=>t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}:seeded})}catch{}}function markCliTabSession(taskId,tabId,sessionId){try{let key=terminalTabsKey(taskId),existing=loadStateFile()[key];if(!existing||!Array.isArray(existing.tabs))return;patchStateFile({[key]:{...existing,tabs:existing.tabs.map((t)=>t.id===tabId&&t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}})}catch{}}function mintCliTab(taskId,vendor,command){let tabId="tab-1";try{let key=terminalTabsKey(taskId),existing=loadStateFile()[key],state=existing&&Array.isArray(existing.tabs)&&existing.tabs.length>0?existing:initialTabs(),ordinal=typeof state.nextOrdinal==="number"&&state.nextOrdinal>1?state.nextOrdinal:2;tabId=`tab-${ordinal}`,patchStateFile({[key]:{...state,tabs:[...state.tabs,{kind:"engine",id:tabId,title:null,ordinal,...vendor?{vendor}:{},...command?{engineCommand:command}:{}}],activeId:tabId,nextOrdinal:ordinal+1}})}catch{tabId=`tab-cli-${Date.now().toString(36)}`}return tabId}function restoredTabsOf(sessions,taskId,exceptKey){let prefix=`${taskId}::`,ids=[];for(let s of sessions){if(s.alive||s.restored!==!0||s.key===exceptKey||!s.key.startsWith(prefix))continue;let tab=s.key.slice(prefix.length);if(tab.includes("::"))continue;if(!ids.includes(tab))ids.push(tab)}let tabs=readTabsSnapshot(taskId)?.tabs??[];return ids.map((tab)=>{let sessionId=tabs.find((t)=>t.id===tab)?.sessionId;return sessionId?{tab,sessionId}:{tab}})}function restoredTabLaunch(task,tabId,worktreePath,shell){let tab=readTabsSnapshot(task.id)?.tabs.find((t)=>t.id===tabId&&t.kind==="engine");if(!tab)return null;let base=engineLaunchArgv({command:tab.engineCommand??(tab.vendor?void 0:task.command),vendor:tab.vendor??task.vendor,effort:task.modelEffort});return buildEngineSessionLaunch({task:{id:task.id,kind:task.kind??"task",vendor:tab.vendor??task.vendor,repo:task.repo},worktreePath,shell,argv:engineTabArgv(tab,base,!1,task.vendor),promptIntent:{kind:"none"},tabId})}class ApiError extends Error{code;data;constructor(message,code,data){super(message);this.code=code;this.data=data}}var DAEMON_CODE_PREFIX=/^([A-Z][A-Z0-9_]{2,}): /;function splitDaemonCode(message){let match=DAEMON_CODE_PREFIX.exec(message);if(!match?.[1])return null;return{code:match[1],rest:message.slice(match[0].length)}}function helpStep(verbName){return{hint:"run the verb's --help for its exact flag contract, then retry",nextCommandArgs:["api",verbName,"--help"]}}var VERB_GROUP_IDS=["discover","read","create","drive","edit","issues","workitems","routine","lifecycle","worktree","feedback"];var isTaskKey=isHostedTaskKey,findEngineKey=findHostedEngineKey,taskKeys=hostedTaskKeys,openPtyHost=openHostedSessionHost,ensurePtyHost=ensureHostedSessionHost,listSessions=listHostedSessions,listSessionsOrNull=listHostedSessionsOrNull,deliverToKey=deliverToHostedKey,writePrompt=writeHostedPromptIfClear,ENGINE_START_PROBE_MS=3000,ENGINE_START_POLL_MS=150,ENGINE_NOT_OBSERVED_REASON=`no engine process appeared in the session within ${ENGINE_START_PROBE_MS}ms`;function outcomeFields(outcome){if(!outcome)return{engineReady:!1,delivered:!1};return{engineReady:outcome.ready,delivered:!0,bytes:outcome.bytes,promptEcho:outcome.confirmed?"confirmed":"unconfirmed"}}async function deliverHostedPrompt(rpc,target,cwd,prompt,launch,opts){let{sessions=[]}=await rpc.request("pty.list",{}),existingKey=opts?.forceNew?null:findEngineKey(sessions,target.id,target.engineBin);if(existingKey){let pid=sessions.find((s)=>s.key===existingKey)?.pid,presence=await enginePresence(pid,target.engineBin,opts?.snapshot);if(presence==="unknown")throw new ApiError(`could not read the process table, so task ${target.id}'s engine tab (${existingKey}) could not be checked for a live engine`,"ENGINE_PROBE_FAILED",{hint:"the `ps` probe failed or timed out; retry, or check the machine's process table",nextCommandArgs:["api","pty-list"]});if(presence!=="engine")throw new ApiError(`task ${target.id}'s engine tab (${existingKey}) has no live engine process \u2014 its engine exited into a plain shell`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new",nextCommandArgs:["api","send","--task-id",target.id,"--tab","new","--prompt",prompt]});let deliveryOpts={screenManifest:resolveComposerManifest(opts?.vendor)},tabId=existingKey.split("::")[1]??"tab-1",outcome;try{outcome=await deliverToKey(rpc,existingKey,prompt,deliveryOpts)}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:existingKey,pane:existingKey,started:!1,...outcomeFields(outcome)}}if(!opts?.forceNew){let aliveTabs=sessions.filter((s)=>s.alive&&isTaskKey(s.key,target.id)).map((s)=>s.key);if(aliveTabs.length>0)throw new ApiError(`task ${target.id} has live tabs (${aliveTabs.join(", ")}) but none resolves as its engine tab \u2014 refusing to spawn a new engine`,"NO_ENGINE_TAB",{hint:"address a live engine tab explicitly with --tab <tab-N> (see pty-list), or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","pty-list"]})}let frozen=restoredTabsOf(sessions,target.id,launch.key),disclose=frozen.length>0?{frozenTabs:frozen}:{},staleCanonical=sessions.find((session)=>session.key===launch.key&&!session.alive);if(staleCanonical&&staleCanonical.restored!==!0)await rpc.request("pty.kill",{key:launch.key});let open=await rpc.request("pty.open",{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()});try{if(!open.alive)return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,engineReady:!1,delivered:!1,...disclose};if(launch.firstMessage){let tabId=launch.key.split("::")[1]??"tab-1",outcome;try{outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs,screenManifest:resolveComposerManifest(opts?.vendor)})}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,...outcomeFields(outcome),...disclose}}let started=open.created!==!1||open.respawned===!0;if(open.created===!1&&open.respawned!==!0){let tabId=launch.key.split("::")[1]??"tab-1",outcome;try{outcome=await writePrompt(rpc,launch.key,prompt,{screenManifest:resolveComposerManifest(opts?.vendor)})}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:launch.key,pane:launch.key,started,...outcomeFields(outcome),...disclose}}let pendingInit={session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!0,reason:"repo init script is still running; the engine has not started yet",...disclose};if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;if(await awaitEngineProcess(rpc,launch.key,target.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts?.snapshot})===null){if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath)&&(await listSessions(rpc)).some((session)=>session.key===launch.key&&session.alive)&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;return{session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,launch.key)??ENGINE_NOT_OBSERVED_REASON,...disclose}}return{session:launch.key,pane:launch.key,started,engineReady:!0,delivered:!0,...disclose}}finally{await rpc.request("pty.detach",{key:launch.key}).catch(()=>{})}}function resolveComposerManifest(vendor){return vendor?protocolEntry(vendor).screenManifest:void 0}async function deferOrThrow(error,sink,taskId,tabId,prompt){if(sink){let deferred;try{deferred=await sink.defer({taskId,tabId,prompt,layer:error.layer})}catch{throw composerBusyApiError(error,taskId,prompt)}if(deferred.kind==="occupied")throw new ApiError(`task ${taskId} tab ${tabId} already has a deferred prompt`,"DEFERRED_PROMPT_PENDING",{taskId,tabId,existingId:deferred.id,hint:"a prompt is already held for this tab \u2014 deliver it with `deferred-release --id`, or drop it with `deferred-dismiss --id`, then send yours again (`deferred-list` shows the text and its expiry)",nextCommandArgs:["api","deferred-release","--id",deferred.id]});return{session:`${taskId}::${tabId}`,pane:`${taskId}::${tabId}`,started:!1,engineReady:!1,delivered:!1,deferred:{id:deferred.id,layer:error.layer,...deferred.expiresAt!==void 0?{expiresAt:deferred.expiresAt}:{}}}}throw composerBusyApiError(error,taskId,prompt)}function composerBusyApiError(error,taskId,prompt){let layerText=error.layer==="recent-human-write"?"user was typing recently":"composer has text";return new ApiError(`task ${taskId}'s composer is busy (${layerText})`,"COMPOSER_BUSY",{layer:error.layer,hint:"wait a moment and retry, or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","send","--task-id",taskId,"--prompt",prompt]})}var killTaskSessions=killHostedSessions;
|
|
2
|
+
import{closeTab,engineTabArgv,initialTabs,setTabTitle,terminalTabsKey}from"./chunk-pj0zmjvc.js";import{ComposerBusyError,awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,enginePresence,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,initMarkerSaysFinished,isHostedTaskKey,killHostedSessions,listHostedSessions,listHostedSessionsOrNull,openHostedSessionHost,pastePromptWhenEngineUp,readPersistedTerminalDefaultColors,writeHostedPromptIfClear}from"./chunk-aqsbef90.js";import{engineLaunchArgv,protocolEntry}from"./chunk-qqw3p4fc.js";import{loadStateFile,patchStateFile,updateStateFile}from"./chunk-j75axe29.js";function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function closeTabsSnapshot(taskId,tabId){let closing,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return!1;let{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return closing=void 0,!1;store[key]=next;return}),closing}function renameTabsSnapshot(taskId,tabId,title){let found=!1,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(!state.tabs.some((tab)=>tab.id===tabId))return!1;found=!0;let next=setTabTitle(state,tabId,title);if(next===state)return!1;store[key]=next;return}),found}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t)=>t.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t)=>{let key=`${taskId}::${t.id}`,isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:walked!==void 0?walked:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0))rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,autoTitle:null,alive:!0,engineAlive:engineAliveOf(`${taskId}::${tabId}`,!0,engineAlive),exit:null,unregistered:!0});return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}function publishCliTabSnapshot(taskId,sessionId){if(!taskId)return;try{let key=terminalTabsKey(taskId);if(loadStateFile()[key]!==void 0)return;let seeded=initialTabs();patchStateFile({[key]:sessionId?{...seeded,tabs:seeded.tabs.map((t)=>t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}:seeded})}catch{}}function markCliTabSession(taskId,tabId,sessionId){try{let key=terminalTabsKey(taskId),existing=loadStateFile()[key];if(!existing||!Array.isArray(existing.tabs))return;patchStateFile({[key]:{...existing,tabs:existing.tabs.map((t)=>t.id===tabId&&t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}})}catch{}}function mintCliTab(taskId,vendor,command){let tabId="tab-1";try{let key=terminalTabsKey(taskId),existing=loadStateFile()[key],state=existing&&Array.isArray(existing.tabs)&&existing.tabs.length>0?existing:initialTabs(),ordinal=typeof state.nextOrdinal==="number"&&state.nextOrdinal>1?state.nextOrdinal:2;tabId=`tab-${ordinal}`,patchStateFile({[key]:{...state,tabs:[...state.tabs,{kind:"engine",id:tabId,title:null,ordinal,...vendor?{vendor}:{},...command?{engineCommand:command}:{}}],activeId:tabId,nextOrdinal:ordinal+1}})}catch{tabId=`tab-cli-${Date.now().toString(36)}`}return tabId}function restoredTabsOf(sessions,taskId,exceptKey){let prefix=`${taskId}::`,ids=[];for(let s of sessions){if(s.alive||s.restored!==!0||s.key===exceptKey||!s.key.startsWith(prefix))continue;let tab=s.key.slice(prefix.length);if(tab.includes("::"))continue;if(!ids.includes(tab))ids.push(tab)}let tabs=readTabsSnapshot(taskId)?.tabs??[];return ids.map((tab)=>{let sessionId=tabs.find((t)=>t.id===tab)?.sessionId;return sessionId?{tab,sessionId}:{tab}})}function restoredTabLaunch(task,tabId,worktreePath,shell){let tab=readTabsSnapshot(task.id)?.tabs.find((t)=>t.id===tabId&&t.kind==="engine");if(!tab)return null;let base=engineLaunchArgv({command:tab.engineCommand??(tab.vendor?void 0:task.command),vendor:tab.vendor??task.vendor,effort:task.modelEffort});return buildEngineSessionLaunch({task:{id:task.id,kind:task.kind??"task",vendor:tab.vendor??task.vendor,repo:task.repo},worktreePath,shell,argv:engineTabArgv(tab,base,!1,task.vendor),promptIntent:{kind:"none"},tabId})}class ApiError extends Error{code;data;constructor(message,code,data){super(message);this.code=code;this.data=data}}var DAEMON_CODE_PREFIX=/^([A-Z][A-Z0-9_]{2,}): /;function splitDaemonCode(message){let match=DAEMON_CODE_PREFIX.exec(message);if(!match?.[1])return null;return{code:match[1],rest:message.slice(match[0].length)}}function helpStep(verbName){return{hint:"run the verb's --help for its exact flag contract, then retry",nextCommandArgs:["api",verbName,"--help"]}}var VERB_GROUP_IDS=["discover","read","create","drive","edit","issues","workitems","routine","lifecycle","worktree","feedback"];var isTaskKey=isHostedTaskKey,findEngineKey=findHostedEngineKey,taskKeys=hostedTaskKeys,openPtyHost=openHostedSessionHost,ensurePtyHost=ensureHostedSessionHost,listSessions=listHostedSessions,listSessionsOrNull=listHostedSessionsOrNull,deliverToKey=deliverToHostedKey,writePrompt=writeHostedPromptIfClear,ENGINE_START_PROBE_MS=3000,ENGINE_START_POLL_MS=150,ENGINE_NOT_OBSERVED_REASON=`no engine process appeared in the session within ${ENGINE_START_PROBE_MS}ms`;function outcomeFields(outcome){if(!outcome)return{engineReady:!1,delivered:!1};return{engineReady:outcome.ready,delivered:!0,bytes:outcome.bytes,promptEcho:outcome.confirmed?"confirmed":"unconfirmed"}}async function deliverHostedPrompt(rpc,target,cwd,prompt,launch,opts){let{sessions=[]}=await rpc.request("pty.list",{}),existingKey=opts?.forceNew?null:findEngineKey(sessions,target.id,target.engineBin);if(existingKey){let pid=sessions.find((s)=>s.key===existingKey)?.pid,presence=await enginePresence(pid,target.engineBin,opts?.snapshot);if(presence==="unknown")throw new ApiError(`could not read the process table, so task ${target.id}'s engine tab (${existingKey}) could not be checked for a live engine`,"ENGINE_PROBE_FAILED",{hint:"the `ps` probe failed or timed out; retry, or check the machine's process table",nextCommandArgs:["api","pty-list"]});if(presence!=="engine")throw new ApiError(`task ${target.id}'s engine tab (${existingKey}) has no live engine process \u2014 its engine exited into a plain shell`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new",nextCommandArgs:["api","send","--task-id",target.id,"--tab","new","--prompt",prompt]});let deliveryOpts={screenManifest:resolveComposerManifest(opts?.vendor)},tabId=existingKey.split("::")[1]??"tab-1",outcome;try{outcome=await deliverToKey(rpc,existingKey,prompt,deliveryOpts)}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:existingKey,pane:existingKey,started:!1,...outcomeFields(outcome)}}if(!opts?.forceNew){let aliveTabs=sessions.filter((s)=>s.alive&&isTaskKey(s.key,target.id)).map((s)=>s.key);if(aliveTabs.length>0)throw new ApiError(`task ${target.id} has live tabs (${aliveTabs.join(", ")}) but none resolves as its engine tab \u2014 refusing to spawn a new engine`,"NO_ENGINE_TAB",{hint:"address a live engine tab explicitly with --tab <tab-N> (see pty-list), or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","pty-list"]})}let frozen=restoredTabsOf(sessions,target.id,launch.key),disclose=frozen.length>0?{frozenTabs:frozen}:{},staleCanonical=sessions.find((session)=>session.key===launch.key&&!session.alive);if(staleCanonical&&staleCanonical.restored!==!0)await rpc.request("pty.kill",{key:launch.key});let open=await rpc.request("pty.open",{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()});try{if(!open.alive)return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,engineReady:!1,delivered:!1,...disclose};if(launch.firstMessage){let tabId=launch.key.split("::")[1]??"tab-1",outcome;try{outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs,screenManifest:resolveComposerManifest(opts?.vendor)})}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,...outcomeFields(outcome),...disclose}}let started=open.created!==!1||open.respawned===!0;if(open.created===!1&&open.respawned!==!0){let tabId=launch.key.split("::")[1]??"tab-1",outcome;try{outcome=await writePrompt(rpc,launch.key,prompt,{screenManifest:resolveComposerManifest(opts?.vendor)})}catch(err){if(err instanceof ComposerBusyError)return deferOrThrow(err,opts?.defer,target.id,tabId,prompt);throw err}return{session:launch.key,pane:launch.key,started,...outcomeFields(outcome),...disclose}}let pendingInit={session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!0,reason:"repo init script is still running; the engine has not started yet",...disclose};if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;if(await awaitEngineProcess(rpc,launch.key,target.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts?.snapshot})===null){if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath)&&(await listSessions(rpc)).some((session)=>session.key===launch.key&&session.alive)&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;return{session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,launch.key)??ENGINE_NOT_OBSERVED_REASON,...disclose}}return{session:launch.key,pane:launch.key,started,engineReady:!0,delivered:!0,...disclose}}finally{await rpc.request("pty.detach",{key:launch.key}).catch(()=>{})}}function resolveComposerManifest(vendor){return vendor?protocolEntry(vendor).screenManifest:void 0}async function deferOrThrow(error,sink,taskId,tabId,prompt){if(sink){let deferred;try{deferred=await sink.defer({taskId,tabId,prompt,layer:error.layer})}catch{throw composerBusyApiError(error,taskId,prompt)}if(deferred.kind==="occupied")throw new ApiError(`task ${taskId} tab ${tabId} already has a deferred prompt`,"DEFERRED_PROMPT_PENDING",{taskId,tabId,existingId:deferred.id,hint:"a prompt is already held for this tab \u2014 deliver it with `deferred-release --id`, or drop it with `deferred-dismiss --id`, then send yours again (`deferred-list` shows the text and its expiry)",nextCommandArgs:["api","deferred-release","--id",deferred.id]});return{session:`${taskId}::${tabId}`,pane:`${taskId}::${tabId}`,started:!1,engineReady:!1,delivered:!1,deferred:{id:deferred.id,layer:error.layer,...deferred.expiresAt!==void 0?{expiresAt:deferred.expiresAt}:{}}}}throw composerBusyApiError(error,taskId,prompt)}function composerBusyApiError(error,taskId,prompt){let layerText=error.layer==="recent-human-write"?"user was typing recently":"composer has text";return new ApiError(`task ${taskId}'s composer is busy (${layerText})`,"COMPOSER_BUSY",{layer:error.layer,hint:"wait a moment and retry, or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","send","--task-id",taskId,"--prompt",prompt]})}var killTaskSessions=killHostedSessions;
|
|
3
3
|
export{ApiError,splitDaemonCode,helpStep,VERB_GROUP_IDS,taskEngineArgv,readTabsSnapshot,closeTabsSnapshot,renameTabsSnapshot,unregisteredTabIds,joinTaskTabs,publishCliTabSnapshot,markCliTabSession,mintCliTab,restoredTabLaunch,isTaskKey,findEngineKey,taskKeys,openPtyHost,ensurePtyHost,listSessions,listSessionsOrNull,deliverToKey,ENGINE_START_PROBE_MS,ENGINE_START_POLL_MS,ENGINE_NOT_OBSERVED_REASON,outcomeFields,deliverHostedPrompt,resolveComposerManifest,deferOrThrow,killTaskSessions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{engineEntry,identifiableEngineIds}from"./chunk-
|
|
2
|
+
import{engineEntry,identifiableEngineIds}from"./chunk-xhw8s2es.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import{__require}from"./chunk-wqfp8d9w.js";import{basename}from"path";var WRAPPERS=new Set(["node","bun","npx","deno","sh","zsh","bash","env","script"]);function binaryName(token){return basename(token).replace(/\.(exe|js|mjs|cjs)$/,"")}function executableNameFromArgv(argv){for(let token of argv.slice(0,8)){if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))continue;let name=binaryName(token);if(WRAPPERS.has(name))continue;return name||null}return null}function vendorFromArgv(commandLine){let name=executableNameFromArgv(commandLine.trim().split(/\s+/));if(!name)return null;return identifiableEngineIds().find((v)=>{let entry=engineEntry(v);return entry.defaultCommand[0]===name||entry.processNames?.includes(name)===!0})??null}function parsePsSnapshot(text){let rows=[];for(let line of text.split(`
|
|
3
3
|
`)){let m=/^\s*(\d+)\s+(\d+)\s+(\S.*)$/.exec(line);if(m)rows.push({pid:Number(m[1]),ppid:Number(m[2]),args:m[3]})}return rows}function childrenIndex(rows){let kids=new Map;for(let row of rows){let list=kids.get(row.ppid);if(list)list.push(row);else kids.set(row.ppid,[row])}return kids}function hasAncestor(rows,pid,ancestorPid){let parents=new Map(rows.map((r)=>[r.pid,r.ppid])),cur=pid;for(let hops=0;hops<=rows.length;hops++){if(cur===ancestorPid)return!0;let next=parents.get(cur);if(next===void 0||next<=1)return!1;cur=next}return!1}function foregroundEngineIn(rows,rootPid){let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;let vendor=vendorFromArgv(row.args);if(vendor)return{vendor,argv:row.args,pid:row.pid};queue.push(...kids.get(row.pid)??[])}return null}function engineProcessIn(rows,rootPid,extraLaunch){if(foregroundEngineIn(rows,rootPid))return!0;let expected=extraLaunch?executableNameFromArgv(typeof extraLaunch==="string"?[extraLaunch]:extraLaunch):null;if(!expected)return!1;let kids=childrenIndex(rows),queue=[...kids.get(rootPid)??[]];while(queue.length>0){let row=queue.shift();if(!row)break;if(executableNameFromArgv(row.args.trim().split(/\s+/))===expected)return!0;queue.push(...kids.get(row.pid)??[])}return!1}var PS_PROBE_TIMEOUT_MS=5000,bunPsSpawn=()=>{let proc=Bun.spawn(["ps","-A","-o","pid=,ppid=,args="],{stdout:"pipe",stderr:"ignore"});return{text:new Response(proc.stdout).text(),kill:()=>proc.kill()}};async function psSnapshotWith(spawn,timeoutMs=PS_PROBE_TIMEOUT_MS){let proc=spawn(),timer;try{let text=await Promise.race([proc.text,new Promise((_resolve,reject)=>{timer=setTimeout(()=>{try{proc.kill()}catch{}reject(new PsProbeUnavailableError(`ps did not answer within ${timeoutMs}ms`))},timeoutMs)})]);if(parsePsSnapshot(text).length===0)throw new PsProbeUnavailableError("ps returned no usable rows");return text}finally{if(timer)clearTimeout(timer)}}var psSnapshot=async(anchors)=>{if(process.platform!=="win32")return psSnapshotWith(bunPsSpawn);let{defaultWinProcessProbe,winProcessSnapshot}=await import("./chunk-qqxw72nh.js");return winProcessSnapshot(anchors??[],defaultWinProcessProbe())};async function foregroundEngine(rootPid,snapshot=psSnapshot){try{return foregroundEngineIn(parsePsSnapshot(await snapshot([rootPid])),rootPid)}catch{return null}}
|
|
4
4
|
export{vendorFromArgv,parsePsSnapshot,hasAncestor,foregroundEngineIn,engineProcessIn,PS_PROBE_TIMEOUT_MS,psSnapshotWith,psSnapshot,foregroundEngine};
|