@sma1lboy/rove 0.9.285 → 0.9.286-next.209
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-ga4q9t6j.js → chunk-05vg85n7.js} +1 -1
- package/dist/cli/chunk-0kc4pd1d.js +2 -0
- package/dist/cli/chunk-0mw4pd9k.js +5 -0
- package/dist/cli/{chunk-jbgnvmen.js → chunk-10qdd96d.js} +1 -1
- package/dist/cli/chunk-12619320.js +2 -0
- package/dist/cli/{chunk-ggjwv4wx.js → chunk-12vmzp9q.js} +1 -1
- package/dist/cli/chunk-1g3mm15p.js +6 -0
- package/dist/cli/{chunk-44ya692y.js → chunk-1tmmkk54.js} +1 -1
- package/dist/cli/{chunk-2nqsqc76.js → chunk-21hxxbnv.js} +1 -1
- package/dist/cli/{chunk-rsnjxjff.js → chunk-25cnys7g.js} +1 -1
- package/dist/cli/{chunk-8tm44v9k.js → chunk-2b6nh6z4.js} +1 -1
- package/dist/cli/{chunk-w35escss.js → chunk-2ebc6hrh.js} +3 -3
- package/dist/cli/{chunk-ezjvpbcm.js → chunk-2qxa4wtw.js} +1 -1
- package/dist/cli/{chunk-gzx23swq.js → chunk-2xsf2g02.js} +1 -1
- package/dist/cli/{chunk-dyt6z0hf.js → chunk-38hnq4aq.js} +1 -1
- package/dist/cli/{chunk-9cywjm27.js → chunk-3g85akpp.js} +1 -1
- package/dist/cli/chunk-44msqtz9.js +2 -0
- package/dist/cli/chunk-4d4mb0vs.js +2 -0
- package/dist/cli/{chunk-jkgrmxys.js → chunk-4qhkkyc8.js} +1 -1
- package/dist/cli/{chunk-c34k5fw9.js → chunk-59wn3p37.js} +1 -1
- package/dist/cli/{chunk-qxpxqzsn.js → chunk-6488frgb.js} +3 -3
- package/dist/cli/{chunk-rzdv1xn7.js → chunk-64950ec4.js} +2 -2
- package/dist/cli/{chunk-b9e1p9ah.js → chunk-6627xye7.js} +1 -1
- package/dist/cli/chunk-6jsg9e93.js +2 -0
- package/dist/cli/{chunk-kensctt6.js → chunk-7dd27zx2.js} +1 -1
- package/dist/cli/{chunk-evxv5cxn.js → chunk-7hyv1383.js} +1 -1
- package/dist/cli/{chunk-zqmxjvp7.js → chunk-7vrw0kxr.js} +1 -1
- package/dist/cli/{chunk-zwrma6nn.js → chunk-83jfmryc.js} +4 -4
- package/dist/cli/{chunk-mtpz8a1s.js → chunk-889x8v49.js} +1 -1
- package/dist/cli/{chunk-sddyw966.js → chunk-8qy3wkp8.js} +1 -1
- package/dist/cli/{chunk-dyyd7s8w.js → chunk-9eqts8fy.js} +1 -1
- package/dist/cli/chunk-9gkj63qy.js +2 -0
- package/dist/cli/chunk-9k8f281a.js +2 -0
- package/dist/cli/{chunk-m5fgzb54.js → chunk-aagx78v1.js} +1 -1
- package/dist/cli/{chunk-4j7r3050.js → chunk-ayffb47e.js} +1 -1
- package/dist/cli/chunk-b4ecwjcc.js +2 -0
- package/dist/cli/{chunk-30qkw6b6.js → chunk-b9ea827p.js} +1 -1
- package/dist/cli/chunk-bqfj98de.js +2 -0
- package/dist/cli/{chunk-4hpxk8nt.js → chunk-bwh5y3ra.js} +1 -1
- package/dist/cli/{chunk-f2r8h1sc.js → chunk-bwzeg7tk.js} +1 -1
- package/dist/cli/{chunk-dtb55ekp.js → chunk-bxa9wc61.js} +2 -2
- package/dist/cli/{chunk-8sj76t6r.js → chunk-c0fd63tg.js} +1 -1
- package/dist/cli/chunk-c0r2wf3s.js +2 -0
- package/dist/cli/chunk-cs9w86q1.js +2 -0
- package/dist/cli/{chunk-bqe63559.js → chunk-d5cpwvkj.js} +1 -1
- package/dist/cli/{chunk-5zv1q7by.js → chunk-d6drt08h.js} +1 -1
- package/dist/cli/chunk-dzrrcnqg.js +2 -0
- package/dist/cli/{chunk-4fmrszgk.js → chunk-e7pczqw6.js} +1 -1
- package/dist/cli/{chunk-fmt5hrw3.js → chunk-ensb2qfh.js} +1 -1
- package/dist/cli/{chunk-wm1vtkjt.js → chunk-fb61gtvy.js} +1 -1
- package/dist/cli/{chunk-y60bh5en.js → chunk-ffqja31f.js} +1 -1
- package/dist/cli/{chunk-ma2aq1qp.js → chunk-fv82vwhv.js} +1 -1
- package/dist/cli/chunk-ga80gpqb.js +2 -0
- package/dist/cli/{chunk-tadj24x3.js → chunk-gj8eqt7m.js} +1 -1
- package/dist/cli/{chunk-we49rdrg.js → chunk-gnegn76d.js} +2 -2
- package/dist/cli/chunk-h16qs1y9.js +2 -0
- package/dist/cli/{chunk-jfv4s2v8.js → chunk-hf2ap1e5.js} +2 -2
- package/dist/cli/{chunk-g4ebakrz.js → chunk-hkqcc1t4.js} +1 -1
- package/dist/cli/chunk-j54ekzg2.js +14 -0
- package/dist/cli/chunk-k8y0qbks.js +2 -0
- package/dist/cli/{chunk-by7j1tzd.js → chunk-m26wdf1g.js} +1 -1
- package/dist/cli/{chunk-gbqksy3e.js → chunk-m45b6d19.js} +1 -1
- package/dist/cli/{chunk-mjfsjj8n.js → chunk-mw3bka09.js} +1 -1
- package/dist/cli/chunk-mw6rdm3k.js +2 -0
- package/dist/cli/chunk-ntrep2g8.js +2 -0
- package/dist/cli/{chunk-kk7dx35q.js → chunk-pm46jy62.js} +1 -1
- package/dist/cli/{chunk-r89bws63.js → chunk-psxhek7n.js} +1 -1
- package/dist/cli/{chunk-hvgpsfpr.js → chunk-qbbtvxmk.js} +7 -6
- package/dist/cli/chunk-tpn9gc2k.js +2 -0
- package/dist/cli/chunk-wd9hyz9k.js +2 -0
- package/dist/cli/{chunk-qefrqds0.js → chunk-wpssm9js.js} +1 -1
- package/dist/cli/{chunk-4ja8tvqt.js → chunk-wwes4z56.js} +1 -1
- package/dist/cli/{chunk-e7dd768h.js → chunk-wwpq8gs4.js} +1 -1
- package/dist/cli/{chunk-aamfk80a.js → chunk-wy9h9hsf.js} +1 -1
- package/dist/cli/{chunk-nkvt57nv.js → chunk-x0f8a3ez.js} +5 -3
- package/dist/cli/{chunk-nrmd5j15.js → chunk-x17x38a9.js} +2 -2
- package/dist/cli/{chunk-6vd2fev8.js → chunk-x4yxwa4b.js} +1 -1
- package/dist/cli/{chunk-hvtge15w.js → chunk-xw6kz1v9.js} +1 -1
- package/dist/cli/chunk-yfwn3fj5.js +3 -0
- package/dist/cli/{chunk-t8qd50nw.js → chunk-yqex0gc6.js} +1 -1
- package/dist/cli/{chunk-by6md9e9.js → chunk-yw128fd9.js} +4 -4
- package/dist/cli/chunk-zcbj71t8.js +2 -0
- package/dist/cli/{chunk-42z85xck.js → chunk-zj6grp6a.js} +1 -1
- package/dist/cli/{chunk-2cx12te3.js → chunk-zr220zqb.js} +1 -1
- package/dist/cli/index.js +3 -3
- package/dist/skills/rove/SKILL.md +1 -1
- package/dist/skills/rove/references/api-flags.md +3 -3
- package/dist/web/assets/{index-BVOfppkn.css → index-4JYST4_M.css} +1 -1
- package/dist/web/assets/{index-kdVc_Zi5.js → index-Dss2AnP8.js} +6 -6
- package/dist/web/assets/{term-mount-n0WthOpx.js → term-mount-C31GpifZ.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/cli/chunk-7x5sgkpr.js +0 -2
- package/dist/cli/chunk-dzhk9yd0.js +0 -2
- package/dist/cli/chunk-f1ybka2z.js +0 -2
- package/dist/cli/chunk-fmcbydv8.js +0 -2
- package/dist/cli/chunk-fy6xcmaj.js +0 -2
- package/dist/cli/chunk-hndyy4mw.js +0 -2
- package/dist/cli/chunk-hpay0ax8.js +0 -3
- package/dist/cli/chunk-jzsngv31.js +0 -3
- package/dist/cli/chunk-mf15ed15.js +0 -2
- package/dist/cli/chunk-mjacp0jr.js +0 -2
- package/dist/cli/chunk-mv5t5350.js +0 -3
- package/dist/cli/chunk-na76tkwk.js +0 -2
- package/dist/cli/chunk-p70r2ddj.js +0 -2
- package/dist/cli/chunk-pq3tabnw.js +0 -2
- package/dist/cli/chunk-ptfq1hny.js +0 -2
- package/dist/cli/chunk-q9cvreth.js +0 -2
- package/dist/cli/chunk-rdmwdnds.js +0 -2
- package/dist/cli/chunk-rn8wrdxj.js +0 -2
- package/dist/cli/chunk-sq6zj3fb.js +0 -5
- package/dist/cli/chunk-t76z564h.js +0 -2
- package/dist/cli/chunk-v78df6eg.js +0 -5
- package/dist/cli/chunk-x1zhs3m9.js +0 -2
- package/dist/cli/chunk-xh6kaw6b.js +0 -2
- package/dist/cli/chunk-y7xmqqab.js +0 -2
- package/dist/cli/chunk-z2e08xym.js +0 -2
- package/dist/cli/chunk-z9md1yx4.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{PR_VIEW_TIMEOUT_MS,checkFrame,failingCheckTargets,ghText,isLoopbackHost,makeGhPrUrlRunner,makeGhPrViewRunner,readFailingChecks}from"./chunk-
|
|
2
|
+
import{PR_VIEW_TIMEOUT_MS,checkFrame,failingCheckTargets,ghText,isLoopbackHost,makeGhPrUrlRunner,makeGhPrViewRunner,readFailingChecks}from"./chunk-8qy3wkp8.js";import{countCronBetween,isValidCron,latestCronAtOrBefore,nextCronAfter}from"./chunk-a4hsqj1b.js";import{activityPriority,sameTaskStatus,tabStatus,taskStatus,tightenInstalledPluginPermissions}from"./chunk-wwpq8gs4.js";import{ClientWriter,LineReceiver,objectPayload,optionalActivityDetail,optionalBoolean,optionalNumber,optionalString,optionalVendor,requireNumber,requireString,statusActivity}from"./chunk-rmnm3f9n.js";import{DEFAULT_STATE_DEBOUNCE_MS,startStateWatcher}from"./chunk-cpgnm1xr.js";import{startFileWatchTrigger}from"./chunk-r3s2t9af.js";import{parseDaemonStopReason}from"./chunk-6xr1prk6.js";import{canonicalEngineTab,ownEngineTabs}from"./chunk-q8ffd1pc.js";import{IssuesStore,defaultIssuesStorePath,resolveRepoRoot}from"./chunk-4hestsjp.js";import{buildPluginEnv}from"./chunk-d1vv8xk6.js";import{STICKY_STATES,activityStillWorking,reduceActivity,resolveEngineStateTtlMs}from"./chunk-2bgmby1d.js";import{currentPluginPlatform,loadPluginRegistry,pluginManifestPath,readPluginManifest,supportsPlatform}from"./chunk-psxhek7n.js";import{serialized,writeJsonAtomic,writeTextAtomic}from"./chunk-5mhvjytn.js";import{RowTokenStore,isRowTokenTone}from"./chunk-atn06ncf.js";import{DISPATCH_PROMPT_HEAD_CHARS,DispatchLedger,findAdoptableWorktree,matchTaskByCwd,repoIdOf,resolvePtyOwner,tasksAtWorktreePath}from"./chunk-t2q30c4r.js";import{ENGINE_EXIT_BANNER,engineExitCodeFromTail,plainTail,readPtyExitRecords,readPtyExitStore,recordEngineExit,wrapperBannerCodeFromTail}from"./chunk-5frd2aze.js";import{parsePorcelainRows}from"./chunk-dmzg9zdc.js";import{worktreeFingerprint}from"./chunk-kg9kmwt9.js";import{hasFrozenPtySessions,listPtyHostSessions,ptyHostHasLiveSessions,sweepPtyHostSessions}from"./chunk-e5dv15e5.js";import{logDaemonError,logDaemonInfo}from"./chunk-rxqdw6s5.js";import{applyTabOps,releaseOrdinals,reserveOrdinals}from"./chunk-b9ea827p.js";import{isBuiltinModInstalled,requireBuiltinMod}from"./chunk-v8nbqjwc.js";import{pluginConfigDir,pluginLogPath,pluginRegistryPath,pluginStateDir}from"./chunk-ws2q07kb.js";import{aliasKey,aliasedKeys,ptyScopeFor,teardownScope}from"./chunk-g9ba25q5.js";import{resolveLoginShell}from"./chunk-tn9gtf18.js";import{maybeStartScheduledRun}from"./chunk-qbbtvxmk.js";import{probeDaemonSocket}from"./chunk-q3cnqs5k.js";import{detachOptions}from"./chunk-8yce2acw.js";import{CHANNEL_NAMES,DAEMON_PROTOCOL_VERSION,DELIVERY_EVIDENCE_MAX_CHARS,DELIVERY_EVIDENCE_MAX_ITEMS,DELIVERY_NEXT_MAX_CHARS,DELIVERY_OUTCOMES,DELIVERY_PROMPT_HEAD_CHARS,DELIVERY_STALL_MS,DELIVERY_SUMMARY_MAX_CHARS,GATE_CONTEXT_MAX,GATE_OPTIONS_MAX,GATE_QUESTION_MAX,MAX_DELIVERIES_PER_TASK,MIN_COMPATIBLE_PROTOCOL_VERSION,ROUTINE_RESPONSE_MAX_CHARS,RoveDaemonClient,attentionInboxItemKey,automationRunNeedsAttention,deliveryFooter,frameToLine,isAttentionInboxState,isProtocolCompatible,isRoutineInboxState,normalizeChannelFilter,parseSkipVerdict}from"./chunk-29b3pj9h.js";import{MOD_INPUT_MAX,MOD_PANE_ID_PATTERN,MOD_TITLE_MAX,ROVE_API_VERSION,validateModTree}from"./chunk-96kvwzj8.js";import{AUTO_FIX_MAX,TodoRefusedError,autoFixDecision,canonicalPrUrl,lineageRootId,parseTodoOps,pickRepos,subtreeIds,taskCwd,workspaceCapabilities,workspaceOwnerId}from"./chunk-yfwn3fj5.js";import{rotateLogIfNeeded}from"./chunk-vfrxywtx.js";import{samePath}from"./chunk-pn5ygqn6.js";import{createSocketOwnershipGuard,isProcessAlive,listenOnUnixSocket}from"./chunk-k0yjcgd8.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE,ensureOwnerOnlyStateDir}from"./chunk-yt15y085.js";import{defaultDaemonPidPath,defaultDaemonSocketPath,defaultDeliveriesPath,defaultPtyExitsPath,defaultPtyHostSocketPath,endpointPathFor,resolveDaemonHomeDir}from"./chunk-7kgksv06.js";import{defaultKeybindingsPath,defaultUiPrefsStatePath,resolveProductHomeDir}from"./chunk-8143k3t6.js";import{ROVE_STATE_DIR_BASENAME,readRoveEnv,readRoveHomeDirEnv}from"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{mkdir as mkdir2,unlink as unlink2}from"fs/promises";import{createServer}from"net";import{dirname as dirname2}from"path";import{statSync}from"fs";var WATCHED_FIELDS=["title","branch","worktreePath","status","pinned","vendor","command","modelEffort","model","tier","linkedWorkItem","scratch"];function same(a,b){if(a===b)return!0;if(a==null||b==null)return a==null&&b==null;if(typeof a==="object"||typeof b==="object")return JSON.stringify(a)===JSON.stringify(b);return!1}function samePr(a,b){let strip=(v)=>{if(v==null||typeof v!=="object"||Array.isArray(v))return v;let{lastCheckedAt:_a,lastError:_b,...rest}=v;return rest};return same(strip(a),strip(b))}function diffTask(prev,next){let fields=[],from={},to={};for(let field of WATCHED_FIELDS){let a=prev[field],b=next[field];if(same(a,b))continue;if(fields.push(field),a!==void 0)from[field]=a;if(b!==void 0)to[field]=b}let prChanged=!samePr(prev.prStatus,next.prStatus);if(fields.length===0&&!prChanged)return null;return{fields,from,to,prChanged,worktreeCreated:next.kind==="task"&&!prev.worktreePath&&!!next.worktreePath}}function bornWithWorktree(task){return task.kind==="task"&&!!task.worktreePath}function lifecycleEventFor(kind,detail){switch(kind){case"session-start":return"session.start";case"session-end":return"session.end";case"turn-start":return"turn.prompt";case"turn-complete":return"turn.complete";case"turn-failed":return"turn.failed";case"turn-interrupted":return"turn.interrupted";case"awaiting-input":return detail?.waiting==="input"?"attention.question":"attention.permission";case"tool-pre":return"tool.pre";case"tool-post":return"tool.post";case"tool-failed":return"tool.failed";case"pre-compact":return"context.pre-compact";case"post-compact":return"context.post-compact";case"subagent-start":return"subagent.start";case"subagent-stop":return"subagent.stop";default:return}}var AGENT_EVENT_BY_STATE={turn_complete:"agent.turn-complete",permission_needed:"agent.permission-needed",rate_limited:"agent.rate-limited",error:"agent.error",running:"agent.running",idle:"agent.idle"};function taskContext(task){if(!task)return;let{id,title,repo,branch,worktreePath,vendor,status}=task;return{id,title,repo,branch,worktreePath,vendor,status}}class PluginEventReducer{tasks;agentState=new Map;limitedSince=new Map;tabbed=new Set;now;constructor(now=Date.now){this.now=now}contextFor(taskId){return taskContext(this.tasks?.get(taskId))}reduce(event){switch(event.channel){case"task.snapshot":return this.reduceTasks(event.payload.tasks);case"engine-state":return this.reduceEngine(event.payload);default:return[]}}reduceTasks(tasks){let next=new Map(tasks.map((t)=>[t.id,t])),prev=this.tasks;if(this.tasks=next,!prev)return[];let at=this.now(),out=[];for(let[id,task]of next){let before=prev.get(id);if(!before){if(out.push({event:"task.created",taskId:id,task:taskContext(task),at}),bornWithWorktree(task))out.push({event:"worktree.created",taskId:id,task:taskContext(task),at});continue}let diff=diffTask(before,task);if(!diff)continue;let ctx=taskContext(task);if(diff.fields.length>0)out.push({event:"task.changed",taskId:id,task:ctx,detail:{fields:diff.fields,from:diff.from,to:diff.to},at});if(diff.prChanged)out.push({event:"task.pr-changed",taskId:id,task:ctx,detail:{...before.prStatus!==void 0?{from:before.prStatus}:{},...task.prStatus!==void 0?{to:task.prStatus}:{}},at});if(diff.worktreeCreated)out.push({event:"worktree.created",taskId:id,task:ctx,at})}for(let[id,task]of prev)if(!next.has(id))out.push({event:"task.deleted",taskId:id,task:taskContext(task),at});return out}reduceEngine(payload){let key=`${payload.taskId}\x00${payload.tabId??""}`,prev=this.agentState.get(key);if(this.agentState.set(key,payload.state),prev===payload.state)return[];let event=AGENT_EVENT_BY_STATE[payload.state];if(!event)return[];let at=this.now(),base={taskId:payload.taskId,task:taskContext(this.tasks?.get(payload.taskId)),...payload.tabId?{tabId:payload.tabId}:{},at},out=[{event,...base}],recovered=this.trackRateLimit(key,payload,at);if(recovered!==void 0)out.push({event:"agent.rate-limit-recovered",...base,detail:{limitedAt:new Date(recovered).toISOString(),limitedForMs:at-recovered}});return out}trackRateLimit(key,payload,at){if(payload.tabId)this.tabbed.add(payload.taskId);else if(this.tabbed.has(payload.taskId))return;if(payload.state==="rate_limited"){if(!this.limitedSince.has(key))this.limitedSince.set(key,at);return}if(payload.state!=="turn_complete")return;let since=this.limitedSince.get(key);if(since===void 0)return;return this.limitedSince.delete(key),since}}import{execFile,spawn}from"child_process";import{appendFileSync,mkdirSync}from"fs";var OUTPUT_CAP=8192,PLUGIN_LOG_CAP_BYTES=4194304,SHUTDOWN_GRACE_MS=3000,HOOK_TIMEOUT_MS=30000,HOOK_SLOW_MS=2000;function hookTimeoutMs(spec,kind){return spec.timeoutMs??(kind==="shutdown"?SHUTDOWN_GRACE_MS:HOOK_TIMEOUT_MS)}function appendPluginLogRecord(pluginId,homeDir,record){try{let logPath=pluginLogPath(pluginId,homeDir);rotateLogIfNeeded(logPath,PLUGIN_LOG_CAP_BYTES),appendFileSync(logPath,`${JSON.stringify(record)}
|
|
3
3
|
`,{mode:OWNER_ONLY_FILE_MODE})}catch{}}async function runPluginHook(opts){let{pluginId,spec,kind,label,homeDir}=opts,timeoutMs=hookTimeoutMs(spec,kind),startedAt=Date.now();try{mkdirSync(pluginConfigDir(pluginId,homeDir),{recursive:!0,mode:OWNER_ONLY_DIR_MODE}),mkdirSync(pluginStateDir(pluginId,homeDir),{recursive:!0,mode:OWNER_ONLY_DIR_MODE})}catch(err){appendPluginLogRecord(pluginId,homeDir,{at:startedAt,kind,label,command:spec.command,exitCode:null,durationMs:Date.now()-startedAt,spawnError:String(err)}),opts.log?.(`plugin ${pluginId} ${label}: ${String(err)}`);return}let exitCode=null,stdout="",stderr="",spawnError,timedOut=!1;if(await new Promise((resolve)=>{let[cmd,...args]=spec.command,child=spawn(cmd,args,{cwd:opts.pluginRoot,env:buildPluginEnv({homeDir,socketPath:opts.socketPath,binPath:opts.binPath,pluginId,pluginRoot:opts.pluginRoot,extra:opts.extraEnv}),stdio:["ignore","pipe","pipe"],...detachOptions(opts.platform)}),kill=()=>{try{if(child.pid&&(opts.platform??process.platform)==="win32")execFile("taskkill",["/pid",String(child.pid),"/T","/F"],{windowsHide:!0},(err)=>{if(err)child.kill("SIGKILL")});else if(child.pid)process.kill(-child.pid,"SIGKILL");else child.kill("SIGKILL")}catch{child.kill("SIGKILL")}},deadline=setTimeout(()=>{timedOut=!0,kill()},timeoutMs);deadline.unref?.();let slow=setTimeout(()=>{appendPluginLogRecord(pluginId,homeDir,{at:startedAt,kind,label,command:spec.command,phase:"running",runningMs:Date.now()-startedAt,timeoutMs})},Math.min(HOOK_SLOW_MS,Math.floor(timeoutMs/2)));slow.unref?.(),opts.inFlight?.add(kill);let finish=()=>{clearTimeout(deadline),clearTimeout(slow),opts.inFlight?.delete(kill),resolve()};child.stdout.on("data",(chunk)=>{if(stdout.length<OUTPUT_CAP)stdout+=chunk.toString().slice(0,OUTPUT_CAP-stdout.length)}),child.stderr.on("data",(chunk)=>{if(stderr.length<OUTPUT_CAP)stderr+=chunk.toString().slice(0,OUTPUT_CAP-stderr.length)}),child.on("error",(err)=>{spawnError=String(err),finish()}),child.on("close",(code)=>{exitCode=code,finish()})}),appendPluginLogRecord(pluginId,homeDir,{at:startedAt,kind,label,command:spec.command,exitCode,durationMs:Date.now()-startedAt,...timedOut?{timedOut:!0,timeoutMs}:{},...stdout?{stdout}:{},...stderr?{stderr}:{},...spawnError?{spawnError}:{}}),timedOut)opts.log?.(`plugin ${pluginId} ${label}: killed after ${timeoutMs}ms (hook did not exit)`);else if(spawnError||exitCode!==null&&exitCode!==0)opts.log?.(`plugin ${pluginId} ${label}: ${spawnError??`exit ${exitCode}`}`)}import{execFile as execFile2,spawn as spawn2}from"child_process";import{mkdirSync as mkdirSync2}from"fs";var MOD_MAX_PANES=8,MAX_LINE_BYTES=524288,RESTART_MIN_MS=1000,RESTART_MAX_MS=30000,HEALTHY_RUN_MS=60000;function treeHasControl(node,type,key){if(node.type===type)return node.key===key;if(node.type==="box")return node.children.some((child)=>treeHasControl(child,type,key));return!1}class ModHost{opts;mods=new Map;stopped=!1;constructor(opts){this.opts=opts}sync(specs){if(this.stopped)return;let next=new Map(specs.map((s)=>[s.pluginId,s]));for(let[id,running]of this.mods){let spec=next.get(id);if(!spec||spec.root!==running.spec.root||!sameCommand(spec.mod,running.spec.mod))this.retire(id)}for(let spec of specs)if(!this.mods.has(spec.pluginId))this.launch(spec);this.publish()}press(pluginId,paneId,key){return this.forward(pluginId,paneId,"button",key,{type:"press",pane:paneId,key})}submit(pluginId,paneId,key,value){if(value.length>MOD_INPUT_MAX)return"too-long";return this.forward(pluginId,paneId,"input",key,{type:"submit",pane:paneId,key,value})}deliver(pluginIds,event){for(let running of this.mods.values()){if(!pluginIds.has(running.spec.pluginId)||!running.events.has(event.event))continue;if(running.child?.stdin?.writable)running.child.stdin.write(`${JSON.stringify({type:"event",event})}
|
|
4
4
|
`)}}forward(pluginId,paneId,type,key,msg){let running=this.mods.get(pluginId);if(!running?.child?.stdin?.writable)return"no-mod";let pane=running.panes.get(paneId);if(!pane)return"no-pane";if(!treeHasControl(pane.tree,type,key))return"no-key";return running.child.stdin.write(`${JSON.stringify(msg)}
|
|
5
5
|
`),"sent"}panes(){return[...this.mods.values()].flatMap((m)=>[...m.panes.values()])}stop(){if(this.stopped)return;this.stopped=!0;for(let id of[...this.mods.keys()])this.retire(id)}publish(){this.opts.publish(this.panes())}retire(pluginId){let running=this.mods.get(pluginId);if(!running)return;if(this.mods.delete(pluginId),running.restartTimer)clearTimeout(running.restartTimer);if(running.child)killGroup(running.child,this.opts.platform);running.child=null}launch(spec){let running={spec,child:null,startedAt:0,backoffMs:RESTART_MIN_MS,restartTimer:void 0,panes:new Map,events:new Set};this.mods.set(spec.pluginId,running),this.spawnChild(running)}record(running,record){appendPluginLogRecord(running.spec.pluginId,this.opts.homeDir,{at:Date.now(),kind:"mod",...record})}spawnChild(running){let{pluginId,root,mod}=running.spec,[cmd,...args]=mod.command,child;try{mkdirSync2(pluginConfigDir(pluginId,this.opts.homeDir),{recursive:!0,mode:OWNER_ONLY_DIR_MODE}),mkdirSync2(pluginStateDir(pluginId,this.opts.homeDir),{recursive:!0,mode:OWNER_ONLY_DIR_MODE}),child=spawn2(cmd,args,{cwd:root,env:buildPluginEnv({homeDir:this.opts.homeDir,socketPath:this.opts.socketPath,binPath:this.opts.binPath,pluginId,pluginRoot:root,extra:{ROVE_PLUGIN_EVENT:"mod"}}),stdio:["pipe","pipe","pipe"],...detachOptions(this.opts.platform)})}catch(err){this.record(running,{spawnError:String(err)}),this.scheduleRestart(running);return}running.child=child,running.events=new Set,running.startedAt=Date.now(),this.record(running,{phase:"started",command:mod.command}),child.stdin?.on("error",()=>{}),readLines(child,"stdout",(line)=>this.onLine(running,child,line)),readLines(child,"stderr",(line)=>this.record(running,{stderr:line.slice(0,2048)})),child.on("error",(err)=>this.record(running,{spawnError:String(err)})),child.on("close",(code,signal)=>{if(running.child!==child)return;if(running.child=null,this.record(running,{phase:"exited",exitCode:code,...signal?{signal}:{}}),this.opts.log?.(`mod ${pluginId} exited (${signal??`exit ${code}`})`),running.panes.size>0)running.panes.clear(),this.publish();if(Date.now()-running.startedAt>=HEALTHY_RUN_MS)running.backoffMs=RESTART_MIN_MS;this.scheduleRestart(running)})}scheduleRestart(running){if(this.stopped||this.mods.get(running.spec.pluginId)!==running)return;let delay=running.backoffMs;running.backoffMs=Math.min(running.backoffMs*2,RESTART_MAX_MS),running.restartTimer=setTimeout(()=>{if(running.restartTimer=void 0,this.stopped||this.mods.get(running.spec.pluginId)!==running)return;this.spawnChild(running)},delay),running.restartTimer.unref?.()}onLine(running,child,line){if(running.child!==child||line.trim()==="")return;let msg;try{msg=JSON.parse(line)}catch{this.record(running,{refused:"stdout line is not JSON",line:line.slice(0,200)});return}let refused=this.apply(running,msg);if(refused)this.record(running,{refused})}apply(running,msg){if(msg.type==="subscribe"){if(!Array.isArray(msg.events)||!msg.events.every((e)=>typeof e==="string"))return"subscribe needs events: string[]";return running.events=new Set(msg.events),null}if(typeof msg.id!=="string"||!MOD_PANE_ID_PATTERN.test(msg.id))return"bad pane id";if(msg.type==="close"){if(running.panes.delete(msg.id))this.publish();return null}if(msg.type!=="pane")return`unknown message type ${JSON.stringify(msg.type)}`;if(typeof msg.title!=="string"||msg.title.length===0||msg.title.length>MOD_TITLE_MAX)return`pane ${msg.id}: title must be 1-${MOD_TITLE_MAX} chars`;if(!running.panes.has(msg.id)&&running.panes.size>=MOD_MAX_PANES)return`pane ${msg.id}: more than ${MOD_MAX_PANES} panes`;let tree=validateModTree(msg.tree);if(!tree.ok)return`pane ${msg.id}: ${tree.error}`;return running.panes.set(msg.id,{plugin:running.spec.pluginId,id:msg.id,title:msg.title,tree:tree.tree}),this.publish(),null}}function sameCommand(a,b){return a.command.length===b.command.length&&a.command.every((part,i)=>part===b.command[i])}function killGroup(child,platform=process.platform){try{if(child.pid&&platform==="win32")execFile2("taskkill",["/pid",String(child.pid),"/T","/F"],{windowsHide:!0},(err)=>{if(err)child.kill("SIGTERM")});else if(child.pid)process.kill(-child.pid,"SIGTERM");else child.kill("SIGTERM")}catch{child.kill("SIGTERM")}}function readLines(child,stream,onLine){let buf="";child[stream]?.on("data",(chunk)=>{buf+=chunk.toString();let nl=buf.indexOf(`
|
|
@@ -50,7 +50,7 @@ ${armed.footer}`:handoff.text,result=gate.tabId?await ctx.runtime.deliverPromptT
|
|
|
50
50
|
}
|
|
51
51
|
}
|
|
52
52
|
}`;function nextCursor(connection,previous){let page=record(record(connection).pageInfo);if(page.hasNextPage!==!0)return null;if(typeof page.endCursor!=="string"||!page.endCursor||page.endCursor===previous)throw Error("GitHub returned an invalid pagination cursor");return page.endCursor}function record(value){return typeof value==="object"&&value!==null?value:{}}function nodes(value){let list=record(value).nodes;return Array.isArray(list)?list:[]}function lineOf(value){return typeof value==="number"&&Number.isInteger(value)&&value>0?value:null}function clip(body){return body.length>MAX_BODY_CHARS?`${body.slice(0,MAX_BODY_CHARS)}
|
|
53
|
-
\u2026 (truncated)`:body}function unresolvedThreads(payload){let pr=record(record(record(record(payload).data).repository).pullRequest),threads=[];for(let node of nodes(pr.reviewThreads)){let thread=record(node);if(thread.isResolved===!0)continue;let comments=nodes(thread.comments).map((c)=>{let comment=record(c),login=record(comment.author).login;return{author:typeof login==="string"?login:"ghost",body:clip(typeof comment.body==="string"?comment.body:""),url:typeof comment.url==="string"?comment.url:""}});threads.push({path:typeof thread.path==="string"?thread.path:"",line:lineOf(thread.line)??lineOf(thread.originalLine),outdated:thread.isOutdated===!0,comments})}return{threads:threads.slice(0,MAX_THREADS),totalUnresolved:threads.length}}async function readReviewComments(opts){try{let request=async(query,fields)=>{let read=await ghText(["api","graphql",...fields,"-f",`query=${query}`],opts.worktreePath,PR_VIEW_TIMEOUT_MS);if(!read.ok)return logDaemonInfo("pr-review-comments",`gh could not read PR #${opts.prNumber}: ${read.detail}`),{ok:!1,unavailable:{reason:"gh_failed",detail:read.detail}};return{ok:!0,payload:JSON.parse(read.stdout)}},retained=[],totalUnresolved=0,cursor=null;do{let read=await request(QUERY,["-F","owner={owner}","-F","repo={repo}","-F",`number=${opts.prNumber}`,...cursor===null?[]:["-f",`cursor=${cursor}`]]);if(!read.ok)return{threads:[],totalUnresolved:0,unavailable:read.unavailable};let payload=read.payload,connection=record(record(record(record(payload).data).repository).pullRequest).reviewThreads;for(let node of nodes(connection)){let thread=record(node);if(thread.isResolved===!0)continue;if(totalUnresolved++,retained.length>=MAX_THREADS)continue;let comments=[...nodes(thread.comments)],commentCursor=nextCursor(thread.comments,null);while(commentCursor!==null){if(typeof thread.id!=="string")throw Error("GitHub omitted the review thread ID");let reply=await request(COMMENTS_QUERY,["-f",`id=${thread.id}`,"-f",`cursor=${commentCursor}`]);if(!reply.ok)return{threads:[],totalUnresolved:0,unavailable:reply.unavailable};let page=record(record(record(reply.payload).data).node).comments;comments.push(...nodes(page)),commentCursor=nextCursor(page,commentCursor)}retained.push({...thread,comments:{nodes:comments}})}cursor=nextCursor(connection,cursor)}while(cursor!==null);return{threads:unresolvedThreads({data:{repository:{pullRequest:{reviewThreads:{nodes:retained}}}}}).threads,totalUnresolved}}catch(err){return logDaemonError("pr-review-comments",err),{threads:[],totalUnresolved:0,unavailable:{reason:"gh_error",detail:err instanceof Error?err.message:String(err)}}}}var PR_HANDLERS=[{name:"pr.failingChecks",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch?.getTask(taskId),prNumber=task?.prStatus?.number;if(!task?.worktreePath||typeof prNumber!=="number")return{checks:[],totalFailing:0};return await readFailingChecks({worktreePath:task.worktreePath,prNumber})}},{name:"pr.reviewComments",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch?.getTask(taskId),prNumber=task?.prStatus?.number;if(!task?.worktreePath||typeof prNumber!=="number")return{prNumber:null,threads:[],totalUnresolved:0};return{prNumber,...await readReviewComments({worktreePath:task.worktreePath,prNumber})}}},{name:"pr.rerunFailedChecks",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch?.getTask(taskId),prNumber=task?.prStatus?.number;if(!task?.worktreePath||typeof prNumber!=="number")return{rerunRuns:0,external:0};return await rerunFailedChecks({worktreePath:task.worktreePath,prNumber})}}];var NEW_TAB="new",skip=(reason,extra={})=>({run:!1,reason,...extra});function newestDelivery(deps,taskId,tabId){return deps.deliveries.listForTask(taskId).find((d)=>d.status!=="skipped"&&(tabId===null||d.tabId===null||d.tabId===tabId))}var isEngineMiss=(delivery)=>delivery.status==="missing"&&(delivery.missing?.cause==="rate-limited"||delivery.missing?.cause==="transient-failure");function missingDetail(delivery){let missing=delivery.missing;return`${delivery.id} ended without a report (${missing?.cause??"unknown"})${missing?.note?`: ${missing.note}`:""}`}function quotaUntil(deps,task,nowMs){if((task.quotaResume?Date.parse(task.quotaResume.resumeAt):Number.NaN)>nowMs)return task.quotaResume?.resumeAt??null;let cached=deps.quotaResetAtMs?.(task.vendor,nowMs)??null;return cached===null?null:new Date(cached).toISOString()}function evaluateRunnability(deps,taskId,tabId,opts={}){let now=(deps.now??Date.now)(),ignored=(reason)=>opts.ignore?.includes(reason)===!0,task=deps.orch.getTask(taskId);if(!task||task.deletion)return skip("task-missing");let openGates=deps.gates.list({taskId,status:"open"});if(openGates.length>0&&!ignored("awaiting-owner"))return skip("awaiting-owner",{detail:openGates[0]?.question,gateIds:openGates.map((g)=>g.id)});let fresh=tabId===NEW_TAB,tab=fresh?null:tabId,found=newestDelivery(deps,taskId,tab),newest=found&&isEngineMiss(found)?void 0:found;if(newest?.status==="missing"&&!newest.dismissedAt&&!ignored("report-missing"))return skip("report-missing",{detail:missingDetail(newest)});if(fresh)return{run:!0};let entry=deps.activity.entryOf(taskId,tab),failure=entry?.detail?.failure;if(entry?.state==="rate_limited"&&failure!=="billing"&&!ignored("quota")){let until=quotaUntil(deps,task,now);if(until!==null)return skip("quota",{until,...entry.detail?.note?{detail:entry.detail.note}:{}})}if((entry?.state==="error"&&failure!=="transient"||entry?.state==="rate_limited"&&failure==="billing")&&!ignored("engine-error"))return skip("engine-error",{detail:entry?.detail?.note??(failure?`failure: ${failure}`:void 0)});if(entry?.state==="dead"&&!ignored("engine-dead"))return skip("engine-dead");if(entry?.state==="permission_needed"&&!ignored("awaiting-permission"))return skip("awaiting-permission");if(!ignored("busy")){if(entry?.state==="running")return skip("busy",{detail:"a turn is running"});if(newest?.status==="awaiting")return skip("busy",{detail:`${newest.id} is still awaiting its report`});if(deps.deliveries.claims.isClaimed(taskId,tab))return skip("busy",{detail:"a tick is being delivered"})}return{run:!0}}function quotaResetReader(quota,defaultVendor){return(vendor,nowMs)=>{let usage=quota.peek(vendor??defaultVendor);return usage?exhaustedResetAtMs(usage,nowMs):null}}function createDispatchRunnability(deps,quota,defaultVendor){let resetAtMs=quotaResetReader(quota,defaultVendor),withReset={...deps,quotaResetAtMs:resetAtMs};return{check:(taskId,tabId,ignore)=>evaluateRunnability(withReset,taskId,tabId,ignore?{ignore}:{}),freshQuota(vendor){let resetAt=resetAtMs(vendor,(deps.now??Date.now)());return resetAt===null?void 0:skip("quota",{until:new Date(resetAt).toISOString()})}}}function runnabilityDepsOf(ctx){return{orch:ctx.orch,activity:ctx.activity,gates:ctx.gates,deliveries:ctx.deliveries,quotaResetAtMs:quotaResetReader(ctx.quotaUsage,ctx.runtime.defaultTaskVendor)}}function ignoredFor(tabId,respawn){return tabId&&tabId!=="new"&&!respawn?[]:["engine-dead"]}var RUNNABILITY_HANDLERS=[{name:"task.runnability",handle(payload,ctx){let tabId=optionalString(payload,"tabId");return evaluateRunnability(runnabilityDepsOf(ctx),requireString(payload,"taskId"),tabId??null,{ignore:ignoredFor(tabId,optionalBoolean(payload,"respawn"))})}},{name:"send.admit",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=optionalString(payload,"tabId"),promptHead=requireString(payload,"promptHead"),verdict=evaluateRunnability(runnabilityDepsOf(ctx),taskId,tabId??null,{ignore:ignoredFor(tabId,optionalBoolean(payload,"respawn"))}),armed=optionalBoolean(payload,"expectReport")===!0||ctx.orch.getTask(taskId)?.requireReport===!0,pinnedTab=tabId&&tabId!=="new"?tabId:null;if(!verdict.run){let skipped=armed?await ctx.deliveries.recordSkipped({taskId,tabId:pinnedTab,source:"send",promptHead,skipped:verdict}):void 0;return{skipped:verdict,...skipped?{deliveryId:skipped.id}:{}}}let claimId=ctx.deliveries.claims.claim(taskId,tabId||null,armed);if(!armed)return{claimId};try{let delivery=await ctx.deliveries.arm({taskId,tabId:pinnedTab,source:"send",promptHead});return{claimId,deliveryId:delivery.id}}catch(err){throw ctx.deliveries.claims.release(claimId,!1),err}}},{name:"send.release",handle(payload,ctx){return ctx.deliveries.claims.release(requireString(payload,"claimId"),payload.delivered===!0),{}}}];var QUOTA_RESUME_HANDLERS=[{name:"task.resumeQuota",blocking:!0,async handle(payload,ctx){let taskId=optionalString(payload,"taskId");if(taskId!==void 0&&!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);let waiting=quotaWaitingTasks(ctx.orch.listTasks(),(id)=>ctx.activity.entryOf(id,null)),targets=taskId===void 0?waiting:waiting.filter((task)=>task.id===taskId),runnability={check:(id,tabId,ignore)=>evaluateRunnability(runnabilityDepsOf(ctx),id,tabId,ignore?{ignore}:{})},results=[];for(let task of targets)try{results.push(await resumeQuotaTask(ctx.orch,ctx.runtime,task,ctx.deliveries.claims,()=>ctx.plugins??null,runnability))}catch(err){results.push({taskId:task.id,status:"failed",error:err instanceof Error?err.message:String(err)})}return{results}}}];var SURFACES2=["tui","web","phone"];function parseViewerInfo(payload,viewer){let surface=typeof payload.surface==="string"&&SURFACES2.includes(payload.surface)?payload.surface:viewer===""?"tui":"web",flag=(key)=>typeof payload[key]==="boolean"?payload[key]:void 0,panelOpen=flag("panelOpen"),narrow=flag("narrow");return{surface,panel:surface==="web"&&flag("panel")===!0,...panelOpen!==void 0?{panelOpen}:{},...narrow!==void 0?{narrow}:{},local:flag("local")??surface==="tui"}}function storeOf(ctx){if(!ctx.rowStatus)throw Error("row status unavailable");return ctx.rowStatus}var ROW_STATUS_HANDLERS=[{name:"status.list",handle(_payload,ctx){return storeOf(ctx).list()}},{name:"ui.viewing",handle(payload,ctx){let taskId=payload.taskId===null?null:requireString(payload,"taskId"),tabId=optionalString(payload,"tabId")??null,viewer=optionalString(payload,"viewer")??"";return storeOf(ctx).setViewing(ctx.clientId,viewer,taskId,tabId,parseViewerInfo(payload,viewer)),{ok:!0}}},{name:"ui.viewers",handle(payload,ctx){return{viewers:storeOf(ctx).viewers(optionalString(objectPayload(payload),"taskId"))}}},{name:"activity.answered",handle(payload,ctx){return storeOf(ctx).setAnswered(requireString(payload,"taskId"),requireString(payload,"tabId")),{ok:!0}}}];var OPS=new Set(["seed","open","patch","close","order","focus","meta","forget"]);function storeOf2(ctx){if(!ctx.tabs)throw Error("tab store unavailable");return ctx.tabs}function opsOf(payload){let ops=payload.ops;if(!Array.isArray(ops))throw Error("ops must be an array");for(let op of ops){let name=op&&typeof op==="object"?op.op:void 0;if(typeof name!=="string"||!OPS.has(name))throw Error(`unknown tab op: ${String(name)}`);if(name==="open"){let row=op.row;if(!row||typeof row!=="object"||typeof row.kind!=="string")throw Error("open needs a row with a string kind")}if((name==="patch"||name==="close"||name==="focus")&&typeof op.id!=="string")throw Error(`${name} needs a string id`)}return ops}var TAB_HANDLERS=[{name:"tabs.apply",handle(payload,ctx){let taskId=requireString(payload,"taskId"),ops=opsOf(payload);if(!ctx.orch.getTask(taskId)&&!ops.every((op)=>op.op==="forget"))throw Error(`task not found: ${taskId}`);return storeOf2(ctx).apply(taskId,ops)}},{name:"tabs.get",handle(payload,ctx){return storeOf2(ctx).get(requireString(payload,"taskId"))}},{name:"tabs.list",handle(_payload,ctx){return storeOf2(ctx).list()}},{name:"tabs.reserve",handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return storeOf2(ctx).reserve(taskId,optionalNumber(payload,"count")??2)}},{name:"tabs.release",handle(payload,ctx){let taskId=requireString(payload,"taskId"),from=optionalNumber(payload,"from"),to=optionalNumber(payload,"to");if(from===void 0||to===void 0)throw Error("release needs from and to");return storeOf2(ctx).release(taskId,from,to),{ok:!0}}}];var ENGINE_BUSY2={running:!0,permission_needed:!0},ARCHIVE_HANDLERS=[{name:"task.archive",async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(typeof payload.archived!=="boolean")throw Error("archived must be a boolean");let{archived}=payload,task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);if(task.kind==="main")throw Error("MAIN_TASK: a project's main checkout cannot be archived");let ids=subtreeIds(ctx.orch.listTasks(),taskId);if(archived&&optionalBoolean(payload,"force")!==!0){let busy=ids.filter((id)=>ENGINE_BUSY2[ctx.activity.stateOf(id,null)??"idle"]===!0);if(busy.length>0)throw Error(`TASK_BUSY: ${busy.length===1?"an engine is":`${busy.length} engines are`} still working or waiting on you in ${busy.join(", ")}; archive hides it without stopping it. Pass force to archive anyway.`)}for(let id of ids)await ctx.orch.setArchived(id,archived);return ctx.inbox.publish(),{archived:ids}}}];var FIELD_HANDLERS=[{name:"task.worktreeOnly",async handle(payload,ctx){if(typeof payload.on!=="boolean")throw Error("on must be a boolean");return await ctx.orch.setWorktreeOnly(requireString(payload,"taskId"),payload.on),{}}},{name:"task.pin",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setPinned(taskId,optionalBoolean(payload,"pinned")),{}}},{name:"task.keep",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setKept(taskId,optionalBoolean(payload,"kept")??!0),{}}},{name:"task.autoFixCi",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),enabled=optionalBoolean(payload,"enabled");if(enabled===void 0)throw Error("enabled must be a boolean");return await ctx.orch.setAutoFixCi(taskId,enabled?{attempts:0}:null),{}}},{name:"task.notes",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),notes=typeof payload.notes==="string"?payload.notes:void 0;try{let ops=payload.ops===void 0?void 0:parseTodoOps(payload.ops);return await ctx.orch.updateNotes(taskId,{...notes!==void 0?{notes}:{},...ops?{ops}:{}})}catch(err){if(err instanceof TodoRefusedError)throw Error(`${err.code}: ${err.message}`);throw err}}}];var PROMPT_MAX=20000;function parseScheduledStart(raw){let payload=typeof raw==="object"&&raw!==null?raw:{},at=requireString(payload,"at"),prompt=requireString(payload,"prompt");if(prompt.length>PROMPT_MAX)throw Error(`prompt is longer than ${PROMPT_MAX} characters`);let when=Date.parse(at);if(!Number.isFinite(when))throw Error("at must be an ISO-8601 time");return{at:new Date(when).toISOString(),prompt}}function parseCreate(raw){let create=typeof raw==="object"&&raw!==null?raw:{};if(create.via==="dir"){let vendor=optionalString(create,"vendor");return{via:"dir",dir:requireString(create,"dir"),project:optionalBoolean(create,"project")===!0,...vendor?{vendor}:{}}}if(create.via!=="add")throw Error("create.via must be add or dir");let params=create.params;if(typeof params!=="object"||params===null||Array.isArray(params))throw Error("create.params must be an object");let flags=params;for(let[flag,value]of Object.entries(flags))if(!(typeof value==="string"||typeof value==="boolean"||typeof value==="number")&&!(Array.isArray(value)&&value.every((v)=>typeof v==="string")))throw Error(`create.params.${flag} must be a string, number, boolean or string list`);let runsNow=["prompt","prompt-file","start","worktree-only","count","agents"].find((f)=>(f in flags));if(runsNow)throw Error(`create.params.${runsNow} does not belong in a pending start`);return{via:"add",params:flags}}function pendingOf(ctx){if(!ctx.pendingStarts)throw Error("this daemon keeps no pending starts");return ctx.pendingStarts}var SCHEDULE_HANDLERS=[{name:"pendingStart.add",async handle(payload,ctx){let{at,prompt}=parseScheduledStart(payload),create=parseCreate(payload.create),title=(optionalString(payload,"title")??"").slice(0,200),start=await pendingOf(ctx).add({at,prompt,title,repo:requireString(payload,"repo"),create});return{id:start.id,at:start.at}}},{name:"pendingStart.list",async handle(_payload,ctx){return{starts:ctx.pendingStarts?.list()??[]}}},{name:"pendingStart.cancel",async handle(payload,ctx){let id=requireString(payload,"id");if(!await pendingOf(ctx).remove(id))throw Error(`NOT_SCHEDULED: no pending start ${id}`);return{}}},{name:"task.scheduleStart",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),schedule=parseScheduledStart(payload),task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);if(task.prompt)throw Error("ALREADY_STARTED: this task already has its first message");return await ctx.orch.setScheduledStart(taskId,schedule),{taskId,at:schedule.at}}},{name:"task.cancelScheduledStart",async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return await ctx.orch.setScheduledStart(taskId,null),{}}},{name:"task.startScheduledNow",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId)?.scheduledStart)throw Error("NOT_SCHEDULED: this task has no scheduled start");return{outcome:await startScheduledNow({orch:ctx.orch,runtime:ctx.runtime,link:ctx.selfLink},taskId)}}}];var SCRATCH_HANDLERS=[{name:"task.openDir",async handle(payload,ctx){let dir=requireString(payload,"dir"),task=await ctx.orch.openDirectoryTask({dir,vendor:optionalVendor(payload,"vendor"),scratch:optionalBoolean(payload,"scratch"),title:optionalString(payload,"title")});return{taskId:task.id,task:serializeTask(task)}}},{name:"task.adoptScratchRepo",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.adoptScratchRepo(taskId,requireString(payload,"repo")),{}}}];var SESSION_PR_HANDLERS=[{name:"task.addSessionPr",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),rawUrl=requireString(payload,"url"),url=canonicalPrUrl(rawUrl);if(!url)throw Error(`url must be a github.com/<owner>/<repo>/pull/<n> link: ${rawUrl}`);if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return await ctx.orch.addSessionPr(taskId,url),{taskId,url}}}];async function syncRepos(runtime,task,only){let repos=[];for(let repo of pickRepos(task,only)){if(!repo.worktreePath){repos.push({name:repo.name,ok:!1,error:"no worktree to sync"});continue}try{let res=await runtime.syncWorktreeWithBase(repo.worktreePath,repo.baseRef);repos.push({name:repo.name,ok:!0,baseRef:res.baseRef,alreadyCurrent:res.alreadyCurrent})}catch(err){let error=err instanceof Error?err.message:String(err),code=/^([A-Z][A-Z0-9_]{2,}): /.exec(error)?.[1];repos.push({name:repo.name,ok:!1,error,...code?{code}:{}})}}return{baseRef:repos.find((r)=>r.ok)?.baseRef??"",alreadyCurrent:repos.every((r)=>r.ok&&r.alreadyCurrent===!0),repos}}var SUBSYSTEM="task-deletion-audit";function originText(origin,task){let parts=[];if(origin)parts.push(`client=${origin.clientId}`);if(origin?.requestedBy)parts.push(`by=${origin.requestedBy.taskId}::${origin.requestedBy.tabId}`);let dispatcher=task?.dispatcher;if(dispatcher)parts.push(`spawnedBy=${dispatcher.taskId}::${dispatcher.tabId}`);return parts.length>0?` (${parts.join(" ")})`:""}function subjectText(task,taskId){if(!task)return`task ${taskId}`;let bits=[`task ${taskId}`,`title=${JSON.stringify(task.title)}`,`kind=${task.kind}`];if(task.branch)bits.push(`branch=${task.branch}`);if(task.worktreePath)bits.push(`worktree=${task.worktreePath}`);return bits.join(" ")}function auditDeletionRequested(taskId,task,origin,opts={}){logDaemonInfo(SUBSYSTEM,`requested ${subjectText(task,taskId)} force=${opts.force===!0} deleteBranch=${opts.deleteBranch===!0}${originText(origin,task)}`)}function auditDeletionRemoved(taskId,task){logDaemonInfo(SUBSYSTEM,`removed ${subjectText(task,taskId)}`)}function auditDeletionBranchKept(taskId,branch,reason){logDaemonInfo(SUBSYSTEM,`branch kept task ${taskId} branch=${branch} \u2014 git refused the delete: ${reason.replace(/\s+/g," ").trim()}. Nothing else will remove it; \`git branch -D ${branch}\` does, and drops its reflog with it.`)}function auditDeletionFailed(taskId,task,err){let cause=err instanceof Error?err:Error(String(err)),context=`failed ${subjectText(task,taskId)} \u2014 session teardown and activity/inbox cleanup ALREADY ran; the worktree directory and task entry remain. Reason: `,line=Error(`${context}${cause.message}`);line.name=cause.name;let frames=cause.stack?.split(`
|
|
53
|
+
\u2026 (truncated)`:body}function unresolvedThreads(payload){let pr=record(record(record(record(payload).data).repository).pullRequest),threads=[];for(let node of nodes(pr.reviewThreads)){let thread=record(node);if(thread.isResolved===!0)continue;let comments=nodes(thread.comments).map((c)=>{let comment=record(c),login=record(comment.author).login;return{author:typeof login==="string"?login:"ghost",body:clip(typeof comment.body==="string"?comment.body:""),url:typeof comment.url==="string"?comment.url:""}});threads.push({path:typeof thread.path==="string"?thread.path:"",line:lineOf(thread.line)??lineOf(thread.originalLine),outdated:thread.isOutdated===!0,comments})}return{threads:threads.slice(0,MAX_THREADS),totalUnresolved:threads.length}}async function readReviewComments(opts){try{let request=async(query,fields)=>{let read=await ghText(["api","graphql",...fields,"-f",`query=${query}`],opts.worktreePath,PR_VIEW_TIMEOUT_MS);if(!read.ok)return logDaemonInfo("pr-review-comments",`gh could not read PR #${opts.prNumber}: ${read.detail}`),{ok:!1,unavailable:{reason:"gh_failed",detail:read.detail}};return{ok:!0,payload:JSON.parse(read.stdout)}},retained=[],totalUnresolved=0,cursor=null;do{let read=await request(QUERY,["-F","owner={owner}","-F","repo={repo}","-F",`number=${opts.prNumber}`,...cursor===null?[]:["-f",`cursor=${cursor}`]]);if(!read.ok)return{threads:[],totalUnresolved:0,unavailable:read.unavailable};let payload=read.payload,connection=record(record(record(record(payload).data).repository).pullRequest).reviewThreads;for(let node of nodes(connection)){let thread=record(node);if(thread.isResolved===!0)continue;if(totalUnresolved++,retained.length>=MAX_THREADS)continue;let comments=[...nodes(thread.comments)],commentCursor=nextCursor(thread.comments,null);while(commentCursor!==null){if(typeof thread.id!=="string")throw Error("GitHub omitted the review thread ID");let reply=await request(COMMENTS_QUERY,["-f",`id=${thread.id}`,"-f",`cursor=${commentCursor}`]);if(!reply.ok)return{threads:[],totalUnresolved:0,unavailable:reply.unavailable};let page=record(record(record(reply.payload).data).node).comments;comments.push(...nodes(page)),commentCursor=nextCursor(page,commentCursor)}retained.push({...thread,comments:{nodes:comments}})}cursor=nextCursor(connection,cursor)}while(cursor!==null);return{threads:unresolvedThreads({data:{repository:{pullRequest:{reviewThreads:{nodes:retained}}}}}).threads,totalUnresolved}}catch(err){return logDaemonError("pr-review-comments",err),{threads:[],totalUnresolved:0,unavailable:{reason:"gh_error",detail:err instanceof Error?err.message:String(err)}}}}var PR_HANDLERS=[{name:"pr.failingChecks",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch?.getTask(taskId),prNumber=task?.prStatus?.number;if(!task?.worktreePath||typeof prNumber!=="number")return{checks:[],totalFailing:0};return await readFailingChecks({worktreePath:task.worktreePath,prNumber})}},{name:"pr.reviewComments",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch?.getTask(taskId),prNumber=task?.prStatus?.number;if(!task?.worktreePath||typeof prNumber!=="number")return{prNumber:null,threads:[],totalUnresolved:0};return{prNumber,...await readReviewComments({worktreePath:task.worktreePath,prNumber})}}},{name:"pr.rerunFailedChecks",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch?.getTask(taskId),prNumber=task?.prStatus?.number;if(!task?.worktreePath||typeof prNumber!=="number")return{rerunRuns:0,external:0};return await rerunFailedChecks({worktreePath:task.worktreePath,prNumber})}}];var NEW_TAB="new",skip=(reason,extra={})=>({run:!1,reason,...extra});function newestDelivery(deps,taskId,tabId){return deps.deliveries.listForTask(taskId).find((d)=>d.status!=="skipped"&&(tabId===null||d.tabId===null||d.tabId===tabId))}var isEngineMiss=(delivery)=>delivery.status==="missing"&&(delivery.missing?.cause==="rate-limited"||delivery.missing?.cause==="transient-failure");function missingDetail(delivery){let missing=delivery.missing;return`${delivery.id} ended without a report (${missing?.cause??"unknown"})${missing?.note?`: ${missing.note}`:""}`}function quotaUntil(deps,task,nowMs){if((task.quotaResume?Date.parse(task.quotaResume.resumeAt):Number.NaN)>nowMs)return task.quotaResume?.resumeAt??null;let cached=deps.quotaResetAtMs?.(task.vendor,nowMs)??null;return cached===null?null:new Date(cached).toISOString()}function evaluateRunnability(deps,taskId,tabId,opts={}){let now=(deps.now??Date.now)(),ignored=(reason)=>opts.ignore?.includes(reason)===!0,task=deps.orch.getTask(taskId);if(!task||task.deletion)return skip("task-missing");let openGates=deps.gates.list({taskId,status:"open"});if(openGates.length>0&&!ignored("awaiting-owner"))return skip("awaiting-owner",{detail:openGates[0]?.question,gateIds:openGates.map((g)=>g.id)});let fresh=tabId===NEW_TAB,tab=fresh?null:tabId,found=newestDelivery(deps,taskId,tab),newest=found&&isEngineMiss(found)?void 0:found;if(newest?.status==="missing"&&!newest.dismissedAt&&!ignored("report-missing"))return skip("report-missing",{detail:missingDetail(newest)});if(fresh)return{run:!0};let entry=deps.activity.entryOf(taskId,tab),failure=entry?.detail?.failure;if(entry?.state==="rate_limited"&&failure!=="billing"&&!ignored("quota")){let until=quotaUntil(deps,task,now);if(until!==null)return skip("quota",{until,...entry.detail?.note?{detail:entry.detail.note}:{}})}if((entry?.state==="error"&&failure!=="transient"||entry?.state==="rate_limited"&&failure==="billing")&&!ignored("engine-error"))return skip("engine-error",{detail:entry?.detail?.note??(failure?`failure: ${failure}`:void 0)});if(entry?.state==="dead"&&!ignored("engine-dead"))return skip("engine-dead");if(entry?.state==="permission_needed"&&!ignored("awaiting-permission"))return skip("awaiting-permission");if(!ignored("busy")){if(entry?.state==="running")return skip("busy",{detail:"a turn is running"});if(newest?.status==="awaiting")return skip("busy",{detail:`${newest.id} is still awaiting its report`});if(deps.deliveries.claims.isClaimed(taskId,tab))return skip("busy",{detail:"a tick is being delivered"})}return{run:!0}}function quotaResetReader(quota,defaultVendor){return(vendor,nowMs)=>{let usage=quota.peek(vendor??defaultVendor);return usage?exhaustedResetAtMs(usage,nowMs):null}}function createDispatchRunnability(deps,quota,defaultVendor){let resetAtMs=quotaResetReader(quota,defaultVendor),withReset={...deps,quotaResetAtMs:resetAtMs};return{check:(taskId,tabId,ignore)=>evaluateRunnability(withReset,taskId,tabId,ignore?{ignore}:{}),freshQuota(vendor){let resetAt=resetAtMs(vendor,(deps.now??Date.now)());return resetAt===null?void 0:skip("quota",{until:new Date(resetAt).toISOString()})}}}function runnabilityDepsOf(ctx){return{orch:ctx.orch,activity:ctx.activity,gates:ctx.gates,deliveries:ctx.deliveries,quotaResetAtMs:quotaResetReader(ctx.quotaUsage,ctx.runtime.defaultTaskVendor)}}function ignoredFor(tabId,respawn){return tabId&&tabId!=="new"&&!respawn?[]:["engine-dead"]}var RUNNABILITY_HANDLERS=[{name:"task.runnability",handle(payload,ctx){let tabId=optionalString(payload,"tabId");return evaluateRunnability(runnabilityDepsOf(ctx),requireString(payload,"taskId"),tabId??null,{ignore:ignoredFor(tabId,optionalBoolean(payload,"respawn"))})}},{name:"send.admit",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=optionalString(payload,"tabId"),promptHead=requireString(payload,"promptHead"),verdict=evaluateRunnability(runnabilityDepsOf(ctx),taskId,tabId??null,{ignore:ignoredFor(tabId,optionalBoolean(payload,"respawn"))}),armed=optionalBoolean(payload,"expectReport")===!0||ctx.orch.getTask(taskId)?.requireReport===!0,pinnedTab=tabId&&tabId!=="new"?tabId:null;if(!verdict.run){let skipped=armed?await ctx.deliveries.recordSkipped({taskId,tabId:pinnedTab,source:"send",promptHead,skipped:verdict}):void 0;return{skipped:verdict,...skipped?{deliveryId:skipped.id}:{}}}let claimId=ctx.deliveries.claims.claim(taskId,tabId||null,armed);if(!armed)return{claimId};try{let delivery=await ctx.deliveries.arm({taskId,tabId:pinnedTab,source:"send",promptHead});return{claimId,deliveryId:delivery.id}}catch(err){throw ctx.deliveries.claims.release(claimId,!1),err}}},{name:"send.release",handle(payload,ctx){return ctx.deliveries.claims.release(requireString(payload,"claimId"),payload.delivered===!0),{}}}];var QUOTA_RESUME_HANDLERS=[{name:"task.resumeQuota",blocking:!0,async handle(payload,ctx){let taskId=optionalString(payload,"taskId");if(taskId!==void 0&&!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);let waiting=quotaWaitingTasks(ctx.orch.listTasks(),(id)=>ctx.activity.entryOf(id,null)),targets=taskId===void 0?waiting:waiting.filter((task)=>task.id===taskId),runnability={check:(id,tabId,ignore)=>evaluateRunnability(runnabilityDepsOf(ctx),id,tabId,ignore?{ignore}:{})},results=[];for(let task of targets)try{results.push(await resumeQuotaTask(ctx.orch,ctx.runtime,task,ctx.deliveries.claims,()=>ctx.plugins??null,runnability))}catch(err){results.push({taskId:task.id,status:"failed",error:err instanceof Error?err.message:String(err)})}return{results}}}];var SURFACES2=["tui","web","phone"];function parseViewerInfo(payload,viewer){let surface=typeof payload.surface==="string"&&SURFACES2.includes(payload.surface)?payload.surface:viewer===""?"tui":"web",flag=(key)=>typeof payload[key]==="boolean"?payload[key]:void 0,panelOpen=flag("panelOpen"),narrow=flag("narrow");return{surface,panel:surface==="web"&&flag("panel")===!0,...panelOpen!==void 0?{panelOpen}:{},...narrow!==void 0?{narrow}:{},local:flag("local")??surface==="tui"}}function storeOf(ctx){if(!ctx.rowStatus)throw Error("row status unavailable");return ctx.rowStatus}var ROW_STATUS_HANDLERS=[{name:"status.list",handle(_payload,ctx){return storeOf(ctx).list()}},{name:"ui.viewing",handle(payload,ctx){let taskId=payload.taskId===null?null:requireString(payload,"taskId"),tabId=optionalString(payload,"tabId")??null,viewer=optionalString(payload,"viewer")??"";return storeOf(ctx).setViewing(ctx.clientId,viewer,taskId,tabId,parseViewerInfo(payload,viewer)),{ok:!0}}},{name:"ui.viewers",handle(payload,ctx){return{viewers:storeOf(ctx).viewers(optionalString(objectPayload(payload),"taskId"))}}},{name:"activity.answered",handle(payload,ctx){return storeOf(ctx).setAnswered(requireString(payload,"taskId"),requireString(payload,"tabId")),{ok:!0}}}];var OPS=new Set(["seed","open","patch","close","order","focus","meta","forget"]);function storeOf2(ctx){if(!ctx.tabs)throw Error("tab store unavailable");return ctx.tabs}function opsOf(payload){let ops=payload.ops;if(!Array.isArray(ops))throw Error("ops must be an array");for(let op of ops){let name=op&&typeof op==="object"?op.op:void 0;if(typeof name!=="string"||!OPS.has(name))throw Error(`unknown tab op: ${String(name)}`);if(name==="open"){let row=op.row;if(!row||typeof row!=="object"||typeof row.kind!=="string")throw Error("open needs a row with a string kind")}if((name==="patch"||name==="close"||name==="focus")&&typeof op.id!=="string")throw Error(`${name} needs a string id`)}return ops}var TAB_HANDLERS=[{name:"tabs.apply",handle(payload,ctx){let taskId=requireString(payload,"taskId"),ops=opsOf(payload);if(!ctx.orch.getTask(taskId)&&!ops.every((op)=>op.op==="forget"))throw Error(`task not found: ${taskId}`);return storeOf2(ctx).apply(taskId,ops)}},{name:"tabs.get",handle(payload,ctx){return storeOf2(ctx).get(requireString(payload,"taskId"))}},{name:"tabs.list",handle(_payload,ctx){return storeOf2(ctx).list()}},{name:"tabs.reserve",handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return storeOf2(ctx).reserve(taskId,optionalNumber(payload,"count")??2)}},{name:"tabs.release",handle(payload,ctx){let taskId=requireString(payload,"taskId"),from=optionalNumber(payload,"from"),to=optionalNumber(payload,"to");if(from===void 0||to===void 0)throw Error("release needs from and to");return storeOf2(ctx).release(taskId,from,to),{ok:!0}}}];var ENGINE_BUSY2={running:!0,permission_needed:!0},ARCHIVE_HANDLERS=[{name:"task.archive",async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(typeof payload.archived!=="boolean")throw Error("archived must be a boolean");let{archived}=payload,task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);if(task.kind==="main")throw Error("MAIN_TASK: a project's main checkout cannot be archived");let ids=subtreeIds(ctx.orch.listTasks(),taskId);if(archived&&optionalBoolean(payload,"force")!==!0){let busy=ids.filter((id)=>ENGINE_BUSY2[ctx.activity.stateOf(id,null)??"idle"]===!0);if(busy.length>0)throw Error(`TASK_BUSY: ${busy.length===1?"an engine is":`${busy.length} engines are`} still working or waiting on you in ${busy.join(", ")}; archive hides it without stopping it. Pass force to archive anyway.`)}for(let id of ids)await ctx.orch.setArchived(id,archived);return ctx.inbox.publish(),{archived:ids}}}];var FIELD_HANDLERS=[{name:"task.worktreeOnly",async handle(payload,ctx){if(typeof payload.on!=="boolean")throw Error("on must be a boolean");return await ctx.orch.setWorktreeOnly(requireString(payload,"taskId"),payload.on),{}}},{name:"task.pin",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setPinned(taskId,optionalBoolean(payload,"pinned")),{}}},{name:"task.keep",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setKept(taskId,optionalBoolean(payload,"kept")??!0),{}}},{name:"task.autoFixCi",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),enabled=optionalBoolean(payload,"enabled");if(enabled===void 0)throw Error("enabled must be a boolean");return await ctx.orch.setAutoFixCi(taskId,enabled?{attempts:0}:null),{}}},{name:"task.notes",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),notes=typeof payload.notes==="string"?payload.notes:void 0;try{let ops=payload.ops===void 0?void 0:parseTodoOps(payload.ops);return await ctx.orch.updateNotes(taskId,{...notes!==void 0?{notes}:{},...ops?{ops}:{}})}catch(err){if(err instanceof TodoRefusedError)throw Error(`${err.code}: ${err.message}`);throw err}}}];var PROMPT_MAX=20000;function parseScheduledStart(raw){let payload=typeof raw==="object"&&raw!==null?raw:{},at=requireString(payload,"at"),prompt=requireString(payload,"prompt");if(prompt.length>PROMPT_MAX)throw Error(`prompt is longer than ${PROMPT_MAX} characters`);let when=Date.parse(at);if(!Number.isFinite(when))throw Error("at must be an ISO-8601 time");return{at:new Date(when).toISOString(),prompt}}function parseCreate(raw){let create=typeof raw==="object"&&raw!==null?raw:{};if(create.via==="dir"){let vendor=optionalString(create,"vendor");return{via:"dir",dir:requireString(create,"dir"),project:optionalBoolean(create,"project")===!0,...vendor?{vendor}:{}}}if(create.via!=="add")throw Error("create.via must be add or dir");let params=create.params;if(typeof params!=="object"||params===null||Array.isArray(params))throw Error("create.params must be an object");let flags=params;for(let[flag,value]of Object.entries(flags))if(!(typeof value==="string"||typeof value==="boolean"||typeof value==="number")&&!(Array.isArray(value)&&value.every((v)=>typeof v==="string")))throw Error(`create.params.${flag} must be a string, number, boolean or string list`);let runsNow=["prompt","prompt-file","start","worktree-only","count","agents"].find((f)=>(f in flags));if(runsNow)throw Error(`create.params.${runsNow} does not belong in a pending start`);return{via:"add",params:flags}}function pendingOf(ctx){if(!ctx.pendingStarts)throw Error("this daemon keeps no pending starts");return ctx.pendingStarts}var SCHEDULE_HANDLERS=[{name:"pendingStart.add",async handle(payload,ctx){let{at,prompt}=parseScheduledStart(payload),create=parseCreate(payload.create),title=(optionalString(payload,"title")??"").slice(0,200),start=await pendingOf(ctx).add({at,prompt,title,repo:requireString(payload,"repo"),create});return{id:start.id,at:start.at}}},{name:"pendingStart.list",async handle(_payload,ctx){return{starts:ctx.pendingStarts?.list()??[]}}},{name:"pendingStart.cancel",async handle(payload,ctx){let id=requireString(payload,"id");if(!await pendingOf(ctx).remove(id))throw Error(`NOT_SCHEDULED: no pending start ${id}`);return{}}},{name:"task.scheduleStart",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),schedule=parseScheduledStart(payload),task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);if(task.prompt)throw Error("ALREADY_STARTED: this task already has its first message");return await ctx.orch.setScheduledStart(taskId,schedule),{taskId,at:schedule.at}}},{name:"task.cancelScheduledStart",async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return await ctx.orch.setScheduledStart(taskId,null),{}}},{name:"task.startScheduledNow",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId)?.scheduledStart)throw Error("NOT_SCHEDULED: this task has no scheduled start");return{outcome:await startScheduledNow({orch:ctx.orch,runtime:ctx.runtime,link:ctx.selfLink},taskId)}}}];var SCRATCH_HANDLERS=[{name:"task.openDir",async handle(payload,ctx){let dir=requireString(payload,"dir"),task=await ctx.orch.openDirectoryTask({dir,vendor:optionalVendor(payload,"vendor"),scratch:optionalBoolean(payload,"scratch"),title:optionalString(payload,"title"),model:optionalString(payload,"model"),modelEffort:optionalString(payload,"effort"),...optionalBoolean(payload,"remote")?{workspace:{backend:"remote"}}:{}});return{taskId:task.id,task:serializeTask(task)}}},{name:"task.adoptScratchRepo",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.adoptScratchRepo(taskId,requireString(payload,"repo")),{}}}];var SESSION_PR_HANDLERS=[{name:"task.addSessionPr",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),rawUrl=requireString(payload,"url"),url=canonicalPrUrl(rawUrl);if(!url)throw Error(`url must be a github.com/<owner>/<repo>/pull/<n> link: ${rawUrl}`);if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return await ctx.orch.addSessionPr(taskId,url),{taskId,url}}}];async function syncRepos(runtime,task,only){let repos=[];for(let repo of pickRepos(task,only)){if(!repo.worktreePath){repos.push({name:repo.name,ok:!1,error:"no worktree to sync"});continue}try{let res=await runtime.syncWorktreeWithBase(repo.worktreePath,repo.baseRef);repos.push({name:repo.name,ok:!0,baseRef:res.baseRef,alreadyCurrent:res.alreadyCurrent})}catch(err){let error=err instanceof Error?err.message:String(err),code=/^([A-Z][A-Z0-9_]{2,}): /.exec(error)?.[1];repos.push({name:repo.name,ok:!1,error,...code?{code}:{}})}}return{baseRef:repos.find((r)=>r.ok)?.baseRef??"",alreadyCurrent:repos.every((r)=>r.ok&&r.alreadyCurrent===!0),repos}}var SUBSYSTEM="task-deletion-audit";function originText(origin,task){let parts=[];if(origin)parts.push(`client=${origin.clientId}`);if(origin?.requestedBy)parts.push(`by=${origin.requestedBy.taskId}::${origin.requestedBy.tabId}`);let dispatcher=task?.dispatcher;if(dispatcher)parts.push(`spawnedBy=${dispatcher.taskId}::${dispatcher.tabId}`);return parts.length>0?` (${parts.join(" ")})`:""}function subjectText(task,taskId){if(!task)return`task ${taskId}`;let bits=[`task ${taskId}`,`title=${JSON.stringify(task.title)}`,`kind=${task.kind}`];if(task.branch)bits.push(`branch=${task.branch}`);if(task.worktreePath)bits.push(`worktree=${task.worktreePath}`);return bits.join(" ")}function auditDeletionRequested(taskId,task,origin,opts={}){logDaemonInfo(SUBSYSTEM,`requested ${subjectText(task,taskId)} force=${opts.force===!0} deleteBranch=${opts.deleteBranch===!0}${originText(origin,task)}`)}function auditDeletionRemoved(taskId,task){logDaemonInfo(SUBSYSTEM,`removed ${subjectText(task,taskId)}`)}function auditDeletionBranchKept(taskId,branch,reason){logDaemonInfo(SUBSYSTEM,`branch kept task ${taskId} branch=${branch} \u2014 git refused the delete: ${reason.replace(/\s+/g," ").trim()}. Nothing else will remove it; \`git branch -D ${branch}\` does, and drops its reflog with it.`)}function auditDeletionFailed(taskId,task,err){let cause=err instanceof Error?err:Error(String(err)),context=`failed ${subjectText(task,taskId)} \u2014 session teardown and activity/inbox cleanup ALREADY ran; the worktree directory and task entry remain. Reason: `,line=Error(`${context}${cause.message}`);line.name=cause.name;let frames=cause.stack?.split(`
|
|
54
54
|
`).slice(1)??[];if(frames.length>0)line.stack=[`${line.name}: ${line.message}`,...frames].join(`
|
|
55
55
|
`);logDaemonError(SUBSYSTEM,line)}function recoveryText(ref,commit,repo,uncaptured=[]){let at=repo?` -C ${repo}`:"",gap=uncaptured.length>0?` NOT captured (submodule / nested worktree \u2014 the snapshot holds only a commit pointer): ${uncaptured.join(", ")}.`:"";return`uncommitted work saved to ${ref} (${commit}).${gap} Recover with: git${at} show ${ref} | git${at} restore --source=${ref} -- <path> | list all: git${at} for-each-ref refs/rove/salvage`}function auditDeletionSalvaged(taskId,ref,commit,repo,uncaptured=[]){logDaemonInfo(SUBSYSTEM,`salvaged task ${taskId} \u2014 ${recoveryText(ref,commit,repo,uncaptured)}`)}function auditWorktreeSalvaged(worktreePath,ref,commit,uncaptured=[]){logDaemonInfo(SUBSYSTEM,`salvaged worktree ${worktreePath} \u2014 ${recoveryText(ref,commit,void 0,uncaptured)}`)}function auditDeletionResidue(taskId,worktreePath,reason){logDaemonInfo(SUBSYSTEM,`removed task ${taskId} \u2014 git deregistered the worktree but could NOT delete ${worktreePath} (${reason}). Nothing further is needed in Rove; remove the directory by hand if you want the disk space.`)}function auditWorktreeResidue(worktreePath,reason){logDaemonInfo(SUBSYSTEM,`deregistered ${worktreePath} but could NOT delete the directory (${reason})`)}async function releaseDeletedTask(ctx,taskId,task){if(ctx.activity.clearTask(taskId),await ctx.inbox.deleteTaskBestEffort(taskId),await ctx.gates.withdrawTask(taskId).catch((err)=>logDaemonError("gates-withdraw-task",err)),task&&isBuiltinModInstalled("kanban",ctx.daemon.homeDir))try{let next=await ctx.issues.unlinkTask(task.repo,taskId);if(next)publishIssueSnapshot(ctx,next)}catch(err){logDaemonError("issue-delete-unlink",err)}}function optionalWorkerReport(payload){let branch=optionalString(payload,"reportBranch"),summary=optionalString(payload,"reportSummary"),pr=optionalNumber(payload,"reportPr");if(branch===void 0&&summary===void 0&&pr===void 0)return;return{...branch!==void 0?{branch}:{},...pr!==void 0?{pr}:{},...summary!==void 0?{summary}:{}}}function optionalExtraRepos(payload){let raw=payload.extraRepos;if(raw===void 0||raw===null)return;if(!Array.isArray(raw))throw Error("extraRepos must be an array");return raw.map((entry,i)=>{let item=objectPayload(entry),repo=optionalString(item,"repo");if(!repo)throw Error(`extraRepos[${i}].repo is required`);let baseRef=optionalString(item,"baseRef");return{repo,...baseRef?{baseRef}:{}}})}function payloadDispatcher(payload){let taskId=optionalString(payload,"dispatcherTaskId");return taskId?{taskId,tabId:optionalString(payload,"dispatcherTabId")||"tab-1"}:void 0}function recordAddDispatch(ctx,dispatcher,task){if(!dispatcher)return;ctx.dispatches?.record({kind:"add",from:dispatcher,to:{taskId:task.id,tabId:"tab-1"},promptHead:task.title,delivered:!0})}var TASK_HANDLERS=[{name:"task.list",handle(_payload,ctx){return{tasks:ctx.orch.listTasks().map(serializeTask),activeTaskId:ctx.orch.activeTaskSignal?.()?.()??null}}},{name:"task.get",handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);return{task:serializeTask(task)}}},{name:"task.create",async handle(payload,ctx){let repo=requireString(payload,"repo"),dispatcher=payloadDispatcher(payload),task=await ctx.orch.createTask({repo,title:optionalString(payload,"title"),branch:optionalString(payload,"branch"),baseRef:optionalString(payload,"baseRef"),worktreeName:optionalString(payload,"worktreeName"),extraRepos:optionalExtraRepos(payload),vendor:optionalVendor(payload,"vendor"),command:optionalString(payload,"command"),modelEffort:optionalString(payload,"effort"),model:optionalString(payload,"model"),tier:optionalString(payload,"tier"),groupId:optionalString(payload,"groupId"),forkFrom:optionalString(payload,"forkFrom"),parentTaskId:optionalString(payload,"parentTaskId"),...payload.worktreeOnly===!0?{worktreeOnly:!0}:{},...optionalString(payload,"workspace")==="layerfs"?{workspace:{backend:"layerfs"}}:{},dispatcher});return recordAddDispatch(ctx,dispatcher,task),{taskId:task.id,task:serializeTask(task)}}},{name:"task.spawn",blocking:!0,async handle(payload,ctx){let parentTaskId=requireString(payload,"parentTaskId"),dispatcher=payloadDispatcher(payload),result=await ctx.orch.spawnChildTask({parentTaskId,worktree:optionalBoolean(payload,"worktree")??!0,...payload.worktreeOnly===!0?{worktreeOnly:!0}:{},baseRef:optionalString(payload,"baseRef"),isolateIn:optionalString(payload,"isolateIn"),title:optionalString(payload,"title"),vendor:optionalVendor(payload,"vendor"),command:optionalString(payload,"command"),prompt:optionalString(payload,"prompt"),modelEffort:optionalString(payload,"effort"),model:optionalString(payload,"model"),tier:optionalString(payload,"tier"),groupId:optionalString(payload,"groupId"),branch:optionalString(payload,"branch"),worktreeName:optionalString(payload,"worktreeName"),lazy:optionalBoolean(payload,"lazy"),dispatcher});return recordAddDispatch(ctx,dispatcher,result.task),{taskId:result.task.id,task:serializeTask(result.task),parentDirty:result.parentDirty,sharedLinks:result.sharedLinks}}},{name:"task.rename",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setTitle(taskId,requireString(payload,"title")),{}}},{name:"task.setBranch",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setBranch(taskId,requireString(payload,"branch")),{}}},{name:"task.observeLanguage",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),text2=requireString(payload,"text");return await ctx.orch.observeLanguage(taskId,text2),{}}},{name:"task.setVendor",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),vendor=optionalVendor(payload,"vendor");if(!vendor)throw Error("task.setVendor: vendor is required");let rawEffort=payload.effort;if(rawEffort!==void 0&&typeof rawEffort!=="string")throw Error("effort must be a string");let rawModel=payload.model;if(rawModel!==void 0&&typeof rawModel!=="string")throw Error("model must be a string");return await ctx.orch.setVendor(taskId,vendor,rawEffort,rawModel),{}}},{name:"task.setCommand",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setCommand(taskId,requireString(payload,"command"),optionalVendor(payload,"vendor")),{}}},{name:"task.delete",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),force=optionalBoolean(payload,"force"),deleteBranch=optionalBoolean(payload,"deleteBranch"),cascade=optionalBoolean(payload,"cascade"),targets=cascade?subtreeIds(ctx.orch.listTasks(),taskId):[taskId],tasks=new Map(targets.map((id)=>[id,ctx.orch.getTask(id)])),byTaskId=optionalString(payload,"requestedByTaskId");for(let id of targets)auditDeletionRequested(id,tasks.get(id),{clientId:ctx.clientId,...byTaskId?{requestedBy:{taskId:byTaskId,tabId:optionalString(payload,"requestedByTabId")||"tab-1"}}:{}},{force,deleteBranch});let accepted=await ctx.orch.prepareTaskDeletion(taskId,{force,deleteBranch,cascade});for(let id of targets)await releaseDeletedTask(ctx,id,tasks.get(id));let teardown=Object.fromEntries(targets.flatMap((id)=>{let scope=teardownScope(ctx.orch.listTasks(),id,new Set(targets));return scope.spare.length>0||scope.also.length>0?[[id,scope]]:[]}));if(accepted)for(let id of targets)ctx.deletions.enqueue(id);return{taskId,queued:accepted,...cascade?{deleted:targets}:{},...Object.keys(teardown).length>0?{teardown}:{}}}},{name:"task.landPreflight",async handle(payload,ctx){return{result:await ctx.orch.landPreflight(requireString(payload,"taskId"),optionalString(payload,"repo"))}}},{name:"task.land",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),strategy=optionalString(payload,"strategy")==="squash"?"squash":"merge",result=await ctx.orch.landTask(taskId,{strategy,deleteBranch:optionalBoolean(payload,"deleteBranch")===!0,removeWorktree:optionalBoolean(payload,"removeWorktree"),callerCwd:optionalString(payload,"callerCwd"),repo:optionalString(payload,"repo")});if(result.stopped){let{code,message}=result.stopped;throw Object.assign(Error(message.startsWith(`${code}: `)?message:`${code}: ${message}`),{name:"LandStoppedError",data:{stopped:result.stopped,repos:result.repos}})}return ctx.plugins?.handleUiReport({kind:"task.landed",taskId,detail:{strategy:result.strategy,landedOn:result.landedOn,commit:result.commit}}),{result}}},{name:"task.syncBase",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);let only=optionalString(payload,"repo");if(pickRepos(task,only),task.extraRepos?.length)return{result:await syncRepos(ctx.runtime,task,only)};if(!task.worktreePath)throw Error("task has no worktree to sync");return{result:await ctx.runtime.syncWorktreeWithBase(task.worktreePath,task.baseRef)}}},{name:"task.setParent",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),parentTaskId=payload.parentTaskId===null?null:requireString(payload,"parentTaskId");return await ctx.orch.setParent(taskId,parentTaskId,optionalString(payload,"replyTab"))}},{name:"task.moveToProject",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),{repo,moved}=await ctx.orch.moveTaskToProject(taskId,requireString(payload,"repo"));return{taskId,repo,moved}}},{name:"task.requireReport",async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(typeof payload.required!=="boolean")throw Error("required must be a boolean");return await ctx.orch.setRequireReport(taskId,payload.required),{}}},{name:"task.move",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),direction=requireString(payload,"direction");if(direction==="top")await ctx.orch.moveTaskToTop(taskId);else if(direction==="up"||direction==="down")await ctx.orch.moveTask(taskId,direction==="up"?-1:1);else throw Error("direction must be up, down or top");return{}}},{name:"project.move",async handle(payload,ctx){let repo=requireString(payload,"repo"),target=requireString(payload,"target"),side=requireString(payload,"side");if(side!=="before"&&side!=="after")throw Error("side must be before or after");return await ctx.orch.moveProject(repo,target,side),{}}},{name:"task.status",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),status=requireString(payload,"status");if(!ctx.runtime.isTaskStatus(status))throw Error("status must be a TaskStatus");let linked=status==="done"?ctx.orch.getTask(taskId):void 0,prevStatus=linked?.status;await ctx.orch.setStatus(taskId,status);let report=optionalWorkerReport(payload);if(report)await ctx.orch.setWorkerReport(taskId,report);if(status==="done"&&prevStatus!=="done"&&linked&&isBuiltinModInstalled("kanban",ctx.daemon.homeDir))try{let next=await ctx.issues.mirrorTaskDone(linked.repo,taskId);if(next)publishIssueSnapshot(ctx,next)}catch(err){logDaemonError("issue-done-mirror",err)}return{}}},{name:"task.ensureMain",blocking:!0,async handle(payload,ctx){let repo=requireString(payload,"repo"),task=await ctx.orch.ensureMainTask(repo);return{task:serializeTask(task)}}},{name:"project.forget",async handle(payload,ctx){let repo=requireString(payload,"repo");return await ctx.orch.forgetProject(repo),{}}},{name:"task.ensureWorktree",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId");ctx.bus.publish("task.jobs",{taskId,kind:"ensureWorktree",phase:"running"});try{let path=await ctx.orch.ensureWorktree(taskId,{onProgress:(progress)=>ctx.bus.publish("task.jobs",{taskId,kind:"ensureWorktree",phase:"running",progress})});return ctx.bus.publish("task.jobs",{taskId,kind:"ensureWorktree",phase:"done"}),{worktreePath:path}}catch(err){throw ctx.bus.publish("task.jobs",{taskId,kind:"ensureWorktree",phase:"error",error:err instanceof Error?err.message:String(err)}),err}}},{name:"task.setPrompt",async handle(payload,ctx){let taskId=requireString(payload,"taskId");return await ctx.orch.setPrompt(taskId,requireString(payload,"prompt")),{}}},{name:"task.setActive",async handle(payload,ctx){let taskId=optionalString(payload,"taskId")??null;return await ctx.orch.setActiveTask(taskId),ctx.bus.publish("active-task",{taskId}),{}}}];import{randomUUID}from"crypto";var PROMPT_DEFAULT_TIMEOUT_MS=120000,PROMPT_MAX_TIMEOUT_MS=600000,TAB_CLOSE_TUI_TIMEOUT_MS=750;function reaches(ctx,channel){return ctx.daemon.hasSubscribersFor?.(channel)??!0}var UI_HANDLERS=[{name:"session.deliver",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),text2=requireString(payload,"text"),tabId=optionalString(payload,"tabId"),source=optionalString(payload,"source");if(source!==void 0&&source!=="note"&&source!=="dispatcher")throw Error('source must be "note" or "dispatcher"');let task=ctx.orch.getTask(taskId);if(!task)throw Error(`task not found: ${taskId}`);let scope=ptyScopeFor(ctx.orch.listTasks(),task.id),outcome=task.worktreePath?await(tabId===void 0?ctx.runtime.deliverPromptToLiveEngineDetailed({id:task.id,vendor:task.vendor,command:task.command,worktreePath:task.worktreePath,scope},text2):ctx.runtime.deliverPromptToLiveEngineTabDetailed({id:task.id,tabId,vendor:task.vendor,command:task.command,worktreePath:task.worktreePath,scope},text2)).catch(()=>({outcome:"no-session"})):{outcome:"no-session"};if(outcome.outcome==="no-session")ctx.bus.publish("session.deliver",{taskId,text:text2,...tabId!==void 0?{tabId}:{},at:Date.now(),source:source??"dispatcher"});if(source!=="note")ctx.dispatches?.record({kind:"dispatch",from:senderOf(payload),to:{taskId,tabId:"tabId"in outcome?outcome.tabId:tabId??null},promptHead:text2,delivered:outcome.outcome==="delivered",...outcome.outcome==="delivered"?{}:{reason:outcome.outcome==="no-session"?"broadcast":outcome.outcome}});if(ctx.plugins?.handleUiReport({kind:"message.delivered",taskId,detail:{source:source??"dispatcher",...tabId!==void 0?{tabId}:{},length:text2.length,clients:ctx.daemon.clientCount()}}),outcome.outcome==="delivered")return{ok:!0,delivered:!0,tabId:outcome.tabId,clients:ctx.daemon.clientCount()};if(outcome.outcome==="no-engine")return{ok:!0,delivered:!1,reason:"no-engine",tabId:outcome.tabId,clients:ctx.daemon.clientCount()};return{ok:!0,delivered:!1,reason:"broadcast",clients:ctx.daemon.clientCount()}}},{name:"ui.reportEvent",async handle(payload,ctx){let kind=requireString(payload,"kind");if(!kind.match(/^(file\.(will-open|opened|closed)|task\.opened|project\.opened|tab\.(opened|closed))$/))throw Error(`unknown ui event kind: ${kind}`);let taskId=optionalString(payload,"taskId"),detail=payload.detail,eventDetail=detail&&typeof detail==="object"&&!Array.isArray(detail)?detail:void 0;if(kind==="tab.closed"&&taskId){let closedTabId=eventDetail?.tabId;if(typeof closedTabId==="string"&&closedTabId)ctx.activity.clearTab(taskId,closedTabId),ctx.graphics?.clearTab(taskId,closedTabId)}return ctx.plugins?.handleUiReport({kind,...taskId?{taskId}:{},...eventDetail?{detail:eventDetail}:{}}),{}}},{name:"ui.prompt",blocking:!0,async handle(payload,ctx){let broker=ctx.prompts;if(!broker)throw Error("prompt broker unavailable");let title=requireString(payload,"title");if(!reaches(ctx,"ui.prompt"))return{cancelled:!0,reason:"no-gui"};let placeholder=optionalString(payload,"placeholder"),initial=optionalString(payload,"initial"),rawTimeout=payload.timeoutMs,timeoutMs=Math.min(typeof rawTimeout==="number"&&rawTimeout>=1000?rawTimeout:PROMPT_DEFAULT_TIMEOUT_MS,PROMPT_MAX_TIMEOUT_MS),promptId=randomUUID(),result=broker.create(promptId,timeoutMs);return ctx.bus.publish("ui.prompt",{promptId,title,...placeholder?{placeholder}:{},...initial?{initial}:{},at:Date.now()}),await result}},{name:"ui.promptReply",async handle(payload,ctx){let broker=ctx.prompts;if(!broker)throw Error("prompt broker unavailable");let promptId=requireString(payload,"promptId"),value=optionalString(payload,"value");return{ok:broker.settle(promptId,value!==void 0?{value}:{cancelled:!0,reason:"cancelled"})}}},{name:"mod.press",async handle(payload,ctx){let plugin=requireString(payload,"plugin"),pane=requireString(payload,"pane"),key=requireString(payload,"key"),outcome=ctx.plugins?.pressMod(plugin,pane,key)??"no-mod";return outcome==="sent"?{ok:!0}:{ok:!1,reason:outcome}}},{name:"mod.submit",async handle(payload,ctx){let plugin=requireString(payload,"plugin"),pane=requireString(payload,"pane"),key=requireString(payload,"key"),value=payload.value;if(typeof value!=="string")throw Error("value must be a string");let outcome=ctx.plugins?.submitMod(plugin,pane,key,value)??"no-mod";return outcome==="sent"?{ok:!0}:{ok:!1,reason:outcome}}},{name:"tab.open",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),title=requireString(payload,"title"),argv=payload.argv;if(!Array.isArray(argv)||argv.length===0||!argv.every((a)=>typeof a==="string"&&a.length>0))throw Error("argv must be a non-empty array of strings");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);let placement=optionalString(payload,"placement"),direction=optionalString(payload,"direction"),tabId=optionalString(payload,"tabId");return ctx.bus.publish("tab.open",{taskId,argv,title,...tabId!==void 0?{tabId}:{},...placement==="tab"||placement==="split"?{placement}:{},...direction==="right"||direction==="down"?{direction}:{},at:Date.now()}),{ok:!0,clients:ctx.daemon.clientCount(),reached:reaches(ctx,"tab.open")}}},{name:"tab.close",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),title=requireString(payload,"title"),tabId=optionalString(payload,"tabId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return ctx.bus.publish("tab.close",{taskId,title,...tabId!==void 0?{tabId}:{},at:Date.now()}),{ok:!0,clients:ctx.daemon.clientCount(),reached:reaches(ctx,"tab.close")}}},{name:"terminalTab.close",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=requireString(payload,"tabId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);let broker=ctx.tabCloses;if(!broker||ctx.daemon.guiCount()===0)return{ok:!0,handled:!1};let requestId=randomUUID(),handled=broker.create(requestId,TAB_CLOSE_TUI_TIMEOUT_MS);return ctx.bus.publish("tab.close",{kind:"terminal-tab",taskId,tabId,requestId,at:Date.now()}),{ok:!0,handled:await handled}}},{name:"terminalTab.closeReply",handle(payload,ctx){let requestId=requireString(payload,"requestId"),closed=optionalBoolean(payload,"closed")??!1;return{ok:ctx.tabCloses?.settle(requestId,closed)??!1}}},{name:"terminalTab.rename",handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=requireString(payload,"tabId"),title=optionalString(payload,"title")??"";if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return ctx.bus.publish("tab.rename",{taskId,tabId,title,at:Date.now()}),{ok:!0,clients:ctx.daemon.clientCount()}}},{name:"terminalTab.add",handle(payload,ctx){let taskId=requireString(payload,"taskId"),tab=objectPayload(payload.tab);if(typeof tab.id!=="string"||typeof tab.kind!=="string")throw Error("tab must be an object with a string id and kind");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return ctx.bus.publish("tab.add",{taskId,tab,at:Date.now()}),{ok:!0,clients:ctx.daemon.clientCount()}}},{name:"notice.send",async handle(payload,ctx){let title=requireString(payload,"title"),body=optionalString(payload,"body"),kind=optionalString(payload,"kind")??"done";if(kind.trim()==="")throw Error("kind must be a non-empty string");let taskId=optionalString(payload,"taskId");if(taskId!==void 0&&!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);let source=optionalString(payload,"source");return ctx.bus.publish("notice.event",{title,body,kind,taskId,at:Date.now(),source}),{ok:!0,clients:ctx.daemon.clientCount()}}},{name:"note.file",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),text2=requireString(payload,"text"),author=ctx.orch.getTask(taskId);if(!author)throw Error(`task not found: ${taskId}`);let label=displayTaskTitle(author)||taskId,persisted=await ctx.notes?.append(author.repo,{at:new Date().toISOString(),text:text2,taskId,author:label}).then(()=>!0).catch(()=>!1)??!1;return ctx.plugins?.handleUiReport({kind:"note.filed",taskId,detail:{repo:author.repo,author:label,text:text2.length>512?`${text2.slice(0,512)}\u2026`:text2,length:text2.length,persisted}}),{ok:!0,persisted}}},{name:"note.list",async handle(payload,ctx){let repo=requireString(payload,"repo");return{notes:await ctx.notes?.list(repo)??[]}}},{name:"note.delete",async handle(payload,ctx){let repo=requireString(payload,"repo"),id=requireNumber(payload,"id");return{deleted:await ctx.notes?.remove(repo,id)??!1}}}];function workItemTaskTitle(item){let title=item.title.trim(),room=60-`#${item.number} `.length,points=[...title];if(points.length<=room)return`#${item.number} ${title}`;let clipped=points.slice(0,room-1).join("").trimEnd();return`#${item.number} ${clipped}\u2026`}function fenceFor(text2){let longest=text2.match(/`+/g)?.reduce((n,run)=>Math.max(n,run.length),0)??0;return"`".repeat(Math.max(3,longest+1))}function buildWorkItemPrompt(item){let body=(item.body??"").trim(),clipped=body.length>8000?`${body.slice(0,8000)}
|
|
56
56
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ulid}from"./chunk-qkehg2c1.js";import{acquireWithRetry,mergeTasksWithDisk,readDiskIndex,recoverIndexFromDisk}from"./chunk-
|
|
2
|
+
import{ulid}from"./chunk-qkehg2c1.js";import{acquireWithRetry,mergeTasksWithDisk,readDiskIndex,recoverIndexFromDisk}from"./chunk-yfwn3fj5.js";import{DEFAULT_TASK_VENDOR,toTaskId}from"./chunk-xy8be792.js";import{release}from"./chunk-w8da1czv.js";import{ROVE_STATE_DIR_BASENAME}from"./chunk-zt7wfnva.js";import{preRenameStateDir}from"./chunk-g6wb8p4p.js";import{readRoveHomeDirEnv}from"./chunk-nc46gddg.js";import{mkdir,open,rename,unlink}from"fs/promises";import{homedir}from"os";import{dirname,join}from"path";var CURRENT_VERSION=3;class TaskIndexStore{homeDir;roveDir;path;legacyPath;lockPath;cache={version:CURRENT_VERSION,tasks:[]};loaded=!1;listeners=new Set;saveChain=Promise.resolve();dirtyIds=new Set;removedIds=new Map;constructor(options={}){this.homeDir=options.homeDir??readRoveHomeDirEnv()??homedir(),this.roveDir=join(this.homeDir,ROVE_STATE_DIR_BASENAME),this.path=join(this.roveDir,"tasks.json"),this.legacyPath=join(preRenameStateDir(this.homeDir),"tasks.json"),this.lockPath=`${this.path}.lock`}subscribe(listener){if(this.listeners.add(listener),this.loaded)try{listener(this.cache.tasks.slice())}catch(err){console.error("[rove TaskIndexStore] listener threw on subscribe:",err)}return()=>{this.listeners.delete(listener)}}get filePath(){return this.path}get stateDir(){return this.roveDir}async load(){return this.dirtyIds.clear(),this.removedIds.clear(),this.cache=await recoverIndexFromDisk(this.path,this.legacyPath),this.loaded=!0,this.notifyListeners(),this.snapshot()}async save(){this.assertLoaded();let next=this.saveChain.then(()=>this.doSave());return this.saveChain=next.catch(()=>{}),next}async saveOrRollback(id,undo){try{await this.save()}catch(err){if(undo())this.dirtyIds.delete(id),this.notifyListeners();throw err}}async doSave(){await mkdir(dirname(this.path),{recursive:!0});let dirty=new Set(this.dirtyIds),removed=new Map(this.removedIds),lockToken=await acquireWithRetry(this.lockPath),cacheChanged=!1;try{let disk=await readDiskIndex(this.path,this.legacyPath),merged=mergeTasksWithDisk(this.cache.tasks,disk.tasks,dirty,removed,disk.removed),payload={version:CURRENT_VERSION,tasks:merged.tasks,...merged.removed.length>0?{removed:merged.removed}:{}},json=`${JSON.stringify(payload)}
|
|
3
3
|
`,tmpPath=`${this.path}.${process.pid}.${ulid()}.tmp`;try{let handle=await open(tmpPath,"w",384);try{await handle.writeFile(json,"utf8"),await handle.sync()}finally{await handle.close()}await rename(tmpPath,this.path)}catch(err){throw await unlink(tmpPath).catch(()=>{}),err}for(let id of dirty)this.dirtyIds.delete(id);for(let id of removed.keys())this.removedIds.delete(id);let present=new Set(this.cache.tasks.map((t)=>t.id));for(let task of merged.tasks){if(present.has(task.id))continue;this.cache.tasks.push(task),cacheChanged=!0}let tombstoned=new Set(merged.removed.map((t)=>t.id));if(tombstoned.size>0)for(let i=this.cache.tasks.length-1;i>=0;i--){let entry=this.cache.tasks[i];if(!entry||!tombstoned.has(entry.id))continue;this.cache.tasks.splice(i,1),cacheChanged=!0}}finally{await release(this.lockPath,lockToken).catch((err)=>{console.error("[rove TaskIndexStore] index lock release failed:",err)})}if(cacheChanged)this.notifyListeners()}get(id){return this.assertLoaded(),this.cache.tasks.find((t)=>t.id===id)}list(){return this.assertLoaded(),this.cache.tasks.slice()}async create(partial){this.assertLoaded();let now=new Date().toISOString(),task={vendor:partial.vendor??DEFAULT_TASK_VENDOR,...partial,id:toTaskId(ulid()),createdAt:now,updatedAt:now};return this.cache.tasks.push(task),this.dirtyIds.add(task.id),await this.saveOrRollback(task.id,()=>{let at=this.cache.tasks.indexOf(task);if(at<0)return!1;return this.cache.tasks.splice(at,1),!0}),this.notifyListeners(),task}async update(id,patch){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id);if(idx<0)throw Error(`task not found: ${id}`);let existing=this.cache.tasks[idx];if(!existing)throw Error(`task not found: ${id}`);let{id:_id,createdAt:_createdAt,...mutable}=patch,next={...existing,...mutable,id:existing.id,createdAt:existing.createdAt,updatedAt:new Date().toISOString()};return this.cache.tasks[idx]=next,this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks[at]=existing,!0}),this.notifyListeners(),next}async move(id,delta,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);let ids=withinIds?.length?withinIds:this.cache.tasks.map((t)=>t.id),pos=ids.indexOf(String(id));if(pos<0)throw Error(`task not movable in current group: ${id}`);let targetId=ids[pos+delta];if(!targetId)return task;let fromIdx=this.cache.tasks.findIndex((t)=>t.id===id),toIdx=this.cache.tasks.findIndex((t)=>t.id===targetId);if(fromIdx<0||toIdx<0||fromIdx===toIdx)return task;let[moved]=this.cache.tasks.splice(fromIdx,1);if(!moved)return task;let adjustedToIdx=fromIdx<toIdx?toIdx-1:toIdx,insertAt=delta>0?adjustedToIdx+1:adjustedToIdx,next={...moved,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(insertAt,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,moved),!0}),this.notifyListeners(),next}async moveToFront(id,withinIds){this.assertLoaded();let task=this.cache.tasks.find((t)=>t.id===id);if(!task)throw Error(`task not found: ${id}`);if(!withinIds.includes(String(id)))throw Error(`task not movable in current group: ${id}`);if(withinIds[0]===String(id))return task;let fromIdx=this.cache.tasks.indexOf(task),toIdx=this.cache.tasks.findIndex((t)=>t.id===withinIds[0]),next={...task,updatedAt:new Date().toISOString()};return this.cache.tasks.splice(fromIdx,1),this.cache.tasks.splice(toIdx,0,next),this.dirtyIds.add(String(id)),await this.saveOrRollback(String(id),()=>{let at=this.cache.tasks.indexOf(next);if(at<0)return!1;return this.cache.tasks.splice(at,1),this.cache.tasks.splice(Math.min(fromIdx,this.cache.tasks.length),0,task),!0}),this.notifyListeners(),next}async moveBlock(ids,anchorId,side){this.assertLoaded();let lifted=new Set(ids);if(lifted.has(anchorId))throw Error(`cannot move a block beside itself: ${anchorId}`);let prior=this.cache.tasks.slice(),block=prior.filter((t)=>lifted.has(t.id)),rest=prior.filter((t)=>!lifted.has(t.id)),anchor=rest.findIndex((t)=>t.id===anchorId);if(anchor<0)throw Error(`task not found: ${anchorId}`);if(block.length===0)return;let at=side==="after"?anchor+1:anchor,next=[...rest.slice(0,at),...block,...rest.slice(at)];this.cache.tasks.splice(0,this.cache.tasks.length,...next);try{await this.save()}catch(err){if(this.cache.tasks.length===next.length&&this.cache.tasks.every((t,i)=>t===next[i]))this.cache.tasks.splice(0,this.cache.tasks.length,...prior),this.notifyListeners();throw err}this.notifyListeners()}async remove(id){this.assertLoaded();let idx=this.cache.tasks.findIndex((t)=>t.id===id),removed=this.cache.tasks[idx];if(idx<0||!removed)return!1;return this.cache.tasks.splice(idx,1),this.dirtyIds.delete(String(id)),this.removedIds.set(String(id),new Date().toISOString()),await this.saveOrRollback(String(id),()=>{if(this.cache.tasks.some((t)=>t.id===removed.id))return!1;return this.removedIds.delete(String(id)),this.cache.tasks.splice(Math.min(idx,this.cache.tasks.length),0,removed),!0}),this.notifyListeners(),!0}async _unlinkForTests(){try{await unlink(this.path)}catch(err){if(err.code!=="ENOENT")throw err}this.cache={version:CURRENT_VERSION,tasks:[]},this.loaded=!1,this.dirtyIds.clear(),this.removedIds.clear()}assertLoaded(){if(!this.loaded)throw Error("TaskIndexStore: call load() before any other method")}snapshot(){return{version:CURRENT_VERSION,tasks:this.cache.tasks.slice()}}notifyListeners(){if(this.listeners.size===0)return;let snapshot=this.cache.tasks.slice();for(let listener of this.listeners)try{listener(snapshot)}catch(err){console.error("[rove TaskIndexStore] listener threw on notify:",err)}}}
|
|
4
4
|
export{TaskIndexStore};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{DAEMON_UNREACHABLE_MESSAGE,argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,isDaemonUnreachable,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-9eqts8fy.js";import"./chunk-83jfmryc.js";import"./chunk-10qdd96d.js";import"./chunk-wpssm9js.js";import"./chunk-btvs2v81.js";import"./chunk-38hnq4aq.js";import"./chunk-gj8eqt7m.js";import"./chunk-rz19rphb.js";import"./chunk-67k0f144.js";import"./chunk-2xsxcdp6.js";import"./chunk-mfmythv2.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-4hestsjp.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-5mhvjytn.js";import"./chunk-atn06ncf.js";import"./chunk-qqesxgnt.js";import"./chunk-bwh5y3ra.js";import"./chunk-t2q30c4r.js";import"./chunk-5dkx02g8.js";import"./chunk-x0f8a3ez.js";import"./chunk-qkehg2c1.js";import"./chunk-k6gx8sqh.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-vt7rzq32.js";import"./chunk-x4yxwa4b.js";import"./chunk-21hxxbnv.js";import"./chunk-e5dv15e5.js";import"./chunk-49zrnjq1.js";import"./chunk-mqfvzdpr.js";import"./chunk-afyn4v7z.js";import"./chunk-rxqdw6s5.js";import"./chunk-52y3whbh.js";import"./chunk-q30ggttf.js";import"./chunk-2ebc6hrh.js";import"./chunk-j54ekzg2.js";import"./chunk-b9ea827p.js";import"./chunk-yx4mar9e.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-0mw4pd9k.js";import"./chunk-catrr0z3.js";import"./chunk-ewdanfd9.js";import"./chunk-tn9gtf18.js";import"./chunk-y849hsgp.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-dpgaag6b.js";import"./chunk-cmp64q4j.js";import"./chunk-aagx78v1.js";import"./chunk-qbbtvxmk.js";import"./chunk-wwes4z56.js";import"./chunk-w7zv47mp.js";import"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-mg1cas61.js";import"./chunk-p84bhs57.js";import"./chunk-hkqcc1t4.js";import"./chunk-1tmmkk54.js";import"./chunk-7kysxgbq.js";import"./chunk-yfwn3fj5.js";import"./chunk-vfrxywtx.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-w8da1czv.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,isDaemonUnreachable,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams,DAEMON_UNREACHABLE_MESSAGE};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,shareInflight,vendorFromArgv}from"./chunk-aagx78v1.js";import"./chunk-qbbtvxmk.js";import"./chunk-wwes4z56.js";import"./chunk-w7zv47mp.js";import"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-mg1cas61.js";import"./chunk-p84bhs57.js";import"./chunk-hkqcc1t4.js";import"./chunk-1tmmkk54.js";import"./chunk-7kysxgbq.js";import"./chunk-yfwn3fj5.js";import"./chunk-vfrxywtx.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-w8da1czv.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{PsProbeUnavailableError}from"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{vendorFromArgv,shareInflight,psSnapshotWith,psSnapshot,parsePsSnapshot,hasAncestor,foregroundEngineIn,foregroundEngine,engineProcessIn,PsProbeUnavailableError,PS_PROBE_TIMEOUT_MS};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{readOutdatedCache}from"./chunk-498t9sjd.js";import{hookConfigIssues}from"./chunk-
|
|
2
|
+
import{readOutdatedCache}from"./chunk-498t9sjd.js";import{hookConfigIssues}from"./chunk-mw3bka09.js";import{tightenPluginPermissions}from"./chunk-wwpq8gs4.js";import{engineSkillDir,readSkillCopy}from"./chunk-bwzeg7tk.js";import{PREFIX_KEY_ID,defaultKeymapCopy,findBinding}from"./chunk-k6xmydtr.js";import{AUTO_ROUTING_TIERS}from"./chunk-10qdd96d.js";import{reloadPluginEngines}from"./chunk-wpssm9js.js";import{ENGINE_ACTIVITY_KINDS}from"./chunk-17e2tgyg.js";import{currentPluginPlatform,loadPluginRegistry,parsePluginManifest,pluginManifestPath,qualifiedActionId,readPluginManifest,savePluginRegistry,supportsPlatform}from"./chunk-psxhek7n.js";import{readOnlyGitProcessEnv}from"./chunk-6xppe9bj.js";import{THEME_MODE_PREFERENCES,ensureContrast,inkAtHue,oklchCusp,relativeLuminance,toOklch}from"./chunk-afyn4v7z.js";import{expandHome}from"./chunk-2ebc6hrh.js";import{pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import{readFirstNonEmptyRepoFile}from"./chunk-catrr0z3.js";import{tildify}from"./chunk-1feav1w3.js";import{LOCALES,t}from"./chunk-dpgaag6b.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{activityHookAdapters,engineEntry,maybeStartScheduledRun,spawnCapture}from"./chunk-qbbtvxmk.js";import{recordSpawn}from"./chunk-40dgv828.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{loadStateFile}from"./chunk-p84bhs57.js";import{ROVE_HOOK_VERSION}from"./chunk-1tmmkk54.js";import{rollupPr}from"./chunk-yfwn3fj5.js";import{pathIdentity,pathSyntax}from"./chunk-pn5ygqn6.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE}from"./chunk-yt15y085.js";import{promptAttachmentsDir}from"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import{readRoveEnv}from"./chunk-nc46gddg.js";var pluginPageErrorState=createStateCell([],"plugin-page-errors");function pluginPageErrors(){return pluginPageErrorState.get()}var WORKING_BORDER_KEY="appearance.workingBorder",WORKING_BORDERS=["flow","still"],DEFAULT_WORKING_BORDER="flow";function normalizeWorkingBorder(raw){return WORKING_BORDERS.includes(raw)?raw:"flow"}var SCROLLBACK_ROWS_KEY="terminal.scrollbackRows",DEFAULT_SCROLLBACK_ROWS=1000,SCROLLBACK_ROWS_MIN=100,SCROLLBACK_ROWS_MAX=1e5;function normalizeScrollbackRows(value){let n=typeof value==="number"?Math.floor(value):typeof value==="string"?Number.parseInt(value.trim(),10):Number.NaN;if(!Number.isFinite(n))return DEFAULT_SCROLLBACK_ROWS;return Math.min(SCROLLBACK_ROWS_MAX,Math.max(SCROLLBACK_ROWS_MIN,n))}function persistedScrollbackRows(){return normalizeScrollbackRows(loadStateFile()[SCROLLBACK_ROWS_KEY])}function relativeBuckets(absMs){let minutes=Math.floor(absMs/60000),hours=Math.floor(minutes/60);return{minutes,hours,days:Math.floor(hours/24)}}function relativeAge(ms,nowMs=Date.now()){let delta=Math.max(0,nowMs-ms),secs=Math.floor(delta/1000);if(secs<60)return`${secs}s`;let{minutes,hours,days}=relativeBuckets(delta);if(minutes<60)return`${minutes}m`;if(hours<24)return`${hours}h`;return`${days}d`}import{randomBytes}from"crypto";import{existsSync,mkdirSync,writeFileSync}from"fs";import{isAbsolute,join}from"path";var ATTACHMENT_EXTENSION_REGEX=/\.(png|jpe?g|gif|webp|pdf)$/i,PDF_EXTENSION_REGEX=/\.pdf$/i;function removeOuterQuotes(text){if(text.startsWith('"')&&text.endsWith('"')||text.startsWith("'")&&text.endsWith("'"))return text.slice(1,-1);return text}function stripBackslashEscapes(path){let placeholder=`__DOUBLE_BACKSLASH_${randomBytes(8).toString("hex")}__`;return path.replace(/\\\\/g,placeholder).replace(/\\(.)/g,"$1").replaceAll(placeholder,"\\")}function asAttachmentPath(text,exists=existsSync){let cleaned=stripBackslashEscapes(removeOuterQuotes(text.trim()));if(!ATTACHMENT_EXTENSION_REGEX.test(cleaned))return null;if(!isAbsolute(cleaned))return null;return exists(cleaned)?cleaned:null}function asAttachmentPaths(pasted,exists=existsSync){let lines=pasted.split(`
|
|
3
3
|
`).map((l)=>l.trim()).filter((l)=>l.length>0);if(lines.length===0)return null;let paths=[];for(let line of lines){let p=asAttachmentPath(line,exists);if(!p)return null;paths.push(p)}return paths}function attachmentLabel(path,index){if(PDF_EXTENSION_REGEX.test(path))return`pdf[${index}]`;return ATTACHMENT_EXTENSION_REGEX.test(path)?`images[${index}]`:`files[${index}]`}function appendAttachmentRefs(prompt,attachments){if(attachments.length===0)return prompt;let refs=attachments.map((p,i)=>`${attachmentLabel(p,i)}: ${p}`).join(`
|
|
4
4
|
`);return`${prompt}
|
|
5
5
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{RemoteOrchestrator}from"./chunk-
|
|
2
|
+
import{RemoteOrchestrator}from"./chunk-889x8v49.js";import{dedupeMachines,discoverMachine,duplicateAliasOf,learnedFrom,listMachines,readMachines,setMachineIdentity,startTunnel,updateMachine}from"./chunk-x0f8a3ez.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{RoveDaemonClient}from"./chunk-29b3pj9h.js";import{loadStateFile}from"./chunk-p84bhs57.js";import{logClient,logClientError}from"./chunk-vfrxywtx.js";function discoverReason(failure){switch(failure.code){case"SSH_FAILED":return!failure.ssh||failure.ssh==="unknown"?"ssh-failed":failure.ssh;case"NO_ROVE":return"no-rove";case"NO_DAEMON":return"no-daemon";default:return"bad-status"}}var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map},PEER_CHANNELS=["task.snapshot","engine-state","worktree.changes","task.tokens"];class MachineHub{slots=new Map;machinesAcc=createStateCell([],"machines.status");tasksAcc=createStateCell([],"machines.tasks");liveAcc=createStateCell(NO_LIVE,"machines.live");disposed=!1;machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}remoteTaskIds(){let ids=new Set;for(let slot of this.slots.values())for(let task of slot.tasks)ids.add(String(task.id));return ids}sync(entries=dedupeMachines(listMachines())){if(this.disposed)return;let wanted=new Map(entries.map((entry)=>[entry.alias,entry])),fresh=[];for(let[alias,slot]of this.slots){let next=wanted.get(alias);if(next&&sameAddress(slot.entry,next))slot.entry=next;else this.drop(alias)}for(let entry of entries){if(this.slots.has(entry.alias))continue;this.slots.set(entry.alias,{entry,tasks:[]}),fresh.push(entry)}if(fresh.length===0&&wanted.size===this.slots.size&&this.machinesAcc.get().length===wanted.size)return;let known=new Map(this.machinesAcc.get().map((row)=>[row.alias,row]));this.machinesAcc.set([...this.slots.values()].map((slot)=>known.get(slot.entry.alias)??{alias:slot.entry.alias,hostLabel:slot.entry.alias,state:"connecting"})),this.republishTasks(),this.republishLive();for(let entry of fresh)this.connect(entry)}drop(alias){let slot=this.slots.get(alias);if(!slot)return;this.slots.delete(alias),slot.unsubscribe?.(),slot.orchestrator?.dispose(),slot.tunnel?.stop()}async connect(entry){let slot=this.slots.get(entry.alias);if(!slot||this.disposed)return;let found=await discoverMachine(entry.alias,entry);if(this.disposed||this.slots.get(entry.alias)!==slot)return;let sockets=found.ok?{daemon:found.status.socketPath,pty:found.status.ptySocketPath}:entry.sockets,failed=found.ok?{}:{error:found.message,reason:discoverReason(found)};if(!sockets){this.setStatus(entry.alias,{state:"offline",...failed});return}if(!found.ok)this.setStatus(entry.alias,failed);let learned=found.ok?learnedFrom(found):{};if(found.ok)updateMachine(entry.alias,learned);let tunnel=startTunnel({alias:entry.alias,config:{...entry,...learned,sockets},remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(slot.tunnel=tunnel,tunnel.state()==="unsupported"){this.setStatus(entry.alias,{state:"unsupported",error:"SSH unix-socket forwarding is not available on Windows",reason:"no-forwarding"});return}if(tunnel.onState((state)=>{if(this.slots.get(entry.alias)!==slot)return;if(state==="online")this.openOrchestrator(entry,tunnel);else if(state==="offline"){let known=this.machinesAcc.get().find((row)=>row.alias===entry.alias)?.reason;this.setStatus(entry.alias,{state:"offline",reason:known??"lost"}),this.republishTasks()}}),tunnel.state()==="online")await this.openOrchestrator(entry,tunnel)}async openOrchestrator(entry,tunnel){let slot=this.slots.get(entry.alias);if(!slot||this.disposed||slot.orchestrator)return;let client=new RoveDaemonClient(tunnel.daemonSocketPath),orchestrator=new RemoteOrchestrator(client,{role:"gui",channels:PEER_CHANNELS,expectForeignHome:!0,onPeerIdentity:(peer)=>this.onPeerIdentity(entry.alias,peer)});slot.orchestrator=orchestrator;try{if(await orchestrator.init(),this.slots.get(entry.alias)!==slot)return}catch(err){let message=err instanceof Error?err.message:String(err);this.setStatus(entry.alias,{state:classifyHandshakeFailure(message),error:message,reason:"handshake"}),logClientError("machines",err);return}let stopTasks=orchestrator.tasksSignal().subscribe(()=>{slot.tasks=orchestrator.tasksSignal().get(),this.republishTasks()}),stopConnection=orchestrator.connectionStateSignal().subscribe(()=>{let connected=orchestrator.connectionStateSignal().get()==="online";if(this.slots.get(entry.alias)!==slot)return;this.setStatus(entry.alias,connected?{state:"online",error:void 0,reason:void 0}:{state:"offline",reason:"lost"}),this.republishTasks()}),live=[orchestrator.engineStateSignal(),orchestrator.worktreeChangesSignal(),orchestrator.rowTokensSignal()].map((signal)=>signal.subscribe(()=>this.republishLive()));slot.unsubscribe=()=>{stopTasks(),stopConnection();for(let stop of live)stop()},slot.tasks=orchestrator.tasksSignal().get(),this.setStatus(entry.alias,{state:"online",version:orchestrator.daemonVersionSignal().get()??void 0,error:void 0,reason:void 0}),this.republishTasks(),this.republishLive(),logClient("machines",`${entry.alias} online (${slot.tasks.length} tasks)`)}republishLive(){let activity=new Map,changes=new Map,tokens=new Map;for(let slot of this.slots.values()){let o=slot.orchestrator;if(!o)continue;for(let[id,state]of o.engineStateSignal().get())activity.set(id,state);for(let[path,change]of o.worktreeChangesSignal().get()??[])changes.set(path,change);for(let[id,chips]of o.rowTokensSignal().get())tokens.set(id,chips)}this.liveAcc.set({activity,changes,tokens})}onPeerIdentity(alias,peer){if(!peer.hostname&&!peer.homeDir)return;let identity={hostname:peer.hostname,homeDir:peer.homeDir,daemonPid:peer.daemonPid};setMachineIdentity(alias,identity);let duplicate=duplicateAliasOf(readMachines(loadStateFile()),alias,identity);this.setStatus(alias,{hostname:peer.hostname||void 0,version:peer.roveVersion||void 0,...duplicate?{duplicateOf:duplicate}:{}})}setStatus(alias,patch){let next=this.machinesAcc.get().map((row)=>row.alias===alias?{...row,...patch}:row);this.machinesAcc.set(next)}republishTasks(){let merged=[];for(let slot of this.slots.values()){let status=this.machinesAcc.get().find((row)=>row.alias===slot.entry.alias);if(status?.duplicateOf)continue;let hostLabel=status?.hostLabel||slot.entry.alias,stale=status?.state!=="online";for(let task of slot.tasks)merged.push(stampOrigin(task,slot.entry.alias,hostLabel,stale))}this.tasksAcc.set(merged)}dispose(){this.disposed=!0;for(let alias of[...this.slots.keys()])this.drop(alias)}}function classifyHandshakeFailure(message){return/protocol v\d/i.test(message)?"mismatch":"offline"}function sameAddress(a,b){return a.host===b.host&&a.user===b.user&&a.port===b.port&&JSON.stringify(a.auth)===JSON.stringify(b.auth)}function stampOrigin(task,machineId,hostLabel,stale=!1){return{...task,origin:{machineId,hostLabel,...stale?{stale:!0}:{}}}}
|
|
3
3
|
export{MachineHub,stampOrigin};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ensureForwards,startTunnel}from"./chunk-x0f8a3ez.js";import"./chunk-y1xnjx8x.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-p84bhs57.js";import"./chunk-7kysxgbq.js";import"./chunk-vfrxywtx.js";import"./chunk-pn5ygqn6.js";import"./chunk-w8da1czv.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{startTunnel,ensureForwards};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{installSkillErrors,missingSkillNames}from"./chunk-
|
|
2
|
+
import{installSkillErrors,missingSkillNames}from"./chunk-bwzeg7tk.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{installedEngineIds}from"./chunk-wwes4z56.js";var skillMissing=createStateCell([]),POLL_MS=30000,started=!1;function refreshSkillStatus(){if(!started)return;installedEngineIds().then((installed)=>{let next=missingSkillNames(installed);if(next.join(`
|
|
3
3
|
`)!==skillMissing.get().join(`
|
|
4
4
|
`))skillMissing.set(next)}).catch(()=>{})}function startSkillStatus(){if(started)return;started=!0,refreshSkillStatus(),setInterval(refreshSkillStatus,POLL_MS).unref?.()}function installSkillNow(){let error=installSkillErrors();return refreshSkillStatus(),error}
|
|
5
5
|
export{skillMissing,refreshSkillStatus,startSkillStatus,installSkillNow};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{launchTui,trackWelcomeWrite}from"./chunk-
|
|
2
|
+
import{launchTui,trackWelcomeWrite}from"./chunk-m26wdf1g.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{writeOutdatedCache}from"./chunk-498t9sjd.js";import{PluginCliError,installPlugin}from"./chunk-
|
|
2
|
+
import{writeOutdatedCache}from"./chunk-498t9sjd.js";import{PluginCliError,installPlugin}from"./chunk-2qxa4wtw.js";import{loadPluginRegistry,removePluginEntry,savePluginRegistry}from"./chunk-psxhek7n.js";import"./chunk-vt7rzq32.js";import{pluginCheckoutDir,pluginConfigDir,pluginDataDir,pluginStateDir}from"./chunk-ws2q07kb.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import"./chunk-yt15y085.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{execFileSync}from"child_process";import{existsSync,mkdirSync,readdirSync,renameSync}from"fs";import{join}from"path";function gitOut(args,cwd){try{return execFileSync("git",args,{cwd,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function checkEntry(entry){let repoSpec=entry.source.spec.split("/").slice(0,2).join("/"),localSha=gitOut(["rev-parse","HEAD"],pluginCheckoutDir(entry.id)),remote=gitOut(["ls-remote",`https://github.com/${repoSpec}.git`,"HEAD"]),remoteSha=remote?remote.split(/\s+/)[0]??null:null;return{id:entry.id,spec:entry.source.spec,version:entry.version,localSha,remoteSha,behind:Boolean(localSha&&remoteSha&&localSha!==remoteSha)}}function listOutdated(){let rows=loadPluginRegistry().plugins.filter((p)=>p.source.kind==="github").map(checkEntry);return writeOutdatedCache(rows.filter((r)=>r.behind).map((r)=>r.id)),rows}function printOutdated(){let rows=listOutdated();if(rows.length===0){console.log("no GitHub-installed plugins.");return}for(let r of rows){let status=r.behind?"update available":r.remoteSha===null?"remote unreachable":r.localSha===null?"local sha unreadable":"up to date";console.log(`${r.id} v${r.version} ${status}`)}}function migrateRenamedPlugin(oldId,newId){for(let dirOf of[pluginConfigDir,pluginStateDir]){let from=dirOf(oldId),to=dirOf(newId);if(!existsSync(from))continue;mkdirSync(to,{recursive:!0});for(let entry of readdirSync(from)){if(existsSync(join(to,entry)))continue;renameSync(join(from,entry),join(to,entry))}}savePluginRegistry(removePluginEntry(loadPluginRegistry(),oldId)),console.log(`renamed ${oldId} \u2192 ${newId}: settings and state carried over, old entry unregistered`),console.log(` leftover checkout (safe to remove): ${pluginDataDir(oldId)}`)}async function updatePlugins(ids,opts){let rows=listOutdated(),targets;if(opts.all){if(targets=rows.filter((r)=>r.behind),targets.length===0){console.log("all plugins up to date.");return}}else{if(ids.length===0)throw new PluginCliError("update takes plugin ids or --all");targets=ids.map((id)=>{let row=rows.find((r)=>r.id===id);if(!row)throw new PluginCliError(`\`${id}\` is not a GitHub-installed plugin; see \`${ROVE_PRODUCT_NAME} plugin list\``);return row})}for(let target of targets){if(!target.behind&&!ids.includes(target.id))continue;console.log(`updating ${target.id} (${target.spec})\u2026`);let installedId=await installPlugin(target.spec,{yes:opts.yes});if(installedId!==target.id)migrateRenamedPlugin(target.id,installedId)}listOutdated()}export{updatePlugins,printOutdated};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-
|
|
2
|
+
import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-9eqts8fy.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-83jfmryc.js";import{ensurePluginEnginesLoaded}from"./chunk-wpssm9js.js";import{openDaemonSession}from"./chunk-btvs2v81.js";import{AUTO_MACHINE,LOCAL_MACHINE,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-bwh5y3ra.js";import{ApiError,requireVerbInstalled,verbInstalled}from"./chunk-yx4mar9e.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{__require}from"./chunk-91sykzqq.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
|
|
3
3
|
`)}function emit(value,pretty){let warning=takeIdentityWarning(),payload=warning&&value&&typeof value==="object"&&!Array.isArray(value)?{...value,identityWarning:warning}:value;writeJson(envelopeMode?successEnvelope(payload):payload,pretty)}function fail(message,code,exitCode=1,data){let error=errorBody(new ApiError(message,code,data));if(envelopeMode)writeJson({apiVersion:ROVE_API_VERSION,ok:!1,error},!1);else writeJson({error},!1,process.stderr);process.exit(exitCode)}var USAGE_ERROR_CODES=new Set(["BAD_VERB","UNKNOWN_VERB","BAD_FLAG","MISSING_FLAG","MISSING_VERB","BAD_DAEMON","UNKNOWN_MACHINE"]);async function invokeVerb(verbName,argv,deps){return runVerb(verbName,{argv},deps)}async function runApiSubcommand(argv){let[verbName,...withMachine]=argv,{machine,rest}=takeMachineFlag(withMachine);if(envelopeMode=argvHasFlag(rest,"--envelope"),!verbName||verbName==="--help"||verbName==="-h"||verbName==="help"){if(!verbName)fail(apiUsage(),"MISSING_VERB",2);process.stdout.write(`${apiUsage()}
|
|
4
4
|
`);return}ensurePluginEnginesLoaded();let verb=findVerb(verbName);if(!verb){let err=unknownVerbError(verbName);fail(`${err.message}
|
|
5
5
|
${apiUsage()}`,err.code,2,err.data)}let parsed;try{parsed=parseFlags(rest,booleanFlagsOf(verb),repeatableFlagsOf(verb))}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(parsed.help){if(!verbInstalled(verb))try{requireVerbInstalled(verb)}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data)}process.stdout.write(`${verbHelp(verb)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{stampOrigin}from"./chunk-
|
|
2
|
+
import{stampOrigin}from"./chunk-d6drt08h.js";import{createStateCell}from"./chunk-cmp64q4j.js";var NO_LIVE={activity:new Map,changes:new Map,tokens:new Map};function decodeMachines(payload){let p=payload;if(!p||!Array.isArray(p.machines)||!Array.isArray(p.tasks)||!p.live||typeof p.live!=="object")return null;let map=(value)=>new Map(value&&typeof value==="object"?Object.entries(value):[]);return{machines:p.machines,tasks:p.tasks,live:{activity:map(p.live.activity),changes:map(p.live.changes),tokens:map(p.live.tokens)}}}class MachineFeed{local;machinesAcc=createStateCell([],"machines.status");remoteTasksAcc=createStateCell(null,"machines.remoteTasks");tasksAcc;merged=null;liveAcc=createStateCell(NO_LIVE,"machines.live");stops;constructor(local){this.local=local;this.tasksAcc=this.mergedTasks();let raw=local.rawChannelSignal("machines"),take=()=>{let next=decodeMachines(raw.get());if(!next)return;this.machinesAcc.set(next.machines),this.liveAcc.set(next.live),this.remoteTasksAcc.set(next.machines.length===0?null:next.tasks)};this.stops=[raw.subscribe(take)],take()}machinesSignal(){return this.machinesAcc}tasksSignal(){return this.tasksAcc}liveSignal(){return this.liveAcc}mergedTasks(){let localTasks=this.local.tasksSignal(),get=()=>{let local=localTasks.get(),remote=this.remoteTasksAcc.get();if(remote===null)return local;if(this.merged?.local!==local||this.merged.remote!==remote){let value=[...local.map((task)=>stampOrigin(task,"local","local")),...remote];this.merged={local,remote,value}}return this.merged.value},state=get;return state.get=get,state.subscribe=(listener)=>{let stopLocal=localTasks.subscribe(listener),stopRemote=this.remoteTasksAcc.subscribe(listener);return()=>{stopLocal(),stopRemote()}},state}dispose(){for(let stop of this.stops)stop()}}
|
|
3
3
|
export{decodeMachines,MachineFeed};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{AUTO_MACHINE,LOCAL_MACHINE,forwardVerb,invokeRouted,machineDaemonSocket,machinePtySocket,machineTasks,pickMachine,repoHosts,repoWanted,requireMachine,routeTarget}from"./chunk-bwh5y3ra.js";import"./chunk-t2q30c4r.js";import"./chunk-5dkx02g8.js";import"./chunk-x0f8a3ez.js";import"./chunk-2ebc6hrh.js";import"./chunk-j54ekzg2.js";import"./chunk-b9ea827p.js";import"./chunk-yx4mar9e.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-0mw4pd9k.js";import"./chunk-catrr0z3.js";import"./chunk-ewdanfd9.js";import"./chunk-tn9gtf18.js";import"./chunk-y849hsgp.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-dpgaag6b.js";import"./chunk-cmp64q4j.js";import"./chunk-aagx78v1.js";import"./chunk-qbbtvxmk.js";import"./chunk-wwes4z56.js";import"./chunk-w7zv47mp.js";import"./chunk-q3cnqs5k.js";import"./chunk-88cap497.js";import"./chunk-8yce2acw.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-2brn8e1y.js";import"./chunk-mg1cas61.js";import"./chunk-p84bhs57.js";import"./chunk-hkqcc1t4.js";import"./chunk-1tmmkk54.js";import"./chunk-7kysxgbq.js";import"./chunk-yfwn3fj5.js";import"./chunk-vfrxywtx.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-w8da1czv.js";import"./chunk-k0yjcgd8.js";import"./chunk-yt15y085.js";import"./chunk-7kgksv06.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";export{routeTarget,requireMachine,repoWanted,repoHosts,pickMachine,machineTasks,machinePtySocket,machineDaemonSocket,invokeRouted,forwardVerb,LOCAL_MACHINE,AUTO_MACHINE};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{interactiveEngineCommand,listPresetIds}from"./chunk-
|
|
2
|
+
import{interactiveEngineCommand,listPresetIds}from"./chunk-b9ea827p.js";import{resolveSessionShell}from"./chunk-tn9gtf18.js";import{engineEntry}from"./chunk-qbbtvxmk.js";import{installedEngineIds}from"./chunk-wwes4z56.js";import{spawn,spawnSync}from"child_process";import{statSync}from"fs";import path from"path";function whichOnPath(bin){let bunWhich=globalThis.Bun?.which;if(bunWhich)return bunWhich(bin);let out=spawnSync(process.platform==="win32"?"where":"which",[bin],{encoding:"utf8"});if(out.status!==0)return null;return out.stdout.split(`
|
|
3
3
|
`).map((l)=>l.trim()).find(Boolean)??null}var LOGIN_PROBE_MS=5000,MARK="__rove_which__";function whichInLoginShell(bin){return new Promise((resolve)=>{let out="",child;try{let quoted=`'${bin.replaceAll("'","'\\''")}'`;child=spawn(resolveSessionShell(),["-ilc",`printf '\\n${MARK}%s\\n' "$(command -v ${quoted})"`],{stdio:["ignore","pipe","ignore"]})}catch{return resolve(null)}let timer=setTimeout(()=>child.kill("SIGKILL"),LOGIN_PROBE_MS);child.stdout?.on("data",(b)=>{out+=b.toString()}),child.on("error",()=>{clearTimeout(timer),resolve(null)}),child.on("close",()=>{clearTimeout(timer);let line=out.split(`
|
|
4
4
|
`).find((l)=>l.startsWith(MARK));resolve(line?.slice(MARK.length).trim()||null)})})}var defaultDeps={which:(bin)=>whichOnPath(bin)??(process.platform==="win32"?null:whichInLoginShell(bin)),command:(vendor)=>interactiveEngineCommand(vendor)};async function probeLaunchBinary(argv,which){let bin=argv[0]?.trim();if(!bin)return{found:!1,error:"no launch command"};if(bin.includes(path.sep)||bin.startsWith(".")){try{if(statSync(bin).isFile())return{found:!0,path:bin}}catch{}return{found:!1,error:`not found at ${bin}`}}let found=await which(bin);return found?{found:!0,path:found}:{found:!1,error:"not found on PATH"}}async function detectEngineStatus(vendor,over={}){let deps={...defaultDeps,...over},detector=engineEntry(vendor).detectAccount;if(!detector)return{vendor,binary:await probeLaunchBinary(deps.command(vendor),deps.which),account:null};let status=await detector(deps.accountDeps),binary=status.binary.found?status.binary:await probeLaunchBinary(deps.command(vendor),deps.which);return{vendor,binary,account:status.account,accountError:status.accountError}}function detectEngineStatuses(vendors,over={}){return Promise.all(vendors.map((v)=>detectEngineStatus(v,over)))}function describeAccount(account){if(account===null)return"login not detectable";switch(account.kind){case"oauth":return"email"in account?`logged in (${account.email}${account.organization?`, ${account.organization}`:""})`:"logged in";case"chatgpt":return`logged in (${account.email}${account.plan?`, ${account.plan}`:""})`;case"apikey":return"API key";case"token":return`token (${account.source})`;default:return"no account"}}function engineUsable(status){return status.binary.found&&status.account?.kind!=="none"}async function probeableEngineIds(){return[...new Set([...listPresetIds(),...await installedEngineIds()])]}function summarizeEngines(statuses){let usable=[],signedOut=[];for(let status of statuses)if(engineUsable(status))usable.push(status.vendor);else if(status.binary.found)signedOut.push(status.vendor);return{usable,signedOut}}
|
|
5
5
|
export{detectEngineStatus,detectEngineStatuses,describeAccount,probeableEngineIds,summarizeEngines};
|