@sma1lboy/rove 0.9.293 → 0.9.294-next.287
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/chunk-0a4qc7ay.js +2 -0
- package/dist/cli/{chunk-yhcrvaws.js → chunk-0e0dd4gt.js} +1 -1
- package/dist/cli/{chunk-67fzhb7c.js → chunk-1s8etezx.js} +1 -1
- package/dist/cli/{chunk-e4fp3w22.js → chunk-289j5sz5.js} +1 -1
- package/dist/cli/{chunk-e5r66sx1.js → chunk-2dj8pyb0.js} +1 -1
- package/dist/cli/{chunk-200b7rn7.js → chunk-2qbnp370.js} +6 -6
- package/dist/cli/chunk-331wnz4r.js +2 -0
- package/dist/cli/{chunk-5972648c.js → chunk-35eh1h7a.js} +1 -1
- package/dist/cli/{chunk-04g017px.js → chunk-3pzncc4q.js} +3 -3
- package/dist/cli/{chunk-09kpyzbg.js → chunk-43q0dev6.js} +1 -1
- package/dist/cli/{chunk-j8wpqhhx.js → chunk-4aj7x7cj.js} +1 -1
- package/dist/cli/{chunk-j8v38hsn.js → chunk-53nrxdsk.js} +1 -1
- package/dist/cli/{chunk-73c8nd7c.js → chunk-555t2syq.js} +1 -1
- package/dist/cli/{chunk-8wp1g0qg.js → chunk-55xmk2bk.js} +1 -1
- package/dist/cli/{chunk-h4c927gw.js → chunk-6fmadgnr.js} +1 -1
- package/dist/cli/{chunk-e5dv15e5.js → chunk-6r74n1g2.js} +1 -1
- package/dist/cli/{chunk-4jern6cw.js → chunk-77zmjrpz.js} +1 -1
- package/dist/cli/chunk-7dmcpc3d.js +2 -0
- package/dist/cli/{chunk-1fxqg8qh.js → chunk-7z82k5mk.js} +1 -1
- package/dist/cli/{chunk-d469ea4m.js → chunk-843yxtz9.js} +1 -1
- package/dist/cli/chunk-86fzfqvw.js +3 -0
- package/dist/cli/{chunk-xx8pmcf0.js → chunk-86ssev5h.js} +1 -1
- package/dist/cli/{chunk-7s670aef.js → chunk-8t0mev2r.js} +1 -1
- package/dist/cli/{chunk-3ha43429.js → chunk-9f6gresp.js} +1 -1
- package/dist/cli/{chunk-k5bxc9qw.js → chunk-9rbbpgr7.js} +1 -1
- package/dist/cli/{chunk-btvs2v81.js → chunk-9y21c892.js} +1 -1
- package/dist/cli/{chunk-n7nejaez.js → chunk-amfmxj46.js} +5 -5
- package/dist/cli/chunk-dqbf0mhd.js +2 -0
- package/dist/cli/{chunk-24q493p3.js → chunk-e80q746v.js} +1 -1
- package/dist/cli/{chunk-xpk09a6z.js → chunk-enpy65x0.js} +1 -1
- package/dist/cli/chunk-f2w2txz5.js +2 -0
- package/dist/cli/{chunk-vmrgfd92.js → chunk-fdwxkssa.js} +1 -1
- package/dist/cli/{chunk-ap1r5367.js → chunk-fevt0hdq.js} +1 -1
- package/dist/cli/chunk-g1w5j892.js +2 -0
- package/dist/cli/{chunk-0zjr0a58.js → chunk-g2whw0hn.js} +1 -1
- package/dist/cli/{chunk-re93eych.js → chunk-g7yc7ypx.js} +1 -1
- package/dist/cli/chunk-h3ay33cy.js +2 -0
- package/dist/cli/{chunk-fba1vx00.js → chunk-h8bcerx0.js} +1 -1
- package/dist/cli/{chunk-zq241gyj.js → chunk-hkace0f2.js} +11 -6
- package/dist/cli/{chunk-fgmzgap8.js → chunk-hpj3yt0a.js} +1 -1
- package/dist/cli/{chunk-8t19x73d.js → chunk-hrmey2tv.js} +1 -1
- package/dist/cli/{chunk-z0djv8js.js → chunk-jcn997j5.js} +2 -2
- package/dist/cli/{chunk-t9eppxpn.js → chunk-k4jvvq3e.js} +1 -1
- package/dist/cli/{chunk-b90m8y5x.js → chunk-krg03vp6.js} +2 -2
- package/dist/cli/chunk-m781veb4.js +13 -0
- package/dist/cli/{chunk-mv3avbjy.js → chunk-m81wcbax.js} +1 -1
- package/dist/cli/{chunk-k4373zq1.js → chunk-mztn6b5d.js} +1 -1
- package/dist/cli/chunk-n2fhxnfh.js +8 -0
- package/dist/cli/chunk-n4gvehjb.js +2 -0
- package/dist/cli/chunk-nr8pxs18.js +5 -0
- package/dist/cli/{chunk-a7rt83vq.js → chunk-nzc2dxpa.js} +1 -1
- package/dist/cli/{chunk-7tx957tj.js → chunk-pm0h06xq.js} +1 -1
- package/dist/cli/chunk-pne75syz.js +2 -0
- package/dist/cli/{chunk-wy3wataa.js → chunk-pqmew5ec.js} +1 -1
- package/dist/cli/chunk-q0zc6khk.js +2 -0
- package/dist/cli/{chunk-cx5532jd.js → chunk-qdhn4fkk.js} +1 -1
- package/dist/cli/{chunk-z3w6ex19.js → chunk-qrggd7r7.js} +1 -1
- package/dist/cli/{chunk-090ettyy.js → chunk-rywjrwke.js} +1 -1
- package/dist/cli/{chunk-1rdgjkfq.js → chunk-saz6bjk3.js} +1 -1
- package/dist/cli/{chunk-5qaehxn9.js → chunk-shj563q8.js} +1 -1
- package/dist/cli/{chunk-6f9pye62.js → chunk-st0w18db.js} +1 -1
- package/dist/cli/{chunk-an6tb9ws.js → chunk-swsk86px.js} +13 -13
- package/dist/cli/{chunk-ws7t6j5y.js → chunk-v5d4b79w.js} +1 -1
- package/dist/cli/{chunk-zncmx957.js → chunk-vcwfmhwj.js} +1 -1
- package/dist/cli/{chunk-0gg76kw4.js → chunk-vrcxta5e.js} +3 -3
- package/dist/cli/{chunk-vfq2bbv7.js → chunk-vw2e6t8s.js} +1 -1
- package/dist/cli/chunk-vz3bagem.js +2 -0
- package/dist/cli/{chunk-ejkar8qk.js → chunk-wmv5wy66.js} +1 -1
- package/dist/cli/chunk-wpajzcpn.js +3 -0
- package/dist/cli/{chunk-yx3q2rek.js → chunk-xssbbs39.js} +1 -1
- package/dist/cli/{chunk-g6bpr913.js → chunk-xxy0egyg.js} +1 -1
- package/dist/cli/{chunk-nd214zb8.js → chunk-y0b0st3v.js} +1 -1
- package/dist/cli/{chunk-fvm9jrmz.js → chunk-yhe8zkf3.js} +1 -1
- package/dist/cli/{chunk-q70sf5gq.js → chunk-z1zxx05p.js} +1 -1
- package/dist/cli/chunk-z35jsvwk.js +3 -0
- package/dist/cli/{chunk-etjhj9vj.js → chunk-z5mzv3cd.js} +1 -1
- package/dist/cli/{chunk-xkpnrbs5.js → chunk-zgz78nt4.js} +1 -1
- package/dist/cli/{chunk-q2kf794g.js → chunk-zv7n0aw0.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/completions/rove.bash +2 -2
- package/dist/completions/rove.fish +2 -2
- package/dist/completions/rove.zsh +2 -2
- package/dist/skills/rove/SKILL.md +1 -1
- package/dist/skills/rove/references/api-flags.md +29 -28
- package/dist/web/assets/{index-DHeoZMlK.js → index-BnvxBz2M.js} +5 -5
- package/dist/web/assets/{term-mount-DA2lh8SU.js → term-mount-CSBpwtdK.js} +1 -1
- package/dist/web/index.html +1 -1
- package/dist/web/relay/index.html +5 -5
- package/package.json +1 -1
- package/dist/cli/chunk-04qf2bxc.js +0 -2
- package/dist/cli/chunk-1w7pmkn1.js +0 -15
- package/dist/cli/chunk-4v2b289m.js +0 -2
- package/dist/cli/chunk-5ak2dcec.js +0 -2
- package/dist/cli/chunk-5fc51f8e.js +0 -2
- package/dist/cli/chunk-9yqa4w9p.js +0 -3
- package/dist/cli/chunk-a5f3mddw.js +0 -2
- package/dist/cli/chunk-kqbntvqn.js +0 -2
- package/dist/cli/chunk-ksm6jjq9.js +0 -2
- package/dist/cli/chunk-m711bzrr.js +0 -2
- package/dist/cli/chunk-nbcm8d58.js +0 -3
- package/dist/cli/chunk-q3cnqs5k.js +0 -3
- package/dist/cli/chunk-sdmzsn5n.js +0 -2
- package/dist/cli/chunk-ze844eg8.js +0 -2
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{PER_SESSION,classifyTier,describeTierBlock,isAutoRoutingTier,listFiles,liveSourceProtocol,loadPreviewData,planWorktreeHandoff,readAutoRoutingTable,readClassifierConfig,resolveBase,runWorktreeGit,searchTasks,statusFiles,statusFilesBranch,taskGroupOf,tierBlock}from"./chunk-g6bpr913.js";import{ensurePluginEnginesLoaded,registeredEngineIds}from"./chunk-w14jz8pd.js";import{resolveActiveTaskId}from"./chunk-btvs2v81.js";import{listPaneLaunches}from"./chunk-38hnq4aq.js";import{detectEngineStatus}from"./chunk-ejkar8qk.js";import{resolveEditorLaunch}from"./chunk-rz19rphb.js";import{DeviceLogin,GH_ENV,GITHUB_HOST,runTool,spawnGhLogin}from"./chunk-rset5pt8.js";import{PLACEHOLDER_TASK_TITLE,SHELL_TASK_TITLE,deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import{DIRTY_WORKTREE_CODE,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,canonicalize}from"./chunk-gbe6hggt.js";import{ENGINE_ACTIVITY_KINDS,TASK_ACTIVITY_STATES}from"./chunk-17e2tgyg.js";import{canonicalEngineTab}from"./chunk-q8ffd1pc.js";import{ISSUE_STATUSES}from"./chunk-je7egpqh.js";import{ROW_TOKEN_MAX_TEXT,ROW_TOKEN_TONES}from"./chunk-atn06ncf.js";import{DEFAULT_FEEDBACK_KIND,FEEDBACK_KINDS,isFeedbackKind,submitFeedback}from"./chunk-69xn50zm.js";import{cloneDirFor,cloneRepo,dispatcherEnvPayload,findCheckouts,forwardVerb,isCleanCheckout,noReplyAddress,ownSession,parseRepoRef,pickCheckout,primaryCheckouts,ptyScopeOf,readOwnDispatcher,recordSend,replyTabOf,repoIdOf,repoIdentity,requireMachine,resolveDispatcherTab,verifiedSelfSession,withPeerProvenance}from"./chunk-re93eych.js";import{resolvePtyOwner,tasksAtWorktreePath}from"./chunk-y0e28qha.js";import{dedupeMachines,isWindowsMachine,listMachines,machineSshArgs}from"./chunk-1w7pmkn1.js";import{ulid}from"./chunk-qkehg2c1.js";import{resolvePreferredVendor}from"./chunk-k6gx8sqh.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{CURRENT_VERSION}from"./chunk-fvqehvp7.js";import{ENGINE_NOT_OBSERVED_REASON,ENGINE_START_POLL_MS,ENGINE_START_PROBE_MS,deliverHostedPrompt,deliverToKey,ensurePtyHost,findEngineKey,killTaskSessions,listSessions,listSessionsOrNull,openAdmittedEngine,openPtyHost,outcomeFields,restoredTabLaunch,tabEngineBase,taskKeys}from"./chunk-mv3avbjy.js";import{awaitEngineProcess,enginePresence,findHostedEngineKey,hostedSessionFailureLine,isHostedTaskKey,listHostedSessions,openHostedSessionHost,readPersistedTerminalDefaultColors,screenErrorLine,sessionArgvNamesEngine,withDeliveryLock}from"./chunk-j8v38hsn.js";import{RemoteEngineLaunchError,allocateTab,applyTabOps,buildEngineSessionLaunch,closeTabsSnapshot,collapseSplit,findEditorTab,initialSplit,joinTaskTabs,launchReposOf,leaves,markCliTabSession,patchTabSplit,publishCliTabSnapshot,readDaemonTabs,readTabsSnapshot,removeLeaf,renameLeaf,renameTabsSnapshot,repoEnv,seedCanonicalTab,seedShellHome,shellIdentityInput,shellTabInput,splitActive,splitLeafPtyKey,tabPtyKeyFor,taskEngineArgv,trustEngineWorktree,trustExtraRepos,unregisteredTabIds,wireSplit}from"./chunk-fvm9jrmz.js";import{createRemoteLink,linkedWorktree,removeRemoteLink,runAsync}from"./chunk-6jcmdxza.js";import{GENERIC_PROTOCOL,describePreset,engineLaunchArgv,engineResumeArgv,listEnginePresets,protocolEntry,resolveCommandProtocol,roveApiInvocation,sessionProtocol,withPinnedSessionId}from"./chunk-e5r66sx1.js";import{normalizeRemoteUrl}from"./chunk-han0d078.js";import{ApiError,GROUP_MOD,VERB_GROUP_IDS,cliCaller,helpStep,promptMayHaveLanded,requireVerbInstalled,splitDaemonCode,verbInstalled}from"./chunk-jz1kj4sf.js";import{isBuiltinModInstalled}from"./chunk-v8nbqjwc.js";import{aliasKey,hostedKeyFor,isUnderKey,ptyScopeFor,unclaimedSessions}from"./chunk-g9ba25q5.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{terminalRows}from"./chunk-etfh8f4z.js";import{parseBoolLiteral}from"./chunk-zsfyj36g.js";import{expandTilde}from"./chunk-1feav1w3.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-yx3q2rek.js";import{engineEntry,getCapabilities,remoteNotesFiles,supportsStructuredHistory,vendorsWithEffortLevels,vendorsWithTurnReader}from"./chunk-wy3wataa.js";import{CONTRIB_ENGINE_IDS,installedEngineIds}from"./chunk-av0n24rf.js";import{DELIVERY_OUTCOMES,DELIVERY_SUMMARY_MAX_CHARS,MAX_DELIVERIES_PER_TASK,ROUTINE_RESPONSE_MAX_CHARS,SHOULD_RUN_SKIP_EXIT_CODE,SKIP_REASONS,deliveryFooter}from"./chunk-29b3pj9h.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{addSavedRepo,getSavedRepos,inspectRepo,isGitRepo,isRemoteRepoKey,isValidBranchName,resolveMainRepoRoot}from"./chunk-bgmpczgm.js";import{errorMessage,isDiskFull}from"./chunk-9gctbddn.js";import{loadStateFile}from"./chunk-p84bhs57.js";import{MULTI_REPO_CAP,canonicalPrUrl,gitRepoOf,lineageRootId,repoNameOf,rollupPr,taskCwd,taskRepos,todoCount,uniqueRepoName,workspaceCapabilities}from"./chunk-yfwn3fj5.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{ALL_VENDORS,DEFAULT_VENDOR,coerceVendorId}from"./chunk-h2m7em1e.js";import{pathWithin,samePath}from"./chunk-pn5ygqn6.js";import{defaultDaemonSocketPath}from"./chunk-7kgksv06.js";import{homeDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{readFileSync as readFileSync2}from"fs";import{resolve as resolve2}from"path";async function assertNotEmptySuccess(daemon,ctx,prompt){if(ctx.args.bool("allow-empty"))return;if(!/^\s*succeeded\s*[:\uff1a]/i.test(prompt))return;await refuseIfEmptyBranch(daemon,ctx,async()=>!0,["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])}async function assertNotEmptyDoneReport(daemon,ctx,report){if(ctx.args.bool("allow-empty")||report.outcome!=="done")return;await refuseIfEmptyBranch(daemon,ctx,async(taskId)=>{let{deliveries}=await daemon.request("delivery.list",{taskId});return deliveries.find((d)=>d.id===report.delivery)?.source==="send"},["api","report","--delivery",report.delivery,"--outcome","done","--summary",report.summary,...(report.evidence??[]).flatMap((e)=>["--evidence",e]),...report.next?["--next",report.next]:[],"--allow-empty"])}async function refuseIfEmptyBranch(daemon,ctx,applies,nextCommandArgs){let self=await ownSession(daemon);if(!self)return;let sender;try{if(!await applies(self.taskId))return;sender=(await daemon.request("task.get",{taskId:self.taskId})).task}catch{return}if(!workspaceCapabilities(sender).ownsBranch)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 run it again \u2014 or, if this task genuinely produced no commits (an investigation or a review), re-run with --allow-empty to say so explicitly",nextCommandArgs})}import{readFileSync}from"fs";import{isAbsolute,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}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."})},REPEAT_SEP="\x00";function setFlag(flags,key,value,repeatable){let prev=flags.get(key);flags.set(key,repeatable.has(key)&&prev!==void 0?`${prev}${REPEAT_SEP}${value}`:value)}function parseFlags(argv,booleanFlags=new Set,repeatableFlags=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==="envelope")continue;if(key2==="pretty")pretty=value!=="false"&&value!=="0";else if(key2==="help")help=value!=="false"&&value!=="0";else setFlag(flags,key2,value,repeatableFlags);continue}let key=arg.slice(2);if(key==="envelope")continue;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");setFlag(flags,key,next,repeatableFlags),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")||verb.name==="add"&&f.name==="repo"&&(flags.get("fork")||flags.get("no-worktree")||flags.get("isolate-in")||flags.get("handoff-from"));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"&®isteredEngineIds().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;caller;constructor(verb,flags,caller=cliCaller()){this.verb=verb;this.flags=flags;this.caller=caller}resolvePath(name,raw){let expanded=expandTilde(raw);if(isAbsolute(expanded))return expanded;if(this.caller.cwd===void 0)throw new ApiError(`--${name} must be an absolute path: this caller has no working directory`,"BAD_FLAG");return resolve(this.caller.cwd,expanded)}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}list(name){if(!this.spec(name).repeatable)throw Error(`internal: --${name} is not repeatable on verb "${this.verb.name}"`);let raw=this.flags.get(name);return raw===void 0?[]:raw.split(REPEAT_SEP).filter((v)=>v.length>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.verb.flags.some((f)=>f.name==="prompt")?this.str("prompt"):void 0,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;if(file==="-"&&!this.caller.cli)throw new ApiError("--prompt-file - reads stdin, which this caller cannot send; pass --prompt","BAD_FLAG");let text=readFileSync(file==="-"?0:this.resolvePath("prompt-file",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:this.resolvePath(name,v)}requirePath(name){return this.resolvePath(name,this.require(name))}requireRepo(name){return this.repoPath(name,this.require(name))}repoPath(name,raw){return isRemoteRepoKey(raw)?raw:this.resolvePath(name,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 probe=await runtime.inspectRepo(repoFlag),target=probe.root;if(!probe.usable)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;return await Promise.all([...new Set(repos)].map(async(repo)=>{if(samePath(repo,target)){resolved.set(repo,target);return}let{root,usable}=await runtime.inspectRepo(repo);if(resolved.set(repo,root),!samePath(root,target)&&!usable)unresolvable.add(repo)})),{target,matches:(repo)=>samePath(resolved.get(repo),target),unresolvableRepos:[...unresolvable].sort()}}async function simpleRpc(ctx,name,payload){let request=name;return daemonOf(ctx).request(request,payload)}async function handlePtyList(){let[{RoveDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-dtb0dqwh.js"),import("./chunk-b6xrkzhj.js")]),client=new RoveDaemonClient(defaultPtyHostSocketPath());try{return await client.connect(),await client.request("pty.list",{})}catch{return{sessions:null}}finally{client.close()}}function readJsonBody(source){let raw=readFileSync2(source==="-"?0:resolve2(process.cwd(),expandTilde(source)),"utf8"),parsed;try{parsed=JSON.parse(raw)}catch{throw new ApiError(`--json ${source} is not valid JSON`,"BAD_FLAG")}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw new ApiError("--json must be an object: {delivery, outcome, summary, evidence?, next?}","BAD_FLAG");let body=parsed,evidence=body.evidence;if(evidence!==void 0&&(!Array.isArray(evidence)||evidence.some((e)=>typeof e!=="string")))throw new ApiError("evidence must be an array of strings","BAD_FLAG");for(let key of["delivery","outcome","summary","next"])if(body[key]!==void 0&&typeof body[key]!=="string")throw new ApiError(`${key} must be a string`,"BAD_FLAG");return body}var FIELD_FLAGS=["delivery","outcome","summary","next"];function readBody(ctx){let json=ctx.args.str("json"),evidence=ctx.args.list("evidence");if(json===void 0)return{delivery:ctx.args.str("delivery"),outcome:ctx.args.str("outcome"),summary:ctx.args.str("summary"),evidence,next:ctx.args.str("next")};if(FIELD_FLAGS.some((f)=>ctx.args.str(f)!==void 0)||evidence.length>0)throw new ApiError("pass --json OR the individual flags, not both","BAD_FLAG");return readJsonBody(json)}async function report(ctx){let body=readBody(ctx);if(!body.delivery)throw new ApiError("--delivery is required","MISSING_FLAG");if(!body.outcome||!DELIVERY_OUTCOMES.includes(body.outcome))throw new ApiError(`--outcome must be one of ${DELIVERY_OUTCOMES.join("|")}`,"MISSING_FLAG");if(!body.summary?.trim())throw new ApiError("--summary is required","MISSING_FLAG");if(body.summary.length>DELIVERY_SUMMARY_MAX_CHARS)throw new ApiError(`summary is ${body.summary.length} characters; the cap is ${DELIVERY_SUMMARY_MAX_CHARS}`,"RESPONSE_TOO_LARGE",{hint:"Summarize: lead with the conclusion, put the detail in --evidence (commits, PR urls, paths)."});await assertNotEmptyDoneReport(daemonOf(ctx),ctx,{delivery:body.delivery,outcome:body.outcome,summary:body.summary,evidence:body.evidence,next:body.next});let res=await simpleRpc(ctx,"delivery.report",{deliveryId:body.delivery,outcome:body.outcome,summary:body.summary,...body.evidence?.length?{evidence:body.evidence}:{},...body.next?{next:body.next}:{}});if(res.delivery===null)throw new ApiError(`no delivery ${body.delivery}`,"DELIVERY_NOT_FOUND",{hint:"Copy the id from the [ROVE] report line of the prompt you were given; `deliveries --task-id <id>` lists them."});return res}var REPORT_VERB={name:"report",group:"drive",summary:`Close the report a delivered prompt asked for. Run it as the LAST step of the turn, before you stop: a turn that ends without it is flagged \`report_missing\` in the owner's Inbox (a [ROVE ROUTINE] turn with nothing to report just stops: its delivery goes \`quiet\`). --delivery is the id in the prompt's [ROVE] / [ROVE ROUTINE] line. Re-reporting replaces the earlier report; a late report on a flagged delivery clears the flag. --summary \u2264 ${DELIVERY_SUMMARY_MAX_CHARS} chars; put commits, PR urls, test results and paths in repeatable --evidence, and what the next tick should do in --next. Use --json - (stdin) for text with quotes or backticks. \`--outcome done\` on a \`send\` delivery 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:[{name:"delivery",type:"string",placeholder:"ID",description:"Delivery id, e.g. d-41."},{name:"outcome",type:"enum",values:DELIVERY_OUTCOMES,placeholder:"O",description:"done = finished what was asked; partial = some of it; blocked = needs the owner or an external fix; failed = tried and could not."},{name:"summary",type:"string",placeholder:"TEXT",description:"What was done (or why not)."},{name:"evidence",type:"string",placeholder:"X",repeatable:!0,description:"A commit, PR url, test command + result, or file path. Repeat the flag for several."},{name:"next",type:"string",placeholder:"TEXT",description:"What the next tick should do."},{name:"allow-empty",type:"bool",required:!1,description:"Report `done` from a task with zero commits (EMPTY_SUCCESS_REPORT is refused otherwise, on a `send` delivery). For work that legitimately produces no commits \u2014 an investigation, a review, a question answered."},{name:"json",type:"string",placeholder:"PATH",description:"Read {delivery, outcome, summary, evidence?, next?} as JSON from this file (`-` = stdin) instead of the flags."}],handler:report},DELIVERIES_VERB={name:"deliveries",group:"read",summary:`A task's armed deliveries, newest first (newest ${MAX_DELIVERIES_PER_TASK} are kept): status awaiting|reported|missing|skipped, the report (outcome, summary, evidence, next) and, for missing, why (cause turn-complete|turn-failed|engine-dead|stalled|interrupted|session-end|rate-limited + note; rate-limited raises no Inbox row and does not block) plus dismissedAt once the owner dismissed it (a missing row blocks \`send --if-runnable\` and routine ticks until a late report or that dismissal). A skipped row is a \`send --if-runnable\` tick should-run refused: \`skipped\` is the verdict {reason, detail?, until?, gateIds?}, \`repeats\` how many identical refusals (same tab, same reason) the one row stands for. The per-tick log a loop prompt should read instead of a growing MEMO file.`,flags:[F.taskId(!0),{name:"limit",type:"int",placeholder:"N",description:"At most N entries (default: all retained)."}],handler:async(ctx)=>simpleRpc(ctx,"delivery.list",{taskId:ctx.args.require("task-id"),...ctx.args.int("limit")!==void 0?{limit:ctx.args.int("limit")}:{}})};async function listAllEnginePresets(){let presets=await enginePresetsInList(),byProtocol=new Map,modelsOf=(protocol)=>{let pending=byProtocol.get(protocol);if(!pending){let list=engineEntry(protocol).listModels;pending=list?list().catch(()=>null):Promise.resolve(null),byProtocol.set(protocol,pending)}return pending};return Promise.all(presets.map(async(preset)=>({...preset,models:await modelsOf(preset.protocol)})))}async function enginePresetsInList(){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}function withStatus(presets){return Promise.all(presets.map(async(preset)=>{let status=await detectEngineStatus(preset.id).catch(()=>null);if(!status)return preset;let installed=status.binary.found;return{...preset,installed,ready:installed&&status.account?.kind!=="none"}}))}async function engineListIds(){return(await enginePresetsInList()).map((p)=>p.id)}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 (${CONTRIB_ENGINE_IDS.join(", ")}), and engines contributed by enabled plugins \u2014 each with its RAW launch command, exactly as it runs. Copy one into \`add --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. \`models\` is what the engine can name for \`--model\` (suggestions, not a closed set); null = Rove cannot list them for this engine. --status adds \`installed\` (its CLI is on this machine) and \`ready\` (installed, and signed in where Rove can read the login) to each. Returns { engines }.`,flags:[{name:"status",type:"bool",description:"Probe each engine on this machine: adds `installed` and `ready` to every row. Slower: a missing CLI is also looked for in the login shell."}],offline:!0,handler:async(ctx)=>{let engines=await listAllEnginePresets();return{engines:ctx.args.bool("status")?await withStatus(engines):engines}}};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 reasoning levels accept one (${vendorsWithEffortLevels().join(", ")} 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]})}function assertEngineAcceptsModel(engine,model,recover){if(engineEntry(engine).modelArgv)return;throw new ApiError(`engine ${engine} declares no model flag \u2014 it does not accept a model`,"BAD_MODEL",{engine,hint:"Only engines that declare a model flag accept one (claude, codex, kimi, pi, omp today); `engine-list` shows `models` per engine.",nextCommandArgs:[...recover]})}function vendorToRecord(task,engine){let recorded=coerceVendorId(task.vendor);return sessionProtocol(recorded)===engine?recorded:engine}async function readRunnability(daemon,taskId){try{return await daemon.request("task.runnability",{taskId})}catch{return}}async function shouldRun(ctx){let 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 verdict=await daemonOf(ctx).request("task.runnability",{taskId:ctx.args.require("task-id"),...tab?{tabId:tab}:{}});if(!verdict.run)throw new ApiError(`skip: ${verdict.reason}`,"SKIPPED",{...verdict});return verdict}var SHOULD_RUN_VERB={name:"should-run",group:"read",summary:`Would a tick sent to this task be used? Prints the verdict {run:true} or {run:false, reason, detail?, until?, gateIds?} and exits 0 on run, ${SHOULD_RUN_SKIP_EXIT_CODE} on skip (the verdict is still on stdout). reason, first match wins: ${SKIP_REASONS.join(" | ")}. \`awaiting-owner\` = an open gate (answer or withdraw it), \`report-missing\` = the last delivery ended unreported (late \`report\`, or dismiss its Inbox row), \`quota\` clears itself at \`until\`, \`engine-error\` / \`engine-dead\` clear on the engine's next turn or a restart, \`awaiting-permission\` = the engine waits on an approval, \`busy\` = a turn is running or the last delivery still awaits its report. A task whose only gate is answered-but-undelivered is runnable: the next tick carries the answer. Without --tab the whole task is judged and a dead engine is not a skip (\`send\` revives it); --tab tab-N judges that tab and a dead engine is \`engine-dead\`; --tab new judges only task-level state. To check and send in one step use \`send --if-runnable\`.`,flags:[F.taskId(!0),{name:"tab",type:"string",required:!1,placeholder:"TAB",description:'Judge exactly this tab (e.g. tab-2), or "new" for a tab about to be created. Omitted = the whole task.'}],handler:shouldRun};async function attentionDismiss(ctx){let delivery=ctx.args.require("delivery");if((await daemonOf(ctx).request("attention.dismiss",{deliveryId:delivery})).found===!1)throw new ApiError(`no delivery ${delivery}`,"DELIVERY_NOT_FOUND",{hint:"`deliveries --task-id <id>` lists a task's delivery ids; the Inbox row names it as d-N."});return{ok:!0,delivery,cleared:!0}}var ATTENTION_DISMISS_VERB={name:"attention-dismiss",group:"drive",summary:'Dismiss a `report_missing` Inbox row by its delivery id (d-N): the owner\'s deliberate "seen, carry on" for a tick that ended without a report. It unblocks `should-run` for the task. Opening or visiting the row never does this, and a late `report` clears it on its own. Idempotent; an unknown id is DELIVERY_NOT_FOUND.',flags:[{name:"delivery",type:"string",required:!0,placeholder:"ID",description:"Delivery id, e.g. d-41."}],handler:attentionDismiss};import path from"path";var TASK_STATUSES=["backlog","in_progress","in_review","done","canceled","error"];var TASK_FIELDS=["title","branch","parent","project","command","model","effort","pinned","kept","require-report","auto-fix-ci","status"],REPORT_FLAGS=["report-branch","report-pr","report-summary"];async function renameTab(ctx,taskId,tabId){let title=ctx.args.str("title"),others=[...TASK_FIELDS,...REPORT_FLAGS].filter((f)=>f!=="title"&&ctx.args.str(f)!==void 0);if(title===void 0||others.length>0)throw new ApiError("--tab only renames a tab: pass --title and no other field","BAD_FLAG",{hint:"Update the task's own fields in a separate call without --tab."});let daemon=daemonOf(ctx);if(!await renameTabsSnapshot(daemon,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 daemon.request("terminalTab.rename",{taskId,tabId,title});return{ok:!0,taskId,tabId,title,renamed:!0,clients:reply.clients??0}}async function resolveTarget(ctx,verb="update"){let explicit=ctx.args.str("task-id");if(explicit)return explicit;let self=await ownSession(daemonOf(ctx));if(!self)throw new ApiError("no --task-id given and the caller is not a verified rove session \u2014 pass --task-id ID","MISSING_TARGET",helpStep(verb));return self.taskId}async function projectRoot(ctx){let raw=ctx.args.str("project")?.trim();if(raw===void 0)return;if(raw==="")throw new ApiError("--project cannot be empty \u2014 pass the repo's path","BAD_FLAG");let root=await ctx.runtime.resolveRepoRoot(path.resolve(ctx.caller.cwd??process.cwd(),raw));if(!await ctx.runtime.isUsableRepo(root))throw new ApiError(`--project ${raw} is not inside a git repository`,"NOT_A_GIT_REPO",{hint:"clone or `git init` the project first, then pass its path"});return root}var NO_PARENT="none";async function reparentGroup(ctx,groupId){let parent=ctx.args.str("parent"),stray=["task-id","tab",...TASK_FIELDS.filter((f)=>f!=="parent"),...REPORT_FLAGS].filter((f)=>ctx.args.str(f)!==void 0);if(parent===void 0||parent===""||stray.length>0)throw new ApiError(`--group moves a whole fan-out round and takes only --parent ID (or \`none\`)${stray.length>0?` \u2014 drop ${stray.map((f)=>`--${f}`).join(", ")}`:""}`,"BAD_FLAG",helpStep("update"));let daemon=daemonOf(ctx),{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"]});if(members.some((t)=>t.id===parent))throw new ApiError(`${parent} is itself a member of group ${groupId} \u2014 a round cannot move under one of its own`,"PARENT_IN_GROUP",{hint:"pick a parent outside the round, or move the members one by one with --task-id"});let parentTaskId=parent===NO_PARENT?null:parent,replyTab=parentTaskId===null?void 0:await replyTabOf(ctx.runtime,daemon,parentTaskId),results=[],failures=0;for(let task of members)try{let moved=await simpleRpc(ctx,"task.setParent",{taskId:task.id,parentTaskId,...replyTab?{replyTab}:{}});results.push({taskId:task.id,status:"moved",...moved})}catch(err){failures++;let message=errorMessage(err),coded=err instanceof ApiError?{code:err.code,rest:message}:splitDaemonCode(message);results.push({taskId:task.id,status:"failed",error:coded?.rest??message,...coded?{code:coded.code}:{}})}return{ok:failures===0,groupId,count:members.length,failures,results}}async function updateTask(ctx){let group=ctx.args.str("group");if(group!==void 0)return reparentGroup(ctx,group);let tabId=ctx.args.str("tab"),taskId=tabId!==void 0?ctx.args.require("task-id"):await resolveTarget(ctx);if(tabId!==void 0)return renameTab(ctx,taskId,tabId);let title=ctx.args.str("title"),branch=ctx.args.str("branch"),parent=ctx.args.str("parent"),command=ctx.args.str("command")?.trim(),model=ctx.args.str("model")?.trim(),effort=ctx.args.str("effort")?.trim(),pinned=ctx.args.bool("pinned"),kept=ctx.args.bool("kept"),requireReport=ctx.args.enumOf("require-report"),autoFixCi=ctx.args.enumOf("auto-fix-ci"),status=ctx.args.enumOf("status"),report2={reportBranch:ctx.args.str("report-branch"),reportPr:ctx.args.int("report-pr"),reportSummary:ctx.args.str("report-summary")},reporting=Object.values(report2).some((v)=>v!==void 0);if(TASK_FIELDS.every((f)=>ctx.args.str(f)===void 0)&&!reporting)throw new ApiError(`nothing to update \u2014 pass at least one of ${TASK_FIELDS.map((f)=>`--${f}`).join(", ")}`,"BAD_FLAG",{nextCommandArgs:["api","update","--help"]});if(reporting&&status===void 0)throw new ApiError("--report-* is recorded with a status: pass --status too","BAD_FLAG",{hint:"A worker reporting delivery usually passes --status in_review (or done)."});if(command==="")throw new ApiError("--command cannot be empty","BAD_FLAG");if(parent==="")throw new ApiError("--parent cannot be empty \u2014 pass a task id, or `none` for top level","BAD_FLAG");let daemon=daemonOf(ctx),protocol=command?resolveCommandProtocol(command):void 0,project=await projectRoot(ctx),task,engine;if(model!==void 0||effort!==void 0){task=(await daemon.request("task.get",{taskId})).task,engine=taskEngine(command?{...task,command}:task);let recover=["api","get-task","--task-id",taskId];if(model!==void 0)assertEngineAcceptsModel(engine,model,recover);if(effort!==void 0)assertEngineAcceptsEffort(engine,effort,recover)}let applied=[],step=async(fields,method,payload)=>{let reply;try{reply=await simpleRpc(ctx,method,{taskId,...payload})}catch(err){if(applied.length===0)throw err;let message=err instanceof Error?err.message:String(err),code=err instanceof ApiError?err.code:"PARTIAL_UPDATE";throw new ApiError(`--${fields.join("/--")} failed after ${applied.join(", ")} applied: ${message}`,code,{applied:[...applied],failed:fields})}return applied.push(...fields),reply},reparented;if(parent!==void 0){let parentTaskId=parent===NO_PARENT?null:parent,replyTab=parentTaskId===null?void 0:await replyTabOf(ctx.runtime,daemon,parentTaskId);reparented=await step(["parent"],"task.setParent",{parentTaskId,...replyTab?{replyTab}:{}})}let regrouped;if(project!==void 0)regrouped=await step(["project"],"task.moveToProject",{repo:project});if(branch!==void 0)await step(["branch"],"task.setBranch",{branch});if(command)await step(["command"],"task.setCommand",{command,vendor:protocol});if(task&&engine){let recorded=vendorToRecord(protocol?{...task,vendor:protocol}:task,engine),fields=[...model!==void 0?["model"]:[],...effort!==void 0?["effort"]:[]];await step(fields,"task.setVendor",{vendor:recorded,model,effort})}if(title!==void 0)await step(["title"],"task.rename",{title});if(pinned!==void 0)await step(["pinned"],"task.pin",{pinned});if(kept!==void 0)await step(["kept"],"task.keep",{kept});if(requireReport!==void 0)await step(["require-report"],"task.requireReport",{required:requireReport==="on"});if(autoFixCi!==void 0)await step(["auto-fix-ci"],"task.autoFixCi",{enabled:autoFixCi==="on"});if(status!==void 0)await step(["status"],"task.status",{status,...report2});return{ok:!0,taskId,updated:applied,...reparented?{parent:reparented}:{},...regrouped?{project:{repo:regrouped.repo,moved:regrouped.moved,note:"regrouped only \u2014 the PTYs, cwd, worktree and branch stay where they were"}}:{},...command?{command,protocol,...protocol===GENERIC_PROTOCOL?{generic:!0}:{}}:{},...engine?{engine}:{}}}var EDIT_VERBS=[{name:"update",group:"edit",summary:"Change a task's metadata \u2014 any combination of title, branch (git branch -m if materialized, else recorded), parent, engine --command / --model / --effort (take effect on the next session rebuild), pin, and status + worker report \u2014 in one call. The flags are checked before anything is written; then they apply in order parent \u2192 branch \u2192 engine \u2192 title/pin/status, and a refusal mid-way names what already applied (`applied`). --parent ID re-parents the task without touching its engine, tabs, worktree or branch: the stored parent is ID's top-level ancestor (children never nest, as with `add` from a child; the task's own children come along, listed in `.parent.moved`) and the task's reply address becomes ID itself, so its bare `send` reaches ID (the caller's own tab when run from inside ID, else ID's live engine tab, else tab-1). `--parent none` makes the task top level and drops a reply address that pointed into its old tree. A parent must live on the same machine as the task. Archiving the stored parent, or `delete --cascade` on it, takes the task along. --group G --parent ID moves a whole fan-out round instead and takes nothing else. With --tab, renames that Terminal Tab instead (the API twin of the TUI's f2) and takes only --title. The status is a cosmetic LABEL: `--status canceled` closes, stops and cleans up nothing \u2014 `delete` ends a task. The --report-* fields record what the WORKER CLAIMS it delivered (`.report` on `get-task` / `collect`), deliberately apart from `.prStatus`, which the daemon polled from the forge; they merge onto any previous report and need --status. Returns { updated } \u2014 the fields written, in order.",flags:[{...F.taskId(!1),description:"Target task id (from `list` / `add`). Default: the calling session's own task, from the verified $ROVE_TASK_ID (an unverifiable env is MISSING_TARGET, never a guess)."},{name:"title",type:"string",placeholder:"T",description:"New task title (or, with --tab, the tab's name)."},{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; needs --task-id, and only --title may accompany it. TAB_NOT_FOUND when the task's snapshot names no such tab."},{name:"branch",type:"string",placeholder:"B",description:"New branch name."},{name:"parent",type:"string",placeholder:"ID|none",description:"Move the task under this task (its engine, tabs, worktree and branch stay as they are), or `none` to make it top level. Refusals: PARENT_NOT_FOUND, PARENT_IS_SELF, PARENT_CYCLE, TASK_NOT_MOVABLE, REMOTE_PARENT_UNSUPPORTED."},{name:"project",type:"string",placeholder:"PATH",description:"Move a top-level task (and its children) under the project at PATH (relative paths resolve against $PWD; any directory inside the repo names its main checkout), which becomes a project if it was not one. Only the grouping changes: the live session, tabs, cwd, worktree and branch stay exactly where they are, so a running engine keeps its conversation. Moving a worktree task back to the repo that cut it clears the link. Refusals: NOT_A_GIT_REPO, SAME_PROJECT, TASK_NOT_MOVABLE (a project's main task, a routine session or a multi-repo task), CHILD_NOT_MOVABLE (move its parent; children follow), REMOTE_MOVE_UNSUPPORTED."},{name:"group",type:"string",placeholder:"GROUPID",description:"With --parent: move every task of one fan-out round (the `groupId` that `add --count` returns). Takes nothing but --parent; a member's refusal is recorded in `results`, and a parent inside the round is PARENT_IN_GROUP."},{...F.command(),description:"New engine launch command \u2014 an engine id from `engine-list` or a full command line. The protocol Rove speaks to it is derived from it; the result reports which (`generic: true` when the command names no engine Rove knows)."},{name:"model",type:"string",placeholder:"MODEL",description:"Pin a model, passed to the engine VERBATIM in its own spelling (claude alias or id, codex slug, pi/omp pattern); `engine-list` .models are suggestions, not a closed list. BAD_MODEL when the engine declares no model flag."},{name:"effort",type:"string",placeholder:"LEVEL",description:"Reasoning effort level the task's engine declares (codex: none/low/medium/high/xhigh/max; pi, omp: off/minimal/low/medium/high/xhigh/max; claude: low/medium/high/xhigh/max). BAD_EFFORT names the accepted levels."},{name:"pinned",type:"bool",placeholder:"BOOL",description:"true pins the task to the top of the sidebar, false unpins."},{name:"kept",type:"bool",placeholder:"BOOL",description:"true marks the task as the attempt kept from a parallel round (`add --count` / `--agents`); false clears the mark. A flag only: it archives nothing, and other attempts of the round are untouched."},{name:"require-report",type:"enum",values:["on","off"],description:"on: every later `send` to this task arms a delivery the agent must close with `report --delivery <id>` (a turn that ends without one raises a `report_missing` Inbox row); off: back to plain sends."},{name:"auto-fix-ci",type:"enum",values:["on","off"],description:"on: when this task's PR checks go red on a new head sha and its engine is at rest, the daemon types the fix-CI prompt (with the failing logs) into the engine, at most once per sha and 3 times in all, then stops and raises an Inbox row; the count starts over when the checks pass. Never interrupts a running turn. off: stop and forget the count."},{name:"status",type:"enum",values:TASK_STATUSES,description:"New lifecycle label (cosmetic \u2014 see summary)."},{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:updateTask}];async function todo(ctx){let{args}=ctx,taskId=await resolveTarget(ctx,"todo"),add=args.str("add"),check=args.str("check"),uncheck=args.str("uncheck"),edit=args.str("edit"),text=args.str("text"),remove=args.str("remove"),notes=args.bool("clear-notes")===!0?"":args.str("notes");if(edit===void 0!==(text===void 0))throw new ApiError("--edit ID and --text T go together","BAD_FLAG");let ops=[...add!==void 0?[{op:"add",text:add}]:[],...check!==void 0?[{op:"check",id:check,done:!0}]:[],...uncheck!==void 0?[{op:"check",id:uncheck,done:!1}]:[],...edit!==void 0&&text!==void 0?[{op:"edit",id:edit,text}]:[],...remove!==void 0?[{op:"remove",id:remove}]:[]],after=await simpleRpc(ctx,"task.notes",{taskId,...notes!==void 0?{notes}:{},...ops.length>0?{ops}:{}}),count=todoCount(after.todos);return{ok:!0,taskId,notes:after.notes??"",todos:after.todos,done:count?.done??0,total:count?.total??0}}var TODO_VERB={name:"todo",group:"edit",summary:"Read or change a task's notes and checklist \u2014 the owner's own review list (shown in the web Files panel's Notes tab and as `done/total` on the task row). With no flag it lists them. Flags combine in one call and apply together, in this order: --add, --check, --uncheck, --edit/--text, --remove; one refused op (TODO_NOT_FOUND, TODO_EMPTY, TODO_TOO_LONG, TODO_LIMIT) changes nothing. A todo id is `t<N>` as listed. Default target: the calling session's own task. Returns { ok, taskId, notes, todos: [{ id, text, done }], done, total }.",flags:[{...F.taskId(!1),description:"Target task id (from `list` / `add`). Default: the calling session's own task."},{name:"add",type:"string",placeholder:"TEXT",description:"Add an unchecked todo (one line, up to 500 characters; 100 per task)."},{name:"check",type:"string",placeholder:"ID",description:"Mark todo ID done."},{name:"uncheck",type:"string",placeholder:"ID",description:"Mark todo ID not done."},{name:"edit",type:"string",placeholder:"ID",description:"Change todo ID's text to --text."},{name:"text",type:"string",placeholder:"TEXT",description:"The new text for --edit."},{name:"remove",type:"string",placeholder:"ID",description:"Delete todo ID."},{name:"notes",type:"string",placeholder:"TEXT",description:"Replace the task's free-text notes (up to 20000 characters); Use --clear-notes to empty them."},{name:"clear-notes",type:"bool",description:"Empty the free-text notes."}],handler:todo};var API_SCHEMA_VERSION=ROVE_API_VERSION,GLOBAL_FLAGS=[{name:"pretty",type:"bool",description:"Pretty-print stdout JSON."},{name:"help",type:"bool",description:"Show usage for the verb and exit."},{name:"envelope",type:"bool",description:"Print every outcome as one { apiVersion, ok, result | error } on stdout \u2014 what the daemon's and the bridge's api.invoke return."},{name:"machine",type:"string",placeholder:"ALIAS",description:"Run the verb in that registered machine's daemon (`rove machine list`); paths are paths there. A --task-id on another machine goes there without it."}];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}:{},...f.repeatable?{repeatable:!0}:{},description:f.description}}function installedVerbs(){return VERBS.filter(verbInstalled)}function installedGroups(){return Object.fromEntries(Object.entries(VERB_GROUPS).filter(([group])=>{let mod=GROUP_MOD[group];return mod===void 0||isBuiltinModInstalled(mod)}))}function verbSchema(v){return{name:v.name,group:v.group,summary:v.summary,offline:v.offline??!1,cliOnly:v.cliOnly??!1,flags:v.flags.map(flagJson)}}function schemaIndex(){let cliName=ROVE_PRODUCT_NAME;return{apiVersion:API_SCHEMA_VERSION,roveVersion: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:installedGroups(),verbs:installedVerbs().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[0])requireVerbInstalled(verbs[0]);if(verbs.length===0)throw new ApiError(`unknown group: ${group}. Groups: ${Object.keys(installedGroups()).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,roveVersion: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",envelope:'--envelope prints {"apiVersion","ok","result"} or {"apiVersion","ok","error"} on stdout instead, exit codes unchanged'},transports:{cli:"rove api <verb> --flag value",daemon:'socket request "api.invoke" {verb, params, machine?} \u2192 the envelope; params are keyed by flag name',bridge:'WebSocket op "api.invoke" {verb, params, machine?} \u2192 result, or the full error object'},globalFlags:GLOBAL_FLAGS,aliases:VERB_ALIASES,groups:installedGroups(),verbs:installedVerbs().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=[`${ROVE_PRODUCT_NAME} 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)":f.repeatable?" (repeatable)":"",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] [--envelope] [--machine ALIAS]"),lines.join(`
|
|
2
|
+
import{PER_SESSION,classifyTier,describeTierBlock,isAutoRoutingTier,listFiles,liveSourceProtocol,loadPreviewData,planWorktreeHandoff,readAutoRoutingTable,readClassifierConfig,resolveBase,runWorktreeGit,searchTasks,statusFiles,statusFilesBranch,taskGroupOf,tierBlock}from"./chunk-xxy0egyg.js";import{ensurePluginEnginesLoaded,registeredEngineIds}from"./chunk-w14jz8pd.js";import{resolveActiveTaskId}from"./chunk-9y21c892.js";import{listPaneLaunches}from"./chunk-38hnq4aq.js";import{upgradeMachine}from"./chunk-n2fhxnfh.js";import{detectEngineStatus}from"./chunk-wmv5wy66.js";import{resolveEditorLaunch}from"./chunk-rz19rphb.js";import{DeviceLogin,GH_ENV,GITHUB_HOST,runTool,spawnGhLogin}from"./chunk-rset5pt8.js";import{PLACEHOLDER_TASK_TITLE,SHELL_TASK_TITLE,deriveTitleFromPrompt}from"./chunk-2xsxcdp6.js";import{DIRTY_WORKTREE_CODE,EMPTY_BRANCH_DIRTY_WORKTREE_CODE,canonicalize}from"./chunk-gbe6hggt.js";import{ENGINE_ACTIVITY_KINDS,TASK_ACTIVITY_STATES}from"./chunk-17e2tgyg.js";import{canonicalEngineTab}from"./chunk-q8ffd1pc.js";import{ISSUE_STATUSES}from"./chunk-je7egpqh.js";import{ROW_TOKEN_MAX_TEXT,ROW_TOKEN_TONES}from"./chunk-atn06ncf.js";import{DEFAULT_FEEDBACK_KIND,FEEDBACK_KINDS,isFeedbackKind,submitFeedback}from"./chunk-69xn50zm.js";import{cloneDirFor,cloneRepo,dispatcherEnvPayload,findCheckouts,forwardVerb,isCleanCheckout,noReplyAddress,ownSession,parseRepoRef,pickCheckout,primaryCheckouts,ptyScopeOf,readOwnDispatcher,recordSend,replyTabOf,repoIdOf,repoIdentity,requireMachine,resolveDispatcherTab,verifiedSelfSession,withPeerProvenance}from"./chunk-g7yc7ypx.js";import{resolvePtyOwner,tasksAtWorktreePath}from"./chunk-y0e28qha.js";import{dedupeMachines,isWindowsMachine,listMachines,machineSshArgs}from"./chunk-m781veb4.js";import{ulid}from"./chunk-qkehg2c1.js";import{resolvePreferredVendor}from"./chunk-k6gx8sqh.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{CURRENT_VERSION}from"./chunk-fvqehvp7.js";import{ENGINE_NOT_OBSERVED_REASON,ENGINE_START_POLL_MS,ENGINE_START_PROBE_MS,deliverHostedPrompt,deliverToKey,ensurePtyHost,findEngineKey,killTaskSessions,listSessions,listSessionsOrNull,openAdmittedEngine,openPtyHost,outcomeFields,restoredTabLaunch,tabEngineBase,taskKeys}from"./chunk-m81wcbax.js";import{awaitEngineProcess,enginePresence,findHostedEngineKey,hostedSessionFailureLine,isHostedTaskKey,listHostedSessions,openHostedSessionHost,readPersistedTerminalDefaultColors,screenErrorLine,sessionArgvNamesEngine,withDeliveryLock}from"./chunk-53nrxdsk.js";import{RemoteEngineLaunchError,allocateTab,applyTabOps,buildEngineSessionLaunch,closeTabsSnapshot,collapseSplit,findEditorTab,initialSplit,joinTaskTabs,launchReposOf,leaves,markCliTabSession,patchTabSplit,publishCliTabSnapshot,readDaemonTabs,readTabsSnapshot,removeLeaf,renameLeaf,renameTabsSnapshot,repoEnv,seedCanonicalTab,seedShellHome,shellIdentityInput,shellTabInput,splitActive,splitLeafPtyKey,tabPtyKeyFor,taskEngineArgv,trustEngineWorktree,trustExtraRepos,unregisteredTabIds,wireSplit}from"./chunk-yhe8zkf3.js";import{createRemoteLink,linkedWorktree,removeRemoteLink,runAsync}from"./chunk-6jcmdxza.js";import{GENERIC_PROTOCOL,describePreset,engineLaunchArgv,engineResumeArgv,listEnginePresets,protocolEntry,resolveCommandProtocol,roveApiInvocation,sessionProtocol,withPinnedSessionId}from"./chunk-2dj8pyb0.js";import{normalizeRemoteUrl}from"./chunk-han0d078.js";import{ApiError,GROUP_MOD,VERB_GROUP_IDS,cliCaller,helpStep,promptMayHaveLanded,requireVerbInstalled,splitDaemonCode,verbInstalled}from"./chunk-jz1kj4sf.js";import{isBuiltinModInstalled}from"./chunk-v8nbqjwc.js";import{aliasKey,hostedKeyFor,isUnderKey,ptyScopeFor,unclaimedSessions}from"./chunk-g9ba25q5.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{terminalRows}from"./chunk-etfh8f4z.js";import{parseBoolLiteral}from"./chunk-zsfyj36g.js";import{expandTilde}from"./chunk-1feav1w3.js";import{foregroundEngineIn,parsePsSnapshot,psSnapshot}from"./chunk-xssbbs39.js";import{engineEntry,getCapabilities,remoteNotesFiles,supportsStructuredHistory,vendorsWithEffortLevels,vendorsWithTurnReader}from"./chunk-pqmew5ec.js";import{CONTRIB_ENGINE_IDS,installedEngineIds}from"./chunk-av0n24rf.js";import{DELIVERY_OUTCOMES,DELIVERY_SUMMARY_MAX_CHARS,MAX_DELIVERIES_PER_TASK,ROUTINE_RESPONSE_MAX_CHARS,SHOULD_RUN_SKIP_EXIT_CODE,SKIP_REASONS,deliveryFooter}from"./chunk-29b3pj9h.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{addSavedRepo,getSavedRepos,inspectRepo,isGitRepo,isRemoteRepoKey,isValidBranchName,resolveMainRepoRoot}from"./chunk-bgmpczgm.js";import{errorMessage,isDiskFull}from"./chunk-9gctbddn.js";import{loadStateFile}from"./chunk-p84bhs57.js";import{MULTI_REPO_CAP,canonicalPrUrl,gitRepoOf,lineageRootId,repoNameOf,rollupPr,taskCwd,taskRepos,todoCount,uniqueRepoName,workspaceCapabilities}from"./chunk-yfwn3fj5.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{ALL_VENDORS,DEFAULT_VENDOR,coerceVendorId}from"./chunk-h2m7em1e.js";import{pathWithin,samePath}from"./chunk-pn5ygqn6.js";import{defaultDaemonSocketPath}from"./chunk-7kgksv06.js";import{homeDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{__require}from"./chunk-91sykzqq.js";import{readFileSync as readFileSync2}from"fs";import{resolve as resolve2}from"path";async function assertNotEmptySuccess(daemon,ctx,prompt){if(ctx.args.bool("allow-empty"))return;if(!/^\s*succeeded\s*[:\uff1a]/i.test(prompt))return;await refuseIfEmptyBranch(daemon,ctx,async()=>!0,["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])}async function assertNotEmptyDoneReport(daemon,ctx,report){if(ctx.args.bool("allow-empty")||report.outcome!=="done")return;await refuseIfEmptyBranch(daemon,ctx,async(taskId)=>{let{deliveries}=await daemon.request("delivery.list",{taskId});return deliveries.find((d)=>d.id===report.delivery)?.source==="send"},["api","report","--delivery",report.delivery,"--outcome","done","--summary",report.summary,...(report.evidence??[]).flatMap((e)=>["--evidence",e]),...report.next?["--next",report.next]:[],"--allow-empty"])}async function refuseIfEmptyBranch(daemon,ctx,applies,nextCommandArgs){let self=await ownSession(daemon);if(!self)return;let sender;try{if(!await applies(self.taskId))return;sender=(await daemon.request("task.get",{taskId:self.taskId})).task}catch{return}if(!workspaceCapabilities(sender).ownsBranch)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 run it again \u2014 or, if this task genuinely produced no commits (an investigation or a review), re-run with --allow-empty to say so explicitly",nextCommandArgs})}import{readFileSync}from"fs";import{isAbsolute,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}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."})},REPEAT_SEP="\x00";function setFlag(flags,key,value,repeatable){let prev=flags.get(key);flags.set(key,repeatable.has(key)&&prev!==void 0?`${prev}${REPEAT_SEP}${value}`:value)}function parseFlags(argv,booleanFlags=new Set,repeatableFlags=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==="envelope")continue;if(key2==="pretty")pretty=value!=="false"&&value!=="0";else if(key2==="help")help=value!=="false"&&value!=="0";else setFlag(flags,key2,value,repeatableFlags);continue}let key=arg.slice(2);if(key==="envelope")continue;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");setFlag(flags,key,next,repeatableFlags),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")||verb.name==="add"&&f.name==="repo"&&(flags.get("fork")||flags.get("no-worktree")||flags.get("isolate-in")||flags.get("handoff-from"));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"&®isteredEngineIds().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;caller;constructor(verb,flags,caller=cliCaller()){this.verb=verb;this.flags=flags;this.caller=caller}resolvePath(name,raw){let expanded=expandTilde(raw);if(isAbsolute(expanded))return expanded;if(this.caller.cwd===void 0)throw new ApiError(`--${name} must be an absolute path: this caller has no working directory`,"BAD_FLAG");return resolve(this.caller.cwd,expanded)}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}list(name){if(!this.spec(name).repeatable)throw Error(`internal: --${name} is not repeatable on verb "${this.verb.name}"`);let raw=this.flags.get(name);return raw===void 0?[]:raw.split(REPEAT_SEP).filter((v)=>v.length>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.verb.flags.some((f)=>f.name==="prompt")?this.str("prompt"):void 0,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;if(file==="-"&&!this.caller.cli)throw new ApiError("--prompt-file - reads stdin, which this caller cannot send; pass --prompt","BAD_FLAG");let text=readFileSync(file==="-"?0:this.resolvePath("prompt-file",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:this.resolvePath(name,v)}requirePath(name){return this.resolvePath(name,this.require(name))}requireRepo(name){return this.repoPath(name,this.require(name))}repoPath(name,raw){return isRemoteRepoKey(raw)?raw:this.resolvePath(name,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 probe=await runtime.inspectRepo(repoFlag),target=probe.root;if(!probe.usable)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;return await Promise.all([...new Set(repos)].map(async(repo)=>{if(samePath(repo,target)){resolved.set(repo,target);return}let{root,usable}=await runtime.inspectRepo(repo);if(resolved.set(repo,root),!samePath(root,target)&&!usable)unresolvable.add(repo)})),{target,matches:(repo)=>samePath(resolved.get(repo),target),unresolvableRepos:[...unresolvable].sort()}}async function simpleRpc(ctx,name,payload){let request=name;return daemonOf(ctx).request(request,payload)}async function handlePtyList(){let[{RoveDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-dtb0dqwh.js"),import("./chunk-b6xrkzhj.js")]),client=new RoveDaemonClient(defaultPtyHostSocketPath());try{return await client.connect(),await client.request("pty.list",{})}catch{return{sessions:null}}finally{client.close()}}function readJsonBody(source){let raw=readFileSync2(source==="-"?0:resolve2(process.cwd(),expandTilde(source)),"utf8"),parsed;try{parsed=JSON.parse(raw)}catch{throw new ApiError(`--json ${source} is not valid JSON`,"BAD_FLAG")}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw new ApiError("--json must be an object: {delivery, outcome, summary, evidence?, next?}","BAD_FLAG");let body=parsed,evidence=body.evidence;if(evidence!==void 0&&(!Array.isArray(evidence)||evidence.some((e)=>typeof e!=="string")))throw new ApiError("evidence must be an array of strings","BAD_FLAG");for(let key of["delivery","outcome","summary","next"])if(body[key]!==void 0&&typeof body[key]!=="string")throw new ApiError(`${key} must be a string`,"BAD_FLAG");return body}var FIELD_FLAGS=["delivery","outcome","summary","next"];function readBody(ctx){let json=ctx.args.str("json"),evidence=ctx.args.list("evidence");if(json===void 0)return{delivery:ctx.args.str("delivery"),outcome:ctx.args.str("outcome"),summary:ctx.args.str("summary"),evidence,next:ctx.args.str("next")};if(FIELD_FLAGS.some((f)=>ctx.args.str(f)!==void 0)||evidence.length>0)throw new ApiError("pass --json OR the individual flags, not both","BAD_FLAG");return readJsonBody(json)}async function report(ctx){let body=readBody(ctx);if(!body.delivery)throw new ApiError("--delivery is required","MISSING_FLAG");if(!body.outcome||!DELIVERY_OUTCOMES.includes(body.outcome))throw new ApiError(`--outcome must be one of ${DELIVERY_OUTCOMES.join("|")}`,"MISSING_FLAG");if(!body.summary?.trim())throw new ApiError("--summary is required","MISSING_FLAG");if(body.summary.length>DELIVERY_SUMMARY_MAX_CHARS)throw new ApiError(`summary is ${body.summary.length} characters; the cap is ${DELIVERY_SUMMARY_MAX_CHARS}`,"RESPONSE_TOO_LARGE",{hint:"Summarize: lead with the conclusion, put the detail in --evidence (commits, PR urls, paths)."});await assertNotEmptyDoneReport(daemonOf(ctx),ctx,{delivery:body.delivery,outcome:body.outcome,summary:body.summary,evidence:body.evidence,next:body.next});let res=await simpleRpc(ctx,"delivery.report",{deliveryId:body.delivery,outcome:body.outcome,summary:body.summary,...body.evidence?.length?{evidence:body.evidence}:{},...body.next?{next:body.next}:{}});if(res.delivery===null)throw new ApiError(`no delivery ${body.delivery}`,"DELIVERY_NOT_FOUND",{hint:"Copy the id from the [ROVE] report line of the prompt you were given; `deliveries --task-id <id>` lists them."});return res}var REPORT_VERB={name:"report",group:"drive",summary:`Close the report a delivered prompt asked for. Run it as the LAST step of the turn, before you stop: a turn that ends without it is flagged \`report_missing\` in the owner's Inbox (a [ROVE ROUTINE] turn with nothing to report just stops: its delivery goes \`quiet\`). --delivery is the id in the prompt's [ROVE] / [ROVE ROUTINE] line. Re-reporting replaces the earlier report; a late report on a flagged delivery clears the flag. --summary \u2264 ${DELIVERY_SUMMARY_MAX_CHARS} chars; put commits, PR urls, test results and paths in repeatable --evidence, and what the next tick should do in --next. Use --json - (stdin) for text with quotes or backticks. \`--outcome done\` on a \`send\` delivery 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:[{name:"delivery",type:"string",placeholder:"ID",description:"Delivery id, e.g. d-41."},{name:"outcome",type:"enum",values:DELIVERY_OUTCOMES,placeholder:"O",description:"done = finished what was asked; partial = some of it; blocked = needs the owner or an external fix; failed = tried and could not."},{name:"summary",type:"string",placeholder:"TEXT",description:"What was done (or why not)."},{name:"evidence",type:"string",placeholder:"X",repeatable:!0,description:"A commit, PR url, test command + result, or file path. Repeat the flag for several."},{name:"next",type:"string",placeholder:"TEXT",description:"What the next tick should do."},{name:"allow-empty",type:"bool",required:!1,description:"Report `done` from a task with zero commits (EMPTY_SUCCESS_REPORT is refused otherwise, on a `send` delivery). For work that legitimately produces no commits \u2014 an investigation, a review, a question answered."},{name:"json",type:"string",placeholder:"PATH",description:"Read {delivery, outcome, summary, evidence?, next?} as JSON from this file (`-` = stdin) instead of the flags."}],handler:report},DELIVERIES_VERB={name:"deliveries",group:"read",summary:`A task's armed deliveries, newest first (newest ${MAX_DELIVERIES_PER_TASK} are kept): status awaiting|reported|missing|skipped, the report (outcome, summary, evidence, next) and, for missing, why (cause turn-complete|turn-failed|engine-dead|stalled|interrupted|session-end|rate-limited + note; rate-limited raises no Inbox row and does not block) plus dismissedAt once the owner dismissed it (a missing row blocks \`send --if-runnable\` and routine ticks until a late report or that dismissal). A skipped row is a \`send --if-runnable\` tick should-run refused: \`skipped\` is the verdict {reason, detail?, until?, gateIds?}, \`repeats\` how many identical refusals (same tab, same reason) the one row stands for. The per-tick log a loop prompt should read instead of a growing MEMO file.`,flags:[F.taskId(!0),{name:"limit",type:"int",placeholder:"N",description:"At most N entries (default: all retained)."}],handler:async(ctx)=>simpleRpc(ctx,"delivery.list",{taskId:ctx.args.require("task-id"),...ctx.args.int("limit")!==void 0?{limit:ctx.args.int("limit")}:{}})};async function listAllEnginePresets(){let presets=await enginePresetsInList(),byProtocol=new Map,modelsOf=(protocol)=>{let pending=byProtocol.get(protocol);if(!pending){let list=engineEntry(protocol).listModels;pending=list?list().catch(()=>null):Promise.resolve(null),byProtocol.set(protocol,pending)}return pending};return Promise.all(presets.map(async(preset)=>({...preset,models:await modelsOf(preset.protocol)})))}async function enginePresetsInList(){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}function withStatus(presets){return Promise.all(presets.map(async(preset)=>{let status=await detectEngineStatus(preset.id).catch(()=>null);if(!status)return preset;let installed=status.binary.found;return{...preset,installed,ready:installed&&status.account?.kind!=="none"}}))}async function engineListIds(){return(await enginePresetsInList()).map((p)=>p.id)}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 (${CONTRIB_ENGINE_IDS.join(", ")}), and engines contributed by enabled plugins \u2014 each with its RAW launch command, exactly as it runs. Copy one into \`add --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. \`models\` is what the engine can name for \`--model\` (suggestions, not a closed set); null = Rove cannot list them for this engine. --status adds \`installed\` (its CLI is on this machine) and \`ready\` (installed, and signed in where Rove can read the login) to each. Returns { engines }.`,flags:[{name:"status",type:"bool",description:"Probe each engine on this machine: adds `installed` and `ready` to every row. Slower: a missing CLI is also looked for in the login shell."}],offline:!0,handler:async(ctx)=>{let engines=await listAllEnginePresets();return{engines:ctx.args.bool("status")?await withStatus(engines):engines}}};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 reasoning levels accept one (${vendorsWithEffortLevels().join(", ")} 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]})}function assertEngineAcceptsModel(engine,model,recover){if(engineEntry(engine).modelArgv)return;throw new ApiError(`engine ${engine} declares no model flag \u2014 it does not accept a model`,"BAD_MODEL",{engine,hint:"Only engines that declare a model flag accept one (claude, codex, kimi, pi, omp today); `engine-list` shows `models` per engine.",nextCommandArgs:[...recover]})}function vendorToRecord(task,engine){let recorded=coerceVendorId(task.vendor);return sessionProtocol(recorded)===engine?recorded:engine}async function readRunnability(daemon,taskId){try{return await daemon.request("task.runnability",{taskId})}catch{return}}async function shouldRun(ctx){let 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 verdict=await daemonOf(ctx).request("task.runnability",{taskId:ctx.args.require("task-id"),...tab?{tabId:tab}:{}});if(!verdict.run)throw new ApiError(`skip: ${verdict.reason}`,"SKIPPED",{...verdict});return verdict}var SHOULD_RUN_VERB={name:"should-run",group:"read",summary:`Would a tick sent to this task be used? Prints the verdict {run:true} or {run:false, reason, detail?, until?, gateIds?} and exits 0 on run, ${SHOULD_RUN_SKIP_EXIT_CODE} on skip (the verdict is still on stdout). reason, first match wins: ${SKIP_REASONS.join(" | ")}. \`awaiting-owner\` = an open gate (answer or withdraw it), \`report-missing\` = the last delivery ended unreported (late \`report\`, or dismiss its Inbox row), \`quota\` clears itself at \`until\`, \`engine-error\` / \`engine-dead\` clear on the engine's next turn or a restart, \`awaiting-permission\` = the engine waits on an approval, \`busy\` = a turn is running or the last delivery still awaits its report. A task whose only gate is answered-but-undelivered is runnable: the next tick carries the answer. Without --tab the whole task is judged and a dead engine is not a skip (\`send\` revives it); --tab tab-N judges that tab and a dead engine is \`engine-dead\`; --tab new judges only task-level state. To check and send in one step use \`send --if-runnable\`.`,flags:[F.taskId(!0),{name:"tab",type:"string",required:!1,placeholder:"TAB",description:'Judge exactly this tab (e.g. tab-2), or "new" for a tab about to be created. Omitted = the whole task.'}],handler:shouldRun};async function attentionDismiss(ctx){let delivery=ctx.args.require("delivery");if((await daemonOf(ctx).request("attention.dismiss",{deliveryId:delivery})).found===!1)throw new ApiError(`no delivery ${delivery}`,"DELIVERY_NOT_FOUND",{hint:"`deliveries --task-id <id>` lists a task's delivery ids; the Inbox row names it as d-N."});return{ok:!0,delivery,cleared:!0}}var ATTENTION_DISMISS_VERB={name:"attention-dismiss",group:"drive",summary:'Dismiss a `report_missing` Inbox row by its delivery id (d-N): the owner\'s deliberate "seen, carry on" for a tick that ended without a report. It unblocks `should-run` for the task. Opening or visiting the row never does this, and a late `report` clears it on its own. Idempotent; an unknown id is DELIVERY_NOT_FOUND.',flags:[{name:"delivery",type:"string",required:!0,placeholder:"ID",description:"Delivery id, e.g. d-41."}],handler:attentionDismiss};import path from"path";var TASK_STATUSES=["backlog","in_progress","in_review","done","canceled","error"];var TASK_FIELDS=["title","branch","parent","project","command","model","effort","pinned","kept","require-report","auto-fix-ci","status"],REPORT_FLAGS=["report-branch","report-pr","report-summary"];async function renameTab(ctx,taskId,tabId){let title=ctx.args.str("title"),others=[...TASK_FIELDS,...REPORT_FLAGS].filter((f)=>f!=="title"&&ctx.args.str(f)!==void 0);if(title===void 0||others.length>0)throw new ApiError("--tab only renames a tab: pass --title and no other field","BAD_FLAG",{hint:"Update the task's own fields in a separate call without --tab."});let daemon=daemonOf(ctx);if(!await renameTabsSnapshot(daemon,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 daemon.request("terminalTab.rename",{taskId,tabId,title});return{ok:!0,taskId,tabId,title,renamed:!0,clients:reply.clients??0}}async function resolveTarget(ctx,verb="update"){let explicit=ctx.args.str("task-id");if(explicit)return explicit;let self=await ownSession(daemonOf(ctx));if(!self)throw new ApiError("no --task-id given and the caller is not a verified rove session \u2014 pass --task-id ID","MISSING_TARGET",helpStep(verb));return self.taskId}async function projectRoot(ctx){let raw=ctx.args.str("project")?.trim();if(raw===void 0)return;if(raw==="")throw new ApiError("--project cannot be empty \u2014 pass the repo's path","BAD_FLAG");let root=await ctx.runtime.resolveRepoRoot(path.resolve(ctx.caller.cwd??process.cwd(),raw));if(!await ctx.runtime.isUsableRepo(root))throw new ApiError(`--project ${raw} is not inside a git repository`,"NOT_A_GIT_REPO",{hint:"clone or `git init` the project first, then pass its path"});return root}var NO_PARENT="none";async function reparentGroup(ctx,groupId){let parent=ctx.args.str("parent"),stray=["task-id","tab",...TASK_FIELDS.filter((f)=>f!=="parent"),...REPORT_FLAGS].filter((f)=>ctx.args.str(f)!==void 0);if(parent===void 0||parent===""||stray.length>0)throw new ApiError(`--group moves a whole fan-out round and takes only --parent ID (or \`none\`)${stray.length>0?` \u2014 drop ${stray.map((f)=>`--${f}`).join(", ")}`:""}`,"BAD_FLAG",helpStep("update"));let daemon=daemonOf(ctx),{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"]});if(members.some((t)=>t.id===parent))throw new ApiError(`${parent} is itself a member of group ${groupId} \u2014 a round cannot move under one of its own`,"PARENT_IN_GROUP",{hint:"pick a parent outside the round, or move the members one by one with --task-id"});let parentTaskId=parent===NO_PARENT?null:parent,replyTab=parentTaskId===null?void 0:await replyTabOf(ctx.runtime,daemon,parentTaskId),results=[],failures=0;for(let task of members)try{let moved=await simpleRpc(ctx,"task.setParent",{taskId:task.id,parentTaskId,...replyTab?{replyTab}:{}});results.push({taskId:task.id,status:"moved",...moved})}catch(err){failures++;let message=errorMessage(err),coded=err instanceof ApiError?{code:err.code,rest:message}:splitDaemonCode(message);results.push({taskId:task.id,status:"failed",error:coded?.rest??message,...coded?{code:coded.code}:{}})}return{ok:failures===0,groupId,count:members.length,failures,results}}async function updateTask(ctx){let group=ctx.args.str("group");if(group!==void 0)return reparentGroup(ctx,group);let tabId=ctx.args.str("tab"),taskId=tabId!==void 0?ctx.args.require("task-id"):await resolveTarget(ctx);if(tabId!==void 0)return renameTab(ctx,taskId,tabId);let title=ctx.args.str("title"),branch=ctx.args.str("branch"),parent=ctx.args.str("parent"),command=ctx.args.str("command")?.trim(),model=ctx.args.str("model")?.trim(),effort=ctx.args.str("effort")?.trim(),pinned=ctx.args.bool("pinned"),kept=ctx.args.bool("kept"),requireReport=ctx.args.enumOf("require-report"),autoFixCi=ctx.args.enumOf("auto-fix-ci"),status=ctx.args.enumOf("status"),report2={reportBranch:ctx.args.str("report-branch"),reportPr:ctx.args.int("report-pr"),reportSummary:ctx.args.str("report-summary")},reporting=Object.values(report2).some((v)=>v!==void 0);if(TASK_FIELDS.every((f)=>ctx.args.str(f)===void 0)&&!reporting)throw new ApiError(`nothing to update \u2014 pass at least one of ${TASK_FIELDS.map((f)=>`--${f}`).join(", ")}`,"BAD_FLAG",{nextCommandArgs:["api","update","--help"]});if(reporting&&status===void 0)throw new ApiError("--report-* is recorded with a status: pass --status too","BAD_FLAG",{hint:"A worker reporting delivery usually passes --status in_review (or done)."});if(command==="")throw new ApiError("--command cannot be empty","BAD_FLAG");if(parent==="")throw new ApiError("--parent cannot be empty \u2014 pass a task id, or `none` for top level","BAD_FLAG");let daemon=daemonOf(ctx),protocol=command?resolveCommandProtocol(command):void 0,project=await projectRoot(ctx),task,engine;if(model!==void 0||effort!==void 0){task=(await daemon.request("task.get",{taskId})).task,engine=taskEngine(command?{...task,command}:task);let recover=["api","get-task","--task-id",taskId];if(model!==void 0)assertEngineAcceptsModel(engine,model,recover);if(effort!==void 0)assertEngineAcceptsEffort(engine,effort,recover)}let applied=[],step=async(fields,method,payload)=>{let reply;try{reply=await simpleRpc(ctx,method,{taskId,...payload})}catch(err){if(applied.length===0)throw err;let message=err instanceof Error?err.message:String(err),code=err instanceof ApiError?err.code:"PARTIAL_UPDATE";throw new ApiError(`--${fields.join("/--")} failed after ${applied.join(", ")} applied: ${message}`,code,{applied:[...applied],failed:fields})}return applied.push(...fields),reply},reparented;if(parent!==void 0){let parentTaskId=parent===NO_PARENT?null:parent,replyTab=parentTaskId===null?void 0:await replyTabOf(ctx.runtime,daemon,parentTaskId);reparented=await step(["parent"],"task.setParent",{parentTaskId,...replyTab?{replyTab}:{}})}let regrouped;if(project!==void 0)regrouped=await step(["project"],"task.moveToProject",{repo:project});if(branch!==void 0)await step(["branch"],"task.setBranch",{branch});if(command)await step(["command"],"task.setCommand",{command,vendor:protocol});if(task&&engine){let recorded=vendorToRecord(protocol?{...task,vendor:protocol}:task,engine),fields=[...model!==void 0?["model"]:[],...effort!==void 0?["effort"]:[]];await step(fields,"task.setVendor",{vendor:recorded,model,effort})}if(title!==void 0)await step(["title"],"task.rename",{title});if(pinned!==void 0)await step(["pinned"],"task.pin",{pinned});if(kept!==void 0)await step(["kept"],"task.keep",{kept});if(requireReport!==void 0)await step(["require-report"],"task.requireReport",{required:requireReport==="on"});if(autoFixCi!==void 0)await step(["auto-fix-ci"],"task.autoFixCi",{enabled:autoFixCi==="on"});if(status!==void 0)await step(["status"],"task.status",{status,...report2});return{ok:!0,taskId,updated:applied,...reparented?{parent:reparented}:{},...regrouped?{project:{repo:regrouped.repo,moved:regrouped.moved,note:"regrouped only \u2014 the PTYs, cwd, worktree and branch stay where they were"}}:{},...command?{command,protocol,...protocol===GENERIC_PROTOCOL?{generic:!0}:{}}:{},...engine?{engine}:{}}}var EDIT_VERBS=[{name:"update",group:"edit",summary:"Change a task's metadata \u2014 any combination of title, branch (git branch -m if materialized, else recorded), parent, engine --command / --model / --effort (take effect on the next session rebuild), pin, and status + worker report \u2014 in one call. The flags are checked before anything is written; then they apply in order parent \u2192 branch \u2192 engine \u2192 title/pin/status, and a refusal mid-way names what already applied (`applied`). --parent ID re-parents the task without touching its engine, tabs, worktree or branch: the stored parent is ID's top-level ancestor (children never nest, as with `add` from a child; the task's own children come along, listed in `.parent.moved`) and the task's reply address becomes ID itself, so its bare `send` reaches ID (the caller's own tab when run from inside ID, else ID's live engine tab, else tab-1). `--parent none` makes the task top level and drops a reply address that pointed into its old tree. A parent must live on the same machine as the task. Archiving the stored parent, or `delete --cascade` on it, takes the task along. --group G --parent ID moves a whole fan-out round instead and takes nothing else. With --tab, renames that Terminal Tab instead (the API twin of the TUI's f2) and takes only --title. The status is a cosmetic LABEL: `--status canceled` closes, stops and cleans up nothing \u2014 `delete` ends a task. The --report-* fields record what the WORKER CLAIMS it delivered (`.report` on `get-task` / `collect`), deliberately apart from `.prStatus`, which the daemon polled from the forge; they merge onto any previous report and need --status. Returns { updated } \u2014 the fields written, in order.",flags:[{...F.taskId(!1),description:"Target task id (from `list` / `add`). Default: the calling session's own task, from the verified $ROVE_TASK_ID (an unverifiable env is MISSING_TARGET, never a guess)."},{name:"title",type:"string",placeholder:"T",description:"New task title (or, with --tab, the tab's name)."},{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; needs --task-id, and only --title may accompany it. TAB_NOT_FOUND when the task's snapshot names no such tab."},{name:"branch",type:"string",placeholder:"B",description:"New branch name."},{name:"parent",type:"string",placeholder:"ID|none",description:"Move the task under this task (its engine, tabs, worktree and branch stay as they are), or `none` to make it top level. Refusals: PARENT_NOT_FOUND, PARENT_IS_SELF, PARENT_CYCLE, TASK_NOT_MOVABLE, REMOTE_PARENT_UNSUPPORTED."},{name:"project",type:"string",placeholder:"PATH",description:"Move a top-level task (and its children) under the project at PATH (relative paths resolve against $PWD; any directory inside the repo names its main checkout), which becomes a project if it was not one. Only the grouping changes: the live session, tabs, cwd, worktree and branch stay exactly where they are, so a running engine keeps its conversation. Moving a worktree task back to the repo that cut it clears the link. Refusals: NOT_A_GIT_REPO, SAME_PROJECT, TASK_NOT_MOVABLE (a project's main task, a routine session or a multi-repo task), CHILD_NOT_MOVABLE (move its parent; children follow), REMOTE_MOVE_UNSUPPORTED."},{name:"group",type:"string",placeholder:"GROUPID",description:"With --parent: move every task of one fan-out round (the `groupId` that `add --count` returns). Takes nothing but --parent; a member's refusal is recorded in `results`, and a parent inside the round is PARENT_IN_GROUP."},{...F.command(),description:"New engine launch command \u2014 an engine id from `engine-list` or a full command line. The protocol Rove speaks to it is derived from it; the result reports which (`generic: true` when the command names no engine Rove knows)."},{name:"model",type:"string",placeholder:"MODEL",description:"Pin a model, passed to the engine VERBATIM in its own spelling (claude alias or id, codex slug, pi/omp pattern); `engine-list` .models are suggestions, not a closed list. BAD_MODEL when the engine declares no model flag."},{name:"effort",type:"string",placeholder:"LEVEL",description:"Reasoning effort level the task's engine declares (codex: none/low/medium/high/xhigh/max; pi, omp: off/minimal/low/medium/high/xhigh/max; claude: low/medium/high/xhigh/max). BAD_EFFORT names the accepted levels."},{name:"pinned",type:"bool",placeholder:"BOOL",description:"true pins the task to the top of the sidebar, false unpins."},{name:"kept",type:"bool",placeholder:"BOOL",description:"true marks the task as the attempt kept from a parallel round (`add --count` / `--agents`); false clears the mark. A flag only: it archives nothing, and other attempts of the round are untouched."},{name:"require-report",type:"enum",values:["on","off"],description:"on: every later `send` to this task arms a delivery the agent must close with `report --delivery <id>` (a turn that ends without one raises a `report_missing` Inbox row); off: back to plain sends."},{name:"auto-fix-ci",type:"enum",values:["on","off"],description:"on: when this task's PR checks go red on a new head sha and its engine is at rest, the daemon types the fix-CI prompt (with the failing logs) into the engine, at most once per sha and 3 times in all, then stops and raises an Inbox row; the count starts over when the checks pass. Never interrupts a running turn. off: stop and forget the count."},{name:"status",type:"enum",values:TASK_STATUSES,description:"New lifecycle label (cosmetic \u2014 see summary)."},{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:updateTask}];async function todo(ctx){let{args}=ctx,taskId=await resolveTarget(ctx,"todo"),add=args.str("add"),check=args.str("check"),uncheck=args.str("uncheck"),edit=args.str("edit"),text=args.str("text"),remove=args.str("remove"),notes=args.bool("clear-notes")===!0?"":args.str("notes");if(edit===void 0!==(text===void 0))throw new ApiError("--edit ID and --text T go together","BAD_FLAG");let ops=[...add!==void 0?[{op:"add",text:add}]:[],...check!==void 0?[{op:"check",id:check,done:!0}]:[],...uncheck!==void 0?[{op:"check",id:uncheck,done:!1}]:[],...edit!==void 0&&text!==void 0?[{op:"edit",id:edit,text}]:[],...remove!==void 0?[{op:"remove",id:remove}]:[]],after=await simpleRpc(ctx,"task.notes",{taskId,...notes!==void 0?{notes}:{},...ops.length>0?{ops}:{}}),count=todoCount(after.todos);return{ok:!0,taskId,notes:after.notes??"",todos:after.todos,done:count?.done??0,total:count?.total??0}}var TODO_VERB={name:"todo",group:"edit",summary:"Read or change a task's notes and checklist \u2014 the owner's own review list (shown in the web Files panel's Notes tab and as `done/total` on the task row). With no flag it lists them. Flags combine in one call and apply together, in this order: --add, --check, --uncheck, --edit/--text, --remove; one refused op (TODO_NOT_FOUND, TODO_EMPTY, TODO_TOO_LONG, TODO_LIMIT) changes nothing. A todo id is `t<N>` as listed. Default target: the calling session's own task. Returns { ok, taskId, notes, todos: [{ id, text, done }], done, total }.",flags:[{...F.taskId(!1),description:"Target task id (from `list` / `add`). Default: the calling session's own task."},{name:"add",type:"string",placeholder:"TEXT",description:"Add an unchecked todo (one line, up to 500 characters; 100 per task)."},{name:"check",type:"string",placeholder:"ID",description:"Mark todo ID done."},{name:"uncheck",type:"string",placeholder:"ID",description:"Mark todo ID not done."},{name:"edit",type:"string",placeholder:"ID",description:"Change todo ID's text to --text."},{name:"text",type:"string",placeholder:"TEXT",description:"The new text for --edit."},{name:"remove",type:"string",placeholder:"ID",description:"Delete todo ID."},{name:"notes",type:"string",placeholder:"TEXT",description:"Replace the task's free-text notes (up to 20000 characters); Use --clear-notes to empty them."},{name:"clear-notes",type:"bool",description:"Empty the free-text notes."}],handler:todo};var API_SCHEMA_VERSION=ROVE_API_VERSION,GLOBAL_FLAGS=[{name:"pretty",type:"bool",description:"Pretty-print stdout JSON."},{name:"help",type:"bool",description:"Show usage for the verb and exit."},{name:"envelope",type:"bool",description:"Print every outcome as one { apiVersion, ok, result | error } on stdout \u2014 what the daemon's and the bridge's api.invoke return."},{name:"machine",type:"string",placeholder:"ALIAS",description:"Run the verb in that registered machine's daemon (`rove machine list`); paths are paths there. A --task-id on another machine goes there without it."}];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}:{},...f.repeatable?{repeatable:!0}:{},description:f.description}}function installedVerbs(){return VERBS.filter(verbInstalled)}function installedGroups(){return Object.fromEntries(Object.entries(VERB_GROUPS).filter(([group])=>{let mod=GROUP_MOD[group];return mod===void 0||isBuiltinModInstalled(mod)}))}function verbSchema(v){return{name:v.name,group:v.group,summary:v.summary,offline:v.offline??!1,cliOnly:v.cliOnly??!1,flags:v.flags.map(flagJson)}}function schemaIndex(){let cliName=ROVE_PRODUCT_NAME;return{apiVersion:API_SCHEMA_VERSION,roveVersion: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:installedGroups(),verbs:installedVerbs().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[0])requireVerbInstalled(verbs[0]);if(verbs.length===0)throw new ApiError(`unknown group: ${group}. Groups: ${Object.keys(installedGroups()).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,roveVersion: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",envelope:'--envelope prints {"apiVersion","ok","result"} or {"apiVersion","ok","error"} on stdout instead, exit codes unchanged'},transports:{cli:"rove api <verb> --flag value",daemon:'socket request "api.invoke" {verb, params, machine?} \u2192 the envelope; params are keyed by flag name',bridge:'WebSocket op "api.invoke" {verb, params, machine?} \u2192 result, or the full error object'},globalFlags:GLOBAL_FLAGS,aliases:VERB_ALIASES,groups:installedGroups(),verbs:installedVerbs().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=[`${ROVE_PRODUCT_NAME} 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)":f.repeatable?" (repeatable)":"",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] [--envelope] [--machine ALIAS]"),lines.join(`
|
|
3
3
|
`)}function apiUsage(){let cliName=ROVE_PRODUCT_NAME,rows=installedVerbs().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 DEFAULT_PAGE_MESSAGES=40,MAX_PAGE_MESSAGES=50,PAGE_BYTE_BUDGET=131072,STRING_CLIP_CHARS=16384,DEFAULT_TAIL_LINES=40,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.tab===void 0||typeof c.tab==="string")&&(c.src==="history"&&typeof c.sid==="string"&&typeof c.idx==="number"||c.src==="terminal"&&typeof c.off==="number")))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,at,limit){let forward="from"in at,page=[],bytes=0,limited=!1,i=forward?at.from:at.before-1;for(;forward?i<messages.length:i>=0;forward?i++:i--){if(page.length>=limit)break;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}if(forward)return{page,start:at.from,end:i,limited};return page.reverse(),{page,start:i+1,end:at.before,limited}}function terminalLines(text){return terminalRows(text)}function boundedTail(text,maxLines=TERMINAL_TAIL_LINES){let lines=terminalLines(text),start=Math.max(0,lines.length-Math.min(maxLines,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}}async function peekTaskTerminal(taskId,engineBin,tab,sinceOffset,scope){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,scope)??unclaimedSessions(sessions,scope).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 engineScreenError(task,opts={}){let pattern=protocolEntry(task.vendor).errorLine;if(!pattern)return;try{let alias=task.ptyAlias,page=await peekTaskTerminal(alias?.taskId??task.id,taskEngineArgv(task)[0],alias?.tabId);if(!page||page==="host-unreachable")return;return screenErrorLine(pattern,boundedTail(page.text).tail,opts)}catch{return}}var ACTIVITY_STATES_DOC="`.activity.state` is one of: `idle` (at rest), `running` (a turn is in progress), `turn_complete` (a turn finished \u2014 also at rest; treat it like idle when deciding whether the engine is free), `permission_needed` (blocked on an approval prompt), `rate_limited` (clears on its own), `error` (the last turn failed; `.activity.detail.note` carries the engine's text, and `.activity.source: \"screen\"` means it was read off the engine's own screen because the engine reported nothing), `dead` (the engine process exited; the tab's exit record says how).",AT_REST=new Set(["idle","turn_complete"]);async function readActivityRegistry(daemon){try{let dbg=await daemon.request("debug.inspect");return{tasks:dbg?.activity?.tasks??{},tabs:dbg?.activity?.tabs??{}}}catch{return null}}async function activityView(registry,task,tab){let entry=tab?registry?.tabs[task.id]?.[tab]:registry?.tasks[task.id];if(!entry)return null;let base={state:entry.state,at:new Date(entry.at).toISOString(),forMs:Math.max(0,Date.now()-entry.at),...entry.detail?{detail:entry.detail}:{}},atRest=AT_REST.has(entry.state);if(tab||!(atRest||entry.state==="running"))return base;let note=await engineScreenError(task,{last:!atRest});return note?{...base,state:"error",detail:{failure:"other",note},source:"screen"}:base}function parseOption(raw){let eq=raw.indexOf("=");if(eq<=0||eq===raw.length-1)throw new ApiError(`--option must be key=label (got ${JSON.stringify(raw)})`,"BAD_FLAG",helpStep("gate-raise"));return{key:raw.slice(0,eq).trim(),label:raw.slice(eq+1).trim()}}async function gateRaise(ctx){let{args}=ctx,daemon=daemonOf(ctx),taskId=args.require("task-id"),tabId=args.str("tab");if(!tabId){let self=await ownSession(daemon);if(self?.taskId===taskId)tabId=self.tabId}return{ok:!0,gate:(await daemon.request("gate.raise",{taskId,...tabId?{tabId}:{},question:args.require("question"),options:args.list("option").map(parseOption),...args.str("recommend")?{recommended:args.str("recommend")}:{},...args.str("context")?{context:args.str("context")}:{}})).gate}}async function gateAnswer(ctx){let{args}=ctx,option=args.str("option"),text=args.str("text");if(option===void 0&&text===void 0)throw new ApiError("pass --option KEY and/or --text TEXT","MISSING_FLAG",helpStep("gate-answer"));let res=await daemonOf(ctx).request("gate.answer",{gateId:args.require("gate"),...option!==void 0?{option}:{},...text!==void 0?{text}:{},by:"cli"});return{ok:!0,gate:res.gate,delivered:res.delivered}}async function gateWithdraw(ctx){return{ok:!0,gate:(await daemonOf(ctx).request("gate.withdraw",{gateId:ctx.args.require("gate")})).gate}}async function gates(ctx){let{args}=ctx,repo=args.str("repo")?args.requireRepo("repo"):void 0;return{gates:(await daemonOf(ctx).request("gate.list",{...repo?{repo}:{},...args.str("task-id")?{taskId:args.str("task-id")}:{},status:args.enumOf("status")??"open"})).gates}}async function takeOwedGateAnswers(daemon,taskId,tab){try{let owed=await daemon.request("gate.takeUndelivered",{taskId,...tab?{tabId:tab}:{}});return owed.text?{text:owed.text,gateIds:owed.gateIds}:null}catch{return null}}async function markGateAnswersDelivered(daemon,gateIds){await daemon.request("gate.markDelivered",{gateIds}).catch(()=>{})}function assertQueueFlags(ctx){if(!ctx.args.bool("queue"))return;let clash=ctx.args.bool("replace")?"--replace":ctx.args.bool("if-runnable")?"--if-runnable":ctx.args.bool("respawn")?"--respawn":null;if(clash)throw new ApiError(`--queue waits for a running turn; it does not combine with ${clash}`,"BAD_FLAG",helpStep("send"))}async function queueIfBusy(ctx,daemon,task,tab,text){if(!ctx.args.bool("queue"))return null;let tabId=tab??canonicalEngineTab(readTabsSnapshot(task.id)?.tabs??[])?.id;if(!tabId)return null;let reply=await daemon.request("queue.add",{taskId:task.id,tabId,text,expectReport:ctx.args.bool("expect-report")===!0});if(!reply.queued||!reply.item)return null;return{ok:!0,taskId:task.id,tabId,queued:!0,queueId:reply.item.id,position:reply.position}}var QUEUE_LIST_VERB={name:"queue-list",group:"read",summary:"Prompts `send --queue` is holding for a busy tab, oldest first: {items:[{id, taskId, tabId, text, expectReport, at, lastError?}]}. Each is pasted when its tab's turn ends, one per turn; `lastError` says why the last hand-over did not land (it stays at the head). Held in the daemon's memory: a daemon restart drops them.",flags:[F.taskId(!1)],handler:async(ctx)=>simpleRpc(ctx,"queue.list",ctx.args.str("task-id")?{taskId:ctx.args.str("task-id")}:{})},QUEUE_EDIT_VERB={name:"queue-edit",group:"drive",summary:'Rewrite a prompt `send --queue` is holding (`queue-list` gives the id), keeping its id and its place in line: {edited:true, item} or {edited:false, reason:"not-found"|"pasting"}. `pasting` means its turn already came and the old text is going in.',flags:[{name:"id",type:"string",required:!0,placeholder:"q-N",description:"The held prompt's id."},F.prompt(!0,"The new text, replacing the held prompt's."),F.promptFile()],handler:async(ctx)=>{let text=ctx.args.promptText();if(text===void 0)throw new ApiError("pass --prompt or --prompt-file","MISSING_FLAG",helpStep("queue-edit"));return simpleRpc(ctx,"queue.edit",{id:ctx.args.require("id"),text})}},QUEUE_CANCEL_VERB={name:"queue-cancel",group:"drive",summary:"Take back a prompt `send --queue` is holding (`queue-list` gives the id): {cancelled: true|false}.",flags:[{name:"id",type:"string",required:!0,placeholder:"q-N",description:"The held prompt's id."}],handler:async(ctx)=>simpleRpc(ctx,"queue.cancel",{id:ctx.args.require("id")})};async function handoffBrief(ctx,task,tabId,verb){if(!/^tab-[A-Za-z0-9-]+$/.test(tabId))throw new ApiError(`the tab to hand over must be a tab id like tab-2 (got ${JSON.stringify(tabId)})`,"BAD_TAB");let source=((await readDaemonTabs(daemonOf(ctx),task.id))?.tabs??readTabsSnapshot(task.id)?.tabs??[]).find((t)=>t.id===tabId);if(!source)throw new ApiError(`task ${task.id} has no tab ${tabId}`,"TAB_NOT_FOUND",{taskId:task.id,tabId});if(source.kind!=="engine")throw new ApiError(`${tabId} is not an engine conversation; nothing to hand over`,"BAD_FLAG",helpStep(verb));let tabVendor=source.vendor??task.vendor,plan=await planWorktreeHandoff(source,liveSourceProtocol(source,tabVendor),taskCwd(task),task.title);if(plan.kind==="handoff")return plan.prompt;throw new ApiError(plan.kind==="no-transcript"?`${plan.engine} keeps no transcript Rove can name, so ${tabId} cannot be handed to another engine`:`${tabId} has no conversation yet; send the prompt directly`,plan.kind==="no-transcript"?"NO_TRANSCRIPT":"NO_CONVERSATION",{taskId:task.id,tabId})}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 ensureHostFor(taskId,hint){try{return await ensurePtyHost()}catch(error){throw sessionFailed(taskId,`failed to start PTY host for ${taskId}: ${error instanceof Error?error.message:String(error)}`,hint)}}var OLD_CONVERSATION=["sessionId","spawned","forkFrom","initialPrompt","liveVendor","lastTitle","autoTitle"];async function assertDeadEngineTab(runtime,daemon,task,tabId){let scope=await ptyScopeOf(daemon,task);if(hostedKeyFor(task.id,tabId,scope)===null||scope.alias?.tabId===tabId)throw new ApiError(`tab ${tabId} runs under another task's conversation; --replace cannot swap it`,"BAD_FLAG",{taskId:task.id,tabId});let row=(await runtime.taskTabs(task.id,taskEngineArgv(task),scope)).tabs.find((t)=>t.id===tabId);if(!row||row.kind!=="engine")throw new ApiError(`${tabId} is not an engine conversation; nothing to replace`,"BAD_FLAG",helpStep("send"));if(row.viewOf)throw new ApiError(`${tabId} is a view of task ${row.viewOf}'s session; --replace cannot swap it`,"BAD_FLAG",{taskId:task.id,tabId});if(row.alive===!1||row.engineAlive===!1)return;throw new ApiError(`${tabId}'s engine is still running; --replace only takes over a dead or exited tab. Drop --replace to continue in a shared child task`,"TAB_ALIVE",{taskId:task.id,tabId})}var REWRITTEN=[...OLD_CONVERSATION,"vendor","engineCommand"];async function undoReplace(daemon,taskId,tabId,before){let set={},unset=[];for(let field of REWRITTEN)if(before[field]===void 0)unset.push(field);else set[field]=before[field];await applyTabOps(daemon,taskId,[{op:"patch",id:tabId,set,unset}]);let host=await ensureHostFor(taskId,"no PTY host to stop the replacement in");try{await host.rpc.request("pty.kill",{key:`${taskId}::${tabId}`,wait:!0})}finally{host.close()}}function replaceDeadTab(ctx,task,tabId,command){let{runtime,daemon}=ctx;return withDeliveryLock(`${task.id}::${tabId}::replace`,async()=>{await assertDeadEngineTab(runtime,daemon,task,tabId);let worktree=taskCwd(task);if(!worktree)throw new ApiError(`task ${task.id} has no worktree yet`,"NO_WORKTREE");let before=(await readDaemonTabs(daemon,task.id))?.tabs.find((t)=>t.id===tabId)??{},protocol=command?resolveCommandProtocol(command):void 0,set=protocol?{vendor:protocol,...command!==protocol?{engineCommand:command}:{}}:void 0,unset=protocol&&command===protocol?[...OLD_CONVERSATION,"engineCommand"]:OLD_CONVERSATION,undo=()=>undoReplace(daemon,task.id,tabId,before);await applyTabOps(daemon,task.id,[{op:"patch",id:tabId,...set?{set}:{},unset}]);let target={id:task.id,worktreePath:worktree,kind:task.kind,vendor:task.vendor,command:task.command,modelEffort:task.modelEffort,model:task.model,repo:task.repo};try{await runtime.reviveTab(daemon,target,tabId,worktree,{replaceExited:!0,awaitEngine:!0})}catch(error){throw await undo().catch(()=>{}),error}return undo})}function csvOf(ctx,name,allowed,verb="list"){let raw=ctx.args.str(name);if(raw===void 0)return;let values=raw.split(",").map((s)=>s.trim()).filter(Boolean);if(values.find((v)=>!allowed.includes(v))!==void 0||values.length===0)throw new ApiError(`--${name} takes a comma list of ${allowed.join(", ")}`,"BAD_FLAG",helpStep(verb));return new Set(values)}function listFilters(ctx){let repo=ctx.args.path("repo"),statuses=csvOf(ctx,"status",TASK_STATUSES),activities=csvOf(ctx,"activity",TASK_ACTIVITY_STATES);if(!repo&&!statuses&&!activities)return null;return{repo,statuses,activities}}async function filterTaskList(ctx,daemon,tasks,filters){let isLocal=(t)=>!t.origin||t.origin.machineId==="local",repo=filters.repo?await repoFilter(ctx.runtime,filters.repo,tasks.filter(isLocal).map((t)=>t.repo)):null,kept=tasks.filter((t)=>(!repo||isLocal(t)&&repo.matches(t.repo))&&(!filters.statuses||filters.statuses.has(t.status))),out=kept;if(filters.activities){let wanted=filters.activities,registry=await readActivityRegistry(daemon),local=kept.filter(isLocal),views=await Promise.all(local.map((t)=>activityView(registry,t)));out=local.flatMap((task,i)=>{let activity=views[i];return activity&&wanted.has(activity.state)?[{...task,activity}]:[]})}return{tasks:out,...repo&&repo.unresolvableRepos.length>0?{unresolvableRepos:repo.unresolvableRepos}:{}}}var TASK_FIELDS2={id:!0,title:!0,repo:!0,branch:!0,worktreePath:!0,kind:!0,scratch:!0,noProject:!0,routine:!0,status:!0,pinned:!0,kept:!0,notes:!0,todos:!0,archived:!0,vendor:!0,command:!0,prStatus:!0,modelEffort:!0,model:!0,tier:!0,groupId:!0,observedLanguage:!0,deletion:!0,quotaResume:!0,scheduledStart:!0,autoFixCi:!0,linkedWorkItem:!0,dispatcher:!0,parentTaskId:!0,sharesWorkspaceOf:!0,workspace:!0,cwdSubpath:!0,ptyAlias:!0,requireReport:!0,worktreeOnly:!0,prompt:!0,baseRef:!0,worktreeName:!0,gitRepo:!0,extraRepos:!0,sessionPrs:!0,report:!0,origin:!0,repoId:!0,createdAt:!0,updatedAt:!0},LIST_FIELDS=[...Object.keys(TASK_FIELDS2),"repoCount","activity"];function listFields(ctx){let fields=csvOf(ctx,"fields",LIST_FIELDS);return fields?[...fields]:void 0}function projectTasks(tasks,fields){return tasks.map((task)=>{let row={};for(let field of fields)if(field in task)row[field]=task[field];return row})}var MAX_LIVE_ENGINES_KEY="engine.maxLiveSessions";function normalizeMaxLiveEngines(value){let n=typeof value==="number"?value:typeof value==="string"&&value.trim()!==""?Number(value.trim()):Number.NaN;return Number.isInteger(n)&&n>0?n:void 0}function persistedMaxLiveEngines(){return normalizeMaxLiveEngines(loadStateFile()[MAX_LIVE_ENGINES_KEY])}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 openAdmittedEngine(rpc,{key,cwd,...launch?{command:launch.command}:{},defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:opts.maxLiveEngines,snapshot:opts.snapshot,taskId,retryArgs:["api","send","--task-id",taskId,"--tab",tabId,"--respawn","--plain","--prompt",prompt]});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:"start a new conversation for this prompt with `add --no-worktree`, 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","--plain","--prompt",prompt]})}import{realpathSync,statSync}from"fs";import{join}from"path";function collision(taskId,key,retryArgs){return new ApiError(`session ${key} already existed; no new tab was created`,"TAB_COLLISION",{taskId,hint:"a session already held the tab id the daemon minted; retry to get a fresh id",nextCommandArgs:retryArgs})}var createdFresh=(open)=>open.created??open.replay.length===0;async function openShell(client,rpc,taskId,cwd,multiRepo,home,type){let shell=resolveSessionShell(),tab=home?await seedShellHome(client,taskId,shell):await allocateTab(client,taskId,{kind:"command",title:null,command:[shell]}),key=`${taskId}::${tab.id}`;try{let open;try{open=await rpc.request("pty.open",{key,cwd,command:[shell],defaultColors:readPersistedTerminalDefaultColors()})}catch(error){if(!home)await closeTabsSnapshot(client,taskId,tab.id).catch(()=>{return});throw error}if(!createdFresh(open))throw collision(taskId,key,["api","tab-new","--task-id",taskId,"--kind","shell"]);let repos=multiRepo?await launchReposOf(client,taskId):void 0;if(await rpc.request("pty.write",{key,data:shellTabInput(taskId,tab.id,cwd,repos&&repoEnv(repos))}),type!==void 0)await rpc.request("pty.write",{key,data:`${type}\r`})}finally{await rpc.request("pty.detach",{key}).catch(()=>{})}return{tab,key}}async function openEngine(client,rpc,target,cwd){let taskId=target.id,tab=await seedCanonicalTab(client,taskId),key=`${taskId}::${tab.id}`,retryArgs=["api","tab-new","--task-id",taskId,"--kind","engine"];try{let pinned=withPinnedSessionId(engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort,model:target.model}),target.vendor);trustEngineWorktree(target.vendor,cwd);let repos=target.multiRepo?await launchReposOf(client,taskId):void 0;trustExtraRepos(target.vendor,repos);let launch=buildEngineSessionLaunch({task:{id:taskId,kind:target.kind,vendor:target.vendor,repo:target.repo,repos},worktreePath:cwd,shell:resolveSessionShell(),argv:pinned.argv,promptIntent:{kind:"none"},tabId:tab.id}),open=await openAdmittedEngine(rpc,{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:persistedMaxLiveEngines(),taskId,retryArgs});if(!createdFresh(open)&&open.respawned!==!0)throw collision(taskId,key,retryArgs);if(!open.alive)throw sessionFailed(taskId,`the new engine tab ${tab.id} exited as it started`,"the session was created but nothing stayed running in it \u2014 fix the task's launch command (`api update --command`), then open another tab",{session:key});tab=(await markCliTabSession(client,taskId,tab.id,pinned.sessionId))?.tabs.find((t)=>t.id===tab.id)??tab}finally{await rpc.request("pty.detach",{key}).catch(()=>{})}return{tab,key}}async function openNewTab(client,target,worktree,kind,opts={}){let host=await ensureHostFor(target.id,"no PTY host to run the tab in \u2014 nothing was started; check `rove daemon status`, then retry");try{let opened=kind==="shell"?await openShell(client,host.rpc,target.id,worktree,target.multiRepo===!0,opts.home===!0,opts.type):await openEngine(client,host.rpc,target,worktree);return{tab:opened.tab,session:opened.key}}catch(error){if(error instanceof ApiError)throw error;throw sessionFailed(target.id,`opening a ${kind} tab failed for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"the PTY host or the daemon refused the new tab \u2014 check `rove daemon status`, then retry")}finally{host.close()}}function fileInside(worktree,rel){if(!rel||rel.startsWith("/")||rel.includes("\x00")||rel.split(/[\\/]/).includes(".."))throw new ApiError("--file must be a path relative to the worktree","BAD_FLAG");let abs,root;try{root=realpathSync(worktree),abs=realpathSync(join(worktree,rel))}catch{throw new ApiError(`${rel} does not exist in the worktree`,"FILE_NOT_FOUND")}if(!pathWithin(root,abs))throw new ApiError(`${rel} resolves outside the worktree`,"BAD_FLAG");if(!statSync(abs).isFile())throw new ApiError(`${rel} is not a file`,"BAD_FLAG");return abs}async function spawnCommandTab(client,taskId,cwd,command,title,purpose,retryArgs){let host=await ensureHostFor(taskId,"no PTY host to run the tab in \u2014 nothing was started; check `rove daemon status`, then retry");try{let tab=await allocateTab(client,taskId,{kind:"command",title,command,...purpose?{purpose}:{}}),key=`${taskId}::${tab.id}`;try{let open;try{open=await host.rpc.request("pty.open",{key,cwd,command,defaultColors:readPersistedTerminalDefaultColors()})}catch(error){throw await closeTabsSnapshot(client,taskId,tab.id).catch(()=>{return}),error}if(!createdFresh(open))throw collision(taskId,key,retryArgs)}finally{await host.rpc.request("pty.detach",{key}).catch(()=>{})}return{tab,session:key}}catch(error){if(error instanceof ApiError)throw error;throw sessionFailed(taskId,`opening the tab failed for ${taskId}: ${error instanceof Error?error.message:String(error)}`,"the PTY host or the daemon refused the new tab \u2014 check `rove daemon status`, then retry")}finally{host.close()}}async function launchEditor(client,spec){let abs=fileInside(spec.worktree,spec.file),launch=await resolveEditorLaunch(spec.worktree,abs,spec.line);if(!launch)throw new ApiError("no editor found \u2014 set $VISUAL/$EDITOR, or Settings \u2192 General \u2192 Editor","NO_EDITOR",{hint:"an editor chosen in Settings wins over $EDITOR; `rove config` shows what resolves"});let snapshot=await readDaemonTabs(client,spec.taskId),previous=snapshot?findEditorTab(snapshot)?.id:void 0;return{...await spawnCommandTab(client,spec.taskId,spec.worktree,["sh","-c",launch.command],launch.label,"editor",["api","tab-new","--task-id",spec.taskId,"--kind","editor",`--file=${spec.file}`,...spec.line===void 0?[]:[`--line=${spec.line}`]]),...previous?{replaces:previous}:{},...launch.atLine===void 0?{}:{atLine:launch.atLine}}}function findPane(taskId,pane){let found=listPaneLaunches({socketPath:defaultDaemonSocketPath(),binPath:ROVE_PRODUCT_NAME,taskId}).find((p)=>`${p.pluginId}.${p.paneId}`===pane);if(!found)throw new ApiError(`no enabled plugin pane named ${pane}`,"PANE_NOT_FOUND",{hint:"panes of enabled plugins only; `rove plugin list` shows what is installed"});return found}async function launchPane(client,spec,split){let pane=findPane(spec.taskId,spec.pane),snapshot=await readDaemonTabs(client,spec.taskId),host=snapshot?.tabs.find((t)=>t.id===(spec.hostTab??snapshot.activeId));if(pane.placement==="split"&&host&&host.kind!=="content"){let out=await split(spec.taskId,host.id,spec.worktree,pane);if(out.changed)return{tab:out.tab,session:`${spec.taskId}::${host.id}::${out.leaf}`,leaf:out.leaf}}return spawnCommandTab(client,spec.taskId,spec.worktree,pane.argv,pane.title,void 0,["api","tab-new","--task-id",spec.taskId,"--kind","pane",`--pane=${spec.pane}`])}async function launchViewport(client,spec){let shown=(await readDaemonTabs(client,spec.view.id))?.tabs.find((t)=>t.id==="tab-1"),engine=shown?.kind==="engine"?shown:void 0;return{tab:await allocateTab(client,spec.taskId,{kind:"engine",title:null,...engine?.vendor?{vendor:engine.vendor}:{},sessionId:engine?.sessionId??null,spawned:!0,ptyTask:{id:spec.view.id,worktree:spec.view.worktree}}),session:`${spec.view.id}::tab-1`}}function launchTab(client,spec,split){switch(spec.kind){case"editor":return launchEditor(client,spec);case"pane":return launchPane(client,spec,split);case"viewport":return launchViewport(client,spec)}}var NO_OP={revived:!1,alive:!0,resumed:!1};function engineRelaunch(target,row,worktree){let base=tabEngineBase(target,row),vendor=row.vendor??target.vendor,resumeArgv=row.sessionId&&row.spawned?engineResumeArgv(base,vendor,row.sessionId):null,pinned=resumeArgv?null:withPinnedSessionId(base,vendor,row.sessionId?()=>row.sessionId:void 0);return trustEngineWorktree(vendor,worktree),{launch:buildEngineSessionLaunch({task:{id:target.id,kind:target.kind,vendor,repo:target.repo},worktreePath:worktree,shell:resolveSessionShell(),argv:resumeArgv??pinned?.argv??base,promptIntent:{kind:"none"},tabId:row.id}),resumed:resumeArgv!==null,sessionId:resumeArgv?row.sessionId:pinned?.sessionId}}async function openEngineTab(client,rpc,target,row,worktree){let{launch,resumed,sessionId}=engineRelaunch(target,row,worktree),open=await openAdmittedEngine(rpc,{key:launch.key,cwd:worktree,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:persistedMaxLiveEngines(),taskId:target.id,retryArgs:["api","tab-revive","--task-id",target.id,"--tab",row.id]});if(!createdFresh(open)&&open.respawned!==!0)return NO_OP;if(!open.alive)throw sessionFailed(target.id,`the engine in tab ${row.id} exited as it started`,"the session was reopened but nothing stayed running in it \u2014 fix the task's launch command (`api update --command`), then retry",{session:launch.key});return await markCliTabSession(client,target.id,row.id,sessionId??null),{revived:!0,resumed,...sessionId?{sessionId}:{}}}async function openCommandTab(rpc,target,row,worktree){let key=`${target.id}::${row.id}`,open=await rpc.request("pty.open",{key,cwd:worktree,command:row.command,defaultColors:readPersistedTerminalDefaultColors()});if(!createdFresh(open)&&open.respawned!==!0)return NO_OP;if(!open.alive)throw sessionFailed(target.id,`the command in tab ${row.id} exited as it started`,"run `get-task` for the tab",{session:key});if(row.command.length===1&&!row.purpose)await rpc.request("pty.write",{key,data:shellIdentityInput(target.id,row.id)});return{revived:!0,resumed:!1}}async function reviveTab(client,target,tabId,worktree,opts={}){let host=await ensureHostFor(target.id,"no PTY host to run the tab in \u2014 nothing was started; check `rove daemon status`, then retry"),key=`${target.id}::${tabId}`;try{let{sessions=[]}=await host.rpc.request("pty.list",{}),listed=sessions.find((s)=>s.key===key);if(listed?.alive&&!opts.replaceExited)return NO_OP;let row=(await readDaemonTabs(client,target.id))?.tabs.find((t)=>t.id===tabId);if(!row&&listed&&tabId==="tab-1")row=await seedCanonicalTab(client,target.id);if(!row)throw new ApiError(`tab ${tabId} is not a tab of task ${target.id}`,"TAB_NOT_FOUND",{taskId:target.id,hint:"pick a tab id from `get-task` .tabs[]",nextCommandArgs:["api","get-task","--task-id",target.id]});if(row.kind==="content"||row.kind==="engine"&&row.ptyTask){let why=row.kind==="content"?"is a preview with no session":`is a view of task ${row.ptyTask?.id}'s session`;throw new ApiError(`tab ${tabId} on task ${target.id} ${why}`,"TAB_NOT_REVIVABLE",{taskId:target.id,tabId,hint:"pick a shell or engine tab from `get-task` .tabs[], or revive a view's session under its own task",nextCommandArgs:["api","get-task","--task-id",target.id]})}if(listed&&listed.restored!==!0)await host.rpc.request("pty.kill",{key,wait:!0});if(row.kind!=="engine")return await openCommandTab(host.rpc,target,row,worktree);let revived=await openEngineTab(client,host.rpc,target,row,worktree);if(opts.awaitEngine){if(await awaitEngineProcess(host.rpc,key,tabEngineBase(target,row)[0],{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS})===null)throw sessionFailed(target.id,`the engine did not start in tab ${tabId}`,"check the engine's launch command")}return revived}catch(error){if(error instanceof ApiError)throw error;if(error instanceof RemoteEngineLaunchError)throw new ApiError(error.message,error.code,{taskId:target.id,hint:"an SSH-backed project's engine cannot be launched from this machine; open the task on the machine that holds it"});throw sessionFailed(target.id,`reviving tab ${tabId} failed for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"the PTY host or the daemon refused the open \u2014 check `rove daemon status`, then retry")}finally{await host.rpc.request("pty.detach",{key}).catch(()=>{}),host.close()}}function tabNotFound(taskId,tabId){return 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]})}function locate(taskId,tabId,state){let tab=state&&Array.isArray(state.tabs)?state.tabs.find((t)=>t.id===tabId):void 0;if(!state||!tab)throw tabNotFound(taskId,tabId);if(tab.kind==="content")throw new ApiError(`tab ${tabId} is a content tab; only terminal tabs split`,"TAB_NOT_SPLITTABLE");return{state,tab}}async function editTree(client,taskId,tabId,edit){let{tab}=locate(taskId,tabId,await readDaemonTabs(client,taskId)),before=tab.splitTree??initialSplit(null),after=edit(before);if(after===before)return{tab,before,after};let saved=await patchTabSplit(client,taskId,tabId,collapseSplit(after));if(!saved)throw tabNotFound(taskId,tabId);return{tab:saved,before,after}}async function openLeafShell(rpc,key,cwd,opts={}){if(await rpc.request("pty.open",{key,cwd,command:opts.command??[resolveSessionShell()],defaultColors:readPersistedTerminalDefaultColors(),...opts.size?{cols:opts.size.cols,rows:opts.size.rows}:{}}),opts.identity)await rpc.request("pty.write",{key,data:opts.identity});await rpc.request("pty.detach",{key}).catch(()=>{})}async function splitTab(client,taskId,tabId,worktree,edit){let host=await ensureHostFor(taskId,"no PTY host to run the split in \u2014 nothing was changed; check `rove daemon status`");try{switch(edit.kind){case"open":{let{tab,before,after}=await editTree(client,taskId,tabId,(tree)=>{let from=leaves(tree.root).some((l)=>l.id===edit.from)?edit.from:tree.activeLeafId,base=from===tree.activeLeafId?tree:{...tree,activeLeafId:from},argv=edit.command?.argv??[resolveSessionShell()],next=splitActive(base,edit.orientation,argv,edit.size??null);if(next===base)return tree;return edit.command?renameLeaf(next,next.activeLeafId,edit.command.title):next});if(after===before)return{tab,leaf:before.activeLeafId,changed:!1};let leaf=after.activeLeafId;try{await openLeafShell(host.rpc,splitLeafPtyKey(tabPtyKeyFor(taskId,tab),leaf),worktree,{size:edit.size,command:edit.command?.argv})}catch(error){throw await editTree(client,taskId,tabId,(tree)=>removeLeaf(tree,leaf)??tree).catch(()=>{return}),sessionFailed(taskId,`opening a split shell failed: ${error instanceof Error?error.message:String(error)}`,"the PTY host refused the shell \u2014 the split was taken back; check `rove daemon status`, then retry")}return{tab,leaf,changed:!0}}case"close":{let{tab,before,after}=await editTree(client,taskId,tabId,(tree)=>{let next=removeLeaf(tree,edit.leaf);if(next===null)throw new ApiError(`${edit.leaf} is the only pane; close the tab instead`,"LAST_LEAF");return next});if(after===before)return{tab,leaf:edit.leaf,changed:!1};return await killTaskSessions(host.rpc,[splitLeafPtyKey(tabPtyKeyFor(taskId,tab),edit.leaf)]),{tab,leaf:edit.leaf,changed:!0}}case"rename":{let{tab,before,after}=await editTree(client,taskId,tabId,(tree)=>renameLeaf(tree,edit.leaf,edit.title));return{tab,leaf:edit.leaf,changed:after!==before}}case"reset":{let{tab}=await editTree(client,taskId,tabId,(tree)=>tree),shellTab=tab.kind==="command";if(!shellTab&&edit.leaf==="leaf-1")throw new ApiError("reset respawns a login shell; this pane runs an engine","RESET_ENGINE",{hint:"close the engine tab and open a new one; shell tabs and split shells reset"});let key=splitLeafPtyKey(tabPtyKeyFor(taskId,tab),edit.leaf);return await killTaskSessions(host.rpc,[key],{wait:!0}),await openLeafShell(host.rpc,key,worktree,{size:edit.size,identity:shellTab&&edit.leaf==="leaf-1"?shellIdentityInput(taskId,tab.id):void 0}),{tab,leaf:edit.leaf,changed:!1}}}}finally{host.close()}}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)})}async function ensureWorktree(client,target){if(target.worktreePath)return target.worktreePath;let res=await client.request("task.ensureWorktree",{taskId:target.id});if(!res.worktreePath)throw new ApiError(`task ${target.id} has no worktree`,"NO_WORKTREE");return res.worktreePath}async function deliverHosted(client,target,worktree,prompt){let host=await ensureHostFor(target.id,"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){let engineBin=engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort,model:target.model})[0],tabId=target.tab,respawnRepos=target.respawn&&target.multiRepo?await launchReposOf(client,target.id):void 0;return await deliverToExactTab(host.rpc,target.id,tabId,worktree,prompt,{engineBin,maxLiveEngines:persistedMaxLiveEngines(),...target.respawn?{respawn:()=>restoredTabLaunch({...target,repos:respawnRepos},tabId,worktree,resolveSessionShell())}:{}})}let{argv,sessionId}=withPinnedSessionId(engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort,model:target.model}),target.vendor);trustEngineWorktree(target.vendor,worktree);let repos=target.multiRepo?await launchReposOf(client,target.id):void 0;trustExtraRepos(target.vendor,repos);let launch=buildEngineSessionLaunch({task:{id:target.id,kind:target.kind,vendor:target.vendor,repo:target.repo,repos},worktreePath:worktree,shell:resolveSessionShell(),argv,promptIntent:target.newTask?{kind:"new-task",prompt}:{kind:"explicit",prompt}}),result=await deliverHostedPrompt(host.rpc,{id:target.id,engineBin:argv[0],scope:await ptyScopeOf(client,{id:target.id}),...target.firstConversation?{firstConversation:!0}:{}},worktree,prompt,launch,{maxLiveEngines:persistedMaxLiveEngines(),retryArgs:["api","send","--task-id",target.id,"--plain","--prompt",prompt]});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 the send",{session:result.session,engineReady:result.engineReady,...result.reason?{reason:result.reason}:{}});if(await publishCliTabSnapshot(client,target.id,result.started?sessionId:void 0),result.started&&sessionId){let startedTab=result.session.split("::")[1];if(startedTab)await markCliTabSession(client,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(client,taskId,tabId){let host=await openPtyHost();try{let sessions=host?await listSessions(host.rpc):[],saved=(await readDaemonTabs(client,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?await closeTabsSnapshot(client,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&&closing.ptyTask.tabId===void 0)?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=await ensureWorktree(client,target);if(target.newTask)await client.request("task.observeLanguage",{taskId:target.id,text:prompt}).catch(()=>{});let hosted=await ops.deliverHosted(client,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; start a conversation in it with `api add --parent <id> --no-worktree`");return hosted}async function readLiveTaskIds(tasks){let listed=await handlePtyList();if(!listed?.sessions)return null;let live=new Set;for(let row of listed.sessions){if(row.alive===!1||typeof row.key!=="string")continue;let[taskId,tabId]=row.key.split("::");if(taskId)live.add(resolvePtyOwner(tasks,taskId,tabId))}return live}var defaultApiRuntime={liveTaskIds:readLiveTaskIds,isTaskRunning:async(taskId,engineArgv,scope)=>(await defaultApiRuntime.taskTabs(taskId,engineArgv,scope)).running,taskTabs:async(taskId,engineArgv,scope)=>{let listed=null,host=await openPtyHost();if(host)try{listed=await listSessionsOrNull(host.rpc)}finally{host.close()}let visible=listed?unclaimedSessions(listed,scope):null,sessions=visible??[],hostReachable=listed!==null,liveVendors,engineAlive;try{let{engineProcessIn,foregroundEngineIn:foregroundEngineIn2,parsePsSnapshot:parsePsSnapshot2,psSnapshot:psSnapshot2}=await import("./chunk-24q493p3.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-bdbm8jkd.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,visible,exits,liveVendors,engineAlive).map((row)=>{let sessionId=sessionIds.get(row.id);return sessionId?{...row,sessionId}:row}),running:hostReachable?hasLiveEngineTab(snapshot,scope?.alias?.taskId??taskId,scope?.alias?sessions.filter((s)=>isUnderKey(s.key,aliasKey(scope.alias))):sessions,engineAlive,engineArgv?.[0]):null}},closeTerminalTab:closeHeadlessTerminalTab,deliverPrompt:(client,target,prompt)=>deliverPrompt(client,target,prompt),openTab:async(client,target,kind,opts)=>openNewTab(client,target,await ensureWorktree(client,target),kind,opts),launchTab:(client,spec)=>launchTab(client,spec,(taskId,tabId,worktree,pane)=>splitTab(client,taskId,tabId,worktree,{kind:"open",orientation:"row",from:"",command:{argv:pane.argv,title:pane.title}})),splitTab,reviveTab,resolveRepoRoot:async(absPath)=>resolveMainRepoRoot(absPath),inspectRepo:(absPath)=>inspectRepo(absPath),isUsableRepo:async(absPath)=>isRemoteRepoKey(absPath)||isGitRepo(absPath),isValidBranchName:async(branch)=>isValidBranchName(branch),defaultVendor:async(repo)=>{let{getGlobalDefaultVendor,getRepoLastActiveVendor}=await import("./chunk-k13dhhea.js");return(repo?getRepoLastActiveVendor(repo):void 0)??getGlobalDefaultVendor()},readWorktreeChanges:async(worktreePath)=>(await import("./chunk-11wyec8z.js")).readWorktreeChanges(worktreePath),readBranchSignals:async(worktreePath,recordedBaseRef)=>(await import("./chunk-9xtg2k54.js")).readBranchSignals(worktreePath,recordedBaseRef),tearDownSession:async(taskId,scope)=>{let host=await openPtyHost();if(host)try{await killTaskSessions(host.rpc,taskKeys(await listSessions(host.rpc),taskId,scope))}catch{}finally{host.close()}},listeningPorts:async()=>(await import("./chunk-b95q6zhk.js")).scanListeningPorts(),measureCheckout:async(path2)=>{let{measureCheckout}=await import("./chunk-cqrr5g2e.js"),{execHostForWorktreePath}=await import("./chunk-djq86z2j.js");return measureCheckout(execHostForWorktreePath(path2),path2)}};async function checkMenu(daemon,taskId,tab,fallback){try{let reply=await daemon.request("send.check",{taskId,...tab?{tabId:tab}:{}});return{waiting:reply.awaiting.length>0?reply.awaiting:null,settleMs:reply.settleMs}}catch{}let tabs;try{tabs=(await daemon.request("status.list")).tasks[taskId]?.tabs}catch{return{waiting:fallback?.state==="permission_needed"?tab?[tab]:[]:null,settleMs:0}}let waiting=Object.entries(tabs??{}).filter(([id,s])=>s.kind==="needs-input"&&(tab===void 0||id===tab)).map(([id])=>id);return{waiting:waiting.length>0?waiting:null,settleMs:0}}async function tabsAwaitingChoice(daemon,taskId,tab,fallback){let check=await checkMenu(daemon,taskId,tab,fallback);if(check.waiting===null&&check.settleMs>0){let{promise,resolve:resolve3}=Promise.withResolvers();setTimeout(resolve3,check.settleMs),await promise,check=await checkMenu(daemon,taskId,tab,fallback)}return check.waiting}function awaitingChoiceError(taskId,tabs){let where=tabs.length>0?` (${tabs.join(", ")})`:"";return new ApiError(`not sent: task ${taskId}${where} is showing an approval or question menu (or came to rest straight from one); a paste would land in it and Enter would confirm the highlighted option`,"AWAITING_PERMISSION",{taskId,...tabs.length>0?{tabIds:tabs}:{},hint:"answer the menu with keys in the task's terminal (the TUI, or the web page's keys), then send again; read the menu with read-output --source terminal",nextCommandArgs:["api","read-output","--task-id",taskId,"--source","terminal"]})}async function issueUpdate(ctx){let title=ctx.args.str("title"),body=ctx.args.str("body"),task=ctx.args.str("task"),status=ctx.args.enumOf("status");if(title===void 0&&body===void 0&&task===void 0&&status===void 0)throw new ApiError("issue-update requires --title, --body, --task, and/or --status","MISSING_FLAG");let repoRoot=ctx.args.requireRepo("repo"),id=ctx.args.int("id"),state;if(title!==void 0||body!==void 0||task!==void 0)state=await simpleRpc(ctx,"issue.mutate",{repoRoot,op:{type:"update",id,title,body,...task===void 0?{}:{taskId:task==="none"?null:task}}});if(status!==void 0)state=await simpleRpc(ctx,"issue.mutate",{repoRoot,op:{type:"setStatus",id,status}});return state}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 resolveSendTask(ctx,daemon,tab){let explicit=ctx.args.str("task-id");if(explicit)return{taskId:explicit,tab};let own=await readOwnDispatcher(daemon);if(own?.dispatcher){let{dispatcher}=own;return{taskId:dispatcher.taskId,tab:tab??await resolveDispatcherTab(ctx.runtime,daemon,dispatcher)}}if(own)throw noReplyAddress(own.self);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");return{taskId:active,tab}}async function send(ctx){let rollback={};try{return await sendNow(ctx,rollback)}catch(err){throw await rollback.undo?.().catch(()=>{}),err}}async function sendNow(ctx,rollback){let daemon=daemonOf(ctx),tab=ctx.args.str("tab");if(tab==="new"){let parent=ctx.args.str("task-id"),command=ctx.args.str("command"),text2=ctx.args.promptText();throw new ApiError("send delivers into a conversation that exists; start a new one in the same directory with `add --no-worktree`","BAD_TAB",{hint:"`add --no-worktree` nests under the calling session, or under --parent ID",nextCommandArgs:["api","add",...parent?["--parent",parent]:[],"--no-worktree",...command?["--command",command]:[],...text2?["--prompt",text2]:[]]})}if(tab&&!/^tab-[A-Za-z0-9-]+$/.test(tab))throw new ApiError(`--tab must be a tab id like tab-2 (got ${JSON.stringify(tab)})`,"BAD_TAB");let replace=ctx.args.bool("replace")===!0;if(replace&&!tab)throw new ApiError("--replace takes over one dead tab; pass --tab tab-N","BAD_FLAG",helpStep("send"));let tabCommand=ctx.args.str("command");if(tabCommand&&!replace)throw new ApiError("--command names the engine that takes over a dead tab; pass --tab tab-N --replace (another engine in a new conversation is `add --no-worktree --command`)","BAD_FLAG",helpStep("send"));let prompt=replace?ctx.args.promptText()??"":requirePromptText(ctx,"send"),respawn=ctx.args.bool("respawn");if(assertQueueFlags(ctx),respawn&&tab===void 0)throw new ApiError("--respawn addresses one frozen tab; pass --tab tab-N (got --tab <canonical>)","BAD_FLAG",helpStep("send"));let sendTo=await resolveSendTask(ctx,daemon,tab),taskId=sendTo.taskId;tab=sendTo.tab;let res=await daemon.request("task.get",{taskId});if(replace&&tab)prompt=[await handoffBrief(ctx,res.task,tab,"send"),prompt].filter(Boolean).join(`
|
|
4
|
+
`)}var DEFAULT_PAGE_MESSAGES=40,MAX_PAGE_MESSAGES=50,PAGE_BYTE_BUDGET=131072,STRING_CLIP_CHARS=16384,DEFAULT_TAIL_LINES=40,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.tab===void 0||typeof c.tab==="string")&&(c.src==="history"&&typeof c.sid==="string"&&typeof c.idx==="number"||c.src==="terminal"&&typeof c.off==="number")))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,at,limit){let forward="from"in at,page=[],bytes=0,limited=!1,i=forward?at.from:at.before-1;for(;forward?i<messages.length:i>=0;forward?i++:i--){if(page.length>=limit)break;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}if(forward)return{page,start:at.from,end:i,limited};return page.reverse(),{page,start:i+1,end:at.before,limited}}function terminalLines(text){return terminalRows(text)}function boundedTail(text,maxLines=TERMINAL_TAIL_LINES){let lines=terminalLines(text),start=Math.max(0,lines.length-Math.min(maxLines,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}}async function peekTaskTerminal(taskId,engineBin,tab,sinceOffset,scope){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,scope)??unclaimedSessions(sessions,scope).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 engineScreenError(task,opts={}){let pattern=protocolEntry(task.vendor).errorLine;if(!pattern)return;try{let alias=task.ptyAlias,page=await peekTaskTerminal(alias?.taskId??task.id,taskEngineArgv(task)[0],alias?.tabId);if(!page||page==="host-unreachable")return;return screenErrorLine(pattern,boundedTail(page.text).tail,opts)}catch{return}}var ACTIVITY_STATES_DOC="`.activity.state` is one of: `idle` (at rest), `running` (a turn is in progress), `turn_complete` (a turn finished \u2014 also at rest; treat it like idle when deciding whether the engine is free), `permission_needed` (blocked on an approval prompt), `rate_limited` (clears on its own), `error` (the last turn failed; `.activity.detail.note` carries the engine's text, and `.activity.source: \"screen\"` means it was read off the engine's own screen because the engine reported nothing), `dead` (the engine process exited; the tab's exit record says how).",AT_REST=new Set(["idle","turn_complete"]);async function readActivityRegistry(daemon){try{let dbg=await daemon.request("debug.inspect");return{tasks:dbg?.activity?.tasks??{},tabs:dbg?.activity?.tabs??{}}}catch{return null}}async function activityView(registry,task,tab){let entry=tab?registry?.tabs[task.id]?.[tab]:registry?.tasks[task.id];if(!entry)return null;let base={state:entry.state,at:new Date(entry.at).toISOString(),forMs:Math.max(0,Date.now()-entry.at),...entry.detail?{detail:entry.detail}:{}},atRest=AT_REST.has(entry.state);if(tab||!(atRest||entry.state==="running"))return base;let note=await engineScreenError(task,{last:!atRest});return note?{...base,state:"error",detail:{failure:"other",note},source:"screen"}:base}function parseOption(raw){let eq=raw.indexOf("=");if(eq<=0||eq===raw.length-1)throw new ApiError(`--option must be key=label (got ${JSON.stringify(raw)})`,"BAD_FLAG",helpStep("gate-raise"));return{key:raw.slice(0,eq).trim(),label:raw.slice(eq+1).trim()}}async function gateRaise(ctx){let{args}=ctx,daemon=daemonOf(ctx),taskId=args.require("task-id"),tabId=args.str("tab");if(!tabId){let self=await ownSession(daemon);if(self?.taskId===taskId)tabId=self.tabId}return{ok:!0,gate:(await daemon.request("gate.raise",{taskId,...tabId?{tabId}:{},question:args.require("question"),options:args.list("option").map(parseOption),...args.str("recommend")?{recommended:args.str("recommend")}:{},...args.str("context")?{context:args.str("context")}:{}})).gate}}async function gateAnswer(ctx){let{args}=ctx,option=args.str("option"),text=args.str("text");if(option===void 0&&text===void 0)throw new ApiError("pass --option KEY and/or --text TEXT","MISSING_FLAG",helpStep("gate-answer"));let res=await daemonOf(ctx).request("gate.answer",{gateId:args.require("gate"),...option!==void 0?{option}:{},...text!==void 0?{text}:{},by:"cli"});return{ok:!0,gate:res.gate,delivered:res.delivered}}async function gateWithdraw(ctx){return{ok:!0,gate:(await daemonOf(ctx).request("gate.withdraw",{gateId:ctx.args.require("gate")})).gate}}async function gates(ctx){let{args}=ctx,repo=args.str("repo")?args.requireRepo("repo"):void 0;return{gates:(await daemonOf(ctx).request("gate.list",{...repo?{repo}:{},...args.str("task-id")?{taskId:args.str("task-id")}:{},status:args.enumOf("status")??"open"})).gates}}async function takeOwedGateAnswers(daemon,taskId,tab){try{let owed=await daemon.request("gate.takeUndelivered",{taskId,...tab?{tabId:tab}:{}});return owed.text?{text:owed.text,gateIds:owed.gateIds}:null}catch{return null}}async function markGateAnswersDelivered(daemon,gateIds){await daemon.request("gate.markDelivered",{gateIds}).catch(()=>{})}function assertQueueFlags(ctx){if(!ctx.args.bool("queue"))return;let clash=ctx.args.bool("replace")?"--replace":ctx.args.bool("if-runnable")?"--if-runnable":ctx.args.bool("respawn")?"--respawn":null;if(clash)throw new ApiError(`--queue waits for a running turn; it does not combine with ${clash}`,"BAD_FLAG",helpStep("send"))}async function queueIfBusy(ctx,daemon,task,tab,text){if(!ctx.args.bool("queue"))return null;let tabId=tab??canonicalEngineTab(readTabsSnapshot(task.id)?.tabs??[])?.id;if(!tabId)return null;let reply=await daemon.request("queue.add",{taskId:task.id,tabId,text,expectReport:ctx.args.bool("expect-report")===!0});if(!reply.queued||!reply.item)return null;return{ok:!0,taskId:task.id,tabId,queued:!0,queueId:reply.item.id,position:reply.position}}var QUEUE_LIST_VERB={name:"queue-list",group:"read",summary:"Prompts `send --queue` is holding for a busy tab, oldest first: {items:[{id, taskId, tabId, text, expectReport, at, lastError?}]}. Each is pasted when its tab's turn ends, one per turn; `lastError` says why the last hand-over did not land (it stays at the head). Held in the daemon's memory: a daemon restart drops them.",flags:[F.taskId(!1)],handler:async(ctx)=>simpleRpc(ctx,"queue.list",ctx.args.str("task-id")?{taskId:ctx.args.str("task-id")}:{})},QUEUE_EDIT_VERB={name:"queue-edit",group:"drive",summary:'Rewrite a prompt `send --queue` is holding (`queue-list` gives the id), keeping its id and its place in line: {edited:true, item} or {edited:false, reason:"not-found"|"pasting"}. `pasting` means its turn already came and the old text is going in.',flags:[{name:"id",type:"string",required:!0,placeholder:"q-N",description:"The held prompt's id."},F.prompt(!0,"The new text, replacing the held prompt's."),F.promptFile()],handler:async(ctx)=>{let text=ctx.args.promptText();if(text===void 0)throw new ApiError("pass --prompt or --prompt-file","MISSING_FLAG",helpStep("queue-edit"));return simpleRpc(ctx,"queue.edit",{id:ctx.args.require("id"),text})}},QUEUE_CANCEL_VERB={name:"queue-cancel",group:"drive",summary:"Take back a prompt `send --queue` is holding (`queue-list` gives the id): {cancelled: true|false}.",flags:[{name:"id",type:"string",required:!0,placeholder:"q-N",description:"The held prompt's id."}],handler:async(ctx)=>simpleRpc(ctx,"queue.cancel",{id:ctx.args.require("id")})};async function handoffBrief(ctx,task,tabId,verb){if(!/^tab-[A-Za-z0-9-]+$/.test(tabId))throw new ApiError(`the tab to hand over must be a tab id like tab-2 (got ${JSON.stringify(tabId)})`,"BAD_TAB");let source=((await readDaemonTabs(daemonOf(ctx),task.id))?.tabs??readTabsSnapshot(task.id)?.tabs??[]).find((t)=>t.id===tabId);if(!source)throw new ApiError(`task ${task.id} has no tab ${tabId}`,"TAB_NOT_FOUND",{taskId:task.id,tabId});if(source.kind!=="engine")throw new ApiError(`${tabId} is not an engine conversation; nothing to hand over`,"BAD_FLAG",helpStep(verb));let tabVendor=source.vendor??task.vendor,plan=await planWorktreeHandoff(source,liveSourceProtocol(source,tabVendor),taskCwd(task),task.title);if(plan.kind==="handoff")return plan.prompt;throw new ApiError(plan.kind==="no-transcript"?`${plan.engine} keeps no transcript Rove can name, so ${tabId} cannot be handed to another engine`:`${tabId} has no conversation yet; send the prompt directly`,plan.kind==="no-transcript"?"NO_TRANSCRIPT":"NO_CONVERSATION",{taskId:task.id,tabId})}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 ensureHostFor(taskId,hint){try{return await ensurePtyHost()}catch(error){throw sessionFailed(taskId,`failed to start PTY host for ${taskId}: ${error instanceof Error?error.message:String(error)}`,hint)}}var OLD_CONVERSATION=["sessionId","spawned","forkFrom","initialPrompt","liveVendor","lastTitle","autoTitle"];async function assertDeadEngineTab(runtime,daemon,task,tabId){let scope=await ptyScopeOf(daemon,task);if(hostedKeyFor(task.id,tabId,scope)===null||scope.alias?.tabId===tabId)throw new ApiError(`tab ${tabId} runs under another task's conversation; --replace cannot swap it`,"BAD_FLAG",{taskId:task.id,tabId});let row=(await runtime.taskTabs(task.id,taskEngineArgv(task),scope)).tabs.find((t)=>t.id===tabId);if(!row||row.kind!=="engine")throw new ApiError(`${tabId} is not an engine conversation; nothing to replace`,"BAD_FLAG",helpStep("send"));if(row.viewOf)throw new ApiError(`${tabId} is a view of task ${row.viewOf}'s session; --replace cannot swap it`,"BAD_FLAG",{taskId:task.id,tabId});if(row.alive===!1||row.engineAlive===!1)return;throw new ApiError(`${tabId}'s engine is still running; --replace only takes over a dead or exited tab. Drop --replace to continue in a shared child task`,"TAB_ALIVE",{taskId:task.id,tabId})}var REWRITTEN=[...OLD_CONVERSATION,"vendor","engineCommand"];async function undoReplace(daemon,taskId,tabId,before){let set={},unset=[];for(let field of REWRITTEN)if(before[field]===void 0)unset.push(field);else set[field]=before[field];await applyTabOps(daemon,taskId,[{op:"patch",id:tabId,set,unset}]);let host=await ensureHostFor(taskId,"no PTY host to stop the replacement in");try{await host.rpc.request("pty.kill",{key:`${taskId}::${tabId}`,wait:!0})}finally{host.close()}}function replaceDeadTab(ctx,task,tabId,command){let{runtime,daemon}=ctx;return withDeliveryLock(`${task.id}::${tabId}::replace`,async()=>{await assertDeadEngineTab(runtime,daemon,task,tabId);let worktree=taskCwd(task);if(!worktree)throw new ApiError(`task ${task.id} has no worktree yet`,"NO_WORKTREE");let before=(await readDaemonTabs(daemon,task.id))?.tabs.find((t)=>t.id===tabId)??{},protocol=command?resolveCommandProtocol(command):void 0,set=protocol?{vendor:protocol,...command!==protocol?{engineCommand:command}:{}}:void 0,unset=protocol&&command===protocol?[...OLD_CONVERSATION,"engineCommand"]:OLD_CONVERSATION,undo=()=>undoReplace(daemon,task.id,tabId,before);await applyTabOps(daemon,task.id,[{op:"patch",id:tabId,...set?{set}:{},unset}]);let target={id:task.id,worktreePath:worktree,kind:task.kind,vendor:task.vendor,command:task.command,modelEffort:task.modelEffort,model:task.model,repo:task.repo};try{await runtime.reviveTab(daemon,target,tabId,worktree,{replaceExited:!0,awaitEngine:!0})}catch(error){throw await undo().catch(()=>{}),error}return undo})}function csvOf(ctx,name,allowed,verb="list"){let raw=ctx.args.str(name);if(raw===void 0)return;let values=raw.split(",").map((s)=>s.trim()).filter(Boolean);if(values.find((v)=>!allowed.includes(v))!==void 0||values.length===0)throw new ApiError(`--${name} takes a comma list of ${allowed.join(", ")}`,"BAD_FLAG",helpStep(verb));return new Set(values)}function listFilters(ctx){let repo=ctx.args.path("repo"),statuses=csvOf(ctx,"status",TASK_STATUSES),activities=csvOf(ctx,"activity",TASK_ACTIVITY_STATES);if(!repo&&!statuses&&!activities)return null;return{repo,statuses,activities}}async function filterTaskList(ctx,daemon,tasks,filters){let isLocal=(t)=>!t.origin||t.origin.machineId==="local",repo=filters.repo?await repoFilter(ctx.runtime,filters.repo,tasks.filter(isLocal).map((t)=>t.repo)):null,kept=tasks.filter((t)=>(!repo||isLocal(t)&&repo.matches(t.repo))&&(!filters.statuses||filters.statuses.has(t.status))),out=kept;if(filters.activities){let wanted=filters.activities,registry=await readActivityRegistry(daemon),local=kept.filter(isLocal),views=await Promise.all(local.map((t)=>activityView(registry,t)));out=local.flatMap((task,i)=>{let activity=views[i];return activity&&wanted.has(activity.state)?[{...task,activity}]:[]})}return{tasks:out,...repo&&repo.unresolvableRepos.length>0?{unresolvableRepos:repo.unresolvableRepos}:{}}}var TASK_FIELDS2={id:!0,title:!0,repo:!0,branch:!0,worktreePath:!0,kind:!0,scratch:!0,noProject:!0,routine:!0,status:!0,pinned:!0,kept:!0,notes:!0,todos:!0,archived:!0,vendor:!0,command:!0,prStatus:!0,modelEffort:!0,model:!0,tier:!0,groupId:!0,observedLanguage:!0,deletion:!0,quotaResume:!0,scheduledStart:!0,autoFixCi:!0,linkedWorkItem:!0,dispatcher:!0,parentTaskId:!0,sharesWorkspaceOf:!0,workspace:!0,cwdSubpath:!0,ptyAlias:!0,requireReport:!0,worktreeOnly:!0,prompt:!0,baseRef:!0,worktreeName:!0,gitRepo:!0,extraRepos:!0,sessionPrs:!0,report:!0,origin:!0,repoId:!0,createdAt:!0,updatedAt:!0},LIST_FIELDS=[...Object.keys(TASK_FIELDS2),"repoCount","activity"];function listFields(ctx){let fields=csvOf(ctx,"fields",LIST_FIELDS);return fields?[...fields]:void 0}function projectTasks(tasks,fields){return tasks.map((task)=>{let row={};for(let field of fields)if(field in task)row[field]=task[field];return row})}var MAX_LIVE_ENGINES_KEY="engine.maxLiveSessions";function normalizeMaxLiveEngines(value){let n=typeof value==="number"?value:typeof value==="string"&&value.trim()!==""?Number(value.trim()):Number.NaN;return Number.isInteger(n)&&n>0?n:void 0}function persistedMaxLiveEngines(){return normalizeMaxLiveEngines(loadStateFile()[MAX_LIVE_ENGINES_KEY])}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 openAdmittedEngine(rpc,{key,cwd,...launch?{command:launch.command}:{},defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:opts.maxLiveEngines,snapshot:opts.snapshot,taskId,retryArgs:["api","send","--task-id",taskId,"--tab",tabId,"--respawn","--plain","--prompt",prompt]});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:"start a new conversation for this prompt with `add --no-worktree`, 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","--plain","--prompt",prompt]})}import{realpathSync,statSync}from"fs";import{join}from"path";function collision(taskId,key,retryArgs){return new ApiError(`session ${key} already existed; no new tab was created`,"TAB_COLLISION",{taskId,hint:"a session already held the tab id the daemon minted; retry to get a fresh id",nextCommandArgs:retryArgs})}var createdFresh=(open)=>open.created??open.replay.length===0;async function openShell(client,rpc,taskId,cwd,multiRepo,home,type){let shell=resolveSessionShell(),tab=home?await seedShellHome(client,taskId,shell):await allocateTab(client,taskId,{kind:"command",title:null,command:[shell]}),key=`${taskId}::${tab.id}`;try{let open;try{open=await rpc.request("pty.open",{key,cwd,command:[shell],defaultColors:readPersistedTerminalDefaultColors()})}catch(error){if(!home)await closeTabsSnapshot(client,taskId,tab.id).catch(()=>{return});throw error}if(!createdFresh(open))throw collision(taskId,key,["api","tab-new","--task-id",taskId,"--kind","shell"]);let repos=multiRepo?await launchReposOf(client,taskId):void 0;if(await rpc.request("pty.write",{key,data:shellTabInput(taskId,tab.id,cwd,repos&&repoEnv(repos))}),type!==void 0)await rpc.request("pty.write",{key,data:`${type}\r`})}finally{await rpc.request("pty.detach",{key}).catch(()=>{})}return{tab,key}}async function openEngine(client,rpc,target,cwd){let taskId=target.id,tab=await seedCanonicalTab(client,taskId),key=`${taskId}::${tab.id}`,retryArgs=["api","tab-new","--task-id",taskId,"--kind","engine"];try{let pinned=withPinnedSessionId(engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort,model:target.model}),target.vendor);trustEngineWorktree(target.vendor,cwd);let repos=target.multiRepo?await launchReposOf(client,taskId):void 0;trustExtraRepos(target.vendor,repos);let launch=buildEngineSessionLaunch({task:{id:taskId,kind:target.kind,vendor:target.vendor,repo:target.repo,repos},worktreePath:cwd,shell:resolveSessionShell(),argv:pinned.argv,promptIntent:{kind:"none"},tabId:tab.id}),open=await openAdmittedEngine(rpc,{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:persistedMaxLiveEngines(),taskId,retryArgs});if(!createdFresh(open)&&open.respawned!==!0)throw collision(taskId,key,retryArgs);if(!open.alive)throw sessionFailed(taskId,`the new engine tab ${tab.id} exited as it started`,"the session was created but nothing stayed running in it \u2014 fix the task's launch command (`api update --command`), then open another tab",{session:key});tab=(await markCliTabSession(client,taskId,tab.id,pinned.sessionId))?.tabs.find((t)=>t.id===tab.id)??tab}finally{await rpc.request("pty.detach",{key}).catch(()=>{})}return{tab,key}}async function openNewTab(client,target,worktree,kind,opts={}){let host=await ensureHostFor(target.id,"no PTY host to run the tab in \u2014 nothing was started; check `rove daemon status`, then retry");try{let opened=kind==="shell"?await openShell(client,host.rpc,target.id,worktree,target.multiRepo===!0,opts.home===!0,opts.type):await openEngine(client,host.rpc,target,worktree);return{tab:opened.tab,session:opened.key}}catch(error){if(error instanceof ApiError)throw error;throw sessionFailed(target.id,`opening a ${kind} tab failed for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"the PTY host or the daemon refused the new tab \u2014 check `rove daemon status`, then retry")}finally{host.close()}}function fileInside(worktree,rel){if(!rel||rel.startsWith("/")||rel.includes("\x00")||rel.split(/[\\/]/).includes(".."))throw new ApiError("--file must be a path relative to the worktree","BAD_FLAG");let abs,root;try{root=realpathSync(worktree),abs=realpathSync(join(worktree,rel))}catch{throw new ApiError(`${rel} does not exist in the worktree`,"FILE_NOT_FOUND")}if(!pathWithin(root,abs))throw new ApiError(`${rel} resolves outside the worktree`,"BAD_FLAG");if(!statSync(abs).isFile())throw new ApiError(`${rel} is not a file`,"BAD_FLAG");return abs}async function spawnCommandTab(client,taskId,cwd,command,title,purpose,retryArgs){let host=await ensureHostFor(taskId,"no PTY host to run the tab in \u2014 nothing was started; check `rove daemon status`, then retry");try{let tab=await allocateTab(client,taskId,{kind:"command",title,command,...purpose?{purpose}:{}}),key=`${taskId}::${tab.id}`;try{let open;try{open=await host.rpc.request("pty.open",{key,cwd,command,defaultColors:readPersistedTerminalDefaultColors()})}catch(error){throw await closeTabsSnapshot(client,taskId,tab.id).catch(()=>{return}),error}if(!createdFresh(open))throw collision(taskId,key,retryArgs)}finally{await host.rpc.request("pty.detach",{key}).catch(()=>{})}return{tab,session:key}}catch(error){if(error instanceof ApiError)throw error;throw sessionFailed(taskId,`opening the tab failed for ${taskId}: ${error instanceof Error?error.message:String(error)}`,"the PTY host or the daemon refused the new tab \u2014 check `rove daemon status`, then retry")}finally{host.close()}}async function launchEditor(client,spec){let abs=fileInside(spec.worktree,spec.file),launch=await resolveEditorLaunch(spec.worktree,abs,spec.line);if(!launch)throw new ApiError("no editor found \u2014 set $VISUAL/$EDITOR, or Settings \u2192 General \u2192 Editor","NO_EDITOR",{hint:"an editor chosen in Settings wins over $EDITOR; `rove config` shows what resolves"});let snapshot=await readDaemonTabs(client,spec.taskId),previous=snapshot?findEditorTab(snapshot)?.id:void 0;return{...await spawnCommandTab(client,spec.taskId,spec.worktree,["sh","-c",launch.command],launch.label,"editor",["api","tab-new","--task-id",spec.taskId,"--kind","editor",`--file=${spec.file}`,...spec.line===void 0?[]:[`--line=${spec.line}`]]),...previous?{replaces:previous}:{},...launch.atLine===void 0?{}:{atLine:launch.atLine}}}function findPane(taskId,pane){let found=listPaneLaunches({socketPath:defaultDaemonSocketPath(),binPath:ROVE_PRODUCT_NAME,taskId}).find((p)=>`${p.pluginId}.${p.paneId}`===pane);if(!found)throw new ApiError(`no enabled plugin pane named ${pane}`,"PANE_NOT_FOUND",{hint:"panes of enabled plugins only; `rove plugin list` shows what is installed"});return found}async function launchPane(client,spec,split){let pane=findPane(spec.taskId,spec.pane),snapshot=await readDaemonTabs(client,spec.taskId),host=snapshot?.tabs.find((t)=>t.id===(spec.hostTab??snapshot.activeId));if(pane.placement==="split"&&host&&host.kind!=="content"){let out=await split(spec.taskId,host.id,spec.worktree,pane);if(out.changed)return{tab:out.tab,session:`${spec.taskId}::${host.id}::${out.leaf}`,leaf:out.leaf}}return spawnCommandTab(client,spec.taskId,spec.worktree,pane.argv,pane.title,void 0,["api","tab-new","--task-id",spec.taskId,"--kind","pane",`--pane=${spec.pane}`])}async function launchViewport(client,spec){let shown=(await readDaemonTabs(client,spec.view.id))?.tabs.find((t)=>t.id==="tab-1"),engine=shown?.kind==="engine"?shown:void 0;return{tab:await allocateTab(client,spec.taskId,{kind:"engine",title:null,...engine?.vendor?{vendor:engine.vendor}:{},sessionId:engine?.sessionId??null,spawned:!0,ptyTask:{id:spec.view.id,worktree:spec.view.worktree}}),session:`${spec.view.id}::tab-1`}}function launchTab(client,spec,split){switch(spec.kind){case"editor":return launchEditor(client,spec);case"pane":return launchPane(client,spec,split);case"viewport":return launchViewport(client,spec)}}var NO_OP={revived:!1,alive:!0,resumed:!1};function engineRelaunch(target,row,worktree){let base=tabEngineBase(target,row),vendor=row.vendor??target.vendor,resumeArgv=row.sessionId&&row.spawned?engineResumeArgv(base,vendor,row.sessionId):null,pinned=resumeArgv?null:withPinnedSessionId(base,vendor,row.sessionId?()=>row.sessionId:void 0);return trustEngineWorktree(vendor,worktree),{launch:buildEngineSessionLaunch({task:{id:target.id,kind:target.kind,vendor,repo:target.repo},worktreePath:worktree,shell:resolveSessionShell(),argv:resumeArgv??pinned?.argv??base,promptIntent:{kind:"none"},tabId:row.id}),resumed:resumeArgv!==null,sessionId:resumeArgv?row.sessionId:pinned?.sessionId}}async function openEngineTab(client,rpc,target,row,worktree){let{launch,resumed,sessionId}=engineRelaunch(target,row,worktree),open=await openAdmittedEngine(rpc,{key:launch.key,cwd:worktree,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:persistedMaxLiveEngines(),taskId:target.id,retryArgs:["api","tab-revive","--task-id",target.id,"--tab",row.id]});if(!createdFresh(open)&&open.respawned!==!0)return NO_OP;if(!open.alive)throw sessionFailed(target.id,`the engine in tab ${row.id} exited as it started`,"the session was reopened but nothing stayed running in it \u2014 fix the task's launch command (`api update --command`), then retry",{session:launch.key});return await markCliTabSession(client,target.id,row.id,sessionId??null),{revived:!0,resumed,...sessionId?{sessionId}:{}}}async function openCommandTab(rpc,target,row,worktree){let key=`${target.id}::${row.id}`,open=await rpc.request("pty.open",{key,cwd:worktree,command:row.command,defaultColors:readPersistedTerminalDefaultColors()});if(!createdFresh(open)&&open.respawned!==!0)return NO_OP;if(!open.alive)throw sessionFailed(target.id,`the command in tab ${row.id} exited as it started`,"run `get-task` for the tab",{session:key});if(row.command.length===1&&!row.purpose)await rpc.request("pty.write",{key,data:shellIdentityInput(target.id,row.id)});return{revived:!0,resumed:!1}}async function reviveTab(client,target,tabId,worktree,opts={}){let host=await ensureHostFor(target.id,"no PTY host to run the tab in \u2014 nothing was started; check `rove daemon status`, then retry"),key=`${target.id}::${tabId}`;try{let{sessions=[]}=await host.rpc.request("pty.list",{}),listed=sessions.find((s)=>s.key===key);if(listed?.alive&&!opts.replaceExited)return NO_OP;let row=(await readDaemonTabs(client,target.id))?.tabs.find((t)=>t.id===tabId);if(!row&&listed&&tabId==="tab-1")row=await seedCanonicalTab(client,target.id);if(!row)throw new ApiError(`tab ${tabId} is not a tab of task ${target.id}`,"TAB_NOT_FOUND",{taskId:target.id,hint:"pick a tab id from `get-task` .tabs[]",nextCommandArgs:["api","get-task","--task-id",target.id]});if(row.kind==="content"||row.kind==="engine"&&row.ptyTask){let why=row.kind==="content"?"is a preview with no session":`is a view of task ${row.ptyTask?.id}'s session`;throw new ApiError(`tab ${tabId} on task ${target.id} ${why}`,"TAB_NOT_REVIVABLE",{taskId:target.id,tabId,hint:"pick a shell or engine tab from `get-task` .tabs[], or revive a view's session under its own task",nextCommandArgs:["api","get-task","--task-id",target.id]})}if(listed&&listed.restored!==!0)await host.rpc.request("pty.kill",{key,wait:!0});if(row.kind!=="engine")return await openCommandTab(host.rpc,target,row,worktree);let revived=await openEngineTab(client,host.rpc,target,row,worktree);if(opts.awaitEngine){if(await awaitEngineProcess(host.rpc,key,tabEngineBase(target,row)[0],{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS})===null)throw sessionFailed(target.id,`the engine did not start in tab ${tabId}`,"check the engine's launch command")}return revived}catch(error){if(error instanceof ApiError)throw error;if(error instanceof RemoteEngineLaunchError)throw new ApiError(error.message,error.code,{taskId:target.id,hint:"an SSH-backed project's engine cannot be launched from this machine; open the task on the machine that holds it"});throw sessionFailed(target.id,`reviving tab ${tabId} failed for ${target.id}: ${error instanceof Error?error.message:String(error)}`,"the PTY host or the daemon refused the open \u2014 check `rove daemon status`, then retry")}finally{await host.rpc.request("pty.detach",{key}).catch(()=>{}),host.close()}}function tabNotFound(taskId,tabId){return 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]})}function locate(taskId,tabId,state){let tab=state&&Array.isArray(state.tabs)?state.tabs.find((t)=>t.id===tabId):void 0;if(!state||!tab)throw tabNotFound(taskId,tabId);if(tab.kind==="content")throw new ApiError(`tab ${tabId} is a content tab; only terminal tabs split`,"TAB_NOT_SPLITTABLE");return{state,tab}}async function editTree(client,taskId,tabId,edit){let{tab}=locate(taskId,tabId,await readDaemonTabs(client,taskId)),before=tab.splitTree??initialSplit(null),after=edit(before);if(after===before)return{tab,before,after};let saved=await patchTabSplit(client,taskId,tabId,collapseSplit(after));if(!saved)throw tabNotFound(taskId,tabId);return{tab:saved,before,after}}async function openLeafShell(rpc,key,cwd,opts={}){if(await rpc.request("pty.open",{key,cwd,command:opts.command??[resolveSessionShell()],defaultColors:readPersistedTerminalDefaultColors(),...opts.size?{cols:opts.size.cols,rows:opts.size.rows}:{}}),opts.identity)await rpc.request("pty.write",{key,data:opts.identity});await rpc.request("pty.detach",{key}).catch(()=>{})}async function splitTab(client,taskId,tabId,worktree,edit){let host=await ensureHostFor(taskId,"no PTY host to run the split in \u2014 nothing was changed; check `rove daemon status`");try{switch(edit.kind){case"open":{let{tab,before,after}=await editTree(client,taskId,tabId,(tree)=>{let from=leaves(tree.root).some((l)=>l.id===edit.from)?edit.from:tree.activeLeafId,base=from===tree.activeLeafId?tree:{...tree,activeLeafId:from},argv=edit.command?.argv??[resolveSessionShell()],next=splitActive(base,edit.orientation,argv,edit.size??null);if(next===base)return tree;return edit.command?renameLeaf(next,next.activeLeafId,edit.command.title):next});if(after===before)return{tab,leaf:before.activeLeafId,changed:!1};let leaf=after.activeLeafId;try{await openLeafShell(host.rpc,splitLeafPtyKey(tabPtyKeyFor(taskId,tab),leaf),worktree,{size:edit.size,command:edit.command?.argv})}catch(error){throw await editTree(client,taskId,tabId,(tree)=>removeLeaf(tree,leaf)??tree).catch(()=>{return}),sessionFailed(taskId,`opening a split shell failed: ${error instanceof Error?error.message:String(error)}`,"the PTY host refused the shell \u2014 the split was taken back; check `rove daemon status`, then retry")}return{tab,leaf,changed:!0}}case"close":{let{tab,before,after}=await editTree(client,taskId,tabId,(tree)=>{let next=removeLeaf(tree,edit.leaf);if(next===null)throw new ApiError(`${edit.leaf} is the only pane; close the tab instead`,"LAST_LEAF");return next});if(after===before)return{tab,leaf:edit.leaf,changed:!1};return await killTaskSessions(host.rpc,[splitLeafPtyKey(tabPtyKeyFor(taskId,tab),edit.leaf)]),{tab,leaf:edit.leaf,changed:!0}}case"rename":{let{tab,before,after}=await editTree(client,taskId,tabId,(tree)=>renameLeaf(tree,edit.leaf,edit.title));return{tab,leaf:edit.leaf,changed:after!==before}}case"reset":{let{tab}=await editTree(client,taskId,tabId,(tree)=>tree),shellTab=tab.kind==="command";if(!shellTab&&edit.leaf==="leaf-1")throw new ApiError("reset respawns a login shell; this pane runs an engine","RESET_ENGINE",{hint:"close the engine tab and open a new one; shell tabs and split shells reset"});let key=splitLeafPtyKey(tabPtyKeyFor(taskId,tab),edit.leaf);return await killTaskSessions(host.rpc,[key],{wait:!0}),await openLeafShell(host.rpc,key,worktree,{size:edit.size,identity:shellTab&&edit.leaf==="leaf-1"?shellIdentityInput(taskId,tab.id):void 0}),{tab,leaf:edit.leaf,changed:!1}}}}finally{host.close()}}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)})}async function ensureWorktree(client,target){if(target.worktreePath)return target.worktreePath;let res=await client.request("task.ensureWorktree",{taskId:target.id});if(!res.worktreePath)throw new ApiError(`task ${target.id} has no worktree`,"NO_WORKTREE");return res.worktreePath}async function deliverHosted(client,target,worktree,prompt){let host=await ensureHostFor(target.id,"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){let engineBin=engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort,model:target.model})[0],tabId=target.tab,respawnRepos=target.respawn&&target.multiRepo?await launchReposOf(client,target.id):void 0;return await deliverToExactTab(host.rpc,target.id,tabId,worktree,prompt,{engineBin,maxLiveEngines:persistedMaxLiveEngines(),...target.respawn?{respawn:()=>restoredTabLaunch({...target,repos:respawnRepos},tabId,worktree,resolveSessionShell())}:{}})}let{argv,sessionId}=withPinnedSessionId(engineLaunchArgv({command:target.command,vendor:target.vendor,effort:target.modelEffort,model:target.model}),target.vendor);trustEngineWorktree(target.vendor,worktree);let repos=target.multiRepo?await launchReposOf(client,target.id):void 0;trustExtraRepos(target.vendor,repos);let launch=buildEngineSessionLaunch({task:{id:target.id,kind:target.kind,vendor:target.vendor,repo:target.repo,repos},worktreePath:worktree,shell:resolveSessionShell(),argv,promptIntent:target.newTask?{kind:"new-task",prompt}:{kind:"explicit",prompt}}),result=await deliverHostedPrompt(host.rpc,{id:target.id,engineBin:argv[0],scope:await ptyScopeOf(client,{id:target.id}),...target.firstConversation?{firstConversation:!0}:{}},worktree,prompt,launch,{maxLiveEngines:persistedMaxLiveEngines(),retryArgs:["api","send","--task-id",target.id,"--plain","--prompt",prompt]});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 the send",{session:result.session,engineReady:result.engineReady,...result.reason?{reason:result.reason}:{}});if(await publishCliTabSnapshot(client,target.id,result.started?sessionId:void 0),result.started&&sessionId){let startedTab=result.session.split("::")[1];if(startedTab)await markCliTabSession(client,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(client,taskId,tabId){let host=await openPtyHost();try{let sessions=host?await listSessions(host.rpc):[],saved=(await readDaemonTabs(client,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?await closeTabsSnapshot(client,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&&closing.ptyTask.tabId===void 0)?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=await ensureWorktree(client,target);if(target.newTask)await client.request("task.observeLanguage",{taskId:target.id,text:prompt}).catch(()=>{});let hosted=await ops.deliverHosted(client,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; start a conversation in it with `api add --parent <id> --no-worktree`");return hosted}async function readLiveTaskIds(tasks){let listed=await handlePtyList();if(!listed?.sessions)return null;let live=new Set;for(let row of listed.sessions){if(row.alive===!1||typeof row.key!=="string")continue;let[taskId,tabId]=row.key.split("::");if(taskId)live.add(resolvePtyOwner(tasks,taskId,tabId))}return live}var defaultApiRuntime={liveTaskIds:readLiveTaskIds,isTaskRunning:async(taskId,engineArgv,scope)=>(await defaultApiRuntime.taskTabs(taskId,engineArgv,scope)).running,taskTabs:async(taskId,engineArgv,scope)=>{let listed=null,host=await openPtyHost();if(host)try{listed=await listSessionsOrNull(host.rpc)}finally{host.close()}let visible=listed?unclaimedSessions(listed,scope):null,sessions=visible??[],hostReachable=listed!==null,liveVendors,engineAlive;try{let{engineProcessIn,foregroundEngineIn:foregroundEngineIn2,parsePsSnapshot:parsePsSnapshot2,psSnapshot:psSnapshot2}=await import("./chunk-e80q746v.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-bdbm8jkd.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,visible,exits,liveVendors,engineAlive).map((row)=>{let sessionId=sessionIds.get(row.id);return sessionId?{...row,sessionId}:row}),running:hostReachable?hasLiveEngineTab(snapshot,scope?.alias?.taskId??taskId,scope?.alias?sessions.filter((s)=>isUnderKey(s.key,aliasKey(scope.alias))):sessions,engineAlive,engineArgv?.[0]):null}},closeTerminalTab:closeHeadlessTerminalTab,deliverPrompt:(client,target,prompt)=>deliverPrompt(client,target,prompt),openTab:async(client,target,kind,opts)=>openNewTab(client,target,await ensureWorktree(client,target),kind,opts),launchTab:(client,spec)=>launchTab(client,spec,(taskId,tabId,worktree,pane)=>splitTab(client,taskId,tabId,worktree,{kind:"open",orientation:"row",from:"",command:{argv:pane.argv,title:pane.title}})),splitTab,reviveTab,resolveRepoRoot:async(absPath)=>resolveMainRepoRoot(absPath),inspectRepo:(absPath)=>inspectRepo(absPath),isUsableRepo:async(absPath)=>isRemoteRepoKey(absPath)||isGitRepo(absPath),isValidBranchName:async(branch)=>isValidBranchName(branch),defaultVendor:async(repo)=>{let{getGlobalDefaultVendor,getRepoLastActiveVendor}=await import("./chunk-k13dhhea.js");return(repo?getRepoLastActiveVendor(repo):void 0)??getGlobalDefaultVendor()},readWorktreeChanges:async(worktreePath)=>(await import("./chunk-11wyec8z.js")).readWorktreeChanges(worktreePath),readBranchSignals:async(worktreePath,recordedBaseRef)=>(await import("./chunk-9xtg2k54.js")).readBranchSignals(worktreePath,recordedBaseRef),tearDownSession:async(taskId,scope)=>{let host=await openPtyHost();if(host)try{await killTaskSessions(host.rpc,taskKeys(await listSessions(host.rpc),taskId,scope))}catch{}finally{host.close()}},listeningPorts:async()=>(await import("./chunk-b95q6zhk.js")).scanListeningPorts(),measureCheckout:async(path2)=>{let{measureCheckout}=await import("./chunk-cqrr5g2e.js"),{execHostForWorktreePath}=await import("./chunk-djq86z2j.js");return measureCheckout(execHostForWorktreePath(path2),path2)}};async function checkMenu(daemon,taskId,tab,fallback){try{let reply=await daemon.request("send.check",{taskId,...tab?{tabId:tab}:{}});return{waiting:reply.awaiting.length>0?reply.awaiting:null,settleMs:reply.settleMs}}catch{}let tabs;try{tabs=(await daemon.request("status.list")).tasks[taskId]?.tabs}catch{return{waiting:fallback?.state==="permission_needed"?tab?[tab]:[]:null,settleMs:0}}let waiting=Object.entries(tabs??{}).filter(([id,s])=>s.kind==="needs-input"&&(tab===void 0||id===tab)).map(([id])=>id);return{waiting:waiting.length>0?waiting:null,settleMs:0}}async function tabsAwaitingChoice(daemon,taskId,tab,fallback){let check=await checkMenu(daemon,taskId,tab,fallback);if(check.waiting===null&&check.settleMs>0){let{promise,resolve:resolve3}=Promise.withResolvers();setTimeout(resolve3,check.settleMs),await promise,check=await checkMenu(daemon,taskId,tab,fallback)}return check.waiting}function awaitingChoiceError(taskId,tabs){let where=tabs.length>0?` (${tabs.join(", ")})`:"";return new ApiError(`not sent: task ${taskId}${where} is showing an approval or question menu (or came to rest straight from one); a paste would land in it and Enter would confirm the highlighted option`,"AWAITING_PERMISSION",{taskId,...tabs.length>0?{tabIds:tabs}:{},hint:"answer the menu with keys in the task's terminal (the TUI, or the web page's keys), then send again; read the menu with read-output --source terminal",nextCommandArgs:["api","read-output","--task-id",taskId,"--source","terminal"]})}async function issueUpdate(ctx){let title=ctx.args.str("title"),body=ctx.args.str("body"),task=ctx.args.str("task"),status=ctx.args.enumOf("status");if(title===void 0&&body===void 0&&task===void 0&&status===void 0)throw new ApiError("issue-update requires --title, --body, --task, and/or --status","MISSING_FLAG");let repoRoot=ctx.args.requireRepo("repo"),id=ctx.args.int("id"),state;if(title!==void 0||body!==void 0||task!==void 0)state=await simpleRpc(ctx,"issue.mutate",{repoRoot,op:{type:"update",id,title,body,...task===void 0?{}:{taskId:task==="none"?null:task}}});if(status!==void 0)state=await simpleRpc(ctx,"issue.mutate",{repoRoot,op:{type:"setStatus",id,status}});return state}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 resolveSendTask(ctx,daemon,tab){let explicit=ctx.args.str("task-id");if(explicit)return{taskId:explicit,tab};let own=await readOwnDispatcher(daemon);if(own?.dispatcher){let{dispatcher}=own;return{taskId:dispatcher.taskId,tab:tab??await resolveDispatcherTab(ctx.runtime,daemon,dispatcher)}}if(own)throw noReplyAddress(own.self);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");return{taskId:active,tab}}async function send(ctx){let rollback={};try{return await sendNow(ctx,rollback)}catch(err){throw await rollback.undo?.().catch(()=>{}),err}}async function sendNow(ctx,rollback){let daemon=daemonOf(ctx),tab=ctx.args.str("tab");if(tab==="new"){let parent=ctx.args.str("task-id"),command=ctx.args.str("command"),text2=ctx.args.promptText();throw new ApiError("send delivers into a conversation that exists; start a new one in the same directory with `add --no-worktree`","BAD_TAB",{hint:"`add --no-worktree` nests under the calling session, or under --parent ID",nextCommandArgs:["api","add",...parent?["--parent",parent]:[],"--no-worktree",...command?["--command",command]:[],...text2?["--prompt",text2]:[]]})}if(tab&&!/^tab-[A-Za-z0-9-]+$/.test(tab))throw new ApiError(`--tab must be a tab id like tab-2 (got ${JSON.stringify(tab)})`,"BAD_TAB");let replace=ctx.args.bool("replace")===!0;if(replace&&!tab)throw new ApiError("--replace takes over one dead tab; pass --tab tab-N","BAD_FLAG",helpStep("send"));let tabCommand=ctx.args.str("command");if(tabCommand&&!replace)throw new ApiError("--command names the engine that takes over a dead tab; pass --tab tab-N --replace (another engine in a new conversation is `add --no-worktree --command`)","BAD_FLAG",helpStep("send"));let prompt=replace?ctx.args.promptText()??"":requirePromptText(ctx,"send"),respawn=ctx.args.bool("respawn");if(assertQueueFlags(ctx),respawn&&tab===void 0)throw new ApiError("--respawn addresses one frozen tab; pass --tab tab-N (got --tab <canonical>)","BAD_FLAG",helpStep("send"));let sendTo=await resolveSendTask(ctx,daemon,tab),taskId=sendTo.taskId;tab=sendTo.tab;let res=await daemon.request("task.get",{taskId});if(replace&&tab)prompt=[await handoffBrief(ctx,res.task,tab,"send"),prompt].filter(Boolean).join(`
|
|
5
5
|
|
|
6
6
|
`);await assertNotEmptySuccess(daemon,ctx,prompt);let replacedTab;if(replace&&tab)rollback.undo=await replaceDeadTab({runtime:ctx.runtime,daemon},res.task,tab,tabCommand),replacedTab=tab;let alias=res.task.ptyAlias;if(alias&&tab===void 0)tab=alias.tabId;if(tab&&hostedKeyFor(taskId,tab,await ptyScopeOf(daemon,res.task))===null)throw new ApiError(`tab ${tab} on task ${taskId} belongs to a child task's conversation`,"TAB_NOT_FOUND",{taskId,tabId:tab,hint:"address the child itself with its own --task-id (`list` shows the lineage)",nextCommandArgs:["api","get-task","--task-id",taskId]});let plain=ctx.args.bool("plain")?prompt:await withPeerProvenance(daemon,taskId,prompt),held=await queueIfBusy(ctx,daemon,res.task,tab,plain);if(held)return held;let target=await activityView(await readActivityRegistry(daemon),res.task,tab),waiting=await tabsAwaitingChoice(daemon,taskId,tab,target);if(waiting)throw awaitingChoiceError(taskId,waiting);let owed=await takeOwedGateAnswers(daemon,taskId,tab),withAnswers=owed?`${owed.text}
|
|
7
7
|
|
|
8
8
|
${plain}`:plain,expectReport=ctx.args.bool("expect-report")===!0,pinnedTab=tab?{tabId:tab}:{},admit=ctx.args.bool("if-runnable")?await daemon.request("send.admit",{taskId,...tab?{tabId:tab}:{},...respawn?{respawn}:{},expectReport,promptHead:prompt}):void 0;if(admit?.skipped)throw new ApiError(`not sent: ${admit.skipped.reason}`,"SKIPPED",{taskId,skipped:admit.skipped,...admit.deliveryId?{deliveryId:admit.deliveryId}:{}});let claimId=admit?.claimId,armed=expectReport||res.task.requireReport===!0,deliveryId=admit?admit.deliveryId:armed?(await daemon.request("delivery.arm",{taskId,...pinnedTab,promptHead:prompt})).deliveryId:void 0,text=deliveryId?`${withAnswers}
|
|
9
9
|
|
|
10
|
-
${deliveryFooter(deliveryId,roveApiInvocation())}`:withAnswers,settle=async(delivered2,session)=>{if(claimId)await daemon.request("send.release",{claimId,delivered:delivered2}).catch(()=>{});let landedTab=session?.split("::")[1]??tab;if(await recordSend(daemon,{taskId,tabId:landedTab,prompt,delivered:delivered2,deliveryId}),!deliveryId)return;await daemon.request("delivery.settle",{deliveryId,delivered:delivered2,...landedTab?{tabId:landedTab}:{}}).catch(()=>{})},delivered;try{delivered=await ctx.runtime.deliverPrompt(daemon,{id:alias&&tab===alias.tabId?alias.taskId:taskId,worktreePath:taskCwd(res.task),kind:res.task.kind,vendor:res.task.vendor,command:res.task.command,modelEffort:res.task.modelEffort,model:res.task.model,repo:res.task.repo,...res.task.extraRepos?.length||res.task.sharesWorkspaceOf?{multiRepo:!0}:{},tab,respawn},text)}catch(err){throw await settle(!1),err}if(!delivered.delivered){let mayLand=promptMayHaveLanded(delivered);if(mayLand)rollback.undo=void 0;throw await settle(mayLand,mayLand?delivered.session:void 0),new ApiError(`prompt was not confirmed in ${taskId}'s engine (paste did not land)`,"NOT_DELIVERED")}if(await settle(!0,delivered.session),owed)await markGateAnswersDelivered(daemon,owed.gateIds);return{ok:!0,taskId,...replacedTab?{replacedTab}:{},session:delivered.session,...deliveryId?{deliveryId}:{},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}:{},...target&&TARGET_FAILED.has(target.state)?{targetState:target.state,...target.detail?{targetDetail:target.detail}:{}}:{}}}var TARGET_FAILED=new Set(["error","dead"]);async function dispatch(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),text=requirePromptText(ctx,"dispatch"),tabId=ctx.args.str("tab"),self=await ownSession(daemon).catch(()=>null),reply=await daemon.request("session.deliver",{taskId,text,...tabId!==void 0?{tabId}:{},source:"dispatcher",...self?{fromTaskId:self.taskId,fromTabId:self.tabId}:{}});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),await ptyScopeOf(daemon,res.task)),runnability=await readRunnability(daemon,taskId);return{task:res.task,running,tabs,...runnability?{runnability}:{}}}async function list(ctx){let daemon=daemonOf(ctx),local=await daemon.request("task.list"),{mergeTaskList}=await import("./chunk-sdmzsn5n.js"),all=ctx.caller.cli?await mergeTaskList(local):local,wantArchived=ctx.args.bool("archived")??!1,merged={...all,tasks:(all.tasks??[]).filter((task)=>task.archived===!0===wantArchived)},filters=listFilters(ctx),fields=listFields(ctx),result=filters?{...merged,...await filterTaskList(ctx,daemon,merged.tasks??[],filters)}:merged;if(!result.tasks)return result;let tasks=result.tasks.map((t)=>t.extraRepos?.length?{...t,repoCount:t.extraRepos.length+1}:t);return{...result,tasks:fields?projectTasks(tasks,fields):tasks}}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 RECOVER=["api","engine-list"];async function routineRunEngine(ctx,repo,vendor){return vendor??(repo?await ctx.runtime.defaultVendor(repo):void 0)??DEFAULT_TASK_VENDOR}async function pinnedEngine(ctx,repo,vendor,model,effort){let engine=await routineRunEngine(ctx,repo,vendor),protocol=taskEngine({vendor:engine});if(model)assertEngineAcceptsModel(protocol,model,RECOVER);if(effort)assertEngineAcceptsEffort(protocol,effort,RECOVER);return engine}async function createEngineFields(ctx,repo){let vendor=ctx.args.vendor(),model=ctx.args.str("model")?.trim(),effort=ctx.args.str("effort")?.trim();if(!model&&!effort)return vendor?{vendor}:{};return{vendor:await pinnedEngine(ctx,repo,vendor,model,effort),...model?{model}:{},...effort?{effort}:{}}}async function updateEngineFields(ctx,id){let hasVendor=ctx.args.present("vendor"),hasModel=ctx.args.present("model"),hasEffort=ctx.args.present("effort");if(!hasVendor&&!hasModel&&!hasEffort)return{};let vendor=ctx.args.vendor(),model=ctx.args.str("model")?.trim()||void 0,effort=ctx.args.str("effort")?.trim()||void 0,fields={...hasVendor?{vendor:vendor??null}:{},...hasModel?{model:model??null}:{},...hasEffort?{effort:effort??null}:{}},{automations}=await daemonOf(ctx).request("automation.list",{}),routine=automations.find((a)=>a.id===id);if(!routine)return fields;let nextModel=hasModel?model:routine.model,nextEffort=hasEffort?effort:routine.modelEffort;if(!nextModel&&!nextEffort)return fields;let nextVendor=hasVendor?vendor:routine.vendor,engine=await pinnedEngine(ctx,routine.repo,nextVendor,nextModel,nextEffort);return engine===routine.vendor&&!hasVendor?fields:{...fields,vendor:engine}}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."}],SCRIPT_FLAGS=[{name:"script",type:"string",placeholder:"CMD",description:"Run this shell command in the repo instead of an engine: no task, no worktree, no agent turn. Exit 0 records `ran`, anything else `script_failed`; non-empty stdout (last 4000 chars) is the run's response. Replaces --prompt and the engine flags. '' on update turns it back into a prompt routine."},{name:"script-timeout",type:"int",placeholder:"SEC",default:"120",description:"Seconds before the script is killed and the run recorded as script_failed (max 600)."}],NOTIFY_FLAG={name:"notify",type:"bool",description:"Hand every run's response, and runs that need a human, to the bound chat channel's agent (`rove weixin login`), which decides what to tell you. Off by default."};function scriptPayload(ctx){if(!ctx.args.present("script")){if(ctx.args.present("script-timeout"))throw new ApiError("--script-timeout requires --script (pass the command again to change its timeout)","BAD_FLAG");return{}}let command=ctx.args.str("script");if(command===void 0)return{script:null};return{script:{command,timeoutSeconds:ctx.args.int("script-timeout")??120}}}var 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."},WEBHOOK_FLAG={name:"webhook",type:"bool",description:"Also fire on a signed POST to the web server's /hooks/routines/<id> (GitHub's X-Hub-Signature-256). Turning it on generates the secret, shown as .webhook.secret; paste it into the GitHub webhook with content type application/json. The precheck still runs, with ROVE_WEBHOOK_EVENT and ROVE_WEBHOOK_ACTION set, and the prompt starts with what fired it. Off again forgets the secret."},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."},NEW_CONVERSATION_FLAG={name:"new-conversation",type:"bool",description:"With --persistent-session: every run starts a new conversation in the standing task (same worktree and files) instead of reopening the last one. For a routine that works a queue and needs no memory of earlier runs; refused without --persistent-session."},MODEL_FLAG={name:"model",type:"string",placeholder:"MODEL",description:"Model every run's engine launches on, in the engine's own spelling (`engine-list` shows suggestions). Rejected (BAD_MODEL) on an engine that declares no model flag."},EFFORT_FLAG={name:"effort",type:"string",placeholder:"LEVEL",description:"Reasoning effort every run's engine launches at. Validated against the engine's declared levels (BAD_EFFORT otherwise)."},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, or with --no-repo a directory session) and delivers it. Use --target-task and --target-tab for an existing conversation, or --script to run a command with no engine. An enabled routine keeps the daemon alive.",flags:[{...F.repo(!1),description:"Repo root (git toplevel) every run works in. Relative paths resolve against $PWD. Required unless --no-repo."},{name:"no-repo",type:"bool",description:"A routine with no project: each run works in its own directory (<home>/.rove/routines/<id>) and its session sits in the sidebar's Ungrouped group. Takes no --base-branch."},{name:"name",type:"string",required:!0,placeholder:"N",description:"Routine name."},F.prompt(!1,"Text delivered to the selected conversation or a new session. Required unless --script."),F.promptFile(),{...SCHEDULE_FLAG,required:!0},{...F.vendor(),description:"Engine every run launches. Omitted with --model/--effort: the repo's default engine (falling back to the built-in default) is resolved, validated and stored. Omitted without pins: runs launch the built-in default engine."},MODEL_FLAG,EFFORT_FLAG,{name:"base-branch",type:"string",placeholder:"B",description:"Base ref each run's worktree branches from."},...PRECHECK_FLAGS,...SCRIPT_FLAGS,NOTIFY_FLAG,WEBHOOK_FLAG,GRACE_FLAG,PERSISTENT_FLAG,NEW_CONVERSATION_FLAG,...TARGET_FLAGS,{name:"disabled",type:"bool",description:"Create it paused instead of active."}],handler:async(ctx)=>{let noRepo=ctx.args.bool("no-repo")===!0,hasRepo=ctx.args.str("repo")!==void 0;if(noRepo&&hasRepo)throw new ApiError("--repo and --no-repo conflict \u2014 pass one","CONFLICTING_FLAGS");if(!noRepo&&!hasRepo)throw new ApiError("pass exactly one of --repo PATH or --no-repo","MISSING_FLAG");let repo=noRepo?void 0:ctx.args.requireRepo("repo"),script=scriptPayload(ctx);if(script.script&&ctx.args.promptText()!==void 0)throw new ApiError("pass --prompt or --script, not both","BAD_FLAG");return simpleRpc(ctx,"automation.create",{...repo?{repo}:{},name:ctx.args.require("name"),...script.script?script:{prompt:requirePromptText(ctx,"routine-create")},schedule:ctx.args.require("schedule"),...ctx.args.bool("notify")?{notify:!0}:{},...ctx.args.bool("webhook")?{webhook:!0}:{},...await createEngineFields(ctx,repo),...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("new-conversation")?{newConversation:!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; --enabled false pauses it (disabling the last active one releases the daemon's keep-alive hold) and --enabled true resumes it.",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). While model/effort stay pinned, a cleared vendor is re-resolved from the repo default and stored."},{...MODEL_FLAG,description:`${MODEL_FLAG.description} '' clears it.`},{...EFFORT_FLAG,description:`${EFFORT_FLAG.description} '' clears it.`},{name:"base-branch",type:"string",placeholder:"B",description:"New base ref ('' to clear)."},...PRECHECK_FLAGS,...SCRIPT_FLAGS,{...NOTIFY_FLAG,placeholder:"BOOL"},{...WEBHOOK_FLAG,placeholder:"BOOL"},GRACE_FLAG,PERSISTENT_FLAG,{...NEW_CONVERSATION_FLAG,placeholder:"BOOL"},...TARGET_FLAGS,{name:"enabled",type:"bool",placeholder:"BOOL",description:"false pauses the routine, true resumes it."}],handler:async(ctx)=>{let id=ctx.args.require("id");return simpleRpc(ctx,"automation.update",{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")}:{},...await updateEngineFields(ctx,id),...ctx.args.present("base-branch")?{baseRef:ctx.args.str("base-branch")??null}:{},...precheckPayload(ctx),...scriptPayload(ctx),...ctx.args.present("notify")?{notify:ctx.args.bool("notify")??!0}:{},...ctx.args.present("webhook")?{webhook:ctx.args.bool("webhook")??!0}:{},...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}:{},...ctx.args.present("new-conversation")?{newConversation:ctx.args.bool("new-conversation")??!0}:{},...ctx.args.present("enabled")?{enabled:ctx.args.bool("enabled")??!0}:{}})}},{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-respond",group:"routine",summary:`Report this run's result. Every delivered routine prompt starts with a [ROVE ROUTINE] line naming its run; this is the routine-flavoured spelling of \`report --delivery <id> --outcome done --summary <text>\` and writes the same delivery report, so \`deliveries\` shows it too. One response per run \u2014 responding again replaces it. Cap ${ROUTINE_RESPONSE_MAX_CHARS} characters; markdown renders on the Routines page.`,flags:[{name:"run",type:"string",required:!0,placeholder:"RUN_ID",description:"Run id from the [ROVE ROUTINE] line."},{name:"text",type:"string",placeholder:"TEXT",description:"The response. Exactly one of --text / --prompt-file."},{...F.promptFile(),description:"Read the response from this file (`-` = stdin) \u2014 use it for anything multi-line or with backticks/$vars."}],handler:async(ctx)=>{let runId=ctx.args.require("run"),inline=ctx.args.str("text"),file=ctx.args.promptText();if(inline!==void 0&&file!==void 0)throw new ApiError("pass --text or --prompt-file, not both","BAD_FLAG");let text=inline??file;if(text===void 0)throw new ApiError("--text (or --prompt-file) is required","MISSING_FLAG");if(text.length>ROUTINE_RESPONSE_MAX_CHARS)throw new ApiError(`response is ${text.length} characters; the cap is ${ROUTINE_RESPONSE_MAX_CHARS}`,"RESPONSE_TOO_LARGE",{hint:"Summarize: lead with the conclusion, link or name the files that hold the detail."});let res=await simpleRpc(ctx,"automation.respond",{runId,text});if(res.run===null)throw new ApiError(`no routine run ${runId}`,"RUN_NOT_FOUND",{hint:"Copy the id from the [ROVE ROUTINE] line of the prompt you were given; `routine-runs --id <routine>` lists run ids."});return res}},{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_blocked (should-run refused the tick: `blocked` is the verdict {reason, detail?, until?, gateIds?} \u2014 busy, awaiting-owner, report-missing, quota, awaiting-permission; not an alarm, the cause is already in the Inbox; a manual run-now bypasses it), skipped_missed, skipped_unavailable, ran / script_failed (a --script routine: exit 0 or not; stdout is the response), dispatch_failed (also a should-run refusal for engine-dead or engine-error, which have no Inbox row of their own: it keeps `blocked` and raises the routine alarm). Each run carries `deliveryId`, `deliveryStatus` (awaiting|reported|missing|quiet: the turn completed with nothing to report) and `response` ({text, at}) once its agent reported (routine-respond or report).",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 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});let requireReport=args.bool("require-report");if(requireReport!==void 0)await daemon.request("task.requireReport",{taskId,required:requireReport});return Boolean(status)||pin!==void 0||requireReport!==void 0}async function deliverArmed(ctx,daemon,taskId,target,text){if(ctx.args.bool("require-report")!==!0&&ctx.args.bool("expect-report")!==!0)return ctx.runtime.deliverPrompt(daemon,target,text);let{deliveryId}=await daemon.request("delivery.arm",{taskId,tabId:"tab-1",promptHead:text}),settle=(delivered)=>daemon.request("delivery.settle",{deliveryId,delivered,tabId:"tab-1"}).catch(()=>{});try{let delivered=await ctx.runtime.deliverPrompt(daemon,target,`${text}
|
|
10
|
+
${deliveryFooter(deliveryId,roveApiInvocation())}`:withAnswers,settle=async(delivered2,session)=>{if(claimId)await daemon.request("send.release",{claimId,delivered:delivered2}).catch(()=>{});let landedTab=session?.split("::")[1]??tab;if(await recordSend(daemon,{taskId,tabId:landedTab,prompt,delivered:delivered2,deliveryId}),!deliveryId)return;await daemon.request("delivery.settle",{deliveryId,delivered:delivered2,...landedTab?{tabId:landedTab}:{}}).catch(()=>{})},delivered;try{delivered=await ctx.runtime.deliverPrompt(daemon,{id:alias&&tab===alias.tabId?alias.taskId:taskId,worktreePath:taskCwd(res.task),kind:res.task.kind,vendor:res.task.vendor,command:res.task.command,modelEffort:res.task.modelEffort,model:res.task.model,repo:res.task.repo,...res.task.extraRepos?.length||res.task.sharesWorkspaceOf?{multiRepo:!0}:{},tab,respawn},text)}catch(err){throw await settle(!1),err}if(!delivered.delivered){let mayLand=promptMayHaveLanded(delivered);if(mayLand)rollback.undo=void 0;throw await settle(mayLand,mayLand?delivered.session:void 0),new ApiError(`prompt was not confirmed in ${taskId}'s engine (paste did not land)`,"NOT_DELIVERED")}if(await settle(!0,delivered.session),owed)await markGateAnswersDelivered(daemon,owed.gateIds);return{ok:!0,taskId,...replacedTab?{replacedTab}:{},session:delivered.session,...deliveryId?{deliveryId}:{},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}:{},...target&&TARGET_FAILED.has(target.state)?{targetState:target.state,...target.detail?{targetDetail:target.detail}:{}}:{}}}var TARGET_FAILED=new Set(["error","dead"]);async function dispatch(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),text=requirePromptText(ctx,"dispatch"),tabId=ctx.args.str("tab"),self=await ownSession(daemon).catch(()=>null),reply=await daemon.request("session.deliver",{taskId,text,...tabId!==void 0?{tabId}:{},source:"dispatcher",...self?{fromTaskId:self.taskId,fromTabId:self.tabId}:{}});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),await ptyScopeOf(daemon,res.task)),runnability=await readRunnability(daemon,taskId);return{task:res.task,running,tabs,...runnability?{runnability}:{}}}async function list(ctx){let daemon=daemonOf(ctx),local=await daemon.request("task.list"),{mergeTaskList}=await import("./chunk-vw2e6t8s.js"),all=ctx.caller.cli?await mergeTaskList(local):local,wantArchived=ctx.args.bool("archived")??!1,merged={...all,tasks:(all.tasks??[]).filter((task)=>task.archived===!0===wantArchived)},filters=listFilters(ctx),fields=listFields(ctx),result=filters?{...merged,...await filterTaskList(ctx,daemon,merged.tasks??[],filters)}:merged;if(!result.tasks)return result;let tasks=result.tasks.map((t)=>t.extraRepos?.length?{...t,repoCount:t.extraRepos.length+1}:t);return{...result,tasks:fields?projectTasks(tasks,fields):tasks}}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 RECOVER=["api","engine-list"];async function routineRunEngine(ctx,repo,vendor){return vendor??(repo?await ctx.runtime.defaultVendor(repo):void 0)??DEFAULT_TASK_VENDOR}async function pinnedEngine(ctx,repo,vendor,model,effort){let engine=await routineRunEngine(ctx,repo,vendor),protocol=taskEngine({vendor:engine});if(model)assertEngineAcceptsModel(protocol,model,RECOVER);if(effort)assertEngineAcceptsEffort(protocol,effort,RECOVER);return engine}async function createEngineFields(ctx,repo){let vendor=ctx.args.vendor(),model=ctx.args.str("model")?.trim(),effort=ctx.args.str("effort")?.trim();if(!model&&!effort)return vendor?{vendor}:{};return{vendor:await pinnedEngine(ctx,repo,vendor,model,effort),...model?{model}:{},...effort?{effort}:{}}}async function updateEngineFields(ctx,id){let hasVendor=ctx.args.present("vendor"),hasModel=ctx.args.present("model"),hasEffort=ctx.args.present("effort");if(!hasVendor&&!hasModel&&!hasEffort)return{};let vendor=ctx.args.vendor(),model=ctx.args.str("model")?.trim()||void 0,effort=ctx.args.str("effort")?.trim()||void 0,fields={...hasVendor?{vendor:vendor??null}:{},...hasModel?{model:model??null}:{},...hasEffort?{effort:effort??null}:{}},{automations}=await daemonOf(ctx).request("automation.list",{}),routine=automations.find((a)=>a.id===id);if(!routine)return fields;let nextModel=hasModel?model:routine.model,nextEffort=hasEffort?effort:routine.modelEffort;if(!nextModel&&!nextEffort)return fields;let nextVendor=hasVendor?vendor:routine.vendor,engine=await pinnedEngine(ctx,routine.repo,nextVendor,nextModel,nextEffort);return engine===routine.vendor&&!hasVendor?fields:{...fields,vendor:engine}}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."}],SCRIPT_FLAGS=[{name:"script",type:"string",placeholder:"CMD",description:"Run this shell command in the repo instead of an engine: no task, no worktree, no agent turn. Exit 0 records `ran`, anything else `script_failed`; non-empty stdout (last 4000 chars) is the run's response. Replaces --prompt and the engine flags. '' on update turns it back into a prompt routine."},{name:"script-timeout",type:"int",placeholder:"SEC",default:"120",description:"Seconds before the script is killed and the run recorded as script_failed (max 600)."}],NOTIFY_FLAG={name:"notify",type:"bool",description:"Hand every run's response, and runs that need a human, to the bound chat channel's agent (`rove weixin login`), which decides what to tell you. Off by default."};function scriptPayload(ctx){if(!ctx.args.present("script")){if(ctx.args.present("script-timeout"))throw new ApiError("--script-timeout requires --script (pass the command again to change its timeout)","BAD_FLAG");return{}}let command=ctx.args.str("script");if(command===void 0)return{script:null};return{script:{command,timeoutSeconds:ctx.args.int("script-timeout")??120}}}var 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."},WEBHOOK_FLAG={name:"webhook",type:"bool",description:"Also fire on a signed POST to the web server's /hooks/routines/<id> (GitHub's X-Hub-Signature-256). Turning it on generates the secret, shown as .webhook.secret; paste it into the GitHub webhook with content type application/json. The precheck still runs, with ROVE_WEBHOOK_EVENT and ROVE_WEBHOOK_ACTION set, and the prompt starts with what fired it. Off again forgets the secret."},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."},NEW_CONVERSATION_FLAG={name:"new-conversation",type:"bool",description:"With --persistent-session: every run starts a new conversation in the standing task (same worktree and files) instead of reopening the last one. For a routine that works a queue and needs no memory of earlier runs; refused without --persistent-session."},MODEL_FLAG={name:"model",type:"string",placeholder:"MODEL",description:"Model every run's engine launches on, in the engine's own spelling (`engine-list` shows suggestions). Rejected (BAD_MODEL) on an engine that declares no model flag."},EFFORT_FLAG={name:"effort",type:"string",placeholder:"LEVEL",description:"Reasoning effort every run's engine launches at. Validated against the engine's declared levels (BAD_EFFORT otherwise)."},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, or with --no-repo a directory session) and delivers it. Use --target-task and --target-tab for an existing conversation, or --script to run a command with no engine. An enabled routine keeps the daemon alive.",flags:[{...F.repo(!1),description:"Repo root (git toplevel) every run works in. Relative paths resolve against $PWD. Required unless --no-repo."},{name:"no-repo",type:"bool",description:"A routine with no project: each run works in its own directory (<home>/.rove/routines/<id>) and its session sits in the sidebar's Ungrouped group. Takes no --base-branch."},{name:"name",type:"string",required:!0,placeholder:"N",description:"Routine name."},F.prompt(!1,"Text delivered to the selected conversation or a new session. Required unless --script."),F.promptFile(),{...SCHEDULE_FLAG,required:!0},{...F.vendor(),description:"Engine every run launches. Omitted with --model/--effort: the repo's default engine (falling back to the built-in default) is resolved, validated and stored. Omitted without pins: runs launch the built-in default engine."},MODEL_FLAG,EFFORT_FLAG,{name:"base-branch",type:"string",placeholder:"B",description:"Base ref each run's worktree branches from."},...PRECHECK_FLAGS,...SCRIPT_FLAGS,NOTIFY_FLAG,WEBHOOK_FLAG,GRACE_FLAG,PERSISTENT_FLAG,NEW_CONVERSATION_FLAG,...TARGET_FLAGS,{name:"disabled",type:"bool",description:"Create it paused instead of active."}],handler:async(ctx)=>{let noRepo=ctx.args.bool("no-repo")===!0,hasRepo=ctx.args.str("repo")!==void 0;if(noRepo&&hasRepo)throw new ApiError("--repo and --no-repo conflict \u2014 pass one","CONFLICTING_FLAGS");if(!noRepo&&!hasRepo)throw new ApiError("pass exactly one of --repo PATH or --no-repo","MISSING_FLAG");let repo=noRepo?void 0:ctx.args.requireRepo("repo"),script=scriptPayload(ctx);if(script.script&&ctx.args.promptText()!==void 0)throw new ApiError("pass --prompt or --script, not both","BAD_FLAG");return simpleRpc(ctx,"automation.create",{...repo?{repo}:{},name:ctx.args.require("name"),...script.script?script:{prompt:requirePromptText(ctx,"routine-create")},schedule:ctx.args.require("schedule"),...ctx.args.bool("notify")?{notify:!0}:{},...ctx.args.bool("webhook")?{webhook:!0}:{},...await createEngineFields(ctx,repo),...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("new-conversation")?{newConversation:!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; --enabled false pauses it (disabling the last active one releases the daemon's keep-alive hold) and --enabled true resumes it.",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). While model/effort stay pinned, a cleared vendor is re-resolved from the repo default and stored."},{...MODEL_FLAG,description:`${MODEL_FLAG.description} '' clears it.`},{...EFFORT_FLAG,description:`${EFFORT_FLAG.description} '' clears it.`},{name:"base-branch",type:"string",placeholder:"B",description:"New base ref ('' to clear)."},...PRECHECK_FLAGS,...SCRIPT_FLAGS,{...NOTIFY_FLAG,placeholder:"BOOL"},{...WEBHOOK_FLAG,placeholder:"BOOL"},GRACE_FLAG,PERSISTENT_FLAG,{...NEW_CONVERSATION_FLAG,placeholder:"BOOL"},...TARGET_FLAGS,{name:"enabled",type:"bool",placeholder:"BOOL",description:"false pauses the routine, true resumes it."}],handler:async(ctx)=>{let id=ctx.args.require("id");return simpleRpc(ctx,"automation.update",{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")}:{},...await updateEngineFields(ctx,id),...ctx.args.present("base-branch")?{baseRef:ctx.args.str("base-branch")??null}:{},...precheckPayload(ctx),...scriptPayload(ctx),...ctx.args.present("notify")?{notify:ctx.args.bool("notify")??!0}:{},...ctx.args.present("webhook")?{webhook:ctx.args.bool("webhook")??!0}:{},...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}:{},...ctx.args.present("new-conversation")?{newConversation:ctx.args.bool("new-conversation")??!0}:{},...ctx.args.present("enabled")?{enabled:ctx.args.bool("enabled")??!0}:{}})}},{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-respond",group:"routine",summary:`Report this run's result. Every delivered routine prompt starts with a [ROVE ROUTINE] line naming its run; this is the routine-flavoured spelling of \`report --delivery <id> --outcome done --summary <text>\` and writes the same delivery report, so \`deliveries\` shows it too. One response per run \u2014 responding again replaces it. Cap ${ROUTINE_RESPONSE_MAX_CHARS} characters; markdown renders on the Routines page.`,flags:[{name:"run",type:"string",required:!0,placeholder:"RUN_ID",description:"Run id from the [ROVE ROUTINE] line."},{name:"text",type:"string",placeholder:"TEXT",description:"The response. Exactly one of --text / --prompt-file."},{...F.promptFile(),description:"Read the response from this file (`-` = stdin) \u2014 use it for anything multi-line or with backticks/$vars."}],handler:async(ctx)=>{let runId=ctx.args.require("run"),inline=ctx.args.str("text"),file=ctx.args.promptText();if(inline!==void 0&&file!==void 0)throw new ApiError("pass --text or --prompt-file, not both","BAD_FLAG");let text=inline??file;if(text===void 0)throw new ApiError("--text (or --prompt-file) is required","MISSING_FLAG");if(text.length>ROUTINE_RESPONSE_MAX_CHARS)throw new ApiError(`response is ${text.length} characters; the cap is ${ROUTINE_RESPONSE_MAX_CHARS}`,"RESPONSE_TOO_LARGE",{hint:"Summarize: lead with the conclusion, link or name the files that hold the detail."});let res=await simpleRpc(ctx,"automation.respond",{runId,text});if(res.run===null)throw new ApiError(`no routine run ${runId}`,"RUN_NOT_FOUND",{hint:"Copy the id from the [ROVE ROUTINE] line of the prompt you were given; `routine-runs --id <routine>` lists run ids."});return res}},{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_blocked (should-run refused the tick: `blocked` is the verdict {reason, detail?, until?, gateIds?} \u2014 busy, awaiting-owner, report-missing, quota, awaiting-permission; not an alarm, the cause is already in the Inbox; a manual run-now bypasses it), skipped_missed, skipped_unavailable, ran / script_failed (a --script routine: exit 0 or not; stdout is the response), dispatch_failed (also a should-run refusal for engine-dead or engine-error, which have no Inbox row of their own: it keeps `blocked` and raises the routine alarm). Each run carries `deliveryId`, `deliveryStatus` (awaiting|reported|missing|quiet: the turn completed with nothing to report) and `response` ({text, at}) once its agent reported (routine-respond or report).",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 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});let requireReport=args.bool("require-report");if(requireReport!==void 0)await daemon.request("task.requireReport",{taskId,required:requireReport});return Boolean(status)||pin!==void 0||requireReport!==void 0}async function deliverArmed(ctx,daemon,taskId,target,text){if(ctx.args.bool("require-report")!==!0&&ctx.args.bool("expect-report")!==!0)return ctx.runtime.deliverPrompt(daemon,target,text);let{deliveryId}=await daemon.request("delivery.arm",{taskId,tabId:"tab-1",promptHead:text}),settle=(delivered)=>daemon.request("delivery.settle",{deliveryId,delivered,tabId:"tab-1"}).catch(()=>{});try{let delivered=await ctx.runtime.deliverPrompt(daemon,target,`${text}
|
|
11
11
|
|
|
12
12
|
${deliveryFooter(deliveryId,roveApiInvocation())}`);return await settle(promptMayHaveLanded(delivered)),{...delivered,deliveryId}}catch(err){throw await settle(!1),err}}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 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,model,tier){return{...choice.command?{command:choice.command}:{},...choice.vendor?{vendor:choice.vendor}:{},...effort?{effort}:{},...model?{model}:{},...tier?{tier}:{}}}async function autoTier(prompt){if(!prompt?.trim())throw new ApiError("--tier auto classifies the first message \u2014 pass --prompt/--prompt-file, or name a tier explicitly","BAD_FLAG",helpStep("add"));let outcome=await classifyTier(prompt,readClassifierConfig());if(outcome.kind==="picked"){let{tier,confidence}=outcome.verdict;return{tier,note:`auto \u2192 ${tier} (confidence ${confidence.toFixed(2)})`}}let detail=outcome.detail?`: ${outcome.detail}`:"";return{note:`auto \u2192 no tier (${outcome.reason}${detail})`}}async function tierFields(ctx,prompt){let requested=ctx.args.str("tier")?.trim();if(!requested)return{};if(requested!=="auto"&&!isAutoRoutingTier(requested))throw new ApiError(`--tier must be one of swift, standard, deep, auto (got ${JSON.stringify(requested)})`,"BAD_FLAG",helpStep("add"));for(let flag of["command","model","effort","agents"])if(ctx.args.str(flag))throw new ApiError(`--${flag} conflicts with --tier, which already fills the engine, model and effort from the auto-routing table \u2014 pass one or the other`,"CONFLICTING_FLAGS",helpStep("add"));let table=readAutoRoutingTable();if(!table){if(requested==="auto")return{note:"auto \u2192 no tier (auto routing is not configured)"};throw new ApiError("auto routing is not configured \u2014 a tier has no engine (autoRouting.<tier>.engine in state.json); set it in Settings \u2192 Auto routing","TIER_UNAVAILABLE",helpStep("add"))}let tier,note2;if(requested==="auto"){let picked=await autoTier(prompt);if(note2=picked.note,!picked.tier)return{note:note2};tier=picked.tier}else tier=requested;let target=table[tier],status=await detectEngineStatus(target.engine),block=tierBlock(target,{engineIds:new Set(await engineListIds()),accountKind:()=>status.account?.kind??null});if(block){if(requested==="auto")return{note:`${note2} \u2014 unusable: ${describeTierBlock(block)}`};throw new ApiError(`tier ${tier} cannot start: ${describeTierBlock(block)}`,"TIER_UNAVAILABLE",{tier,block,hint:"Retarget the tier in Settings \u2192 Auto routing, or pass --command/--model/--effort by hand.",nextCommandArgs:["api","engine-list"]})}let vendor=resolveCommandProtocol(target.engine);try{if(target.model)assertEngineAcceptsModel(vendor,target.model,["api","engine-list"]);if(target.effort)assertEngineAcceptsEffort(vendor,target.effort,["api","engine-list"])}catch(err){if(requested!=="auto")throw err;return{note:`${note2} \u2014 unusable: ${err instanceof Error?err.message:String(err)}`}}return{fields:{choice:{command:target.engine,vendor},effort:target.effort,model:target.model,tier},...note2?{note:note2}:{}}}async function withTierNote(note2,body){if(Object.keys(note2).length===0)return body();try{return await body()}catch(err){if(!(err instanceof ApiError))throw err;throw new ApiError(err.message,err.code,{...err.data,...note2})}}function modelFor(ctx,engines){let model=ctx.args.str("model")?.trim();if(!model)return;for(let engine of new Set(engines))assertEngineAcceptsModel(engine,model,["api","engine-list"]);return model}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}function foreignModelWarnings(engines,model){if(!model)return[];return[...new Set(engines)].filter((engine)=>protocolEntry(engine).foreignModel?.(model)).map((engine)=>`engine ${engine} is unlikely to run model ${JSON.stringify(model)} \u2014 that spelling belongs to another vendor; \`engine-list\` shows ${engine}'s models`)}function launchedEngine(task){return{vendor:task.vendor??null,command:task.command??null,model:task.model??null,effort:task.modelEffort??null}}function parentFlags(ctx){let{args}=ctx,parent=args.str("parent"),noParent=args.bool("no-parent")===!0,noWorktree=args.bool("no-worktree")===!0,isolateIn=args.str("isolate-in"),has=(flag)=>args.str(flag)!==void 0||args.bool(flag)===!0,conflict=(a,b)=>{throw new ApiError(`--${a} and --${b} conflict`,"CONFLICTING_FLAGS",helpStep("add"))};if(parent&&noParent)conflict("parent","no-parent");if(noWorktree&&isolateIn)conflict("no-worktree","isolate-in");for(let[flag,on]of[["no-worktree",noWorktree],["isolate-in",isolateIn!==void 0]]){if(!on)continue;if(noParent)conflict(flag,"no-parent");for(let other of["repo","fork","base-for","workspace"])if(has(other))conflict(flag,other)}if(noWorktree){for(let other of["base-branch","branch","worktree-name","count","agents"])if(has(other))conflict("no-worktree",other)}return{parent,noParent,noWorktree,isolateIn,takesParentRepo:noWorktree||isolateIn!==void 0}}async function resolveAddParent(ctx,daemon,flags,repo){if(flags.parent)return await getParent(daemon,flags.parent);if(flags.noParent)return null;if(!ctx.caller.cli||ctx.caller.forwarded)return requireOrNull(flags);let self=await verifiedSelfSession();if(!self)return requireOrNull(flags);let{tasks}=await daemon.request("task.list",{}).catch(()=>({tasks:[]})),caller=tasks.find((task)=>task.id===resolvePtyOwner(tasks,self.taskId,self.tabId));if(!caller)return requireOrNull(flags);if(flags.takesParentRepo)return caller;let root=tasks.find((task)=>task.id===lineageRootId(tasks,caller.id));if(!root||root.routine||isRemoteRepoKey(root.repo)||repo===void 0)return null;return samePath(await ctx.runtime.resolveRepoRoot(root.repo),repo)?caller:null}function requireOrNull(flags){if(!flags.takesParentRepo)return null;let flag=flags.noWorktree?"--no-worktree":"--isolate-in";throw new ApiError(`${flag} needs a parent and the caller is not a verified rove session \u2014 pass --parent ID`,"MISSING_TARGET",helpStep("add"))}async function getParent(daemon,taskId){try{return(await daemon.request("task.get",{taskId})).task}catch{throw new ApiError(`no task ${taskId} on this machine \u2014 a parent must live beside its child`,"PARENT_NOT_FOUND",{hint:"list the ids with `rove api list`",nextCommandArgs:["api","list"]})}}async function placeAdd(ctx,parent,flags,create){if(!parent)return{kind:"top"};let parentId=parent.id;if(flags.noWorktree)return{kind:"shared",parentId};if(flags.isolateIn)return{kind:"cut",parentId,isolateIn:flags.isolateIn};return!create.fork&&!create.ownWorkspace&&!create.baseRef&&!create.multiRepo&&!isRemoteRepoKey(parent.repo)&&samePath(await ctx.runtime.resolveRepoRoot(parent.repo),create.repo)?{kind:"cut",parentId}:{kind:"nested",parentId}}function placedRequest(placement,create){if(placement.kind==="top")return{method:"task.create",payload:create};if(placement.kind==="nested")return{method:"task.create",payload:{...create,parentTaskId:placement.parentId}};let{repo:_repo,extraRepos:_extra,forkFrom:_fork,...rest}=create,payload={...rest,parentTaskId:placement.parentId};if(placement.kind==="shared")return{method:"task.spawn",payload:{...payload,worktree:!1}};return{method:"task.spawn",payload:{...payload,worktree:!0,lazy:!0,...placement.isolateIn?{isolateIn:placement.isolateIn}:{}}}}async function addParallel(ctx,repo,repoSet,placement,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")??repoSet.primaryBaseRef,picked=await tierFields(ctx,prompt),tier=picked.fields,choice=tier?.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=tier?tier.effort:effortFor(ctx,plan),model=tier?tier.model:modelFor(ctx,plan),warnings=foreignModelWarnings(plan,model),groupId=ulid(),created=[],createFailure=null,dispatcher=args.bool("no-dispatcher")===!0?{}:await dispatcherEnvPayload(daemon);for(let[i,vendor]of plan.entries()){let engine=agentsSpec?{command:vendor,vendor}:{...choice,vendor},payload={repo,groupId,...dispatcher,...enginePayload(engine,effort,model,tier?.tier)};if(title)payload.title=plan.length>1?`${title} #${i+1}/${plan.length}`:title;if(baseRef)payload.baseRef=baseRef;if(repoSet.extraRepos.length>0)payload.extraRepos=repoSet.extraRepos;try{let request=placedRequest(placement,payload),res=await daemon.request(request.method,request.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})=>deliverArmed(ctx,daemon,taskId,{id:taskId,worktreePath:taskCwd(task),kind:task.kind,vendor,command:task.command,modelEffort:task.modelEffort,model:task.model,repo:task.repo,...task.extraRepos?.length?{multiRepo:!0}:{},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,engine:launchedEngine(task),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,engine:launchedEngine(task),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,...picked.note?{tierAuto:picked.note}:{},...warnings.length>0?{warnings}:{}};if(failures.length>0)throw new ApiError(`add delivered ${tasks.length}/${plan.length}`,"PARTIAL_FANOUT",result);return result}var LOCAL_ONLY=["count","agents","fork","workspace","no-worktree","isolate-in","worktree-only","tier"];async function addOnMachine(ctx,alias){let{args}=ctx,daemon=daemonOf(ctx),clash=LOCAL_ONLY.find((flag)=>args.str(flag)!==void 0),repos=args.list("repo");if(clash||repos.length>1)throw new ApiError(`--workspace-on takes one task in one repo on that machine: it conflicts with ${clash?`--${clash}`:"a second --repo"}`,"CONFLICTING_FLAGS",helpStep("add"));let prompt=args.promptText();if(!prompt&&!args.bool("start"))throw new ApiError("add would create a task with no agent: pass --prompt/--prompt-file for work, or --start for an idle engine","EMPTY_SESSION",helpStep("add"));let entry=requireMachine(alias);if(isWindowsMachine(entry))throw new ApiError(`--workspace-on cannot reach "${alias}", a Windows machine: run the engine there with --machine ${alias} --engine-there`,"UNSUPPORTED",helpStep("add"));let title=args.str("title")||(prompt?deriveTitleFromPrompt(prompt):""),pass=(flag)=>{let value=args.str(flag);return value===void 0?{}:{[flag]:value}},cut=await forwardVerb(entry,"add",{repo:repos[0]??"","worktree-only":!0,...title?{title}:{},...pass("branch"),...pass("base-branch"),...pass("clone"),...pass("allow-fork")});if(!cut.ok)throw new ApiError(cut.error.message,cut.error.code,cut.error.data);let there=cut.result,undo=async()=>{await forwardVerb(entry,"delete",{"task-id":there.taskId,wait:!0,force:!0})},dir;try{dir=await createRemoteLink({ws:{machine:alias,taskId:there.taskId,path:there.worktreePath,branch:there.task.branch,...there.task.repoId?{repoId:there.task.repoId}:{}},repo:there.task.repo,sshArgv:machineSshArgs(alias,entry),engineNotes:remoteNotesFiles()})}catch(err){throw await undo(),new ApiError(errorMessage(err),"MACHINE_UNREACHABLE",{machine:alias})}let task;try{let choice=await engineChoice(ctx,dir),engines=choice.vendor?[choice.vendor]:[],effort=effortFor(ctx,engines),model=modelFor(ctx,engines);if(task=(await daemon.request("task.openDir",{dir,remote:!0,...choice.vendor?{vendor:choice.vendor}:{},...title?{title}:{},...model?{model}:{},...effort?{effort}:{}})).task,choice.command)await daemon.request("task.setCommand",{taskId:task.id,command:choice.command})}catch(err){throw removeRemoteLink(dir),await undo(),err}let taskId=task.id;if(args.bool("activate"))await daemon.request("task.setActive",{taskId});await applyPostCreateFlags(daemon,taskId,args);let target={id:taskId,worktreePath:dir,kind:task.kind,vendor:task.vendor,command:task.command,modelEffort:task.modelEffort,model:task.model,repo:task.repo},where={machine:alias,remoteTaskId:there.taskId,remotePath:there.worktreePath,home:homeDir()};if(!prompt){let opened=await ctx.runtime.openTab(daemon,target,"engine");return{taskId,task,engine:launchedEngine(task),...where,started:!0,tabId:opened.tab.id}}let brief=args.bool("no-dispatcher")===!0?prompt:await withPeerProvenance(daemon,taskId,prompt),delivered=await deliverArmed(ctx,daemon,taskId,{...target,newTask:!0},brief);if(!delivered.delivered)throw new ApiError(`task ${taskId} created but the prompt was not delivered`,"NOT_DELIVERED",{taskId,...where});return await persistPrompt(daemon,taskId,prompt),task=(await daemon.request("task.get",{taskId})).task,{taskId,task,engine:launchedEngine(task),...where,started:delivered.started,engineReady:delivered.engineReady,session:delivered.session,delivered:delivered.delivered}}async function localCheckouts(ctx){let{tasks}=await daemonOf(ctx).request("task.list");return[...new Set([...getSavedRepos(),...tasks.map((t)=>t.repo)])].flatMap((path2)=>{let identity=repoIdentity(path2);return identity?[{path:path2,identity}]:[]})}async function resolveLocalRepo(ctx,want,allowFork=!1){let candidates=await localCheckouts(ctx),matches=findCheckouts(want,candidates),id=want.origin??(want.root?`root:${want.root}`:""),picked=pickCheckout(matches,{primary:primaryCheckouts()[id],allowFork,isClean:isCleanCheckout});return{repo:picked.path,...picked.fork?{fork:picked.fork}:{},checkouts:matches.map((m)=>m.path),searched:candidates.length}}var REPO_MATCH_VERB={name:"repo-match",group:"discover",summary:"Find this machine's checkout of a repo by identity: `--root` (its first commit) or `--origin` (normalized remote URL, `host/owner/name`). Several checkouts: the primary (`rove machine primary`) wins, else a clean one. A checkout with the same root but another origin is a fork and only matches with --allow-fork. Searches the saved repos and every task's repo. Returns { repo } (null when none matches), { fork } (a fork that was skipped), { checkouts } and { searched }.",flags:[{name:"origin",type:"string",placeholder:"URL",description:"Remote URL; any git form, compared normalized."},{name:"root",type:"string",placeholder:"SHA",description:"The repo's root commit."},{name:"allow-fork",type:"bool",description:"Accept a fork (same root commit, other origin)."}],handler:async(ctx)=>{let origin=ctx.args.str("origin"),root=ctx.args.str("root");if(!origin&&!root)throw new ApiError("pass --origin or --root","BAD_FLAG");return resolveLocalRepo(ctx,{...origin?{origin:normalizeRemoteUrl(origin)}:{},...root?{root}:{}},ctx.args.bool("allow-fork")===!0)}},REPO_LIST_VERB={name:"repo-list",group:"discover",summary:"This machine's repos by id (`host/owner/name`, or `root:<sha>` with no origin): each with its checkouts and which one is primary. Read from the saved repos and every task's repo. Returns { repos: [{ id, primary, checkouts }] }.",flags:[],handler:async(ctx)=>{let primaries=primaryCheckouts(),byId=new Map;for(let c of await localCheckouts(ctx)){let id=repoIdOf(c.identity);if(!id)continue;byId.set(id,[...byId.get(id)??[],c.path])}return{repos:[...byId].map(([id,checkouts])=>({id,primary:primaries[id]??null,checkouts})).sort((a,b)=>a.id.localeCompare(b.id))}}};async function resolveRepoFlag(ctx,raw){let ref=parseRepoRef(raw,ctx.caller.cwd??process.cwd());if(ref.kind==="path")return ctx.args.repoPath("repo",raw);let found=await resolveLocalRepo(ctx,{origin:ref.id});if(found.repo)return found.repo;if(ctx.args.bool("clone")!==!0)throw new ApiError(`no checkout of ${ref.id} on this machine`,"NO_LOCAL_CHECKOUT",{hint:`pass --clone to clone it into ${cloneDirFor(ref.id)}, or --repo with a checkout's path`});try{let dir=await cloneRepo(ref);return addSavedRepo(dir),dir}catch(err){throw new ApiError(`could not clone ${ref.cloneUrl}: ${errorMessage(err)}`,"CLONE_FAILED",{hint:isDiskFull(err)?"the disk is full: free some space, then run the same command again":"check this machine can fetch it (`git ls-remote <url>`), or clone it yourself and pass its path"})}}async function resolveRepoSet(ctx,primary,extraRefs){let{args,runtime}=ctx,baseFor=args.list("base-for");if(extraRefs.length===0){if(baseFor.length>0)throw new ApiError("--base-for names a repo of a multi-repo task \u2014 pass --repo more than once","BAD_FLAG",helpStep("add"));return{extraRepos:[]}}if(1+extraRefs.length>MULTI_REPO_CAP)throw new ApiError(`${1+extraRefs.length} repos exceed the cap of ${MULTI_REPO_CAP} per task (the first --repo is the primary)`,"TOO_MANY_REPOS",helpStep("add"));if(isRemoteRepoKey(primary))throw new ApiError(`--repo ${primary} is a remote project; a multi-repo task must keep every repo local`,"REMOTE_EXTRA_UNSUPPORTED");let names=new Set([repoNameOf(primary)]),repos=[{name:repoNameOf(primary),repo:primary}];for(let raw of extraRefs){let requested=await resolveRepoFlag(ctx,raw);if(isRemoteRepoKey(requested))throw new ApiError(`--repo ${raw} is a remote project; a multi-repo task must keep every repo local`,"REMOTE_EXTRA_UNSUPPORTED",helpStep("add"));let root=await runtime.resolveRepoRoot(requested);if(!await runtime.isUsableRepo(root))throw new ApiError(`--repo ${raw} is not a git repository \u2014 every repo of a task needs one to cut its worktree and branch from`,"NOT_A_GIT_REPO",helpStep("add"));if(repos.some((r)=>samePath(r.repo,root)))throw new ApiError(`--repo ${raw} resolves to ${root}, already part of this task`,"REPO_DUPLICATE",helpStep("add"));let name=uniqueRepoName(repoNameOf(root),names);names.add(name),repos.push({name,repo:root})}let baseRefs=new Map;for(let spec of baseFor){let eq=spec.indexOf("="),key=spec.slice(0,eq),ref=spec.slice(eq+1);if(eq<=0||!ref)throw new ApiError(`--base-for ${JSON.stringify(spec)} must be REPO=REF`,"BAD_FLAG",helpStep("add"));let keyRoot=key.includes("/")?await runtime.resolveRepoRoot(args.repoPath("base-for",key)):void 0,target;for(let r of repos)if(r.name===key||keyRoot!==void 0&&samePath(await runtime.resolveRepoRoot(r.repo),keyRoot)){target=r;break}if(!target)throw new ApiError(`--base-for ${key}: no such repo in this task (repos: ${repos.map((r)=>r.name).join(", ")})`,"BAD_FLAG",helpStep("add"));if(baseRefs.has(target.name))throw new ApiError(`--base-for ${key} given twice`,"BAD_FLAG",helpStep("add"));baseRefs.set(target.name,ref)}let primaryBaseRef=baseRefs.get(repos[0]?.name??""),explicit=args.str("base-branch");if(primaryBaseRef&&explicit&&primaryBaseRef!==explicit)throw new ApiError(`--base-branch ${explicit} and --base-for ${repos[0]?.name}=${primaryBaseRef} both set the primary's base \u2014 pass one`,"BAD_FLAG",helpStep("add"));return{extraRepos:repos.slice(1).map((r)=>{let baseRef=baseRefs.get(r.name);return{repo:r.repo,...baseRef?{baseRef}:{}}}),...primaryBaseRef?{primaryBaseRef}:{}}}async function spawnSharedChild(daemon,parentTaskId,command,title){let vendor=command?resolveCommandProtocol(command):void 0;return(await daemon.request("task.spawn",{parentTaskId,worktree:!1,...title?{title}:{},...command?{command}:{},...vendor?{vendor}:{},...await dispatcherEnvPayload(daemon)})).task}var FIRST_CONVERSATION_LOCK_MS=120000;function withFirstConversationLock(taskId,fn){return withDeliveryLock(`${taskId}::new-conversation`,fn,{timeoutMs:FIRST_CONVERSATION_LOCK_MS})}async function engineStarted(daemon,runtime,task){if(task.ptyAlias)return!0;let engines=((await readDaemonTabs(daemon,task.id))?.tabs??[]).filter((tab)=>tab.kind==="engine");if(engines.length===0)return!1;if(engines.some((tab)=>tab.spawned))return!0;let{tabs:rows}=await runtime.taskTabs(task.id,taskEngineArgv(task),await ptyScopeOf(daemon,task));return rows.find((row)=>row.id===engines[0]?.id)?.alive===!0}async function ownConversation(daemon,runtime,task,command,title){if(await engineStarted(daemon,runtime,task))return null;if(command&&command!==task.command){let vendor=resolveCommandProtocol(command);await daemon.request("task.setCommand",{taskId:task.id,command,...vendor?{vendor}:{}})}if(title&&task.title===PLACEHOLDER_TASK_TITLE)await daemon.request("task.rename",{taskId:task.id,title}).catch(()=>{return});return(await daemon.request("task.get",{taskId:task.id})).task}async function conversationHome(daemon,runtime,task,command){let own=await ownConversation(daemon,runtime,task,command,"");return own?{task:own,child:!1}:{task:await spawnSharedChild(daemon,task.id,command),child:!0}}var ENGINE_REFUSALS={ENGINE_LIMIT:!0,ENGINE_ADMISSION_BUSY:!0,ENGINE_ADMISSION_UNAVAILABLE:!0};async function failSharedChild(daemon,err,childTaskId,retryArgs){if(!(err instanceof ApiError))throw err;if(ENGINE_REFUSALS[err.code])throw await daemon.request("task.delete",{taskId:childTaskId}).catch(()=>{return}),new ApiError(err.message,err.code,{...err.data,nextCommandArgs:retryArgs});throw new ApiError(err.message,err.code,{...err.data,childTaskId})}async function add(ctx){let{args,runtime}=ctx,workspaceOn=args.str("workspace-on");if(workspaceOn)return addOnMachine(ctx,workspaceOn);let daemon=daemonOf(ctx),flags=parentFlags(ctx),handoffFrom=args.str("handoff-from");if(handoffFrom&&!flags.noWorktree)throw new ApiError("--handoff-from continues the parent's conversation in the parent's directory; pass --no-worktree with it","BAD_FLAG",helpStep("add"));let refs=args.list("repo"),fork=await resolveFork(ctx),inherited=flags.takesParentRepo?await resolveAddParent(ctx,daemon,flags,void 0):null,requestedRepo=inherited?inherited.repo:fork?fork.repo:await resolveRepoFlag(ctx,refs[0]??""),repo=inherited?inherited.repo:await runtime.resolveRepoRoot(requestedRepo);if(!inherited&&!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;if(args.bool("start")&&(parallel||args.promptText()||handoffFrom))throw new ApiError("--start boots one idle engine without a first message: it conflicts with --prompt/--prompt-file and --handoff-from (which already start the engine) and with --count/--agents","CONFLICTING_FLAGS",helpStep("add"));let worktreeOnly=args.bool("worktree-only")===!0;if(worktreeOnly&&(parallel||args.promptText()||args.bool("start")||args.bool("no-worktree")))throw new ApiError("--worktree-only cuts a checkout and starts no engine: it conflicts with --prompt/--prompt-file, --start, --count/--agents and --no-worktree","CONFLICTING_FLAGS",helpStep("add"));if(!parallel&&!args.promptText()&&!args.bool("start")&&!worktreeOnly&&!handoffFrom)throw new ApiError("add would create a task with no agent: pass --prompt/--prompt-file for work, --start for an idle engine to type into, or --worktree-only for a checkout that is not a session","EMPTY_SESSION",helpStep("add"));let 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,repoSet=inherited?{extraRepos:[]}:await resolveRepoSet(ctx,repo,refs.slice(1)),workspace=args.str("workspace");if(workspace&&(parallel||fork||repoSet.extraRepos.length>0))throw new ApiError("--workspace takes one task in one repo: it conflicts with --fork, --count, --agents, --no-worktree, --isolate-in and extra repos","CONFLICTING_FLAGS",helpStep("add"));let parent=inherited??await resolveAddParent(ctx,daemon,flags,repo),placement=await placeAdd(ctx,parent,flags,{repo,fork:fork!==void 0,baseRef:args.str("base-branch")??repoSet.primaryBaseRef,multiRepo:repoSet.extraRepos.length>0,ownWorkspace:workspace!==void 0}),result=await(placement.kind==="shared"?withFirstConversationLock(placement.parentId,()=>addOne(ctx,repo,repoSet,placement,parent)):parallel?addParallel(ctx,repo,repoSet,placement,count,agentsSpec):addOne(ctx,repo,repoSet,placement,parent));return resolvedFrom&&result&&typeof result==="object"?{...result,...resolvedFrom}:result}var FORK_EXCLUSIVE=["repo","base-branch","base-for","count","agents"];async function resolveFork(ctx){let taskId=ctx.args.str("fork");if(!taskId)return;let clash=FORK_EXCLUSIVE.find((flag)=>ctx.args.str(flag)!==void 0);if(clash)throw new ApiError(`--fork and --${clash} conflict \u2014 a fork is a sibling in the parent's repo, starting at the parent's HEAD`,"CONFLICTING_FLAGS",helpStep("add"));let{task}=await daemonOf(ctx).request("task.get",{taskId});return{taskId,repo:task.repo}}async function typedEngineFields(ctx,repo){let choice=await engineChoice(ctx,repo),engines=choice.vendor?[choice.vendor]:[];return{choice,effort:effortFor(ctx,engines),model:modelFor(ctx,engines)}}function deliveryTarget(task,newTask=!1){return{id:task.id,worktreePath:taskCwd(task),kind:task.kind,vendor:task.vendor,command:task.command,modelEffort:task.modelEffort,model:task.model,repo:task.repo,...task.extraRepos?.length||task.sharesWorkspaceOf?{multiRepo:!0}:{},...newTask?{newTask:!0}:{}}}var CREATE_ONLY_ENGINE_FLAGS=["effort","model","tier"];async function parentOwnConversation(ctx,placement,parent,title){if(placement.kind!=="shared"||!parent)return null;let own=await ownConversation(daemonOf(ctx),ctx.runtime,parent,ctx.args.str("command"),title);if(!own)return null;let clash=CREATE_ONLY_ENGINE_FLAGS.find((flag)=>ctx.args.str(flag)!==void 0);if(clash)throw new ApiError(`task ${parent.id} has no conversation yet, so this one runs in the task itself and --${clash} cannot be set here \u2014 set it with \`update\` first`,"CONFLICTING_FLAGS",helpStep("add"));return own}async function addOne(ctx,repo,repoSet,placement,parent){let daemon=daemonOf(ctx),{args}=ctx,handoffFrom=args.str("handoff-from"),typed=args.promptText(),prompt=handoffFrom&&parent?[await handoffBrief(ctx,parent,handoffFrom,"add"),typed].filter(Boolean).join(`
|
|
13
13
|
|
|
@@ -15,10 +15,10 @@ ${deliveryFooter(deliveryId,roveApiInvocation())}`);return await settle(promptMa
|
|
|
15
15
|
`).some((line)=>/auth git-credential/.test(line))}function parseSshProbe(result){if(result.missing)return{ok:!1,detail:"ssh is not installed"};if(result.timedOut)return{ok:!1,detail:"timed out"};let text=`${result.stderr}
|
|
16
16
|
${result.stdout}`,hi=/Hi ([A-Za-z0-9-]+)! You've successfully authenticated/.exec(text);if(hi?.[1])return{ok:!0,user:hi[1]};let lines=text.split(`
|
|
17
17
|
`).map((l)=>l.replace(/^git@github\.com: /,"").trim()).filter(Boolean);return{ok:!1,detail:(lines.find((l)=>/Permission denied|Host key verification failed|Could not resolve|Connection /.test(l))??lines[lines.length-1]??"ssh failed").slice(0,160)}}async function githubStatus(deps){let run=deps.run??runTool,[git,gh,helpers,ssh]=await Promise.all([run("git",["--version"],{timeoutMs:VERSION_MS}),run("gh",["--version"],{timeoutMs:VERSION_MS,env:GH_ENV}),run("git",["config","--get-regexp","^credential\\.(https://github\\.com\\.)?helper$"],{timeoutMs:VERSION_MS}),run("ssh",["-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=5",`git@${GITHUB_HOST}`],{timeoutMs:PROBE_MS})]),ghVersion=parseVersion("gh",gh),auth=ghVersion?await ghAccount(run):{account:null,protocol:null,scopes:[],detail:"gh is not installed"};return{git:parseVersion("git",git),gh:ghVersion,account:auth.account,...auth.account===null&&auth.detail&&ghVersion?{authDetail:auth.detail}:{},host:GITHUB_HOST,protocol:auth.protocol,scopes:auth.scopes,gitUsesGh:parseGitUsesGh(helpers.stdout),ssh:parseSshProbe(ssh),login:deps.login()}}var GH_MS=15000,TOKEN_SHAPE=/^[A-Za-z0-9_]{20,255}$/;async function setupGit(run){await run("gh",["auth","setup-git","--hostname",GITHUB_HOST],{timeoutMs:GH_MS,env:GH_ENV})}async function finishLogin(syncOthers,run=runTool){if(await setupGit(run),!syncOthers)return;let token=await readHubToken(run).catch(()=>null);if(!token)return;await autoSyncSignedOut(token)}var deviceLogin=new DeviceLogin({spawn:spawnGhLogin,finish:(syncOthers)=>finishLogin(syncOthers)}),localStatus=(run)=>githubStatus({...run?{run}:{},login:()=>deviceLogin.state()});async function readHubToken(run=runTool){let res=await run("gh",["auth","token","--hostname",GITHUB_HOST],{timeoutMs:GH_MS,env:GH_ENV}),token=res.stdout.trim();if(res.missing)throw new ApiError("gh is not installed on this machine","GITHUB_GH_MISSING");if(res.code!==0||!token)throw new ApiError("this machine is not signed in to GitHub","GITHUB_SIGNED_OUT",{hint:"connect GitHub here first (`rove api github-login`)"});return token}var scrub=(text,token)=>text.split(token).join("***").trim().slice(0,300);async function applyToken(token,run=runTool){if(!TOKEN_SHAPE.test(token))throw new ApiError("the token is not a GitHub token","BAD_FLAG");let res=await run("gh",["auth","login","--with-token","--hostname",GITHUB_HOST],{timeoutMs:GH_MS,env:GH_ENV,input:`${token}
|
|
18
|
-
`});if(res.missing)throw new ApiError("gh is not installed on this machine","GITHUB_GH_MISSING");if(res.code!==0)throw new ApiError(`gh refused the token: ${scrub(res.stderr||res.stdout,token)||"no output"}`,"GITHUB_LOGIN_FAILED");return await setupGit(run),localStatus(run)}async function logoutGithub(run=runTool){let before=await localStatus(run);if(!before.account)throw new ApiError("this machine is not signed in to GitHub","GITHUB_SIGNED_OUT");let res=await run("gh",["auth","logout","--hostname",GITHUB_HOST,"--user",before.account],{timeoutMs:GH_MS,env:GH_ENV});if(res.code!==0)throw new ApiError(`gh could not sign out: ${(res.stderr||res.stdout).trim().slice(0,300)}`,"GITHUB_LOGOUT_FAILED");return localStatus(run)}function unwrap(envelope){if(envelope.ok)return envelope.result;let{message,code,...data}=envelope.error;throw new ApiError(message,code,data)}async function syncTo(alias,token,forward=forwardVerb){let envelope=await forward(requireMachine(alias),"github-apply",{token});return unwrap(envelope)}async function autoSyncSignedOut(token,forward=forwardVerb,machines=dedupeMachines(listMachines())){let synced=[];return await Promise.allSettled(machines.map(async(entry)=>{let status=unwrap(await forward(entry,"github-status",{}));if(!status.gh||status.account||status.authDetail)return;unwrap(await forward(entry,"github-apply",{token})),synced.push(entry.alias)})),synced}async function inDaemon(ctx,verb,params,here){if(ctx.caller.daemon)return here();let envelope=await daemonOf(ctx).request("api.invoke",{verb,params});if(envelope.ok)return envelope.result;let{message,code,...data}=envelope.error;throw new ApiError(message,code,data)}var GITHUB_VERBS=[{name:"github-status",group:"read",summary:"Can THIS machine use GitHub? Returns { git, gh (versions or null), account (the signed-in `gh` login or null), host, protocol, scopes, gitUsesGh (git pushes through gh), ssh: { ok, user?, detail? }, login: { state: pending|syncing|failed, code?, url?, error? } | null }. Missing tools are values, never errors. Add --machine <alias> for another machine.",flags:[],handler:(ctx)=>inDaemon(ctx,"github-status",{},()=>localStatus())},{name:"github-login",group:"edit",summary:"Sign THIS machine's `gh` in to GitHub with the device flow: returns { state, code, url } \u2014 type the code at the URL; poll `github-status` (.login) until `.account` is set. One flow per machine: a second call returns the pending one. --cancel stops it. When it finishes, `git` is set up to use it and the other machines that are signed out receive the same account (never one already signed in as someone else).",flags:[{name:"cancel",type:"bool",description:"Stop the pending flow (or dismiss its failure) instead of starting one."}],handler:(ctx)=>{let cancel=ctx.args.bool("cancel")===!0;return inDaemon(ctx,"github-login",cancel?{cancel}:{},async()=>cancel?{cancelled:deviceLogin.cancel()}:deviceLogin.start(ctx.caller.forwarded!==!0))}},{name:"github-logout",group:"edit",summary:"Sign THIS machine's `gh` out of github.com (`gh auth logout` for the active account). Returns the new github-status. Signs the machine out for every tool that uses gh, not only Rove.",flags:[],handler:(ctx)=>inDaemon(ctx,"github-logout",{},()=>logoutGithub())},{name:"github-sync",group:"edit",summary:"Give a registered machine THIS machine's GitHub account: reads this machine's `gh` token in the daemon and signs the target's `gh` in with it (the token is never printed or stored). Returns the target's github-status. Takes --to, not --machine, because the verb itself runs here. Refused when another machine's hub sends it.",flags:[{name:"to",type:"string",required:!0,placeholder:"ALIAS",description:"The registered machine to sign in."}],handler:(ctx)=>{if(ctx.caller.forwarded)throw new ApiError("github-sync only runs on the machine whose account is shared","GITHUB_SYNC_FORWARDED");let to=ctx.args.require("to");return inDaemon(ctx,"github-sync",{to},async()=>syncTo(to,await readHubToken()))}},{name:"github-apply",group:"edit",summary:"INTERNAL \u2014 sent by another machine's `github-sync`, not for direct use. Signs this machine's `gh` in with --token (piped to gh over stdin) and returns the new github-status. Refused unless another machine's hub forwarded it.",flags:[{name:"token",type:"string",required:!0,placeholder:"TOKEN",description:"A GitHub token for `gh auth login --with-token`."}],handler:async(ctx)=>{if(!ctx.caller.forwarded)throw new ApiError("github-apply only accepts a call forwarded from another machine","GITHUB_APPLY_FORWARDED_ONLY",{hint:"use `rove api github-sync --to <alias>` on the machine whose account you want to share"});return applyToken(ctx.args.require("token"))}}];async function issueList(ctx){let repoRoot=ctx.args.requireRepo("repo"),statuses=csvOf(ctx,"status",ISSUE_STATUSES,"issue-list"),needle=ctx.args.str("search")?.trim().toLowerCase();if(!statuses&&!needle)return simpleRpc(ctx,"issue.list",{repoRoot});let state=await daemonOf(ctx).request("issue.list",{repoRoot}),issues=state.issues.filter((i)=>(!statuses||statuses.has(i.status))&&(!needle||i.title.toLowerCase().includes(needle)||i.body.toLowerCase().includes(needle)));return{...state,issues}}var ISSUE_VERBS=[{name:"issue-list",group:"issues",summary:"List daemon-owned issues for a repo. --status and --search AND together; `nextId` and `skipped` still describe the whole board.",flags:[F.repo(),{name:"status",type:"csv",placeholder:"S1,S2",description:`Only issues in these statuses (${ISSUE_STATUSES.join(", ")}).`},{name:"search",type:"string",placeholder:"Q",description:"Only issues whose title or body contains Q (case-insensitive)."}],handler:issueList},{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-update",group:"issues",summary:"Update a daemon-owned issue's title, body, linked task, and/or status. Title, body and link land in one all-or-nothing write; the status follows as its own change.",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."},{name:"status",type:"enum",values:ISSUE_STATUSES,description:"New issue status."}],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-update --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"}async function remoteGit(repo,args){let out=await runAsync("git",args,{cwd:repo,env:readOnlyGitProcessEnv(),timeoutMs:REMOTE_TIMEOUT_MS});return{ok:out.ok,stdout:out.stdout.trim(),stderr:out.stderr.trim()||(out.error?`git ${args[0]} did not finish`:"")}}async function deleteRemoteBranch(repo,branch){let name=remoteFor(repo,branch),push=await remoteGit(repo,["push",name,"--delete",branch]);if(push.ok)return{name,deleted:!0};let remaining=await remoteGit(repo,["ls-remote","--heads",name,branch]);if(remaining.ok&&remaining.stdout.length===0)return{name,deleted:!0};return{name,deleted:!1,error:push.stderr||"git push exited non-zero"}}async function reportBranchDeletion(repo,branch,opts){if(!branch||!opts.deleteBranch&&!opts.deleteRemote)return;if(opts.heldBy!==void 0){let keptReason2=`task "${opts.heldBy}" still uses this branch`;return{branch,deleted:!1,keptReason:keptReason2,...opts.deleteRemote?{remote:{name:remoteFor(repo,branch),deleted:!1,error:`skipped: ${keptReason2}`}}:{}}}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:await 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 ownSession(daemon);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,cascade=ctx.args.bool("cascade")??!1,subject=deleteBranch||deleteRemote?(await daemon.request("task.get",{taskId})).task:void 0,res;try{res=await daemon.request("task.delete",{taskId,force,deleteBranch,...cascade?{cascade}:{},...self?{requestedByTaskId:self.taskId,requestedByTabId:self.tabId}:{}})}catch(err){throw deleteRecoveryError(err,taskId)}let removing=res.deleted??[taskId];for(let id of removing)await ctx.runtime.tearDownSession(id,res.teardown?.[id]);if(!res.queued)return{...res,status:"not_found"};if(!ctx.args.bool("wait")&&!subject)return{...res,status:"queued"};let outcomes=[];for(let id of removing)outcomes.push(await awaitDeletion(daemon,id));let outcome=outcomes.find((o)=>o.status==="failed")??outcomes.find((o)=>o.status==="pending")??outcomes[0];if(!outcome)return{...res,status:"removed"};let branch=subject&&outcome.status==="removed"?await reportBranchDeletion(gitRepoOf(subject),subject.branch??"",{deleteBranch,force,deleteRemote,heldBy:await branchHolder(daemon,subject,removing)}):void 0;return{...res,...outcome,...branch?{branch}:{}}}async function branchHolder(daemon,subject,gone){let{tasks}=await daemon.request("task.list");return tasks.find((t)=>!gone.includes(t.id)&&(subject.worktreePath&&t.worktreePath&&samePath(t.worktreePath,subject.worktreePath)||subject.branch&&t.branch===subject.branch&&gitRepoOf(t)===gitRepoOf(subject)&&workspaceCapabilities(t).ownsBranch))?.title}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((resolve3)=>setTimeout(resolve3,DELETE_POLL_INTERVAL_MS))}}async function setArchived(ctx,archived){let taskId=ctx.args.require("task-id"),res=await daemonOf(ctx).request("task.archive",{taskId,archived,force:archived&&(ctx.args.bool("force")??!1)});return{taskId,archived,ids:res.archived}}var archiveTask=(ctx)=>setArchived(ctx,!0),unarchiveTask=(ctx)=>setArchived(ctx,!1);async function land(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),repo=ctx.args.str("repo");if(ctx.args.bool("dry-run")===!0)return(await daemon.request("task.landPreflight",{taskId,...repo?{repo}:{}})).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"),...ctx.caller.cwd!==void 0?{callerCwd:ctx.caller.cwd}:{},...repo?{repo}:{}})}catch(err){throw landStoppedError(err,taskId)??landRecoveryError(err,taskId)}return{ok:!0,taskId,...res.result}}function landStoppedError(err,taskId){let data=err instanceof Error&&err.name==="LandStoppedError"?err.data:void 0;if(!data?.stopped)return null;let head=landRecoveryError(err,taskId),recovery=head instanceof ApiError?head.data:void 0,message=errorMessage(err);return new ApiError(splitDaemonCode(message)?.rest??message,data.stopped.code,{taskId,failedRepo:data.stopped.repo,repos:data.repos,hint:`repos that already landed stay landed \u2014 fix ${data.stopped.repo}, then run \`land\` again: it resumes with the repos still pending`,...recovery})}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"]})}function removableWorktree(ctx,task){let worktreePath=(task.worktreePath??"").trim();if(!worktreePath)throw new ApiError(`task ${task.id} has no worktree on disk`,"NO_WORKTREE",{hint:"nothing to remove \u2014 `ensure-worktree` materialises one"});let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(gitRepoOf(task))))throw new ApiError(`refusing to remove ${worktreePath} \u2014 it is the project's own checkout, not a Rove worktree`,"BASE_CHECKOUT");if(ctx.caller.cwd!==void 0&&pathWithin(wt,canonicalize(ctx.caller.cwd))!==null)throw new ApiError(`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`,"CALLER_WORKTREE");return worktreePath}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=removableWorktree(ctx,task),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)}async function sync(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),repo=ctx.args.str("repo"),res=await daemon.request("task.syncBase",{taskId,...repo?{repo}:{}}),failed=res.result.repos?.find((r)=>!r.ok);if(failed)throw new ApiError(splitDaemonCode(failed.error??"")?.rest??failed.error??"sync failed",failed.code??"SYNC_FAILED",{taskId,failedRepo:failed.name,repos:res.result.repos,hint:"the other repos synced; a conflicted merge is left in place in its worktree \u2014 resolve and commit it there"});return{ok:!0,taskId,...res.result}}var LIFECYCLE_VERBS=[{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 }. A MULTI-REPO task (`add --repo A --repo B`) lands every repo into its own base, in picked order: every repo is probed first and nothing is merged if any refuses; the run stops at the first conflict, leaving earlier repos landed; re-run `land` to resume (a repo already merged reads as `skipped`). Worktrees are removed only once every repo has landed. Its result adds `.repos[]` ({ name, status: landed|skipped|conflict|refused|failed|pending, landedOn, ahead, commit, error?, code? }); a stop is the usual error (LAND_CONFLICT, MAIN_CHECKOUT_DIRTY, \u2026) carrying `.repos[]` and `.failedRepo`.",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."},{name:"repo",type:"string",placeholder:"NAME",description:"Multi-repo task: land (or, with --dry-run, probe) only this repo, named as in `.task.extraRepos[].name` (the primary's name is its directory name). UNKNOWN_REPO otherwise."}],handler:land},{name:"sync",group:"lifecycle",summary:"Merge the base branch INTO a task's worktree (the inverse of `land`; the sidebar's \u2193N drift). Refuses a dirty worktree (SYNC_WORKTREE_DIRTY \u2014 commit first, never stash); a conflict is left IN PLACE in the worktree for you to resolve (SYNC_CONFLICT lists the files). Returns { baseRef, alreadyCurrent }. A multi-repo task syncs EVERY repo against its own base and carries `.repos[]` ({ name, ok, baseRef?, alreadyCurrent?, error?, code? }); one repo's conflict does not stop the others, and is raised as the error after all ran.",flags:[F.taskId(),{name:"repo",type:"string",placeholder:"NAME",description:"Multi-repo task: sync only this repo (`.task.extraRepos[].name`; UNKNOWN_REPO otherwise)."}],handler:sync},{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. CHILDREN (tasks nested under it by `add`): by default the task's children are promoted \u2014 they keep running, re-parented to the deleted task's own parent (or top level); --cascade deletes the whole subtree instead, each worktree still passing the dirty gate before ANY of it is queued. A directory more than one task runs in (an owner and its shared children) is removed only with its last task; deleting a shared child never touches the directory, and an owner leaving hands the directory to a remaining child.",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:"cascade",type:"bool",description:"Also delete every descendant of the task (its child tasks, recursively). Default: children are promoted instead. The reply lists the ids as `deleted`."},{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},{name:"archive",group:"lifecycle",summary:"Hide a task from the sidebar and the default `list`, without touching anything else: the worktree, branch, transcript and any running session stay exactly as they are, and `send`, `read-output`, `get-task` and `delete` keep working on it by id. Applies to the task and every descendant (its child tasks, recursively) together. Refused with TASK_BUSY while an engine in the subtree is running or waiting on you \u2014 pass --force to hide it anyway; archive never stops a session. A project's `main` checkout cannot be archived. Undo with `unarchive`; `list --archived` finds archived tasks. Returns { taskId, archived, ids } \u2014 `ids` is every task hidden.",flags:[F.taskId(),{name:"force",type:"bool",description:"Archive even though an engine in the subtree is running or waiting on you. Nothing is stopped."}],handler:archiveTask},{name:"unarchive",group:"lifecycle",summary:"Bring an archived task back into the sidebar and `list`, together with its archived descendants. A child unarchived on its own while its parent is still archived shows as a top-level row until the parent returns. Returns { taskId, archived: false, ids }.",flags:[F.taskId()],handler:unarchiveTask}];var ACCEPTED="a PR URL (https://github.com/OWNER/REPO/pull/N) or a PR number of the repo in the current directory";async function urlForNumber(n){let res=await runAsync("gh",["pr","view",n,"--json","url","-q",".url"],{timeoutMs:30000});return res.ok?canonicalPrUrl(res.stdout.trim()):void 0}async function attachSessionPr(ctx,taskId,url){return simpleRpc(ctx,"task.addSessionPr",{taskId,url})}var PR_ATTACH_VERB={name:"pr-attach",group:"edit",summary:"Show a pull request on a task's row, with its live state. Run it once after opening a PR from ANY directory (a worktree Rove does not track); `publish` already does it for the PRs it opens. Idempotent: attaching the same PR again changes nothing. Without --task-id it targets your own task. Returns { taskId, url }.",flags:[{name:"url",type:"string",required:!0,placeholder:"URL|N",description:`The pull request: ${ACCEPTED}.`},{name:"task-id",type:"string",placeholder:"ID",description:"The task to attach to. Default: the task this session runs in."}],handler:async(ctx)=>{let raw=ctx.args.require("url").trim(),url=/^\d+$/.test(raw)?await urlForNumber(raw):canonicalPrUrl(raw);if(!url)throw new ApiError(`--url ${raw} is not ${ACCEPTED}`,"BAD_FLAG",{hint:"pass the URL `gh pr create` printed"});return attachSessionPr(ctx,await resolveTarget(ctx,"pr-attach"),url)}};async function published(ctx,taskId,branch,url){let attached=await attachSessionPr(ctx,taskId,url).then(()=>({}),(err)=>({attachError:errorMessage(err)}));return{branch,pushed:!0,pr:{url},...attached}}async function run(cwd,cmd,args){let res=await runAsync(cmd,args,{cwd,timeoutMs:120000});return{ok:res.ok,out:res.error??`${res.stdout}${res.stderr}`.trim()}}var PUBLISH_VERB={name:"publish",group:"lifecycle",summary:"Push a task's branch to its remote (`origin` unless --remote) and open its pull request with `gh`, or return the one already open. What `land` does for a task on another machine. Returns { branch, pushed, pr: { url } | null, prError? } \u2014 `prError` says why no PR (gh missing or not signed in, a non-GitHub remote, no commits ahead); the push still happened. Refuses a task with no worktree or no branch.",flags:[F.taskId(),{name:"remote",type:"string",placeholder:"NAME",description:"Remote to push to. Default: origin."}],handler:async(ctx)=>{let taskId=ctx.args.require("task-id"),{task}=await daemonOf(ctx).request("task.get",{taskId});if(!task.worktreePath||!task.branch)throw new ApiError(`task ${taskId} has no worktree or branch to publish`,"NO_WORKTREE",{nextCommandArgs:["api","ensure-worktree","--task-id",taskId]});let cwd=task.worktreePath,remote=ctx.args.str("remote")??"origin",push=await run(cwd,"git",["push","-u",remote,task.branch]);if(!push.ok)throw new ApiError(`git push to ${remote} failed: ${push.out}`,"PUSH_FAILED");let existing=await run(cwd,"gh",["pr","view",task.branch,"--json","url","-q",".url"]);if(existing.ok&&existing.out.startsWith("http"))return published(ctx,taskId,task.branch,existing.out);let base=task.baseRef?["--base",String(task.baseRef)]:[],created=await run(cwd,"gh",["pr","create","--fill","--head",task.branch,...base]),url=created.out.split(`
|
|
18
|
+
`});if(res.missing)throw new ApiError("gh is not installed on this machine","GITHUB_GH_MISSING");if(res.code!==0)throw new ApiError(`gh refused the token: ${scrub(res.stderr||res.stdout,token)||"no output"}`,"GITHUB_LOGIN_FAILED");return await setupGit(run),localStatus(run)}async function logoutGithub(run=runTool){let before=await localStatus(run);if(!before.account)throw new ApiError("this machine is not signed in to GitHub","GITHUB_SIGNED_OUT");let res=await run("gh",["auth","logout","--hostname",GITHUB_HOST,"--user",before.account],{timeoutMs:GH_MS,env:GH_ENV});if(res.code!==0)throw new ApiError(`gh could not sign out: ${(res.stderr||res.stdout).trim().slice(0,300)}`,"GITHUB_LOGOUT_FAILED");return localStatus(run)}function unwrap(envelope){if(envelope.ok)return envelope.result;let{message,code,...data}=envelope.error;throw new ApiError(message,code,data)}async function syncTo(alias,token,forward=forwardVerb){let envelope=await forward(requireMachine(alias),"github-apply",{token});return unwrap(envelope)}async function autoSyncSignedOut(token,forward=forwardVerb,machines=dedupeMachines(listMachines())){let synced=[];return await Promise.allSettled(machines.map(async(entry)=>{let status=unwrap(await forward(entry,"github-status",{}));if(!status.gh||status.account||status.authDetail)return;unwrap(await forward(entry,"github-apply",{token})),synced.push(entry.alias)})),synced}async function inDaemon(ctx,verb,params,here){if(ctx.caller.daemon)return here();let envelope=await daemonOf(ctx).request("api.invoke",{verb,params});if(envelope.ok)return envelope.result;let{message,code,...data}=envelope.error;throw new ApiError(message,code,data)}var GITHUB_VERBS=[{name:"github-status",group:"read",summary:"Can THIS machine use GitHub? Returns { git, gh (versions or null), account (the signed-in `gh` login or null), host, protocol, scopes, gitUsesGh (git pushes through gh), ssh: { ok, user?, detail? }, login: { state: pending|syncing|failed, code?, url?, error? } | null }. Missing tools are values, never errors. Add --machine <alias> for another machine.",flags:[],handler:(ctx)=>inDaemon(ctx,"github-status",{},()=>localStatus())},{name:"github-login",group:"edit",summary:"Sign THIS machine's `gh` in to GitHub with the device flow: returns { state, code, url } \u2014 type the code at the URL; poll `github-status` (.login) until `.account` is set. One flow per machine: a second call returns the pending one. --cancel stops it. When it finishes, `git` is set up to use it and the other machines that are signed out receive the same account (never one already signed in as someone else).",flags:[{name:"cancel",type:"bool",description:"Stop the pending flow (or dismiss its failure) instead of starting one."}],handler:(ctx)=>{let cancel=ctx.args.bool("cancel")===!0;return inDaemon(ctx,"github-login",cancel?{cancel}:{},async()=>cancel?{cancelled:deviceLogin.cancel()}:deviceLogin.start(ctx.caller.forwarded!==!0))}},{name:"github-logout",group:"edit",summary:"Sign THIS machine's `gh` out of github.com (`gh auth logout` for the active account). Returns the new github-status. Signs the machine out for every tool that uses gh, not only Rove.",flags:[],handler:(ctx)=>inDaemon(ctx,"github-logout",{},()=>logoutGithub())},{name:"github-sync",group:"edit",summary:"Give a registered machine THIS machine's GitHub account: reads this machine's `gh` token in the daemon and signs the target's `gh` in with it (the token is never printed or stored). Returns the target's github-status. Takes --to, not --machine, because the verb itself runs here. Refused when another machine's hub sends it.",flags:[{name:"to",type:"string",required:!0,placeholder:"ALIAS",description:"The registered machine to sign in."}],handler:(ctx)=>{if(ctx.caller.forwarded)throw new ApiError("github-sync only runs on the machine whose account is shared","GITHUB_SYNC_FORWARDED");let to=ctx.args.require("to");return inDaemon(ctx,"github-sync",{to},async()=>syncTo(to,await readHubToken()))}},{name:"github-apply",group:"edit",summary:"INTERNAL \u2014 sent by another machine's `github-sync`, not for direct use. Signs this machine's `gh` in with --token (piped to gh over stdin) and returns the new github-status. Refused unless another machine's hub forwarded it.",flags:[{name:"token",type:"string",required:!0,placeholder:"TOKEN",description:"A GitHub token for `gh auth login --with-token`."}],handler:async(ctx)=>{if(!ctx.caller.forwarded)throw new ApiError("github-apply only accepts a call forwarded from another machine","GITHUB_APPLY_FORWARDED_ONLY",{hint:"use `rove api github-sync --to <alias>` on the machine whose account you want to share"});return applyToken(ctx.args.require("token"))}}];async function issueList(ctx){let repoRoot=ctx.args.requireRepo("repo"),statuses=csvOf(ctx,"status",ISSUE_STATUSES,"issue-list"),needle=ctx.args.str("search")?.trim().toLowerCase();if(!statuses&&!needle)return simpleRpc(ctx,"issue.list",{repoRoot});let state=await daemonOf(ctx).request("issue.list",{repoRoot}),issues=state.issues.filter((i)=>(!statuses||statuses.has(i.status))&&(!needle||i.title.toLowerCase().includes(needle)||i.body.toLowerCase().includes(needle)));return{...state,issues}}var ISSUE_VERBS=[{name:"issue-list",group:"issues",summary:"List daemon-owned issues for a repo. --status and --search AND together; `nextId` and `skipped` still describe the whole board.",flags:[F.repo(),{name:"status",type:"csv",placeholder:"S1,S2",description:`Only issues in these statuses (${ISSUE_STATUSES.join(", ")}).`},{name:"search",type:"string",placeholder:"Q",description:"Only issues whose title or body contains Q (case-insensitive)."}],handler:issueList},{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-update",group:"issues",summary:"Update a daemon-owned issue's title, body, linked task, and/or status. Title, body and link land in one all-or-nothing write; the status follows as its own change.",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."},{name:"status",type:"enum",values:ISSUE_STATUSES,description:"New issue status."}],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-update --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"}async function remoteGit(repo,args){let out=await runAsync("git",args,{cwd:repo,env:readOnlyGitProcessEnv(),timeoutMs:REMOTE_TIMEOUT_MS});return{ok:out.ok,stdout:out.stdout.trim(),stderr:out.stderr.trim()||(out.error?`git ${args[0]} did not finish`:"")}}async function deleteRemoteBranch(repo,branch){let name=remoteFor(repo,branch),push=await remoteGit(repo,["push",name,"--delete",branch]);if(push.ok)return{name,deleted:!0};let remaining=await remoteGit(repo,["ls-remote","--heads",name,branch]);if(remaining.ok&&remaining.stdout.length===0)return{name,deleted:!0};return{name,deleted:!1,error:push.stderr||"git push exited non-zero"}}async function reportBranchDeletion(repo,branch,opts){if(!branch||!opts.deleteBranch&&!opts.deleteRemote)return;if(opts.heldBy!==void 0){let keptReason2=`task "${opts.heldBy}" still uses this branch`;return{branch,deleted:!1,keptReason:keptReason2,...opts.deleteRemote?{remote:{name:remoteFor(repo,branch),deleted:!1,error:`skipped: ${keptReason2}`}}:{}}}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:await 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 ownSession(daemon);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,cascade=ctx.args.bool("cascade")??!1,subject=deleteBranch||deleteRemote?(await daemon.request("task.get",{taskId})).task:void 0,res;try{res=await daemon.request("task.delete",{taskId,force,deleteBranch,...cascade?{cascade}:{},...self?{requestedByTaskId:self.taskId,requestedByTabId:self.tabId}:{}})}catch(err){throw deleteRecoveryError(err,taskId)}let removing=res.deleted??[taskId];for(let id of removing)await ctx.runtime.tearDownSession(id,res.teardown?.[id]);if(!res.queued)return{...res,status:"not_found"};if(!ctx.args.bool("wait")&&!subject)return{...res,status:"queued"};let outcomes=[];for(let id of removing)outcomes.push(await awaitDeletion(daemon,id));let outcome=outcomes.find((o)=>o.status==="failed")??outcomes.find((o)=>o.status==="pending")??outcomes[0];if(!outcome)return{...res,status:"removed"};let branch=subject&&outcome.status==="removed"?await reportBranchDeletion(gitRepoOf(subject),subject.branch??"",{deleteBranch,force,deleteRemote,heldBy:await branchHolder(daemon,subject,removing)}):void 0;return{...res,...outcome,...branch?{branch}:{}}}async function branchHolder(daemon,subject,gone){let{tasks}=await daemon.request("task.list");return tasks.find((t)=>!gone.includes(t.id)&&(subject.worktreePath&&t.worktreePath&&samePath(t.worktreePath,subject.worktreePath)||subject.branch&&t.branch===subject.branch&&gitRepoOf(t)===gitRepoOf(subject)&&workspaceCapabilities(t).ownsBranch))?.title}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((resolve3)=>setTimeout(resolve3,DELETE_POLL_INTERVAL_MS))}}async function setArchived(ctx,archived){let taskId=ctx.args.require("task-id"),res=await daemonOf(ctx).request("task.archive",{taskId,archived,force:archived&&(ctx.args.bool("force")??!1)});return{taskId,archived,ids:res.archived}}var archiveTask=(ctx)=>setArchived(ctx,!0),unarchiveTask=(ctx)=>setArchived(ctx,!1);async function land(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),repo=ctx.args.str("repo");if(ctx.args.bool("dry-run")===!0)return(await daemon.request("task.landPreflight",{taskId,...repo?{repo}:{}})).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"),...ctx.caller.cwd!==void 0?{callerCwd:ctx.caller.cwd}:{},...repo?{repo}:{}})}catch(err){throw landStoppedError(err,taskId)??landRecoveryError(err,taskId)}return{ok:!0,taskId,...res.result}}function landStoppedError(err,taskId){let data=err instanceof Error&&err.name==="LandStoppedError"?err.data:void 0;if(!data?.stopped)return null;let head=landRecoveryError(err,taskId),recovery=head instanceof ApiError?head.data:void 0,message=errorMessage(err);return new ApiError(splitDaemonCode(message)?.rest??message,data.stopped.code,{taskId,failedRepo:data.stopped.repo,repos:data.repos,hint:`repos that already landed stay landed \u2014 fix ${data.stopped.repo}, then run \`land\` again: it resumes with the repos still pending`,...recovery})}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"]})}function removableWorktree(ctx,task){let worktreePath=(task.worktreePath??"").trim();if(!worktreePath)throw new ApiError(`task ${task.id} has no worktree on disk`,"NO_WORKTREE",{hint:"nothing to remove \u2014 `ensure-worktree` materialises one"});let wt=canonicalize(worktreePath);if(samePath(wt,canonicalize(gitRepoOf(task))))throw new ApiError(`refusing to remove ${worktreePath} \u2014 it is the project's own checkout, not a Rove worktree`,"BASE_CHECKOUT");if(ctx.caller.cwd!==void 0&&pathWithin(wt,canonicalize(ctx.caller.cwd))!==null)throw new ApiError(`refusing to remove the caller's own worktree (${worktreePath}) \u2014 re-run from outside it`,"CALLER_WORKTREE");return worktreePath}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=removableWorktree(ctx,task),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)}async function sync(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id"),repo=ctx.args.str("repo"),res=await daemon.request("task.syncBase",{taskId,...repo?{repo}:{}}),failed=res.result.repos?.find((r)=>!r.ok);if(failed)throw new ApiError(splitDaemonCode(failed.error??"")?.rest??failed.error??"sync failed",failed.code??"SYNC_FAILED",{taskId,failedRepo:failed.name,repos:res.result.repos,hint:"the other repos synced; a conflicted merge is left in place in its worktree \u2014 resolve and commit it there"});return{ok:!0,taskId,...res.result}}var LIFECYCLE_VERBS=[{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 }. A MULTI-REPO task (`add --repo A --repo B`) lands every repo into its own base, in picked order: every repo is probed first and nothing is merged if any refuses; the run stops at the first conflict, leaving earlier repos landed; re-run `land` to resume (a repo already merged reads as `skipped`). Worktrees are removed only once every repo has landed. Its result adds `.repos[]` ({ name, status: landed|skipped|conflict|refused|failed|pending, landedOn, ahead, commit, error?, code? }); a stop is the usual error (LAND_CONFLICT, MAIN_CHECKOUT_DIRTY, \u2026) carrying `.repos[]` and `.failedRepo`.",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."},{name:"repo",type:"string",placeholder:"NAME",description:"Multi-repo task: land (or, with --dry-run, probe) only this repo, named as in `.task.extraRepos[].name` (the primary's name is its directory name). UNKNOWN_REPO otherwise."}],handler:land},{name:"sync",group:"lifecycle",summary:"Merge the base branch INTO a task's worktree (the inverse of `land`; the sidebar's \u2193N drift). Refuses a dirty worktree (SYNC_WORKTREE_DIRTY \u2014 commit first, never stash); a conflict is left IN PLACE in the worktree for you to resolve (SYNC_CONFLICT lists the files). Returns { baseRef, alreadyCurrent }. A multi-repo task syncs EVERY repo against its own base and carries `.repos[]` ({ name, ok, baseRef?, alreadyCurrent?, error?, code? }); one repo's conflict does not stop the others, and is raised as the error after all ran.",flags:[F.taskId(),{name:"repo",type:"string",placeholder:"NAME",description:"Multi-repo task: sync only this repo (`.task.extraRepos[].name`; UNKNOWN_REPO otherwise)."}],handler:sync},{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. CHILDREN (tasks nested under it by `add`): by default the task's children are promoted \u2014 they keep running, re-parented to the deleted task's own parent (or top level); --cascade deletes the whole subtree instead, each worktree still passing the dirty gate before ANY of it is queued. A directory more than one task runs in (an owner and its shared children) is removed only with its last task; deleting a shared child never touches the directory, and an owner leaving hands the directory to a remaining child.",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:"cascade",type:"bool",description:"Also delete every descendant of the task (its child tasks, recursively). Default: children are promoted instead. The reply lists the ids as `deleted`."},{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},{name:"archive",group:"lifecycle",summary:"Hide a task from the sidebar and the default `list`, without touching anything else: the worktree, branch, transcript and any running session stay exactly as they are, and `send`, `read-output`, `get-task` and `delete` keep working on it by id. Applies to the task and every descendant (its child tasks, recursively) together. Refused with TASK_BUSY while an engine in the subtree is running or waiting on you \u2014 pass --force to hide it anyway; archive never stops a session. A project's `main` checkout cannot be archived. Undo with `unarchive`; `list --archived` finds archived tasks. Returns { taskId, archived, ids } \u2014 `ids` is every task hidden.",flags:[F.taskId(),{name:"force",type:"bool",description:"Archive even though an engine in the subtree is running or waiting on you. Nothing is stopped."}],handler:archiveTask},{name:"unarchive",group:"lifecycle",summary:"Bring an archived task back into the sidebar and `list`, together with its archived descendants. A child unarchived on its own while its parent is still archived shows as a top-level row until the parent returns. Returns { taskId, archived: false, ids }.",flags:[F.taskId()],handler:unarchiveTask}];var MACHINE_UPDATE_VERB={name:"machine-update",group:"edit",summary:"Update Rove on a registered machine, from here: that machine installs the newest build of THIS machine's release channel and restarts its own daemon. Its sessions keep running; anything its daemon was doing is cut off. Returns { alias, from, to, changed }. Takes --to, not --machine, because the verb itself runs here. Can take minutes.",flags:[{name:"to",type:"string",required:!0,placeholder:"ALIAS",description:"The registered machine to update."}],handler:async(ctx)=>{if(ctx.caller.forwarded)throw new ApiError("machine-update only runs on the machine that registered the target","MACHINE_UPDATE_FORWARDED");let entry=requireMachine(ctx.args.require("to"));try{return await upgradeMachine(entry)}catch(err){throw new ApiError(errorMessage(err),"MACHINE_UPDATE_FAILED",{machine:entry.alias})}}};var ACCEPTED="a PR URL (https://github.com/OWNER/REPO/pull/N) or a PR number of the repo in the current directory";async function urlForNumber(n){let res=await runAsync("gh",["pr","view",n,"--json","url","-q",".url"],{timeoutMs:30000});return res.ok?canonicalPrUrl(res.stdout.trim()):void 0}async function attachSessionPr(ctx,taskId,url){return simpleRpc(ctx,"task.addSessionPr",{taskId,url})}var PR_ATTACH_VERB={name:"pr-attach",group:"edit",summary:"Show a pull request on a task's row, with its live state. Run it once after opening a PR from ANY directory (a worktree Rove does not track); `publish` already does it for the PRs it opens. Idempotent: attaching the same PR again changes nothing. Without --task-id it targets your own task. Returns { taskId, url }.",flags:[{name:"url",type:"string",required:!0,placeholder:"URL|N",description:`The pull request: ${ACCEPTED}.`},{name:"task-id",type:"string",placeholder:"ID",description:"The task to attach to. Default: the task this session runs in."}],handler:async(ctx)=>{let raw=ctx.args.require("url").trim(),url=/^\d+$/.test(raw)?await urlForNumber(raw):canonicalPrUrl(raw);if(!url)throw new ApiError(`--url ${raw} is not ${ACCEPTED}`,"BAD_FLAG",{hint:"pass the URL `gh pr create` printed"});return attachSessionPr(ctx,await resolveTarget(ctx,"pr-attach"),url)}};async function published(ctx,taskId,branch,url){let attached=await attachSessionPr(ctx,taskId,url).then(()=>({}),(err)=>({attachError:errorMessage(err)}));return{branch,pushed:!0,pr:{url},...attached}}async function run(cwd,cmd,args){let res=await runAsync(cmd,args,{cwd,timeoutMs:120000});return{ok:res.ok,out:res.error??`${res.stdout}${res.stderr}`.trim()}}var PUBLISH_VERB={name:"publish",group:"lifecycle",summary:"Push a task's branch to its remote (`origin` unless --remote) and open its pull request with `gh`, or return the one already open. What `land` does for a task on another machine. Returns { branch, pushed, pr: { url } | null, prError? } \u2014 `prError` says why no PR (gh missing or not signed in, a non-GitHub remote, no commits ahead); the push still happened. Refuses a task with no worktree or no branch.",flags:[F.taskId(),{name:"remote",type:"string",placeholder:"NAME",description:"Remote to push to. Default: origin."}],handler:async(ctx)=>{let taskId=ctx.args.require("task-id"),{task}=await daemonOf(ctx).request("task.get",{taskId});if(!task.worktreePath||!task.branch)throw new ApiError(`task ${taskId} has no worktree or branch to publish`,"NO_WORKTREE",{nextCommandArgs:["api","ensure-worktree","--task-id",taskId]});let cwd=task.worktreePath,remote=ctx.args.str("remote")??"origin",push=await run(cwd,"git",["push","-u",remote,task.branch]);if(!push.ok)throw new ApiError(`git push to ${remote} failed: ${push.out}`,"PUSH_FAILED");let existing=await run(cwd,"gh",["pr","view",task.branch,"--json","url","-q",".url"]);if(existing.ok&&existing.out.startsWith("http"))return published(ctx,taskId,task.branch,existing.out);let base=task.baseRef?["--base",String(task.baseRef)]:[],created=await run(cwd,"gh",["pr","create","--fill","--head",task.branch,...base]),url=created.out.split(`
|
|
19
19
|
`).find((line)=>line.startsWith("http"));if(created.ok&&url)return published(ctx,taskId,task.branch,url);return{branch:task.branch,pushed:!0,pr:null,prError:created.out||"gh pr create failed"}}};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 CONTEXT_NOTE_CAP=15,CONTEXT_TASK_LIMIT=20;function buildContext(input){let rows=[];for(let task of input.tasks){let entry=input.activity?.[task.id],activity=entry&&TASK_ACTIVITY_STATES.includes(entry.state)?{state:entry.state,at:entry.at}:null,{group,rank}=taskGroupOf({task,activity,tabAlive:input.liveTaskIds?input.liveTaskIds.has(task.id):null,now:input.now}),pr=rollupPr(task);rows.push({taskId:task.id,title:task.title,branch:task.branch,group,rank,activity:activity?{state:activity.state,forMs:Math.max(0,input.now-activity.at)}:null,...pr?{checkState:pr.checkState}:{},...pr?.number!==void 0?{pr:pr.number}:{},...task.report?{report:task.report}:{},at:activity?.at??0})}rows.sort((a,b)=>a.rank-b.rank||b.at-a.at);let kept=rows.slice(0,input.limit).map(({at:_at,...row})=>row),omitted=rows.length-kept.length;return{repo:input.repo,at:new Date(input.now).toISOString(),tasks:kept,...omitted>0?{omittedTasks:omitted}:{},attention:input.attention,gates:input.gates,notes:input.notes.slice(0,CONTEXT_NOTE_CAP)}}function age(ms){let m=Math.floor(ms/60000);if(m<60)return`${m}m`;let h=Math.floor(m/60);return h<48?`${h}h`:`${Math.floor(h/24)}d`}function shortId(id){return id.slice(-6)}function renderContext(payload){let lines=[`repo ${payload.repo} \xB7 ${payload.tasks.length} tasks \xB7 ${payload.attention.length} in the inbox`];if(payload.tasks.length===0)lines.push(" (no tasks)");for(let task of payload.tasks){let bits=[];if(task.activity)bits.push(`${task.activity.state} ${age(task.activity.forMs)}`);if(task.checkState)bits.push(`ci:${task.checkState}`);if(task.pr!==void 0)bits.push(`PR#${task.pr}`);if(task.report?.summary)bits.push(`\u201C${task.report.summary}\u201D`);else if(task.report)bits.push("reported");lines.push(` ${task.group.padEnd(16)} ${shortId(task.taskId)} ${task.title}${task.branch?` [${task.branch}]`:""}${bits.length>0?` \u2014 ${bits.join(" \xB7 ")}`:""}`)}if(payload.omittedTasks)lines.push(` (+${payload.omittedTasks} quieter tasks not shown \u2014 raise --limit)`);if(payload.attention.length>0){lines.push(`inbox (${payload.attention.length} unhandled):`);for(let item of payload.attention)lines.push(` ${item.state} ${item.taskId?shortId(item.taskId):"routine"}`)}if(payload.gates.length>0){lines.push(`open decisions (${payload.gates.length}, answer with \`gate-answer\`):`);for(let gate of payload.gates){let opts=gate.options.map((o)=>`${o.key}${o.key===gate.recommended?"*":""}`).join("/");lines.push(` ${gate.id} ${shortId(gate.taskId)} ${gate.question}${opts?` [${opts}]`:""}`)}}if(payload.notes.length>0){lines.push(`field notes (${payload.notes.length}, newest first):`);for(let note2 of payload.notes)lines.push(` #${note2.id} ${note2.text}`)}return lines.join(`
|
|
20
|
-
`)}async function tryRead(read){try{return await read()}catch{return null}}async function loadContext(daemon,runtime,opts){let{tasks:allTasks}=await daemon.request("task.list"),filter=opts.repo===null?null:await repoFilter(runtime,opts.repo,allTasks.map((t)=>t.repo)),inScope=(repo)=>filter===null||filter.matches(repo),repoTaskIds=new Set(allTasks.filter((task)=>inScope(task.repo)).map((task)=>task.id)),tasks=allTasks.filter((task)=>(task.kind??"task")==="task"&&inScope(task.repo)&&task.deletion?.phase!=="queued"&&task.deletion?.phase!=="running"),[inspect,inbox,gates2,notes,liveTaskIds]=await Promise.all([tryRead(()=>daemon.request("debug.inspect")),tryRead(()=>daemon.request("attention.list")),tryRead(()=>daemon.request("gate.list")),filter?tryRead(()=>daemon.request("note.list",{repo:filter.target})):null,tryRead(()=>runtime.liveTaskIds(allTasks))]);return{payload:buildContext({repo:filter?.target??"*",tasks,activity:inspect?.activity?.tasks??null,liveTaskIds:liveTaskIds??null,attention:(inbox?.items??[]).filter((item)=>item.state!=="decision_needed"&&(item.taskId===null||repoTaskIds.has(item.taskId))),gates:(gates2?.gates??[]).filter((gate)=>repoTaskIds.has(gate.taskId)),notes:notes?.notes??[],now:Date.now(),limit:opts.limit}),unresolvableRepos:filter?.unresolvableRepos??[],gatesUnreadable:gates2===null}}async function context(ctx){let{args,runtime}=ctx,{payload,unresolvableRepos}=await loadContext(daemonOf(ctx),runtime,{repo:args.requireRepo("repo"),limit:args.int("limit")??CONTEXT_TASK_LIMIT});if(args.bool("text"))return{text:renderContext(payload)};return{...payload,...unresolvableRepos.length>0?{unresolvableRepos}:{}}}var CONTEXT_VERB={name:"context",group:"read",summary:"The coordinator's orientation read (session start, or whenever you lack the state): one composed snapshot of a repo \u2014 every worktree task with its DERIVED group (waiting-on-you|landing|ready-for-review|working|idle|unknown, sorted by rank so the first row is what needs a person next), title, branch, live engine activity + how long, `.checkState` (Rove's own CI truth), the worker's `.report` claim; plus the unhandled attention inbox and the repo's newest field notes (the same ones injected into fresh sessions here). The group is DERIVED from report/PR/activity/liveness \u2014 it is not the declared `status`, which a crashed worker leaves lying. `--text` renders it compactly instead of as structured JSON.",flags:[F.repo(!0),{name:"limit",type:"int",default:String(CONTEXT_TASK_LIMIT),placeholder:"N",description:"Max tasks to include. Sorted by rank, so the cap drops the quiet tail; `omittedTasks` reports it."},{name:"text",type:"bool",description:"Return { text } \u2014 one compact line per task instead of the structured rows."}],handler:context};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 run2 of runs)byStatus[run2.status]=(byStatus[run2.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.flatMap((a)=>a.repo?[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(!automation.repo||!filter.matches(automation.repo))continue;let page=await daemon.request("automation.runs",{id:automation.id});for(let run2 of page.runs)if((epochOf(run2.at)??0)>=sinceMs)runs.push(run2)}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-m711bzrr.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[{RoveDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-dtb0dqwh.js"),import("./chunk-b6xrkzhj.js")]),client=new RoveDaemonClient(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{compareByExitAtDesc,readPtyExitRecords}=await import("./chunk-bdbm8jkd.js"),records=Object.values(readPtyExitRecords()).sort(compareByExitAtDesc);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};import{sep}from"path";function taskRoots(task){let extras=(task.extraRepos??[]).map((r)=>r.worktreePath);return[task.worktreePath,...extras].filter((p)=>typeof p==="string"&&p.length>0)}function under(cwd,root){let trimmed=root.endsWith(sep)?root.slice(0,-1):root;return cwd===trimmed||cwd.startsWith(trimmed+sep)}function urlOf(host,port){if(["*","0.0.0.0","::","127.0.0.1","::1","::ffff:127.0.0.1","localhost"].includes(host))return`http://localhost:${port}`;return host.includes(":")?`http://[${host}]:${port}`:`http://${host}:${port}`}function owningTaskId(tasks,cwd){if(!cwd)return null;let best=null;for(let task of tasks)for(let root of taskRoots(task))if(under(cwd,root)&&(!best||root.length>best.depth))best={id:task.id,depth:root.length};return best?.id??null}async function handlePorts(ctx){let daemon=daemonOf(ctx),all=ctx.args.bool("all"),taskId=ctx.args.str("task-id");if(all&&taskId!==void 0)throw new ApiError("pass --task-id or --all, not both","BAD_FLAG",helpStep("ports"));if(!all&&taskId===void 0)throw new ApiError("--task-id is required (or pass --all)","MISSING_FLAG");if(!all)await daemon.request("task.get",{taskId});let tasks=(await daemon.request("task.list")).tasks??[],sockets=await ctx.runtime.listeningPorts();if(!sockets)return all?{ports:null}:{taskId,ports:null};let rows=[];for(let s of sockets){let owner=owningTaskId(tasks,s.cwd);if(all)rows.push({...s,url:urlOf(s.host,s.port),taskId:owner});else if(owner===taskId)rows.push({...s,url:urlOf(s.host,s.port)})}return all?{ports:rows}:{taskId,ports:rows}}var PORTS_VERB={name:"ports",group:"read",summary:"List the TCP ports a task's processes listen on (a dev server, a preview, a debugger), on this machine. A listener belongs to the task whose checkout holds its process's cwd. Returns { taskId, ports: [{ port, host, url, pid, command, cwd }] }; --all lists every listener with its owning `taskId` (null = no task). `ports: null` = the scan could not run, which says nothing about what is listening.",flags:[F.taskId(!1),{name:"all",type:"bool",description:"Every listener on this machine, each tagged with its owning task."}],handler:handlePorts};async function handleReviewComments(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id");await daemon.request("task.get",{taskId});let res=await daemon.request("pr.reviewComments",{taskId});return{taskId,...res}}var REVIEW_COMMENTS_VERB={name:"review-comments",group:"read",summary:"List the unresolved review threads on a task's PR, each with its `path` and `line`, so an agent can address review feedback. Returns { taskId, prNumber, threads: [{ path, line, outdated, comments: [{ author, body, url }] }], totalUnresolved }; at most 50 threads. `prNumber: null` = the task has no PR yet. `unavailable` = GitHub could not be asked (gh missing or signed out), which says nothing about open threads.",flags:[F.taskId()],handler:handleReviewComments};var DEFAULT_LIMIT2=20,MAX_LIMIT=100;async function search(ctx){let query=(ctx.args.str("query")??"").trim();if(!query)throw new ApiError("search needs a non-empty --query","MISSING_FLAG");let limit=Math.min(MAX_LIMIT,Math.max(1,ctx.args.int("limit")??DEFAULT_LIMIT2)),daemon=daemonOf(ctx),{tasks:all}=await daemon.request("task.list"),repoFlag=ctx.args.str("repo"),tasks=all;if(repoFlag){let filter=await repoFilter(ctx.runtime,ctx.args.requireRepo("repo"),all.map((t)=>t.repo));tasks=all.filter((t)=>filter.matches(t.repo))}return searchTasks(tasks,query,limit)}var SEARCH_VERB={name:"search",group:"read",summary:"Search every task's engine conversations (user and assistant prose, not tool output), newest session first. Returns {query, matches:[{taskId, title, tabId?, role, at, snippet}], skipped:[{taskId, reason}], truncated}; reason is other-machine or engine-unsupported (an engine with no history reader).",flags:[{name:"query",type:"string",required:!0,placeholder:"TEXT",description:"Text to find, case-insensitive."},{name:"repo",type:"string",required:!1,placeholder:"PATH",description:"Only this repo's tasks. Relative paths resolve against $PWD."},{name:"limit",type:"int",default:String(DEFAULT_LIMIT2),placeholder:"N",description:`Stop after N matches (max ${MAX_LIMIT}); at most ${PER_SESSION} per session.`}],handler:search};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((resolve3,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})}
|
|
20
|
+
`)}async function tryRead(read){try{return await read()}catch{return null}}async function loadContext(daemon,runtime,opts){let{tasks:allTasks}=await daemon.request("task.list"),filter=opts.repo===null?null:await repoFilter(runtime,opts.repo,allTasks.map((t)=>t.repo)),inScope=(repo)=>filter===null||filter.matches(repo),repoTaskIds=new Set(allTasks.filter((task)=>inScope(task.repo)).map((task)=>task.id)),tasks=allTasks.filter((task)=>(task.kind??"task")==="task"&&inScope(task.repo)&&task.deletion?.phase!=="queued"&&task.deletion?.phase!=="running"),[inspect,inbox,gates2,notes,liveTaskIds]=await Promise.all([tryRead(()=>daemon.request("debug.inspect")),tryRead(()=>daemon.request("attention.list")),tryRead(()=>daemon.request("gate.list")),filter?tryRead(()=>daemon.request("note.list",{repo:filter.target})):null,tryRead(()=>runtime.liveTaskIds(allTasks))]);return{payload:buildContext({repo:filter?.target??"*",tasks,activity:inspect?.activity?.tasks??null,liveTaskIds:liveTaskIds??null,attention:(inbox?.items??[]).filter((item)=>item.state!=="decision_needed"&&(item.taskId===null||repoTaskIds.has(item.taskId))),gates:(gates2?.gates??[]).filter((gate)=>repoTaskIds.has(gate.taskId)),notes:notes?.notes??[],now:Date.now(),limit:opts.limit}),unresolvableRepos:filter?.unresolvableRepos??[],gatesUnreadable:gates2===null}}async function context(ctx){let{args,runtime}=ctx,{payload,unresolvableRepos}=await loadContext(daemonOf(ctx),runtime,{repo:args.requireRepo("repo"),limit:args.int("limit")??CONTEXT_TASK_LIMIT});if(args.bool("text"))return{text:renderContext(payload)};return{...payload,...unresolvableRepos.length>0?{unresolvableRepos}:{}}}var CONTEXT_VERB={name:"context",group:"read",summary:"The coordinator's orientation read (session start, or whenever you lack the state): one composed snapshot of a repo \u2014 every worktree task with its DERIVED group (waiting-on-you|landing|ready-for-review|working|idle|unknown, sorted by rank so the first row is what needs a person next), title, branch, live engine activity + how long, `.checkState` (Rove's own CI truth), the worker's `.report` claim; plus the unhandled attention inbox and the repo's newest field notes (the same ones injected into fresh sessions here). The group is DERIVED from report/PR/activity/liveness \u2014 it is not the declared `status`, which a crashed worker leaves lying. `--text` renders it compactly instead of as structured JSON.",flags:[F.repo(!0),{name:"limit",type:"int",default:String(CONTEXT_TASK_LIMIT),placeholder:"N",description:"Max tasks to include. Sorted by rank, so the cap drops the quiet tail; `omittedTasks` reports it."},{name:"text",type:"bool",description:"Return { text } \u2014 one compact line per task instead of the structured rows."}],handler:context};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 run2 of runs)byStatus[run2.status]=(byStatus[run2.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.flatMap((a)=>a.repo?[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(!automation.repo||!filter.matches(automation.repo))continue;let page=await daemon.request("automation.runs",{id:automation.id});for(let run2 of page.runs)if((epochOf(run2.at)??0)>=sinceMs)runs.push(run2)}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-7dmcpc3d.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[{RoveDaemonClient},{defaultPtyHostSocketPath}]=await Promise.all([import("./chunk-dtb0dqwh.js"),import("./chunk-b6xrkzhj.js")]),client=new RoveDaemonClient(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{compareByExitAtDesc,readPtyExitRecords}=await import("./chunk-bdbm8jkd.js"),records=Object.values(readPtyExitRecords()).sort(compareByExitAtDesc);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};import{sep}from"path";function taskRoots(task){let extras=(task.extraRepos??[]).map((r)=>r.worktreePath);return[task.worktreePath,...extras].filter((p)=>typeof p==="string"&&p.length>0)}function under(cwd,root){let trimmed=root.endsWith(sep)?root.slice(0,-1):root;return cwd===trimmed||cwd.startsWith(trimmed+sep)}function urlOf(host,port){if(["*","0.0.0.0","::","127.0.0.1","::1","::ffff:127.0.0.1","localhost"].includes(host))return`http://localhost:${port}`;return host.includes(":")?`http://[${host}]:${port}`:`http://${host}:${port}`}function owningTaskId(tasks,cwd){if(!cwd)return null;let best=null;for(let task of tasks)for(let root of taskRoots(task))if(under(cwd,root)&&(!best||root.length>best.depth))best={id:task.id,depth:root.length};return best?.id??null}async function handlePorts(ctx){let daemon=daemonOf(ctx),all=ctx.args.bool("all"),taskId=ctx.args.str("task-id");if(all&&taskId!==void 0)throw new ApiError("pass --task-id or --all, not both","BAD_FLAG",helpStep("ports"));if(!all&&taskId===void 0)throw new ApiError("--task-id is required (or pass --all)","MISSING_FLAG");if(!all)await daemon.request("task.get",{taskId});let tasks=(await daemon.request("task.list")).tasks??[],sockets=await ctx.runtime.listeningPorts();if(!sockets)return all?{ports:null}:{taskId,ports:null};let rows=[];for(let s of sockets){let owner=owningTaskId(tasks,s.cwd);if(all)rows.push({...s,url:urlOf(s.host,s.port),taskId:owner});else if(owner===taskId)rows.push({...s,url:urlOf(s.host,s.port)})}return all?{ports:rows}:{taskId,ports:rows}}var PORTS_VERB={name:"ports",group:"read",summary:"List the TCP ports a task's processes listen on (a dev server, a preview, a debugger), on this machine. A listener belongs to the task whose checkout holds its process's cwd. Returns { taskId, ports: [{ port, host, url, pid, command, cwd }] }; --all lists every listener with its owning `taskId` (null = no task). `ports: null` = the scan could not run, which says nothing about what is listening.",flags:[F.taskId(!1),{name:"all",type:"bool",description:"Every listener on this machine, each tagged with its owning task."}],handler:handlePorts};async function handleReviewComments(ctx){let daemon=daemonOf(ctx),taskId=ctx.args.require("task-id");await daemon.request("task.get",{taskId});let res=await daemon.request("pr.reviewComments",{taskId});return{taskId,...res}}var REVIEW_COMMENTS_VERB={name:"review-comments",group:"read",summary:"List the unresolved review threads on a task's PR, each with its `path` and `line`, so an agent can address review feedback. Returns { taskId, prNumber, threads: [{ path, line, outdated, comments: [{ author, body, url }] }], totalUnresolved }; at most 50 threads. `prNumber: null` = the task has no PR yet. `unavailable` = GitHub could not be asked (gh missing or signed out), which says nothing about open threads.",flags:[F.taskId()],handler:handleReviewComments};var DEFAULT_LIMIT2=20,MAX_LIMIT=100;async function search(ctx){let query=(ctx.args.str("query")??"").trim();if(!query)throw new ApiError("search needs a non-empty --query","MISSING_FLAG");let limit=Math.min(MAX_LIMIT,Math.max(1,ctx.args.int("limit")??DEFAULT_LIMIT2)),daemon=daemonOf(ctx),{tasks:all}=await daemon.request("task.list"),repoFlag=ctx.args.str("repo"),tasks=all;if(repoFlag){let filter=await repoFilter(ctx.runtime,ctx.args.requireRepo("repo"),all.map((t)=>t.repo));tasks=all.filter((t)=>filter.matches(t.repo))}return searchTasks(tasks,query,limit)}var SEARCH_VERB={name:"search",group:"read",summary:"Search every task's engine conversations (user and assistant prose, not tool output), newest session first. Returns {query, matches:[{taskId, title, tabId?, role, at, snippet}], skipped:[{taskId, reason}], truncated}; reason is other-machine or engine-unsupported (an engine with no history reader).",flags:[{name:"query",type:"string",required:!0,placeholder:"TEXT",description:"Text to find, case-insensitive."},{name:"repo",type:"string",required:!1,placeholder:"PATH",description:"Only this repo's tasks. Relative paths resolve against $PWD."},{name:"limit",type:"int",default:String(DEFAULT_LIMIT2),placeholder:"N",description:`Stop after N matches (max ${MAX_LIMIT}); at most ${PER_SESSION} per session.`}],handler:search};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((resolve3,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})}
|
|
21
21
|
`),!until.has(event.state))return;finish(()=>resolve3({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",cliOnly:!0,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};function sourceChanged(detail){return new ApiError(`${detail} \u2014 restart the read without the cursor`,"SOURCE_CHANGED")}async function readTaskOutput(input,deps){let messageLimit=Math.min(Math.max(input.limit??DEFAULT_PAGE_MESSAGES,1),MAX_PAGE_MESSAGES),lineLimit=Math.min(Math.max(input.limit??DEFAULT_TAIL_LINES,1),TERMINAL_TAIL_LINES);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((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,messageLimit):continueTerminal(input,deps,cursor,lineLimit)}if(input.source==="terminal")return firstTerminalPage(input,deps,null,lineLimit);let pinned=await resolveHistory(input,deps);if(pinned===null){if(input.source==="history")throw new ApiError(`${input.tab} is not an engine tab \u2014 it has no structured history`,"HISTORY_REQUIRED");return firstTerminalPage(input,deps,null,lineLimit)}if(typeof pinned==="string"){if(input.source==="history")throw new ApiError(`structured history unavailable for ${input.taskId}: ${pinned}`,"HISTORY_REQUIRED");return firstTerminalPage(input,deps,pinned,lineLimit)}let messages;try{messages=await pinned.reader.readHistory(pinned.sessionId)}catch{if(input.source==="history")throw new ApiError(`structured history unavailable for ${input.taskId}: history_unreadable`,"HISTORY_REQUIRED");return firstTerminalPage(input,deps,"history_unreadable",lineLimit)}if(messages.length===0&&input.source==="auto")return firstTerminalPage(input,deps,"history_missing",lineLimit);return historyEnvelope(input,pinned.sessionId,messages,{before:messages.length},messageLimit)}async function resolveHistory(input,deps){if(input.tab)return deps.tabHistory(input.tab);if(input.sharesWorkspace)return deps.ownHistory?.()??"history_missing";if(!deps.history)return"engine_unsupported";if(!input.worktree)return"history_missing";let ids;try{ids=await deps.history.listSessionIdsForWorktree(input.worktree)}catch{return"history_unreadable"}let sid=ids[ids.length-1];return sid?{reader:deps.history,sessionId:sid}:"history_missing"}async function continueHistory(input,deps,cursor,limit){let pinned=await resolveHistory(input,deps);if(pinned===null||pinned==="engine_unsupported")throw sourceChanged("the engine no longer provides structured history");if(pinned==="history_unreadable")throw new ApiError("history became unreadable \u2014 retry, or restart without the cursor","HISTORY_UNREADABLE");let sid=typeof pinned==="string"?null:pinned.sessionId;if(typeof pinned==="string"||sid!==cursor.sid)throw sourceChanged(`the engine session changed (was ${cursor.sid}, now ${sid??"none"})`);let messages;try{messages=await pinned.reader.readHistory(cursor.sid)}catch{throw new ApiError("history became unreadable \u2014 retry, or restart without the cursor","HISTORY_UNREADABLE")}if(cursor.idx>messages.length)throw sourceChanged("the pinned transcript shrank");return historyEnvelope(input,cursor.sid,messages,cursor.older?{before:cursor.idx}:{from:cursor.idx},limit)}function historyEnvelope(input,sessionId,messages,at,limit){let{page,start,end,limited}=buildHistoryPage(messages,at,limit),base={v:1,task:input.taskId,src:"history",sid:sessionId,tab:input.tab};return{taskId:input.taskId,source:"history",history:{sessionId,messages:page,returnedMessageCount:page.length,totalMessages:messages.length,firstIndex:start,limited},cursor:encodeCursor({...base,idx:end}),olderCursor:start>0?encodeCursor({...base,idx:start,older:!0}):null,fallbackReason:null,warnings:[]}}async function firstTerminalPage(input,deps,fallbackReason,lines){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,olderCursor: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,lines);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}),olderCursor:null,fallbackReason,warnings:[]}}async function continueTerminal(input,deps,cursor,lines){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,lines),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}),olderCursor:null,fallbackReason:fr,warnings}}function snapshotTabHistory(task,tabId){let tabs=readTabsSnapshot(task.id)?.tabs??[],tab=tabId?tabs.find((t)=>t.id===tabId):canonicalEngineTab(tabs);if(!tab||tab.kind!=="engine")return null;let vendor=tab.vendor??task.vendor;if(!vendor||!supportsStructuredHistory(sessionProtocol(vendor)))return"engine_unsupported";return tab.sessionId?{reader:protocolEntry(vendor).history,sessionId:tab.sessionId}:"history_missing"}async function sharesDirectory(daemon,task){if(task.sharesWorkspaceOf)return!0;if(!task.worktreePath)return!1;try{let{tasks}=await daemon.request("task.list");return tasks.some((t)=>t.id!==task.id&&samePath(t.worktreePath,task.worktreePath))}catch{return!1}}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}),alias=task.ptyAlias,sharesWorkspace=alias!==void 0||await sharesDirectory(daemon,task),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,tabHistory:(tabId)=>snapshotTabHistory(task,tabId),ownHistory:()=>snapshotTabHistory(task,alias?.tabId),peekTerminal:async(tabId,sinceOffset)=>{let scope=await ptyScopeOf(daemon,task),owner=alias&&(tabId===void 0||tabId===alias.tabId)?alias.taskId:taskId;try{return await peekTaskTerminal(owner,engineBin,tabId??alias?.tabId,sinceOffset,scope)}catch(err){if(!tabId&&alias&&err instanceof ApiError&&err.code==="TAB_NOT_FOUND")return null;throw err}}},envelope=await readTaskOutput({taskId,worktree:task.worktreePath??null,sharesWorkspace,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),await ptyScopeOf(daemon,task)),engineError=envelope.source==="history"&&!tab?await engineScreenError(task):void 0;return{vendor:vendor??null,running,...envelope,...engineError?{engineError}:{}}}var READ_OUTPUT_VERB={name:"read-output",group:"read",summary:"Read what a task's engine is doing, newest first, as bounded JSON: the engine's own structured history when available, else a labeled terminal tail (typed fallbackReason). The first page is the LATEST \u2014 the last --limit messages or terminal lines. `cursor` pages forward and, once caught up, is the poll point: re-read with it to get only what the session wrote since (pair with `watch` to know when). `olderCursor` pages back through history. --tab tab-N reads one exact tab: its own conversation when it is an engine tab with one, else its terminal. Read-only \u2014 never attaches or types; the cursor stays pinned to one source/session/tab (SOURCE_CHANGED when it moved). A history read also carries `engineError` when the engine's screen ends on an error row it never wrote to its transcript (a turn that failed before replying).",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 tab (e.g. tab-3, ids from `get-task` .tabs[]) instead of the task's engine: an engine tab's own pinned conversation when it has one, else that tab's terminal."},{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` (forward / poll) or `olderCursor` (back) from a previous page. Pinned to that page's source, session and tab."},{name:"limit",type:"int",placeholder:"N",description:`Page size: history messages (default ${DEFAULT_PAGE_MESSAGES}, max ${MAX_PAGE_MESSAGES}) or terminal lines (default ${DEFAULT_TAIL_LINES}, max ${TERMINAL_TAIL_LINES}).`}],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. Archived tasks are left out unless --archived. Filters AND together: --repo, --status, --activity (comma lists match any value). --fields id,title,status trims each row to those keys. With --activity each task carries the `.activity` it matched; a task whose state Rove cannot read never matches. `unresolvableRepos` beside `tasks` names task repos --repo could not compare.",flags:[F.repo(!1),{name:"status",type:"csv",placeholder:"S1,S2",description:`Only tasks in these lifecycle statuses (${TASK_STATUSES.join(", ")}).`},{name:"activity",type:"csv",placeholder:"A1,A2",description:`Only tasks whose engine is in these states (${TASK_ACTIVITY_STATES.join(", ")}). \`permission_needed,error\` = tasks waiting on you.`},{name:"archived",type:"bool",description:"List ONLY archived tasks (`archive` hides a task from the default list; `unarchive` brings it back)."},{name:"fields",type:"csv",placeholder:"F1,F2",description:"Keep only these keys on each task (e.g. `id,title,status,branch`), so a large fleet reads short; a key a task does not carry stays absent. `activeTaskId` and `unresolvableRepos` are unaffected. An unknown name is refused with BAD_FLAG and lists the valid ones."}],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 (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. ${ACTIVITY_STATES_DOC}`,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},CONTEXT_VERB,DIGEST_VERB,AGENT_TURNS_VERB,INSPECT_VERB,READ_OUTPUT_VERB,QUEUE_LIST_VERB,SEARCH_VERB,WATCH_VERB,PORTS_VERB,VIEWERS_VERB,REVIEW_COMMENTS_VERB];import{open,realpath}from"fs/promises";import{extname,join as join2,sep as sep2}from"path";import{isAbsolute as isAbsolute2,normalize}from"path";function flatten(entries,scope){return entries.flatMap((e)=>e.children?.length?flatten(e.children,scope):[{path:e.path,status:e.status,added:e.added??null,deleted:e.deleted??null,scope}])}function worktreeFiles(worktreePath){return listFiles(worktreePath)}async function worktreeDiff(worktreePath,prBaseRef){let base=await resolveBase(worktreePath,prBaseRef),[branch,working]=await Promise.all([base?statusFilesBranch(worktreePath,base):Promise.resolve([]),statusFiles(worktreePath)]);return{base,files:[...flatten(branch,"branch"),...flatten(working,"working")]}}function isWorktreeRelative(path2){return!isAbsolute2(path2)&&!normalize(path2).split(/[\\/]/).includes("..")}var REF_LIST_LIMIT=200,COMMIT_LIST_LIMIT=30;async function listRefs(worktreePath,pattern){let res=await runWorktreeGit(worktreePath,["for-each-ref","--format=%(refname:short)",`--count=${REF_LIST_LIMIT}`,pattern]);return res.status===0?res.stdout.split(`
|
|
22
22
|
`).filter((l)=>l.length>0&&!l.endsWith("/HEAD")):[]}async function worktreeRefs(worktreePath){let[branches,remotes,tags,log]=await Promise.all([listRefs(worktreePath,"refs/heads"),listRefs(worktreePath,"refs/remotes"),listRefs(worktreePath,"refs/tags"),runWorktreeGit(worktreePath,["log",`--max-count=${COMMIT_LIST_LIMIT}`,"--format=%h%x09%s"])]),commits=log.status===0?log.stdout.split(`
|
|
23
|
-
`).filter((l)=>l.includes("\t")).map((l)=>({sha:l.slice(0,l.indexOf("\t")),subject:l.slice(l.indexOf("\t")+1)})):[];return{branches,remotes,tags,commits}}async function checkRef(worktreePath,ref){let typed=ref.trim();if(typed.length===0||typed.startsWith("-")||/[\s\0]/.test(typed))return null;return(await runWorktreeGit(worktreePath,["rev-parse","--verify","--quiet",`${typed}^{commit}`])).status===0?typed:null}async function worktreeDiffFile(worktreePath,path2,scope,prBaseRef,opts={}){if(!isWorktreeRelative(path2))throw new ApiError("path must be relative to the worktree","BAD_ARGS");let{base:asked,...preview}=opts;if(asked!==void 0&&scope!=="task")throw new ApiError("--base only applies to --scope task","BAD_ARGS");if(scope==="working")return loadPreviewData(worktreePath,path2,void 0,preview);let base;if(asked!==void 0){if(base=await checkRef(worktreePath,asked),!base)throw new ApiError(`${asked} is not a commit in this repository`,"BAD_REF")}else base=await resolveBase(worktreePath,prBaseRef);if(!base)throw new ApiError("could not resolve a base branch for this task","NO_BASE");return loadPreviewData(worktreePath,path2,scope==="task"?{base,working:!0}:{base},preview)}var FILE_READ_MAX_BYTES=5242880,MIME={md:"text/markdown",markdown:"text/markdown",html:"text/html",htm:"text/html",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf"};async function realpathOrMissing(path2,shown){try{return await realpath(path2)}catch{throw new ApiError(`${shown} does not exist`,"NOT_FOUND")}}async function readPreviewFile(worktreePath,rel){if(rel===""||rel.includes("\x00")||!isWorktreeRelative(rel))throw new ApiError("path must be relative to the worktree","BAD_ARGS");let root=await realpathOrMissing(worktreePath,"the worktree"),real=await realpathOrMissing(join2(worktreePath,rel),rel);if(!real.startsWith(root.endsWith(sep2)?root:root+sep2))throw new ApiError("path is outside the worktree","BAD_ARGS");let mime=MIME[extname(real).slice(1).toLowerCase()];if(!mime)throw new ApiError("only markdown, HTML, SVG, images and PDFs preview","NOT_PREVIEWABLE",{hint:"read other files through the Files pane's diff or code view"});let file=await open(real,"r");try{let{size,isFile}=await file.stat().then((s)=>({size:s.size,isFile:s.isFile()}));if(!isFile)throw new ApiError(`${rel} is not a regular file`,"NOT_PREVIEWABLE");if(size>FILE_READ_MAX_BYTES)throw new ApiError(`${rel} is ${size} bytes; a preview reads at most ${FILE_READ_MAX_BYTES}`,"TOO_LARGE",{size});let buffer=Buffer.allocUnsafe(size+1),{bytesRead}=await file.read(buffer,0,size+1,0);if(bytesRead>size)throw new ApiError(`${rel} changed while it was read`,"TOO_LARGE");return{path:rel,mime,size:bytesRead,base64:buffer.subarray(0,bytesRead).toString("base64")}}finally{await file.close()}}async function taskWorktree(ctx){let taskId=ctx.args.require("task-id"),{task}=await daemonOf(ctx).request("task.get",{taskId});if(!task.worktreePath)throw new ApiError(`task ${taskId} has no worktree yet`,"NO_WORKTREE",{hint:"materialize it first",nextCommandArgs:["api","ensure-worktree","--task-id",taskId]});return{path:task.worktreePath,prBaseRef:task.prStatus?.baseRef}}async function readWorktree(ctx,verb,pass,here){let wt=await taskWorktree(ctx),there=linkedWorktree(wt.path);if(!there)return here(wt);let given=pass.flatMap((name)=>{let value=ctx.args.str(name);return value===void 0?[]:[[name,value]]}),params={"task-id":there.taskId,...Object.fromEntries(given)},envelope=await forwardVerb(requireMachine(there.machine),verb,params);if(!envelope.ok)throw new ApiError(envelope.error.message,envelope.error.code,envelope.error.data);return envelope.result}var REVIEW_VERBS=[{name:"worktree-files",group:"read",summary:"List a task's worktree files: tracked plus untracked-not-ignored, worktree-relative. Returns { files }. Runs where the worktree lives, so it reads a task on another registered machine too.",flags:[F.taskId()],handler:(ctx)=>readWorktree(ctx,"worktree-files",[],async(wt)=>({files:await worktreeFiles(wt.path)}))},{name:"worktree-file",group:"read",summary:"Read one previewable file of a task's worktree for a client to render: markdown, HTML, SVG, PNG/JPEG/GIF/WebP or PDF, at most 5 MB. Returns { path, mime, size, base64 }. Confined: a worktree-relative path whose real path (symlinks resolved) stays inside the worktree, else BAD_ARGS; any other type is NOT_PREVIEWABLE, a larger file TOO_LARGE. Runs where the worktree lives, so it reads a task on another registered machine too.",flags:[F.taskId(),{name:"path",type:"string",required:!0,placeholder:"PATH",description:"Worktree-relative file path; absolute or `..` paths are refused."}],handler:(ctx)=>readWorktree(ctx,"worktree-file",["path"],(wt)=>readPreviewFile(wt.path,ctx.args.require("path")))},{name:"worktree-diff",group:"read",summary:"A task's changed files: committed on its branch against the base (`scope: branch`, PR base first), then uncommitted (`scope: working`). Returns { base, files[{ path, status, added, deleted, scope }] }; `base` is null when none resolves.",flags:[F.taskId()],handler:(ctx)=>readWorktree(ctx,"worktree-diff",[],(wt)=>worktreeDiff(wt.path,wt.prBaseRef))},{name:"worktree-diff-file",group:"read",summary:"One changed file's preview in a task's worktree: its uncommitted diff (`--scope working`), its committed diff against the base (`--scope branch`) or everything since the base, uncommitted and untracked work included (`--scope task`). Returns the Files pane's preview data (diff hunks, or the file for a code/binary view).",flags:[F.taskId(),{name:"path",type:"string",required:!0,placeholder:"PATH",description:"Worktree-relative file path; absolute or `..` paths are refused."},{name:"scope",type:"enum",values:["branch","working","task"],required:!0,description:"`working` = uncommitted changes; `branch` = commits since the base; `task` = commits and uncommitted work since the base."},{name:"base",type:"string",placeholder:"REF",description:"With `--scope task`: compare against this branch, tag or commit instead of the task's base. Refused (`BAD_REF`) when it is not a commit in the repository."},{name:"ignore-whitespace",type:"bool",description:"Diff with `git diff -w`: whitespace-only changes drop out. Off by default."}],handler:(ctx)=>readWorktree(ctx,"worktree-diff-file",["path","scope","base","ignore-whitespace"],(wt)=>{let asked=ctx.args.require("scope"),scope=asked==="branch"||asked==="task"?asked:"working";return worktreeDiffFile(wt.path,ctx.args.require("path"),scope,wt.prBaseRef,{ignoreWhitespace:ctx.args.bool("ignore-whitespace")===!0,...ctx.args.str("base")?{base:ctx.args.str("base")}:{}})})},{name:"worktree-refs",group:"read",summary:"What a task's diff can be compared against: its repository's local branches, remote branches and tags, plus the worktree branch's recent commits. Returns { branches, remotes, tags, commits[{ sha, subject }] }.",flags:[F.taskId()],handler:(ctx)=>readWorktree(ctx,"worktree-refs",[],(wt)=>worktreeRefs(wt.path))}];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:"author",type:"string",placeholder:"USER",description:"Only items opened by 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("author")?{author:ctx.args.str("author")}:{},...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")}:{}})}];async function checkpointList(ctx){let taskId=ctx.args.require("task-id"),res=await daemonOf(ctx).request("task.checkpointList",{taskId});return{taskId,...res}}async function checkpoint(ctx){let taskId=ctx.args.require("task-id"),res=await daemonOf(ctx).request("task.checkpoint",{taskId});return{taskId,...res}}async function rewind(ctx){let taskId=ctx.args.require("task-id"),to=ctx.args.int("to"),res=await daemonOf(ctx).request("task.rewind",{taskId,to,...ctx.args.bool("force")===!0?{force:!0}:{}});return{taskId,...res}}var CONCURRENCY=4;function ownedCheckouts(task){if((task.kind??"task")!=="task"||task.sharesWorkspaceOf)return[];let primary=(task.worktreePath??"").trim(),extras=(task.extraRepos??[]).map((r)=>(r.worktreePath??"").trim()),repo=canonicalize(gitRepoOf(task));return[primary,...extras].filter((p)=>p.length>0&&!samePath(canonicalize(p),repo))}function sum(values){let total=0;for(let v of values){if(v===null)return null;total+=v}return total}async function mapLimited(items,limit,fn){let out=Array(items.length),next=0,worker=async()=>{while(next<items.length){let i=next++;out[i]=await fn(items[i])}};return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),out}async function usageRow(ctx,task){let paths=ownedCheckouts(task),checkouts=[];for(let path2 of paths)checkouts.push({path:path2,...await ctx.runtime.measureCheckout(path2)});let present=checkouts.filter((c)=>c.exists!==!1);return{taskId:task.id,title:task.title,branch:task.branch,archived:task.archived===!0,status:task.status,updatedAt:task.updatedAt,prLifecycle:task.prStatus?.lifecycle??null,bytes:sum(present.map((c)=>c.bytes)),ignoredBytes:sum(present.map((c)=>c.ignoredBytes)),checkouts}}function bySize(a,b){if(a.bytes===null||b.bytes===null)return a.bytes===null?b.bytes===null?0:1:-1;return b.bytes-a.bytes}var DAY_MS=86400000;function candidateFilter(ctx){let idleDays=ctx.args.nonNegativeInt("idle-days"),merged=ctx.args.bool("merged");if(idleDays===void 0&&!merged)return null;let cutoff=idleDays===void 0?null:Date.now()-idleDays*DAY_MS;return(task)=>{if(merged&&task.prStatus?.lifecycle!=="merged")return!1;if(cutoff===null)return!0;let touched=Date.parse(task.updatedAt);return Number.isFinite(touched)&&touched<=cutoff}}async function handleWorktreeUsage(ctx){let daemon=daemonOf(ctx),keep=candidateFilter(ctx),taskId=ctx.args.str("task-id");if(taskId!==void 0){if(keep)throw new ApiError("--idle-days and --merged filter the full list, not --task-id","BAD_FLAG");let{task}=await daemon.request("task.get",{taskId});if(ownedCheckouts(task).length===0)throw new ApiError(`task ${taskId} owns no worktree`,"NO_WORKTREE",{hint:"a project's own checkout, a directory task and a shared child use a directory they don't own"});return usageRow(ctx,task)}let owners=((await daemon.request("task.list")).tasks??[]).filter((t)=>ownedCheckouts(t).length>0&&!t.deletion&&(!keep||keep(t))),rows=(await mapLimited(owners,CONCURRENCY,(t)=>usageRow(ctx,t))).filter((r)=>r.checkouts.some((c)=>c.exists!==!1));return rows.sort(bySize),{tasks:rows,bytes:sum(rows.map((r)=>r.bytes)),ignoredBytes:sum(rows.map((r)=>r.ignoredBytes))}}var WORKTREE_USAGE_VERB={name:"worktree-usage",group:"worktree",summary:"Disk used by each task's own worktrees (extra repos included), largest first, archived tasks too \u2014 what `remove-worktree` would reclaim. `ignoredBytes` is the gitignored part (dependencies, build output). A project's own checkout, a directory task and a shared child are never listed; a task whose worktree is not on disk is left out. --idle-days and --merged narrow the list to cleanup candidates (both given: both must hold); totals cover only what is listed. Returns { tasks: [{ taskId, title, branch, archived, status, updatedAt, prLifecycle, bytes, ignoredBytes, checkouts: [{ path, exists, bytes, ignoredBytes }] }], bytes, ignoredBytes }; with --task-id, that one row. A null size means it could not be measured, never zero.",flags:[F.taskId(!1),{name:"idle-days",type:"uint",placeholder:"N",description:"Only tasks whose record has not changed in at least N days."},{name:"merged",type:"bool",description:"Only tasks whose pull request Rove last saw merged."}],handler:handleWorktreeUsage};var CONCURRENCY2=4,ENGINE_BUSY=new Set(["running","permission_needed"]);function skipCode(err){if(err instanceof ApiError)return{code:err.code,message:err.message};let message=errorMessage(err),split=splitDaemonCode(message);return split?{code:split.code,message:split.rest.trim()||message}:{code:"REMOVE_FAILED",message}}async function handleWorktreeReclaim(ctx){let keep=candidateFilter(ctx);if(!keep)throw new ApiError("worktree-reclaim needs --merged or --idle-days: it never removes every worktree","BAD_FLAG",{hint:"preview with --dry-run, e.g. `worktree-reclaim --merged --dry-run`",nextCommandArgs:["api","worktree-reclaim","--merged","--dry-run"]});let dryRun=ctx.args.bool("dry-run")??!1,daemon=daemonOf(ctx),tasks=(await daemon.request("task.list")).tasks??[],owners=tasks.filter((t)=>ownedCheckouts(t).length>0&&!t.deletion&&keep(t)),activity=await readActivityRegistry(daemon);if(!activity)throw new ApiError("could not read engine activity, so which worktrees are in use is unknown","BAD_DAEMON",{hint:"remove them one at a time with `remove-worktree --task-id`",nextCommandArgs:["api","inspect"]});let measured=await mapLimited(owners,CONCURRENCY2,async(task)=>{let worktreePath=(task.worktreePath??"").trim(),usage=worktreePath?await ctx.runtime.measureCheckout(worktreePath):null;return{task,worktreePath,exists:usage?.exists,bytes:usage?.bytes??null}}),removed=[],skipped=[];for(let{task,worktreePath,exists,bytes}of measured){if(!worktreePath||exists===!1)continue;let row={taskId:task.id,title:task.title,branch:task.branch,worktreePath,bytes},skip=(code,message)=>skipped.push({...row,code,message});if((task.extraRepos??[]).length>0){skip("MULTI_REPO","spans several repos; `remove-worktree` or `delete` it on its own");continue}if(ENGINE_BUSY.has(activity.tasks[task.id]?.state??"idle")){skip("TASK_BUSY","an engine is still working or waiting on you in it");continue}if(tasksAtWorktreePath(tasks,worktreePath).length>1||tasks.some((t)=>t.sharesWorkspaceOf===task.id)){skip("WORKTREE_SHARED","another task shares this checkout");continue}try{if(removableWorktree(ctx,task),dryRun){removed.push(row);continue}let res=await daemon.request("worktree.remove",{path:worktreePath,force:!1});removed.push(res.residue?{...row,residue:res.residue}:row)}catch(err){let{code,message}=skipCode(err);skip(code,message)}}let bySize2=(a,b)=>(b.bytes??-1)-(a.bytes??-1);return removed.sort(bySize2),skipped.sort(bySize2),{dryRun,removed,skipped,bytes:sum(removed.map((r)=>r.bytes))}}var WORKTREE_RECLAIM_VERB={name:"worktree-reclaim",group:"worktree",summary:"Remove the worktree of every cleanup candidate at once \u2014 the tasks `worktree-usage` lists with the same --merged / --idle-days filters (at least one is required) \u2014 keeping each task and its branch, so `ensure-worktree` can bring a checkout back. Never forced: a checkout with uncommitted, untracked or gitignored work, a task whose engine is running or waiting on you, a multi-repo task, a shared directory and the caller's own worktree are skipped with a code, and the rest are still removed. --dry-run reports what would be removed and changes nothing; it does not run the dirty check, which only the removal itself makes. Returns { dryRun, removed: [{ taskId, title, branch, worktreePath, bytes, residue? }], skipped: [{ \u2026same, code, message }], bytes } \u2014 `bytes` is what the removed checkouts took, null when one could not be measured.",flags:[{name:"idle-days",type:"uint",placeholder:"N",description:"Only tasks whose record has not changed in at least N days."},{name:"merged",type:"bool",description:"Only tasks whose pull request Rove last saw merged."},{name:"dry-run",type:"bool",description:"Report what would be removed without removing anything."}],handler:handleWorktreeReclaim};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:"checkpoint-list",group:"worktree",summary:"List a task's checkpoints \u2014 file-only undo points of its worktree, taken automatically when an engine turn completes (and by `checkpoint`). Newest last. Managed tasks only (not a project's main checkout or a dir task). Checkpoints belong to the workspace owner: a child sharing its parent's directory (`add --no-worktree`) lists its owner's, and `workspaceTaskId` names whose. Returns { taskId, workspaceTaskId, checkpoints: [{ n, ref, commit, tree, at, tabId? }] }; each is the git ref refs/rove/checkpoints/<workspaceTaskId>/<n>, so `git diff <ref>` works too.",flags:[F.taskId()],handler:checkpointList},{name:"checkpoint",group:"worktree",summary:"Snapshot a task's worktree now (tracked edits and untracked files, minus gitignored ones) as the next checkpoint, under the workspace owner's id for a shared child. Never touches the branch, HEAD or index. Skipped when the tree equals the latest checkpoint. The newest 100 per workspace are kept. Returns { taskId, workspaceTaskId, created, checkpoint, uncaptured? } \u2014 `uncaptured` names nested repos/submodules whose contents are not captured.",flags:[F.taskId()],handler:checkpoint},{name:"rewind",group:"worktree",summary:"Restore a task's worktree files to checkpoint N of its workspace owner (`workspaceTaskId`; a shared child acts on its owner's history) \u2014 files only: the branch, HEAD and the conversation are not rewound, and the index is reset to HEAD. The current state is checkpointed first, so a rewind is undoable: `rewind --to <undo.n>` goes back. Files created after N are deleted, files deleted since are restored, gitignored files are left alone. Refused with TASK_BUSY while any engine sharing the workspace (owner or child) is mid-turn or waiting on you, unless --force. Returns { taskId, workspaceTaskId, target, undo, uncaptured }.",flags:[F.taskId(),{name:"to",type:"int",required:!0,placeholder:"N",description:"Checkpoint number to restore (from `checkpoint-list`)."},{name:"force",type:"bool",description:"Rewind even while the engine is running or waiting on permission."}],handler:rewind},{name:"export-branch",group:"worktree",summary:"Copy a layerfs task's git branch out of its sandbox into the host repo as the same branch name (a `git bundle` of the commits past where the task started, fetched without force). Commit inside the task first: only commits travel. Land, push or open a PR from the host repo afterwards. Refused with EXPORT_UNSUPPORTED for any other backend, whose branch is already in the repo. Returns { taskId, workspaceTaskId, branch, commit }.",flags:[F.taskId()],handler:async(ctx)=>{let taskId=ctx.args.require("task-id");return{taskId,...await simpleRpc(ctx,"task.exportBranch",{taskId})}}},WORKTREE_USAGE_VERB,WORKTREE_RECLAIM_VERB,{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"]},spawn:{hint:"spawn was folded into `add`, which nests the new task under the calling session: --no-worktree shares the parent's directory, --parent ID names another parent, --no-parent opts out",nextCommandArgs:["api","add","--help"]},"set-vendor":{hint:"set-vendor was replaced by `update --command`, which takes the engine's raw launch command (an engine id from `engine-list`, or a full command line)",nextCommandArgs:["api","update","--help"]},...Object.fromEntries([["rename","--title (with --tab to rename a tab)"],["set-branch","--branch"],["set-command","--command"],["set-effort","--effort (was --level)"],["set-model","--model"],["set-status","--status and --report-*"],["pin","--pinned true|false"]].map(([verb,flag])=>[verb,{hint:`${verb} was folded into \`update\`: pass ${flag}; one update call can change several fields at once`,nextCommandArgs:["api","update","--help"]}])),"issue-set-status":{hint:"issue-set-status was folded into `issue-update`: pass --status",nextCommandArgs:["api","issue-update","--help"]},"routine-set-enabled":{hint:"routine-set-enabled was folded into `routine-update`: pass --enabled true|false",nextCommandArgs:["api","routine-update","--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,...REVIEW_VERBS,REPO_MATCH_VERB,REPO_LIST_VERB,PUBLISH_VERB,PR_ATTACH_VERB,DELIVERIES_VERB,SHOULD_RUN_VERB,...CREATE_VERBS,...DRIVE_VERBS,REPORT_VERB,ATTENTION_DISMISS_VERB,...GATE_VERBS,...FEEDBACK_VERBS,...ISSUE_VERBS,...ROUTINE_VERBS,...WORK_ITEM_VERBS,...EDIT_VERBS,TODO_VERB,...LIFECYCLE_VERBS,...WORKTREE_VERBS,...GITHUB_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)}
|
|
23
|
+
`).filter((l)=>l.includes("\t")).map((l)=>({sha:l.slice(0,l.indexOf("\t")),subject:l.slice(l.indexOf("\t")+1)})):[];return{branches,remotes,tags,commits}}async function checkRef(worktreePath,ref){let typed=ref.trim();if(typed.length===0||typed.startsWith("-")||/[\s\0]/.test(typed))return null;return(await runWorktreeGit(worktreePath,["rev-parse","--verify","--quiet",`${typed}^{commit}`])).status===0?typed:null}async function worktreeDiffFile(worktreePath,path2,scope,prBaseRef,opts={}){if(!isWorktreeRelative(path2))throw new ApiError("path must be relative to the worktree","BAD_ARGS");let{base:asked,...preview}=opts;if(asked!==void 0&&scope!=="task")throw new ApiError("--base only applies to --scope task","BAD_ARGS");if(scope==="working")return loadPreviewData(worktreePath,path2,void 0,preview);let base;if(asked!==void 0){if(base=await checkRef(worktreePath,asked),!base)throw new ApiError(`${asked} is not a commit in this repository`,"BAD_REF")}else base=await resolveBase(worktreePath,prBaseRef);if(!base)throw new ApiError("could not resolve a base branch for this task","NO_BASE");return loadPreviewData(worktreePath,path2,scope==="task"?{base,working:!0}:{base},preview)}var FILE_READ_MAX_BYTES=5242880,MIME={md:"text/markdown",markdown:"text/markdown",html:"text/html",htm:"text/html",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",pdf:"application/pdf"};async function realpathOrMissing(path2,shown){try{return await realpath(path2)}catch{throw new ApiError(`${shown} does not exist`,"NOT_FOUND")}}async function readPreviewFile(worktreePath,rel){if(rel===""||rel.includes("\x00")||!isWorktreeRelative(rel))throw new ApiError("path must be relative to the worktree","BAD_ARGS");let root=await realpathOrMissing(worktreePath,"the worktree"),real=await realpathOrMissing(join2(worktreePath,rel),rel);if(!real.startsWith(root.endsWith(sep2)?root:root+sep2))throw new ApiError("path is outside the worktree","BAD_ARGS");let mime=MIME[extname(real).slice(1).toLowerCase()];if(!mime)throw new ApiError("only markdown, HTML, SVG, images and PDFs preview","NOT_PREVIEWABLE",{hint:"read other files through the Files pane's diff or code view"});let file=await open(real,"r");try{let{size,isFile}=await file.stat().then((s)=>({size:s.size,isFile:s.isFile()}));if(!isFile)throw new ApiError(`${rel} is not a regular file`,"NOT_PREVIEWABLE");if(size>FILE_READ_MAX_BYTES)throw new ApiError(`${rel} is ${size} bytes; a preview reads at most ${FILE_READ_MAX_BYTES}`,"TOO_LARGE",{size});let buffer=Buffer.allocUnsafe(size+1),{bytesRead}=await file.read(buffer,0,size+1,0);if(bytesRead>size)throw new ApiError(`${rel} changed while it was read`,"TOO_LARGE");return{path:rel,mime,size:bytesRead,base64:buffer.subarray(0,bytesRead).toString("base64")}}finally{await file.close()}}async function taskWorktree(ctx){let taskId=ctx.args.require("task-id"),{task}=await daemonOf(ctx).request("task.get",{taskId});if(!task.worktreePath)throw new ApiError(`task ${taskId} has no worktree yet`,"NO_WORKTREE",{hint:"materialize it first",nextCommandArgs:["api","ensure-worktree","--task-id",taskId]});return{path:task.worktreePath,prBaseRef:task.prStatus?.baseRef}}async function readWorktree(ctx,verb,pass,here){let wt=await taskWorktree(ctx),there=linkedWorktree(wt.path);if(!there)return here(wt);let given=pass.flatMap((name)=>{let value=ctx.args.str(name);return value===void 0?[]:[[name,value]]}),params={"task-id":there.taskId,...Object.fromEntries(given)},envelope=await forwardVerb(requireMachine(there.machine),verb,params);if(!envelope.ok)throw new ApiError(envelope.error.message,envelope.error.code,envelope.error.data);return envelope.result}var REVIEW_VERBS=[{name:"worktree-files",group:"read",summary:"List a task's worktree files: tracked plus untracked-not-ignored, worktree-relative. Returns { files }. Runs where the worktree lives, so it reads a task on another registered machine too.",flags:[F.taskId()],handler:(ctx)=>readWorktree(ctx,"worktree-files",[],async(wt)=>({files:await worktreeFiles(wt.path)}))},{name:"worktree-file",group:"read",summary:"Read one previewable file of a task's worktree for a client to render: markdown, HTML, SVG, PNG/JPEG/GIF/WebP or PDF, at most 5 MB. Returns { path, mime, size, base64 }. Confined: a worktree-relative path whose real path (symlinks resolved) stays inside the worktree, else BAD_ARGS; any other type is NOT_PREVIEWABLE, a larger file TOO_LARGE. Runs where the worktree lives, so it reads a task on another registered machine too.",flags:[F.taskId(),{name:"path",type:"string",required:!0,placeholder:"PATH",description:"Worktree-relative file path; absolute or `..` paths are refused."}],handler:(ctx)=>readWorktree(ctx,"worktree-file",["path"],(wt)=>readPreviewFile(wt.path,ctx.args.require("path")))},{name:"worktree-diff",group:"read",summary:"A task's changed files: committed on its branch against the base (`scope: branch`, PR base first), then uncommitted (`scope: working`). Returns { base, files[{ path, status, added, deleted, scope }] }; `base` is null when none resolves.",flags:[F.taskId()],handler:(ctx)=>readWorktree(ctx,"worktree-diff",[],(wt)=>worktreeDiff(wt.path,wt.prBaseRef))},{name:"worktree-diff-file",group:"read",summary:"One changed file's preview in a task's worktree: its uncommitted diff (`--scope working`), its committed diff against the base (`--scope branch`) or everything since the base, uncommitted and untracked work included (`--scope task`). Returns the Files pane's preview data (diff hunks, or the file for a code/binary view).",flags:[F.taskId(),{name:"path",type:"string",required:!0,placeholder:"PATH",description:"Worktree-relative file path; absolute or `..` paths are refused."},{name:"scope",type:"enum",values:["branch","working","task"],required:!0,description:"`working` = uncommitted changes; `branch` = commits since the base; `task` = commits and uncommitted work since the base."},{name:"base",type:"string",placeholder:"REF",description:"With `--scope task`: compare against this branch, tag or commit instead of the task's base. Refused (`BAD_REF`) when it is not a commit in the repository."},{name:"ignore-whitespace",type:"bool",description:"Diff with `git diff -w`: whitespace-only changes drop out. Off by default."}],handler:(ctx)=>readWorktree(ctx,"worktree-diff-file",["path","scope","base","ignore-whitespace"],(wt)=>{let asked=ctx.args.require("scope"),scope=asked==="branch"||asked==="task"?asked:"working";return worktreeDiffFile(wt.path,ctx.args.require("path"),scope,wt.prBaseRef,{ignoreWhitespace:ctx.args.bool("ignore-whitespace")===!0,...ctx.args.str("base")?{base:ctx.args.str("base")}:{}})})},{name:"worktree-refs",group:"read",summary:"What a task's diff can be compared against: its repository's local branches, remote branches and tags, plus the worktree branch's recent commits. Returns { branches, remotes, tags, commits[{ sha, subject }] }.",flags:[F.taskId()],handler:(ctx)=>readWorktree(ctx,"worktree-refs",[],(wt)=>worktreeRefs(wt.path))}];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:"author",type:"string",placeholder:"USER",description:"Only items opened by 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("author")?{author:ctx.args.str("author")}:{},...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")}:{}})}];async function checkpointList(ctx){let taskId=ctx.args.require("task-id"),res=await daemonOf(ctx).request("task.checkpointList",{taskId});return{taskId,...res}}async function checkpoint(ctx){let taskId=ctx.args.require("task-id"),res=await daemonOf(ctx).request("task.checkpoint",{taskId});return{taskId,...res}}async function rewind(ctx){let taskId=ctx.args.require("task-id"),to=ctx.args.int("to"),res=await daemonOf(ctx).request("task.rewind",{taskId,to,...ctx.args.bool("force")===!0?{force:!0}:{}});return{taskId,...res}}var CONCURRENCY=4;function ownedCheckouts(task){if((task.kind??"task")!=="task"||task.sharesWorkspaceOf)return[];let primary=(task.worktreePath??"").trim(),extras=(task.extraRepos??[]).map((r)=>(r.worktreePath??"").trim()),repo=canonicalize(gitRepoOf(task));return[primary,...extras].filter((p)=>p.length>0&&!samePath(canonicalize(p),repo))}function sum(values){let total=0;for(let v of values){if(v===null)return null;total+=v}return total}async function mapLimited(items,limit,fn){let out=Array(items.length),next=0,worker=async()=>{while(next<items.length){let i=next++;out[i]=await fn(items[i])}};return await Promise.all(Array.from({length:Math.min(limit,items.length)},worker)),out}async function usageRow(ctx,task){let paths=ownedCheckouts(task),checkouts=[];for(let path2 of paths)checkouts.push({path:path2,...await ctx.runtime.measureCheckout(path2)});let present=checkouts.filter((c)=>c.exists!==!1);return{taskId:task.id,title:task.title,branch:task.branch,archived:task.archived===!0,status:task.status,updatedAt:task.updatedAt,prLifecycle:task.prStatus?.lifecycle??null,bytes:sum(present.map((c)=>c.bytes)),ignoredBytes:sum(present.map((c)=>c.ignoredBytes)),checkouts}}function bySize(a,b){if(a.bytes===null||b.bytes===null)return a.bytes===null?b.bytes===null?0:1:-1;return b.bytes-a.bytes}var DAY_MS=86400000;function candidateFilter(ctx){let idleDays=ctx.args.nonNegativeInt("idle-days"),merged=ctx.args.bool("merged");if(idleDays===void 0&&!merged)return null;let cutoff=idleDays===void 0?null:Date.now()-idleDays*DAY_MS;return(task)=>{if(merged&&task.prStatus?.lifecycle!=="merged")return!1;if(cutoff===null)return!0;let touched=Date.parse(task.updatedAt);return Number.isFinite(touched)&&touched<=cutoff}}async function handleWorktreeUsage(ctx){let daemon=daemonOf(ctx),keep=candidateFilter(ctx),taskId=ctx.args.str("task-id");if(taskId!==void 0){if(keep)throw new ApiError("--idle-days and --merged filter the full list, not --task-id","BAD_FLAG");let{task}=await daemon.request("task.get",{taskId});if(ownedCheckouts(task).length===0)throw new ApiError(`task ${taskId} owns no worktree`,"NO_WORKTREE",{hint:"a project's own checkout, a directory task and a shared child use a directory they don't own"});return usageRow(ctx,task)}let owners=((await daemon.request("task.list")).tasks??[]).filter((t)=>ownedCheckouts(t).length>0&&!t.deletion&&(!keep||keep(t))),rows=(await mapLimited(owners,CONCURRENCY,(t)=>usageRow(ctx,t))).filter((r)=>r.checkouts.some((c)=>c.exists!==!1));return rows.sort(bySize),{tasks:rows,bytes:sum(rows.map((r)=>r.bytes)),ignoredBytes:sum(rows.map((r)=>r.ignoredBytes))}}var WORKTREE_USAGE_VERB={name:"worktree-usage",group:"worktree",summary:"Disk used by each task's own worktrees (extra repos included), largest first, archived tasks too \u2014 what `remove-worktree` would reclaim. `ignoredBytes` is the gitignored part (dependencies, build output). A project's own checkout, a directory task and a shared child are never listed; a task whose worktree is not on disk is left out. --idle-days and --merged narrow the list to cleanup candidates (both given: both must hold); totals cover only what is listed. Returns { tasks: [{ taskId, title, branch, archived, status, updatedAt, prLifecycle, bytes, ignoredBytes, checkouts: [{ path, exists, bytes, ignoredBytes }] }], bytes, ignoredBytes }; with --task-id, that one row. A null size means it could not be measured, never zero.",flags:[F.taskId(!1),{name:"idle-days",type:"uint",placeholder:"N",description:"Only tasks whose record has not changed in at least N days."},{name:"merged",type:"bool",description:"Only tasks whose pull request Rove last saw merged."}],handler:handleWorktreeUsage};var CONCURRENCY2=4,ENGINE_BUSY=new Set(["running","permission_needed"]);function skipCode(err){if(err instanceof ApiError)return{code:err.code,message:err.message};let message=errorMessage(err),split=splitDaemonCode(message);return split?{code:split.code,message:split.rest.trim()||message}:{code:"REMOVE_FAILED",message}}async function handleWorktreeReclaim(ctx){let keep=candidateFilter(ctx);if(!keep)throw new ApiError("worktree-reclaim needs --merged or --idle-days: it never removes every worktree","BAD_FLAG",{hint:"preview with --dry-run, e.g. `worktree-reclaim --merged --dry-run`",nextCommandArgs:["api","worktree-reclaim","--merged","--dry-run"]});let dryRun=ctx.args.bool("dry-run")??!1,daemon=daemonOf(ctx),tasks=(await daemon.request("task.list")).tasks??[],owners=tasks.filter((t)=>ownedCheckouts(t).length>0&&!t.deletion&&keep(t)),activity=await readActivityRegistry(daemon);if(!activity)throw new ApiError("could not read engine activity, so which worktrees are in use is unknown","BAD_DAEMON",{hint:"remove them one at a time with `remove-worktree --task-id`",nextCommandArgs:["api","inspect"]});let measured=await mapLimited(owners,CONCURRENCY2,async(task)=>{let worktreePath=(task.worktreePath??"").trim(),usage=worktreePath?await ctx.runtime.measureCheckout(worktreePath):null;return{task,worktreePath,exists:usage?.exists,bytes:usage?.bytes??null}}),removed=[],skipped=[];for(let{task,worktreePath,exists,bytes}of measured){if(!worktreePath||exists===!1)continue;let row={taskId:task.id,title:task.title,branch:task.branch,worktreePath,bytes},skip=(code,message)=>skipped.push({...row,code,message});if((task.extraRepos??[]).length>0){skip("MULTI_REPO","spans several repos; `remove-worktree` or `delete` it on its own");continue}if(ENGINE_BUSY.has(activity.tasks[task.id]?.state??"idle")){skip("TASK_BUSY","an engine is still working or waiting on you in it");continue}if(tasksAtWorktreePath(tasks,worktreePath).length>1||tasks.some((t)=>t.sharesWorkspaceOf===task.id)){skip("WORKTREE_SHARED","another task shares this checkout");continue}try{if(removableWorktree(ctx,task),dryRun){removed.push(row);continue}let res=await daemon.request("worktree.remove",{path:worktreePath,force:!1});removed.push(res.residue?{...row,residue:res.residue}:row)}catch(err){let{code,message}=skipCode(err);skip(code,message)}}let bySize2=(a,b)=>(b.bytes??-1)-(a.bytes??-1);return removed.sort(bySize2),skipped.sort(bySize2),{dryRun,removed,skipped,bytes:sum(removed.map((r)=>r.bytes))}}var WORKTREE_RECLAIM_VERB={name:"worktree-reclaim",group:"worktree",summary:"Remove the worktree of every cleanup candidate at once \u2014 the tasks `worktree-usage` lists with the same --merged / --idle-days filters (at least one is required) \u2014 keeping each task and its branch, so `ensure-worktree` can bring a checkout back. Never forced: a checkout with uncommitted, untracked or gitignored work, a task whose engine is running or waiting on you, a multi-repo task, a shared directory and the caller's own worktree are skipped with a code, and the rest are still removed. --dry-run reports what would be removed and changes nothing; it does not run the dirty check, which only the removal itself makes. Returns { dryRun, removed: [{ taskId, title, branch, worktreePath, bytes, residue? }], skipped: [{ \u2026same, code, message }], bytes } \u2014 `bytes` is what the removed checkouts took, null when one could not be measured.",flags:[{name:"idle-days",type:"uint",placeholder:"N",description:"Only tasks whose record has not changed in at least N days."},{name:"merged",type:"bool",description:"Only tasks whose pull request Rove last saw merged."},{name:"dry-run",type:"bool",description:"Report what would be removed without removing anything."}],handler:handleWorktreeReclaim};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:"checkpoint-list",group:"worktree",summary:"List a task's checkpoints \u2014 file-only undo points of its worktree, taken automatically when an engine turn completes (and by `checkpoint`). Newest last. Managed tasks only (not a project's main checkout or a dir task). Checkpoints belong to the workspace owner: a child sharing its parent's directory (`add --no-worktree`) lists its owner's, and `workspaceTaskId` names whose. Returns { taskId, workspaceTaskId, checkpoints: [{ n, ref, commit, tree, at, tabId? }] }; each is the git ref refs/rove/checkpoints/<workspaceTaskId>/<n>, so `git diff <ref>` works too.",flags:[F.taskId()],handler:checkpointList},{name:"checkpoint",group:"worktree",summary:"Snapshot a task's worktree now (tracked edits and untracked files, minus gitignored ones) as the next checkpoint, under the workspace owner's id for a shared child. Never touches the branch, HEAD or index. Skipped when the tree equals the latest checkpoint. The newest 100 per workspace are kept. Returns { taskId, workspaceTaskId, created, checkpoint, uncaptured? } \u2014 `uncaptured` names nested repos/submodules whose contents are not captured.",flags:[F.taskId()],handler:checkpoint},{name:"rewind",group:"worktree",summary:"Restore a task's worktree files to checkpoint N of its workspace owner (`workspaceTaskId`; a shared child acts on its owner's history) \u2014 files only: the branch, HEAD and the conversation are not rewound, and the index is reset to HEAD. The current state is checkpointed first, so a rewind is undoable: `rewind --to <undo.n>` goes back. Files created after N are deleted, files deleted since are restored, gitignored files are left alone. Refused with TASK_BUSY while any engine sharing the workspace (owner or child) is mid-turn or waiting on you, unless --force. Returns { taskId, workspaceTaskId, target, undo, uncaptured }.",flags:[F.taskId(),{name:"to",type:"int",required:!0,placeholder:"N",description:"Checkpoint number to restore (from `checkpoint-list`)."},{name:"force",type:"bool",description:"Rewind even while the engine is running or waiting on permission."}],handler:rewind},{name:"export-branch",group:"worktree",summary:"Copy a layerfs task's git branch out of its sandbox into the host repo as the same branch name (a `git bundle` of the commits past where the task started, fetched without force). Commit inside the task first: only commits travel. Land, push or open a PR from the host repo afterwards. Refused with EXPORT_UNSUPPORTED for any other backend, whose branch is already in the repo. Returns { taskId, workspaceTaskId, branch, commit }.",flags:[F.taskId()],handler:async(ctx)=>{let taskId=ctx.args.require("task-id");return{taskId,...await simpleRpc(ctx,"task.exportBranch",{taskId})}}},WORKTREE_USAGE_VERB,WORKTREE_RECLAIM_VERB,{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"]},spawn:{hint:"spawn was folded into `add`, which nests the new task under the calling session: --no-worktree shares the parent's directory, --parent ID names another parent, --no-parent opts out",nextCommandArgs:["api","add","--help"]},"set-vendor":{hint:"set-vendor was replaced by `update --command`, which takes the engine's raw launch command (an engine id from `engine-list`, or a full command line)",nextCommandArgs:["api","update","--help"]},...Object.fromEntries([["rename","--title (with --tab to rename a tab)"],["set-branch","--branch"],["set-command","--command"],["set-effort","--effort (was --level)"],["set-model","--model"],["set-status","--status and --report-*"],["pin","--pinned true|false"]].map(([verb,flag])=>[verb,{hint:`${verb} was folded into \`update\`: pass ${flag}; one update call can change several fields at once`,nextCommandArgs:["api","update","--help"]}])),"issue-set-status":{hint:"issue-set-status was folded into `issue-update`: pass --status",nextCommandArgs:["api","issue-update","--help"]},"routine-set-enabled":{hint:"routine-set-enabled was folded into `routine-update`: pass --enabled true|false",nextCommandArgs:["api","routine-update","--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,...REVIEW_VERBS,REPO_MATCH_VERB,REPO_LIST_VERB,PUBLISH_VERB,PR_ATTACH_VERB,DELIVERIES_VERB,SHOULD_RUN_VERB,...CREATE_VERBS,...DRIVE_VERBS,REPORT_VERB,ATTENTION_DISMISS_VERB,...GATE_VERBS,...FEEDBACK_VERBS,...ISSUE_VERBS,...ROUTINE_VERBS,...WORK_ITEM_VERBS,...EDIT_VERBS,TODO_VERB,...LIFECYCLE_VERBS,...WORKTREE_VERBS,...GITHUB_VERBS,MACHINE_UPDATE_VERB],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)}
|
|
24
24
|
export{REPEAT_SEP,parseFlags,validateAgainstSpec,VerbArgs,parseAgentsSpec,buildCountPlan,API_SCHEMA_VERSION,verbSchema,schemaIndex,fullSchema,verbHelp,apiUsage,deliverPrompt,defaultApiRuntime,buildContext,loadContext,worktreeDiff,worktreeRefs,checkRef,VERB_ALIASES,unknownVerbError,VERBS,API_VERBS,VERB_GROUPS,findVerb};
|