@sma1lboy/rove 0.9.196 → 0.9.197

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/cli/{chunk-pn8n5337.js → chunk-151e0hdm.js} +1 -1
  2. package/dist/cli/{chunk-ckmjmata.js → chunk-1dd1h64w.js} +1 -1
  3. package/dist/cli/{chunk-6zwv7ght.js → chunk-1dvk8k4t.js} +1 -1
  4. package/dist/cli/{chunk-gzb71t55.js → chunk-467s029g.js} +1 -1
  5. package/dist/cli/{chunk-tfpw31v2.js → chunk-48mveswg.js} +1 -1
  6. package/dist/cli/{chunk-z6tm9svv.js → chunk-4n1yds3y.js} +1 -1
  7. package/dist/cli/{chunk-1mccpcrg.js → chunk-4tv9vgwp.js} +1 -1
  8. package/dist/cli/{chunk-hykh89d9.js → chunk-6amqr8vs.js} +1 -1
  9. package/dist/cli/{chunk-4c83htw2.js → chunk-6mqsm8t9.js} +1 -1
  10. package/dist/cli/{chunk-8rg38fq5.js → chunk-6t0rj7bf.js} +1 -1
  11. package/dist/cli/{chunk-24mfhdhv.js → chunk-6yfkm32y.js} +1 -1
  12. package/dist/cli/{chunk-mrm0p3jx.js → chunk-7atht8k1.js} +1 -1
  13. package/dist/cli/{chunk-e803hkkq.js → chunk-8htkv9kd.js} +1 -1
  14. package/dist/cli/{chunk-cswym6jd.js → chunk-91bc8n0h.js} +2 -2
  15. package/dist/cli/{chunk-xn986hn6.js → chunk-94jkey0h.js} +1 -1
  16. package/dist/cli/{chunk-jchxs2w6.js → chunk-ax0fk856.js} +1 -1
  17. package/dist/cli/{chunk-bqpbprb6.js → chunk-cvsqsf6p.js} +1 -1
  18. package/dist/cli/{chunk-fc8jtpq5.js → chunk-d7hr2jks.js} +1 -1
  19. package/dist/cli/{chunk-2pf63t41.js → chunk-dj161zdt.js} +1 -1
  20. package/dist/cli/{chunk-9zaz5by0.js → chunk-ercqyycv.js} +1 -1
  21. package/dist/cli/{chunk-xycn7fvg.js → chunk-f97hbn4b.js} +1 -1
  22. package/dist/cli/{chunk-r7rb2txn.js → chunk-fhds10kn.js} +1 -1
  23. package/dist/cli/{chunk-8yxbfm8p.js → chunk-fpqpmszm.js} +1 -1
  24. package/dist/cli/{chunk-qw707fq7.js → chunk-fxkamrb5.js} +1 -1
  25. package/dist/cli/{chunk-etf0vgry.js → chunk-g9j5ateg.js} +2 -2
  26. package/dist/cli/{chunk-fy7m06tc.js → chunk-gxazefj8.js} +1 -1
  27. package/dist/cli/{chunk-kpf012j2.js → chunk-jmqttxwj.js} +1 -1
  28. package/dist/cli/{chunk-6wv15xmv.js → chunk-jye42vh7.js} +1 -1
  29. package/dist/cli/{chunk-add3p95d.js → chunk-kdbsc4ap.js} +1 -1
  30. package/dist/cli/{chunk-58ke204z.js → chunk-kdr5qrga.js} +1 -1
  31. package/dist/cli/{chunk-sqnrd72g.js → chunk-mkt74d74.js} +1 -1
  32. package/dist/cli/{chunk-75m9rbr5.js → chunk-mn9mpc52.js} +2 -2
  33. package/dist/cli/{chunk-xbze970v.js → chunk-mz2ppnp5.js} +1 -1
  34. package/dist/cli/{chunk-ybwb5k90.js → chunk-n0510hra.js} +1 -1
  35. package/dist/cli/{chunk-dqemtamw.js → chunk-n2vvwxsh.js} +3 -3
  36. package/dist/cli/{chunk-ch1pvacq.js → chunk-nh7k3af8.js} +2 -2
  37. package/dist/cli/{chunk-vyhx5nqr.js → chunk-qj4wbfsn.js} +1 -1
  38. package/dist/cli/{chunk-crem8tnp.js → chunk-qrb102ms.js} +1 -1
  39. package/dist/cli/{chunk-3gv2khha.js → chunk-rrkkkc97.js} +1 -1
  40. package/dist/cli/{chunk-4er0sjve.js → chunk-ry2ztajh.js} +2 -2
  41. package/dist/cli/{chunk-6vf0dyza.js → chunk-sn1fvs9r.js} +2 -2
  42. package/dist/cli/{chunk-azhajh0p.js → chunk-wsecz7jj.js} +1 -1
  43. package/dist/cli/{chunk-jt3rv2yj.js → chunk-wypff3pn.js} +1 -1
  44. package/dist/cli/{chunk-z0x49jfv.js → chunk-ynssqhyz.js} +1 -1
  45. package/dist/cli/{chunk-1g1z82a1.js → chunk-ywgqcfk1.js} +1 -1
  46. package/dist/cli/index.js +3 -3
  47. package/dist/cli/kobe.js +1 -1
  48. package/dist/cli/rove.js +1 -1
  49. package/package.json +1 -1
@@ -1,8 +1,8 @@
1
1
  // @bun
2
- import{ensurePluginEnginesLoaded,registeredEngineIds}from"./chunk-c8xm2s8h.js";import{resolveActiveTaskId}from"./chunk-ac0yv0v4.js";import{DEFAULT_FEEDBACK_CATEGORY_SLUG,submitFeedback}from"./chunk-azhajh0p.js";import{ENGINE_ACTIVITY_KINDS}from"./chunk-3e5n28t6.js";import{deriveTitleFromPrompt}from"./chunk-xb9b93ts.js";import{DIRTY_WORKTREE_CODE,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,canonicalize}from"./chunk-ztwz2465.js";import{ulid}from"./chunk-qkehg2c1.js";import{ENGINE_NOT_OBSERVED_REASON,ENGINE_START_POLL_MS,ENGINE_START_PROBE_MS,closeTabsSnapshot,deliverHostedPrompt,deliverToKey,ensurePtyHost,findEngineKey,joinTaskTabs,killTaskSessions,listSessions,listSessionsOrNull,markCliTabSession,mintCliTab,openPtyHost,outcomeFields,publishCliTabSnapshot,readTabsSnapshot,renameTabsSnapshot,restoredTabLaunch,taskEngineArgv,taskKeys,unregisteredTabIds}from"./chunk-jt3rv2yj.js";import{tabPtyKeyFor}from"./chunk-8yxbfm8p.js";import{awaitEngineProcess,buildEngineSessionLaunch,enginePresence,findHostedEngineKey,hostedSessionFailureLine,isHostedTaskKey,listHostedSessions,openHostedSessionHost,readPersistedTerminalDefaultColors,sessionArgvNamesEngine,trustEngineWorktree}from"./chunk-cswym6jd.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{ApiError,VERB_GROUP_IDS,helpStep,splitDaemonCode}from"./chunk-f7zjggfv.js";import{terminalRows}from"./chunk-w25b7xxz.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{expandTilde}from"./chunk-fczqwtmq.js";import{GENERIC_PROTOCOL,describePreset,engineLaunchArgv,listEnginePresets,protocolEntry,resolveCommandProtocol,sessionProtocol,withPinnedSessionId}from"./chunk-jchxs2w6.js";import{kobeApiInvocation}from"./chunk-6zwv7ght.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-ckmjmata.js";import{engineEntry,getCapabilities,supportsStructuredHistory,vendorsWithTurnReader}from"./chunk-add3p95d.js";import{installedEngineIds}from"./chunk-kx3kydwv.js";import{CURRENT_VERSION}from"./chunk-24mfhdhv.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{isRemoteRepoKey}from"./chunk-9ydhv2zb.js";import{loadStateFile}from"./chunk-3jh78dmc.js";import{ALL_VENDORS,DEFAULT_VENDOR,coerceVendorId}from"./chunk-05jej26n.js";import{homeDir}from"./chunk-q5jhy3t8.js";import{pathWithin,samePath}from"./chunk-f10n6063.js";import{activeCliName}from"./chunk-00ehck55.js";import{__require}from"./chunk-wqfp8d9w.js";import{readFileSync}from"fs";import{resolve}from"path";var FANOUT_CAP=10;function parsePositiveInt(raw){if(!/^\d+$/.test(raw.trim()))return;let n=Number.parseInt(raw,10);return Number.isSafeInteger(n)&&n>0?n:void 0}function parseNonNegativeInt(raw){if(!/^\d+$/.test(raw.trim()))return;let n=Number.parseInt(raw,10);return Number.isSafeInteger(n)&&n>=0?n:void 0}function parseBoolLiteral(raw){if(["true","1","yes"].includes(raw))return!0;if(["false","0","no"].includes(raw))return!1;return}var FANOUT_STEP=helpStep("add"),F={repo:(required=!0)=>({name:"repo",type:"string",required,placeholder:"PATH",description:"Repo root (git toplevel). Relative paths resolve against $PWD."}),taskId:(required=!0)=>({name:"task-id",type:"string",required,placeholder:"ID",description:"Target task id (from `list` / `add`)."}),vendor:()=>({name:"vendor",type:"enum",values:ALL_VENDORS,placeholder:"V",description:"Engine vendor for the task."}),command:()=>({name:"command",type:"string",placeholder:"CMD",description:"Engine launch command, verbatim \u2014 an engine id from `engine-list` (e.g. claude) or a full command line (e.g. 'codex --search'). Unvalidated: probe an unfamiliar engine's flags with `<cmd> --help` first. Omitted = the repo's default engine."}),title:()=>({name:"title",type:"string",placeholder:"T",description:"Human task title."}),prompt:(required,desc)=>({name:"prompt",type:"string",required,placeholder:"TEXT",description:required?`${desc} Required unless --prompt-file is given.`:desc}),promptFile:()=>({name:"prompt-file",type:"string",placeholder:"PATH",description:"Read the prompt from this file instead of --prompt (`-` = stdin). Use it whenever the text has backticks, $vars, or quotes you don't want the shell to touch. Exactly one of --prompt / --prompt-file."})};function parseFlags(argv,booleanFlags=new Set){let flags=new Map,pretty=!1,help=!1;for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("--")&&arg!=="-h")throw new ApiError(`unexpected positional arg: ${arg}`,"BAD_FLAG");if(arg==="-h"){help=!0;continue}let eq=arg.indexOf("=");if(eq!==-1){let key2=arg.slice(2,eq),value=arg.slice(eq+1);if(key2==="pretty")pretty=value!=="false"&&value!=="0";else if(key2==="help")help=value!=="false"&&value!=="0";else flags.set(key2,value);continue}let key=arg.slice(2);if(key==="pretty"){pretty=!0;continue}if(key==="help"){help=!0;continue}if(booleanFlags.has(key)){let next2=argv[i+1];if(next2!==void 0&&parseBoolLiteral(next2)!==void 0)flags.set(key,next2),i+=1;else flags.set(key,"true");continue}let next=argv[i+1];if(next===void 0||next.startsWith("--"))throw new ApiError(`flag --${key} requires a value`,"BAD_FLAG");flags.set(key,next),i+=1}return{flags,pretty,help}}function validateAgainstSpec(verb,flags){let known=new Set(verb.flags.map((f)=>f.name));for(let key of flags.keys())if(!known.has(key))throw new ApiError(`unknown flag --${key} for "${verb.name}"`,"BAD_FLAG",helpStep(verb.name));for(let f of verb.flags){let satisfied=flags.get(f.name)||f.name==="prompt"&&flags.get("prompt-file");if(f.required&&!satisfied)throw new ApiError(`--${f.name} is required for "${verb.name}"`,"MISSING_FLAG",helpStep(verb.name));if(f.type==="enum"&&f.values){let raw=flags.get(f.name);if(raw!==void 0&&!f.values.includes(raw)){if(f.name==="vendor"&&registeredEngineIds().includes(raw))continue;throw new ApiError(`--${f.name} must be one of ${f.values.join(", ")}`,"BAD_FLAG",helpStep(verb.name))}}if(f.type==="int"){let raw=flags.get(f.name);if(raw!==void 0&&parsePositiveInt(raw)===void 0)throw new ApiError(`--${f.name} must be a positive integer`,"BAD_FLAG")}if(f.type==="uint"){let raw=flags.get(f.name);if(raw!==void 0&&parseNonNegativeInt(raw)===void 0)throw new ApiError(`--${f.name} must be a non-negative integer`,"BAD_FLAG")}}}class VerbArgs{verb;flags;constructor(verb,flags){this.verb=verb;this.flags=flags}spec(name){let f=this.verb.flags.find((s)=>s.name===name);if(!f)throw Error(`internal: --${name} is not declared on verb "${this.verb.name}"`);return f}str(name){this.spec(name);let v=this.flags.get(name);return v&&v.length>0?v:void 0}present(name){return this.spec(name),this.flags.get(name)!==void 0}promptText(){if(this.promptMemo!==void 0)return this.promptMemo.value;let value=this.readPromptText();return this.promptMemo={value},value}promptMemo;readPromptText(){let inline=this.str("prompt"),file=this.str("prompt-file");if(inline!==void 0&&file!==void 0)throw new ApiError("pass --prompt or --prompt-file, not both","BAD_FLAG",helpStep(this.verb.name));if(file===void 0)return inline;let text=readFileSync(file==="-"?0:resolve(process.cwd(),expandTilde(file)),"utf8");if(text.trim().length===0)throw new ApiError(`--prompt-file ${file} is empty`,"BAD_FLAG");return text}require(name){let v=this.str(name);if(v===void 0)throw new ApiError(`--${name} is required`,"MISSING_FLAG");return v}enumOf(name){let f=this.spec(name),v=this.str(name);if(v===void 0)return;if(f.values&&!f.values.includes(v))throw new ApiError(`--${name} must be one of ${f.values.join(", ")}`,"BAD_FLAG",helpStep(this.verb.name));return v}requireEnum(name){return this.require(name),this.enumOf(name)}vendor(){let value=this.str("vendor");if(value===void 0)return;let builtins=this.spec("vendor").values??ALL_VENDORS;if(builtins.includes(value))return value;if(registeredEngineIds().includes(value))return value;throw new ApiError(`--vendor must be a built-in (${builtins.join(", ")}) or a registered engine id \u2014 see \`engine-list\``,"BAD_FLAG",helpStep(this.verb.name))}bool(name){this.spec(name);let raw=this.str(name);if(raw===void 0)return;let value=parseBoolLiteral(raw);if(value===void 0)throw new ApiError(`--${name} must be a boolean (true/false)`,"BAD_FLAG");return value}int(name){this.spec(name);let raw=this.str(name);if(raw===void 0)return;let n=parsePositiveInt(raw);if(n===void 0)throw new ApiError(`--${name} must be a positive integer`,"BAD_FLAG");return n}nonNegativeInt(name){this.spec(name);let raw=this.str(name);if(raw===void 0)return;let n=parseNonNegativeInt(raw);if(n===void 0)throw new ApiError(`--${name} must be a non-negative integer`,"BAD_FLAG");return n}path(name){let v=this.str(name);return v===void 0?void 0:resolve(process.cwd(),expandTilde(v))}requirePath(name){return resolve(process.cwd(),expandTilde(this.require(name)))}requireRepo(name){let raw=this.require(name);return isRemoteRepoKey(raw)?raw:resolve(process.cwd(),expandTilde(raw))}}function parseAgentsSpec(spec){let out=[];for(let part of spec.split(",")){let trimmed=part.trim();if(!trimmed)continue;let colon=trimmed.indexOf(":");if(colon===-1)throw new ApiError(`--agents entry "${trimmed}" must be engine:count`,"BAD_FLAG",FANOUT_STEP);let vendor=trimmed.slice(0,colon);if(!ALL_VENDORS.includes(vendor)&&!registeredEngineIds().includes(vendor))throw new ApiError(`--agents engine "${vendor}" must be a built-in (${ALL_VENDORS.join(", ")}) or a registered engine id \u2014 see \`engine-list\``,"BAD_FLAG",FANOUT_STEP);let count=parsePositiveInt(trimmed.slice(colon+1));if(count===void 0)throw new ApiError(`--agents count for "${vendor}" must be a positive integer`,"BAD_FLAG",FANOUT_STEP);if(out.length+count>FANOUT_CAP)throw new ApiError(`--agents requests ${out.length+count} agents, exceeds the cap of ${FANOUT_CAP}`,"BAD_FLAG",FANOUT_STEP);for(let i=0;i<count;i++)out.push(vendor)}if(out.length===0)throw new ApiError('--agents specified no agents (e.g. "claude:2,codex:1")',"BAD_FLAG",FANOUT_STEP);return out}function buildCountPlan(count,vendor){if(count>FANOUT_CAP)throw new ApiError(`--count ${count} exceeds the parallel cap of ${FANOUT_CAP} \u2014 spawn in batches`,"BAD_FLAG",FANOUT_STEP);return Array(count).fill(vendor)}function daemonOf(ctx){if(!ctx.client)throw new ApiError("daemon required","BAD_DAEMON");return ctx.client}async function repoFilter(runtime,repoFlag,repos){let target=await runtime.resolveRepoRoot(repoFlag);if(!await runtime.isUsableRepo(target))throw new ApiError(`--repo ${repoFlag} is not a readable git repository (resolved to ${target}) \u2014 the project may have moved or been deleted; \`rove api list\` still shows its tasks`,"REPO_UNRESOLVABLE");let resolved=new Map,unresolvable=new Set;for(let repo of new Set(repos)){let root=await runtime.resolveRepoRoot(repo);if(resolved.set(repo,root),!samePath(root,target)&&!await runtime.isUsableRepo(root))unresolvable.add(repo)}return{target,matches:(repo)=>samePath(resolved.get(repo),target),unresolvableRepos:[...unresolvable].sort()}}async function simpleRpc(ctx,name,payload){return daemonOf(ctx).request(name,payload)}async function handlePtyList(){let[{KobeDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-ydhngxy3.js"),import("./chunk-r1mp0eb2.js")]),client=new KobeDaemonClient(defaultPtyHostSocketPath());try{return await client.connect(),await client.request("pty.list",{})}catch{return{sessions:null}}finally{client.close()}}async function listAllEnginePresets(){ensurePluginEnginesLoaded();let presets=[...listEnginePresets()],seen=new Set(presets.map((p)=>p.id));for(let id of await installedEngineIds())if(!seen.has(id))presets.push(describePreset(id));return presets}var ENGINE_LIST_VERB={name:"engine-list",group:"discover",summary:"List every engine Rove can launch \u2014 built-ins, registered presets, the shipped contrib engines whose CLI is on PATH (gemini, opencode, cursor, grok, droid, amp), and engines contributed by enabled plugins \u2014 each with its RAW launch command, exactly as it runs. Copy one into `add --command` / `send --tab new --command` verbatim, or edit its flags first. `protocol` is the adapter Rove speaks to it (history, trust, delivery); `generic` = none, which still runs fine but loses transcript reads. Returns { engines }.",flags:[],offline:!0,handler:async()=>({engines:await listAllEnginePresets()})};async function setCommand(ctx){let command=ctx.args.require("command"),vendor=resolveCommandProtocol(command);return await simpleRpc(ctx,"task.setCommand",{taskId:ctx.args.require("task-id"),command,vendor}),{ok:!0,command,protocol:vendor,...vendor===GENERIC_PROTOCOL?{generic:!0}:{}}}var SET_COMMAND_VERB={name:"set-command",group:"edit",summary:"Set a task's engine launch command (takes effect on the next session rebuild). The protocol Rove speaks to it is derived from the command \u2014 the result reports which one, `generic` when the command names no engine Rove knows.",flags:[F.taskId(),{...F.command(),required:!0}],handler:setCommand};function taskEngine(task){let command=task.command?.trim();if(command){let resolved=resolveCommandProtocol(command);if(resolved!==GENERIC_PROTOCOL)return resolved}return sessionProtocol(coerceVendorId(task.vendor))}function assertEngineAcceptsEffort(engine,level,recover){let levels=engineEntry(engine).effortLevels??[];if(levels.length===0)throw new ApiError(`engine ${engine} declares no reasoning effort levels`,"BAD_EFFORT",{engine,hint:"Only engines with declared levels accept one (codex today). Check the task's engine with `get-task`.",nextCommandArgs:[...recover]});if(!levels.includes(level))throw new ApiError(`engine ${engine} does not accept effort level ${JSON.stringify(level)} \u2014 it declares ${levels.join(", ")}`,"BAD_EFFORT",{engine,levels,hint:`Pass one of: ${levels.join(", ")}.`,nextCommandArgs:[...recover]})}async function setEffort(ctx){let taskId=ctx.args.require("task-id"),level=ctx.args.require("level").trim(),daemon=daemonOf(ctx),{task}=await daemon.request("task.get",{taskId}),engine=taskEngine(task);assertEngineAcceptsEffort(engine,level,["api","get-task","--task-id",taskId]);let recorded=coerceVendorId(task.vendor),vendor=sessionProtocol(recorded)===engine?recorded:engine;return await simpleRpc(ctx,"task.setVendor",{taskId,vendor,effort:level}),{ok:!0,taskId,engine,effort:level}}var SET_EFFORT_VERB={name:"set-effort",group:"edit",summary:"Set a task's reasoning effort level (takes effect on the next session rebuild). Rejected when the task's engine declares no levels, or does not declare THIS one \u2014 the error names the levels it does accept. Codex accepts none/low/medium/high/xhigh/max; claude has none.",flags:[F.taskId(),{name:"level",type:"string",required:!0,placeholder:"LEVEL",description:"Effort level the task's engine declares (codex: none, low, medium, high, xhigh, max)."}],handler:setEffort};var API_SCHEMA_VERSION=2,GLOBAL_FLAGS=[{name:"pretty",type:"bool",description:"Pretty-print stdout JSON."},{name:"help",type:"bool",description:"Show usage for the verb and exit."}];function displayValues(f){if(!f.values)return;if(f.name!=="vendor")return f.values;let registered=registeredEngineIds().filter((id)=>!f.values.includes(id));return registered.length>0?[...f.values,...registered]:f.values}function flagJson(f){let values=displayValues(f);return{name:f.name,type:f.type,required:f.required??!1,...values?{values}:{},...f.default!==void 0?{default:f.default}:{},...f.placeholder?{placeholder:f.placeholder}:{},description:f.description}}function verbSchema(v){return{name:v.name,group:v.group,summary:v.summary,offline:v.offline??!1,flags:v.flags.map(flagJson)}}function schemaIndex(){let cliName=activeCliName();return{apiVersion:API_SCHEMA_VERSION,kobeVersion:CURRENT_VERSION,hint:`Compact index. Drill into ONE verb: \`${cliName} api schema --verb <name>\` (or \`${cliName} api <verb> --help\`). One group: \`--group <g>\`. Whole spec: \`--all\`.`,groups:VERB_GROUPS,verbs:VERBS.map((v)=>({name:v.name,group:v.group,summary:v.summary})),globalFlags:GLOBAL_FLAGS,aliases:VERB_ALIASES}}function groupSchema(group){let verbs=VERBS.filter((v)=>v.group===group);if(verbs.length===0)throw new ApiError(`unknown group: ${group}. Groups: ${Object.keys(VERB_GROUPS).join(", ")}`,"BAD_VERB",{hint:"that group does not exist \u2014 the compact index lists every group and the verbs in it",nextCommandArgs:["api","schema"]});return{group,verbs:verbs.map((v)=>({name:v.name,summary:v.summary}))}}function fullSchema(){return{apiVersion:API_SCHEMA_VERSION,kobeVersion:CURRENT_VERSION,output:{success:"one JSON object on stdout, newline-terminated, exit 0",error:'{"error":{"message","code"}} on stderr, exit != 0',pretty:"--pretty indents stdout JSON"},globalFlags:GLOBAL_FLAGS,aliases:VERB_ALIASES,groups:VERB_GROUPS,verbs:VERBS.map(verbSchema)}}function flagSignature(verb){return verb.flags.map((f)=>{let meta=f.type==="enum"&&f.values?displayValues(f).join("|"):f.placeholder??(f.type==="bool"?"":"X"),core=meta?`--${f.name} ${meta}`:`--${f.name}`;return f.required?core:`[${core}]`}).join(" ")}function verbHelp(verb){let lines=[`${activeCliName()} api ${verb.name} ${flagSignature(verb)}`.trimEnd(),"",verb.summary,""],alias=Object.entries(VERB_ALIASES).find(([,canon])=>canon===verb.name)?.[0];if(alias)lines.push(`Alias: ${alias}`,"");if(verb.flags.length>0){lines.push("Flags:");for(let f of verb.flags){let req=f.required?" (required)":"",def=f.default!==void 0?` [default: ${f.default}]`:"",vals=f.type==="enum"&&f.values?` {${displayValues(f).join("|")}}`:"";lines.push(` --${f.name}${vals}${req}${def} ${f.description}`)}lines.push("")}return lines.push("Global: [--pretty] [--help]"),lines.join(`
2
+ import{ensurePluginEnginesLoaded,registeredEngineIds}from"./chunk-c8xm2s8h.js";import{resolveActiveTaskId}from"./chunk-ac0yv0v4.js";import{DEFAULT_FEEDBACK_CATEGORY_SLUG,submitFeedback}from"./chunk-wsecz7jj.js";import{ENGINE_ACTIVITY_KINDS}from"./chunk-3e5n28t6.js";import{deriveTitleFromPrompt}from"./chunk-xb9b93ts.js";import{DIRTY_WORKTREE_CODE,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,canonicalize}from"./chunk-ztwz2465.js";import{ulid}from"./chunk-qkehg2c1.js";import{ENGINE_NOT_OBSERVED_REASON,ENGINE_START_POLL_MS,ENGINE_START_PROBE_MS,closeTabsSnapshot,deliverHostedPrompt,deliverToKey,ensurePtyHost,findEngineKey,joinTaskTabs,killTaskSessions,listSessions,listSessionsOrNull,markCliTabSession,mintCliTab,openPtyHost,outcomeFields,publishCliTabSnapshot,readTabsSnapshot,renameTabsSnapshot,restoredTabLaunch,taskEngineArgv,taskKeys,unregisteredTabIds}from"./chunk-wypff3pn.js";import{tabPtyKeyFor}from"./chunk-fpqpmszm.js";import{awaitEngineProcess,buildEngineSessionLaunch,enginePresence,findHostedEngineKey,hostedSessionFailureLine,isHostedTaskKey,listHostedSessions,openHostedSessionHost,readPersistedTerminalDefaultColors,sessionArgvNamesEngine,trustEngineWorktree}from"./chunk-91bc8n0h.js";import{resolveLoginShell}from"./chunk-b99tf0jr.js";import{ApiError,VERB_GROUP_IDS,helpStep,splitDaemonCode}from"./chunk-f7zjggfv.js";import{terminalRows}from"./chunk-w25b7xxz.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{expandTilde}from"./chunk-fczqwtmq.js";import{GENERIC_PROTOCOL,describePreset,engineLaunchArgv,listEnginePresets,protocolEntry,resolveCommandProtocol,sessionProtocol,withPinnedSessionId}from"./chunk-ax0fk856.js";import{kobeApiInvocation}from"./chunk-1dvk8k4t.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-1dd1h64w.js";import{engineEntry,getCapabilities,supportsStructuredHistory,vendorsWithTurnReader}from"./chunk-kdbsc4ap.js";import{installedEngineIds}from"./chunk-kx3kydwv.js";import{CURRENT_VERSION}from"./chunk-6yfkm32y.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{isRemoteRepoKey}from"./chunk-9ydhv2zb.js";import{loadStateFile}from"./chunk-3jh78dmc.js";import{ALL_VENDORS,DEFAULT_VENDOR,coerceVendorId}from"./chunk-05jej26n.js";import{homeDir}from"./chunk-q5jhy3t8.js";import{pathWithin,samePath}from"./chunk-f10n6063.js";import{activeCliName}from"./chunk-00ehck55.js";import{__require}from"./chunk-wqfp8d9w.js";import{readFileSync}from"fs";import{resolve}from"path";var FANOUT_CAP=10;function parsePositiveInt(raw){if(!/^\d+$/.test(raw.trim()))return;let n=Number.parseInt(raw,10);return Number.isSafeInteger(n)&&n>0?n:void 0}function parseNonNegativeInt(raw){if(!/^\d+$/.test(raw.trim()))return;let n=Number.parseInt(raw,10);return Number.isSafeInteger(n)&&n>=0?n:void 0}function parseBoolLiteral(raw){if(["true","1","yes"].includes(raw))return!0;if(["false","0","no"].includes(raw))return!1;return}var FANOUT_STEP=helpStep("add"),F={repo:(required=!0)=>({name:"repo",type:"string",required,placeholder:"PATH",description:"Repo root (git toplevel). Relative paths resolve against $PWD."}),taskId:(required=!0)=>({name:"task-id",type:"string",required,placeholder:"ID",description:"Target task id (from `list` / `add`)."}),vendor:()=>({name:"vendor",type:"enum",values:ALL_VENDORS,placeholder:"V",description:"Engine vendor for the task."}),command:()=>({name:"command",type:"string",placeholder:"CMD",description:"Engine launch command, verbatim \u2014 an engine id from `engine-list` (e.g. claude) or a full command line (e.g. 'codex --search'). Unvalidated: probe an unfamiliar engine's flags with `<cmd> --help` first. Omitted = the repo's default engine."}),title:()=>({name:"title",type:"string",placeholder:"T",description:"Human task title."}),prompt:(required,desc)=>({name:"prompt",type:"string",required,placeholder:"TEXT",description:required?`${desc} Required unless --prompt-file is given.`:desc}),promptFile:()=>({name:"prompt-file",type:"string",placeholder:"PATH",description:"Read the prompt from this file instead of --prompt (`-` = stdin). Use it whenever the text has backticks, $vars, or quotes you don't want the shell to touch. Exactly one of --prompt / --prompt-file."})};function parseFlags(argv,booleanFlags=new Set){let flags=new Map,pretty=!1,help=!1;for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("--")&&arg!=="-h")throw new ApiError(`unexpected positional arg: ${arg}`,"BAD_FLAG");if(arg==="-h"){help=!0;continue}let eq=arg.indexOf("=");if(eq!==-1){let key2=arg.slice(2,eq),value=arg.slice(eq+1);if(key2==="pretty")pretty=value!=="false"&&value!=="0";else if(key2==="help")help=value!=="false"&&value!=="0";else flags.set(key2,value);continue}let key=arg.slice(2);if(key==="pretty"){pretty=!0;continue}if(key==="help"){help=!0;continue}if(booleanFlags.has(key)){let next2=argv[i+1];if(next2!==void 0&&parseBoolLiteral(next2)!==void 0)flags.set(key,next2),i+=1;else flags.set(key,"true");continue}let next=argv[i+1];if(next===void 0||next.startsWith("--"))throw new ApiError(`flag --${key} requires a value`,"BAD_FLAG");flags.set(key,next),i+=1}return{flags,pretty,help}}function validateAgainstSpec(verb,flags){let known=new Set(verb.flags.map((f)=>f.name));for(let key of flags.keys())if(!known.has(key))throw new ApiError(`unknown flag --${key} for "${verb.name}"`,"BAD_FLAG",helpStep(verb.name));for(let f of verb.flags){let satisfied=flags.get(f.name)||f.name==="prompt"&&flags.get("prompt-file");if(f.required&&!satisfied)throw new ApiError(`--${f.name} is required for "${verb.name}"`,"MISSING_FLAG",helpStep(verb.name));if(f.type==="enum"&&f.values){let raw=flags.get(f.name);if(raw!==void 0&&!f.values.includes(raw)){if(f.name==="vendor"&&registeredEngineIds().includes(raw))continue;throw new ApiError(`--${f.name} must be one of ${f.values.join(", ")}`,"BAD_FLAG",helpStep(verb.name))}}if(f.type==="int"){let raw=flags.get(f.name);if(raw!==void 0&&parsePositiveInt(raw)===void 0)throw new ApiError(`--${f.name} must be a positive integer`,"BAD_FLAG")}if(f.type==="uint"){let raw=flags.get(f.name);if(raw!==void 0&&parseNonNegativeInt(raw)===void 0)throw new ApiError(`--${f.name} must be a non-negative integer`,"BAD_FLAG")}}}class VerbArgs{verb;flags;constructor(verb,flags){this.verb=verb;this.flags=flags}spec(name){let f=this.verb.flags.find((s)=>s.name===name);if(!f)throw Error(`internal: --${name} is not declared on verb "${this.verb.name}"`);return f}str(name){this.spec(name);let v=this.flags.get(name);return v&&v.length>0?v:void 0}present(name){return this.spec(name),this.flags.get(name)!==void 0}promptText(){if(this.promptMemo!==void 0)return this.promptMemo.value;let value=this.readPromptText();return this.promptMemo={value},value}promptMemo;readPromptText(){let inline=this.str("prompt"),file=this.str("prompt-file");if(inline!==void 0&&file!==void 0)throw new ApiError("pass --prompt or --prompt-file, not both","BAD_FLAG",helpStep(this.verb.name));if(file===void 0)return inline;let text=readFileSync(file==="-"?0:resolve(process.cwd(),expandTilde(file)),"utf8");if(text.trim().length===0)throw new ApiError(`--prompt-file ${file} is empty`,"BAD_FLAG");return text}require(name){let v=this.str(name);if(v===void 0)throw new ApiError(`--${name} is required`,"MISSING_FLAG");return v}enumOf(name){let f=this.spec(name),v=this.str(name);if(v===void 0)return;if(f.values&&!f.values.includes(v))throw new ApiError(`--${name} must be one of ${f.values.join(", ")}`,"BAD_FLAG",helpStep(this.verb.name));return v}requireEnum(name){return this.require(name),this.enumOf(name)}vendor(){let value=this.str("vendor");if(value===void 0)return;let builtins=this.spec("vendor").values??ALL_VENDORS;if(builtins.includes(value))return value;if(registeredEngineIds().includes(value))return value;throw new ApiError(`--vendor must be a built-in (${builtins.join(", ")}) or a registered engine id \u2014 see \`engine-list\``,"BAD_FLAG",helpStep(this.verb.name))}bool(name){this.spec(name);let raw=this.str(name);if(raw===void 0)return;let value=parseBoolLiteral(raw);if(value===void 0)throw new ApiError(`--${name} must be a boolean (true/false)`,"BAD_FLAG");return value}int(name){this.spec(name);let raw=this.str(name);if(raw===void 0)return;let n=parsePositiveInt(raw);if(n===void 0)throw new ApiError(`--${name} must be a positive integer`,"BAD_FLAG");return n}nonNegativeInt(name){this.spec(name);let raw=this.str(name);if(raw===void 0)return;let n=parseNonNegativeInt(raw);if(n===void 0)throw new ApiError(`--${name} must be a non-negative integer`,"BAD_FLAG");return n}path(name){let v=this.str(name);return v===void 0?void 0:resolve(process.cwd(),expandTilde(v))}requirePath(name){return resolve(process.cwd(),expandTilde(this.require(name)))}requireRepo(name){let raw=this.require(name);return isRemoteRepoKey(raw)?raw:resolve(process.cwd(),expandTilde(raw))}}function parseAgentsSpec(spec){let out=[];for(let part of spec.split(",")){let trimmed=part.trim();if(!trimmed)continue;let colon=trimmed.indexOf(":");if(colon===-1)throw new ApiError(`--agents entry "${trimmed}" must be engine:count`,"BAD_FLAG",FANOUT_STEP);let vendor=trimmed.slice(0,colon);if(!ALL_VENDORS.includes(vendor)&&!registeredEngineIds().includes(vendor))throw new ApiError(`--agents engine "${vendor}" must be a built-in (${ALL_VENDORS.join(", ")}) or a registered engine id \u2014 see \`engine-list\``,"BAD_FLAG",FANOUT_STEP);let count=parsePositiveInt(trimmed.slice(colon+1));if(count===void 0)throw new ApiError(`--agents count for "${vendor}" must be a positive integer`,"BAD_FLAG",FANOUT_STEP);if(out.length+count>FANOUT_CAP)throw new ApiError(`--agents requests ${out.length+count} agents, exceeds the cap of ${FANOUT_CAP}`,"BAD_FLAG",FANOUT_STEP);for(let i=0;i<count;i++)out.push(vendor)}if(out.length===0)throw new ApiError('--agents specified no agents (e.g. "claude:2,codex:1")',"BAD_FLAG",FANOUT_STEP);return out}function buildCountPlan(count,vendor){if(count>FANOUT_CAP)throw new ApiError(`--count ${count} exceeds the parallel cap of ${FANOUT_CAP} \u2014 spawn in batches`,"BAD_FLAG",FANOUT_STEP);return Array(count).fill(vendor)}function daemonOf(ctx){if(!ctx.client)throw new ApiError("daemon required","BAD_DAEMON");return ctx.client}async function repoFilter(runtime,repoFlag,repos){let target=await runtime.resolveRepoRoot(repoFlag);if(!await runtime.isUsableRepo(target))throw new ApiError(`--repo ${repoFlag} is not a readable git repository (resolved to ${target}) \u2014 the project may have moved or been deleted; \`rove api list\` still shows its tasks`,"REPO_UNRESOLVABLE");let resolved=new Map,unresolvable=new Set;for(let repo of new Set(repos)){let root=await runtime.resolveRepoRoot(repo);if(resolved.set(repo,root),!samePath(root,target)&&!await runtime.isUsableRepo(root))unresolvable.add(repo)}return{target,matches:(repo)=>samePath(resolved.get(repo),target),unresolvableRepos:[...unresolvable].sort()}}async function simpleRpc(ctx,name,payload){return daemonOf(ctx).request(name,payload)}async function handlePtyList(){let[{KobeDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-ydhngxy3.js"),import("./chunk-r1mp0eb2.js")]),client=new KobeDaemonClient(defaultPtyHostSocketPath());try{return await client.connect(),await client.request("pty.list",{})}catch{return{sessions:null}}finally{client.close()}}async function listAllEnginePresets(){ensurePluginEnginesLoaded();let presets=[...listEnginePresets()],seen=new Set(presets.map((p)=>p.id));for(let id of await installedEngineIds())if(!seen.has(id))presets.push(describePreset(id));return presets}var ENGINE_LIST_VERB={name:"engine-list",group:"discover",summary:"List every engine Rove can launch \u2014 built-ins, registered presets, the shipped contrib engines whose CLI is on PATH (gemini, opencode, cursor, grok, droid, amp), and engines contributed by enabled plugins \u2014 each with its RAW launch command, exactly as it runs. Copy one into `add --command` / `send --tab new --command` verbatim, or edit its flags first. `protocol` is the adapter Rove speaks to it (history, trust, delivery); `generic` = none, which still runs fine but loses transcript reads. Returns { engines }.",flags:[],offline:!0,handler:async()=>({engines:await listAllEnginePresets()})};async function setCommand(ctx){let command=ctx.args.require("command"),vendor=resolveCommandProtocol(command);return await simpleRpc(ctx,"task.setCommand",{taskId:ctx.args.require("task-id"),command,vendor}),{ok:!0,command,protocol:vendor,...vendor===GENERIC_PROTOCOL?{generic:!0}:{}}}var SET_COMMAND_VERB={name:"set-command",group:"edit",summary:"Set a task's engine launch command (takes effect on the next session rebuild). The protocol Rove speaks to it is derived from the command \u2014 the result reports which one, `generic` when the command names no engine Rove knows.",flags:[F.taskId(),{...F.command(),required:!0}],handler:setCommand};function taskEngine(task){let command=task.command?.trim();if(command){let resolved=resolveCommandProtocol(command);if(resolved!==GENERIC_PROTOCOL)return resolved}return sessionProtocol(coerceVendorId(task.vendor))}function assertEngineAcceptsEffort(engine,level,recover){let levels=engineEntry(engine).effortLevels??[];if(levels.length===0)throw new ApiError(`engine ${engine} declares no reasoning effort levels`,"BAD_EFFORT",{engine,hint:"Only engines with declared levels accept one (codex today). Check the task's engine with `get-task`.",nextCommandArgs:[...recover]});if(!levels.includes(level))throw new ApiError(`engine ${engine} does not accept effort level ${JSON.stringify(level)} \u2014 it declares ${levels.join(", ")}`,"BAD_EFFORT",{engine,levels,hint:`Pass one of: ${levels.join(", ")}.`,nextCommandArgs:[...recover]})}async function setEffort(ctx){let taskId=ctx.args.require("task-id"),level=ctx.args.require("level").trim(),daemon=daemonOf(ctx),{task}=await daemon.request("task.get",{taskId}),engine=taskEngine(task);assertEngineAcceptsEffort(engine,level,["api","get-task","--task-id",taskId]);let recorded=coerceVendorId(task.vendor),vendor=sessionProtocol(recorded)===engine?recorded:engine;return await simpleRpc(ctx,"task.setVendor",{taskId,vendor,effort:level}),{ok:!0,taskId,engine,effort:level}}var SET_EFFORT_VERB={name:"set-effort",group:"edit",summary:"Set a task's reasoning effort level (takes effect on the next session rebuild). Rejected when the task's engine declares no levels, or does not declare THIS one \u2014 the error names the levels it does accept. Codex accepts none/low/medium/high/xhigh/max; claude has none.",flags:[F.taskId(),{name:"level",type:"string",required:!0,placeholder:"LEVEL",description:"Effort level the task's engine declares (codex: none, low, medium, high, xhigh, max)."}],handler:setEffort};var API_SCHEMA_VERSION=2,GLOBAL_FLAGS=[{name:"pretty",type:"bool",description:"Pretty-print stdout JSON."},{name:"help",type:"bool",description:"Show usage for the verb and exit."}];function displayValues(f){if(!f.values)return;if(f.name!=="vendor")return f.values;let registered=registeredEngineIds().filter((id)=>!f.values.includes(id));return registered.length>0?[...f.values,...registered]:f.values}function flagJson(f){let values=displayValues(f);return{name:f.name,type:f.type,required:f.required??!1,...values?{values}:{},...f.default!==void 0?{default:f.default}:{},...f.placeholder?{placeholder:f.placeholder}:{},description:f.description}}function verbSchema(v){return{name:v.name,group:v.group,summary:v.summary,offline:v.offline??!1,flags:v.flags.map(flagJson)}}function schemaIndex(){let cliName=activeCliName();return{apiVersion:API_SCHEMA_VERSION,kobeVersion:CURRENT_VERSION,hint:`Compact index. Drill into ONE verb: \`${cliName} api schema --verb <name>\` (or \`${cliName} api <verb> --help\`). One group: \`--group <g>\`. Whole spec: \`--all\`.`,groups:VERB_GROUPS,verbs:VERBS.map((v)=>({name:v.name,group:v.group,summary:v.summary})),globalFlags:GLOBAL_FLAGS,aliases:VERB_ALIASES}}function groupSchema(group){let verbs=VERBS.filter((v)=>v.group===group);if(verbs.length===0)throw new ApiError(`unknown group: ${group}. Groups: ${Object.keys(VERB_GROUPS).join(", ")}`,"BAD_VERB",{hint:"that group does not exist \u2014 the compact index lists every group and the verbs in it",nextCommandArgs:["api","schema"]});return{group,verbs:verbs.map((v)=>({name:v.name,summary:v.summary}))}}function fullSchema(){return{apiVersion:API_SCHEMA_VERSION,kobeVersion:CURRENT_VERSION,output:{success:"one JSON object on stdout, newline-terminated, exit 0",error:'{"error":{"message","code"}} on stderr, exit != 0',pretty:"--pretty indents stdout JSON"},globalFlags:GLOBAL_FLAGS,aliases:VERB_ALIASES,groups:VERB_GROUPS,verbs:VERBS.map(verbSchema)}}function flagSignature(verb){return verb.flags.map((f)=>{let meta=f.type==="enum"&&f.values?displayValues(f).join("|"):f.placeholder??(f.type==="bool"?"":"X"),core=meta?`--${f.name} ${meta}`:`--${f.name}`;return f.required?core:`[${core}]`}).join(" ")}function verbHelp(verb){let lines=[`${activeCliName()} api ${verb.name} ${flagSignature(verb)}`.trimEnd(),"",verb.summary,""],alias=Object.entries(VERB_ALIASES).find(([,canon])=>canon===verb.name)?.[0];if(alias)lines.push(`Alias: ${alias}`,"");if(verb.flags.length>0){lines.push("Flags:");for(let f of verb.flags){let req=f.required?" (required)":"",def=f.default!==void 0?` [default: ${f.default}]`:"",vals=f.type==="enum"&&f.values?` {${displayValues(f).join("|")}}`:"";lines.push(` --${f.name}${vals}${req}${def} ${f.description}`)}lines.push("")}return lines.push("Global: [--pretty] [--help]"),lines.join(`
3
3
  `)}function apiUsage(){let cliName=activeCliName(),rows=VERBS.map((v)=>` ${v.name.padEnd(18)} ${v.summary}`);return[`usage: ${cliName} api <verb> [flags] [--pretty] [--help]`,"",`Explore the full surface (names, flags, types) with: ${cliName} api schema`,"","verbs:",...rows,"","Output is one JSON object on stdout (exit 0); errors are JSON on stderr (exit != 0)."].join(`
4
- `)}var selfSessionOnce,identityWarning=null;async function realProbe(){let[{openPtyHost:openPtyHost2,listSessions:listSessions2},{psSnapshot:psSnapshot2}]=await Promise.all([import("./chunk-4c83htw2.js"),import("./chunk-e803hkkq.js")]);return{sessions:async()=>{let host=await openPtyHost2();if(!host)return[];try{return await listSessions2(host.rpc)}finally{host.close()}},ps:psSnapshot2,pid:process.pid}}async function verifiedSelfSession(env=process.env,probe){if(!probe&&selfSessionOnce)return selfSessionOnce;let run=resolveSelfSession(env,probe);return selfSessionOnce=run,run}async function resolveSelfSession(env,probe){let taskId=env.KOBE_TASK_ID;if(!taskId)return null;let tabId=env.KOBE_TAB_ID||"tab-1";try{let p=probe??await realProbe(),key=`${taskId}::${tabId}`,session=(await p.sessions()).find((s)=>s.key===key&&s.alive);if(session?.pid){let{hasAncestor,parsePsSnapshot:parsePsSnapshot2}=await import("./chunk-e803hkkq.js");if(hasAncestor(parsePsSnapshot2(await p.ps([session.pid,p.pid])),p.pid,session.pid))return identityWarning=null,{taskId,tabId}}}catch{}return identityWarning=`$ROVE_TASK_ID/$KOBE_TASK_ID names task ${taskId} ${tabId}, but this process is not running inside that tab (an inherited env, not an identity) \u2014 dispatcher/peer provenance omitted`,null}function takeIdentityWarning(){let warning=identityWarning;return identityWarning=null,warning}async function dispatcherEnvPayload(env=process.env,probe){let self=await verifiedSelfSession(env,probe);if(!self)return{};return{dispatcherTaskId:self.taskId,dispatcherTabId:self.tabId}}async function readOwnDispatcher(daemon){let self=await verifiedSelfSession();if(!self)return null;try{return(await daemon.request("task.get",{taskId:self.taskId})).task.dispatcher??null}catch{return null}}async function resolveDispatcherTab(runtime,dispatcher){let{tabs,running}=await runtime.taskTabs(dispatcher.taskId);if(tabs.some((t)=>t.id===dispatcher.tabId&&t.alive))return dispatcher.tabId;if(running)return;throw new ApiError(`dispatcher tab ${dispatcher.tabId} on task ${dispatcher.taskId} is dead and the task has no live engine tab \u2014 the reply has nowhere to land`,"DISPATCHER_UNREACHABLE",{dispatcher,hint:`address an alive target explicitly with --task-id/--tab (see \`${activeCliName()} api pty-list\`), or notify the user with \`${activeCliName()} api notify\``,nextCommandArgs:["api","pty-list"]})}async function withPeerProvenance(daemon,targetTaskId,prompt){let self=await verifiedSelfSession(),senderId=self?.taskId;if(!senderId||senderId===targetTaskId)return prompt;let label=senderId;try{let res=await daemon.request("task.get",{taskId:senderId});label=res.task.title||res.task.branch||senderId}catch{}let api=kobeApiInvocation(),replyTarget=`--task-id ${senderId} --tab ${self.tabId}`;return`[ROVE PEER] from "${label}" (task ${senderId} \u2014 Rove agent skill /rove, read it once per session (legacy /kobe installs still work); reply only if it changes what I do next: \`${api} send ${replyTarget} --prompt "<text>"\`; verb reference: \`${api} schema\`)
4
+ `)}var selfSessionOnce,identityWarning=null;async function realProbe(){let[{openPtyHost:openPtyHost2,listSessions:listSessions2},{psSnapshot:psSnapshot2}]=await Promise.all([import("./chunk-6mqsm8t9.js"),import("./chunk-8htkv9kd.js")]);return{sessions:async()=>{let host=await openPtyHost2();if(!host)return[];try{return await listSessions2(host.rpc)}finally{host.close()}},ps:psSnapshot2,pid:process.pid}}async function verifiedSelfSession(env=process.env,probe){if(!probe&&selfSessionOnce)return selfSessionOnce;let run=resolveSelfSession(env,probe);return selfSessionOnce=run,run}async function resolveSelfSession(env,probe){let taskId=env.KOBE_TASK_ID;if(!taskId)return null;let tabId=env.KOBE_TAB_ID||"tab-1";try{let p=probe??await realProbe(),key=`${taskId}::${tabId}`,session=(await p.sessions()).find((s)=>s.key===key&&s.alive);if(session?.pid){let{hasAncestor,parsePsSnapshot:parsePsSnapshot2}=await import("./chunk-8htkv9kd.js");if(hasAncestor(parsePsSnapshot2(await p.ps([session.pid,p.pid])),p.pid,session.pid))return identityWarning=null,{taskId,tabId}}}catch{}return identityWarning=`$ROVE_TASK_ID/$KOBE_TASK_ID names task ${taskId} ${tabId}, but this process is not running inside that tab (an inherited env, not an identity) \u2014 dispatcher/peer provenance omitted`,null}function takeIdentityWarning(){let warning=identityWarning;return identityWarning=null,warning}async function dispatcherEnvPayload(env=process.env,probe){let self=await verifiedSelfSession(env,probe);if(!self)return{};return{dispatcherTaskId:self.taskId,dispatcherTabId:self.tabId}}async function readOwnDispatcher(daemon){let self=await verifiedSelfSession();if(!self)return null;try{return(await daemon.request("task.get",{taskId:self.taskId})).task.dispatcher??null}catch{return null}}async function resolveDispatcherTab(runtime,dispatcher){let{tabs,running}=await runtime.taskTabs(dispatcher.taskId);if(tabs.some((t)=>t.id===dispatcher.tabId&&t.alive))return dispatcher.tabId;if(running)return;throw new ApiError(`dispatcher tab ${dispatcher.tabId} on task ${dispatcher.taskId} is dead and the task has no live engine tab \u2014 the reply has nowhere to land`,"DISPATCHER_UNREACHABLE",{dispatcher,hint:`address an alive target explicitly with --task-id/--tab (see \`${activeCliName()} api pty-list\`), or notify the user with \`${activeCliName()} api notify\``,nextCommandArgs:["api","pty-list"]})}async function withPeerProvenance(daemon,targetTaskId,prompt){let self=await verifiedSelfSession(),senderId=self?.taskId;if(!senderId||senderId===targetTaskId)return prompt;let label=senderId;try{let res=await daemon.request("task.get",{taskId:senderId});label=res.task.title||res.task.branch||senderId}catch{}let api=kobeApiInvocation(),replyTarget=`--task-id ${senderId} --tab ${self.tabId}`;return`[ROVE PEER] from "${label}" (task ${senderId} \u2014 Rove agent skill /rove, read it once per session (legacy /kobe installs still work); reply only if it changes what I do next: \`${api} send ${replyTarget} --prompt "<text>"\`; verb reference: \`${api} schema\`)
5
5
 
6
- ${prompt}`}async function deliverToExactTab(rpc,taskId,tabId,cwd,prompt,opts){let key=`${taskId}::${tabId}`,{sessions=[]}=await rpc.request("pty.list",{}),session=sessions.find((s)=>s.key===key);if(!session?.alive){if(session?.restored===!0){if(!opts?.respawn)throw restoredTabError(taskId,tabId,prompt);let launch=opts.respawn(),open=await rpc.request("pty.open",{key,cwd,...launch?{command:launch.command}:{},defaultColors:readPersistedTerminalDefaultColors()});if(open.respawned!==!0&&open.alive!==!0)throw new ApiError(`tab ${tabId} on task ${taskId} could not be respawned`,"SESSION_FAILED",{taskId,tabId,hint:"the frozen record is still on disk; open the task in the TUI to see the session's own output",nextCommandArgs:["api","read-output","--task-id",taskId,"--tab",tabId,"--source","terminal"]});let enginePid=await awaitEngineProcess(rpc,key,opts.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts.snapshot});if(enginePid===null)return{session:key,pane:key,started:!1,respawned:!0,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,key)??ENGINE_NOT_OBSERVED_REASON};return await deliverRespawned(rpc,key,prompt,enginePid.vendor)}throw new ApiError(`tab ${tabId} has no live session on task ${taskId} \u2014 see \`rove api pty-list\` for alive tabs`,"TAB_NOT_FOUND")}let presence=await enginePresence(session.pid,opts?.engineBin,opts?.snapshot);if(presence.kind==="unknown")throw new ApiError(`could not read the process table, so tab ${tabId} on task ${taskId} 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.kind!=="engine")throw new ApiError(`tab ${tabId} on task ${taskId} has no live engine process \u2014 it is a plain shell right now`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new, or pick an engine tab from pty-list",nextCommandArgs:["api","pty-list"]});let outcome=await deliverToKey(rpc,key,prompt,{vendor:presence.vendor});return{session:key,pane:key,started:!1,...outcomeFields(outcome)}}async function deliverRespawned(rpc,key,prompt,vendor){let outcome=await deliverToKey(rpc,key,prompt,{vendor});return{session:key,pane:key,started:!1,respawned:!0,...outcomeFields(outcome)}}function restoredTabError(taskId,tabId,prompt){return new ApiError(`tab ${tabId} on task ${taskId} is a freeze-restored session \u2014 its pty host restarted, so the tab exists with its scrollback but nothing is running in it`,"TAB_RESTORED",{taskId,tabId,hint:"revive it with --respawn (resumes the tab's pinned conversation when it has one \u2014 `get-task` shows `sessionId`; a tab without one replays its recorded launch command)",nextCommandArgs:["api","send","--task-id",taskId,"--tab",tabId,"--respawn","--prompt",prompt]})}function hasLiveEngineTab(snapshot,taskId,sessions,engineAlive,engineBin){let labelled=new Set((snapshot?.tabs??[]).filter((t)=>t.kind==="engine").map((t)=>t.id));return sessions.some((s)=>{if(s.alive!==!0||!isHostedTaskKey(s.key,taskId))return!1;if(engineAlive?.get(s.key)===!1)return!1;if(s.key===`${taskId}::tab-1`)return!0;let tabId=s.key.slice(taskId.length+2);return labelled.has(tabId)||sessionArgvNamesEngine(s.command,engineBin)})}function sessionFailed(taskId,message,hint,extra){return new ApiError(message,"SESSION_FAILED",{taskId,...extra,hint,nextCommandArgs:["api","read-output","--task-id",taskId,"--source","terminal"]})}async function deliverHosted(target,worktree,prompt){let host;try{host=await ensurePtyHost()}catch(error){throw sessionFailed(target.id,`failed to start PTY host for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"no PTY host to run the engine in \u2014 nothing was started; check `rove daemon status`, then retry the same send")}try{if(target.tab&&target.tab!=="new"){let engineBin=engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort})[0],tabId=target.tab;return await deliverToExactTab(host.rpc,target.id,tabId,worktree,prompt,{engineBin,...target.respawn?{respawn:()=>restoredTabLaunch(target,tabId,worktree,process.env.SHELL?.trim()||"/bin/zsh")}:{}})}let newTab=target.tab==="new"?mintCliTab(target.id,target.tabVendor,target.tabCommand):void 0,launchVendor=target.tabVendor??target.vendor,launchCommand=target.tabCommand??(target.tabVendor?void 0:target.command),{argv,sessionId}=withPinnedSessionId(engineLaunchArgv({command:launchCommand,vendor:launchVendor,effort:target.modelEffort}),launchVendor);trustEngineWorktree(launchVendor,worktree);let launch=buildEngineSessionLaunch({task:{id:target.id,kind:target.kind,vendor:launchVendor,repo:target.repo},worktreePath:worktree,shell:process.env.SHELL?.trim()||"/bin/zsh",argv,promptIntent:target.newTask?{kind:"new-task",prompt}:{kind:"explicit",prompt},tabId:newTab}),result=await deliverHostedPrompt(host.rpc,{id:target.id,engineBin:argv[0]},worktree,prompt,launch,{forceNew:newTab!==void 0});if(result.started&&!result.delivered)throw sessionFailed(target.id,`failed to start hosted engine session for ${target.id}`,"the session was created but no engine ran in it \u2014 fix the task's launch command (`api update --command`), then retry with `api send --tab new`",{session:result.session,engineReady:result.engineReady,...result.reason?{reason:result.reason}:{}});if(!newTab)publishCliTabSnapshot(target.id,result.started?sessionId:void 0);if(result.started&&sessionId){let startedTab=newTab??result.session.split("::")[1];if(startedTab)markCliTabSession(target.id,startedTab,sessionId)}return result}catch(error){if(error instanceof ApiError)throw error;throw sessionFailed(target.id,`hosted engine session failed for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"the hosted session threw while starting or delivering \u2014 read its terminal tail for the cause, then retry the send")}finally{host.close()}}var realPromptDeliveryOps={deliverHosted};async function closeHeadlessTerminalTab(taskId,tabId){let host=await openPtyHost();try{let sessions=host?await listSessions(host.rpc):[],saved=readTabsSnapshot(taskId)?.tabs.find((tab)=>tab.id===tabId),directKey=`${taskId}::${tabId}`,unregisteredAlive=sessions.some((session)=>session.key===directKey&&session.alive);if(!saved&&!unregisteredAlive)throw new ApiError(`tab ${tabId} does not exist on task ${taskId}`,"TAB_NOT_FOUND",{hint:"refresh the task's tab ids with get-task, then retry with one of its .tabs[].id values",nextCommandArgs:["api","get-task","--task-id",taskId]});let closing=saved?closeTabsSnapshot(taskId,tabId):void 0;if(saved&&!closing)throw new ApiError(`tab ${tabId} no longer exists on task ${taskId}`,"TAB_NOT_FOUND",{hint:"the tab closed while this command was running; refresh with get-task before retrying",nextCommandArgs:["api","get-task","--task-id",taskId]});let baseKey=closing?tabPtyKeyFor(taskId,closing):directKey,keys=!(closing?.kind==="engine"&&closing.ptyTask)?sessions.filter((session)=>session.key===baseKey||session.key.startsWith(`${baseKey}::`)).map((session)=>session.key):[],wasAlive=sessions.some((session)=>keys.includes(session.key)&&session.alive);if(host)await killTaskSessions(host.rpc,keys);return{kind:closing?.kind??"engine",wasAlive}}finally{host?.close()}}async function deliverPrompt(client,target,prompt,ops=realPromptDeliveryOps){let worktree=target.worktreePath;if(!worktree)worktree=(await client.request("task.ensureWorktree",{taskId:target.id})).worktreePath;if(!worktree)throw new ApiError(`task ${target.id} has no worktree`,"NO_WORKTREE");if(target.newTask)await client.request("task.observeLanguage",{taskId:target.id,text:prompt}).catch(()=>{});let hosted=await ops.deliverHosted(target,worktree,prompt);if(!hosted)throw sessionFailed(target.id,`failed to start hosted engine session for ${target.id}`,"delivery returned nothing \u2014 the task exists but has no session; retry with `api send --tab new`");return hosted}var defaultApiRuntime={isTaskRunning:async(taskId,engineArgv)=>(await defaultApiRuntime.taskTabs(taskId,engineArgv)).running,taskTabs:async(taskId,engineArgv)=>{let listed=null,host=await openPtyHost();if(host)try{listed=await listSessionsOrNull(host.rpc)}finally{host.close()}let sessions=listed??[],hostReachable=listed!==null,liveVendors,engineAlive;try{let{engineProcessIn,foregroundEngineIn:foregroundEngineIn2,parsePsSnapshot:parsePsSnapshot2,psSnapshot:psSnapshot2}=await import("./chunk-e803hkkq.js"),walkable=sessions.filter((s)=>s.alive&&typeof s.pid==="number"&&s.pid>0);if(walkable.length>0){let rows=parsePsSnapshot2(await psSnapshot2(walkable.map((s)=>s.pid)));liveVendors=new Map(walkable.map((s)=>[s.key,foregroundEngineIn2(rows,s.pid)?.vendor??null])),engineAlive=new Map(walkable.map((s)=>[s.key,engineProcessIn(rows,s.pid,engineArgv)]))}else engineAlive=new Map}catch{}let exits={};try{exits=(await import("./chunk-var92s38.js")).readPtyExitRecords()}catch{}let snapshot=readTabsSnapshot(taskId),sessionIds=new Map((snapshot?.tabs??[]).map((t)=>[t.id,t.sessionId??void 0]));return{tabs:joinTaskTabs(snapshot,taskId,listed,exits,liveVendors,engineAlive).map((row)=>{let sessionId=sessionIds.get(row.id);return sessionId?{...row,sessionId}:row}),running:hostReachable?hasLiveEngineTab(snapshot,taskId,sessions,engineAlive,engineArgv?.[0]):null}},closeTerminalTab:closeHeadlessTerminalTab,deliverPrompt:(client,target,prompt)=>deliverPrompt(client,target,prompt),resolveRepoRoot:async(absPath)=>(await import("./chunk-6txd5jtt.js")).resolveMainRepoRoot(absPath),isUsableRepo:async(absPath)=>{let{isGitRepo,isRemoteRepoKey:isRemoteRepoKey2}=await import("./chunk-6txd5jtt.js");return isRemoteRepoKey2(absPath)||isGitRepo(absPath)},isValidBranchName:async(branch)=>(await import("./chunk-6txd5jtt.js")).isValidBranchName(branch),defaultVendor:async(repo)=>{let{getGlobalDefaultVendor,getRepoLastActiveVendor}=await import("./chunk-na3tmp41.js");return(repo?getRepoLastActiveVendor(repo):void 0)??getGlobalDefaultVendor()},readWorktreeChanges:async(worktreePath)=>(await import("./chunk-s0snbj93.js")).readWorktreeChanges(worktreePath),readBranchSignals:async(worktreePath,recordedBaseRef)=>(await import("./chunk-j4xfsn9g.js")).readBranchSignals(worktreePath,recordedBaseRef),tearDownSession:async(taskId)=>{let host=await openPtyHost();if(host)try{await killTaskSessions(host.rpc,taskKeys(await listSessions(host.rpc),taskId))}catch{}finally{host.close()}}};async function issueUpdate(ctx){let title=ctx.args.str("title"),body=ctx.args.str("body"),task=ctx.args.str("task");if(title===void 0&&body===void 0&&task===void 0)throw new ApiError("issue-update requires --title, --body, and/or --task","MISSING_FLAG");let repoRoot=ctx.args.requireRepo("repo"),id=ctx.args.int("id");return simpleRpc(ctx,"issue.mutate",{repoRoot,op:{type:"update",id,title,body,...task===void 0?{}:{taskId:task==="none"?null:task}}})}async function assertNotEmptySuccess(daemon,ctx,prompt){if(ctx.args.bool("allow-empty"))return;if(!/^\s*succeeded\s*[:\uff1a]/i.test(prompt))return;let self=await verifiedSelfSession();if(!self)return;let sender;try{sender=(await daemon.request("task.get",{taskId:self.taskId})).task}catch{return}if(sender.kind==="main"||sender.kind==="dir")return;if(!sender.worktreePath)return;let ahead;try{ahead=(await ctx.runtime.readBranchSignals(sender.worktreePath,sender.baseRef)).ahead}catch{return}if(ahead!==0)return;let branch=sender.branch||"your branch";throw new ApiError(`refusing to report success: ${branch} has 0 commits \u2014 "succeeded" means COMMITTED, and this report would reach the coordinator as a clean success with nothing to land`,"EMPTY_SUCCESS_REPORT",{taskId:self.taskId,branch,hint:"commit your work with a real message and send again \u2014 or, if this task genuinely produced no commits (an investigation or a review), re-send with --allow-empty to say so explicitly",nextCommandArgs:["api","send",...ctx.args.str("task-id")?["--task-id",ctx.args.str("task-id")]:[],...ctx.args.str("tab")?["--tab",ctx.args.str("tab")]:[],"--allow-empty","--prompt",prompt]})}function requirePromptText(ctx,verb){let text=ctx.args.promptText();if(text===void 0)throw new ApiError("--prompt (or --prompt-file) is required","MISSING_FLAG",helpStep(verb));return text}async function send(ctx){let daemon=daemonOf(ctx),prompt=requirePromptText(ctx,"send"),tab=ctx.args.str("tab");if(tab&&tab!=="new"&&!/^tab-[A-Za-z0-9-]+$/.test(tab))throw new ApiError(`--tab must be "new" or a tab id like tab-2 (got ${JSON.stringify(tab)})`,"BAD_TAB");let tabCommand=ctx.args.str("command");if(tabCommand&&tab!=="new")throw new ApiError(`--command only applies to a new tab; pass --tab new (got --tab ${tab??"<canonical>"})`,"BAD_FLAG",helpStep("send"));let respawn=ctx.args.bool("respawn");if(respawn&&(tab===void 0||tab==="new"))throw new ApiError(`--respawn addresses one frozen tab; pass --tab tab-N (got --tab ${tab??"<canonical>"})`,"BAD_FLAG",helpStep("send"));let tabVendor=tabCommand?resolveCommandProtocol(tabCommand):void 0,taskId=ctx.args.str("task-id");if(!taskId){let dispatcher=await readOwnDispatcher(daemon);if(dispatcher){if(taskId=dispatcher.taskId,tab===void 0)tab=await resolveDispatcherTab(ctx.runtime,dispatcher)}else{let active=await resolveActiveTaskId(daemon);if(!active)throw new ApiError("no --task-id given and no active task \u2014 open a task first or pass --task-id","MISSING_TARGET");taskId=active}}let res=await daemon.request("task.get",{taskId});await assertNotEmptySuccess(daemon,ctx,prompt);let text=ctx.args.bool("plain")?prompt:await withPeerProvenance(daemon,taskId,prompt),delivered=await ctx.runtime.deliverPrompt(daemon,{id:taskId,worktreePath:res.task.worktreePath,kind:res.task.kind,vendor:res.task.vendor,command:res.task.command,modelEffort:tabCommand?void 0:res.task.modelEffort,repo:res.task.repo,tab,tabVendor,tabCommand,respawn},text);if(!delivered.delivered)throw new ApiError(`prompt was not confirmed in ${taskId}'s engine (paste did not land)`,"NOT_DELIVERED");return{ok:!0,taskId,session:delivered.session,started:delivered.started,engineReady:delivered.engineReady,delivered:delivered.delivered,...delivered.bytes===void 0?{}:{bytes:delivered.bytes},...delivered.promptEcho?{promptEcho:delivered.promptEcho}:{},...delivered.reason?{reason:delivered.reason}:{},...delivered.respawned?{respawned:!0}:{},...delivered.frozenTabs?.length?{frozenTabs:delivered.frozenTabs}:{}}}async function dispatch(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),text=requirePromptText(ctx,"dispatch"),tabId=ctx.args.str("tab"),reply=await daemon.request("session.deliver",{taskId,text,...tabId!==void 0?{tabId}:{},source:"dispatcher"});return{ok:!0,taskId,...reply?.tabId!==void 0?{tabId:reply.tabId}:tabId!==void 0?{tabId}:{},routed:"session.deliver",...reply?.delivered!==void 0?{delivered:reply.delivered}:{},...reply?.reason!==void 0?{reason:reply.reason}:{},...reply?.layer!==void 0?{layer:reply.layer}:{},...reply?.clients!==void 0?{clients:reply.clients}:{}}}var DISPATCH_VERB={name:"dispatch",group:"drive",summary:'Route text into a task\'s live session. The dispatcher\'s messenger (docs/design/dispatcher.md); unlike `send`, it never starts an engine \u2014 it requires an already-hosted session. The daemon pastes into it and reports `delivered`; `delivered:false` with `reason:"busy"` means a human is mid-message, and `reason:"broadcast"` means no hosted session answered and the text went out on the session.deliver channel for a browser to pick up (unconfirmable; `clients: 0` proves it reached nobody).',flags:[F.taskId(!0),F.prompt(!0,"Text delivered into the task's engine session."),F.promptFile(),{name:"tab",type:"string",required:!1,placeholder:"TAB",description:"Deliver into exactly this tab (e.g. tab-3) instead of the canonical engine tab."}],handler:dispatch};async function note(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),text=ctx.args.require("text");return await daemon.request("note.file",{taskId,text})}async function getTask(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),res=await daemon.request("task.get",{taskId}),{tabs,running}=await ctx.runtime.taskTabs(taskId,taskEngineArgv(res.task));return{task:res.task,running,tabs}}async function list(ctx){let local=await daemonOf(ctx).request("task.list"),{mergeTaskList}=await import("./chunk-k9xpebq8.js");return await mergeTaskList(local)}async function setActive(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.bool("none")?null:ctx.args.require("task-id");return await daemon.request("task.setActive",{taskId}),{ok:!0,activeTaskId:taskId}}var SCHEDULE_FLAG={name:"schedule",type:"string",placeholder:"CRON",description:"Five-field cron in the daemon host's local time, e.g. '0 9 * * MON-FRI'."},PRECHECK_FLAGS=[{name:"precheck",type:"string",placeholder:"CMD",description:"Shell command run in the repo BEFORE the engine starts. Non-zero exit skips the run without spawning an agent \u2014 the cheap way to avoid burning a turn when nothing changed."},{name:"precheck-timeout",type:"int",placeholder:"SEC",default:"120",description:"Seconds before the precheck is killed and the run skipped."}],GRACE_FLAG={name:"grace",type:"uint",placeholder:"MIN",default:"60",description:"How late a missed occurrence may still run when the daemon was down. Only the most recent missed occurrence is ever run."},PERSISTENT_FLAG={name:"persistent-session",type:"bool",description:"Re-deliver into ONE standing task instead of a fresh worktree per run \u2014 for a routine that needs yesterday's context (a trend check). Its task is folded behind the sidebar's routine count row. Leave off for a routine that EDITS code: a week of runs on one branch is a branch nobody can land."},TARGET_FLAGS=[{name:"target-task",type:"string",placeholder:"ID",description:"Existing task id. Requires --target-tab; never creates or revives a session. Pass both empty to clear on update."},{name:"target-tab",type:"string",placeholder:"TAB",description:"Exact existing engine tab id, e.g. tab-2. Requires --target-task."}];function targetPayload(ctx){let hasTask=ctx.args.present("target-task"),hasTab=ctx.args.present("target-tab");if(!hasTask&&!hasTab)return{};if(!hasTask||!hasTab)throw new ApiError("--target-task and --target-tab must be supplied together","BAD_FLAG");let taskId=ctx.args.str("target-task"),tabId=ctx.args.str("target-tab");if(!taskId&&!tabId)return{target:null};if(!taskId||!tabId)throw new ApiError("both target values must be nonempty, or both empty to clear","BAD_FLAG");return{target:{kind:"existing-tab",taskId,tabId}}}function precheckPayload(ctx){if(!ctx.args.present("precheck")){if(ctx.args.present("precheck-timeout"))throw new ApiError("--precheck-timeout requires --precheck (pass the command again to change its timeout)","BAD_FLAG");return{}}let command=ctx.args.str("precheck");if(command===void 0)return{precheck:null};return{precheck:{command,timeoutSeconds:ctx.args.int("precheck-timeout")??120}}}var ROUTINE_VERBS=[{name:"routine-list",group:"routine",summary:"List scheduled routines with their next run time.",flags:[],handler:(ctx)=>simpleRpc(ctx,"automation.list",{})},{name:"routine-create",group:"routine",summary:"Schedule a prompt. Each firing creates a fresh task (worktree + engine) and delivers it. Use --target-task and --target-tab for an existing conversation. An enabled routine keeps the daemon alive.",flags:[F.repo(),{name:"name",type:"string",required:!0,placeholder:"N",description:"Routine name."},F.prompt(!0,"Text delivered to the selected conversation or a new session."),F.promptFile(),{...SCHEDULE_FLAG,required:!0},F.vendor(),{name:"base-branch",type:"string",placeholder:"B",description:"Base ref each run's worktree branches from."},...PRECHECK_FLAGS,GRACE_FLAG,PERSISTENT_FLAG,...TARGET_FLAGS,{name:"disabled",type:"bool",description:"Create it paused instead of active."}],handler:(ctx)=>simpleRpc(ctx,"automation.create",{repo:ctx.args.requireRepo("repo"),name:ctx.args.require("name"),prompt:requirePromptText(ctx,"routine-create"),schedule:ctx.args.require("schedule"),...ctx.args.vendor()?{vendor:ctx.args.vendor()}:{},...ctx.args.str("base-branch")?{baseRef:ctx.args.str("base-branch")}:{},...precheckPayload(ctx),...targetPayload(ctx),...ctx.args.nonNegativeInt("grace")!==void 0?{missedRunGraceMinutes:ctx.args.nonNegativeInt("grace")}:{},...ctx.args.bool("persistent-session")?{persistentSession:!0}:{},...ctx.args.bool("disabled")?{enabled:!1}:{}})},{name:"routine-update",group:"routine",summary:"Change a routine. A new --schedule re-anchors its next run; --precheck '' clears the precheck.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."},{name:"name",type:"string",placeholder:"N",description:"New name."},F.prompt(!1,"New prompt."),F.promptFile(),SCHEDULE_FLAG,{...F.vendor(),type:"string",description:"New engine vendor; empty clears it before binding an existing target."},{name:"base-branch",type:"string",placeholder:"B",description:"New base ref ('' to clear)."},...PRECHECK_FLAGS,GRACE_FLAG,PERSISTENT_FLAG,...TARGET_FLAGS],handler:(ctx)=>simpleRpc(ctx,"automation.update",{id:ctx.args.require("id"),...ctx.args.str("name")!==void 0?{name:ctx.args.str("name")}:{},...ctx.args.promptText()!==void 0?{prompt:ctx.args.promptText()}:{},...ctx.args.str("schedule")!==void 0?{schedule:ctx.args.str("schedule")}:{},...ctx.args.present("vendor")?{vendor:ctx.args.vendor()??null}:{},...ctx.args.present("base-branch")?{baseRef:ctx.args.str("base-branch")??null}:{},...precheckPayload(ctx),...targetPayload(ctx),...ctx.args.nonNegativeInt("grace")!==void 0?{missedRunGraceMinutes:ctx.args.nonNegativeInt("grace")}:{},...ctx.args.present("persistent-session")?{persistentSession:ctx.args.bool("persistent-session")??!0}:{}})},{name:"routine-set-enabled",group:"routine",summary:"Pause or resume a routine. Disabling the last active one releases the daemon's keep-alive hold.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."},{name:"enabled",type:"bool",required:!0,description:"true to resume, false to pause."}],handler:(ctx)=>simpleRpc(ctx,"automation.update",{id:ctx.args.require("id"),enabled:ctx.args.bool("enabled")})},{name:"routine-delete",group:"routine",summary:"Delete a routine and its run history. Tasks it already created are untouched.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."}],handler:(ctx)=>simpleRpc(ctx,"automation.delete",{id:ctx.args.require("id")})},{name:"routine-run-now",group:"routine",summary:"Run a routine immediately, skipping its precheck (asking for it IS the answer). Does not shift its schedule.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."}],handler:(ctx)=>simpleRpc(ctx,"automation.runNow",{id:ctx.args.require("id")})},{name:"routine-runs",group:"routine",summary:"Run history, newest first. Statuses: dispatched, revived (standing session respawned \u2014 files kept, conversation did not), skipped_cancelled (disabled, changed or stopped before delivery), skipped_precheck (nothing to do), skipped_missed, skipped_unavailable, dispatch_failed.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."}],handler:(ctx)=>simpleRpc(ctx,"automation.runs",{id:ctx.args.require("id")})}];async function engineChoice(ctx,repo){let command=ctx.args.str("command");if(command)return{command,vendor:resolveCommandProtocol(command)};let fallback=await ctx.runtime.defaultVendor(repo);return fallback?{command:fallback,vendor:fallback}:{}}function enginePayload(choice,effort){return{...choice.command?{command:choice.command}:{},...choice.vendor?{vendor:choice.vendor}:{},...effort?{effort}:{}}}function effortFor(ctx,engines){let level=ctx.args.str("effort")?.trim();if(!level)return;for(let engine of new Set(engines))assertEngineAcceptsEffort(engine,level,["api","engine-list"]);return level}async function applyPostCreateFlags(daemon,taskId,args){let status=args.enumOf("status");if(status)await daemon.request("task.status",{taskId,status});let pin=args.bool("pin");if(pin!==void 0)await daemon.request("task.pin",{taskId,pinned:pin});return Boolean(status)||pin!==void 0}async function add(ctx){let{args,runtime}=ctx,requestedRepo=args.requireRepo("repo"),repo=await runtime.resolveRepoRoot(requestedRepo);if(!await runtime.isUsableRepo(repo))throw new ApiError(`--repo ${repo} is not a git repository \u2014 a task needs one to cut its worktree and branch from (run \`git init\` there, or point --repo at a checkout)`,"NOT_A_REPO",helpStep("add"));let count=args.int("count"),agentsSpec=args.str("agents"),parallel=count!==void 0||agentsSpec!==void 0,branch=parallel?void 0:args.str("branch");if(branch&&!await runtime.isValidBranchName(branch))throw new ApiError(`--branch ${JSON.stringify(branch)} is not a valid git branch name (no spaces, no leading "-", no "..", "~^:?*[\\", no trailing ".lock") \u2014 see \`git check-ref-format --branch\``,"INVALID_BRANCH",helpStep("add"));let resolvedFrom=pathWithin(repo,requestedRepo)?{repoResolvedFrom:requestedRepo}:void 0,result=parallel?await addParallel(ctx,repo,count,agentsSpec):await addOne(ctx,repo);return resolvedFrom&&result&&typeof result==="object"?{...result,...resolvedFrom}:result}async function addOne(ctx,repo){let daemon=daemonOf(ctx),{args}=ctx,prompt=args.promptText(),choice=await engineChoice(ctx,repo),effort=effortFor(ctx,choice.vendor?[choice.vendor]:[]),payload={repo,...await dispatcherEnvPayload(),...enginePayload(choice,effort)},title=args.str("title")||(prompt?deriveTitleFromPrompt(prompt):"");if(title)payload.title=title;let branch=args.str("branch");if(branch)payload.branch=branch;let baseRef=args.str("base-branch");if(baseRef)payload.baseRef=baseRef;let worktreeName=args.str("worktree-name");if(worktreeName)payload.worktreeName=worktreeName;let res=await daemon.request("task.create",payload),taskId=res.taskId;if(args.bool("activate"))await daemon.request("task.setActive",{taskId});let task=res.task;if(await applyPostCreateFlags(daemon,taskId,args))task=(await daemon.request("task.get",{taskId})).task;if(!prompt)return{taskId,task,home:homeDir(),started:!1};let brief=await withPeerProvenance(daemon,taskId,prompt),delivered=await ctx.runtime.deliverPrompt(daemon,{id:taskId,worktreePath:task.worktreePath,kind:task.kind,vendor:task.vendor,command:task.command,modelEffort:task.modelEffort,repo:task.repo,newTask:!0},brief);if(!delivered.delivered)throw new ApiError(`task ${taskId} created but the prompt was not delivered (paste did not land)`,"NOT_DELIVERED",{taskId});let promptPersisted=await persistPrompt(daemon,taskId,prompt);return task=(await daemon.request("task.get",{taskId})).task,{taskId,task,home:homeDir(),started:delivered.started,engineReady:delivered.engineReady,session:delivered.session,delivered:delivered.delivered,...delivered.bytes===void 0?{}:{bytes:delivered.bytes},...delivered.promptEcho?{promptEcho:delivered.promptEcho}:{},...delivered.reason?{reason:delivered.reason}:{},...promptPersisted?{}:{promptPersisted:!1}}}async function persistPrompt(daemon,taskId,prompt){try{return await daemon.request("task.setPrompt",{taskId,prompt}),!0}catch(err){return console.error(`[rove api add] task.setPrompt failed for ${taskId} \u2014 no "Run again" for this task:`,err),!1}}async function addParallel(ctx,repo,count,agentsSpec){let daemon=daemonOf(ctx),{args}=ctx,prompt=args.promptText();if(!prompt)throw new ApiError("--count/--agents spawn parallel attempts of ONE prompt \u2014 pass --prompt","MISSING_FLAG",helpStep("add"));if(args.str("branch"))throw new ApiError("--branch names ONE branch and cannot be shared by parallel siblings \u2014 drop it (each sibling gets its own auto branch) or spawn them one at a time","BAD_FLAG",helpStep("add"));if(args.str("worktree-name"))throw new ApiError("--worktree-name names ONE directory and cannot be shared by parallel siblings \u2014 drop it (each sibling gets its own generated name) or spawn them one at a time","BAD_FLAG",helpStep("add"));if(agentsSpec){let conflict=count!==void 0?"--count":args.str("command")?"--command":null;if(conflict)throw new ApiError(`${conflict} conflicts with --agents, which already names each sibling's engine and how many \u2014 pass one or the other`,"BAD_FLAG",helpStep("add"))}let title=args.str("title")||deriveTitleFromPrompt(prompt),baseRef=args.str("base-branch"),choice=await engineChoice(ctx,repo),plan=agentsSpec?parseAgentsSpec(agentsSpec):buildCountPlan(count??1,choice.vendor??DEFAULT_VENDOR);if(plan.length>FANOUT_CAP)throw new ApiError(`a parallel round of ${plan.length} exceeds the cap of ${FANOUT_CAP} \u2014 spawn in batches`,"BAD_FLAG");let effort=effortFor(ctx,plan),groupId=ulid(),created=[],createFailure=null,dispatcher=await dispatcherEnvPayload();for(let[i,vendor]of plan.entries()){let engine=agentsSpec?{command:vendor,vendor}:{...choice,vendor},payload={repo,groupId,...dispatcher,...enginePayload(engine,effort)};if(title)payload.title=plan.length>1?`${title} #${i+1}/${plan.length}`:title;if(baseRef)payload.baseRef=baseRef;try{let res=await daemon.request("task.create",payload);created.push({taskId:res.taskId,vendor,task:res.task})}catch(err){let code=err instanceof ApiError?err.code:"CREATE_FAILED",message=err instanceof Error?err.message:String(err);createFailure={vendor,error:{message,code}};break}}for(let{taskId}of created)await applyPostCreateFlags(daemon,taskId,args);let settled=await Promise.allSettled(created.map(({taskId,vendor,task})=>ctx.runtime.deliverPrompt(daemon,{id:taskId,worktreePath:task.worktreePath,kind:task.kind,vendor,command:task.command,modelEffort:task.modelEffort,repo:task.repo,newTask:!0},prompt))),tasks=[],failures=[],persistedPrompts=[];if(settled.forEach((r,i)=>{let{taskId,vendor,task}=created[i];if(r.status==="fulfilled"&&r.value.delivered){let row={ok:!0,taskId,title:task.title,branch:task.branch,vendor,started:r.value.started,engineReady:r.value.engineReady,session:r.value.session,...r.value.reason?{reason:r.value.reason}:{}};tasks.push(row),persistedPrompts.push(persistPrompt(daemon,taskId,prompt).then((ok)=>{if(!ok)row.promptPersisted=!1}));return}let err=r.status==="rejected"?r.reason:new ApiError(`prompt was not confirmed in ${taskId}'s engine`,"NOT_DELIVERED"),code=err instanceof ApiError?err.code:"DELIVER_FAILED",message=err instanceof Error?err.message:String(err);failures.push({ok:!1,taskId,vendor,error:{message,code}})}),createFailure)failures.push({ok:!1,vendor:createFailure.vendor,error:createFailure.error});await Promise.all(persistedPrompts);let result={count:created.length,requested:plan.length,groupId,home:homeDir(),tasks,failures};if(failures.length>0)throw new ApiError(`add delivered ${tasks.length}/${plan.length}`,"PARTIAL_FANOUT",result);return result}var TASK_STATUSES=["backlog","in_progress","in_review","done","canceled","error"];var CREATE_VERBS=[{name:"add",group:"create",summary:`Create a task (shows in the sidebar immediately). With --prompt it also starts the engine and delivers it. PARALLEL ATTEMPTS: --count N spawns N sibling tasks of the SAME prompt, each in its own worktree/branch (--agents claude:2,codex:1 for a mixed fleet); capped at ${FANOUT_CAP}, prefer 3-4. Does NOT steal focus \u2014 pass --activate to make it the active task. The sidebar shows .task.title and .task.branch \u2014 name a task by those (or its id), never by the directory in .task.worktreePath, which the UI never renders. Alias: spawn-task.`,flags:[F.repo(),F.title(),{name:"branch",type:"string",placeholder:"B",description:"Explicit branch name (else derived from the title in the repo's own style). Single task only."},{name:"base-branch",type:"string",placeholder:"B",description:"Base ref the worktree branches from."},{name:"worktree-name",type:"string",placeholder:"NAME",description:"Name the worktree DIRECTORY instead of taking one from the animal pool \u2014 so the caller can predict `.task.worktreePath` (`<worktrees root>/<NAME>`) rather than reading it back with get-task. One path segment of letters/digits/`.`/`_`/`-`, not starting with `.` (INVALID_WORKTREE_NAME otherwise). A name already in use in this repo \u2014 by a live task, a directory on disk, or a concurrent create \u2014 is REFUSED with WORKTREE_NAME_TAKEN, never silently suffixed `-v2`. Single task only."},F.command(),{name:"effort",type:"string",placeholder:"LEVEL",description:"Reasoning effort for the FIRST session, not just later ones. Validated against the engine's declared levels (codex: none/low/medium/high/xhigh/max; claude declares none) \u2014 free-form, since a plugin engine may declare its own. With --agents, every engine in the plan must declare it."},{name:"count",type:"int",placeholder:"N",description:`Spawn N sibling tasks of one prompt (parallel attempts, cap ${FANOUT_CAP}). Requires --prompt.`},{name:"agents",type:"string",placeholder:"claude:2,codex:1",description:"Per-ENGINE counts for a mixed parallel round (alternative to --count). Engine ids only \u2014 see `engine-list`."},{name:"status",type:"enum",values:TASK_STATUSES,default:"backlog",description:"Initial lifecycle status."},{name:"pin",type:"bool",description:"Pin the task to the top of the sidebar."},{name:"activate",type:"bool",default:"false",description:"Make this the active task (pulls every mounted TUI's Tasks-pane focus). Off by default."},F.prompt(!1,"Optional first message \u2014 when set, materializes the worktree, starts the engine, and pastes it. Required with --count/--agents."),F.promptFile()],handler:add}];function interruptSequenceFor(task){let vendor=task.vendor,sequence=vendor?getCapabilities(vendor)?.interruptSequence:void 0;if(sequence)return sequence;throw new ApiError(`engine ${vendor??"(unknown)"} has not declared how it is interrupted`,"UNSUPPORTED",{taskId:task.id,...vendor?{vendor}:{},hint:"only engines that declare an interrupt sequence can be interrupted \u2014 stop this one by hand in its tab, or close the tab with `tab-close`",nextCommandArgs:["api","get-task","--task-id",task.id]})}async function interruptTask(ctx){let taskId=ctx.args.require("task-id"),tabFlag=ctx.args.str("tab"),{task}=await daemonOf(ctx).request("task.get",{taskId}),sequence=interruptSequenceFor({...task,id:taskId}),host=await openHostedSessionHost();if(!host)throw new ApiError(`no pty host to reach task ${taskId}`,"NO_ENGINE_TAB",{taskId,hint:"nothing is hosting this task's engine \u2014 `pty-list` says whether a host is up at all",nextCommandArgs:["api","pty-list"]});try{let sessions=await listHostedSessions(host.rpc),key=tabFlag?`${taskId}::${tabFlag}`:findHostedEngineKey(sessions,taskId,taskEngineArgv(task)[0]);if(!key||!sessions.some((session)=>session.key===key&&session.alive))throw new ApiError(tabFlag?`task ${taskId} has no live tab ${tabFlag}`:`task ${taskId} has no live engine tab to interrupt`,tabFlag?"TAB_NOT_FOUND":"NO_ENGINE_TAB",{taskId,...tabFlag?{tabId:tabFlag}:{},hint:"`get-task` lists the live tabs in .tabs[]",nextCommandArgs:["api","get-task","--task-id",taskId]});return await host.rpc.request("pty.write",{key,data:sequence}),{ok:!0,taskId,tabId:key.split("::")[1]??"tab-1",vendor:task.vendor,interrupted:!0,bytes:Buffer.byteLength(sequence,"utf8")}}finally{host.close()}}var INTERRUPT_VERB={name:"interrupt",group:"drive",summary:"Stop the turn a task's engine is currently running \u2014 the headless twin of pressing the engine's own interrupt key. Writes the ENGINE-declared interrupt bytes to its pty; the session, its conversation and its worktree all survive, which is what separates this from `tab-close` and `delete`. Use it when a worker runs away: `send` cannot reach it (a busy engine's composer is not quiet), and until now the only levers left destroyed something. Engines that have not declared an interrupt sequence (every `generic` protocol engine) are refused with UNSUPPORTED rather than guessed at \u2014 Esc and ctrl-C mean opposite things across engines. Returns { taskId, tabId, vendor, interrupted, bytes }; `interrupted` reports the WRITE, so read `collect`'s .activity.state for the effect.",flags:[F.taskId(),{name:"tab",type:"string",placeholder:"TAB",description:"Interrupt this exact tab (id from `get-task` .tabs[].id). Omitted = the task's canonical engine tab, the same one a bare `send` targets."}],handler:interruptTask};var PANE_VERB={name:"pane-open",group:"drive",summary:"Open a terminal pane in a task's workspace: split the focused tab (default, or --tab's tab) or open a separate command tab, optionally running a command. Broadcast over the daemon's tab.open channel \u2014 an attached TUI showing the task performs the split. Task defaults to $ROVE_TASK_ID, then the active task. Returns the resolved `title` (the label `pane-close --title` must match \u2014 derived from the command's first word when --title is omitted) plus `clients` (attached connections; 0 = nobody performed the split).",flags:[F.taskId(!1),{name:"tab",type:"string",placeholder:"TAB",description:"Host tab for the split (e.g. tab-3) instead of the focused tab (split placement only)."},{name:"command",type:"string",placeholder:"CMD",description:"Shell command the pane runs (via the login shell's `-ilc`, so pipes/args and your shell rc's PATH/exports work); the pane closes when it exits. Omit for an interactive shell."},{name:"direction",type:"enum",values:["right","down"],default:"right",description:"Split orientation relative to the active pane (split placement only)."},{name:"placement",type:"enum",values:["split","tab"],default:"split",description:"`split` joins the focused tab's split group; `tab` opens a separate command tab."},{name:"title",type:"string",placeholder:"TEXT",description:`Pane label (default: the command's first word, else "shell").`}],handler:async(ctx)=>{let client=daemonOf(ctx),taskId=ctx.args.str("task-id")??process.env.KOBE_TASK_ID??await resolveActiveTaskId(client);if(!taskId)throw new ApiError("no target task: pass --task-id (no $ROVE_TASK_ID, no active task)","MISSING_TARGET");let command=ctx.args.str("command"),shell=resolveLoginShell({fallback:"/bin/sh"}),argv=command?[shell,"-ilc",command]:[shell,"-il"],title=ctx.args.str("title")??(command?command.trim().split(/\s+/)[0]??"shell":"shell"),tabId=ctx.args.str("tab");return{...await simpleRpc(ctx,"tab.open",{taskId,argv,title,...tabId!==void 0?{tabId}:{},placement:ctx.args.str("placement")??"split",direction:ctx.args.str("direction")??"right"}),title}}},PANE_CLOSE_VERB={name:"pane-close",group:"drive",summary:"Close panes opened by pane-open: every split pane / command tab in the task whose label matches --title. Broadcast over the daemon's tab.close channel \u2014 an attached TUI showing the task performs the close (headless no-op). Task defaults to $ROVE_TASK_ID, then the active task. Returns `clients` (attached connections; 0 = nobody performed the close).",flags:[F.taskId(!1),{name:"title",type:"string",required:!0,placeholder:"TEXT",description:"Pane label to close \u2014 the --title the pane was opened with (engine panes are never closed)."},{name:"tab",type:"string",placeholder:"TAB",description:"Scope the title match to one tab (e.g. tab-3) instead of every tab of the task."}],handler:async(ctx)=>{let client=daemonOf(ctx),taskId=ctx.args.str("task-id")??process.env.KOBE_TASK_ID??await resolveActiveTaskId(client);if(!taskId)throw new ApiError("no target task: pass --task-id (no $ROVE_TASK_ID, no active task)","MISSING_TARGET");let tabId=ctx.args.str("tab");return simpleRpc(ctx,"tab.close",{taskId,title:ctx.args.str("title"),...tabId!==void 0?{tabId}:{}})}},TAB_CLOSE_VERB={name:"tab-close",group:"drive",summary:"Close one Terminal Tab by the id returned in get-task .tabs[]. Runs the same close path as ctrl+w when a TUI is attached; otherwise removes the persisted tab snapshot and ends its hosted PTYs directly. Engine, shell/command, and content tabs are all valid. Closing the last tab leaves the task open with no session.",flags:[F.taskId(!0),{name:"tab",type:"string",required:!0,placeholder:"TAB",description:"Exact Terminal Tab id from get-task .tabs[].id (for example tab-3)."}],handler:async(ctx)=>{let taskId=ctx.args.require("task-id"),tabId=ctx.args.require("tab");if((await daemonOf(ctx).request("terminalTab.close",{taskId,tabId})).handled)return{ok:!0,taskId,tabId,handledBy:"tui"};let result=await ctx.runtime.closeTerminalTab(taskId,tabId);return{ok:!0,taskId,tabId,handledBy:"headless",...result}}};var DRIVE_VERBS=[{name:"send",group:"drive",summary:"Paste a follow-up prompt into a task's running engine (one full turn). Without --task-id, a task spawned from another Rove session replies to its dispatcher's tab (then that task's live canonical engine; nothing alive = DISPATCHER_UNREACHABLE, never a silent spawn); otherwise the active task. Sent from inside another Rove task ($ROVE_TASK_ID), the prompt is prefixed with [ROVE PEER] provenance \u2014 who sent it and how to reply (tab-precise) \u2014 so agent-to-agent messaging needs no coordinator. The prompt is pasted into the target composer and submitted; delivery is refused only when there is physically nothing to write to (no such tab, dead PTY, no engine process). A `succeeded:` report sent from a managed task whose branch has 0 commits is REFUSED (EMPTY_SUCCESS_REPORT) \u2014 commit first, or pass --allow-empty when the task genuinely produced no commits.",flags:[F.taskId(!1),F.prompt(!0,"Text pasted + submitted into the engine pane."),F.promptFile(),{name:"tab",type:"string",required:!1,placeholder:"TAB",description:'Tab addressing: "new" spawns the prompt in a fresh engine tab; "tab-N" delivers to that exact alive tab (error when dead/absent). Omitted = the canonical engine tab.'},{...F.command(),description:"Engine launch command for a `--tab new` tab \u2014 the API twin of the TUI's ctrl+e pick. Lets one worktree run two agents on the same files (e.g. hand the stuck work to codex without leaving the branch). An engine id from `engine-list` or a full command line; pinned to that tab, so it survives restarts and a later set-command on the task. Only valid with --tab new."},{name:"respawn",type:"bool",required:!1,description:"Revive a FREEZE-RESTORED --tab tab-N before delivering. After a pty-host restart (reboot, crash) a tab keeps its scrollback and launch command but nothing runs in it; without this flag such a tab is refused (TAB_RESTORED) rather than silently re-run. With it, the tab is respawned in place and resumes its pinned conversation when it has one (`get-task` shows each tab's sessionId) \u2014 a tab with none replays its recorded launch command, which for claude carries the task's original first prompt. Only valid with --tab tab-N."},{name:"plain",type:"bool",required:!1,description:"Deliver the prompt verbatim \u2014 skip the [ROVE PEER] provenance prefix."},{name:"allow-empty",type:"bool",required:!1,description:"Report success from a task with zero commits (EMPTY_SUCCESS_REPORT is refused otherwise). For work that legitimately produces no commits \u2014 an investigation, a review, a question answered."}],handler:send},DISPATCH_VERB,INTERRUPT_VERB,{name:"note",group:"drive",summary:"File a one-line field note \u2014 a resolved, repo-level gotcha worth sharing. Appended to the repo's durable note store (every future session on this repo starts with it) and forwarded to the dispatcher session for live relay (docs/design/dispatcher.md).",flags:[F.taskId(!0),{name:"text",type:"string",required:!0,placeholder:"TEXT",description:"One line: the verified conclusion another session could act on."}],handler:note},{name:"note-list",group:"drive",summary:"Read a repo's accumulated field notes, newest first. Returns { notes } \u2014 each with the `id` note-delete takes.",flags:[F.repo(!0)],handler:(ctx)=>simpleRpc(ctx,"note.list",{repo:ctx.args.requireRepo("repo")})},{name:"note-delete",group:"drive",summary:"Retire one field note by the id `note-list` reports. The note store is not an archive: its newest entries are injected into every fresh session on the repo, so a note whose fact has stopped being true keeps being handed to agents as if it still were. Returns { deleted } \u2014 false (not an error) when the id names nothing, which is also what an already-evicted note answers.",flags:[F.repo(!0),{name:"id",type:"int",required:!0,placeholder:"N",description:"Note id from `note-list`."}],handler:(ctx)=>simpleRpc(ctx,"note.delete",{repo:ctx.args.requireRepo("repo"),id:ctx.args.int("id")})},PANE_VERB,PANE_CLOSE_VERB,TAB_CLOSE_VERB,{name:"notify",group:"drive",summary:"Show a toast in every attached Rove UI \u2014 broadcast over the daemon's notice.event channel. Agents/scripts use it to surface 'done / needs input / error' moments without touching the task's session. Returns `clients` (attached connections; 0 = no UI showed the toast).",flags:[{name:"title",type:"string",required:!0,placeholder:"TEXT",description:"Toast text (one line)."},{name:"body",type:"string",placeholder:"TEXT",description:"Optional second line under the title \u2014 context, not a second message."},{name:"kind",type:"string",default:"done",placeholder:"KIND",description:`Free-form kind tag. "done", "needs_input" and "error" get the TUI's severity styling/unread mark; any other value renders neutrally.`},F.taskId(!1),{name:"source",type:"string",placeholder:"TAG",description:"Free-form origin tag (e.g. an agent name) recorded on the event."}],handler:async(ctx)=>{return simpleRpc(ctx,"notice.send",{title:ctx.args.str("title"),body:ctx.args.str("body"),kind:ctx.args.str("kind")??"done",taskId:ctx.args.str("task-id"),source:ctx.args.str("source")})}},{name:"prompt",group:"drive",summary:"Ask the human for a line of text through the attached TUI's input dialog (plugins' host-provided prompt). Blocks until answered, cancelled, or timed out; returns { value } or { cancelled, reason }.",flags:[{name:"title",type:"string",required:!0,placeholder:"TEXT",description:"Dialog title (shown verbatim)."},{name:"placeholder",type:"string",placeholder:"TEXT",description:"Input placeholder."},{name:"initial",type:"string",placeholder:"TEXT",description:"Pre-filled input value."},{name:"timeout",type:"string",placeholder:"MS",description:"Give up after this many milliseconds (default 120000, max 600000)."}],handler:async(ctx)=>{let timeoutRaw=ctx.args.str("timeout"),timeoutMs=timeoutRaw?Number.parseInt(timeoutRaw,10):void 0;return simpleRpc(ctx,"ui.prompt",{title:ctx.args.str("title"),placeholder:ctx.args.str("placeholder"),initial:ctx.args.str("initial"),...timeoutMs&&Number.isFinite(timeoutMs)?{timeoutMs}:{}})}},{name:"engine-report",group:"drive",summary:"Report a normalized engine-activity verb for a task \u2014 the public face of the same engine.reportEvent RPC the built-in hook adapters use. Lets a plugin-contributed engine (or any wrapper script) drive the sidebar badge, attention inbox, and plugin event stream without a built-in hook adapter. Kinds: session-start|turn-start|turn-complete|turn-failed|turn-interrupted|awaiting-input|session-end (state kinds) plus tool-pre|tool-post|tool-failed|pre-compact|post-compact|subagent-start|subagent-stop (plugin-only).",flags:[F.taskId(!1),{name:"kind",type:"enum",values:ENGINE_ACTIVITY_KINDS,required:!0,placeholder:"KIND",description:"Normalized activity verb (see summary). Unknown kinds are rejected."},{name:"engine",type:"string",placeholder:"ID",description:"Engine id producing the report (a plugin engine id, or a built-in vendor)."},{name:"tab",type:"string",placeholder:"TAB",description:"Terminal tab id the session runs in (defaults to $ROVE_TAB_ID / $KOBE_TAB_ID)."},{name:"detail",type:"string",placeholder:"JSON",description:`Optional detail JSON, e.g. '{"failure":"rate_limit"}' or '{"waiting":"input"}'.`}],handler:async(ctx)=>{let taskId=ctx.args.str("task-id")??process.env.ROVE_TASK_ID??process.env.KOBE_TASK_ID,tabId=ctx.args.str("tab")??process.env.ROVE_TAB_ID??process.env.KOBE_TAB_ID,detailRaw=ctx.args.str("detail"),detail;if(detailRaw!==void 0)try{detail=JSON.parse(detailRaw)}catch{throw new ApiError("--detail must be valid JSON","BAD_FLAG",helpStep("engine-report"))}return simpleRpc(ctx,"engine.reportEvent",{kind:ctx.args.str("kind"),...taskId?{taskId}:{cwd:process.cwd()},...ctx.args.str("engine")?{engine:ctx.args.str("engine")}:{},...tabId?{tabId}:{},...detail!==void 0?{detail}:{}})}},{name:"set-active",group:"drive",summary:"Set the shared active task (the focus every Tasks pane highlights). Pass --none to clear.",flags:[F.taskId(!1),{name:"none",type:"bool",description:"Clear the active task instead of setting one."}],handler:setActive}];async function renameTaskOrTab(ctx){let taskId=ctx.args.require("task-id"),title=ctx.args.require("title"),tabId=ctx.args.str("tab");if(tabId===void 0)return simpleRpc(ctx,"task.rename",{taskId,title});if(!renameTabsSnapshot(taskId,tabId,title))throw new ApiError(`task ${taskId} has no tab ${tabId}`,"TAB_NOT_FOUND",{hint:"`get-task` lists the addressable tab ids in .tabs[].id",nextCommandArgs:["api","get-task","--task-id",taskId]});let reply=await daemonOf(ctx).request("terminalTab.rename",{taskId,tabId,title});return{ok:!0,taskId,tabId,title,renamed:!0,clients:reply.clients??0}}var EDIT_VERBS=[{name:"rename",group:"edit",summary:"Set a task's title, or with --tab one Terminal Tab's name \u2014 the API twin of the TUI's f2. Tab lifecycle is otherwise symmetric already (pane-open / tab-close / read-output --tab / send --tab), so naming was the one thing an agent could not do to a tab it had opened. An attached TUI repaints its tab strip; with none attached the persisted snapshot carries the name to the next mount.",flags:[F.taskId(),{name:"title",type:"string",required:!0,placeholder:"T",description:"New title."},{name:"tab",type:"string",placeholder:"TAB",description:"Rename this Terminal Tab (id from `get-task` .tabs[].id, e.g. tab-2) instead of the task. TAB_NOT_FOUND when the task's snapshot names no such tab."}],handler:renameTaskOrTab},{name:"set-branch",group:"edit",summary:"Rename a task's branch (git branch -m if materialized, else recorded).",flags:[F.taskId(),{name:"branch",type:"string",required:!0,placeholder:"B",description:"New branch name."}],handler:(ctx)=>simpleRpc(ctx,"task.setBranch",{taskId:ctx.args.require("task-id"),branch:ctx.args.require("branch")})},SET_COMMAND_VERB,SET_EFFORT_VERB,{name:"set-status",group:"edit",summary:"Set a task's lifecycle LABEL, and optionally record what the worker DELIVERED. The status half is cosmetic \u2014 the task row, its worktree, its branch and its engine session all stay exactly as they are, so `--status canceled` does NOT close, stop, or clean up anything. To end a task use `delete` (which keeps the git branch). The --report-* half writes `.report` on the task ({ branch?, pr?, summary?, at }), readable from `get-task` and `collect`: it is what the WORKER CLAIMS, and is deliberately not the same field as `.prStatus`, which the daemon POLLED from the forge \u2014 a worker can report a PR number that does not exist, and a dispatcher deciding whether to land needs to know which of the two it is reading. Report fields merge onto any previous report and restamp `at`, so a follow-up naming only --report-pr keeps the branch reported earlier.",flags:[F.taskId(),{name:"status",type:"enum",required:!0,values:TASK_STATUSES,description:"New status."},{name:"report-branch",type:"string",placeholder:"B",description:"The branch the worker says holds the work (a CLAIM \u2014 `.branch` is the task's actual branch)."},{name:"report-pr",type:"int",placeholder:"N",description:"The PR number the worker says it opened (a CLAIM \u2014 `.prStatus.number` is what the daemon read from the forge)."},{name:"report-summary",type:"string",placeholder:"TEXT",description:"One line of what was delivered."}],handler:(ctx)=>simpleRpc(ctx,"task.status",{taskId:ctx.args.require("task-id"),status:ctx.args.requireEnum("status"),reportBranch:ctx.args.str("report-branch"),reportPr:ctx.args.int("report-pr"),reportSummary:ctx.args.str("report-summary")})}];async function collect(ctx){let daemon=daemonOf(ctx),{args,runtime}=ctx,idsFlag=args.str("task-ids"),repoFlag=args.path("repo"),groupFlag=args.str("group"),taskIds,unresolvableRepos=[];if(idsFlag)taskIds=idsFlag.split(",").map((s)=>s.trim()).filter(Boolean);else if(repoFlag||groupFlag){let{tasks}=await daemon.request("task.list"),filter=repoFlag?await repoFilter(runtime,repoFlag,tasks.map((t)=>t.repo)):null;unresolvableRepos=filter?.unresolvableRepos??[],taskIds=[];for(let t of tasks){if(groupFlag&&t.groupId!==groupFlag)continue;if(filter&&!filter.matches(t.repo))continue;taskIds.push(t.id)}}else throw new ApiError("collect needs --task-ids id1,id2, --group GROUPID, or --repo PATH","MISSING_TARGET");let registry=null;try{registry=(await daemon.request("debug.inspect"))?.activity?.tasks??{}}catch{registry=null}let out=[];for(let taskId of taskIds){let{task}=await daemon.request("task.get",{taskId}),{tabs,running}=await runtime.taskTabs(taskId,taskEngineArgv(task)),changes=task.worktreePath?await runtime.readWorktreeChanges(task.worktreePath):null,base=task.worktreePath?await runtime.readBranchSignals(task.worktreePath,task.baseRef):{baseRef:null,ahead:null,behind:null,diff:null},entry=registry?.[task.id],activity=entry?{state:entry.state,at:new Date(entry.at).toISOString(),forMs:Math.max(0,Date.now()-entry.at)}:null;out.push({taskId:task.id,title:task.title,branch:task.branch,worktreePath:task.worktreePath,vendor:task.vendor,status:task.status,...task.groupId?{groupId:task.groupId}:{},...task.report?{report:task.report}:{},...task.dispatcher?{dispatcher:task.dispatcher}:{},running,activity,tabs,changes,base})}return{tasks:out,...unresolvableRepos.length>0?{unresolvableRepos}:{}}}async function feedback(ctx){return{ok:!0,discussion:submitFeedback({title:ctx.args.require("title"),body:ctx.args.require("body"),categorySlug:ctx.args.str("category")})}}var FEEDBACK_VERBS=[{name:"feedback",group:"feedback",summary:"Create a GitHub Discussion in the Rove repo's Feedback category through `gh`.",flags:[{name:"title",type:"string",required:!0,placeholder:"T",description:"Discussion title."},{name:"body",type:"string",required:!0,placeholder:"TEXT",description:"Discussion body."},{name:"category",type:"string",default:DEFAULT_FEEDBACK_CATEGORY_SLUG,placeholder:"SLUG",description:"Discussion category slug."}],offline:!0,handler:feedback}];var ISSUE_STATUSES=["open","doing","hold","done"],ISSUE_VERBS=[{name:"issue-list",group:"issues",summary:"List daemon-owned issues for a repo.",flags:[F.repo()],handler:(ctx)=>simpleRpc(ctx,"issue.list",{repoRoot:ctx.args.requireRepo("repo")})},{name:"issue-create",group:"issues",summary:"Create a daemon-owned issue for a repo.",flags:[F.repo(),{name:"title",type:"string",required:!0,placeholder:"T",description:"Issue title."},{name:"body",type:"string",placeholder:"TEXT",description:"Issue body."}],handler:(ctx)=>simpleRpc(ctx,"issue.mutate",{repoRoot:ctx.args.requireRepo("repo"),op:{type:"create",title:ctx.args.require("title"),body:ctx.args.str("body")}})},{name:"issue-set-status",group:"issues",summary:"Set a daemon-owned issue's status.",flags:[F.repo(),{name:"id",type:"int",required:!0,placeholder:"N",description:"Issue id."},{name:"status",type:"enum",required:!0,values:ISSUE_STATUSES,description:"New issue status."}],handler:(ctx)=>simpleRpc(ctx,"issue.mutate",{repoRoot:ctx.args.requireRepo("repo"),op:{type:"setStatus",id:ctx.args.int("id"),status:ctx.args.requireEnum("status")}})},{name:"issue-update",group:"issues",summary:"Update a daemon-owned issue's title, body, and/or linked task.",flags:[F.repo(),{name:"id",type:"int",required:!0,placeholder:"N",description:"Issue id."},{name:"title",type:"string",placeholder:"T",description:"New title."},{name:"body",type:"string",placeholder:"TEXT",description:"New body."},{name:"task",type:"string",placeholder:"TASK_ID",description:"Link the issue to this task (kanban: In progress). Pass `none` to unlink."}],handler:issueUpdate},{name:"issue-delete",group:"issues",summary:"Delete a daemon-owned issue. Removes ONLY the tracker record \u2014 a linked task, its branch and its worktree are left untouched. The same `delete` op the kanban page's `d` runs; use `issue-set-status --status done` when the story was finished rather than abandoned.",flags:[F.repo(),{name:"id",type:"int",required:!0,placeholder:"N",description:"Issue id."}],handler:(ctx)=>simpleRpc(ctx,"issue.mutate",{repoRoot:ctx.args.requireRepo("repo"),op:{type:"delete",id:ctx.args.int("id")}})}];import{spawnSync}from"child_process";var REMOTE_TIMEOUT_MS=30000;function git(cwd,args,timeoutMs){try{let out=spawnSync("git",[...args],{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:readOnlyGitProcessEnv(),...timeoutMs===void 0?{}:{timeout:timeoutMs}});return{ok:out.status===0,stdout:(out.stdout??"").trim(),stderr:(out.stderr??"").trim()||(out.status===null?`git ${args[0]} did not finish`:"")}}catch(err){return{ok:!1,stdout:"",stderr:err instanceof Error?err.message:String(err)}}}function localBranchExists(repo,branch){return git(repo,["show-ref","--verify","--quiet",`refs/heads/${branch}`]).ok}function remoteFor(repo,branch){let configured=git(repo,["config","--get",`branch.${branch}.remote`]);return configured.ok&&configured.stdout.length>0?configured.stdout:"origin"}function deleteRemoteBranch(repo,branch){let name=remoteFor(repo,branch),push=git(repo,["push",name,"--delete",branch],REMOTE_TIMEOUT_MS);if(push.ok)return{name,deleted:!0};let remaining=git(repo,["ls-remote","--heads",name,branch],REMOTE_TIMEOUT_MS);if(remaining.ok&&remaining.stdout.length===0)return{name,deleted:!0};return{name,deleted:!1,error:push.stderr||"git push exited non-zero"}}function reportBranchDeletion(repo,branch,opts){if(!branch||!opts.deleteBranch&&!opts.deleteRemote)return;let deleted=!0,keptReason;if(opts.deleteBranch){if(localBranchExists(repo,branch)){let retry=git(repo,["branch",opts.force?"-D":"-d",branch]);if(deleted=retry.ok||!localBranchExists(repo,branch),!deleted)keptReason=retry.stderr||retry.stdout||"git branch refused the delete"}}else deleted=!localBranchExists(repo,branch);return{branch,deleted,...keptReason?{keptReason}:{},...opts.deleteRemote?{remote:deleteRemoteBranch(repo,branch)}:{}}}var DELETE_WAIT_TIMEOUT_MS=60000,DELETE_POLL_INTERVAL_MS=250;async function deleteTask(ctx){let daemon=daemonOf(ctx),groupId=ctx.args.str("group"),taskIdFlag=ctx.args.str("task-id");if(groupId&&taskIdFlag)throw new ApiError("pass --task-id or --group, not both","BAD_FLAG");if(!groupId&&!taskIdFlag)throw new ApiError("delete needs --task-id ID or --group GROUPID","MISSING_TARGET");let self=await verifiedSelfSession();if(!groupId)return deleteOne(ctx,taskIdFlag,self);let{tasks}=await daemon.request("task.list"),members=tasks.filter((t)=>t.groupId===groupId);if(members.length===0)throw new ApiError(`no tasks in group ${groupId}`,"TASK_NOT_FOUND",{hint:"the groupId is the one `add --count` returned; any surviving sibling's `.groupId` in `list` recovers it",nextCommandArgs:["api","list"]});let results=[];for(let task of members)try{results.push(await deleteOne(ctx,task.id,self))}catch(err){let message=errorMessage(err),code=err instanceof ApiError?err.code:splitDaemonCode(message)?.code;results.push({taskId:task.id,status:"failed",error:message,...code?{code}:{}})}let failures=results.filter((r)=>r.status==="failed").length;return{groupId,count:members.length,failures,results}}async function deleteOne(ctx,taskId,self){let daemon=daemonOf(ctx),force=ctx.args.bool("force")??!1,deleteBranch=ctx.args.bool("delete-branch")??!1,deleteRemote=ctx.args.bool("delete-remote")??!1,subject=deleteBranch||deleteRemote?(await daemon.request("task.get",{taskId})).task:void 0,res;try{res=await daemon.request("task.delete",{taskId,force,deleteBranch,...self?{requestedByTaskId:self.taskId,requestedByTabId:self.tabId}:{}})}catch(err){throw deleteRecoveryError(err,taskId)}if(await ctx.runtime.tearDownSession(taskId),!res.queued)return{...res,status:"not_found"};if(!ctx.args.bool("wait")&&!subject)return{...res,status:"queued"};let outcome=await awaitDeletion(daemon,taskId),branch=subject&&outcome.status==="removed"?reportBranchDeletion(subject.repo,subject.branch??"",{deleteBranch,force,deleteRemote}):void 0;return{...res,...outcome,...branch?{branch}:{}}}async function awaitDeletion(daemon,taskId){let deadline=Date.now()+DELETE_WAIT_TIMEOUT_MS;for(;;){let{tasks}=await daemon.request("task.list"),task=tasks.find((t)=>t.id===taskId);if(!task)return{status:"removed"};let deletion=task.deletion;if(deletion?.phase==="error")return{status:"failed",error:deletion.error??"worktree removal failed"};if(Date.now()>=deadline)return{status:"pending"};await new Promise((resolve2)=>setTimeout(resolve2,DELETE_POLL_INTERVAL_MS))}}async function land(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id");if(ctx.args.bool("dry-run")===!0)return(await daemon.request("task.landPreflight",{taskId})).result;let strategy=ctx.args.str("strategy")==="squash"?"squash":"merge",res;try{res=await daemon.request("task.land",{taskId,strategy,deleteBranch:ctx.args.bool("delete-branch")??!1,removeWorktree:ctx.args.bool("remove-worktree"),callerCwd:process.cwd()})}catch(err){throw landRecoveryError(err,taskId)}return{ok:!0,taskId,...res.result}}function landRecoveryError(err,taskId){let message=errorMessage(err);if(!message.includes(EMPTY_BRANCH_DIRTY_WORKTREE_CODE))return err;let branch=/EMPTY_BRANCH_DIRTY_WORKTREE: '([^']+)'/.exec(message)?.[1]??"your task branch";return new ApiError(splitDaemonCode(message)?.rest??message,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,{hint:"the worker wrote files but never committed them \u2014 send it back to commit its own work, then land again",nextCommandArgs:["api","send","--task-id",taskId,"--prompt",`your work is uncommitted on ${branch} \u2014 commit it yourself with a proper message, then report back`]})}function deleteRecoveryError(err,taskId){let message=errorMessage(err),coded=splitDaemonCode(message);if(coded?.code!==DIRTY_WORKTREE_CODE)return err;return new ApiError(coded.rest,DIRTY_WORKTREE_CODE,{taskId,hint:"the worktree still holds work this delete would destroy \u2014 the message names it, and a gitignored path never shows in `git status`. Send the worker back to commit it, or pass --force to delete the task AND discard that work",nextCommandArgs:["api","send","--task-id",taskId,"--prompt","your worktree still holds work that this cleanup would destroy (it may be gitignored, so `git status` will not show it \u2014 check `git status --ignored`). Commit it yourself with a proper message, then report back"]})}async function removeTaskWorktree(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),force=ctx.args.bool("force")??!1,{task}=await daemon.request("task.get",{taskId}),worktreePath=(task.worktreePath??"").trim();if(!worktreePath)throw new ApiError(`task ${taskId} has no worktree on disk`,"NO_WORKTREE",{hint:"nothing to remove \u2014 `ensure-worktree` materialises one"});let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(task.repo)))throw new ApiError(`refusing to remove ${worktreePath} \u2014 it is the project's own checkout, not a Rove worktree`,"BASE_CHECKOUT");if(pathWithin(wt,canonicalize(process.cwd()))!==null)throw new ApiError(`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`,"CALLER_WORKTREE");let res=await daemon.request("worktree.remove",{path:worktreePath,force});return{ok:!0,taskId,worktreePath,branch:task.branch,...res}}async function adopt(ctx){let daemon=daemonOf(ctx),{args}=ctx,input={repo:args.requireRepo("repo"),worktreePath:args.requirePath("worktree")},branch=args.str("branch");if(branch)input.branch=branch;let command=args.str("command");if(command)input.command=command,input.vendor=resolveCommandProtocol(command);let title=args.str("title");if(title)input.title=title;return daemon.request("worktree.adopt",input)}var LIFECYCLE_VERBS=[{name:"pin",group:"lifecycle",summary:"Pin (or with --pinned=false, unpin) a task to the top of the sidebar.",flags:[F.taskId(),{name:"pinned",type:"bool",default:"true",description:"true to pin, false to unpin."}],handler:(ctx)=>simpleRpc(ctx,"task.pin",{taskId:ctx.args.require("task-id"),pinned:ctx.args.bool("pinned")??!0})},{name:"land",group:"lifecycle",summary:"Merge a task's branch back into its base repo's current branch. Refuses a dirty base checkout, a branch that no longer resolves in the base repo (MISSING_REF \u2014 renamed or deleted outside Rove), and a branch with zero commits ahead of the base (EMPTY_BRANCH; EMPTY_BRANCH_DIRTY_WORKTREE with a send-back recovery path when the worktree still holds the uncommitted work). On conflict, aborts and returns the conflicted files (resolve by hand). Returns { landedOn, commit }.",flags:[F.taskId(),{name:"dry-run",type:"bool",description:"Report whether the land would proceed, and write nothing. Returns { branch, landedOn, ahead?, baseDirty?, refusal?, dirtyFiles?, baseDir } \u2014 `landedOn` is the base checkout's CURRENT branch (the merge destination), `ahead` the commits that would land, and `refusal` one of DETACHED_HEAD, UNREADABLE_BASE, UNBORN_BASE, SAME_BRANCH, MAIN_CHECKOUT_DIRTY, MISSING_REF, EMPTY_BRANCH, EMPTY_BRANCH_DIRTY_WORKTREE when the land would be refused. Ignores --strategy/--delete-branch/--remove-worktree."},{name:"strategy",type:"enum",values:["merge","squash"],default:"merge",description:"merge (--no-ff) or squash into one commit."},{name:"delete-branch",type:"bool",description:"Delete the task's branch after a successful land. Uses `git branch -D`, which drops the branch's reflog too; with --strategy squash the base's new commit does not reach the branch's own commits, so Rove first anchors the tip at refs/rove/salvage/<branch>-<stamp> and returns it as `branchAnchor`. Requires the worktree to be gone: git refuses to delete a branch a live worktree has checked out, so a land that kept the worktree keeps the branch too and says so in `branchKept`."},{name:"remove-worktree",type:"bool",default:"true",description:"Remove the task's worktree after a successful land (default; the branch always stays). Pass --remove-worktree=false to keep it. Dirty worktrees, the base checkout, and the caller's own worktree are refused \u2014 the outcome is reported in the result's `worktree` field, never thrown."}],handler:land},{name:"delete",group:"lifecycle",summary:"Remove a task and its worktree; the git branch stays unless --delete-branch. Needs --force on a dirty worktree. Returns { queued } \u2014 removal itself runs in the background; add --wait for the resolved outcome. With --delete-branch / --delete-remote the reply also carries `branch` \u2014 { branch, deleted, keptReason?, remote? } \u2014 so `the branch went with it` is a fact you read rather than an assumption. Pass --group instead of --task-id to close a whole fan-out round in one call: it returns { groupId, count, failures, results } with one entry per sibling, and a refusal on one (a dirty worktree) is recorded there rather than aborting the rest.",flags:[F.taskId(!1),{name:"group",type:"string",placeholder:"GROUPID",description:"Delete every task of one fan-out round (the `groupId` that `add --count` returns, the same selector `collect --group` takes). Mutually exclusive with --task-id."},{name:"force",type:"bool",description:"Delete even with uncommitted changes (never implies --delete-branch)."},{name:"delete-branch",type:"bool",description:"Also delete the task's LOCAL git branch (default: keep it). The outcome is reported in the result's `branch` field \u2014 `{ deleted, keptReason? }` \u2014 because git legitimately refuses (unmerged work, a sibling worktree holding the branch) and that refusal used to reach daemon.log and nowhere a caller could read it. Implies --wait: a branch verdict read before the worktree is gone describes the worktree, not the branch."},{name:"delete-remote",type:"bool",description:"Also `git push --delete` the branch on its remote (its own `branch.<name>.remote`, else origin). A SEPARATE opt-in that --delete-branch never implies: a local branch is recoverable from any clone that still has it, a remote one is recoverable by nobody and its deletion closes any open PR. Reported in `branch.remote` \u2014 `{ name, deleted, error? }`. Implies --wait."},{name:"wait",type:"bool",description:"Follow the background removal and report its OUTCOME (removed / failed / pending) instead of returning as soon as it is queued."}],handler:deleteTask}];var DEFAULT_SINCE_DAYS=7,DEFAULT_LIMIT=200;function summarizeTurns(turns){let byModel={},inputTokens=0,outputTokens=0,cacheReadTokens=0,cacheCreationTokens=0,durationMs=0;for(let turn of turns){inputTokens+=turn.usage?.input_tokens??0,outputTokens+=turn.usage?.output_tokens??0,cacheReadTokens+=turn.usage?.cache_read_input_tokens??0,cacheCreationTokens+=turn.usage?.cache_creation_input_tokens??0,durationMs+=Math.max(0,turn.endedAt-turn.startedAt);let model=turn.model??"unknown";byModel[model]=(byModel[model]??0)+1}return{turns:turns.length,inputTokens,outputTokens,cacheReadTokens,cacheCreationTokens,durationMs,byModel}}async function agentTurns(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.str("task-id"),repoPath=ctx.args.path("repo"),repo=repoPath?await ctx.runtime.resolveRepoRoot(repoPath):void 0,sinceDays=ctx.args.int("since-days")??DEFAULT_SINCE_DAYS,since=Date.now()-sinceDays*24*60*60*1000,limit=ctx.args.int("limit")??DEFAULT_LIMIT,{turns}=await daemon.request("agentTurn.list",{...taskId?{taskId}:{},...repo?{repoRoot:repo}:{},since,limit});return{since:new Date(since).toISOString(),totals:summarizeTurns(turns),turns}}var AGENT_TURNS_VERB={name:"agent-turns",group:"read",summary:`Per-turn agent telemetry: one record per completed engine turn (task/tab/vendor/model/timings/tokens), newest first, plus totals. Engine-produced, daemon-stored; read-only. Engines that report turns: ${vendorsWithTurnReader().join(", ")} \u2014 a task on any other engine yields an empty page because that engine has no turn reader, not because it did no work.`,flags:[{name:"task-id",type:"string",placeholder:"ID",description:"Only this task's turns."},{name:"repo",type:"string",placeholder:"PATH",description:"Only turns of tasks in this repo. Relative paths resolve against $PWD."},{name:"since-days",type:"int",default:String(DEFAULT_SINCE_DAYS),placeholder:"N",description:"Look-back window in days."},{name:"limit",type:"int",default:String(DEFAULT_LIMIT),placeholder:"N",description:"Max turns returned."}],handler:agentTurns};var DEFAULT_SINCE_DAYS2=7;function epochOf(iso){if(!iso)return null;let ms=Date.parse(iso);return Number.isNaN(ms)?null:ms}function buildDigest(repo,sinceMs,tasks,runs){let byStatus={};for(let run of runs)byStatus[run.status]=(byStatus[run.status]??0)+1;return{repo,since:new Date(sinceMs).toISOString(),tasks:{total:tasks.length},routines:{runs:runs.length,byStatus}}}async function digest(ctx){let daemon=daemonOf(ctx),{args,runtime}=ctx,repoFlag=args.requireRepo("repo"),sinceMs=Date.now()-(args.int("since-days")??DEFAULT_SINCE_DAYS2)*86400000,{tasks:allTasks}=await daemon.request("task.list"),{automations}=await daemon.request("automation.list"),filter=await repoFilter(runtime,repoFlag,[...allTasks.map((t)=>t.repo),...automations.map((a)=>a.repo)]),repo=filter.target,tasks=[];for(let task of allTasks){if((task.kind??"task")!=="task")continue;if((epochOf(task.updatedAt)??0)<sinceMs)continue;if(filter.matches(task.repo))tasks.push(task)}let runs=[];for(let automation of automations){if(!filter.matches(automation.repo))continue;let page=await daemon.request("automation.runs",{id:automation.id});for(let run of page.runs)if((epochOf(run.at)??0)>=sinceMs)runs.push(run)}return{...buildDigest(repo,sinceMs,tasks,runs),...filter.unresolvableRepos.length>0?{unresolvableRepos:filter.unresolvableRepos}:{}}}var DIGEST_VERB={name:"digest",group:"read",summary:"Aggregate a repo's recent agent work: tasks touched in the window plus routine run outcomes. Reads state Rove already persists \u2014 the measurement any workflow change has to move.",flags:[{name:"repo",type:"string",required:!0,placeholder:"PATH",description:"Repo root (git toplevel). Relative paths resolve against $PWD."},{name:"since-days",type:"int",default:String(DEFAULT_SINCE_DAYS2),placeholder:"N",description:"Look-back window in days."}],handler:digest};async function daemonSection(){let{connectIfRunning}=await import("./chunk-d4fvkzp3.js"),client=null;try{if(client=await connectIfRunning(),!client)return null;return await client.request("debug.inspect",{})}catch(err){return{error:err instanceof Error?err.message:String(err)}}finally{client?.close()}}async function sessionsSection(taskId){let[{KobeDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-ydhngxy3.js"),import("./chunk-r1mp0eb2.js")]),client=new KobeDaemonClient(defaultPtyHostSocketPath()),sessions;try{await client.connect(),sessions=(await client.request("pty.list",{})).sessions??[]}catch{return null}finally{client.close()}if(taskId)sessions=sessions.filter((s)=>s.key.startsWith(`${taskId}::`));let rows=null;try{let pids=sessions.map((s)=>s.pid).filter((pid)=>typeof pid==="number"&&pid>0);rows=parsePsSnapshot(await psSnapshot(pids))}catch{rows=null}return sessions.map((s)=>{let walkable=rows!==null&&typeof s.pid==="number"&&s.pid>0,found=walkable&&rows?foregroundEngineIn(rows,s.pid):null;return{key:s.key,alive:s.alive,pid:s.pid??null,title:s.title||null,exit:s.exit??null,foreground:walkable?found?{vendor:found.vendor,pid:found.pid,argv:found.argv}:null:"unknown"}})}async function sessionExitsSection(taskId){try{let{readPtyExitRecords}=await import("./chunk-var92s38.js"),records=Object.values(readPtyExitRecords()).sort((a,b)=>a.at<b.at?1:-1);return taskId?records.filter((r)=>r.key.startsWith(`${taskId}::`)):records}catch(err){return{error:err instanceof Error?err.message:String(err)}}}function tabsSection(taskId,sessions){let live=Array.isArray(sessions)?sessions.filter((s)=>typeof s?.key==="string"):[];try{let state=loadStateFile(),out={},prefix="terminalTabs.";for(let[key,value]of Object.entries(state)){if(!key.startsWith("terminalTabs."))continue;let id=key.slice(13);if(taskId&&id!==taskId)continue;let snap=value;if(!snap||!Array.isArray(snap.tabs))continue;let unregistered=unregisteredTabIds(snap,id,live);out[id]={activeId:snap.activeId,tabs:snap.tabs.map((t)=>({id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null})),...unregistered.length>0?{unregistered}:{}}}for(let s of live){let id=s.key.split("::")[0]??"";if(!id||out[id]!==void 0||taskId&&id!==taskId)continue;let unregistered=unregisteredTabIds(void 0,id,live);if(unregistered.length>0)out[id]={activeId:null,tabs:[],unregistered}}return out}catch(err){return{error:err instanceof Error?err.message:String(err)}}}async function inspect(ctx){let taskId=ctx.args.str("task-id"),[daemon,sessions,sessionExits]=await Promise.all([daemonSection(),sessionsSection(taskId),sessionExitsSection(taskId)]);return{daemon,sessions,sessionExits,tabs:tabsSection(taskId,sessions),at:new Date().toISOString()}}var INSPECT_VERB={name:"inspect",group:"read",summary:"Production diagnostics in one read: daemon activity registry (raw states, probe vendors, watchdogs), pty-host sessions joined with a live process-tree engine walk, durable session death records (exit code/signal/output tail), and the persisted tab snapshots the sidebar renders from. Read-only; missing daemon/host degrade to null.",flags:[F.taskId(!1)],offline:!0,handler:inspect};var WATCHABLE_STATES=["idle","running","turn_complete","rate_limited","permission_needed","error","dead"],HEARTBEAT_MS=5000,DEFAULT_TIMEOUT_MS=300000;async function resolveTaskIds(ctx){let ids=ctx.args.str("task-ids"),group=ctx.args.str("group");if(ids&&group)throw new ApiError("pass --task-ids or --group, not both","BAD_FLAG");if(ids){let list2=ids.split(",").map((s)=>s.trim()).filter(Boolean);if(list2.length>0)return list2}if(!group)throw new ApiError("watch needs --task-ids id1,id2 or --group GROUPID","MISSING_TARGET");let{tasks}=await daemonOf(ctx).request("task.list"),members=tasks.filter((t)=>t.groupId===group).map((t)=>t.id);if(members.length===0)throw new ApiError(`no tasks in group ${group}`,"TASK_NOT_FOUND",{hint:"the groupId is the one `add --count` returned; any surviving sibling's `.groupId` in `list` recovers it",nextCommandArgs:["api","list"]});return members}function parseUntil(raw){let states=raw.split(",").map((s)=>s.trim()).filter(Boolean),unknown=states.filter((s)=>!WATCHABLE_STATES.includes(s));if(unknown.length>0)throw new ApiError(`--until names states that do not exist: ${unknown.join(", ")} (valid: ${WATCHABLE_STATES.join(", ")})`,"BAD_FLAG");if(states.length===0)throw new ApiError("--until needs at least one state","BAD_FLAG");return states}async function watch(ctx){let daemon=daemonOf(ctx),taskIds=new Set(await resolveTaskIds(ctx)),until=new Set(parseUntil(ctx.args.require("until"))),timeoutRaw=ctx.args.int("timeout"),timeoutMs=timeoutRaw&&timeoutRaw>0?timeoutRaw:DEFAULT_TIMEOUT_MS;return await new Promise((resolve2,reject)=>{let settled=!1,events=0,seen=new Set,SEEN_CAP=512,finish=(fn)=>{if(settled)return;settled=!0,clearInterval(heartbeat),clearTimeout(deadline),off(),fn()},off=daemon.onChannel("engine-state",(payload)=>{let event=payload;if(!taskIds.has(event.taskId))return;let key=`${event.taskId}::${event.tabId??""}::${event.state}::${event.at}`;if(seen.has(key))return;if(seen.size>=SEEN_CAP)seen.clear();if(seen.add(key),events++,process.stdout.write(`${JSON.stringify({taskId:event.taskId,...event.tabId?{tabId:event.tabId}:{},state:event.state,at:event.at})}
6
+ ${prompt}`}async function deliverToExactTab(rpc,taskId,tabId,cwd,prompt,opts){let key=`${taskId}::${tabId}`,{sessions=[]}=await rpc.request("pty.list",{}),session=sessions.find((s)=>s.key===key);if(!session?.alive){if(session?.restored===!0){if(!opts?.respawn)throw restoredTabError(taskId,tabId,prompt);let launch=opts.respawn(),open=await rpc.request("pty.open",{key,cwd,...launch?{command:launch.command}:{},defaultColors:readPersistedTerminalDefaultColors()});if(open.respawned!==!0&&open.alive!==!0)throw new ApiError(`tab ${tabId} on task ${taskId} could not be respawned`,"SESSION_FAILED",{taskId,tabId,hint:"the frozen record is still on disk; open the task in the TUI to see the session's own output",nextCommandArgs:["api","read-output","--task-id",taskId,"--tab",tabId,"--source","terminal"]});let enginePid=await awaitEngineProcess(rpc,key,opts.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts.snapshot});if(enginePid===null)return{session:key,pane:key,started:!1,respawned:!0,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,key)??ENGINE_NOT_OBSERVED_REASON};return await deliverRespawned(rpc,key,prompt,enginePid.vendor)}throw new ApiError(`tab ${tabId} has no live session on task ${taskId} \u2014 see \`rove api pty-list\` for alive tabs`,"TAB_NOT_FOUND")}let presence=await enginePresence(session.pid,opts?.engineBin,opts?.snapshot);if(presence.kind==="unknown")throw new ApiError(`could not read the process table, so tab ${tabId} on task ${taskId} 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.kind!=="engine")throw new ApiError(`tab ${tabId} on task ${taskId} has no live engine process \u2014 it is a plain shell right now`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new, or pick an engine tab from pty-list",nextCommandArgs:["api","pty-list"]});let outcome=await deliverToKey(rpc,key,prompt,{vendor:presence.vendor});return{session:key,pane:key,started:!1,...outcomeFields(outcome)}}async function deliverRespawned(rpc,key,prompt,vendor){let outcome=await deliverToKey(rpc,key,prompt,{vendor});return{session:key,pane:key,started:!1,respawned:!0,...outcomeFields(outcome)}}function restoredTabError(taskId,tabId,prompt){return new ApiError(`tab ${tabId} on task ${taskId} is a freeze-restored session \u2014 its pty host restarted, so the tab exists with its scrollback but nothing is running in it`,"TAB_RESTORED",{taskId,tabId,hint:"revive it with --respawn (resumes the tab's pinned conversation when it has one \u2014 `get-task` shows `sessionId`; a tab without one replays its recorded launch command)",nextCommandArgs:["api","send","--task-id",taskId,"--tab",tabId,"--respawn","--prompt",prompt]})}function hasLiveEngineTab(snapshot,taskId,sessions,engineAlive,engineBin){let labelled=new Set((snapshot?.tabs??[]).filter((t)=>t.kind==="engine").map((t)=>t.id));return sessions.some((s)=>{if(s.alive!==!0||!isHostedTaskKey(s.key,taskId))return!1;if(engineAlive?.get(s.key)===!1)return!1;if(s.key===`${taskId}::tab-1`)return!0;let tabId=s.key.slice(taskId.length+2);return labelled.has(tabId)||sessionArgvNamesEngine(s.command,engineBin)})}function sessionFailed(taskId,message,hint,extra){return new ApiError(message,"SESSION_FAILED",{taskId,...extra,hint,nextCommandArgs:["api","read-output","--task-id",taskId,"--source","terminal"]})}async function deliverHosted(target,worktree,prompt){let host;try{host=await ensurePtyHost()}catch(error){throw sessionFailed(target.id,`failed to start PTY host for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"no PTY host to run the engine in \u2014 nothing was started; check `rove daemon status`, then retry the same send")}try{if(target.tab&&target.tab!=="new"){let engineBin=engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort})[0],tabId=target.tab;return await deliverToExactTab(host.rpc,target.id,tabId,worktree,prompt,{engineBin,...target.respawn?{respawn:()=>restoredTabLaunch(target,tabId,worktree,process.env.SHELL?.trim()||"/bin/zsh")}:{}})}let newTab=target.tab==="new"?mintCliTab(target.id,target.tabVendor,target.tabCommand):void 0,launchVendor=target.tabVendor??target.vendor,launchCommand=target.tabCommand??(target.tabVendor?void 0:target.command),{argv,sessionId}=withPinnedSessionId(engineLaunchArgv({command:launchCommand,vendor:launchVendor,effort:target.modelEffort}),launchVendor);trustEngineWorktree(launchVendor,worktree);let launch=buildEngineSessionLaunch({task:{id:target.id,kind:target.kind,vendor:launchVendor,repo:target.repo},worktreePath:worktree,shell:process.env.SHELL?.trim()||"/bin/zsh",argv,promptIntent:target.newTask?{kind:"new-task",prompt}:{kind:"explicit",prompt},tabId:newTab}),result=await deliverHostedPrompt(host.rpc,{id:target.id,engineBin:argv[0]},worktree,prompt,launch,{forceNew:newTab!==void 0});if(result.started&&!result.delivered)throw sessionFailed(target.id,`failed to start hosted engine session for ${target.id}`,"the session was created but no engine ran in it \u2014 fix the task's launch command (`api update --command`), then retry with `api send --tab new`",{session:result.session,engineReady:result.engineReady,...result.reason?{reason:result.reason}:{}});if(!newTab)publishCliTabSnapshot(target.id,result.started?sessionId:void 0);if(result.started&&sessionId){let startedTab=newTab??result.session.split("::")[1];if(startedTab)markCliTabSession(target.id,startedTab,sessionId)}return result}catch(error){if(error instanceof ApiError)throw error;throw sessionFailed(target.id,`hosted engine session failed for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"the hosted session threw while starting or delivering \u2014 read its terminal tail for the cause, then retry the send")}finally{host.close()}}var realPromptDeliveryOps={deliverHosted};async function closeHeadlessTerminalTab(taskId,tabId){let host=await openPtyHost();try{let sessions=host?await listSessions(host.rpc):[],saved=readTabsSnapshot(taskId)?.tabs.find((tab)=>tab.id===tabId),directKey=`${taskId}::${tabId}`,unregisteredAlive=sessions.some((session)=>session.key===directKey&&session.alive);if(!saved&&!unregisteredAlive)throw new ApiError(`tab ${tabId} does not exist on task ${taskId}`,"TAB_NOT_FOUND",{hint:"refresh the task's tab ids with get-task, then retry with one of its .tabs[].id values",nextCommandArgs:["api","get-task","--task-id",taskId]});let closing=saved?closeTabsSnapshot(taskId,tabId):void 0;if(saved&&!closing)throw new ApiError(`tab ${tabId} no longer exists on task ${taskId}`,"TAB_NOT_FOUND",{hint:"the tab closed while this command was running; refresh with get-task before retrying",nextCommandArgs:["api","get-task","--task-id",taskId]});let baseKey=closing?tabPtyKeyFor(taskId,closing):directKey,keys=!(closing?.kind==="engine"&&closing.ptyTask)?sessions.filter((session)=>session.key===baseKey||session.key.startsWith(`${baseKey}::`)).map((session)=>session.key):[],wasAlive=sessions.some((session)=>keys.includes(session.key)&&session.alive);if(host)await killTaskSessions(host.rpc,keys);return{kind:closing?.kind??"engine",wasAlive}}finally{host?.close()}}async function deliverPrompt(client,target,prompt,ops=realPromptDeliveryOps){let worktree=target.worktreePath;if(!worktree)worktree=(await client.request("task.ensureWorktree",{taskId:target.id})).worktreePath;if(!worktree)throw new ApiError(`task ${target.id} has no worktree`,"NO_WORKTREE");if(target.newTask)await client.request("task.observeLanguage",{taskId:target.id,text:prompt}).catch(()=>{});let hosted=await ops.deliverHosted(target,worktree,prompt);if(!hosted)throw sessionFailed(target.id,`failed to start hosted engine session for ${target.id}`,"delivery returned nothing \u2014 the task exists but has no session; retry with `api send --tab new`");return hosted}var defaultApiRuntime={isTaskRunning:async(taskId,engineArgv)=>(await defaultApiRuntime.taskTabs(taskId,engineArgv)).running,taskTabs:async(taskId,engineArgv)=>{let listed=null,host=await openPtyHost();if(host)try{listed=await listSessionsOrNull(host.rpc)}finally{host.close()}let sessions=listed??[],hostReachable=listed!==null,liveVendors,engineAlive;try{let{engineProcessIn,foregroundEngineIn:foregroundEngineIn2,parsePsSnapshot:parsePsSnapshot2,psSnapshot:psSnapshot2}=await import("./chunk-8htkv9kd.js"),walkable=sessions.filter((s)=>s.alive&&typeof s.pid==="number"&&s.pid>0);if(walkable.length>0){let rows=parsePsSnapshot2(await psSnapshot2(walkable.map((s)=>s.pid)));liveVendors=new Map(walkable.map((s)=>[s.key,foregroundEngineIn2(rows,s.pid)?.vendor??null])),engineAlive=new Map(walkable.map((s)=>[s.key,engineProcessIn(rows,s.pid,engineArgv)]))}else engineAlive=new Map}catch{}let exits={};try{exits=(await import("./chunk-var92s38.js")).readPtyExitRecords()}catch{}let snapshot=readTabsSnapshot(taskId),sessionIds=new Map((snapshot?.tabs??[]).map((t)=>[t.id,t.sessionId??void 0]));return{tabs:joinTaskTabs(snapshot,taskId,listed,exits,liveVendors,engineAlive).map((row)=>{let sessionId=sessionIds.get(row.id);return sessionId?{...row,sessionId}:row}),running:hostReachable?hasLiveEngineTab(snapshot,taskId,sessions,engineAlive,engineArgv?.[0]):null}},closeTerminalTab:closeHeadlessTerminalTab,deliverPrompt:(client,target,prompt)=>deliverPrompt(client,target,prompt),resolveRepoRoot:async(absPath)=>(await import("./chunk-6txd5jtt.js")).resolveMainRepoRoot(absPath),isUsableRepo:async(absPath)=>{let{isGitRepo,isRemoteRepoKey:isRemoteRepoKey2}=await import("./chunk-6txd5jtt.js");return isRemoteRepoKey2(absPath)||isGitRepo(absPath)},isValidBranchName:async(branch)=>(await import("./chunk-6txd5jtt.js")).isValidBranchName(branch),defaultVendor:async(repo)=>{let{getGlobalDefaultVendor,getRepoLastActiveVendor}=await import("./chunk-na3tmp41.js");return(repo?getRepoLastActiveVendor(repo):void 0)??getGlobalDefaultVendor()},readWorktreeChanges:async(worktreePath)=>(await import("./chunk-s0snbj93.js")).readWorktreeChanges(worktreePath),readBranchSignals:async(worktreePath,recordedBaseRef)=>(await import("./chunk-j4xfsn9g.js")).readBranchSignals(worktreePath,recordedBaseRef),tearDownSession:async(taskId)=>{let host=await openPtyHost();if(host)try{await killTaskSessions(host.rpc,taskKeys(await listSessions(host.rpc),taskId))}catch{}finally{host.close()}}};async function issueUpdate(ctx){let title=ctx.args.str("title"),body=ctx.args.str("body"),task=ctx.args.str("task");if(title===void 0&&body===void 0&&task===void 0)throw new ApiError("issue-update requires --title, --body, and/or --task","MISSING_FLAG");let repoRoot=ctx.args.requireRepo("repo"),id=ctx.args.int("id");return simpleRpc(ctx,"issue.mutate",{repoRoot,op:{type:"update",id,title,body,...task===void 0?{}:{taskId:task==="none"?null:task}}})}async function assertNotEmptySuccess(daemon,ctx,prompt){if(ctx.args.bool("allow-empty"))return;if(!/^\s*succeeded\s*[:\uff1a]/i.test(prompt))return;let self=await verifiedSelfSession();if(!self)return;let sender;try{sender=(await daemon.request("task.get",{taskId:self.taskId})).task}catch{return}if(sender.kind==="main"||sender.kind==="dir")return;if(!sender.worktreePath)return;let ahead;try{ahead=(await ctx.runtime.readBranchSignals(sender.worktreePath,sender.baseRef)).ahead}catch{return}if(ahead!==0)return;let branch=sender.branch||"your branch";throw new ApiError(`refusing to report success: ${branch} has 0 commits \u2014 "succeeded" means COMMITTED, and this report would reach the coordinator as a clean success with nothing to land`,"EMPTY_SUCCESS_REPORT",{taskId:self.taskId,branch,hint:"commit your work with a real message and send again \u2014 or, if this task genuinely produced no commits (an investigation or a review), re-send with --allow-empty to say so explicitly",nextCommandArgs:["api","send",...ctx.args.str("task-id")?["--task-id",ctx.args.str("task-id")]:[],...ctx.args.str("tab")?["--tab",ctx.args.str("tab")]:[],"--allow-empty","--prompt",prompt]})}function requirePromptText(ctx,verb){let text=ctx.args.promptText();if(text===void 0)throw new ApiError("--prompt (or --prompt-file) is required","MISSING_FLAG",helpStep(verb));return text}async function send(ctx){let daemon=daemonOf(ctx),prompt=requirePromptText(ctx,"send"),tab=ctx.args.str("tab");if(tab&&tab!=="new"&&!/^tab-[A-Za-z0-9-]+$/.test(tab))throw new ApiError(`--tab must be "new" or a tab id like tab-2 (got ${JSON.stringify(tab)})`,"BAD_TAB");let tabCommand=ctx.args.str("command");if(tabCommand&&tab!=="new")throw new ApiError(`--command only applies to a new tab; pass --tab new (got --tab ${tab??"<canonical>"})`,"BAD_FLAG",helpStep("send"));let respawn=ctx.args.bool("respawn");if(respawn&&(tab===void 0||tab==="new"))throw new ApiError(`--respawn addresses one frozen tab; pass --tab tab-N (got --tab ${tab??"<canonical>"})`,"BAD_FLAG",helpStep("send"));let tabVendor=tabCommand?resolveCommandProtocol(tabCommand):void 0,taskId=ctx.args.str("task-id");if(!taskId){let dispatcher=await readOwnDispatcher(daemon);if(dispatcher){if(taskId=dispatcher.taskId,tab===void 0)tab=await resolveDispatcherTab(ctx.runtime,dispatcher)}else{let active=await resolveActiveTaskId(daemon);if(!active)throw new ApiError("no --task-id given and no active task \u2014 open a task first or pass --task-id","MISSING_TARGET");taskId=active}}let res=await daemon.request("task.get",{taskId});await assertNotEmptySuccess(daemon,ctx,prompt);let text=ctx.args.bool("plain")?prompt:await withPeerProvenance(daemon,taskId,prompt),delivered=await ctx.runtime.deliverPrompt(daemon,{id:taskId,worktreePath:res.task.worktreePath,kind:res.task.kind,vendor:res.task.vendor,command:res.task.command,modelEffort:tabCommand?void 0:res.task.modelEffort,repo:res.task.repo,tab,tabVendor,tabCommand,respawn},text);if(!delivered.delivered)throw new ApiError(`prompt was not confirmed in ${taskId}'s engine (paste did not land)`,"NOT_DELIVERED");return{ok:!0,taskId,session:delivered.session,started:delivered.started,engineReady:delivered.engineReady,delivered:delivered.delivered,...delivered.bytes===void 0?{}:{bytes:delivered.bytes},...delivered.promptEcho?{promptEcho:delivered.promptEcho}:{},...delivered.reason?{reason:delivered.reason}:{},...delivered.respawned?{respawned:!0}:{},...delivered.frozenTabs?.length?{frozenTabs:delivered.frozenTabs}:{}}}async function dispatch(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),text=requirePromptText(ctx,"dispatch"),tabId=ctx.args.str("tab"),reply=await daemon.request("session.deliver",{taskId,text,...tabId!==void 0?{tabId}:{},source:"dispatcher"});return{ok:!0,taskId,...reply?.tabId!==void 0?{tabId:reply.tabId}:tabId!==void 0?{tabId}:{},routed:"session.deliver",...reply?.delivered!==void 0?{delivered:reply.delivered}:{},...reply?.reason!==void 0?{reason:reply.reason}:{},...reply?.layer!==void 0?{layer:reply.layer}:{},...reply?.clients!==void 0?{clients:reply.clients}:{}}}var DISPATCH_VERB={name:"dispatch",group:"drive",summary:'Route text into a task\'s live session. The dispatcher\'s messenger (docs/design/dispatcher.md); unlike `send`, it never starts an engine \u2014 it requires an already-hosted session. The daemon pastes into it and reports `delivered`; `delivered:false` with `reason:"busy"` means a human is mid-message, and `reason:"broadcast"` means no hosted session answered and the text went out on the session.deliver channel for a browser to pick up (unconfirmable; `clients: 0` proves it reached nobody).',flags:[F.taskId(!0),F.prompt(!0,"Text delivered into the task's engine session."),F.promptFile(),{name:"tab",type:"string",required:!1,placeholder:"TAB",description:"Deliver into exactly this tab (e.g. tab-3) instead of the canonical engine tab."}],handler:dispatch};async function note(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),text=ctx.args.require("text");return await daemon.request("note.file",{taskId,text})}async function getTask(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),res=await daemon.request("task.get",{taskId}),{tabs,running}=await ctx.runtime.taskTabs(taskId,taskEngineArgv(res.task));return{task:res.task,running,tabs}}async function list(ctx){let local=await daemonOf(ctx).request("task.list"),{mergeTaskList}=await import("./chunk-k9xpebq8.js");return await mergeTaskList(local)}async function setActive(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.bool("none")?null:ctx.args.require("task-id");return await daemon.request("task.setActive",{taskId}),{ok:!0,activeTaskId:taskId}}var SCHEDULE_FLAG={name:"schedule",type:"string",placeholder:"CRON",description:"Five-field cron in the daemon host's local time, e.g. '0 9 * * MON-FRI'."},PRECHECK_FLAGS=[{name:"precheck",type:"string",placeholder:"CMD",description:"Shell command run in the repo BEFORE the engine starts. Non-zero exit skips the run without spawning an agent \u2014 the cheap way to avoid burning a turn when nothing changed."},{name:"precheck-timeout",type:"int",placeholder:"SEC",default:"120",description:"Seconds before the precheck is killed and the run skipped."}],GRACE_FLAG={name:"grace",type:"uint",placeholder:"MIN",default:"60",description:"How late a missed occurrence may still run when the daemon was down. Only the most recent missed occurrence is ever run."},PERSISTENT_FLAG={name:"persistent-session",type:"bool",description:"Re-deliver into ONE standing task instead of a fresh worktree per run \u2014 for a routine that needs yesterday's context (a trend check). Its task is folded behind the sidebar's routine count row. Leave off for a routine that EDITS code: a week of runs on one branch is a branch nobody can land."},TARGET_FLAGS=[{name:"target-task",type:"string",placeholder:"ID",description:"Existing task id. Requires --target-tab; never creates or revives a session. Pass both empty to clear on update."},{name:"target-tab",type:"string",placeholder:"TAB",description:"Exact existing engine tab id, e.g. tab-2. Requires --target-task."}];function targetPayload(ctx){let hasTask=ctx.args.present("target-task"),hasTab=ctx.args.present("target-tab");if(!hasTask&&!hasTab)return{};if(!hasTask||!hasTab)throw new ApiError("--target-task and --target-tab must be supplied together","BAD_FLAG");let taskId=ctx.args.str("target-task"),tabId=ctx.args.str("target-tab");if(!taskId&&!tabId)return{target:null};if(!taskId||!tabId)throw new ApiError("both target values must be nonempty, or both empty to clear","BAD_FLAG");return{target:{kind:"existing-tab",taskId,tabId}}}function precheckPayload(ctx){if(!ctx.args.present("precheck")){if(ctx.args.present("precheck-timeout"))throw new ApiError("--precheck-timeout requires --precheck (pass the command again to change its timeout)","BAD_FLAG");return{}}let command=ctx.args.str("precheck");if(command===void 0)return{precheck:null};return{precheck:{command,timeoutSeconds:ctx.args.int("precheck-timeout")??120}}}var ROUTINE_VERBS=[{name:"routine-list",group:"routine",summary:"List scheduled routines with their next run time.",flags:[],handler:(ctx)=>simpleRpc(ctx,"automation.list",{})},{name:"routine-create",group:"routine",summary:"Schedule a prompt. Each firing creates a fresh task (worktree + engine) and delivers it. Use --target-task and --target-tab for an existing conversation. An enabled routine keeps the daemon alive.",flags:[F.repo(),{name:"name",type:"string",required:!0,placeholder:"N",description:"Routine name."},F.prompt(!0,"Text delivered to the selected conversation or a new session."),F.promptFile(),{...SCHEDULE_FLAG,required:!0},F.vendor(),{name:"base-branch",type:"string",placeholder:"B",description:"Base ref each run's worktree branches from."},...PRECHECK_FLAGS,GRACE_FLAG,PERSISTENT_FLAG,...TARGET_FLAGS,{name:"disabled",type:"bool",description:"Create it paused instead of active."}],handler:(ctx)=>simpleRpc(ctx,"automation.create",{repo:ctx.args.requireRepo("repo"),name:ctx.args.require("name"),prompt:requirePromptText(ctx,"routine-create"),schedule:ctx.args.require("schedule"),...ctx.args.vendor()?{vendor:ctx.args.vendor()}:{},...ctx.args.str("base-branch")?{baseRef:ctx.args.str("base-branch")}:{},...precheckPayload(ctx),...targetPayload(ctx),...ctx.args.nonNegativeInt("grace")!==void 0?{missedRunGraceMinutes:ctx.args.nonNegativeInt("grace")}:{},...ctx.args.bool("persistent-session")?{persistentSession:!0}:{},...ctx.args.bool("disabled")?{enabled:!1}:{}})},{name:"routine-update",group:"routine",summary:"Change a routine. A new --schedule re-anchors its next run; --precheck '' clears the precheck.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."},{name:"name",type:"string",placeholder:"N",description:"New name."},F.prompt(!1,"New prompt."),F.promptFile(),SCHEDULE_FLAG,{...F.vendor(),type:"string",description:"New engine vendor; empty clears it before binding an existing target."},{name:"base-branch",type:"string",placeholder:"B",description:"New base ref ('' to clear)."},...PRECHECK_FLAGS,GRACE_FLAG,PERSISTENT_FLAG,...TARGET_FLAGS],handler:(ctx)=>simpleRpc(ctx,"automation.update",{id:ctx.args.require("id"),...ctx.args.str("name")!==void 0?{name:ctx.args.str("name")}:{},...ctx.args.promptText()!==void 0?{prompt:ctx.args.promptText()}:{},...ctx.args.str("schedule")!==void 0?{schedule:ctx.args.str("schedule")}:{},...ctx.args.present("vendor")?{vendor:ctx.args.vendor()??null}:{},...ctx.args.present("base-branch")?{baseRef:ctx.args.str("base-branch")??null}:{},...precheckPayload(ctx),...targetPayload(ctx),...ctx.args.nonNegativeInt("grace")!==void 0?{missedRunGraceMinutes:ctx.args.nonNegativeInt("grace")}:{},...ctx.args.present("persistent-session")?{persistentSession:ctx.args.bool("persistent-session")??!0}:{}})},{name:"routine-set-enabled",group:"routine",summary:"Pause or resume a routine. Disabling the last active one releases the daemon's keep-alive hold.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."},{name:"enabled",type:"bool",required:!0,description:"true to resume, false to pause."}],handler:(ctx)=>simpleRpc(ctx,"automation.update",{id:ctx.args.require("id"),enabled:ctx.args.bool("enabled")})},{name:"routine-delete",group:"routine",summary:"Delete a routine and its run history. Tasks it already created are untouched.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."}],handler:(ctx)=>simpleRpc(ctx,"automation.delete",{id:ctx.args.require("id")})},{name:"routine-run-now",group:"routine",summary:"Run a routine immediately, skipping its precheck (asking for it IS the answer). Does not shift its schedule.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."}],handler:(ctx)=>simpleRpc(ctx,"automation.runNow",{id:ctx.args.require("id")})},{name:"routine-runs",group:"routine",summary:"Run history, newest first. Statuses: dispatched, revived (standing session respawned \u2014 files kept, conversation did not), skipped_cancelled (disabled, changed or stopped before delivery), skipped_precheck (nothing to do), skipped_missed, skipped_unavailable, dispatch_failed.",flags:[{name:"id",type:"string",required:!0,placeholder:"ID",description:"Routine id."}],handler:(ctx)=>simpleRpc(ctx,"automation.runs",{id:ctx.args.require("id")})}];async function engineChoice(ctx,repo){let command=ctx.args.str("command");if(command)return{command,vendor:resolveCommandProtocol(command)};let fallback=await ctx.runtime.defaultVendor(repo);return fallback?{command:fallback,vendor:fallback}:{}}function enginePayload(choice,effort){return{...choice.command?{command:choice.command}:{},...choice.vendor?{vendor:choice.vendor}:{},...effort?{effort}:{}}}function effortFor(ctx,engines){let level=ctx.args.str("effort")?.trim();if(!level)return;for(let engine of new Set(engines))assertEngineAcceptsEffort(engine,level,["api","engine-list"]);return level}async function applyPostCreateFlags(daemon,taskId,args){let status=args.enumOf("status");if(status)await daemon.request("task.status",{taskId,status});let pin=args.bool("pin");if(pin!==void 0)await daemon.request("task.pin",{taskId,pinned:pin});return Boolean(status)||pin!==void 0}async function add(ctx){let{args,runtime}=ctx,requestedRepo=args.requireRepo("repo"),repo=await runtime.resolveRepoRoot(requestedRepo);if(!await runtime.isUsableRepo(repo))throw new ApiError(`--repo ${repo} is not a git repository \u2014 a task needs one to cut its worktree and branch from (run \`git init\` there, or point --repo at a checkout)`,"NOT_A_REPO",helpStep("add"));let count=args.int("count"),agentsSpec=args.str("agents"),parallel=count!==void 0||agentsSpec!==void 0,branch=parallel?void 0:args.str("branch");if(branch&&!await runtime.isValidBranchName(branch))throw new ApiError(`--branch ${JSON.stringify(branch)} is not a valid git branch name (no spaces, no leading "-", no "..", "~^:?*[\\", no trailing ".lock") \u2014 see \`git check-ref-format --branch\``,"INVALID_BRANCH",helpStep("add"));let resolvedFrom=pathWithin(repo,requestedRepo)?{repoResolvedFrom:requestedRepo}:void 0,result=parallel?await addParallel(ctx,repo,count,agentsSpec):await addOne(ctx,repo);return resolvedFrom&&result&&typeof result==="object"?{...result,...resolvedFrom}:result}async function addOne(ctx,repo){let daemon=daemonOf(ctx),{args}=ctx,prompt=args.promptText(),choice=await engineChoice(ctx,repo),effort=effortFor(ctx,choice.vendor?[choice.vendor]:[]),payload={repo,...await dispatcherEnvPayload(),...enginePayload(choice,effort)},title=args.str("title")||(prompt?deriveTitleFromPrompt(prompt):"");if(title)payload.title=title;let branch=args.str("branch");if(branch)payload.branch=branch;let baseRef=args.str("base-branch");if(baseRef)payload.baseRef=baseRef;let worktreeName=args.str("worktree-name");if(worktreeName)payload.worktreeName=worktreeName;let res=await daemon.request("task.create",payload),taskId=res.taskId;if(args.bool("activate"))await daemon.request("task.setActive",{taskId});let task=res.task;if(await applyPostCreateFlags(daemon,taskId,args))task=(await daemon.request("task.get",{taskId})).task;if(!prompt)return{taskId,task,home:homeDir(),started:!1};let brief=await withPeerProvenance(daemon,taskId,prompt),delivered=await ctx.runtime.deliverPrompt(daemon,{id:taskId,worktreePath:task.worktreePath,kind:task.kind,vendor:task.vendor,command:task.command,modelEffort:task.modelEffort,repo:task.repo,newTask:!0},brief);if(!delivered.delivered)throw new ApiError(`task ${taskId} created but the prompt was not delivered (paste did not land)`,"NOT_DELIVERED",{taskId});let promptPersisted=await persistPrompt(daemon,taskId,prompt);return task=(await daemon.request("task.get",{taskId})).task,{taskId,task,home:homeDir(),started:delivered.started,engineReady:delivered.engineReady,session:delivered.session,delivered:delivered.delivered,...delivered.bytes===void 0?{}:{bytes:delivered.bytes},...delivered.promptEcho?{promptEcho:delivered.promptEcho}:{},...delivered.reason?{reason:delivered.reason}:{},...promptPersisted?{}:{promptPersisted:!1}}}async function persistPrompt(daemon,taskId,prompt){try{return await daemon.request("task.setPrompt",{taskId,prompt}),!0}catch(err){return console.error(`[rove api add] task.setPrompt failed for ${taskId} \u2014 no "Run again" for this task:`,err),!1}}async function addParallel(ctx,repo,count,agentsSpec){let daemon=daemonOf(ctx),{args}=ctx,prompt=args.promptText();if(!prompt)throw new ApiError("--count/--agents spawn parallel attempts of ONE prompt \u2014 pass --prompt","MISSING_FLAG",helpStep("add"));if(args.str("branch"))throw new ApiError("--branch names ONE branch and cannot be shared by parallel siblings \u2014 drop it (each sibling gets its own auto branch) or spawn them one at a time","BAD_FLAG",helpStep("add"));if(args.str("worktree-name"))throw new ApiError("--worktree-name names ONE directory and cannot be shared by parallel siblings \u2014 drop it (each sibling gets its own generated name) or spawn them one at a time","BAD_FLAG",helpStep("add"));if(agentsSpec){let conflict=count!==void 0?"--count":args.str("command")?"--command":null;if(conflict)throw new ApiError(`${conflict} conflicts with --agents, which already names each sibling's engine and how many \u2014 pass one or the other`,"BAD_FLAG",helpStep("add"))}let title=args.str("title")||deriveTitleFromPrompt(prompt),baseRef=args.str("base-branch"),choice=await engineChoice(ctx,repo),plan=agentsSpec?parseAgentsSpec(agentsSpec):buildCountPlan(count??1,choice.vendor??DEFAULT_VENDOR);if(plan.length>FANOUT_CAP)throw new ApiError(`a parallel round of ${plan.length} exceeds the cap of ${FANOUT_CAP} \u2014 spawn in batches`,"BAD_FLAG");let effort=effortFor(ctx,plan),groupId=ulid(),created=[],createFailure=null,dispatcher=await dispatcherEnvPayload();for(let[i,vendor]of plan.entries()){let engine=agentsSpec?{command:vendor,vendor}:{...choice,vendor},payload={repo,groupId,...dispatcher,...enginePayload(engine,effort)};if(title)payload.title=plan.length>1?`${title} #${i+1}/${plan.length}`:title;if(baseRef)payload.baseRef=baseRef;try{let res=await daemon.request("task.create",payload);created.push({taskId:res.taskId,vendor,task:res.task})}catch(err){let code=err instanceof ApiError?err.code:"CREATE_FAILED",message=err instanceof Error?err.message:String(err);createFailure={vendor,error:{message,code}};break}}for(let{taskId}of created)await applyPostCreateFlags(daemon,taskId,args);let settled=await Promise.allSettled(created.map(({taskId,vendor,task})=>ctx.runtime.deliverPrompt(daemon,{id:taskId,worktreePath:task.worktreePath,kind:task.kind,vendor,command:task.command,modelEffort:task.modelEffort,repo:task.repo,newTask:!0},prompt))),tasks=[],failures=[],persistedPrompts=[];if(settled.forEach((r,i)=>{let{taskId,vendor,task}=created[i];if(r.status==="fulfilled"&&r.value.delivered){let row={ok:!0,taskId,title:task.title,branch:task.branch,vendor,started:r.value.started,engineReady:r.value.engineReady,session:r.value.session,...r.value.reason?{reason:r.value.reason}:{}};tasks.push(row),persistedPrompts.push(persistPrompt(daemon,taskId,prompt).then((ok)=>{if(!ok)row.promptPersisted=!1}));return}let err=r.status==="rejected"?r.reason:new ApiError(`prompt was not confirmed in ${taskId}'s engine`,"NOT_DELIVERED"),code=err instanceof ApiError?err.code:"DELIVER_FAILED",message=err instanceof Error?err.message:String(err);failures.push({ok:!1,taskId,vendor,error:{message,code}})}),createFailure)failures.push({ok:!1,vendor:createFailure.vendor,error:createFailure.error});await Promise.all(persistedPrompts);let result={count:created.length,requested:plan.length,groupId,home:homeDir(),tasks,failures};if(failures.length>0)throw new ApiError(`add delivered ${tasks.length}/${plan.length}`,"PARTIAL_FANOUT",result);return result}var TASK_STATUSES=["backlog","in_progress","in_review","done","canceled","error"];var CREATE_VERBS=[{name:"add",group:"create",summary:`Create a task (shows in the sidebar immediately). With --prompt it also starts the engine and delivers it. PARALLEL ATTEMPTS: --count N spawns N sibling tasks of the SAME prompt, each in its own worktree/branch (--agents claude:2,codex:1 for a mixed fleet); capped at ${FANOUT_CAP}, prefer 3-4. Does NOT steal focus \u2014 pass --activate to make it the active task. The sidebar shows .task.title and .task.branch \u2014 name a task by those (or its id), never by the directory in .task.worktreePath, which the UI never renders. Alias: spawn-task.`,flags:[F.repo(),F.title(),{name:"branch",type:"string",placeholder:"B",description:"Explicit branch name (else derived from the title in the repo's own style). Single task only."},{name:"base-branch",type:"string",placeholder:"B",description:"Base ref the worktree branches from."},{name:"worktree-name",type:"string",placeholder:"NAME",description:"Name the worktree DIRECTORY instead of taking one from the animal pool \u2014 so the caller can predict `.task.worktreePath` (`<worktrees root>/<NAME>`) rather than reading it back with get-task. One path segment of letters/digits/`.`/`_`/`-`, not starting with `.` (INVALID_WORKTREE_NAME otherwise). A name already in use in this repo \u2014 by a live task, a directory on disk, or a concurrent create \u2014 is REFUSED with WORKTREE_NAME_TAKEN, never silently suffixed `-v2`. Single task only."},F.command(),{name:"effort",type:"string",placeholder:"LEVEL",description:"Reasoning effort for the FIRST session, not just later ones. Validated against the engine's declared levels (codex: none/low/medium/high/xhigh/max; claude declares none) \u2014 free-form, since a plugin engine may declare its own. With --agents, every engine in the plan must declare it."},{name:"count",type:"int",placeholder:"N",description:`Spawn N sibling tasks of one prompt (parallel attempts, cap ${FANOUT_CAP}). Requires --prompt.`},{name:"agents",type:"string",placeholder:"claude:2,codex:1",description:"Per-ENGINE counts for a mixed parallel round (alternative to --count). Engine ids only \u2014 see `engine-list`."},{name:"status",type:"enum",values:TASK_STATUSES,default:"backlog",description:"Initial lifecycle status."},{name:"pin",type:"bool",description:"Pin the task to the top of the sidebar."},{name:"activate",type:"bool",default:"false",description:"Make this the active task (pulls every mounted TUI's Tasks-pane focus). Off by default."},F.prompt(!1,"Optional first message \u2014 when set, materializes the worktree, starts the engine, and pastes it. Required with --count/--agents."),F.promptFile()],handler:add}];function interruptSequenceFor(task){let vendor=task.vendor,sequence=vendor?getCapabilities(vendor)?.interruptSequence:void 0;if(sequence)return sequence;throw new ApiError(`engine ${vendor??"(unknown)"} has not declared how it is interrupted`,"UNSUPPORTED",{taskId:task.id,...vendor?{vendor}:{},hint:"only engines that declare an interrupt sequence can be interrupted \u2014 stop this one by hand in its tab, or close the tab with `tab-close`",nextCommandArgs:["api","get-task","--task-id",task.id]})}async function interruptTask(ctx){let taskId=ctx.args.require("task-id"),tabFlag=ctx.args.str("tab"),{task}=await daemonOf(ctx).request("task.get",{taskId}),sequence=interruptSequenceFor({...task,id:taskId}),host=await openHostedSessionHost();if(!host)throw new ApiError(`no pty host to reach task ${taskId}`,"NO_ENGINE_TAB",{taskId,hint:"nothing is hosting this task's engine \u2014 `pty-list` says whether a host is up at all",nextCommandArgs:["api","pty-list"]});try{let sessions=await listHostedSessions(host.rpc),key=tabFlag?`${taskId}::${tabFlag}`:findHostedEngineKey(sessions,taskId,taskEngineArgv(task)[0]);if(!key||!sessions.some((session)=>session.key===key&&session.alive))throw new ApiError(tabFlag?`task ${taskId} has no live tab ${tabFlag}`:`task ${taskId} has no live engine tab to interrupt`,tabFlag?"TAB_NOT_FOUND":"NO_ENGINE_TAB",{taskId,...tabFlag?{tabId:tabFlag}:{},hint:"`get-task` lists the live tabs in .tabs[]",nextCommandArgs:["api","get-task","--task-id",taskId]});return await host.rpc.request("pty.write",{key,data:sequence}),{ok:!0,taskId,tabId:key.split("::")[1]??"tab-1",vendor:task.vendor,interrupted:!0,bytes:Buffer.byteLength(sequence,"utf8")}}finally{host.close()}}var INTERRUPT_VERB={name:"interrupt",group:"drive",summary:"Stop the turn a task's engine is currently running \u2014 the headless twin of pressing the engine's own interrupt key. Writes the ENGINE-declared interrupt bytes to its pty; the session, its conversation and its worktree all survive, which is what separates this from `tab-close` and `delete`. Use it when a worker runs away: `send` cannot reach it (a busy engine's composer is not quiet), and until now the only levers left destroyed something. Engines that have not declared an interrupt sequence (every `generic` protocol engine) are refused with UNSUPPORTED rather than guessed at \u2014 Esc and ctrl-C mean opposite things across engines. Returns { taskId, tabId, vendor, interrupted, bytes }; `interrupted` reports the WRITE, so read `collect`'s .activity.state for the effect.",flags:[F.taskId(),{name:"tab",type:"string",placeholder:"TAB",description:"Interrupt this exact tab (id from `get-task` .tabs[].id). Omitted = the task's canonical engine tab, the same one a bare `send` targets."}],handler:interruptTask};var PANE_VERB={name:"pane-open",group:"drive",summary:"Open a terminal pane in a task's workspace: split the focused tab (default, or --tab's tab) or open a separate command tab, optionally running a command. Broadcast over the daemon's tab.open channel \u2014 an attached TUI showing the task performs the split. Task defaults to $ROVE_TASK_ID, then the active task. Returns the resolved `title` (the label `pane-close --title` must match \u2014 derived from the command's first word when --title is omitted) plus `clients` (attached connections; 0 = nobody performed the split).",flags:[F.taskId(!1),{name:"tab",type:"string",placeholder:"TAB",description:"Host tab for the split (e.g. tab-3) instead of the focused tab (split placement only)."},{name:"command",type:"string",placeholder:"CMD",description:"Shell command the pane runs (via the login shell's `-ilc`, so pipes/args and your shell rc's PATH/exports work); the pane closes when it exits. Omit for an interactive shell."},{name:"direction",type:"enum",values:["right","down"],default:"right",description:"Split orientation relative to the active pane (split placement only)."},{name:"placement",type:"enum",values:["split","tab"],default:"split",description:"`split` joins the focused tab's split group; `tab` opens a separate command tab."},{name:"title",type:"string",placeholder:"TEXT",description:`Pane label (default: the command's first word, else "shell").`}],handler:async(ctx)=>{let client=daemonOf(ctx),taskId=ctx.args.str("task-id")??process.env.KOBE_TASK_ID??await resolveActiveTaskId(client);if(!taskId)throw new ApiError("no target task: pass --task-id (no $ROVE_TASK_ID, no active task)","MISSING_TARGET");let command=ctx.args.str("command"),shell=resolveLoginShell({fallback:"/bin/sh"}),argv=command?[shell,"-ilc",command]:[shell,"-il"],title=ctx.args.str("title")??(command?command.trim().split(/\s+/)[0]??"shell":"shell"),tabId=ctx.args.str("tab");return{...await simpleRpc(ctx,"tab.open",{taskId,argv,title,...tabId!==void 0?{tabId}:{},placement:ctx.args.str("placement")??"split",direction:ctx.args.str("direction")??"right"}),title}}},PANE_CLOSE_VERB={name:"pane-close",group:"drive",summary:"Close panes opened by pane-open: every split pane / command tab in the task whose label matches --title. Broadcast over the daemon's tab.close channel \u2014 an attached TUI showing the task performs the close (headless no-op). Task defaults to $ROVE_TASK_ID, then the active task. Returns `clients` (attached connections; 0 = nobody performed the close).",flags:[F.taskId(!1),{name:"title",type:"string",required:!0,placeholder:"TEXT",description:"Pane label to close \u2014 the --title the pane was opened with (engine panes are never closed)."},{name:"tab",type:"string",placeholder:"TAB",description:"Scope the title match to one tab (e.g. tab-3) instead of every tab of the task."}],handler:async(ctx)=>{let client=daemonOf(ctx),taskId=ctx.args.str("task-id")??process.env.KOBE_TASK_ID??await resolveActiveTaskId(client);if(!taskId)throw new ApiError("no target task: pass --task-id (no $ROVE_TASK_ID, no active task)","MISSING_TARGET");let tabId=ctx.args.str("tab");return simpleRpc(ctx,"tab.close",{taskId,title:ctx.args.str("title"),...tabId!==void 0?{tabId}:{}})}},TAB_CLOSE_VERB={name:"tab-close",group:"drive",summary:"Close one Terminal Tab by the id returned in get-task .tabs[]. Runs the same close path as ctrl+w when a TUI is attached; otherwise removes the persisted tab snapshot and ends its hosted PTYs directly. Engine, shell/command, and content tabs are all valid. Closing the last tab leaves the task open with no session.",flags:[F.taskId(!0),{name:"tab",type:"string",required:!0,placeholder:"TAB",description:"Exact Terminal Tab id from get-task .tabs[].id (for example tab-3)."}],handler:async(ctx)=>{let taskId=ctx.args.require("task-id"),tabId=ctx.args.require("tab");if((await daemonOf(ctx).request("terminalTab.close",{taskId,tabId})).handled)return{ok:!0,taskId,tabId,handledBy:"tui"};let result=await ctx.runtime.closeTerminalTab(taskId,tabId);return{ok:!0,taskId,tabId,handledBy:"headless",...result}}};var DRIVE_VERBS=[{name:"send",group:"drive",summary:"Paste a follow-up prompt into a task's running engine (one full turn). Without --task-id, a task spawned from another Rove session replies to its dispatcher's tab (then that task's live canonical engine; nothing alive = DISPATCHER_UNREACHABLE, never a silent spawn); otherwise the active task. Sent from inside another Rove task ($ROVE_TASK_ID), the prompt is prefixed with [ROVE PEER] provenance \u2014 who sent it and how to reply (tab-precise) \u2014 so agent-to-agent messaging needs no coordinator. The prompt is pasted into the target composer and submitted; delivery is refused only when there is physically nothing to write to (no such tab, dead PTY, no engine process). A `succeeded:` report sent from a managed task whose branch has 0 commits is REFUSED (EMPTY_SUCCESS_REPORT) \u2014 commit first, or pass --allow-empty when the task genuinely produced no commits.",flags:[F.taskId(!1),F.prompt(!0,"Text pasted + submitted into the engine pane."),F.promptFile(),{name:"tab",type:"string",required:!1,placeholder:"TAB",description:'Tab addressing: "new" spawns the prompt in a fresh engine tab; "tab-N" delivers to that exact alive tab (error when dead/absent). Omitted = the canonical engine tab.'},{...F.command(),description:"Engine launch command for a `--tab new` tab \u2014 the API twin of the TUI's ctrl+e pick. Lets one worktree run two agents on the same files (e.g. hand the stuck work to codex without leaving the branch). An engine id from `engine-list` or a full command line; pinned to that tab, so it survives restarts and a later set-command on the task. Only valid with --tab new."},{name:"respawn",type:"bool",required:!1,description:"Revive a FREEZE-RESTORED --tab tab-N before delivering. After a pty-host restart (reboot, crash) a tab keeps its scrollback and launch command but nothing runs in it; without this flag such a tab is refused (TAB_RESTORED) rather than silently re-run. With it, the tab is respawned in place and resumes its pinned conversation when it has one (`get-task` shows each tab's sessionId) \u2014 a tab with none replays its recorded launch command, which for claude carries the task's original first prompt. Only valid with --tab tab-N."},{name:"plain",type:"bool",required:!1,description:"Deliver the prompt verbatim \u2014 skip the [ROVE PEER] provenance prefix."},{name:"allow-empty",type:"bool",required:!1,description:"Report success from a task with zero commits (EMPTY_SUCCESS_REPORT is refused otherwise). For work that legitimately produces no commits \u2014 an investigation, a review, a question answered."}],handler:send},DISPATCH_VERB,INTERRUPT_VERB,{name:"note",group:"drive",summary:"File a one-line field note \u2014 a resolved, repo-level gotcha worth sharing. Appended to the repo's durable note store (every future session on this repo starts with it) and forwarded to the dispatcher session for live relay (docs/design/dispatcher.md).",flags:[F.taskId(!0),{name:"text",type:"string",required:!0,placeholder:"TEXT",description:"One line: the verified conclusion another session could act on."}],handler:note},{name:"note-list",group:"drive",summary:"Read a repo's accumulated field notes, newest first. Returns { notes } \u2014 each with the `id` note-delete takes.",flags:[F.repo(!0)],handler:(ctx)=>simpleRpc(ctx,"note.list",{repo:ctx.args.requireRepo("repo")})},{name:"note-delete",group:"drive",summary:"Retire one field note by the id `note-list` reports. The note store is not an archive: its newest entries are injected into every fresh session on the repo, so a note whose fact has stopped being true keeps being handed to agents as if it still were. Returns { deleted } \u2014 false (not an error) when the id names nothing, which is also what an already-evicted note answers.",flags:[F.repo(!0),{name:"id",type:"int",required:!0,placeholder:"N",description:"Note id from `note-list`."}],handler:(ctx)=>simpleRpc(ctx,"note.delete",{repo:ctx.args.requireRepo("repo"),id:ctx.args.int("id")})},PANE_VERB,PANE_CLOSE_VERB,TAB_CLOSE_VERB,{name:"notify",group:"drive",summary:"Show a toast in every attached Rove UI \u2014 broadcast over the daemon's notice.event channel. Agents/scripts use it to surface 'done / needs input / error' moments without touching the task's session. Returns `clients` (attached connections; 0 = no UI showed the toast).",flags:[{name:"title",type:"string",required:!0,placeholder:"TEXT",description:"Toast text (one line)."},{name:"body",type:"string",placeholder:"TEXT",description:"Optional second line under the title \u2014 context, not a second message."},{name:"kind",type:"string",default:"done",placeholder:"KIND",description:`Free-form kind tag. "done", "needs_input" and "error" get the TUI's severity styling/unread mark; any other value renders neutrally.`},F.taskId(!1),{name:"source",type:"string",placeholder:"TAG",description:"Free-form origin tag (e.g. an agent name) recorded on the event."}],handler:async(ctx)=>{return simpleRpc(ctx,"notice.send",{title:ctx.args.str("title"),body:ctx.args.str("body"),kind:ctx.args.str("kind")??"done",taskId:ctx.args.str("task-id"),source:ctx.args.str("source")})}},{name:"prompt",group:"drive",summary:"Ask the human for a line of text through the attached TUI's input dialog (plugins' host-provided prompt). Blocks until answered, cancelled, or timed out; returns { value } or { cancelled, reason }.",flags:[{name:"title",type:"string",required:!0,placeholder:"TEXT",description:"Dialog title (shown verbatim)."},{name:"placeholder",type:"string",placeholder:"TEXT",description:"Input placeholder."},{name:"initial",type:"string",placeholder:"TEXT",description:"Pre-filled input value."},{name:"timeout",type:"string",placeholder:"MS",description:"Give up after this many milliseconds (default 120000, max 600000)."}],handler:async(ctx)=>{let timeoutRaw=ctx.args.str("timeout"),timeoutMs=timeoutRaw?Number.parseInt(timeoutRaw,10):void 0;return simpleRpc(ctx,"ui.prompt",{title:ctx.args.str("title"),placeholder:ctx.args.str("placeholder"),initial:ctx.args.str("initial"),...timeoutMs&&Number.isFinite(timeoutMs)?{timeoutMs}:{}})}},{name:"engine-report",group:"drive",summary:"Report a normalized engine-activity verb for a task \u2014 the public face of the same engine.reportEvent RPC the built-in hook adapters use. Lets a plugin-contributed engine (or any wrapper script) drive the sidebar badge, attention inbox, and plugin event stream without a built-in hook adapter. Kinds: session-start|turn-start|turn-complete|turn-failed|turn-interrupted|awaiting-input|session-end (state kinds) plus tool-pre|tool-post|tool-failed|pre-compact|post-compact|subagent-start|subagent-stop (plugin-only).",flags:[F.taskId(!1),{name:"kind",type:"enum",values:ENGINE_ACTIVITY_KINDS,required:!0,placeholder:"KIND",description:"Normalized activity verb (see summary). Unknown kinds are rejected."},{name:"engine",type:"string",placeholder:"ID",description:"Engine id producing the report (a plugin engine id, or a built-in vendor)."},{name:"tab",type:"string",placeholder:"TAB",description:"Terminal tab id the session runs in (defaults to $ROVE_TAB_ID / $KOBE_TAB_ID)."},{name:"detail",type:"string",placeholder:"JSON",description:`Optional detail JSON, e.g. '{"failure":"rate_limit"}' or '{"waiting":"input"}'.`}],handler:async(ctx)=>{let taskId=ctx.args.str("task-id")??process.env.ROVE_TASK_ID??process.env.KOBE_TASK_ID,tabId=ctx.args.str("tab")??process.env.ROVE_TAB_ID??process.env.KOBE_TAB_ID,detailRaw=ctx.args.str("detail"),detail;if(detailRaw!==void 0)try{detail=JSON.parse(detailRaw)}catch{throw new ApiError("--detail must be valid JSON","BAD_FLAG",helpStep("engine-report"))}return simpleRpc(ctx,"engine.reportEvent",{kind:ctx.args.str("kind"),...taskId?{taskId}:{cwd:process.cwd()},...ctx.args.str("engine")?{engine:ctx.args.str("engine")}:{},...tabId?{tabId}:{},...detail!==void 0?{detail}:{}})}},{name:"set-active",group:"drive",summary:"Set the shared active task (the focus every Tasks pane highlights). Pass --none to clear.",flags:[F.taskId(!1),{name:"none",type:"bool",description:"Clear the active task instead of setting one."}],handler:setActive}];async function renameTaskOrTab(ctx){let taskId=ctx.args.require("task-id"),title=ctx.args.require("title"),tabId=ctx.args.str("tab");if(tabId===void 0)return simpleRpc(ctx,"task.rename",{taskId,title});if(!renameTabsSnapshot(taskId,tabId,title))throw new ApiError(`task ${taskId} has no tab ${tabId}`,"TAB_NOT_FOUND",{hint:"`get-task` lists the addressable tab ids in .tabs[].id",nextCommandArgs:["api","get-task","--task-id",taskId]});let reply=await daemonOf(ctx).request("terminalTab.rename",{taskId,tabId,title});return{ok:!0,taskId,tabId,title,renamed:!0,clients:reply.clients??0}}var EDIT_VERBS=[{name:"rename",group:"edit",summary:"Set a task's title, or with --tab one Terminal Tab's name \u2014 the API twin of the TUI's f2. Tab lifecycle is otherwise symmetric already (pane-open / tab-close / read-output --tab / send --tab), so naming was the one thing an agent could not do to a tab it had opened. An attached TUI repaints its tab strip; with none attached the persisted snapshot carries the name to the next mount.",flags:[F.taskId(),{name:"title",type:"string",required:!0,placeholder:"T",description:"New title."},{name:"tab",type:"string",placeholder:"TAB",description:"Rename this Terminal Tab (id from `get-task` .tabs[].id, e.g. tab-2) instead of the task. TAB_NOT_FOUND when the task's snapshot names no such tab."}],handler:renameTaskOrTab},{name:"set-branch",group:"edit",summary:"Rename a task's branch (git branch -m if materialized, else recorded).",flags:[F.taskId(),{name:"branch",type:"string",required:!0,placeholder:"B",description:"New branch name."}],handler:(ctx)=>simpleRpc(ctx,"task.setBranch",{taskId:ctx.args.require("task-id"),branch:ctx.args.require("branch")})},SET_COMMAND_VERB,SET_EFFORT_VERB,{name:"set-status",group:"edit",summary:"Set a task's lifecycle LABEL, and optionally record what the worker DELIVERED. The status half is cosmetic \u2014 the task row, its worktree, its branch and its engine session all stay exactly as they are, so `--status canceled` does NOT close, stop, or clean up anything. To end a task use `delete` (which keeps the git branch). The --report-* half writes `.report` on the task ({ branch?, pr?, summary?, at }), readable from `get-task` and `collect`: it is what the WORKER CLAIMS, and is deliberately not the same field as `.prStatus`, which the daemon POLLED from the forge \u2014 a worker can report a PR number that does not exist, and a dispatcher deciding whether to land needs to know which of the two it is reading. Report fields merge onto any previous report and restamp `at`, so a follow-up naming only --report-pr keeps the branch reported earlier.",flags:[F.taskId(),{name:"status",type:"enum",required:!0,values:TASK_STATUSES,description:"New status."},{name:"report-branch",type:"string",placeholder:"B",description:"The branch the worker says holds the work (a CLAIM \u2014 `.branch` is the task's actual branch)."},{name:"report-pr",type:"int",placeholder:"N",description:"The PR number the worker says it opened (a CLAIM \u2014 `.prStatus.number` is what the daemon read from the forge)."},{name:"report-summary",type:"string",placeholder:"TEXT",description:"One line of what was delivered."}],handler:(ctx)=>simpleRpc(ctx,"task.status",{taskId:ctx.args.require("task-id"),status:ctx.args.requireEnum("status"),reportBranch:ctx.args.str("report-branch"),reportPr:ctx.args.int("report-pr"),reportSummary:ctx.args.str("report-summary")})}];async function collect(ctx){let daemon=daemonOf(ctx),{args,runtime}=ctx,idsFlag=args.str("task-ids"),repoFlag=args.path("repo"),groupFlag=args.str("group"),taskIds,unresolvableRepos=[];if(idsFlag)taskIds=idsFlag.split(",").map((s)=>s.trim()).filter(Boolean);else if(repoFlag||groupFlag){let{tasks}=await daemon.request("task.list"),filter=repoFlag?await repoFilter(runtime,repoFlag,tasks.map((t)=>t.repo)):null;unresolvableRepos=filter?.unresolvableRepos??[],taskIds=[];for(let t of tasks){if(groupFlag&&t.groupId!==groupFlag)continue;if(filter&&!filter.matches(t.repo))continue;taskIds.push(t.id)}}else throw new ApiError("collect needs --task-ids id1,id2, --group GROUPID, or --repo PATH","MISSING_TARGET");let registry=null;try{registry=(await daemon.request("debug.inspect"))?.activity?.tasks??{}}catch{registry=null}let out=[];for(let taskId of taskIds){let{task}=await daemon.request("task.get",{taskId}),{tabs,running}=await runtime.taskTabs(taskId,taskEngineArgv(task)),changes=task.worktreePath?await runtime.readWorktreeChanges(task.worktreePath):null,base=task.worktreePath?await runtime.readBranchSignals(task.worktreePath,task.baseRef):{baseRef:null,ahead:null,behind:null,diff:null},entry=registry?.[task.id],activity=entry?{state:entry.state,at:new Date(entry.at).toISOString(),forMs:Math.max(0,Date.now()-entry.at)}:null;out.push({taskId:task.id,title:task.title,branch:task.branch,worktreePath:task.worktreePath,vendor:task.vendor,status:task.status,...task.groupId?{groupId:task.groupId}:{},...task.report?{report:task.report}:{},...task.dispatcher?{dispatcher:task.dispatcher}:{},running,activity,tabs,changes,base})}return{tasks:out,...unresolvableRepos.length>0?{unresolvableRepos}:{}}}async function feedback(ctx){return{ok:!0,discussion:submitFeedback({title:ctx.args.require("title"),body:ctx.args.require("body"),categorySlug:ctx.args.str("category")})}}var FEEDBACK_VERBS=[{name:"feedback",group:"feedback",summary:"Create a GitHub Discussion in the Rove repo's Feedback category through `gh`.",flags:[{name:"title",type:"string",required:!0,placeholder:"T",description:"Discussion title."},{name:"body",type:"string",required:!0,placeholder:"TEXT",description:"Discussion body."},{name:"category",type:"string",default:DEFAULT_FEEDBACK_CATEGORY_SLUG,placeholder:"SLUG",description:"Discussion category slug."}],offline:!0,handler:feedback}];var ISSUE_STATUSES=["open","doing","hold","done"],ISSUE_VERBS=[{name:"issue-list",group:"issues",summary:"List daemon-owned issues for a repo.",flags:[F.repo()],handler:(ctx)=>simpleRpc(ctx,"issue.list",{repoRoot:ctx.args.requireRepo("repo")})},{name:"issue-create",group:"issues",summary:"Create a daemon-owned issue for a repo.",flags:[F.repo(),{name:"title",type:"string",required:!0,placeholder:"T",description:"Issue title."},{name:"body",type:"string",placeholder:"TEXT",description:"Issue body."}],handler:(ctx)=>simpleRpc(ctx,"issue.mutate",{repoRoot:ctx.args.requireRepo("repo"),op:{type:"create",title:ctx.args.require("title"),body:ctx.args.str("body")}})},{name:"issue-set-status",group:"issues",summary:"Set a daemon-owned issue's status.",flags:[F.repo(),{name:"id",type:"int",required:!0,placeholder:"N",description:"Issue id."},{name:"status",type:"enum",required:!0,values:ISSUE_STATUSES,description:"New issue status."}],handler:(ctx)=>simpleRpc(ctx,"issue.mutate",{repoRoot:ctx.args.requireRepo("repo"),op:{type:"setStatus",id:ctx.args.int("id"),status:ctx.args.requireEnum("status")}})},{name:"issue-update",group:"issues",summary:"Update a daemon-owned issue's title, body, and/or linked task.",flags:[F.repo(),{name:"id",type:"int",required:!0,placeholder:"N",description:"Issue id."},{name:"title",type:"string",placeholder:"T",description:"New title."},{name:"body",type:"string",placeholder:"TEXT",description:"New body."},{name:"task",type:"string",placeholder:"TASK_ID",description:"Link the issue to this task (kanban: In progress). Pass `none` to unlink."}],handler:issueUpdate},{name:"issue-delete",group:"issues",summary:"Delete a daemon-owned issue. Removes ONLY the tracker record \u2014 a linked task, its branch and its worktree are left untouched. The same `delete` op the kanban page's `d` runs; use `issue-set-status --status done` when the story was finished rather than abandoned.",flags:[F.repo(),{name:"id",type:"int",required:!0,placeholder:"N",description:"Issue id."}],handler:(ctx)=>simpleRpc(ctx,"issue.mutate",{repoRoot:ctx.args.requireRepo("repo"),op:{type:"delete",id:ctx.args.int("id")}})}];import{spawnSync}from"child_process";var REMOTE_TIMEOUT_MS=30000;function git(cwd,args,timeoutMs){try{let out=spawnSync("git",[...args],{cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"],env:readOnlyGitProcessEnv(),...timeoutMs===void 0?{}:{timeout:timeoutMs}});return{ok:out.status===0,stdout:(out.stdout??"").trim(),stderr:(out.stderr??"").trim()||(out.status===null?`git ${args[0]} did not finish`:"")}}catch(err){return{ok:!1,stdout:"",stderr:err instanceof Error?err.message:String(err)}}}function localBranchExists(repo,branch){return git(repo,["show-ref","--verify","--quiet",`refs/heads/${branch}`]).ok}function remoteFor(repo,branch){let configured=git(repo,["config","--get",`branch.${branch}.remote`]);return configured.ok&&configured.stdout.length>0?configured.stdout:"origin"}function deleteRemoteBranch(repo,branch){let name=remoteFor(repo,branch),push=git(repo,["push",name,"--delete",branch],REMOTE_TIMEOUT_MS);if(push.ok)return{name,deleted:!0};let remaining=git(repo,["ls-remote","--heads",name,branch],REMOTE_TIMEOUT_MS);if(remaining.ok&&remaining.stdout.length===0)return{name,deleted:!0};return{name,deleted:!1,error:push.stderr||"git push exited non-zero"}}function reportBranchDeletion(repo,branch,opts){if(!branch||!opts.deleteBranch&&!opts.deleteRemote)return;let deleted=!0,keptReason;if(opts.deleteBranch){if(localBranchExists(repo,branch)){let retry=git(repo,["branch",opts.force?"-D":"-d",branch]);if(deleted=retry.ok||!localBranchExists(repo,branch),!deleted)keptReason=retry.stderr||retry.stdout||"git branch refused the delete"}}else deleted=!localBranchExists(repo,branch);return{branch,deleted,...keptReason?{keptReason}:{},...opts.deleteRemote?{remote:deleteRemoteBranch(repo,branch)}:{}}}var DELETE_WAIT_TIMEOUT_MS=60000,DELETE_POLL_INTERVAL_MS=250;async function deleteTask(ctx){let daemon=daemonOf(ctx),groupId=ctx.args.str("group"),taskIdFlag=ctx.args.str("task-id");if(groupId&&taskIdFlag)throw new ApiError("pass --task-id or --group, not both","BAD_FLAG");if(!groupId&&!taskIdFlag)throw new ApiError("delete needs --task-id ID or --group GROUPID","MISSING_TARGET");let self=await verifiedSelfSession();if(!groupId)return deleteOne(ctx,taskIdFlag,self);let{tasks}=await daemon.request("task.list"),members=tasks.filter((t)=>t.groupId===groupId);if(members.length===0)throw new ApiError(`no tasks in group ${groupId}`,"TASK_NOT_FOUND",{hint:"the groupId is the one `add --count` returned; any surviving sibling's `.groupId` in `list` recovers it",nextCommandArgs:["api","list"]});let results=[];for(let task of members)try{results.push(await deleteOne(ctx,task.id,self))}catch(err){let message=errorMessage(err),code=err instanceof ApiError?err.code:splitDaemonCode(message)?.code;results.push({taskId:task.id,status:"failed",error:message,...code?{code}:{}})}let failures=results.filter((r)=>r.status==="failed").length;return{groupId,count:members.length,failures,results}}async function deleteOne(ctx,taskId,self){let daemon=daemonOf(ctx),force=ctx.args.bool("force")??!1,deleteBranch=ctx.args.bool("delete-branch")??!1,deleteRemote=ctx.args.bool("delete-remote")??!1,subject=deleteBranch||deleteRemote?(await daemon.request("task.get",{taskId})).task:void 0,res;try{res=await daemon.request("task.delete",{taskId,force,deleteBranch,...self?{requestedByTaskId:self.taskId,requestedByTabId:self.tabId}:{}})}catch(err){throw deleteRecoveryError(err,taskId)}if(await ctx.runtime.tearDownSession(taskId),!res.queued)return{...res,status:"not_found"};if(!ctx.args.bool("wait")&&!subject)return{...res,status:"queued"};let outcome=await awaitDeletion(daemon,taskId),branch=subject&&outcome.status==="removed"?reportBranchDeletion(subject.repo,subject.branch??"",{deleteBranch,force,deleteRemote}):void 0;return{...res,...outcome,...branch?{branch}:{}}}async function awaitDeletion(daemon,taskId){let deadline=Date.now()+DELETE_WAIT_TIMEOUT_MS;for(;;){let{tasks}=await daemon.request("task.list"),task=tasks.find((t)=>t.id===taskId);if(!task)return{status:"removed"};let deletion=task.deletion;if(deletion?.phase==="error")return{status:"failed",error:deletion.error??"worktree removal failed"};if(Date.now()>=deadline)return{status:"pending"};await new Promise((resolve2)=>setTimeout(resolve2,DELETE_POLL_INTERVAL_MS))}}async function land(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id");if(ctx.args.bool("dry-run")===!0)return(await daemon.request("task.landPreflight",{taskId})).result;let strategy=ctx.args.str("strategy")==="squash"?"squash":"merge",res;try{res=await daemon.request("task.land",{taskId,strategy,deleteBranch:ctx.args.bool("delete-branch")??!1,removeWorktree:ctx.args.bool("remove-worktree"),callerCwd:process.cwd()})}catch(err){throw landRecoveryError(err,taskId)}return{ok:!0,taskId,...res.result}}function landRecoveryError(err,taskId){let message=errorMessage(err);if(!message.includes(EMPTY_BRANCH_DIRTY_WORKTREE_CODE))return err;let branch=/EMPTY_BRANCH_DIRTY_WORKTREE: '([^']+)'/.exec(message)?.[1]??"your task branch";return new ApiError(splitDaemonCode(message)?.rest??message,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,{hint:"the worker wrote files but never committed them \u2014 send it back to commit its own work, then land again",nextCommandArgs:["api","send","--task-id",taskId,"--prompt",`your work is uncommitted on ${branch} \u2014 commit it yourself with a proper message, then report back`]})}function deleteRecoveryError(err,taskId){let message=errorMessage(err),coded=splitDaemonCode(message);if(coded?.code!==DIRTY_WORKTREE_CODE)return err;return new ApiError(coded.rest,DIRTY_WORKTREE_CODE,{taskId,hint:"the worktree still holds work this delete would destroy \u2014 the message names it, and a gitignored path never shows in `git status`. Send the worker back to commit it, or pass --force to delete the task AND discard that work",nextCommandArgs:["api","send","--task-id",taskId,"--prompt","your worktree still holds work that this cleanup would destroy (it may be gitignored, so `git status` will not show it \u2014 check `git status --ignored`). Commit it yourself with a proper message, then report back"]})}async function removeTaskWorktree(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),force=ctx.args.bool("force")??!1,{task}=await daemon.request("task.get",{taskId}),worktreePath=(task.worktreePath??"").trim();if(!worktreePath)throw new ApiError(`task ${taskId} has no worktree on disk`,"NO_WORKTREE",{hint:"nothing to remove \u2014 `ensure-worktree` materialises one"});let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(task.repo)))throw new ApiError(`refusing to remove ${worktreePath} \u2014 it is the project's own checkout, not a Rove worktree`,"BASE_CHECKOUT");if(pathWithin(wt,canonicalize(process.cwd()))!==null)throw new ApiError(`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`,"CALLER_WORKTREE");let res=await daemon.request("worktree.remove",{path:worktreePath,force});return{ok:!0,taskId,worktreePath,branch:task.branch,...res}}async function adopt(ctx){let daemon=daemonOf(ctx),{args}=ctx,input={repo:args.requireRepo("repo"),worktreePath:args.requirePath("worktree")},branch=args.str("branch");if(branch)input.branch=branch;let command=args.str("command");if(command)input.command=command,input.vendor=resolveCommandProtocol(command);let title=args.str("title");if(title)input.title=title;return daemon.request("worktree.adopt",input)}var LIFECYCLE_VERBS=[{name:"pin",group:"lifecycle",summary:"Pin (or with --pinned=false, unpin) a task to the top of the sidebar.",flags:[F.taskId(),{name:"pinned",type:"bool",default:"true",description:"true to pin, false to unpin."}],handler:(ctx)=>simpleRpc(ctx,"task.pin",{taskId:ctx.args.require("task-id"),pinned:ctx.args.bool("pinned")??!0})},{name:"land",group:"lifecycle",summary:"Merge a task's branch back into its base repo's current branch. Refuses a dirty base checkout, a branch that no longer resolves in the base repo (MISSING_REF \u2014 renamed or deleted outside Rove), and a branch with zero commits ahead of the base (EMPTY_BRANCH; EMPTY_BRANCH_DIRTY_WORKTREE with a send-back recovery path when the worktree still holds the uncommitted work). On conflict, aborts and returns the conflicted files (resolve by hand). Returns { landedOn, commit }.",flags:[F.taskId(),{name:"dry-run",type:"bool",description:"Report whether the land would proceed, and write nothing. Returns { branch, landedOn, ahead?, baseDirty?, refusal?, dirtyFiles?, baseDir } \u2014 `landedOn` is the base checkout's CURRENT branch (the merge destination), `ahead` the commits that would land, and `refusal` one of DETACHED_HEAD, UNREADABLE_BASE, UNBORN_BASE, SAME_BRANCH, MAIN_CHECKOUT_DIRTY, MISSING_REF, EMPTY_BRANCH, EMPTY_BRANCH_DIRTY_WORKTREE when the land would be refused. Ignores --strategy/--delete-branch/--remove-worktree."},{name:"strategy",type:"enum",values:["merge","squash"],default:"merge",description:"merge (--no-ff) or squash into one commit."},{name:"delete-branch",type:"bool",description:"Delete the task's branch after a successful land. Uses `git branch -D`, which drops the branch's reflog too; with --strategy squash the base's new commit does not reach the branch's own commits, so Rove first anchors the tip at refs/rove/salvage/<branch>-<stamp> and returns it as `branchAnchor`. Requires the worktree to be gone: git refuses to delete a branch a live worktree has checked out, so a land that kept the worktree keeps the branch too and says so in `branchKept`."},{name:"remove-worktree",type:"bool",default:"true",description:"Remove the task's worktree after a successful land (default; the branch always stays). Pass --remove-worktree=false to keep it. Dirty worktrees, the base checkout, and the caller's own worktree are refused \u2014 the outcome is reported in the result's `worktree` field, never thrown."}],handler:land},{name:"delete",group:"lifecycle",summary:"Remove a task and its worktree; the git branch stays unless --delete-branch. Needs --force on a dirty worktree. Returns { queued } \u2014 removal itself runs in the background; add --wait for the resolved outcome. With --delete-branch / --delete-remote the reply also carries `branch` \u2014 { branch, deleted, keptReason?, remote? } \u2014 so `the branch went with it` is a fact you read rather than an assumption. Pass --group instead of --task-id to close a whole fan-out round in one call: it returns { groupId, count, failures, results } with one entry per sibling, and a refusal on one (a dirty worktree) is recorded there rather than aborting the rest.",flags:[F.taskId(!1),{name:"group",type:"string",placeholder:"GROUPID",description:"Delete every task of one fan-out round (the `groupId` that `add --count` returns, the same selector `collect --group` takes). Mutually exclusive with --task-id."},{name:"force",type:"bool",description:"Delete even with uncommitted changes (never implies --delete-branch)."},{name:"delete-branch",type:"bool",description:"Also delete the task's LOCAL git branch (default: keep it). The outcome is reported in the result's `branch` field \u2014 `{ deleted, keptReason? }` \u2014 because git legitimately refuses (unmerged work, a sibling worktree holding the branch) and that refusal used to reach daemon.log and nowhere a caller could read it. Implies --wait: a branch verdict read before the worktree is gone describes the worktree, not the branch."},{name:"delete-remote",type:"bool",description:"Also `git push --delete` the branch on its remote (its own `branch.<name>.remote`, else origin). A SEPARATE opt-in that --delete-branch never implies: a local branch is recoverable from any clone that still has it, a remote one is recoverable by nobody and its deletion closes any open PR. Reported in `branch.remote` \u2014 `{ name, deleted, error? }`. Implies --wait."},{name:"wait",type:"bool",description:"Follow the background removal and report its OUTCOME (removed / failed / pending) instead of returning as soon as it is queued."}],handler:deleteTask}];var DEFAULT_SINCE_DAYS=7,DEFAULT_LIMIT=200;function summarizeTurns(turns){let byModel={},inputTokens=0,outputTokens=0,cacheReadTokens=0,cacheCreationTokens=0,durationMs=0;for(let turn of turns){inputTokens+=turn.usage?.input_tokens??0,outputTokens+=turn.usage?.output_tokens??0,cacheReadTokens+=turn.usage?.cache_read_input_tokens??0,cacheCreationTokens+=turn.usage?.cache_creation_input_tokens??0,durationMs+=Math.max(0,turn.endedAt-turn.startedAt);let model=turn.model??"unknown";byModel[model]=(byModel[model]??0)+1}return{turns:turns.length,inputTokens,outputTokens,cacheReadTokens,cacheCreationTokens,durationMs,byModel}}async function agentTurns(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.str("task-id"),repoPath=ctx.args.path("repo"),repo=repoPath?await ctx.runtime.resolveRepoRoot(repoPath):void 0,sinceDays=ctx.args.int("since-days")??DEFAULT_SINCE_DAYS,since=Date.now()-sinceDays*24*60*60*1000,limit=ctx.args.int("limit")??DEFAULT_LIMIT,{turns}=await daemon.request("agentTurn.list",{...taskId?{taskId}:{},...repo?{repoRoot:repo}:{},since,limit});return{since:new Date(since).toISOString(),totals:summarizeTurns(turns),turns}}var AGENT_TURNS_VERB={name:"agent-turns",group:"read",summary:`Per-turn agent telemetry: one record per completed engine turn (task/tab/vendor/model/timings/tokens), newest first, plus totals. Engine-produced, daemon-stored; read-only. Engines that report turns: ${vendorsWithTurnReader().join(", ")} \u2014 a task on any other engine yields an empty page because that engine has no turn reader, not because it did no work.`,flags:[{name:"task-id",type:"string",placeholder:"ID",description:"Only this task's turns."},{name:"repo",type:"string",placeholder:"PATH",description:"Only turns of tasks in this repo. Relative paths resolve against $PWD."},{name:"since-days",type:"int",default:String(DEFAULT_SINCE_DAYS),placeholder:"N",description:"Look-back window in days."},{name:"limit",type:"int",default:String(DEFAULT_LIMIT),placeholder:"N",description:"Max turns returned."}],handler:agentTurns};var DEFAULT_SINCE_DAYS2=7;function epochOf(iso){if(!iso)return null;let ms=Date.parse(iso);return Number.isNaN(ms)?null:ms}function buildDigest(repo,sinceMs,tasks,runs){let byStatus={};for(let run of runs)byStatus[run.status]=(byStatus[run.status]??0)+1;return{repo,since:new Date(sinceMs).toISOString(),tasks:{total:tasks.length},routines:{runs:runs.length,byStatus}}}async function digest(ctx){let daemon=daemonOf(ctx),{args,runtime}=ctx,repoFlag=args.requireRepo("repo"),sinceMs=Date.now()-(args.int("since-days")??DEFAULT_SINCE_DAYS2)*86400000,{tasks:allTasks}=await daemon.request("task.list"),{automations}=await daemon.request("automation.list"),filter=await repoFilter(runtime,repoFlag,[...allTasks.map((t)=>t.repo),...automations.map((a)=>a.repo)]),repo=filter.target,tasks=[];for(let task of allTasks){if((task.kind??"task")!=="task")continue;if((epochOf(task.updatedAt)??0)<sinceMs)continue;if(filter.matches(task.repo))tasks.push(task)}let runs=[];for(let automation of automations){if(!filter.matches(automation.repo))continue;let page=await daemon.request("automation.runs",{id:automation.id});for(let run of page.runs)if((epochOf(run.at)??0)>=sinceMs)runs.push(run)}return{...buildDigest(repo,sinceMs,tasks,runs),...filter.unresolvableRepos.length>0?{unresolvableRepos:filter.unresolvableRepos}:{}}}var DIGEST_VERB={name:"digest",group:"read",summary:"Aggregate a repo's recent agent work: tasks touched in the window plus routine run outcomes. Reads state Rove already persists \u2014 the measurement any workflow change has to move.",flags:[{name:"repo",type:"string",required:!0,placeholder:"PATH",description:"Repo root (git toplevel). Relative paths resolve against $PWD."},{name:"since-days",type:"int",default:String(DEFAULT_SINCE_DAYS2),placeholder:"N",description:"Look-back window in days."}],handler:digest};async function daemonSection(){let{connectIfRunning}=await import("./chunk-d4fvkzp3.js"),client=null;try{if(client=await connectIfRunning(),!client)return null;return await client.request("debug.inspect",{})}catch(err){return{error:err instanceof Error?err.message:String(err)}}finally{client?.close()}}async function sessionsSection(taskId){let[{KobeDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-ydhngxy3.js"),import("./chunk-r1mp0eb2.js")]),client=new KobeDaemonClient(defaultPtyHostSocketPath()),sessions;try{await client.connect(),sessions=(await client.request("pty.list",{})).sessions??[]}catch{return null}finally{client.close()}if(taskId)sessions=sessions.filter((s)=>s.key.startsWith(`${taskId}::`));let rows=null;try{let pids=sessions.map((s)=>s.pid).filter((pid)=>typeof pid==="number"&&pid>0);rows=parsePsSnapshot(await psSnapshot(pids))}catch{rows=null}return sessions.map((s)=>{let walkable=rows!==null&&typeof s.pid==="number"&&s.pid>0,found=walkable&&rows?foregroundEngineIn(rows,s.pid):null;return{key:s.key,alive:s.alive,pid:s.pid??null,title:s.title||null,exit:s.exit??null,foreground:walkable?found?{vendor:found.vendor,pid:found.pid,argv:found.argv}:null:"unknown"}})}async function sessionExitsSection(taskId){try{let{readPtyExitRecords}=await import("./chunk-var92s38.js"),records=Object.values(readPtyExitRecords()).sort((a,b)=>a.at<b.at?1:-1);return taskId?records.filter((r)=>r.key.startsWith(`${taskId}::`)):records}catch(err){return{error:err instanceof Error?err.message:String(err)}}}function tabsSection(taskId,sessions){let live=Array.isArray(sessions)?sessions.filter((s)=>typeof s?.key==="string"):[];try{let state=loadStateFile(),out={},prefix="terminalTabs.";for(let[key,value]of Object.entries(state)){if(!key.startsWith("terminalTabs."))continue;let id=key.slice(13);if(taskId&&id!==taskId)continue;let snap=value;if(!snap||!Array.isArray(snap.tabs))continue;let unregistered=unregisteredTabIds(snap,id,live);out[id]={activeId:snap.activeId,tabs:snap.tabs.map((t)=>({id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null})),...unregistered.length>0?{unregistered}:{}}}for(let s of live){let id=s.key.split("::")[0]??"";if(!id||out[id]!==void 0||taskId&&id!==taskId)continue;let unregistered=unregisteredTabIds(void 0,id,live);if(unregistered.length>0)out[id]={activeId:null,tabs:[],unregistered}}return out}catch(err){return{error:err instanceof Error?err.message:String(err)}}}async function inspect(ctx){let taskId=ctx.args.str("task-id"),[daemon,sessions,sessionExits]=await Promise.all([daemonSection(),sessionsSection(taskId),sessionExitsSection(taskId)]);return{daemon,sessions,sessionExits,tabs:tabsSection(taskId,sessions),at:new Date().toISOString()}}var INSPECT_VERB={name:"inspect",group:"read",summary:"Production diagnostics in one read: daemon activity registry (raw states, probe vendors, watchdogs), pty-host sessions joined with a live process-tree engine walk, durable session death records (exit code/signal/output tail), and the persisted tab snapshots the sidebar renders from. Read-only; missing daemon/host degrade to null.",flags:[F.taskId(!1)],offline:!0,handler:inspect};var WATCHABLE_STATES=["idle","running","turn_complete","rate_limited","permission_needed","error","dead"],HEARTBEAT_MS=5000,DEFAULT_TIMEOUT_MS=300000;async function resolveTaskIds(ctx){let ids=ctx.args.str("task-ids"),group=ctx.args.str("group");if(ids&&group)throw new ApiError("pass --task-ids or --group, not both","BAD_FLAG");if(ids){let list2=ids.split(",").map((s)=>s.trim()).filter(Boolean);if(list2.length>0)return list2}if(!group)throw new ApiError("watch needs --task-ids id1,id2 or --group GROUPID","MISSING_TARGET");let{tasks}=await daemonOf(ctx).request("task.list"),members=tasks.filter((t)=>t.groupId===group).map((t)=>t.id);if(members.length===0)throw new ApiError(`no tasks in group ${group}`,"TASK_NOT_FOUND",{hint:"the groupId is the one `add --count` returned; any surviving sibling's `.groupId` in `list` recovers it",nextCommandArgs:["api","list"]});return members}function parseUntil(raw){let states=raw.split(",").map((s)=>s.trim()).filter(Boolean),unknown=states.filter((s)=>!WATCHABLE_STATES.includes(s));if(unknown.length>0)throw new ApiError(`--until names states that do not exist: ${unknown.join(", ")} (valid: ${WATCHABLE_STATES.join(", ")})`,"BAD_FLAG");if(states.length===0)throw new ApiError("--until needs at least one state","BAD_FLAG");return states}async function watch(ctx){let daemon=daemonOf(ctx),taskIds=new Set(await resolveTaskIds(ctx)),until=new Set(parseUntil(ctx.args.require("until"))),timeoutRaw=ctx.args.int("timeout"),timeoutMs=timeoutRaw&&timeoutRaw>0?timeoutRaw:DEFAULT_TIMEOUT_MS;return await new Promise((resolve2,reject)=>{let settled=!1,events=0,seen=new Set,SEEN_CAP=512,finish=(fn)=>{if(settled)return;settled=!0,clearInterval(heartbeat),clearTimeout(deadline),off(),fn()},off=daemon.onChannel("engine-state",(payload)=>{let event=payload;if(!taskIds.has(event.taskId))return;let key=`${event.taskId}::${event.tabId??""}::${event.state}::${event.at}`;if(seen.has(key))return;if(seen.size>=SEEN_CAP)seen.clear();if(seen.add(key),events++,process.stdout.write(`${JSON.stringify({taskId:event.taskId,...event.tabId?{tabId:event.tabId}:{},state:event.state,at:event.at})}
7
7
  `),!until.has(event.state))return;finish(()=>resolve2({ok:!0,watched:[...taskIds],until:[...until],events,matched:{taskId:event.taskId,...event.tabId?{tabId:event.tabId}:{},state:event.state}}))}),deadline=setTimeout(()=>{finish(()=>reject(new ApiError(`no watched task reached ${[...until].join("/")} within ${timeoutMs}ms`,"WATCH_TIMEOUT",{watched:[...taskIds],until:[...until],events,hint:"the state may simply not have happened yet \u2014 `collect --task-ids` shows where each task is right now",nextCommandArgs:["api","collect","--task-ids",[...taskIds].join(",")]})))},timeoutMs),heartbeat=setInterval(()=>{daemon.request("daemon.status").catch(()=>{finish(()=>reject(new ApiError("the daemon went away while watching","DAEMON_GONE",{watched:[...taskIds],events,hint:"the watch is over and nothing was missed on purpose \u2014 re-run it once the daemon is back",nextCommandArgs:["daemon","status"]})))})},HEARTBEAT_MS);daemon.subscribe({channels:["engine-state"]}).catch((err)=>{finish(()=>reject(err))})})}var WATCH_VERB={name:"watch",group:"read",summary:"Block until a watched task's engine reaches one of --until's states, streaming every transition as NDJSON on the way \u2014 the push-driven replacement for a `collect` polling loop. Each line is { taskId, tabId?, state, at }; the usual single result object follows when the watch ends. Exits 0 on a match (with `matched`), WATCH_TIMEOUT when --timeout elapses first, DAEMON_GONE when the daemon dies mid-watch (reconnect and re-run \u2014 this verb never reconnects on its own). `dead` is watchable and is the one state polling is worst at: a SIGKILLed engine fires no hook, so the daemon writes it from the pty exit record and pushes it here immediately.",flags:[{name:"task-ids",type:"csv",placeholder:"a,b,c",description:"Comma-separated task ids to watch."},{name:"group",type:"string",placeholder:"GROUPID",description:"Watch every task of one fan-out round (the `groupId` that `add --count` returns)."},{name:"until",type:"string",required:!0,placeholder:"STATE[,STATE]",description:`Stop at the first of these engine states: ${WATCHABLE_STATES.join(", ")}. A state that does not exist is refused up front \u2014 a typo would otherwise wait forever.`},{name:"timeout",type:"int",placeholder:"MS",description:`Give up after this many milliseconds (default ${DEFAULT_TIMEOUT_MS}). Timing out is WATCH_TIMEOUT, exit non-zero \u2014 it says nothing happened, never that nothing will.`}],handler:watch};var DEFAULT_PAGE_MESSAGES=40,MAX_PAGE_MESSAGES=50,PAGE_BYTE_BUDGET=131072,STRING_CLIP_CHARS=16384,TERMINAL_TAIL_LINES=200,TERMINAL_TAIL_BYTES=65536;function encodeCursor(cursor){return Buffer.from(JSON.stringify(cursor),"utf8").toString("base64url")}function decodeCursor(raw,taskId){let parsed;try{parsed=JSON.parse(Buffer.from(raw,"base64url").toString("utf8"))}catch{throw new ApiError("invalid cursor (not a read-output cursor)","CURSOR_INVALID")}let c=parsed;if(!(c!==null&&typeof c==="object"&&c.v===1&&typeof c.task==="string"&&(c.src==="history"&&typeof c.sid==="string"&&typeof c.idx==="number"||c.src==="terminal"&&typeof c.off==="number"&&(c.tab===void 0||typeof c.tab==="string"))))throw new ApiError("invalid cursor (unknown version or shape)","CURSOR_INVALID");if(c.task!==taskId)throw new ApiError(`cursor belongs to task ${c.task}, not ${taskId}`,"CURSOR_TASK_MISMATCH");return c}function clipStrings(value){if(typeof value==="string"){if(value.length<=STRING_CLIP_CHARS)return value;let points=[...value];if(points.length<=STRING_CLIP_CHARS)return value;return`${points.slice(0,STRING_CLIP_CHARS).join("")}\u2026[+${points.length-STRING_CLIP_CHARS} chars clipped]`}if(Array.isArray(value))return value.map(clipStrings);if(value!==null&&typeof value==="object"){let out={};for(let[k,v]of Object.entries(value))out[k]=clipStrings(v);return out}return value}function buildHistoryPage(messages,startIdx,limit){let page=[],bytes=0,limited=!1,i=startIdx;for(;i<messages.length&&page.length<limit;i++){let clipped=clipStrings(messages[i]),size=JSON.stringify(clipped).length;if(page.length>0&&bytes+size>PAGE_BYTE_BUDGET){limited=!0;break}page.push(clipped),bytes+=size}return{page,nextIdx:i,limited}}function terminalLines(text){return terminalRows(text)}function boundedTail(text){let lines=terminalLines(text),start=Math.max(0,lines.length-TERMINAL_TAIL_LINES),bytes=0;for(let i=lines.length-1;i>=start;i--)if(bytes+=(lines[i]?.length??0)+1,bytes>TERMINAL_TAIL_BYTES&&i<lines.length-1){start=i+1;break}return{tail:lines.slice(start),truncated:start>0}}function sourceChanged(detail){return new ApiError(`${detail} \u2014 restart the read without the cursor`,"SOURCE_CHANGED")}async function readTaskOutput(input,deps){let limit=Math.min(Math.max(input.limit??DEFAULT_PAGE_MESSAGES,1),MAX_PAGE_MESSAGES);if(input.tab&&input.source==="history")throw new ApiError("--tab reads one terminal tab; --source history is task/worktree-scoped","BAD_FLAG");if(input.cursor){let cursor=decodeCursor(input.cursor,input.taskId);if(input.source!=="auto"&&input.source!==cursor.src)throw new ApiError(`cursor is pinned to source "${cursor.src}" but --source is "${input.source}"`,"CURSOR_INVALID");if(input.tab&&cursor.src!=="terminal")throw new ApiError(`cursor is pinned to source "${cursor.src}" but --tab reads a terminal tab`,"CURSOR_INVALID");if(cursor.src==="terminal"&&(cursor.tab??null)!==(input.tab??null))throw new ApiError(`cursor is pinned to tab ${cursor.tab??"canonical"} \u2014 pass the same --tab or restart without the cursor`,"CURSOR_INVALID");return cursor.src==="history"?continueHistory(input,deps,cursor,limit):continueTerminal(input,deps,cursor)}if(input.tab||input.source==="terminal")return firstTerminalPage(input,deps,null);let first=await tryFirstHistoryPage(input,deps,limit);if(typeof first!=="string")return first;if(input.source==="history")throw new ApiError(`structured history unavailable for ${input.taskId}: ${first}`,"HISTORY_REQUIRED");return firstTerminalPage(input,deps,first)}async function currentSessionId(history,worktree){let ids=await history.listSessionIdsForWorktree(worktree);return ids.length>0?ids[ids.length-1]??null:null}async function tryFirstHistoryPage(input,deps,limit){if(!deps.history)return"engine_unsupported";if(!input.worktree)return"history_missing";let sid;try{sid=await currentSessionId(deps.history,input.worktree)}catch{return"history_unreadable"}if(!sid)return"history_missing";let messages;try{messages=await deps.history.readHistory(sid)}catch{return"history_unreadable"}return historyEnvelope(input.taskId,sid,messages,0,limit)}async function continueHistory(input,deps,cursor,limit){if(!deps.history||!input.worktree)throw sourceChanged("the engine no longer provides structured history");let sid,messages;try{sid=await currentSessionId(deps.history,input.worktree),messages=sid===cursor.sid?await deps.history.readHistory(cursor.sid):[]}catch{throw new ApiError("history became unreadable \u2014 retry, or restart without the cursor","HISTORY_UNREADABLE")}if(sid!==cursor.sid)throw sourceChanged(`the task's engine session changed (was ${cursor.sid}, now ${sid??"none"})`);if(cursor.idx>messages.length)throw sourceChanged("the pinned transcript shrank");return historyEnvelope(input.taskId,cursor.sid,messages,cursor.idx,limit)}function historyEnvelope(taskId,sessionId,messages,startIdx,limit){let{page,nextIdx,limited}=buildHistoryPage(messages,startIdx,limit);return{taskId,source:"history",history:{sessionId,messages:page,returnedMessageCount:page.length,totalMessages:messages.length,limited},cursor:encodeCursor({v:1,task:taskId,src:"history",sid:sessionId,idx:nextIdx}),fallbackReason:null,warnings:[]}}async function firstTerminalPage(input,deps,fallbackReason){let t=await deps.peekTerminal(input.tab);if(!t||t==="host-unreachable"){let unreachable=t==="host-unreachable";return{taskId:input.taskId,source:"terminal",terminal:{tail:[],truncated:!1,live:!1,tab:input.tab},cursor:null,fallbackReason:unreachable?"pty_host_unreachable":fallbackReason,warnings:[unreachable?"the pty host could not be reached \u2014 this is 'could not look', not 'no session'":"no live terminal session for this task"]}}let{tail,truncated}=boundedTail(t.text);return{taskId:input.taskId,source:"terminal",terminal:{tail,truncated,live:t.live,exit:t.exit??null,tab:input.tab},cursor:encodeCursor({v:1,task:input.taskId,src:"terminal",pid:t.pid,off:t.offset,fr:fallbackReason,tab:input.tab}),fallbackReason,warnings:[]}}async function continueTerminal(input,deps,cursor){let t=await deps.peekTerminal(cursor.tab,cursor.off);if(t==="host-unreachable")throw sourceChanged("the pty host could not be reached");if(!t)throw sourceChanged("the terminal session is gone");if(t.pid!==cursor.pid)throw sourceChanged("the terminal session restarted (new process)");let warnings=t.sinceValid?[]:["scrollback trimmed \u2014 there is a gap before this page"],{tail,truncated}=boundedTail(t.text),fr=cursor.fr??null;return{taskId:input.taskId,source:"terminal",terminal:{tail,truncated,live:t.live,exit:t.exit??null,tab:cursor.tab},cursor:encodeCursor({v:1,task:input.taskId,src:"terminal",pid:t.pid,off:t.offset,fr,tab:cursor.tab}),fallbackReason:fr,warnings}}async function peekTaskTerminal(taskId,engineBin,tab,sinceOffset){let host=await openPtyHost();if(!host)return"host-unreachable";try{let key;if(tab)key=`${taskId}::${tab}`;else{let sessions=await listSessionsOrNull(host.rpc);if(sessions===null)return"host-unreachable";key=findEngineKey(sessions,taskId,engineBin)??sessions.find((s)=>s.key===`${taskId}::tab-1`)?.key}if(!key)return null;let res;try{res=await host.rpc.request("pty.peek",{key,sinceOffset})}catch{return"host-unreachable"}if(!res.exists){if(tab)throw new ApiError(`tab ${tab} has no hosted session on task ${taskId} \u2014 see \`rove api pty-list\` for live tabs`,"TAB_NOT_FOUND");return null}return{pid:res.pid,offset:res.offset,text:Buffer.from(res.data,"base64").toString("utf8"),sinceValid:res.sinceValid,live:res.alive,exit:res.exit??null}}catch(err){if(err instanceof ApiError)throw err;return null}finally{host.close()}}async function handleReadOutput(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.str("task-id");if(!taskId){let active=await resolveActiveTaskId(daemon);if(!active)throw new ApiError("no --task-id given and no active task \u2014 pass --task-id","MISSING_TARGET");taskId=active}let{task}=await daemon.request("task.get",{taskId}),vendor=task.vendor,engineBin=vendor||task.command?taskEngineArgv(task)[0]:void 0,tab=ctx.args.str("tab"),deps={history:vendor&&supportsStructuredHistory(sessionProtocol(vendor))?protocolEntry(vendor).history:null,peekTerminal:(tabId,sinceOffset)=>peekTaskTerminal(taskId,engineBin,tabId,sinceOffset)},envelope=await readTaskOutput({taskId,worktree:task.worktreePath??null,source:ctx.args.enumOf("source")??"auto",tab,cursor:ctx.args.str("cursor"),limit:ctx.args.int("limit")},deps),running=await ctx.runtime.isTaskRunning(taskId,taskEngineArgv(task));return{vendor:vendor??null,running,...envelope}}var READ_OUTPUT_VERB={name:"read-output",group:"read",summary:"Read a task's engine output as bounded, cursor-paged JSON: the engine's own structured history when available, else a labeled terminal tail (typed fallbackReason). --tab tab-N reads one exact terminal tab. Read-only; the cursor stays pinned to one source/session/tab (SOURCE_CHANGED when it moved).",flags:[{name:"task-id",type:"string",placeholder:"ID",description:"Target task id (defaults to the active task)."},{name:"tab",type:"string",placeholder:"TAB",description:"Read exactly this terminal tab's hosted session (e.g. tab-3) instead of the canonical engine tab. Terminal-only read; cannot combine with --source history."},{name:"source",type:"enum",values:["auto","history","terminal"],default:"auto",description:"auto = structured history else terminal fallback; history = require structured (typed error instead of fallback); terminal = bounded terminal tail."},{name:"cursor",type:"string",placeholder:"C",description:"Opaque cursor from the previous page. Pinned to that page's source and session."},{name:"limit",type:"int",placeholder:"N",default:String(DEFAULT_PAGE_MESSAGES),description:`History messages per page (default ${DEFAULT_PAGE_MESSAGES}, max ${MAX_PAGE_MESSAGES}).`}],handler:handleReadOutput};var READ_VERBS=[{name:"list",group:"read",summary:"List all tasks. Returns { tasks, activeTaskId } \u2014 `activeTaskId` is the shared focus verbs default to when --task-id is omitted (null = no active task), the audit read for any implicit-target delivery.",flags:[],handler:list},{name:"get-task",group:"read",summary:"Read one task's metadata + terminal tabs. `.running` = any hosted engine tab is live; `.tabs[]` (id/kind/vendor/liveVendor/lastTitle/alive) is the discovery read for `send --tab tab-N`; `.task.dispatcher` = the Rove session (task+tab) that created it, when one did; `.task.prStatus.checkState` (none|pending|passing|failing|unknown) is Rove's OWN CI truth for the branch's PR \u2014 `passing` is what \"CI is green\" means, never a local test run. `.task.worktreePath` is where the files live; the user only ever sees `.task.title` and `.task.branch`, so refer to the task by those.",flags:[F.taskId()],handler:getTask},{name:"pty-list",group:"read",summary:"List hosted PTY sessions (key, alive, pid, command, live OSC window title). Returns { sessions }: `[]` = a live pty host with nothing running (the fleet IS idle); `null` = no pty host to ask, so this is `couldn't look` and says NOTHING about what is running.",flags:[],offline:!0,handler:handlePtyList},{name:"collect",group:"read",summary:"Read-only health snapshot of a parallel round: identity, branch, lineage (.dispatcher, .groupId), .running (pty-host process truth, not a cached status), .activity (daemon engine state + how long it has been in it, null when unknowable), per-tab .tabs with a dead tab's exit cause AND output tail, uncommitted .changes (non-zero = it cannot land; null = could not read git \u2014 do NOT treat as clean), and committed .base (ahead count + diffstat \u2014 ahead:0 is the `succeeded but committed nothing` tell). Select with --group (one fan-out round), --repo, or --task-ids.",flags:[{name:"task-ids",type:"csv",placeholder:"a,b,c",description:"Comma-separated task ids."},{name:"group",type:"string",placeholder:"GROUPID",description:"Every task of one fan-out round (the `groupId` that `add --count` returns)."},F.repo(!1)],handler:collect},DIGEST_VERB,AGENT_TURNS_VERB,INSPECT_VERB,READ_OUTPUT_VERB,WATCH_VERB];var WORK_ITEM_STATES=["open","closed","all"],WORK_ITEM_VERBS=[{name:"workitem-list",group:"workitems",summary:"List a repo's GitHub issues through the `gh` CLI. Read-only \u2014 nothing is copied into Rove's own issue store.",flags:[F.repo(),{name:"state",type:"enum",values:WORK_ITEM_STATES,default:"open",description:"Issue state filter."},{name:"limit",type:"int",placeholder:"N",default:"20",description:"Max items (1-50, max 50)."},{name:"search",type:"string",placeholder:"Q",description:"Free-text search passed to `gh --search`."},{name:"assignee",type:"string",placeholder:"USER",description:"Only items assigned to this user; `@me` for yourself."},{name:"label",type:"string",placeholder:"L",description:"Only items carrying this label."}],handler:(ctx)=>simpleRpc(ctx,"workitem.list",{repo:ctx.args.requireRepo("repo"),...ctx.args.str("state")?{state:ctx.args.str("state")}:{},...ctx.args.int("limit")!==void 0?{limit:ctx.args.int("limit")}:{},...ctx.args.str("search")?{search:ctx.args.str("search")}:{},...ctx.args.str("assignee")?{assignee:ctx.args.str("assignee")}:{},...ctx.args.str("label")?{labels:[ctx.args.str("label")]}:{}})},{name:"workitem-start",group:"workitems",summary:"Start a task on one GitHub issue: creates a worktree + engine session whose first message carries the issue title, body, and URL. The task keeps a link back to the issue.",flags:[F.repo(),{name:"number",type:"int",required:!0,placeholder:"N",description:"Issue number."},F.vendor(),{name:"base-branch",type:"string",placeholder:"B",description:"Base ref the worktree branches from."}],handler:(ctx)=>simpleRpc(ctx,"workitem.start",{repo:ctx.args.requireRepo("repo"),number:ctx.args.int("number"),...ctx.args.vendor()?{vendor:ctx.args.vendor()}:{},...ctx.args.str("base-branch")?{baseRef:ctx.args.str("base-branch")}:{}})}];var WORKTREE_VERBS=[{name:"ensure-worktree",group:"worktree",summary:"Materialize a task's git worktree on disk now (without starting an engine). Returns { worktreePath }.",flags:[F.taskId()],handler:(ctx)=>simpleRpc(ctx,"task.ensureWorktree",{taskId:ctx.args.require("task-id")})},{name:"remove-worktree",group:"worktree",summary:"Remove a task's git worktree directory, keeping the TASK and its BRANCH \u2014 the inverse of ensure-worktree, which can materialize it again. Same path as the Worktrees page's delete: the session is torn down first, a dirty tree is refused without --force, and every forced removal takes a salvage snapshot into refs/rove/salvage/<branch>-<stamp>. Refuses the project's own checkout (BASE_CHECKOUT) and the worktree the caller is running from (CALLER_WORKTREE). Use `delete` instead to end the task itself. Returns { worktreePath, branch, removed, residue? }.",flags:[F.taskId(),{name:"force",type:"bool",description:"Remove even with uncommitted changes (a salvage snapshot is taken first). Never deletes the branch."}],handler:removeTaskWorktree},{name:"discover-adoptable",group:"worktree",summary:"List existing git worktrees in a repo not yet tracked as Rove tasks. Returns { worktrees }.",flags:[F.repo()],handler:(ctx)=>simpleRpc(ctx,"worktree.discoverAdoptable",{repo:ctx.args.requireRepo("repo")})},{name:"adopt",group:"worktree",summary:"Import an existing git worktree as a Rove task. Returns { task }.",flags:[F.repo(),{name:"worktree",type:"string",required:!0,placeholder:"PATH",description:"Path of the worktree to adopt."},{name:"branch",type:"string",placeholder:"B",description:"Branch override (else the worktree's own)."},F.command(),F.title()],handler:adopt}];async function handleSchema(ctx){let verbName=ctx.args.str("verb");if(verbName){let v=findVerb(verbName);if(!v)throw unknownVerbError(verbName);return verbSchema(v)}let group=ctx.args.str("group");if(group)return groupSchema(group);if(ctx.args.bool("all"))return fullSchema();return schemaIndex()}var VERB_ALIASES={"spawn-task":"add"},RETIRED_VERBS={"fan-out":{hint:"fan-out was folded into `add`: pass --count N (or --agents claude:2,codex:1) to spawn N parallel tasks of one prompt",nextCommandArgs:["api","add","--help"]},"set-vendor":{hint:"set-vendor was replaced by `set-command`, which takes the engine's raw launch command (an engine id from `engine-list`, or a full command line)",nextCommandArgs:["api","set-command","--help"]},archive:{hint:"archive was removed: there is no hide-without-delete anymore \u2014 use `delete` to remove a finished task and its worktree; the git branch survives (pass --delete-branch explicitly only when the history may go)",nextCommandArgs:["api","delete","--help"]}},SCHEMA_STEP={hint:"list every valid verb + flag as JSON, then retry with a real verb",nextCommandArgs:["api","schema"]};function unknownVerbError(verbName){let retired=RETIRED_VERBS[verbName];if(retired)return new ApiError(`unknown verb: ${verbName} (removed)`,"UNKNOWN_VERB",{hint:retired.hint,nextCommandArgs:[...retired.nextCommandArgs]});return new ApiError(`unknown verb: ${verbName}`,"BAD_VERB",SCHEMA_STEP)}var SCHEMA_VERB={name:"schema",group:"discover",summary:"Explore the API. Default = a COMPACT index (groups + verb summaries, no flags). Drill in with --verb / --group; --all for the full spec.",flags:[{name:"verb",type:"string",placeholder:"NAME",description:"Full flag detail for ONE verb."},{name:"group",type:"string",placeholder:"G",description:"List the verbs in one group (compact)."},{name:"all",type:"bool",description:"The COMPLETE spec \u2014 every verb AND every flag (large; avoid by default)."}],offline:!0,handler:handleSchema},VERBS=[SCHEMA_VERB,ENGINE_LIST_VERB,...READ_VERBS,...CREATE_VERBS,...DRIVE_VERBS,...FEEDBACK_VERBS,...ISSUE_VERBS,...ROUTINE_VERBS,...WORK_ITEM_VERBS,...EDIT_VERBS,...LIFECYCLE_VERBS,...WORKTREE_VERBS],API_VERBS=VERBS.map((v)=>v.name),VERB_GROUPS=(()=>{let byGroup=Object.fromEntries(VERB_GROUP_IDS.map((g)=>[g,[]]));for(let v of VERBS)byGroup[v.group].push(v.name);return byGroup})();function findVerb(name){let canonical=VERB_ALIASES[name]??name;return VERBS.find((v)=>v.name===canonical)}
8
8
  export{parseFlags,validateAgainstSpec,VerbArgs,parseAgentsSpec,buildCountPlan,API_SCHEMA_VERSION,verbSchema,schemaIndex,fullSchema,verbHelp,apiUsage,takeIdentityWarning,deliverPrompt,defaultApiRuntime,VERB_ALIASES,RETIRED_VERBS,unknownVerbError,VERBS,API_VERBS,VERB_GROUPS,findVerb};
@@ -4,5 +4,5 @@ import{generateCompletions,isShellKind,mergeSubVerbs,shippedCompletionsPath}from
4
4
 
5
5
  ${usage}`),process.exit(2)};if(rest.some((arg)=>HELP_WORDS.includes(arg))){process.stdout.write(usage);return}let flags=rest.filter((arg)=>arg.startsWith("-")),shells=rest.filter((arg)=>!arg.startsWith("-")),unknownFlag=flags.find((flag)=>flag!=="--path"&&flag!=="--install");if(unknownFlag)fail(`unknown option "${unknownFlag}"`);if(new Set(flags).size>1)fail("--path and --install are different things; pass one");let shell=shells.length===1?shells[0]:void 0;if(!isShellKind(shell))fail(`unknown shell "${shells.join(" ")}"`);let scriptPath=shippedCompletionsPath(shell,cliName,deps.shippedDir),shipped=existsSync(scriptPath)?scriptPath:null;if(flags[0]==="--path"){if(!shipped)fail(`no pre-generated ${shell} script at ${scriptPath}
6
6
  ${cliName} completions ${shell} # print the script to stdout instead`);process.stdout.write(`${shipped}
7
- `);return}if(flags[0]==="--install"){let[{installCompletions},{t}]=await Promise.all([import("./chunk-1mccpcrg.js"),import("./chunk-3xkh6kf7.js")]),completion=installCompletions(shell,deps.home,cliName,shipped),line=completion.installed?"onboarding.appliedCompletions":"onboarding.keptCompletions";process.stdout.write(`${t(line,{path:completion.path})}
8
- `);return}if(shipped){process.stdout.write(readFileSync(shipped,"utf8"));return}let{API_VERBS}=await import("./chunk-xbze970v.js");process.stdout.write(generateCompletions(shell,cliName,mergeSubVerbs(API_VERBS)))}export{runCompletionsSubcommand};
7
+ `);return}if(flags[0]==="--install"){let[{installCompletions},{t}]=await Promise.all([import("./chunk-4tv9vgwp.js"),import("./chunk-3xkh6kf7.js")]),completion=installCompletions(shell,deps.home,cliName,shipped),line=completion.installed?"onboarding.appliedCompletions":"onboarding.keptCompletions";process.stdout.write(`${t(line,{path:completion.path})}
8
+ `);return}if(shipped){process.stdout.write(readFileSync(shipped,"utf8"));return}let{API_VERBS}=await import("./chunk-mz2ppnp5.js");process.stdout.write(generateCompletions(shell,cliName,mergeSubVerbs(API_VERBS)))}export{runCompletionsSubcommand};