@sma1lboy/rove 0.9.295-next.320 → 0.9.295-next.321

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/cli/{chunk-zj25qsfj.js → chunk-02bkfsxf.js} +1 -1
  2. package/dist/cli/{chunk-1975ej5j.js → chunk-0vgpq1jc.js} +1 -1
  3. package/dist/cli/{chunk-c1441pfv.js → chunk-1651ft9x.js} +1 -1
  4. package/dist/cli/{chunk-s70prg81.js → chunk-172tz5gj.js} +1 -1
  5. package/dist/cli/{chunk-3prnp53k.js → chunk-24zvsw6v.js} +1 -1
  6. package/dist/cli/{chunk-h90nwdg8.js → chunk-2tevn0vy.js} +1 -1
  7. package/dist/cli/{chunk-vb2ct88r.js → chunk-2wy4j5dq.js} +1 -1
  8. package/dist/cli/{chunk-qcypgc4n.js → chunk-3661pvwa.js} +1 -1
  9. package/dist/cli/{chunk-8jbcwja0.js → chunk-4agqc5sj.js} +1 -1
  10. package/dist/cli/{chunk-nt00jh8k.js → chunk-5r83hjhx.js} +1 -1
  11. package/dist/cli/{chunk-47g6ecty.js → chunk-616xv0af.js} +1 -1
  12. package/dist/cli/{chunk-y9j708v1.js → chunk-6jf8qxvv.js} +1 -1
  13. package/dist/cli/{chunk-dm2ycqag.js → chunk-6pzrfp3r.js} +1 -1
  14. package/dist/cli/{chunk-sjkk3jkf.js → chunk-7djtmcpv.js} +1 -1
  15. package/dist/cli/{chunk-asagdr71.js → chunk-7vxdryc2.js} +1 -1
  16. package/dist/cli/{chunk-xrfptza1.js → chunk-8ehej6v5.js} +1 -1
  17. package/dist/cli/{chunk-nx2da2j6.js → chunk-8yyzskdm.js} +1 -1
  18. package/dist/cli/{chunk-hbnnbbpd.js → chunk-9x01kzv8.js} +1 -1
  19. package/dist/cli/{chunk-0w81tahc.js → chunk-b83fxvne.js} +1 -1
  20. package/dist/cli/{chunk-mct40bd0.js → chunk-canetc0e.js} +1 -1
  21. package/dist/cli/{chunk-jxdc5g7p.js → chunk-cwqcn7fb.js} +2 -2
  22. package/dist/cli/{chunk-37sc43gb.js → chunk-dcjp2mnk.js} +1 -1
  23. package/dist/cli/{chunk-2mn87bwe.js → chunk-deqqfhem.js} +1 -1
  24. package/dist/cli/{chunk-9k60sxq2.js → chunk-dsnb2r9a.js} +1 -1
  25. package/dist/cli/{chunk-1b1wzmfn.js → chunk-e36q555a.js} +1 -1
  26. package/dist/cli/{chunk-097dzz4a.js → chunk-extktb3x.js} +1 -1
  27. package/dist/cli/{chunk-maq0qvms.js → chunk-hransg15.js} +1 -1
  28. package/dist/cli/{chunk-90af74mn.js → chunk-j163pcsk.js} +2 -2
  29. package/dist/cli/{chunk-01ekh175.js → chunk-jqn9m2d2.js} +1 -1
  30. package/dist/cli/{chunk-w4kbb5fa.js → chunk-kevh7hah.js} +1 -1
  31. package/dist/cli/{chunk-a3yt083k.js → chunk-mbtxjbfh.js} +1 -1
  32. package/dist/cli/{chunk-3pk8zypt.js → chunk-mj899dp9.js} +1 -1
  33. package/dist/cli/{chunk-bfqpnera.js → chunk-n8vz2bfm.js} +2 -2
  34. package/dist/cli/{chunk-m90n6nks.js → chunk-nce18fwt.js} +1 -1
  35. package/dist/cli/{chunk-r4w7x5zw.js → chunk-r7q2dwww.js} +1 -1
  36. package/dist/cli/{chunk-05vpa04d.js → chunk-rxajd35f.js} +1 -1
  37. package/dist/cli/{chunk-6r1120mc.js → chunk-ry8fe3ds.js} +2 -2
  38. package/dist/cli/{chunk-mehqk0h4.js → chunk-sg877d7p.js} +1 -1
  39. package/dist/cli/{chunk-zx1yw850.js → chunk-vnvbbt1t.js} +1 -1
  40. package/dist/cli/{chunk-0t81dyc8.js → chunk-w2wnv98d.js} +1 -1
  41. package/dist/cli/{chunk-cp8d5q26.js → chunk-w4gv42vg.js} +1 -1
  42. package/dist/cli/{chunk-ebybc98b.js → chunk-w81aezsx.js} +2 -2
  43. package/dist/cli/{chunk-8nypbzrg.js → chunk-wp7qzamb.js} +1 -1
  44. package/dist/cli/{chunk-b15q2s62.js → chunk-wwm5qrtx.js} +1 -1
  45. package/dist/cli/{chunk-qn1wqzvg.js → chunk-wyvy7zjq.js} +1 -1
  46. package/dist/cli/{chunk-v893heq9.js → chunk-wz3nm36w.js} +1 -1
  47. package/dist/cli/{chunk-gc9sanw0.js → chunk-zycbr5s2.js} +1 -1
  48. package/dist/cli/index.js +2 -2
  49. package/dist/cli/rove.js +1 -1
  50. package/package.json +1 -1
@@ -15,7 +15,7 @@ ${prompt}`:prompt}function carryOwedGateAnswers(gates,taskId,tabId,prompt){let h
15
15
 
16
16
  `:"",body=promptHeld?"Instructions unchanged from this routine's earlier run in this conversation: follow them again.":automation.prompt;return`[ROVE ROUTINE] "${automation.name}" run #${run.runNumber} \u2014 when done, report with: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026] (only if something happened or you are blocked)
17
17
 
18
- ${fired}${body}`}var DEFAULT_AUTOMATION_TICK_MS=60000;function dueAutomations(automations,nowMs){return automations.filter((a)=>{if(!a.enabled)return!1;let at=Date.parse(a.nextRunAt);return Number.isFinite(at)&&at<=nowMs})}function resolveDueOccurrence(automation,nowMs,tickMs=DEFAULT_AUTOMATION_TICK_MS){let notBefore=Date.parse(automation.createdAt),scheduledFor=latestCronAtOrBefore(automation.schedule,nowMs,Number.isFinite(notBefore)?notBefore:0);if(scheduledFor===null)return null;let graceMs=automation.missedRunGraceMinutes*60000+Math.max(tickMs,0);return{scheduledFor,missed:nowMs-scheduledFor>graceMs}}function runEventFor(status){if(status==="dispatched"||status==="revived"||status==="ran")return"automation.dispatched";if(status==="dispatch_failed"||status==="script_failed")return"automation.failed";return"automation.skipped"}function resolveLink(link){return typeof link==="function"?link():link}function emitRunEvent(deps,automation,status,args,extra){if(extra.taskId&&(status==="dispatched"||status==="revived"||status==="dispatch_failed"))deps.dispatches?.record({kind:"routine",from:null,routine:automation.name,to:{taskId:extra.taskId,tabId:extra.tabId??null},promptHead:automation.prompt,delivered:status!=="dispatch_failed",...extra.error?{reason:extra.error}:{}});deps.plugins?.()?.handleUiReport({kind:runEventFor(status),...extra.taskId?{taskId:extra.taskId}:{},detail:{automationId:automation.id,name:automation.name,...automation.repo?{repo:automation.repo}:{},status,trigger:args.trigger,scheduledFor:new Date(args.scheduledFor).toISOString(),...extra.tabId?{tabId:extra.tabId}:{},...extra.error?{error:extra.error}:{}}})}async function raiseOrClearInboxEpisode(deps,automation,status,extra){let inbox=deps.inbox;if(!inbox)return;let now=deps.now??Date.now;await(automationRunNeedsAttention(status)?inbox.recordRoutineFailure({automationId:automation.id,name:automation.name,status,...extra.error?{error:extra.error}:{}},extra.taskId??null,now()):inbox.deleteRoutineEpisode?.(automation.id,"routine_failed"))?.catch((err)=>logDaemonError("automation-inbox",err))}async function recordSkip(deps,automation,status,scheduledFor,error){let now=deps.now??Date.now;await deps.store.recordRun({automationId:automation.id,scheduledFor:new Date(scheduledFor).toISOString(),status,trigger:"scheduled",at:new Date(now()).toISOString(),error}),emitRunEvent(deps,automation,status,{scheduledFor,trigger:"scheduled"},{error})}function droppedOccurrences(automation,scheduledFor){let armedAt=Date.parse(automation.nextRunAt);if(!Number.isFinite(armedAt)||armedAt>=scheduledFor)return null;let count=countCronBetween(automation.schedule,armedAt,scheduledFor);return count>0?{count,firstMs:armedAt}:null}async function runScript(script,automation,record,now,env){let result=await runAutomationPrecheck(script,await ensureRoutineCwd(automation),void 0,env),stdout=result.stdout.trim(),response=stdout?{response:{text:stdout,at:new Date(now()).toISOString()}}:{};if(precheckPassed(result))return await record("ran",response);let reason=formatPrecheckSkip(result).replace(/^precheck/,"script"),stderr=result.stderr.trim();return logDaemonInfo("automation",`${automation.name}: ${reason}`),await record("script_failed",{...response,error:stderr?`${reason}: ${stderr.slice(-500)}`:reason})}async function runAutomationOnce(deps,automation,args){let env=args.event?webhookPrecheckEnv(args.event):void 0,now=deps.now??Date.now,reserved=deps.store.reserveRun(automation.id),record=async(status,extra={})=>{return await deps.store.recordRun({automationId:automation.id,scheduledFor:new Date(args.scheduledFor).toISOString(),status,trigger:args.trigger,...args.event?{event:args.event.summary}:{},at:new Date(now()).toISOString(),...extra},reserved),emitRunEvent(deps,automation,status,args,extra),await raiseOrClearInboxEpisode(deps,automation,status,extra),status},cancelled=()=>deps.stopped?.()===!0||deps.store.get(automation.id)!==automation||args.trigger!=="manual"&&!automation.enabled;if(cancelled())return await record("skipped_cancelled",{error:"routine disabled, changed, deleted or runner stopped before delivery"});if(await routineRepoMissing(automation.repo))return await record("skipped_unavailable",{error:`repo does not exist: ${automation.repo}`});if(args.trigger!=="manual"&&automation.precheck){let skipped=await precheckSkip(automation,automation.precheck,await ensureRoutineCwd(automation),env);if(skipped)return await record("skipped_precheck",{precheckResult:skipped.precheckResult,error:skipped.reason})}if(cancelled())return await record("skipped_cancelled",{error:"routine disabled, changed, deleted or runner stopped before delivery"});if(automation.script)return await runScript(automation.script,automation,record,now,env);let outcome,deliveryId,elided=!1,elidedLive=!1,settleDelivery=async(delivered)=>{if(!deliveryId)return;let id=deliveryId;if(delivered===null)deliveryId=void 0;await(delivered===null?deps.deliveries.cancel(id):deps.deliveries.setTab(id,delivered.tabId??"tab-1")).catch((err)=>logDaemonError("automation-delivery",err))};try{outcome=await dispatchAutomation({canDeliver:()=>!cancelled(),orch:deps.orch,runtime:deps.runtime,link:()=>resolveLink(deps.link),...deps.gates?{gates:deps.gates}:{},...deps.runnability&&args.trigger!=="manual"?{runnability:deps.runnability}:{},...deps.now?{now:deps.now}:{}},automation,async(target)=>{if(deliveryId??=(await deps.deliveries.arm({taskId:target.taskId,tabId:target.tabId,source:"routine",automationRunId:reserved.id,promptHead:automation.prompt})).id,elided=sessionHoldsPrompt(automation,deps.store.runsFor(automation.id),target),!target.fresh)elidedLive=elided;let api=deps.runtime.roveApiInvocation?.()??"rove api";return withRoutineRunHeader(automation,reserved,api,deliveryId,args.event,elided)})}catch(err){let error=err instanceof Error?err.message:String(err);return logDaemonError("automation-dispatch",err),await settleDelivery(null),await record("skipped_unavailable",{error})}if(outcome.status==="revived"&&outcome.resumed)elided=elidedLive;if(await settleDelivery(outcome.status==="dispatched"||outcome.status==="revived"?outcome:null),outcome.sessionTaskIdToSet){if(!await deps.store.linkSessionTask(automation.id,outcome.sessionTaskIdToSet,automation).catch((err)=>{return logDaemonError("automation-session-link",err),!0}))logDaemonInfo("automation",`${automation.name}: not adopting ${outcome.sessionTaskIdToSet}`)}else if(outcome.sessionTaskIdToClear)await deps.store.update(automation.id,{sessionTaskId:null}).catch((err)=>logDaemonError("automation-session-unlink",err));if(outcome.status==="dispatched"||outcome.status==="revived"){let tab=outcome.tabId?` tab=${outcome.tabId}`:"";logDaemonInfo("automation",`${outcome.status} ${automation.name} task=${outcome.taskId}${tab}`)}return await record(outcome.status,{...outcome.taskId?{taskId:outcome.taskId}:{},...outcome.tabId?{tabId:outcome.tabId}:{},...outcome.error?{error:outcome.error}:{},...outcome.blocked?{blocked:outcome.blocked}:{},...deliveryId?{deliveryId,promptHash:routinePromptHash(automation.prompt)}:{},...deliveryId&&elided?{promptElided:!0}:{}})}async function sweepAutomations(deps,tickMs=DEFAULT_AUTOMATION_TICK_MS){let now=deps.now??Date.now;for(let automation of dueAutomations(deps.store.list(),now())){if(deps.stopped?.())return;let nowMs=now(),occurrence=resolveDueOccurrence(automation,nowMs,tickMs);if(!occurrence){await deps.store.advanceNextRun(automation.id,nowMs);continue}let dropped=droppedOccurrences(automation,occurrence.scheduledFor),claimed=await deps.store.advanceNextRun(automation.id,occurrence.scheduledFor,automation.nextRunAt);if(!claimed)continue;if(dropped){let first=new Date(dropped.firstMs).toISOString();await recordSkip(deps,automation,"skipped_missed",dropped.firstMs,`${dropped.count} earlier occurrence${dropped.count===1?"":"s"} never ran (from ${first})`).catch((err)=>logDaemonError("automation-dropped",err))}if(occurrence.missed){await recordSkip(deps,automation,"skipped_missed",occurrence.scheduledFor,`missed by more than the ${automation.missedRunGraceMinutes}m grace window`);continue}await runAutomationOnce(deps,claimed,{scheduledFor:occurrence.scheduledFor,trigger:"scheduled"}).catch((err)=>logDaemonError("automation-run",err))}}function startAutomationRunner(deps,tickMs=DEFAULT_AUTOMATION_TICK_MS){let stopped=!1;return startTicker({name:"automation-sweep",tickMs,run:()=>sweepAutomations({...deps,stopped:()=>stopped},tickMs),onStop:()=>{stopped=!0}})}var DEFAULT_CONTEXT_USAGE_TICK_MS=1e4,CONTEXT_USAGE_TIMEOUT_MS=4000,CONTEXT_USAGE_SLOW_RETRY_MS=60000,CONTEXT_USAGE_MIN_INTERVAL_MS=5000;function sameContextUsage(a,b){return a.contextTokens===b.contextTokens&&a.contextWindowTokens===b.contextWindowTokens&&a.approximate===b.approximate&&a.inputTokens===b.inputTokens&&a.outputTokens===b.outputTokens&&a.cacheReadTokens===b.cacheReadTokens&&a.cacheCreationTokens===b.cacheCreationTokens&&JSON.stringify(a.parts)===JSON.stringify(b.parts)}function contextUsageTargets(states,getVendor){let seen=new Set,targets=[];for(let state of states){if(!state.tabId||!state.sessionId)continue;let vendor=getVendor(state.taskId);if(!vendor)continue;let key=`${state.taskId}::${state.tabId}`;if(seen.has(key))continue;seen.add(key),targets.push({key,vendor,sessionId:state.sessionId})}return targets}class ContextUsageCollector{registry;orch;bus;runtime;options;entries=new Map;stopped=!1;constructor(registry,orch,bus,runtime,options={}){this.registry=registry;this.orch=orch;this.bus=bus;this.runtime=runtime;this.options=options}tick(){if(this.stopped)return;if(this.options.hasSubscribers&&!this.options.hasSubscribers())return;try{let targets=contextUsageTargets(this.registry.liveSessions(),(id)=>this.orch.getTask(id)?.vendor),live=new Set(targets.map((t)=>t.key)),pruned=!1;for(let key of[...this.entries.keys()]){if(live.has(key))continue;if(this.entries.get(key)?.value)pruned=!0;this.entries.delete(key)}if(pruned)this.publish();for(let target of targets)this.collect(target)}catch(err){logDaemonError("context-usage",err)}}stop(){this.stopped=!0}collect(target){let entry=this.entries.get(target.key);if(!entry)entry={inFlight:!1,nextAllowedAt:0},this.entries.set(target.key,entry);if(entry.sessionId!==void 0&&entry.sessionId!==target.sessionId){let had=entry.value!==void 0;if(entry.value=void 0,entry.nextAllowedAt=0,entry.sessionId=target.sessionId,had)this.publish()}entry.sessionId=target.sessionId;let cadence=this.options.cadence??{timeoutMs:CONTEXT_USAGE_TIMEOUT_MS,slowRetryMs:CONTEXT_USAGE_SLOW_RETRY_MS,minIntervalMs:CONTEXT_USAGE_MIN_INTERVAL_MS},read=this.options.read??((t)=>this.runtime.readEngineContextUsage(t.vendor,t.sessionId)),startedAt=Date.now();if(entry.inFlight||startedAt<entry.nextAllowedAt)return;entry.inFlight=!0;let controller=new AbortController,timer=setTimeout(()=>controller.abort(),cadence.timeoutMs),held=entry;read(target,controller.signal).then((value)=>{if(controller.signal.aborted||this.stopped)return;if(this.entries.get(target.key)!==held)return;if(!value)return;if(held.value&&sameContextUsage(held.value,value))return;held.value=value,this.publish()}).catch(()=>{}).finally(()=>{clearTimeout(timer);let finishedAt=Date.now();held.nextAllowedAt=computeNextAllowedAt(startedAt,finishedAt,controller.signal.aborted,cadence),held.inFlight=!1})}publish(){let context={};for(let[key,entry]of this.entries)if(entry.value)context[key]=entry.value;this.bus.publish("usage.context",{context})}}function startContextUsageCollector(registry,orch,bus,runtime,tickMs=DEFAULT_CONTEXT_USAGE_TICK_MS,hasSubscribers){if(tickMs<=0)return()=>{};let collector=new ContextUsageCollector(registry,orch,bus,runtime,{hasSubscribers});collector.tick();let timer=setInterval(()=>collector.tick(),tickMs);return timer.unref?.(),()=>{clearInterval(timer),collector.stop()}}import{basename}from"path";var DEFAULT_KEYBINDINGS_DEBOUNCE_MS=200;function startKeybindingsWatcher(bus,options={}){let debounceMs=options.debounceMs??DEFAULT_KEYBINDINGS_DEBOUNCE_MS;if(debounceMs<=0)return()=>{};let filePath=options.path??defaultKeybindingsPath(),baseYaml=basename(filePath),baseYml=baseYaml.replace(/\.yaml$/,".yml"),rev=0;return bus.publish("keybindings",{rev}),startFileWatchTrigger({filePath,matchBasenames:[baseYaml,baseYml],debounceMs,onTrigger:()=>{try{rev+=1,bus.publish("keybindings",{rev})}catch(err){logDaemonError("keybindings-watcher",err)}},onError:(err)=>logDaemonError("keybindings-watcher",err)})}function sessionPrKey(taskId,url){return`${taskId}::pr::${url}`}function pollableSessionPrs(task){if(task.repo.startsWith("ssh://")||task.worktreePath?.startsWith("ssh://"))return[];return task.sessionPrs??[]}function sessionPrJobs(orch,tasks,ctx){let jobs=[];for(let task of tasks)for(let{url}of pollableSessionPrs(task)){let entry=ctx.schedule.get(sessionPrKey(task.id,url));if(entry&&ctx.now<entry.nextAllowedAt)continue;jobs.push(()=>pollSessionPr(orch,task.id,url,entry?.failures??0,ctx))}return jobs}async function pollSessionPr(orch,taskId,url,prevFailures,ctx){let{runtime,schedule,now,cfg,rand}=ctx,key=sessionPrKey(taskId,url);try{let result=await ctx.run(url);if(result.kind==="error"){logOncePerChange(`session-pr:${key}`,"pr-status-poller",`gh pr view failed (${result.error}) for task ${taskId} session PR ${url} \u2014 keeping last status, backing off`),schedule.set(key,runtime.prStatus.nextPoll({kind:"error",error:result.error},prevFailures,now,cfg,rand));return}logOncePerChange(`session-pr:${key}`,"pr-status-poller",void 0);let next=result.kind==="pr"?runtime.prStatus.mapView(result.view,ctx.at):null;if(!next){schedule.set(key,runtime.prStatus.nextPoll({kind:"empty"},prevFailures,now,cfg,rand));return}let attached=orch.getTask(taskId)?.sessionPrs?.find((p)=>p.url===url);if(!attached){schedule.delete(key);return}let changed;if(attached.status?.lastError!==void 0||!runtime.prStatus.sameStatus(attached.status,next))await orch.setSessionPrStatus(taskId,url,next),changed=taskId;let settled=next.lifecycle==="merged"||next.lifecycle==="closed";return schedule.set(key,runtime.prStatus.nextPoll({kind:"pr",settled},prevFailures,now,cfg,rand)),changed}catch(err){logDaemonError("pr-status-poller",err),schedule.set(key,runtime.prStatus.nextPoll({kind:"error",error:"network"},prevFailures,now,cfg,rand));return}}var DEFAULT_PR_STATUS_POLL_MS=30000,NO_PR_BACKOFF_MS=300000,SETTLED_BACKOFF_MS=600000,PR_FAILURE_BASE_MS=DEFAULT_PR_STATUS_POLL_MS,PR_FAILURE_CAP_MS=900000,NO_REMOTE_BACKOFF_MS=1800000,PR_POLL_JITTER_RATIO=0.2,PR_POLL_CONCURRENCY=8;function isRepoPollable(task,view){if(!workspaceCapabilities(task).ownsBranch)return!1;if(!view.branch||!view.worktreePath)return!1;if(view.repo.startsWith("ssh://")||view.worktreePath.startsWith("ssh://"))return!1;return!0}var EXTRA_KEY_SEP="::";function pollKey(taskId,extraName){return extraName===void 0?taskId:`${taskId}${EXTRA_KEY_SEP}${extraName}`}async function setPrStaleMarker(orch,taskId,extraName,error){let row=orch.getTask(taskId),prev=extraName===void 0?row?.prStatus:row?.extraRepos?.find((e)=>e.name===extraName)?.prStatus;if(!prev||prev.lastError===error)return!1;let{lastError:_cleared,...rest}=prev;return await orch.setPRStatus(taskId,error===void 0?rest:{...rest,lastError:error},extraName),!0}async function runPrStatusPass(orch,opts){let tickMs=opts.tickMs??DEFAULT_PR_STATUS_POLL_MS,rand=opts.rand,cfg={tickMs,settledMs:SETTLED_BACKOFF_MS,noPrMs:NO_PR_BACKOFF_MS,noRemoteMs:NO_REMOTE_BACKOFF_MS,failureBaseMs:PR_FAILURE_BASE_MS,failureCapMs:PR_FAILURE_CAP_MS,jitterRatio:PR_POLL_JITTER_RATIO},tasks=orch.listTasks(),liveKeys=new Set;for(let task of tasks){liveKeys.add(task.id);for(let extra of task.extraRepos??[])liveKeys.add(pollKey(task.id,extra.name));for(let{url}of pollableSessionPrs(task))liveKeys.add(sessionPrKey(task.id,url))}for(let key of opts.schedule.keys())if(!liveKeys.has(key))opts.schedule.delete(key);let due=[];for(let task of tasks){let repos=[{extraName:void 0,repo:task},...(task.extraRepos??[]).map((e)=>({extraName:e.name,repo:e}))];for(let{extraName,repo}of repos){let key=pollKey(task.id,extraName);if(!isRepoPollable(task,repo)){opts.schedule.delete(key);continue}let entry=opts.schedule.get(key);if(entry&&opts.now<entry.nextAllowedAt)continue;due.push({task,extraName,repo,prevFailures:entry?.failures??0})}}let pollOne=async(task,extraName,repo,prevFailures)=>{let key=pollKey(task.id,extraName),label=extraName===void 0?task.id:`${task.id} repo ${extraName}`;try{let prev=extraName===void 0?task.prStatus:task.extraRepos?.find((e)=>e.name===extraName)?.prStatus,result=await opts.run(repo.worktreePath??"",repo.branch,prev?.number);if(result.kind==="error"){logOncePerChange(`pr-poll:${key}`,"pr-status-poller",`gh pr list failed (${result.error}) for task ${label} [${repo.branch}] \u2014 keeping last PR status, backing off`);let marked=await setPrStaleMarker(orch,task.id,extraName,result.error);return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"error",error:result.error},prevFailures,opts.now,cfg,rand)),marked?task.id:void 0}if(result.kind==="empty"){logOncePerChange(`pr-poll:${key}`,"pr-status-poller",void 0);let marked=await setPrStaleMarker(orch,task.id,extraName,void 0);return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"empty"},prevFailures,opts.now,cfg,rand)),marked?task.id:void 0}logOncePerChange(`pr-poll:${key}`,"pr-status-poller",void 0);let next=opts.runtime.prStatus.mapView(result.view,opts.at),current=orch.getTask(task.id);if(!current){opts.schedule.delete(key);return}let currentPr=extraName===void 0?current.prStatus:current.extraRepos?.find((e)=>e.name===extraName)?.prStatus,wasStale=currentPr?.lastError!==void 0,changedId;if(wasStale||!opts.runtime.prStatus.sameStatus(currentPr,next??void 0))await orch.setPRStatus(task.id,next,extraName),changedId=task.id;let settled=next?.lifecycle==="merged"||next?.lifecycle==="closed";return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"pr",settled},prevFailures,opts.now,cfg,rand)),changedId}catch(err){logDaemonError("pr-status-poller",err);let marked=await setPrStaleMarker(orch,task.id,extraName,"network").catch(()=>!1);return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"error",error:"network"},prevFailures,opts.now,cfg,rand)),marked?task.id:void 0}},sessionJobs=opts.runUrl?sessionPrJobs(orch,tasks,{runtime:opts.runtime,run:opts.runUrl,now:opts.now,at:opts.at,schedule:opts.schedule,cfg,rand}):[],total=due.length+sessionJobs.length,slots=Array(total),cursor=0,worker=async()=>{for(let i=cursor++;i<total;i=cursor++){if(i>=due.length){slots[i]=await sessionJobs[i-due.length]?.();continue}let item=due[i];if(item)slots[i]=await pollOne(item.task,item.extraName,item.repo,item.prevFailures)}};return await Promise.all(Array.from({length:Math.min(PR_POLL_CONCURRENCY,total)},worker)),[...new Set(slots.filter((id)=>id!==void 0))]}function startPrStatusPoller(orch,runtime,intervalMs=DEFAULT_PR_STATUS_POLL_MS,hasSubscribers,run=makeGhPrViewRunner(runtime.prStatus.classify,runtime.prStatus.viewFields),hasWorkingAgent,runUrl=makeGhPrUrlRunner(runtime.prStatus.classify,runtime.prStatus.viewFields)){let schedule=new Map;return startTicker({name:"pr-status-poller",tickMs:intervalMs,...hasSubscribers?{gate:()=>hasSubscribers()||(hasWorkingAgent?.()??!1)}:{},run:()=>runPrStatusPass(orch,{runtime,run,runUrl,now:Date.now(),at:new Date().toISOString(),schedule,tickMs:intervalMs})})}class InflightClaims{now;claims=new Map;nextId=1;constructor(now=Date.now){this.now=now}claim(taskId,tabId,covered=!1){let id=`c-${this.nextId++}`;return this.claims.set(id,{taskId,tabId,covered,expiresAt:this.now()+90000}),id}release(id,landed){let claim=this.claims.get(id);if(!claim)return;if(landed&&!claim.covered)claim.expiresAt=this.now()+15000;else this.claims.delete(id)}isClaimed(taskId,tabId){let now=this.now();for(let[id,claim]of this.claims){if(claim.expiresAt<=now){this.claims.delete(id);continue}if(claim.taskId===taskId&&(tabId===null||claim.tabId===null||claim.tabId===tabId))return!0}return!1}}function quotaResumeContinuePrompt(language){return language==="zh"?"\u4ECE\u4E2D\u65AD\u7684\u5730\u65B9\u7EE7\u7EED\u8FD9\u4E2A\u4EFB\u52A1\u3002\u4E0A\u9762\u7684\u5BF9\u8BDD\u8BB0\u5F55\u91CC\u5DF2\u7ECF\u5B8C\u6210\u7684\u5DE5\u4F5C\u4E0D\u8981\u91CD\u505A\u3002":"Continue the task from where it stopped. The transcript above shows the work already completed \u2014 do not redo it."}var DEFAULT_QUOTA_RESUME_TICK_MS=60000;function dueQuotaResumes(tasks,nowMs){return tasks.filter((task)=>{if(!task.quotaResume||!task.worktreePath)return!1;if(task.deletion)return!1;let at=Date.parse(task.quotaResume.resumeAt);return Number.isFinite(at)&&at<=nowMs})}function quotaWaitingTasks(tasks,entryOf){return tasks.filter((task)=>{if(!task.worktreePath||task.deletion)return!1;if(task.quotaResume)return!0;let entry=entryOf(task.id);return entry?.state==="rate_limited"&&entry.detail?.failure!=="billing"})}function exhaustedResetAtMs(usage,nowMs){let candidates=usage.windows.filter((w)=>w.percent>=100&&w.resetsAt!=null&&w.resetsAt>nowMs).map((w)=>w.resetsAt);return candidates.length>0?Math.min(...candidates):null}async function scheduleQuotaResume(orch,runtime,cache,taskId,now=Date.now,plugins){let task=orch.getTask(taskId);if(!task||!task.worktreePath||task.deletion)return;let usage=await cache.get(task.vendor??runtime.defaultTaskVendor,0),resetAtMs=usage?exhaustedResetAtMs(usage,now()):null;if(resetAtMs==null)return;let resumeAt=new Date(resetAtMs).toISOString();await orch.setQuotaResume(taskId,{resumeAt,requestedAt:new Date(now()).toISOString()}),logDaemonInfo("quota-resume",`armed task=${taskId} resumeAt=${resumeAt}`),plugins?.()?.handleUiReport({kind:"quota.exhausted",taskId,detail:{vendor:task.vendor??runtime.defaultTaskVendor,resumeAt}})}async function resumeQuotaTask(orch,runtime,task,claims,plugins,runnability){if(claims.isClaimed(task.id,null))return{taskId:task.id,status:"declined",reason:"busy"};let verdict=runnability?.check(task.id,null,["quota"]);if(verdict&&!verdict.run)return await orch.setQuotaResume(task.id,null),logDaemonInfo("quota-resume",`declined task=${task.id} reason=${verdict.reason}`),{taskId:task.id,status:"declined",reason:verdict.reason};let claimId=claims.claim(task.id,null),delivered=!1;try{return await orch.setQuotaResume(task.id,null),delivered=await runtime.deliverPromptToLiveEngine({id:task.id,vendor:task.vendor,command:task.command,worktreePath:task.worktreePath,scope:ptyScopeFor(orch.listTasks(),task.id)},quotaResumeContinuePrompt(task.observedLanguage)),logDaemonInfo("quota-resume",`resume task=${task.id} delivered=${delivered}`),plugins?.()?.handleUiReport({kind:"quota.resumed",taskId:task.id,detail:{delivered}}),{taskId:task.id,status:delivered?"resumed":"not-delivered"}}finally{claims.release(claimId,delivered)}}function startQuotaResumeRunner(orch,runtime,tickMs=DEFAULT_QUOTA_RESUME_TICK_MS,now=Date.now,plugins,runnability,claims=new InflightClaims){return startTicker({name:"quota-resume",tickMs,run:async()=>{for(let task of dueQuotaResumes(orch.listTasks(),now()))await resumeQuotaTask(orch,runtime,task,claims,plugins,runnability).catch((err)=>logDaemonError("quota-resume",err))}})}var FRESH_POLL_MS=900000,RETRY_BASE_MS=60000,MIN_FETCH_INTERVAL_MS=60000;class QuotaUsageCache{runtime;bus;now;entries=new Map;constructor(runtime,bus,now=Date.now){this.runtime=runtime;this.bus=bus;this.now=now}peek(vendor){return this.entries.get(vendor)?.usage??null}async get(vendor,maxAgeMs){let entry=this.entry(vendor),age=this.now()-(entry.usage?.capturedAt??0);if(entry.usage&&age<=maxAgeMs)return entry.usage;if(entry.inFlight)return entry.inFlight;if(this.now()-entry.attemptedAt<MIN_FETCH_INTERVAL_MS)return entry.usage;return this.fetch(vendor,entry)}async refreshIfDue(vendor){let entry=this.entry(vendor),retryAfter=entry.failures===0?0:Math.min(RETRY_BASE_MS*2**(entry.failures-1),FRESH_POLL_MS),dueAfter=entry.usage?FRESH_POLL_MS:retryAfter;if(this.now()-entry.attemptedAt<dueAfter)return;await this.fetch(vendor,entry)}entry(vendor){let existing=this.entries.get(vendor);if(existing)return existing;let fresh={usage:null,attemptedAt:0,failures:0,inFlight:null};return this.entries.set(vendor,fresh),fresh}fetch(vendor,entry){if(entry.inFlight)return entry.inFlight;return entry.attemptedAt=this.now(),entry.inFlight=this.runtime.quotaUsage(vendor).catch(()=>null).then((usage)=>{if(entry.inFlight=null,usage){entry.failures=0;let changed=JSON.stringify(usage.windows)!==JSON.stringify(entry.usage?.windows);if(entry.usage=usage,changed)this.publish()}else entry.failures+=1;return entry.usage}),entry.inFlight}publish(){let usage={};for(let[vendor,entry]of this.entries)if(entry.usage)usage[vendor]=entry.usage;this.bus.publish("usage.snapshot",{usage})}}function startQuotaUsagePoller(cache,listVendors,hasSubscribers,tickMs=MIN_FETCH_INTERVAL_MS){return startTicker({name:"quota-usage-poller",tickMs,gate:hasSubscribers,immediate:!0,run:()=>{for(let vendor of new Set(listVendors()))cache.refreshIfDue(vendor)}})}var DEFAULT_SCHEDULED_START_TICK_MS=15000;function dueScheduledStarts(tasks,nowMs){return tasks.filter((task)=>{if(!task.scheduledStart||task.deletion)return!1;let at=Date.parse(task.scheduledStart.at);return!Number.isFinite(at)||at<=nowMs})}async function startScheduledNow(deps,taskId){let task=deps.orch.getTask(taskId),schedule=task?.scheduledStart;if(!task||!schedule)return"dropped";if(await deps.orch.setScheduledStart(taskId,null),task.deletion||task.prompt)return logDaemonInfo("scheduled-start",`dropped task=${taskId} (${task.deletion?"being deleted":"already started"})`),"dropped";await deps.orch.setPrompt(taskId,schedule.prompt);let link=typeof deps.link==="function"?deps.link():deps.link,outcome=await deps.runtime.startTaskSessionWithPrompt(link,taskId,schedule.prompt);return logDaemonInfo("scheduled-start",`start task=${taskId} started=${outcome.started} ${outcome.error??""}`.trim()),outcome.started?"started":"failed"}async function firePendingStart(deps,start){if(!deps.pending||!await deps.pending.remove(start.id))return"dropped";let error=await createPendingStart(deps,start).catch((err)=>err instanceof Error?err.message:String(err));if(logDaemonInfo("scheduled-start",`pending start=${start.id} ${error?`failed: ${error}`:"started"}`),!error)return"started";return await deps.pending.fail(start,error),"failed"}async function createPendingStart(deps,start){let{create}=start;if(create.via==="add"){if(!deps.invoke)return"this daemon cannot run verbs";let envelope=await deps.invoke("add",{...create.params,prompt:start.prompt});return envelope.ok?void 0:`${envelope.error.code}: ${envelope.error.message}`}let dir=create.project?(await deps.orch.ensureMainTask(create.dir)).repo:create.dir,task=await deps.orch.openDirectoryTask({dir,...create.vendor?{vendor:create.vendor}:{},...start.title?{title:start.title}:{}});await deps.orch.setPrompt(task.id,start.prompt);let link=typeof deps.link==="function"?deps.link():deps.link,outcome=await deps.runtime.startTaskSessionWithPrompt(link,task.id,start.prompt);return outcome.started?void 0:outcome.error??"engine session did not start"}function startScheduledStartRunner(deps,tickMs=DEFAULT_SCHEDULED_START_TICK_MS,now=Date.now){return startTicker({name:"scheduled-start",tickMs,immediate:!0,run:async()=>{for(let task of dueScheduledStarts(deps.orch.listTasks(),now()))await startScheduledNow(deps,task.id).catch((err)=>logDaemonError("scheduled-start",err));for(let start of deps.pending?.due(now())??[])await firePendingStart(deps,start).catch((err)=>logDaemonError("scheduled-start",err))}})}function isRemoteRepoKey(value){return value.startsWith("ssh://")}var DEFAULT_TRANSCRIPT_ACTIVITY_TICK_MS=1500,TRANSCRIPT_ACTIVITY_TIMEOUT_MS=4000,TRANSCRIPT_ACTIVITY_SLOW_RETRY_MS=60000,TRANSCRIPT_ACTIVITY_MIN_INTERVAL_MS=1500;function sameTranscriptActivityEntry(a,b){return a.mtimeMs===b.mtimeMs&&a.completionId===b.completionId&&a.completionAt===b.completionAt}async function runTranscriptActivity(worktreePath,vendor,detector,_signal){let{marker,mtimeMs}=await detector.latestActivity(worktreePath);return{mtimeMs:detector.supportsCompletionMarkers()?mtimeMs:0,completionId:marker?.id??null,completionAt:marker?.timestampMs??0}}function trackedWorktrees(tasks,defaultVendor){let map=new Map,ownersFirst=[...tasks].sort((a,b)=>Number(!!a.sharesWorkspaceOf)-Number(!!b.sharesWorkspaceOf));for(let task of ownersFirst){if(!task.worktreePath)continue;if(isRemoteRepoKey(task.repo)||isRemoteRepoKey(task.worktreePath))continue;if(map.has(task.worktreePath))continue;map.set(task.worktreePath,task.vendor??defaultVendor)}return map}class TranscriptActivityCollector{orch;bus;options;entries=new Map;stopped=!1;constructor(orch,bus,options){this.orch=orch;this.bus=bus;this.options=options}tick(){if(this.stopped)return;if(this.options.hasSubscribers&&!this.options.hasSubscribers())return;try{let tracked=trackedWorktrees(this.orch.listTasks(),this.options.defaultVendor),pruned=!1;for(let path of this.entries.keys()){if(tracked.has(path))continue;if(this.entries.get(path)?.value)pruned=!0;this.entries.delete(path)}if(pruned)this.publish();for(let[path,vendor]of tracked)this.maybeCollect(path,vendor)}catch(err){logDaemonError("transcript-activity",err)}}stop(){this.stopped=!0}maybeCollect(worktreePath,vendor){let entry=this.entries.get(worktreePath);if(!entry)entry={inFlight:!1,nextAllowedAt:0,vendor,detector:this.createDetector(vendor)},this.entries.set(worktreePath,entry);else if(entry.vendor!==vendor)entry.vendor=vendor,entry.detector=this.createDetector(vendor);let cadence=this.options.cadence??{timeoutMs:TRANSCRIPT_ACTIVITY_TIMEOUT_MS,slowRetryMs:TRANSCRIPT_ACTIVITY_SLOW_RETRY_MS,minIntervalMs:TRANSCRIPT_ACTIVITY_MIN_INTERVAL_MS},run=this.options.run??runTranscriptActivity,current=entry;maybeStartScheduledRun(current,cadence,(signal)=>run(worktreePath,current.vendor,current.detector,signal),(value)=>{if(this.stopped)return;if(this.entries.get(worktreePath)!==current)return;if(current.value&&sameTranscriptActivityEntry(current.value,value))return;current.value=value,this.publish()})}publish(){let activity={};for(let[path,entry]of this.entries)if(entry.value)activity[path]=entry.value;this.bus.publish("transcript.activity",{activity})}createDetector(vendor){return this.options.createDetector?.(vendor)??{latestActivity:async()=>({marker:null,mtimeMs:0}),latestActivityInFile:async()=>null,supportsCompletionMarkers:()=>!1}}}function startTranscriptActivityCollector(orch,runtime,bus,tickMs=DEFAULT_TRANSCRIPT_ACTIVITY_TICK_MS,hasSubscribers){let collector=new TranscriptActivityCollector(orch,bus,{hasSubscribers,createDetector:runtime.createEngineTurnDetector,defaultVendor:runtime.defaultTaskVendor,run:async(path,vendor,detector,signal)=>{let{marker,mtimeMs}=await detector.latestActivity(path);return{mtimeMs:detector.supportsCompletionMarkers()?mtimeMs:await runtime.latestTranscriptMtime(vendor,path),completionId:marker?.id??null,completionAt:marker?.timestampMs??0}}});return startTicker({name:"transcript-activity-collector",tickMs,immediate:!0,run:()=>collector.tick(),onStop:()=>collector.stop()})}import{readFileSync}from"fs";import{basename as basename2}from"path";var DEFAULT_UI_PREFS_DEBOUNCE_MS=200,FOCUS_ACCENT_SLOT_NAMES=["primary","success","info"],THEME_MODE_NAMES=["dark","light","auto"];function readUiPrefsFromStateFile(statePath){let parsed={};try{let raw=JSON.parse(readFileSync(statePath,"utf8"));if(raw&&typeof raw==="object"&&!Array.isArray(raw))parsed=raw}catch{}let theme=typeof parsed.activeTheme==="string"&&parsed.activeTheme.length>0?parsed.activeTheme:null,themeMode=typeof parsed.themeMode==="string"&&THEME_MODE_NAMES.includes(parsed.themeMode)?parsed.themeMode:null,transparentBackground=parsed.transparentBackground!==!1,focusAccent=typeof parsed.focusAccent==="string"&&FOCUS_ACCENT_SLOT_NAMES.includes(parsed.focusAccent)?parsed.focusAccent:null,sortMode=parsed.activeSortMode==="recent"||parsed.activeSortMode==="attention"||parsed.activeSortMode==="name"?parsed.activeSortMode:"default",keysCollapsed=parsed["tasksPane.keysCollapsed"]===!0,projectFilter=typeof parsed["tasksPane.projectFilter"]==="string"&&parsed["tasksPane.projectFilter"].length>0?parsed["tasksPane.projectFilter"]:null,locale=typeof parsed.locale==="string"&&parsed.locale.length>0?parsed.locale:"en";return{theme,themeMode,transparentBackground,focusAccent,locale,sortMode,keysCollapsed,projectFilter}}function samePrefs(a,b){return a.theme===b.theme&&a.themeMode===b.themeMode&&a.transparentBackground===b.transparentBackground&&a.focusAccent===b.focusAccent&&a.locale===b.locale&&a.sortMode===b.sortMode&&a.keysCollapsed===b.keysCollapsed&&a.projectFilter===b.projectFilter}function startUiPrefsWatcher(bus,options={}){let debounceMs=options.debounceMs??DEFAULT_UI_PREFS_DEBOUNCE_MS;if(debounceMs<=0)return()=>{};let statePath=options.statePath??defaultUiPrefsStatePath(),stateFile=basename2(statePath),last=null,publishIfChanged=()=>{try{let next=readUiPrefsFromStateFile(statePath);if(last&&samePrefs(last,next))return;last=next,bus.publish("ui-prefs",next)}catch(err){logDaemonError("ui-prefs-watcher",err)}},stop=startFileWatchTrigger({filePath:statePath,matchBasenames:[stateFile],debounceMs,onTrigger:publishIfChanged,onError:(err)=>logDaemonError("ui-prefs-watcher",err)});return publishIfChanged(),stop}import{stat as stat2}from"fs/promises";import{dirname}from"path";var DEFAULT_VANISHED_PROJECTS_TICK_MS=30000,PROBE_CADENCE={timeoutMs:2000,slowRetryMs:600000,minIntervalMs:DEFAULT_VANISHED_PROJECTS_TICK_MS},MAX_IN_FLIGHT=2;async function isDirectory(path){return(await stat2(path).catch(()=>null))?.isDirectory()===!0}async function checkoutVanished(path){if(await isDirectory(path))return!1;return isDirectory(dirname(path))}function createVanishedProjectsSweep(orch,probe=checkoutVanished){let states=new Map,inFlight=()=>[...states.values()].filter((s)=>s.inFlight).length;return()=>{let listed=new Set;for(let task of orch.listTasks()){if(task.kind!=="main"||task.repo.startsWith("ssh://"))continue;let path=task.worktreePath||task.repo;if(listed.add(path),inFlight()>=MAX_IN_FLIGHT)continue;let state=states.get(path)??{inFlight:!1,nextAllowedAt:0};states.set(path,state);let repo=task.repo;maybeStartScheduledRun(state,PROBE_CADENCE,()=>probe(path),(gone)=>{if(!gone)return;orch.forgetProject(repo).then(()=>logDaemonInfo("vanished-projects",`forgot ${repo}: its checkout is gone`)).catch((err)=>logDaemonError("vanished-projects",err))})}for(let[path,state]of states)if(!listed.has(path)&&!state.inFlight)states.delete(path)}}function startVanishedProjectsSweeper(orch,tickMs=DEFAULT_VANISHED_PROJECTS_TICK_MS){return startTicker({name:"vanished-projects",tickMs,immediate:!0,run:createVanishedProjectsSweep(orch)})}import{spawn as spawn4}from"child_process";function runGit(worktreePath,args,signal){return new Promise((resolve)=>{let stdout="",settled=!1,finish=(status)=>{if(settled)return;settled=!0,resolve(status===0?stdout:null)},child=spawn4("git",args.slice(),{cwd:worktreePath,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_OPTIONAL_LOCKS:"0"},signal,killSignal:"SIGKILL"});child.stdout?.on("data",(chunk)=>{stdout+=String(chunk)}),child.on("error",()=>finish(null)),child.on("close",finish)})}async function countDrift(worktreePath,baseRef,signal){return parseAheadBehind(await runGit(worktreePath,["rev-list","--left-right","--count",`${baseRef}...HEAD`],signal))}function parseAheadBehind(stdout){if(stdout===null)return null;let parts=stdout.trim().split(/\s+/);if(parts.length!==2)return null;let behind=Number.parseInt(parts[0]??"",10),ahead=Number.parseInt(parts[1]??"",10);if(!Number.isInteger(behind)||behind<0||!Number.isInteger(ahead)||ahead<0)return null;return{behind,ahead}}function countPorcelain(stdout){let added=0,deleted=0;for(let row of parsePorcelainRows(stdout))if(row.x==="D"||row.y==="D")deleted++;else added++;return{added,deleted}}async function runGitStatus(worktreePath,signal,baseRef){let stdout=await runGit(worktreePath,["status","--porcelain=v1"],signal);if(stdout===null)throw Error("git status failed");let counts=countPorcelain(stdout);if(!baseRef)return counts;let drift=await countDrift(worktreePath,baseRef,signal);return drift===null?counts:{...counts,...drift}}var EMPTY_PATHS=new Set;function isRemoteRepoKey2(value){return value.startsWith("ssh://")}function sameWorktreeChanges(a,b){return a.added===b.added&&a.deleted===b.deleted&&a.behind===b.behind&&a.ahead===b.ahead}var DEFAULT_WORKTREE_CHANGES_TICK_MS=2000,WORKTREE_CHANGES_CONCURRENCY=4,WORKTREE_CHANGES_TIMEOUT_MS=4000,WORKTREE_CHANGES_SLOW_RETRY_MS=60000,WORKTREE_CHANGES_MIN_INTERVAL_MS=1500,WORKTREE_CHANGES_QUIET_INTERVAL_MS=60000;function trackedWorktreePaths(tasks){let paths=new Map;for(let task of tasks)for(let repo of[task,...task.extraRepos??[]]){if(!repo.worktreePath)continue;if(isRemoteRepoKey2(repo.repo)||isRemoteRepoKey2(repo.worktreePath))continue;if(paths.get(repo.worktreePath)===void 0)paths.set(repo.worktreePath,repo.baseRef)}return paths}var UNREADABLE=Symbol("worktree-changes-unreadable");class WorktreeChangesCollector{orch;bus;options;entries=new Map;stopped=!1;queued=new Map;active=0;activePaths=new Set;drainHandle;publishTimer;controllers=new Set;constructor(orch,bus,options={}){this.orch=orch;this.bus=bus;this.options=options}tick(){if(this.stopped)return;if(this.options.hasSubscribers&&!this.options.hasSubscribers())return;try{let tasks=this.orch.listTasks(),tracked=trackedWorktreePaths(tasks),pruned=!1;for(let path of this.entries.keys()){if(tracked.has(path))continue;if(this.entries.get(path)?.value)pruned=!0;this.entries.delete(path),this.queued.delete(path)}for(let path of this.queued.keys())if(!tracked.has(path))this.queued.delete(path);if(pruned)this.publish();let busy=this.busyPaths(tasks);for(let[path,baseRef]of tracked)if(!this.entries.get(path)?.inFlight)this.queued.set(path,{baseRef,busy:busy.has(path)});this.drain()}catch(err){logDaemonError("worktree-changes",err)}}stop(){if(this.stopped=!0,this.queued.clear(),this.drainHandle)clearImmediate(this.drainHandle);if(this.publishTimer)clearTimeout(this.publishTimer);for(let controller of this.controllers)controller.abort()}drain(){if(this.stopped||this.options.hasSubscribers?.()===!1)return;let limit=WORKTREE_CHANGES_CONCURRENCY;for(let[path,demand]of this.queued){if(this.active>=limit)break;if(this.activePaths.has(path))continue;this.queued.delete(path);try{this.maybeCollect(path,demand.baseRef,demand.busy)}catch(err){logDaemonError("worktree-changes",err)}}}runFinished(path){if(this.active--,this.activePaths.delete(path),this.stopped||this.drainHandle)return;this.drainHandle=setImmediate(()=>{this.drainHandle=void 0,this.drain()})}busyPaths(tasks){let ids=this.options.activeTaskIds?.();if(!ids)return EMPTY_PATHS;let active=new Set(ids);if(active.size===0)return EMPTY_PATHS;let paths=new Set;for(let task of tasks){if(!active.has(task.id))continue;for(let repo of[task,...task.extraRepos??[]])if(repo.worktreePath)paths.add(repo.worktreePath)}return paths}maybeCollect(worktreePath,baseRef,busy=!1){let entry=this.entries.get(worktreePath);if(!entry)entry={inFlight:!1,nextAllowedAt:0},this.entries.set(worktreePath,entry);let now=Date.now(),probe=(this.options.probe??worktreeFingerprint)(worktreePath,baseRef),quietUntil=entry.quietUntil??0;if(!busy&&probe!==null&&probe===entry.probe&&now<quietUntil)return;let quietIntervalMs=this.options.quietIntervalMs??WORKTREE_CHANGES_QUIET_INTERVAL_MS,cadence=this.options.cadence??{timeoutMs:WORKTREE_CHANGES_TIMEOUT_MS,slowRetryMs:WORKTREE_CHANGES_SLOW_RETRY_MS,minIntervalMs:WORKTREE_CHANGES_MIN_INTERVAL_MS},run=this.options.run??runGitStatus;maybeStartScheduledRun(entry,cadence,(signal)=>{entry.probe=probe,entry.quietUntil=Date.now()+quietIntervalMs,this.active++,this.activePaths.add(worktreePath);let controller=new AbortController;this.controllers.add(controller);let abort=()=>controller.abort();return signal.addEventListener("abort",abort,{once:!0}),(async()=>{try{return await run(worktreePath,controller.signal,baseRef)}catch{return UNREADABLE}finally{signal.removeEventListener("abort",abort),this.controllers.delete(controller),this.runFinished(worktreePath)}})()},(value)=>{if(this.stopped)return;if(this.entries.get(worktreePath)!==entry)return;if(value===UNREADABLE&&entry.value!==void 0&&entry.value!==UNREADABLE)return;if(entry.value===value)return;if(entry.value&&entry.value!==UNREADABLE&&value!==UNREADABLE&&sameWorktreeChanges(entry.value,value))return;entry.value=value,this.publish()})}publish(){if(this.publishTimer||this.stopped)return;this.publishTimer=setTimeout(()=>{if(this.publishTimer=void 0,!this.stopped)this.publishNow()},this.options.publishDelayMs??10)}publishNow(){let changes={},unreadable=[];for(let[path,entry]of this.entries)if(entry.value===UNREADABLE)unreadable.push(path);else if(entry.value)changes[path]=entry.value;this.bus.publish("worktree.changes",unreadable.length>0?{changes,unreadable}:{changes})}}function startWorktreeChangesCollector(orch,runtime,bus,tickMs=DEFAULT_WORKTREE_CHANGES_TICK_MS,hasSubscribers,activeTaskIds){let collector=new WorktreeChangesCollector(orch,bus,{hasSubscribers,run:runtime.runWorktreeStatus,...activeTaskIds?{activeTaskIds}:{}});return startTicker({name:"worktree-changes-collector",tickMs,immediate:!0,run:()=>collector.tick(),onStop:()=>collector.stop()})}var DEFAULT_UPDATE_POLL_MS=21600000;function createProtocolUpgradeReporter(orch,runtime){return(taskId,tabId,evidence)=>{if(tabId!=="tab-1")return;let task=orch.getTask(taskId);if(!task)return;let upgrade=runtime.resolveProtocolUpgrade?.(task,evidence);if(!upgrade)return;return orch.setCommand(taskId,upgrade.command,upgrade.vendor).then(()=>logDaemonInfo("protocol-sniff",`upgraded task ${taskId} to the ${upgrade.vendor} protocol from its live session`)).catch((err)=>logDaemonError("protocol-sniff",err))}}var MACHINE_HUB_GATE_MS=1000,MACHINE_HUB_IDLE_MS=15000;function gateMachineHub(start,bus,hasSubscribersFor){let stop=null,idleSince=null,tick=()=>{try{if(hasSubscribersFor("machines"))idleSince=null,stop??=start(bus);else if(stop){if(idleSince??=Date.now(),Date.now()-idleSince>=MACHINE_HUB_IDLE_MS)stop(),stop=null}}catch(err){logDaemonError("machine-hub",err)}};tick();let timer=setInterval(tick,MACHINE_HUB_GATE_MS);return timer.unref?.(),()=>{clearInterval(timer),stop?.()}}function startDaemonCollectors(orch,runtime,bus,hasSubscribersFor,options,quotaUsage,automations,activity,inbox){let ownerOf=options.ownerOf??((taskId,tabId)=>resolvePtyOwner(orch.listTasks(),taskId,tabId)),receiveStatus=activity?programStatusActivity(activity,(id)=>!!orch.getTask(id),inbox,automations?.deliveryDeps,ownerOf):void 0,stopStatusWatch=receiveStatus?watchProgramStatus(receiveStatus,{homeDir:options.homeDir}):async()=>{},stopActivityObserver=activity?startActivityObserver(activity,{...createActivityObserverIo(options.homeDir,runtime,activity,ownerOf),onEngineEvidence:createProtocolUpgradeReporter(orch,runtime),onProgramStatusEvent:receiveStatus},()=>hasSubscribersFor("engine-state"),{ownerOf}):()=>{},checkUpdate=options.checkUpdate??runtime.checkLatestVersion,updatePollMs=options.updatePollMs??DEFAULT_UPDATE_POLL_MS,pollUpdate=()=>{checkUpdate().then((info)=>bus.publish("update",{info})).catch((err)=>logDaemonError("update-poller",err))},updateTimer=null;if(updatePollMs>0)pollUpdate(),updateTimer=setInterval(pollUpdate,updatePollMs),updateTimer.unref?.();let stopAutoTitlePoller=startAutoTitlePoller(orch,runtime,options.autoTitlePollMs??DEFAULT_AUTO_TITLE_POLL_MS,()=>hasSubscribersFor("task.snapshot"),options.conversationOf),stopUiPrefsWatcher=startUiPrefsWatcher(bus,{statePath:defaultUiPrefsStatePath(options.homeDir),debounceMs:options.uiPrefsDebounceMs??DEFAULT_UI_PREFS_DEBOUNCE_MS}),stopStateWatcher=startStateWatcher(bus,defaultUiPrefsStatePath(options.homeDir),options.uiPrefsDebounceMs??DEFAULT_STATE_DEBOUNCE_MS),stopMachineHub=runtime.startMachineHub?gateMachineHub(runtime.startMachineHub,bus,hasSubscribersFor):()=>{},stopKeybindingsWatcher=startKeybindingsWatcher(bus,{path:defaultKeybindingsPath(options.homeDir),debounceMs:options.keybindingsDebounceMs??DEFAULT_KEYBINDINGS_DEBOUNCE_MS}),stopWorktreeChangesCollector=startWorktreeChangesCollector(orch,runtime,bus,options.worktreeChangesTickMs??DEFAULT_WORKTREE_CHANGES_TICK_MS,()=>hasSubscribersFor("worktree.changes"),activity?()=>activity.workingTaskIds():void 0),stopTranscriptActivityCollector=startTranscriptActivityCollector(orch,runtime,bus,options.transcriptActivityTickMs??DEFAULT_TRANSCRIPT_ACTIVITY_TICK_MS,()=>hasSubscribersFor("transcript.activity")),stopContextUsageCollector=activity?startContextUsageCollector(activity,orch,bus,runtime,options.contextUsageTickMs??DEFAULT_CONTEXT_USAGE_TICK_MS,()=>hasSubscribersFor("usage.context")):()=>{},stopPrStatusPoller=startPrStatusPoller(orch,runtime,options.prStatusPollMs??DEFAULT_PR_STATUS_POLL_MS,()=>hasSubscribersFor("task.snapshot"),void 0,()=>needsPrPoll(orch.listTasks())||(activity?.workingTaskIds().length??0)>0),stopQuotaResumeRunner=startQuotaResumeRunner(orch,runtime,options.quotaResumeTickMs??DEFAULT_QUOTA_RESUME_TICK_MS,void 0,automations?.plugins,automations?.runnability,automations?.deliveryDeps.deliveries.claims),invokeApi=runtime.invokeApi?.bind(runtime),socketPath=automations?.socketPath,stopScheduledStartRunner=automations?startScheduledStartRunner({orch,runtime,link:automations.link,...automations.pendingStarts?{pending:automations.pendingStarts}:{},...invokeApi&&socketPath?{invoke:(verb,params)=>invokeApi(verb,params,socketPath)}:{}},options.scheduledStartTickMs??DEFAULT_SCHEDULED_START_TICK_MS):async()=>{},stopAutoFixRunner=activity&&options.autoFixTickMs!==0?startAutoFixRunner({orch,runtime,activity,inbox},options.autoFixTickMs??DEFAULT_AUTO_FIX_TICK_MS):()=>{},stopVanishedProjects=startVanishedProjectsSweeper(orch),stopAutomationRunner=automations?startAutomationRunner({store:automations.store,deliveries:automations.deliveryDeps.deliveries,orch,runtime,link:automations.link,...automations.plugins?{plugins:automations.plugins}:{},...automations.inbox?{inbox:automations.inbox}:{},...automations.gates?{gates:automations.gates}:{},...automations.runnability?{runnability:automations.runnability}:{},...automations.dispatches?{dispatches:automations.dispatches}:{}},options.automationTickMs??DEFAULT_AUTOMATION_TICK_MS):()=>{},deliverySweepBootedAt=(automations?.deliveryDeps.now??Date.now)(),stopDeliverySweep=automations&&activity?startTicker({name:"delivery-sweep",tickMs:options.automationTickMs??DEFAULT_AUTOMATION_TICK_MS,run:()=>sweepStalledDeliveries(automations.deliveryDeps,activity,deliverySweepBootedAt)}):()=>{},stopQuotaUsagePoller=quotaUsage?startQuotaUsagePoller(quotaUsage,()=>runtime.vendorsWithQuotaProbe(),()=>hasSubscribersFor("usage.snapshot"),options.quotaUsageTickMs):()=>{};return async()=>{if(updateTimer)clearInterval(updateTimer);await Promise.allSettled([stopActivityObserver,stopStatusWatch,stopAutoTitlePoller,stopPrStatusPoller,stopQuotaResumeRunner,stopScheduledStartRunner,stopAutoFixRunner,stopAutomationRunner,stopDeliverySweep,stopQuotaUsagePoller,stopUiPrefsWatcher,stopStateWatcher,stopVanishedProjects,stopMachineHub,stopKeybindingsWatcher,stopWorktreeChangesCollector,stopTranscriptActivityCollector,stopContextUsageCollector].map(async(stop)=>stop()))}}import{hostname}from"os";var AGENT_TURN_HANDLERS=[{name:"agentTurn.list",handle(payload,ctx){let taskId=optionalString(payload,"taskId"),repo=optionalString(payload,"repoRoot"),since=optionalNumber(payload,"since"),limit=optionalNumber(payload,"limit");return{turns:ctx.agentTurns?.list({...taskId?{taskId}:{},...repo?{repo}:{},...since!==void 0?{since}:{},...limit!==void 0?{limit}:{}})??[]}}}];function refusal(code,message){return{apiVersion:ROVE_API_VERSION,ok:!1,error:{code,message}}}function isParamValue(value){if(typeof value==="string"||typeof value==="boolean")return!0;if(typeof value==="number")return Number.isFinite(value);return Array.isArray(value)&&value.every((v)=>typeof v==="string")}var invoking=0;function invokingVerbs(){return invoking}var API_HANDLERS=[{name:"api.invoke",blocking:!0,async handle(payload,ctx){let verb=requireString(payload,"verb"),raw=payload.params??{};if(typeof raw!=="object"||raw===null||Array.isArray(raw))return refusal("BAD_FLAG","params must be an object keyed by flag name");let params=raw,bad=Object.entries(params).find(([,value])=>!isParamValue(value));if(bad)return refusal("BAD_FLAG",`param ${bad[0]} must be a string, number, boolean or string list`);if(!ctx.runtime.invokeApi)return refusal("RPC_ERROR","this daemon cannot run verbs");invoking++;try{return await ctx.runtime.invokeApi(verb,params,ctx.daemon.socketPath,{machine:optionalString(payload,"machine"),forwarded:optionalBoolean(payload,"forwarded"),from:optionalString(payload,"from")})}finally{invoking--}}}];var ATTENTION_HANDLERS=[{name:"attention.dismissRoutine",async handle(payload,ctx){return await ctx.inbox.deleteRoutineEpisode(requireString(payload,"automationId")),{deleted:!0}}},{name:"attention.dismiss",async handle(payload,ctx){let deliveryId=optionalString(payload,"deliveryId");if(deliveryId&&payload.taskId===void 0&&!ctx.deliveries.get(deliveryId))return{deleted:!1,found:!1};let taskId=deliveryId?optionalString(payload,"taskId")??ctx.deliveries.get(deliveryId)?.taskId:requireString(payload,"taskId"),tabId=optionalString(payload,"tabId")??null,at=payload.at===void 0?void 0:requireNumber(payload,"at"),deleted=deliveryId?await ctx.inbox.deleteDeliveryEpisode(deliveryId):await ctx.inbox.deleteEpisode(taskId,tabId,at);if(deliveryId)await ctx.deliveries.dismiss(deliveryId);if(deleted)ctx.plugins?.handleUiReport({kind:"attention.handled",taskId,detail:{how:"dismissed",...tabId?{tabId}:{}}});return{deleted}}},{name:"attention.list",handle(_payload,ctx){return{items:ctx.inbox.snapshot()}}},{name:"attention.read",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=optionalString(payload,"tabId")??null,at=requireNumber(payload,"at"),updated=await ctx.inbox.markRead(taskId,tabId,at);if(updated)ctx.plugins?.handleUiReport({kind:"attention.handled",taskId,detail:{how:"read",...tabId?{tabId}:{}}});return{updated}}},{name:"task.rowToken",handle(payload,ctx){if(!ctx.rowTokens)return{ok:!1,reason:"UNSUPPORTED"};let taskId=requireString(payload,"taskId"),source=optionalString(payload,"source")??"cli",key=optionalString(payload,"key")??"default";if(optionalBoolean(payload,"clear")===!0)return{ok:!0,cleared:ctx.rowTokens.clear(taskId,source,optionalString(payload,"key"))};let tone=payload.tone;return{ok:!0,token:ctx.rowTokens.set({taskId,source,key,text:requireString(payload,"text"),...isRowTokenTone(tone)?{tone}:{},...optionalNumber(payload,"ttlMs")!==void 0?{ttlMs:optionalNumber(payload,"ttlMs")}:{}})}}}];function queueOf(ctx){if(!ctx.promptQueue)throw Error("this daemon has no prompt queue");return ctx.promptQueue}function awaitingMenu(ctx,taskId,tabId){if(ctx.rowStatus?.list().tasks[taskId]?.tabs[tabId]?.kind==="needs-input")return!0;return ctx.promptQueue?.restUnconfirmed(taskId,tabId,ctx.rowStatus?.answeredAt(taskId,tabId))===!0}function heldBack(ctx,item){let state=ctx.activity.stateOf(item.taskId,item.tabId);if(state==="permission_needed"||awaitingMenu(ctx,item.taskId,item.tabId))return"awaiting-permission";if(state==="running"||state==="rate_limited")return"busy";return null}async function pasteQueued(ctx,item){let task=ctx.orch.getTask(item.taskId);if(!task||task.deletion||!task.worktreePath)return"task is gone";let blocked=heldBack(ctx,item);if(blocked)return blocked;let deliveryId=null;try{if(item.expectReport||task.requireReport===!0)deliveryId=(await ctx.deliveries.arm({taskId:task.id,tabId:item.tabId,source:"send",promptHead:item.text})).id;let text2=deliveryId?`${item.text}
18
+ ${fired}${body}`}var DEFAULT_AUTOMATION_TICK_MS=60000;function dueAutomations(automations,nowMs){return automations.filter((a)=>{if(!a.enabled)return!1;let at=Date.parse(a.nextRunAt);return Number.isFinite(at)&&at<=nowMs})}function resolveDueOccurrence(automation,nowMs,tickMs=DEFAULT_AUTOMATION_TICK_MS){let notBefore=Date.parse(automation.createdAt),scheduledFor=latestCronAtOrBefore(automation.schedule,nowMs,Number.isFinite(notBefore)?notBefore:0);if(scheduledFor===null)return null;let graceMs=automation.missedRunGraceMinutes*60000+Math.max(tickMs,0);return{scheduledFor,missed:nowMs-scheduledFor>graceMs}}function runEventFor(status){if(status==="dispatched"||status==="revived"||status==="ran")return"automation.dispatched";if(status==="dispatch_failed"||status==="script_failed")return"automation.failed";return"automation.skipped"}function resolveLink(link){return typeof link==="function"?link():link}function emitRunEvent(deps,automation,status,args,extra){if(extra.taskId&&(status==="dispatched"||status==="revived"||status==="dispatch_failed"))deps.dispatches?.record({kind:"routine",from:null,routine:automation.name,to:{taskId:extra.taskId,tabId:extra.tabId??null},promptHead:automation.prompt,delivered:status!=="dispatch_failed",...extra.error?{reason:extra.error}:{}});deps.plugins?.()?.handleUiReport({kind:runEventFor(status),...extra.taskId?{taskId:extra.taskId}:{},detail:{automationId:automation.id,name:automation.name,...automation.repo?{repo:automation.repo}:{},status,trigger:args.trigger,scheduledFor:new Date(args.scheduledFor).toISOString(),...extra.tabId?{tabId:extra.tabId}:{},...extra.error?{error:extra.error}:{}}})}async function raiseOrClearInboxEpisode(deps,automation,status,extra){let inbox=deps.inbox;if(!inbox)return;let now=deps.now??Date.now;await(automationRunNeedsAttention(status)?inbox.recordRoutineFailure({automationId:automation.id,name:automation.name,status,...extra.error?{error:extra.error}:{}},extra.taskId??null,now()):inbox.deleteRoutineEpisode?.(automation.id,"routine_failed"))?.catch((err)=>logDaemonError("automation-inbox",err))}async function recordSkip(deps,automation,status,scheduledFor,error){let now=deps.now??Date.now;await deps.store.recordRun({automationId:automation.id,scheduledFor:new Date(scheduledFor).toISOString(),status,trigger:"scheduled",at:new Date(now()).toISOString(),error}),emitRunEvent(deps,automation,status,{scheduledFor,trigger:"scheduled"},{error})}function droppedOccurrences(automation,scheduledFor){let armedAt=Date.parse(automation.nextRunAt);if(!Number.isFinite(armedAt)||armedAt>=scheduledFor)return null;let count=countCronBetween(automation.schedule,armedAt,scheduledFor);return count>0?{count,firstMs:armedAt}:null}async function runScript(script,automation,record,now,env){let result=await runAutomationPrecheck(script,await ensureRoutineCwd(automation),void 0,env),stdout=result.stdout.trim(),response=stdout?{response:{text:stdout,at:new Date(now()).toISOString()}}:{};if(precheckPassed(result))return await record("ran",response);let reason=formatPrecheckSkip(result).replace(/^precheck/,"script"),stderr=result.stderr.trim();return logDaemonInfo("automation",`${automation.name}: ${reason}`),await record("script_failed",{...response,error:stderr?`${reason}: ${stderr.slice(-500)}`:reason})}async function runAutomationOnce(deps,automation,args){let env=args.event?webhookPrecheckEnv(args.event):void 0,now=deps.now??Date.now,reserved=deps.store.reserveRun(automation.id),record=async(status,extra={})=>{return await deps.store.recordRun({automationId:automation.id,scheduledFor:new Date(args.scheduledFor).toISOString(),status,trigger:args.trigger,...args.event?{event:args.event.summary}:{},at:new Date(now()).toISOString(),...extra},reserved),emitRunEvent(deps,automation,status,args,extra),await raiseOrClearInboxEpisode(deps,automation,status,extra),status},cancelled=()=>deps.stopped?.()===!0||deps.store.get(automation.id)!==automation||args.trigger!=="manual"&&!automation.enabled;if(cancelled())return await record("skipped_cancelled",{error:"routine disabled, changed, deleted or runner stopped before delivery"});if(await routineRepoMissing(automation.repo))return await record("skipped_unavailable",{error:`repo does not exist: ${automation.repo}`});if(args.trigger!=="manual"&&automation.precheck){let skipped=await precheckSkip(automation,automation.precheck,await ensureRoutineCwd(automation),env);if(skipped)return await record("skipped_precheck",{precheckResult:skipped.precheckResult,error:skipped.reason})}if(cancelled())return await record("skipped_cancelled",{error:"routine disabled, changed, deleted or runner stopped before delivery"});if(automation.script)return await runScript(automation.script,automation,record,now,env);let outcome,deliveryId,elided=!1,elidedLive=!1,settleDelivery=async(delivered)=>{if(!deliveryId)return;let id=deliveryId;if(delivered===null)deliveryId=void 0;await(delivered===null?deps.deliveries.cancel(id):deps.deliveries.setTab(id,delivered.tabId??"tab-1")).catch((err)=>logDaemonError("automation-delivery",err))};try{outcome=await dispatchAutomation({canDeliver:()=>!cancelled(),orch:deps.orch,runtime:deps.runtime,link:()=>resolveLink(deps.link),...deps.gates?{gates:deps.gates}:{},...deps.runnability&&args.trigger!=="manual"?{runnability:deps.runnability}:{},...deps.now?{now:deps.now}:{}},automation,async(target)=>{if(deliveryId??=(await deps.deliveries.arm({taskId:target.taskId,tabId:target.tabId,source:"routine",automationRunId:reserved.id,promptHead:automation.prompt})).id,elided=sessionHoldsPrompt(automation,deps.store.runsFor(automation.id),target),!target.fresh)elidedLive=elided;let api=deps.runtime.roveApiInvocation?.()??"rove api";return withRoutineRunHeader(automation,reserved,api,deliveryId,args.event,elided)})}catch(err){let error=err instanceof Error?err.message:String(err);return logDaemonError("automation-dispatch",err),await settleDelivery(null),await record("skipped_unavailable",{error})}if(outcome.status==="revived"&&outcome.resumed)elided=elidedLive;if(await settleDelivery(outcome.status==="dispatched"||outcome.status==="revived"?outcome:null),outcome.sessionTaskIdToSet){if(!await deps.store.linkSessionTask(automation.id,outcome.sessionTaskIdToSet,automation).catch((err)=>{return logDaemonError("automation-session-link",err),!0}))logDaemonInfo("automation",`${automation.name}: not adopting ${outcome.sessionTaskIdToSet}`)}else if(outcome.sessionTaskIdToClear)await deps.store.update(automation.id,{sessionTaskId:null}).catch((err)=>logDaemonError("automation-session-unlink",err));if(outcome.status==="dispatched"||outcome.status==="revived"){let tab=outcome.tabId?` tab=${outcome.tabId}`:"";logDaemonInfo("automation",`${outcome.status} ${automation.name} task=${outcome.taskId}${tab}`)}return await record(outcome.status,{...outcome.taskId?{taskId:outcome.taskId}:{},...outcome.tabId?{tabId:outcome.tabId}:{},...outcome.error?{error:outcome.error}:{},...outcome.blocked?{blocked:outcome.blocked}:{},...deliveryId?{deliveryId,promptHash:routinePromptHash(automation.prompt)}:{},...deliveryId&&elided?{promptElided:!0}:{}})}async function sweepAutomations(deps,tickMs=DEFAULT_AUTOMATION_TICK_MS){let now=deps.now??Date.now;for(let automation of dueAutomations(deps.store.list(),now())){if(deps.stopped?.())return;let nowMs=now(),occurrence=resolveDueOccurrence(automation,nowMs,tickMs);if(!occurrence){await deps.store.advanceNextRun(automation.id,nowMs);continue}let dropped=droppedOccurrences(automation,occurrence.scheduledFor),claimed=await deps.store.advanceNextRun(automation.id,occurrence.scheduledFor,automation.nextRunAt);if(!claimed)continue;if(dropped){let first=new Date(dropped.firstMs).toISOString();await recordSkip(deps,automation,"skipped_missed",dropped.firstMs,`${dropped.count} earlier occurrence${dropped.count===1?"":"s"} never ran (from ${first})`).catch((err)=>logDaemonError("automation-dropped",err))}if(occurrence.missed){await recordSkip(deps,automation,"skipped_missed",occurrence.scheduledFor,`missed by more than the ${automation.missedRunGraceMinutes}m grace window`);continue}await runAutomationOnce(deps,claimed,{scheduledFor:occurrence.scheduledFor,trigger:"scheduled"}).catch((err)=>logDaemonError("automation-run",err))}}function startAutomationRunner(deps,tickMs=DEFAULT_AUTOMATION_TICK_MS){let stopped=!1;return startTicker({name:"automation-sweep",tickMs,run:()=>sweepAutomations({...deps,stopped:()=>stopped},tickMs),onStop:()=>{stopped=!0}})}var DEFAULT_CONTEXT_USAGE_TICK_MS=1e4,CONTEXT_USAGE_TIMEOUT_MS=4000,CONTEXT_USAGE_SLOW_RETRY_MS=60000,CONTEXT_USAGE_MIN_INTERVAL_MS=5000;function sameContextUsage(a,b){return a.contextTokens===b.contextTokens&&a.contextWindowTokens===b.contextWindowTokens&&a.approximate===b.approximate&&a.inputTokens===b.inputTokens&&a.outputTokens===b.outputTokens&&a.cacheReadTokens===b.cacheReadTokens&&a.cacheCreationTokens===b.cacheCreationTokens&&JSON.stringify(a.parts)===JSON.stringify(b.parts)}function contextUsageTargets(states,getVendor){let seen=new Set,targets=[];for(let state of states){if(!state.tabId||!state.sessionId)continue;let vendor=getVendor(state.taskId);if(!vendor)continue;let key=`${state.taskId}::${state.tabId}`;if(seen.has(key))continue;seen.add(key),targets.push({key,vendor,sessionId:state.sessionId})}return targets}class ContextUsageCollector{registry;orch;bus;runtime;options;entries=new Map;stopped=!1;constructor(registry,orch,bus,runtime,options={}){this.registry=registry;this.orch=orch;this.bus=bus;this.runtime=runtime;this.options=options}tick(){if(this.stopped)return;if(this.options.hasSubscribers&&!this.options.hasSubscribers())return;try{let targets=contextUsageTargets(this.registry.liveSessions(),(id)=>this.orch.getTask(id)?.vendor),live=new Set(targets.map((t)=>t.key)),pruned=!1;for(let key of[...this.entries.keys()]){if(live.has(key))continue;if(this.entries.get(key)?.value)pruned=!0;this.entries.delete(key)}if(pruned)this.publish();for(let target of targets)this.collect(target)}catch(err){logDaemonError("context-usage",err)}}stop(){this.stopped=!0}collect(target){let entry=this.entries.get(target.key);if(!entry)entry={inFlight:!1,nextAllowedAt:0},this.entries.set(target.key,entry);if(entry.sessionId!==void 0&&entry.sessionId!==target.sessionId){let had=entry.value!==void 0;if(entry.value=void 0,entry.nextAllowedAt=0,entry.sessionId=target.sessionId,had)this.publish()}entry.sessionId=target.sessionId;let cadence=this.options.cadence??{timeoutMs:CONTEXT_USAGE_TIMEOUT_MS,slowRetryMs:CONTEXT_USAGE_SLOW_RETRY_MS,minIntervalMs:CONTEXT_USAGE_MIN_INTERVAL_MS},read=this.options.read??((t)=>this.runtime.readEngineContextUsage(t.vendor,t.sessionId)),startedAt=Date.now();if(entry.inFlight||startedAt<entry.nextAllowedAt)return;entry.inFlight=!0;let controller=new AbortController,timer=setTimeout(()=>controller.abort(),cadence.timeoutMs),held=entry;read(target,controller.signal).then((value)=>{if(controller.signal.aborted||this.stopped)return;if(this.entries.get(target.key)!==held)return;if(!value)return;if(held.value&&sameContextUsage(held.value,value))return;held.value=value,this.publish()}).catch(()=>{}).finally(()=>{clearTimeout(timer);let finishedAt=Date.now();held.nextAllowedAt=computeNextAllowedAt(startedAt,finishedAt,controller.signal.aborted,cadence),held.inFlight=!1})}publish(){let context={};for(let[key,entry]of this.entries)if(entry.value)context[key]=entry.value;this.bus.publish("usage.context",{context})}}function startContextUsageCollector(registry,orch,bus,runtime,tickMs=DEFAULT_CONTEXT_USAGE_TICK_MS,hasSubscribers){if(tickMs<=0)return()=>{};let collector=new ContextUsageCollector(registry,orch,bus,runtime,{hasSubscribers});collector.tick();let timer=setInterval(()=>collector.tick(),tickMs);return timer.unref?.(),()=>{clearInterval(timer),collector.stop()}}import{basename}from"path";var DEFAULT_KEYBINDINGS_DEBOUNCE_MS=200;function startKeybindingsWatcher(bus,options={}){let debounceMs=options.debounceMs??DEFAULT_KEYBINDINGS_DEBOUNCE_MS;if(debounceMs<=0)return()=>{};let filePath=options.path??defaultKeybindingsPath(),baseYaml=basename(filePath),baseYml=baseYaml.replace(/\.yaml$/,".yml"),rev=0;return bus.publish("keybindings",{rev}),startFileWatchTrigger({filePath,matchBasenames:[baseYaml,baseYml],debounceMs,onTrigger:()=>{try{rev+=1,bus.publish("keybindings",{rev})}catch(err){logDaemonError("keybindings-watcher",err)}},onError:(err)=>logDaemonError("keybindings-watcher",err)})}import{readFileSync,statSync as statSync2}from"fs";var PR_REFRESH_SECONDS_KEY="pr.refreshSeconds",PR_REFRESH_MIN_SECONDS=30,PR_REFRESH_MAX_SECONDS=3600;function normalizePrRefreshSeconds(value){if(typeof value!=="number"||!Number.isInteger(value))return;if(value===0)return 0;if(value<PR_REFRESH_MIN_SECONDS||value>PR_REFRESH_MAX_SECONDS)return;return value*1000}function makePrRefreshReader(statePath=defaultUiPrefsStatePath){let stamp,cached;return()=>{let file=statePath(),next;try{let st=statSync2(file);next=`${file}:${st.mtimeMs}:${st.size}`}catch{stamp=void 0,cached=void 0;return}if(next===stamp)return cached;stamp=next;try{let raw=JSON.parse(readFileSync(file,"utf8")),value=raw&&typeof raw==="object"&&!Array.isArray(raw)?raw[PR_REFRESH_SECONDS_KEY]:void 0;cached=normalizePrRefreshSeconds(value)}catch{cached=void 0}return cached}}function sessionPrKey(taskId,url){return`${taskId}::pr::${url}`}function pollableSessionPrs(task){if(task.repo.startsWith("ssh://")||task.worktreePath?.startsWith("ssh://"))return[];return task.sessionPrs??[]}function sessionPrJobs(orch,tasks,ctx){let jobs=[];for(let task of tasks)for(let{url}of pollableSessionPrs(task)){let entry=ctx.schedule.get(sessionPrKey(task.id,url));if(entry&&ctx.now<entry.nextAllowedAt)continue;jobs.push(()=>pollSessionPr(orch,task.id,url,entry?.failures??0,ctx))}return jobs}async function pollSessionPr(orch,taskId,url,prevFailures,ctx){let{runtime,schedule,now,cfg,rand}=ctx,key=sessionPrKey(taskId,url);try{let result=await ctx.run(url);if(result.kind==="error"){logOncePerChange(`session-pr:${key}`,"pr-status-poller",`gh pr view failed (${result.error}) for task ${taskId} session PR ${url} \u2014 keeping last status, backing off`),schedule.set(key,runtime.prStatus.nextPoll({kind:"error",error:result.error},prevFailures,now,cfg,rand));return}logOncePerChange(`session-pr:${key}`,"pr-status-poller",void 0);let next=result.kind==="pr"?runtime.prStatus.mapView(result.view,ctx.at):null;if(!next){schedule.set(key,runtime.prStatus.nextPoll({kind:"empty"},prevFailures,now,cfg,rand));return}let attached=orch.getTask(taskId)?.sessionPrs?.find((p)=>p.url===url);if(!attached){schedule.delete(key);return}let changed;if(attached.status?.lastError!==void 0||!runtime.prStatus.sameStatus(attached.status,next))await orch.setSessionPrStatus(taskId,url,next),changed=taskId;let settled=next.lifecycle==="merged"||next.lifecycle==="closed";return schedule.set(key,runtime.prStatus.nextPoll({kind:"pr",settled},prevFailures,now,cfg,rand)),changed}catch(err){logDaemonError("pr-status-poller",err),schedule.set(key,runtime.prStatus.nextPoll({kind:"error",error:"network"},prevFailures,now,cfg,rand));return}}var DEFAULT_PR_STATUS_POLL_MS=30000,NO_PR_BACKOFF_MS=300000,SETTLED_BACKOFF_MS=600000,PR_FAILURE_BASE_MS=DEFAULT_PR_STATUS_POLL_MS,PR_FAILURE_CAP_MS=900000,NO_REMOTE_BACKOFF_MS=1800000,PR_POLL_JITTER_RATIO=0.2,PR_POLL_CONCURRENCY=8;function isRepoPollable(task,view){if(!workspaceCapabilities(task).ownsBranch)return!1;if(!view.branch||!view.worktreePath)return!1;if(view.repo.startsWith("ssh://")||view.worktreePath.startsWith("ssh://"))return!1;return!0}var EXTRA_KEY_SEP="::";function pollKey(taskId,extraName){return extraName===void 0?taskId:`${taskId}${EXTRA_KEY_SEP}${extraName}`}async function setPrStaleMarker(orch,taskId,extraName,error){let row=orch.getTask(taskId),prev=extraName===void 0?row?.prStatus:row?.extraRepos?.find((e)=>e.name===extraName)?.prStatus;if(!prev||prev.lastError===error)return!1;let{lastError:_cleared,...rest}=prev;return await orch.setPRStatus(taskId,error===void 0?rest:{...rest,lastError:error},extraName),!0}async function runPrStatusPass(orch,opts){let tickMs=opts.tickMs??DEFAULT_PR_STATUS_POLL_MS,rand=opts.rand,cfg={tickMs,settledMs:SETTLED_BACKOFF_MS,noPrMs:NO_PR_BACKOFF_MS,noRemoteMs:NO_REMOTE_BACKOFF_MS,failureBaseMs:PR_FAILURE_BASE_MS,failureCapMs:PR_FAILURE_CAP_MS,jitterRatio:PR_POLL_JITTER_RATIO},tasks=orch.listTasks(),liveKeys=new Set;for(let task of tasks){liveKeys.add(task.id);for(let extra of task.extraRepos??[])liveKeys.add(pollKey(task.id,extra.name));for(let{url}of pollableSessionPrs(task))liveKeys.add(sessionPrKey(task.id,url))}for(let key of opts.schedule.keys())if(!liveKeys.has(key))opts.schedule.delete(key);let due=[];for(let task of tasks){let repos=[{extraName:void 0,repo:task},...(task.extraRepos??[]).map((e)=>({extraName:e.name,repo:e}))];for(let{extraName,repo}of repos){let key=pollKey(task.id,extraName);if(!isRepoPollable(task,repo)){opts.schedule.delete(key);continue}let entry=opts.schedule.get(key);if(entry&&opts.now<entry.nextAllowedAt)continue;due.push({task,extraName,repo,prevFailures:entry?.failures??0})}}let pollOne=async(task,extraName,repo,prevFailures)=>{let key=pollKey(task.id,extraName),label=extraName===void 0?task.id:`${task.id} repo ${extraName}`;try{let prev=extraName===void 0?task.prStatus:task.extraRepos?.find((e)=>e.name===extraName)?.prStatus,result=await opts.run(repo.worktreePath??"",repo.branch,prev?.number);if(result.kind==="error"){logOncePerChange(`pr-poll:${key}`,"pr-status-poller",`gh pr list failed (${result.error}) for task ${label} [${repo.branch}] \u2014 keeping last PR status, backing off`);let marked=await setPrStaleMarker(orch,task.id,extraName,result.error);return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"error",error:result.error},prevFailures,opts.now,cfg,rand)),marked?task.id:void 0}if(result.kind==="empty"){logOncePerChange(`pr-poll:${key}`,"pr-status-poller",void 0);let marked=await setPrStaleMarker(orch,task.id,extraName,void 0);return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"empty"},prevFailures,opts.now,cfg,rand)),marked?task.id:void 0}logOncePerChange(`pr-poll:${key}`,"pr-status-poller",void 0);let next=opts.runtime.prStatus.mapView(result.view,opts.at),current=orch.getTask(task.id);if(!current){opts.schedule.delete(key);return}let currentPr=extraName===void 0?current.prStatus:current.extraRepos?.find((e)=>e.name===extraName)?.prStatus,wasStale=currentPr?.lastError!==void 0,changedId;if(wasStale||!opts.runtime.prStatus.sameStatus(currentPr,next??void 0))await orch.setPRStatus(task.id,next,extraName),changedId=task.id;let settled=next?.lifecycle==="merged"||next?.lifecycle==="closed";return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"pr",settled},prevFailures,opts.now,cfg,rand)),changedId}catch(err){logDaemonError("pr-status-poller",err);let marked=await setPrStaleMarker(orch,task.id,extraName,"network").catch(()=>!1);return opts.schedule.set(key,opts.runtime.prStatus.nextPoll({kind:"error",error:"network"},prevFailures,opts.now,cfg,rand)),marked?task.id:void 0}},sessionJobs=opts.runUrl?sessionPrJobs(orch,tasks,{runtime:opts.runtime,run:opts.runUrl,now:opts.now,at:opts.at,schedule:opts.schedule,cfg,rand}):[],total=due.length+sessionJobs.length,slots=Array(total),cursor=0,worker=async()=>{for(let i=cursor++;i<total;i=cursor++){if(i>=due.length){slots[i]=await sessionJobs[i-due.length]?.();continue}let item=due[i];if(item)slots[i]=await pollOne(item.task,item.extraName,item.repo,item.prevFailures)}};return await Promise.all(Array.from({length:Math.min(PR_POLL_CONCURRENCY,total)},worker)),[...new Set(slots.filter((id)=>id!==void 0))]}function startPrStatusPoller(orch,runtime,intervalMs=DEFAULT_PR_STATUS_POLL_MS,hasSubscribers,run=makeGhPrViewRunner(runtime.prStatus.classify,runtime.prStatus.viewFields),hasWorkingAgent,runUrl=makeGhPrUrlRunner(runtime.prStatus.classify,runtime.prStatus.viewFields),refreshMs){let schedule=new Map;return startTicker({name:"pr-status-poller",tickMs:intervalMs,...hasSubscribers?{gate:()=>hasSubscribers()||(hasWorkingAgent?.()??!1)}:{},run:()=>{let cadence=refreshMs?.()??intervalMs;if(cadence<=0)return;return runPrStatusPass(orch,{runtime,run,runUrl,now:Date.now(),at:new Date().toISOString(),schedule,tickMs:Math.max(cadence,intervalMs)})}})}class InflightClaims{now;claims=new Map;nextId=1;constructor(now=Date.now){this.now=now}claim(taskId,tabId,covered=!1){let id=`c-${this.nextId++}`;return this.claims.set(id,{taskId,tabId,covered,expiresAt:this.now()+90000}),id}release(id,landed){let claim=this.claims.get(id);if(!claim)return;if(landed&&!claim.covered)claim.expiresAt=this.now()+15000;else this.claims.delete(id)}isClaimed(taskId,tabId){let now=this.now();for(let[id,claim]of this.claims){if(claim.expiresAt<=now){this.claims.delete(id);continue}if(claim.taskId===taskId&&(tabId===null||claim.tabId===null||claim.tabId===tabId))return!0}return!1}}function quotaResumeContinuePrompt(language){return language==="zh"?"\u4ECE\u4E2D\u65AD\u7684\u5730\u65B9\u7EE7\u7EED\u8FD9\u4E2A\u4EFB\u52A1\u3002\u4E0A\u9762\u7684\u5BF9\u8BDD\u8BB0\u5F55\u91CC\u5DF2\u7ECF\u5B8C\u6210\u7684\u5DE5\u4F5C\u4E0D\u8981\u91CD\u505A\u3002":"Continue the task from where it stopped. The transcript above shows the work already completed \u2014 do not redo it."}var DEFAULT_QUOTA_RESUME_TICK_MS=60000;function dueQuotaResumes(tasks,nowMs){return tasks.filter((task)=>{if(!task.quotaResume||!task.worktreePath)return!1;if(task.deletion)return!1;let at=Date.parse(task.quotaResume.resumeAt);return Number.isFinite(at)&&at<=nowMs})}function quotaWaitingTasks(tasks,entryOf){return tasks.filter((task)=>{if(!task.worktreePath||task.deletion)return!1;if(task.quotaResume)return!0;let entry=entryOf(task.id);return entry?.state==="rate_limited"&&entry.detail?.failure!=="billing"})}function exhaustedResetAtMs(usage,nowMs){let candidates=usage.windows.filter((w)=>w.percent>=100&&w.resetsAt!=null&&w.resetsAt>nowMs).map((w)=>w.resetsAt);return candidates.length>0?Math.min(...candidates):null}async function scheduleQuotaResume(orch,runtime,cache,taskId,now=Date.now,plugins){let task=orch.getTask(taskId);if(!task||!task.worktreePath||task.deletion)return;let usage=await cache.get(task.vendor??runtime.defaultTaskVendor,0),resetAtMs=usage?exhaustedResetAtMs(usage,now()):null;if(resetAtMs==null)return;let resumeAt=new Date(resetAtMs).toISOString();await orch.setQuotaResume(taskId,{resumeAt,requestedAt:new Date(now()).toISOString()}),logDaemonInfo("quota-resume",`armed task=${taskId} resumeAt=${resumeAt}`),plugins?.()?.handleUiReport({kind:"quota.exhausted",taskId,detail:{vendor:task.vendor??runtime.defaultTaskVendor,resumeAt}})}async function resumeQuotaTask(orch,runtime,task,claims,plugins,runnability){if(claims.isClaimed(task.id,null))return{taskId:task.id,status:"declined",reason:"busy"};let verdict=runnability?.check(task.id,null,["quota"]);if(verdict&&!verdict.run)return await orch.setQuotaResume(task.id,null),logDaemonInfo("quota-resume",`declined task=${task.id} reason=${verdict.reason}`),{taskId:task.id,status:"declined",reason:verdict.reason};let claimId=claims.claim(task.id,null),delivered=!1;try{return await orch.setQuotaResume(task.id,null),delivered=await runtime.deliverPromptToLiveEngine({id:task.id,vendor:task.vendor,command:task.command,worktreePath:task.worktreePath,scope:ptyScopeFor(orch.listTasks(),task.id)},quotaResumeContinuePrompt(task.observedLanguage)),logDaemonInfo("quota-resume",`resume task=${task.id} delivered=${delivered}`),plugins?.()?.handleUiReport({kind:"quota.resumed",taskId:task.id,detail:{delivered}}),{taskId:task.id,status:delivered?"resumed":"not-delivered"}}finally{claims.release(claimId,delivered)}}function startQuotaResumeRunner(orch,runtime,tickMs=DEFAULT_QUOTA_RESUME_TICK_MS,now=Date.now,plugins,runnability,claims=new InflightClaims){return startTicker({name:"quota-resume",tickMs,run:async()=>{for(let task of dueQuotaResumes(orch.listTasks(),now()))await resumeQuotaTask(orch,runtime,task,claims,plugins,runnability).catch((err)=>logDaemonError("quota-resume",err))}})}var FRESH_POLL_MS=900000,RETRY_BASE_MS=60000,MIN_FETCH_INTERVAL_MS=60000;class QuotaUsageCache{runtime;bus;now;entries=new Map;constructor(runtime,bus,now=Date.now){this.runtime=runtime;this.bus=bus;this.now=now}peek(vendor){return this.entries.get(vendor)?.usage??null}async get(vendor,maxAgeMs){let entry=this.entry(vendor),age=this.now()-(entry.usage?.capturedAt??0);if(entry.usage&&age<=maxAgeMs)return entry.usage;if(entry.inFlight)return entry.inFlight;if(this.now()-entry.attemptedAt<MIN_FETCH_INTERVAL_MS)return entry.usage;return this.fetch(vendor,entry)}async refreshIfDue(vendor){let entry=this.entry(vendor),retryAfter=entry.failures===0?0:Math.min(RETRY_BASE_MS*2**(entry.failures-1),FRESH_POLL_MS),dueAfter=entry.usage?FRESH_POLL_MS:retryAfter;if(this.now()-entry.attemptedAt<dueAfter)return;await this.fetch(vendor,entry)}entry(vendor){let existing=this.entries.get(vendor);if(existing)return existing;let fresh={usage:null,attemptedAt:0,failures:0,inFlight:null};return this.entries.set(vendor,fresh),fresh}fetch(vendor,entry){if(entry.inFlight)return entry.inFlight;return entry.attemptedAt=this.now(),entry.inFlight=this.runtime.quotaUsage(vendor).catch(()=>null).then((usage)=>{if(entry.inFlight=null,usage){entry.failures=0;let changed=JSON.stringify(usage.windows)!==JSON.stringify(entry.usage?.windows);if(entry.usage=usage,changed)this.publish()}else entry.failures+=1;return entry.usage}),entry.inFlight}publish(){let usage={};for(let[vendor,entry]of this.entries)if(entry.usage)usage[vendor]=entry.usage;this.bus.publish("usage.snapshot",{usage})}}function startQuotaUsagePoller(cache,listVendors,hasSubscribers,tickMs=MIN_FETCH_INTERVAL_MS){return startTicker({name:"quota-usage-poller",tickMs,gate:hasSubscribers,immediate:!0,run:()=>{for(let vendor of new Set(listVendors()))cache.refreshIfDue(vendor)}})}var DEFAULT_SCHEDULED_START_TICK_MS=15000;function dueScheduledStarts(tasks,nowMs){return tasks.filter((task)=>{if(!task.scheduledStart||task.deletion)return!1;let at=Date.parse(task.scheduledStart.at);return!Number.isFinite(at)||at<=nowMs})}async function startScheduledNow(deps,taskId){let task=deps.orch.getTask(taskId),schedule=task?.scheduledStart;if(!task||!schedule)return"dropped";if(await deps.orch.setScheduledStart(taskId,null),task.deletion||task.prompt)return logDaemonInfo("scheduled-start",`dropped task=${taskId} (${task.deletion?"being deleted":"already started"})`),"dropped";await deps.orch.setPrompt(taskId,schedule.prompt);let link=typeof deps.link==="function"?deps.link():deps.link,outcome=await deps.runtime.startTaskSessionWithPrompt(link,taskId,schedule.prompt);return logDaemonInfo("scheduled-start",`start task=${taskId} started=${outcome.started} ${outcome.error??""}`.trim()),outcome.started?"started":"failed"}async function firePendingStart(deps,start){if(!deps.pending||!await deps.pending.remove(start.id))return"dropped";let error=await createPendingStart(deps,start).catch((err)=>err instanceof Error?err.message:String(err));if(logDaemonInfo("scheduled-start",`pending start=${start.id} ${error?`failed: ${error}`:"started"}`),!error)return"started";return await deps.pending.fail(start,error),"failed"}async function createPendingStart(deps,start){let{create}=start;if(create.via==="add"){if(!deps.invoke)return"this daemon cannot run verbs";let envelope=await deps.invoke("add",{...create.params,prompt:start.prompt});return envelope.ok?void 0:`${envelope.error.code}: ${envelope.error.message}`}let dir=create.project?(await deps.orch.ensureMainTask(create.dir)).repo:create.dir,task=await deps.orch.openDirectoryTask({dir,...create.vendor?{vendor:create.vendor}:{},...start.title?{title:start.title}:{}});await deps.orch.setPrompt(task.id,start.prompt);let link=typeof deps.link==="function"?deps.link():deps.link,outcome=await deps.runtime.startTaskSessionWithPrompt(link,task.id,start.prompt);return outcome.started?void 0:outcome.error??"engine session did not start"}function startScheduledStartRunner(deps,tickMs=DEFAULT_SCHEDULED_START_TICK_MS,now=Date.now){return startTicker({name:"scheduled-start",tickMs,immediate:!0,run:async()=>{for(let task of dueScheduledStarts(deps.orch.listTasks(),now()))await startScheduledNow(deps,task.id).catch((err)=>logDaemonError("scheduled-start",err));for(let start of deps.pending?.due(now())??[])await firePendingStart(deps,start).catch((err)=>logDaemonError("scheduled-start",err))}})}function isRemoteRepoKey(value){return value.startsWith("ssh://")}var DEFAULT_TRANSCRIPT_ACTIVITY_TICK_MS=1500,TRANSCRIPT_ACTIVITY_TIMEOUT_MS=4000,TRANSCRIPT_ACTIVITY_SLOW_RETRY_MS=60000,TRANSCRIPT_ACTIVITY_MIN_INTERVAL_MS=1500;function sameTranscriptActivityEntry(a,b){return a.mtimeMs===b.mtimeMs&&a.completionId===b.completionId&&a.completionAt===b.completionAt}async function runTranscriptActivity(worktreePath,vendor,detector,_signal){let{marker,mtimeMs}=await detector.latestActivity(worktreePath);return{mtimeMs:detector.supportsCompletionMarkers()?mtimeMs:0,completionId:marker?.id??null,completionAt:marker?.timestampMs??0}}function trackedWorktrees(tasks,defaultVendor){let map=new Map,ownersFirst=[...tasks].sort((a,b)=>Number(!!a.sharesWorkspaceOf)-Number(!!b.sharesWorkspaceOf));for(let task of ownersFirst){if(!task.worktreePath)continue;if(isRemoteRepoKey(task.repo)||isRemoteRepoKey(task.worktreePath))continue;if(map.has(task.worktreePath))continue;map.set(task.worktreePath,task.vendor??defaultVendor)}return map}class TranscriptActivityCollector{orch;bus;options;entries=new Map;stopped=!1;constructor(orch,bus,options){this.orch=orch;this.bus=bus;this.options=options}tick(){if(this.stopped)return;if(this.options.hasSubscribers&&!this.options.hasSubscribers())return;try{let tracked=trackedWorktrees(this.orch.listTasks(),this.options.defaultVendor),pruned=!1;for(let path of this.entries.keys()){if(tracked.has(path))continue;if(this.entries.get(path)?.value)pruned=!0;this.entries.delete(path)}if(pruned)this.publish();for(let[path,vendor]of tracked)this.maybeCollect(path,vendor)}catch(err){logDaemonError("transcript-activity",err)}}stop(){this.stopped=!0}maybeCollect(worktreePath,vendor){let entry=this.entries.get(worktreePath);if(!entry)entry={inFlight:!1,nextAllowedAt:0,vendor,detector:this.createDetector(vendor)},this.entries.set(worktreePath,entry);else if(entry.vendor!==vendor)entry.vendor=vendor,entry.detector=this.createDetector(vendor);let cadence=this.options.cadence??{timeoutMs:TRANSCRIPT_ACTIVITY_TIMEOUT_MS,slowRetryMs:TRANSCRIPT_ACTIVITY_SLOW_RETRY_MS,minIntervalMs:TRANSCRIPT_ACTIVITY_MIN_INTERVAL_MS},run=this.options.run??runTranscriptActivity,current=entry;maybeStartScheduledRun(current,cadence,(signal)=>run(worktreePath,current.vendor,current.detector,signal),(value)=>{if(this.stopped)return;if(this.entries.get(worktreePath)!==current)return;if(current.value&&sameTranscriptActivityEntry(current.value,value))return;current.value=value,this.publish()})}publish(){let activity={};for(let[path,entry]of this.entries)if(entry.value)activity[path]=entry.value;this.bus.publish("transcript.activity",{activity})}createDetector(vendor){return this.options.createDetector?.(vendor)??{latestActivity:async()=>({marker:null,mtimeMs:0}),latestActivityInFile:async()=>null,supportsCompletionMarkers:()=>!1}}}function startTranscriptActivityCollector(orch,runtime,bus,tickMs=DEFAULT_TRANSCRIPT_ACTIVITY_TICK_MS,hasSubscribers){let collector=new TranscriptActivityCollector(orch,bus,{hasSubscribers,createDetector:runtime.createEngineTurnDetector,defaultVendor:runtime.defaultTaskVendor,run:async(path,vendor,detector,signal)=>{let{marker,mtimeMs}=await detector.latestActivity(path);return{mtimeMs:detector.supportsCompletionMarkers()?mtimeMs:await runtime.latestTranscriptMtime(vendor,path),completionId:marker?.id??null,completionAt:marker?.timestampMs??0}}});return startTicker({name:"transcript-activity-collector",tickMs,immediate:!0,run:()=>collector.tick(),onStop:()=>collector.stop()})}import{readFileSync as readFileSync2}from"fs";import{basename as basename2}from"path";var DEFAULT_UI_PREFS_DEBOUNCE_MS=200,FOCUS_ACCENT_SLOT_NAMES=["primary","success","info"],THEME_MODE_NAMES=["dark","light","auto"];function readUiPrefsFromStateFile(statePath){let parsed={};try{let raw=JSON.parse(readFileSync2(statePath,"utf8"));if(raw&&typeof raw==="object"&&!Array.isArray(raw))parsed=raw}catch{}let theme=typeof parsed.activeTheme==="string"&&parsed.activeTheme.length>0?parsed.activeTheme:null,themeMode=typeof parsed.themeMode==="string"&&THEME_MODE_NAMES.includes(parsed.themeMode)?parsed.themeMode:null,transparentBackground=parsed.transparentBackground!==!1,focusAccent=typeof parsed.focusAccent==="string"&&FOCUS_ACCENT_SLOT_NAMES.includes(parsed.focusAccent)?parsed.focusAccent:null,sortMode=parsed.activeSortMode==="recent"||parsed.activeSortMode==="attention"||parsed.activeSortMode==="name"?parsed.activeSortMode:"default",keysCollapsed=parsed["tasksPane.keysCollapsed"]===!0,projectFilter=typeof parsed["tasksPane.projectFilter"]==="string"&&parsed["tasksPane.projectFilter"].length>0?parsed["tasksPane.projectFilter"]:null,locale=typeof parsed.locale==="string"&&parsed.locale.length>0?parsed.locale:"en";return{theme,themeMode,transparentBackground,focusAccent,locale,sortMode,keysCollapsed,projectFilter}}function samePrefs(a,b){return a.theme===b.theme&&a.themeMode===b.themeMode&&a.transparentBackground===b.transparentBackground&&a.focusAccent===b.focusAccent&&a.locale===b.locale&&a.sortMode===b.sortMode&&a.keysCollapsed===b.keysCollapsed&&a.projectFilter===b.projectFilter}function startUiPrefsWatcher(bus,options={}){let debounceMs=options.debounceMs??DEFAULT_UI_PREFS_DEBOUNCE_MS;if(debounceMs<=0)return()=>{};let statePath=options.statePath??defaultUiPrefsStatePath(),stateFile=basename2(statePath),last=null,publishIfChanged=()=>{try{let next=readUiPrefsFromStateFile(statePath);if(last&&samePrefs(last,next))return;last=next,bus.publish("ui-prefs",next)}catch(err){logDaemonError("ui-prefs-watcher",err)}},stop=startFileWatchTrigger({filePath:statePath,matchBasenames:[stateFile],debounceMs,onTrigger:publishIfChanged,onError:(err)=>logDaemonError("ui-prefs-watcher",err)});return publishIfChanged(),stop}import{stat as stat2}from"fs/promises";import{dirname}from"path";var DEFAULT_VANISHED_PROJECTS_TICK_MS=30000,PROBE_CADENCE={timeoutMs:2000,slowRetryMs:600000,minIntervalMs:DEFAULT_VANISHED_PROJECTS_TICK_MS},MAX_IN_FLIGHT=2;async function isDirectory(path){return(await stat2(path).catch(()=>null))?.isDirectory()===!0}async function checkoutVanished(path){if(await isDirectory(path))return!1;return isDirectory(dirname(path))}function createVanishedProjectsSweep(orch,probe=checkoutVanished){let states=new Map,inFlight=()=>[...states.values()].filter((s)=>s.inFlight).length;return()=>{let listed=new Set;for(let task of orch.listTasks()){if(task.kind!=="main"||task.repo.startsWith("ssh://"))continue;let path=task.worktreePath||task.repo;if(listed.add(path),inFlight()>=MAX_IN_FLIGHT)continue;let state=states.get(path)??{inFlight:!1,nextAllowedAt:0};states.set(path,state);let repo=task.repo;maybeStartScheduledRun(state,PROBE_CADENCE,()=>probe(path),(gone)=>{if(!gone)return;orch.forgetProject(repo).then(()=>logDaemonInfo("vanished-projects",`forgot ${repo}: its checkout is gone`)).catch((err)=>logDaemonError("vanished-projects",err))})}for(let[path,state]of states)if(!listed.has(path)&&!state.inFlight)states.delete(path)}}function startVanishedProjectsSweeper(orch,tickMs=DEFAULT_VANISHED_PROJECTS_TICK_MS){return startTicker({name:"vanished-projects",tickMs,immediate:!0,run:createVanishedProjectsSweep(orch)})}import{spawn as spawn4}from"child_process";function runGit(worktreePath,args,signal){return new Promise((resolve)=>{let stdout="",settled=!1,finish=(status)=>{if(settled)return;settled=!0,resolve(status===0?stdout:null)},child=spawn4("git",args.slice(),{cwd:worktreePath,stdio:["ignore","pipe","ignore"],env:{...process.env,GIT_OPTIONAL_LOCKS:"0"},signal,killSignal:"SIGKILL"});child.stdout?.on("data",(chunk)=>{stdout+=String(chunk)}),child.on("error",()=>finish(null)),child.on("close",finish)})}async function countDrift(worktreePath,baseRef,signal){return parseAheadBehind(await runGit(worktreePath,["rev-list","--left-right","--count",`${baseRef}...HEAD`],signal))}function parseAheadBehind(stdout){if(stdout===null)return null;let parts=stdout.trim().split(/\s+/);if(parts.length!==2)return null;let behind=Number.parseInt(parts[0]??"",10),ahead=Number.parseInt(parts[1]??"",10);if(!Number.isInteger(behind)||behind<0||!Number.isInteger(ahead)||ahead<0)return null;return{behind,ahead}}function countPorcelain(stdout){let added=0,deleted=0;for(let row of parsePorcelainRows(stdout))if(row.x==="D"||row.y==="D")deleted++;else added++;return{added,deleted}}async function runGitStatus(worktreePath,signal,baseRef){let stdout=await runGit(worktreePath,["status","--porcelain=v1"],signal);if(stdout===null)throw Error("git status failed");let counts=countPorcelain(stdout);if(!baseRef)return counts;let drift=await countDrift(worktreePath,baseRef,signal);return drift===null?counts:{...counts,...drift}}var EMPTY_PATHS=new Set;function isRemoteRepoKey2(value){return value.startsWith("ssh://")}function sameWorktreeChanges(a,b){return a.added===b.added&&a.deleted===b.deleted&&a.behind===b.behind&&a.ahead===b.ahead}var DEFAULT_WORKTREE_CHANGES_TICK_MS=2000,WORKTREE_CHANGES_CONCURRENCY=4,WORKTREE_CHANGES_TIMEOUT_MS=4000,WORKTREE_CHANGES_SLOW_RETRY_MS=60000,WORKTREE_CHANGES_MIN_INTERVAL_MS=1500,WORKTREE_CHANGES_QUIET_INTERVAL_MS=60000;function trackedWorktreePaths(tasks){let paths=new Map;for(let task of tasks)for(let repo of[task,...task.extraRepos??[]]){if(!repo.worktreePath)continue;if(isRemoteRepoKey2(repo.repo)||isRemoteRepoKey2(repo.worktreePath))continue;if(paths.get(repo.worktreePath)===void 0)paths.set(repo.worktreePath,repo.baseRef)}return paths}var UNREADABLE=Symbol("worktree-changes-unreadable");class WorktreeChangesCollector{orch;bus;options;entries=new Map;stopped=!1;queued=new Map;active=0;activePaths=new Set;drainHandle;publishTimer;controllers=new Set;constructor(orch,bus,options={}){this.orch=orch;this.bus=bus;this.options=options}tick(){if(this.stopped)return;if(this.options.hasSubscribers&&!this.options.hasSubscribers())return;try{let tasks=this.orch.listTasks(),tracked=trackedWorktreePaths(tasks),pruned=!1;for(let path of this.entries.keys()){if(tracked.has(path))continue;if(this.entries.get(path)?.value)pruned=!0;this.entries.delete(path),this.queued.delete(path)}for(let path of this.queued.keys())if(!tracked.has(path))this.queued.delete(path);if(pruned)this.publish();let busy=this.busyPaths(tasks);for(let[path,baseRef]of tracked)if(!this.entries.get(path)?.inFlight)this.queued.set(path,{baseRef,busy:busy.has(path)});this.drain()}catch(err){logDaemonError("worktree-changes",err)}}stop(){if(this.stopped=!0,this.queued.clear(),this.drainHandle)clearImmediate(this.drainHandle);if(this.publishTimer)clearTimeout(this.publishTimer);for(let controller of this.controllers)controller.abort()}drain(){if(this.stopped||this.options.hasSubscribers?.()===!1)return;let limit=WORKTREE_CHANGES_CONCURRENCY;for(let[path,demand]of this.queued){if(this.active>=limit)break;if(this.activePaths.has(path))continue;this.queued.delete(path);try{this.maybeCollect(path,demand.baseRef,demand.busy)}catch(err){logDaemonError("worktree-changes",err)}}}runFinished(path){if(this.active--,this.activePaths.delete(path),this.stopped||this.drainHandle)return;this.drainHandle=setImmediate(()=>{this.drainHandle=void 0,this.drain()})}busyPaths(tasks){let ids=this.options.activeTaskIds?.();if(!ids)return EMPTY_PATHS;let active=new Set(ids);if(active.size===0)return EMPTY_PATHS;let paths=new Set;for(let task of tasks){if(!active.has(task.id))continue;for(let repo of[task,...task.extraRepos??[]])if(repo.worktreePath)paths.add(repo.worktreePath)}return paths}maybeCollect(worktreePath,baseRef,busy=!1){let entry=this.entries.get(worktreePath);if(!entry)entry={inFlight:!1,nextAllowedAt:0},this.entries.set(worktreePath,entry);let now=Date.now(),probe=(this.options.probe??worktreeFingerprint)(worktreePath,baseRef),quietUntil=entry.quietUntil??0;if(!busy&&probe!==null&&probe===entry.probe&&now<quietUntil)return;let quietIntervalMs=this.options.quietIntervalMs??WORKTREE_CHANGES_QUIET_INTERVAL_MS,cadence=this.options.cadence??{timeoutMs:WORKTREE_CHANGES_TIMEOUT_MS,slowRetryMs:WORKTREE_CHANGES_SLOW_RETRY_MS,minIntervalMs:WORKTREE_CHANGES_MIN_INTERVAL_MS},run=this.options.run??runGitStatus;maybeStartScheduledRun(entry,cadence,(signal)=>{entry.probe=probe,entry.quietUntil=Date.now()+quietIntervalMs,this.active++,this.activePaths.add(worktreePath);let controller=new AbortController;this.controllers.add(controller);let abort=()=>controller.abort();return signal.addEventListener("abort",abort,{once:!0}),(async()=>{try{return await run(worktreePath,controller.signal,baseRef)}catch{return UNREADABLE}finally{signal.removeEventListener("abort",abort),this.controllers.delete(controller),this.runFinished(worktreePath)}})()},(value)=>{if(this.stopped)return;if(this.entries.get(worktreePath)!==entry)return;if(value===UNREADABLE&&entry.value!==void 0&&entry.value!==UNREADABLE)return;if(entry.value===value)return;if(entry.value&&entry.value!==UNREADABLE&&value!==UNREADABLE&&sameWorktreeChanges(entry.value,value))return;entry.value=value,this.publish()})}publish(){if(this.publishTimer||this.stopped)return;this.publishTimer=setTimeout(()=>{if(this.publishTimer=void 0,!this.stopped)this.publishNow()},this.options.publishDelayMs??10)}publishNow(){let changes={},unreadable=[];for(let[path,entry]of this.entries)if(entry.value===UNREADABLE)unreadable.push(path);else if(entry.value)changes[path]=entry.value;this.bus.publish("worktree.changes",unreadable.length>0?{changes,unreadable}:{changes})}}function startWorktreeChangesCollector(orch,runtime,bus,tickMs=DEFAULT_WORKTREE_CHANGES_TICK_MS,hasSubscribers,activeTaskIds){let collector=new WorktreeChangesCollector(orch,bus,{hasSubscribers,run:runtime.runWorktreeStatus,...activeTaskIds?{activeTaskIds}:{}});return startTicker({name:"worktree-changes-collector",tickMs,immediate:!0,run:()=>collector.tick(),onStop:()=>collector.stop()})}var DEFAULT_UPDATE_POLL_MS=21600000;function createProtocolUpgradeReporter(orch,runtime){return(taskId,tabId,evidence)=>{if(tabId!=="tab-1")return;let task=orch.getTask(taskId);if(!task)return;let upgrade=runtime.resolveProtocolUpgrade?.(task,evidence);if(!upgrade)return;return orch.setCommand(taskId,upgrade.command,upgrade.vendor).then(()=>logDaemonInfo("protocol-sniff",`upgraded task ${taskId} to the ${upgrade.vendor} protocol from its live session`)).catch((err)=>logDaemonError("protocol-sniff",err))}}var MACHINE_HUB_GATE_MS=1000,MACHINE_HUB_IDLE_MS=15000;function gateMachineHub(start,bus,hasSubscribersFor){let stop=null,idleSince=null,tick=()=>{try{if(hasSubscribersFor("machines"))idleSince=null,stop??=start(bus);else if(stop){if(idleSince??=Date.now(),Date.now()-idleSince>=MACHINE_HUB_IDLE_MS)stop(),stop=null}}catch(err){logDaemonError("machine-hub",err)}};tick();let timer=setInterval(tick,MACHINE_HUB_GATE_MS);return timer.unref?.(),()=>{clearInterval(timer),stop?.()}}function startDaemonCollectors(orch,runtime,bus,hasSubscribersFor,options,quotaUsage,automations,activity,inbox){let ownerOf=options.ownerOf??((taskId,tabId)=>resolvePtyOwner(orch.listTasks(),taskId,tabId)),receiveStatus=activity?programStatusActivity(activity,(id)=>!!orch.getTask(id),inbox,automations?.deliveryDeps,ownerOf):void 0,stopStatusWatch=receiveStatus?watchProgramStatus(receiveStatus,{homeDir:options.homeDir}):async()=>{},stopActivityObserver=activity?startActivityObserver(activity,{...createActivityObserverIo(options.homeDir,runtime,activity,ownerOf),onEngineEvidence:createProtocolUpgradeReporter(orch,runtime),onProgramStatusEvent:receiveStatus},()=>hasSubscribersFor("engine-state"),{ownerOf}):()=>{},checkUpdate=options.checkUpdate??runtime.checkLatestVersion,updatePollMs=options.updatePollMs??DEFAULT_UPDATE_POLL_MS,pollUpdate=()=>{checkUpdate().then((info)=>bus.publish("update",{info})).catch((err)=>logDaemonError("update-poller",err))},updateTimer=null;if(updatePollMs>0)pollUpdate(),updateTimer=setInterval(pollUpdate,updatePollMs),updateTimer.unref?.();let stopAutoTitlePoller=startAutoTitlePoller(orch,runtime,options.autoTitlePollMs??DEFAULT_AUTO_TITLE_POLL_MS,()=>hasSubscribersFor("task.snapshot"),options.conversationOf),stopUiPrefsWatcher=startUiPrefsWatcher(bus,{statePath:defaultUiPrefsStatePath(options.homeDir),debounceMs:options.uiPrefsDebounceMs??DEFAULT_UI_PREFS_DEBOUNCE_MS}),stopStateWatcher=startStateWatcher(bus,defaultUiPrefsStatePath(options.homeDir),options.uiPrefsDebounceMs??DEFAULT_STATE_DEBOUNCE_MS),stopMachineHub=runtime.startMachineHub?gateMachineHub(runtime.startMachineHub,bus,hasSubscribersFor):()=>{},stopKeybindingsWatcher=startKeybindingsWatcher(bus,{path:defaultKeybindingsPath(options.homeDir),debounceMs:options.keybindingsDebounceMs??DEFAULT_KEYBINDINGS_DEBOUNCE_MS}),stopWorktreeChangesCollector=startWorktreeChangesCollector(orch,runtime,bus,options.worktreeChangesTickMs??DEFAULT_WORKTREE_CHANGES_TICK_MS,()=>hasSubscribersFor("worktree.changes"),activity?()=>activity.workingTaskIds():void 0),stopTranscriptActivityCollector=startTranscriptActivityCollector(orch,runtime,bus,options.transcriptActivityTickMs??DEFAULT_TRANSCRIPT_ACTIVITY_TICK_MS,()=>hasSubscribersFor("transcript.activity")),stopContextUsageCollector=activity?startContextUsageCollector(activity,orch,bus,runtime,options.contextUsageTickMs??DEFAULT_CONTEXT_USAGE_TICK_MS,()=>hasSubscribersFor("usage.context")):()=>{},stopPrStatusPoller=startPrStatusPoller(orch,runtime,options.prStatusPollMs??DEFAULT_PR_STATUS_POLL_MS,()=>hasSubscribersFor("task.snapshot"),void 0,()=>needsPrPoll(orch.listTasks())||(activity?.workingTaskIds().length??0)>0,void 0,makePrRefreshReader()),stopQuotaResumeRunner=startQuotaResumeRunner(orch,runtime,options.quotaResumeTickMs??DEFAULT_QUOTA_RESUME_TICK_MS,void 0,automations?.plugins,automations?.runnability,automations?.deliveryDeps.deliveries.claims),invokeApi=runtime.invokeApi?.bind(runtime),socketPath=automations?.socketPath,stopScheduledStartRunner=automations?startScheduledStartRunner({orch,runtime,link:automations.link,...automations.pendingStarts?{pending:automations.pendingStarts}:{},...invokeApi&&socketPath?{invoke:(verb,params)=>invokeApi(verb,params,socketPath)}:{}},options.scheduledStartTickMs??DEFAULT_SCHEDULED_START_TICK_MS):async()=>{},stopAutoFixRunner=activity&&options.autoFixTickMs!==0?startAutoFixRunner({orch,runtime,activity,inbox},options.autoFixTickMs??DEFAULT_AUTO_FIX_TICK_MS):()=>{},stopVanishedProjects=startVanishedProjectsSweeper(orch),stopAutomationRunner=automations?startAutomationRunner({store:automations.store,deliveries:automations.deliveryDeps.deliveries,orch,runtime,link:automations.link,...automations.plugins?{plugins:automations.plugins}:{},...automations.inbox?{inbox:automations.inbox}:{},...automations.gates?{gates:automations.gates}:{},...automations.runnability?{runnability:automations.runnability}:{},...automations.dispatches?{dispatches:automations.dispatches}:{}},options.automationTickMs??DEFAULT_AUTOMATION_TICK_MS):()=>{},deliverySweepBootedAt=(automations?.deliveryDeps.now??Date.now)(),stopDeliverySweep=automations&&activity?startTicker({name:"delivery-sweep",tickMs:options.automationTickMs??DEFAULT_AUTOMATION_TICK_MS,run:()=>sweepStalledDeliveries(automations.deliveryDeps,activity,deliverySweepBootedAt)}):()=>{},stopQuotaUsagePoller=quotaUsage?startQuotaUsagePoller(quotaUsage,()=>runtime.vendorsWithQuotaProbe(),()=>hasSubscribersFor("usage.snapshot"),options.quotaUsageTickMs):()=>{};return async()=>{if(updateTimer)clearInterval(updateTimer);await Promise.allSettled([stopActivityObserver,stopStatusWatch,stopAutoTitlePoller,stopPrStatusPoller,stopQuotaResumeRunner,stopScheduledStartRunner,stopAutoFixRunner,stopAutomationRunner,stopDeliverySweep,stopQuotaUsagePoller,stopUiPrefsWatcher,stopStateWatcher,stopVanishedProjects,stopMachineHub,stopKeybindingsWatcher,stopWorktreeChangesCollector,stopTranscriptActivityCollector,stopContextUsageCollector].map(async(stop)=>stop()))}}import{hostname}from"os";var AGENT_TURN_HANDLERS=[{name:"agentTurn.list",handle(payload,ctx){let taskId=optionalString(payload,"taskId"),repo=optionalString(payload,"repoRoot"),since=optionalNumber(payload,"since"),limit=optionalNumber(payload,"limit");return{turns:ctx.agentTurns?.list({...taskId?{taskId}:{},...repo?{repo}:{},...since!==void 0?{since}:{},...limit!==void 0?{limit}:{}})??[]}}}];function refusal(code,message){return{apiVersion:ROVE_API_VERSION,ok:!1,error:{code,message}}}function isParamValue(value){if(typeof value==="string"||typeof value==="boolean")return!0;if(typeof value==="number")return Number.isFinite(value);return Array.isArray(value)&&value.every((v)=>typeof v==="string")}var invoking=0;function invokingVerbs(){return invoking}var API_HANDLERS=[{name:"api.invoke",blocking:!0,async handle(payload,ctx){let verb=requireString(payload,"verb"),raw=payload.params??{};if(typeof raw!=="object"||raw===null||Array.isArray(raw))return refusal("BAD_FLAG","params must be an object keyed by flag name");let params=raw,bad=Object.entries(params).find(([,value])=>!isParamValue(value));if(bad)return refusal("BAD_FLAG",`param ${bad[0]} must be a string, number, boolean or string list`);if(!ctx.runtime.invokeApi)return refusal("RPC_ERROR","this daemon cannot run verbs");invoking++;try{return await ctx.runtime.invokeApi(verb,params,ctx.daemon.socketPath,{machine:optionalString(payload,"machine"),forwarded:optionalBoolean(payload,"forwarded"),from:optionalString(payload,"from")})}finally{invoking--}}}];var ATTENTION_HANDLERS=[{name:"attention.dismissRoutine",async handle(payload,ctx){return await ctx.inbox.deleteRoutineEpisode(requireString(payload,"automationId")),{deleted:!0}}},{name:"attention.dismiss",async handle(payload,ctx){let deliveryId=optionalString(payload,"deliveryId");if(deliveryId&&payload.taskId===void 0&&!ctx.deliveries.get(deliveryId))return{deleted:!1,found:!1};let taskId=deliveryId?optionalString(payload,"taskId")??ctx.deliveries.get(deliveryId)?.taskId:requireString(payload,"taskId"),tabId=optionalString(payload,"tabId")??null,at=payload.at===void 0?void 0:requireNumber(payload,"at"),deleted=deliveryId?await ctx.inbox.deleteDeliveryEpisode(deliveryId):await ctx.inbox.deleteEpisode(taskId,tabId,at);if(deliveryId)await ctx.deliveries.dismiss(deliveryId);if(deleted)ctx.plugins?.handleUiReport({kind:"attention.handled",taskId,detail:{how:"dismissed",...tabId?{tabId}:{}}});return{deleted}}},{name:"attention.list",handle(_payload,ctx){return{items:ctx.inbox.snapshot()}}},{name:"attention.read",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=optionalString(payload,"tabId")??null,at=requireNumber(payload,"at"),updated=await ctx.inbox.markRead(taskId,tabId,at);if(updated)ctx.plugins?.handleUiReport({kind:"attention.handled",taskId,detail:{how:"read",...tabId?{tabId}:{}}});return{updated}}},{name:"task.rowToken",handle(payload,ctx){if(!ctx.rowTokens)return{ok:!1,reason:"UNSUPPORTED"};let taskId=requireString(payload,"taskId"),source=optionalString(payload,"source")??"cli",key=optionalString(payload,"key")??"default";if(optionalBoolean(payload,"clear")===!0)return{ok:!0,cleared:ctx.rowTokens.clear(taskId,source,optionalString(payload,"key"))};let tone=payload.tone;return{ok:!0,token:ctx.rowTokens.set({taskId,source,key,text:requireString(payload,"text"),...isRowTokenTone(tone)?{tone}:{},...optionalNumber(payload,"ttlMs")!==void 0?{ttlMs:optionalNumber(payload,"ttlMs")}:{}})}}}];function queueOf(ctx){if(!ctx.promptQueue)throw Error("this daemon has no prompt queue");return ctx.promptQueue}function awaitingMenu(ctx,taskId,tabId){if(ctx.rowStatus?.list().tasks[taskId]?.tabs[tabId]?.kind==="needs-input")return!0;return ctx.promptQueue?.restUnconfirmed(taskId,tabId,ctx.rowStatus?.answeredAt(taskId,tabId))===!0}function heldBack(ctx,item){let state=ctx.activity.stateOf(item.taskId,item.tabId);if(state==="permission_needed"||awaitingMenu(ctx,item.taskId,item.tabId))return"awaiting-permission";if(state==="running"||state==="rate_limited")return"busy";return null}async function pasteQueued(ctx,item){let task=ctx.orch.getTask(item.taskId);if(!task||task.deletion||!task.worktreePath)return"task is gone";let blocked=heldBack(ctx,item);if(blocked)return blocked;let deliveryId=null;try{if(item.expectReport||task.requireReport===!0)deliveryId=(await ctx.deliveries.arm({taskId:task.id,tabId:item.tabId,source:"send",promptHead:item.text})).id;let text2=deliveryId?`${item.text}
19
19
 
20
20
  ${deliveryFooter(deliveryId,ctx.runtime.roveApiInvocation())}`:item.text,result=await ctx.runtime.deliverPromptToLiveEngineTabDetailed({id:task.id,vendor:task.vendor,command:task.command,worktreePath:task.worktreePath,scope:ptyScopeFor(ctx.orch.listTasks(),task.id),tabId:item.tabId},text2);if(result.outcome!=="delivered"){if(deliveryId)await ctx.deliveries.cancel(deliveryId);return result.outcome}if(deliveryId)await ctx.deliveries.setTab(deliveryId,result.tabId);return null}catch(err){if(logDaemonError("queue-handover",err),deliveryId)await ctx.deliveries.cancel(deliveryId).catch(()=>{});return err instanceof Error?err.message:String(err)}}var QUEUE_HANDLERS=[{name:"queue.add",handle(payload,ctx){let taskId=requireString(payload,"taskId"),task=ctx.orch.getTask(taskId);if(!task||task.deletion)throw Error(`task not found: ${taskId}`);return queueOf(ctx).add({taskId,tabId:requireString(payload,"tabId"),text:requireString(payload,"text"),expectReport:optionalBoolean(payload,"expectReport")===!0})}},{name:"queue.list",handle(payload,ctx){let queue=queueOf(ctx);for(let item of queue.list())if(!ctx.orch.getTask(item.taskId))queue.cancel(item.id);return{items:queue.list(optionalString(payload,"taskId"))}}},{name:"queue.edit",handle(payload,ctx){let text2=requireString(payload,"text");if(text2.trim().length===0)throw Error("text is empty; take the prompt back with queue.cancel instead");return queueOf(ctx).edit(requireString(payload,"id"),text2)}},{name:"queue.cancel",handle(payload,ctx){return{cancelled:queueOf(ctx).cancel(requireString(payload,"id"))}}},{name:"send.check",handle(payload,ctx){let taskId=requireString(payload,"taskId"),named=optionalString(payload,"tabId"),tabs=named?[named]:[...new Set([...Object.keys(ctx.rowStatus?.list().tasks[taskId]?.tabs??{}),...ctx.promptQueue?.tabsOf(taskId)??[]])];return{awaiting:tabs.filter((tab)=>awaitingMenu(ctx,taskId,tab)),settleMs:Math.max(0,...tabs.map((tab)=>ctx.promptQueue?.settleLeft(taskId,tab)??0))}}}];function displayTaskTitle(task){return task.title||task.branch||task.worktreePath||task.repo||"scratch"}function serializeTask(task){let repoId=repoIdOf(task.repo);return{id:task.id,title:displayTaskTitle(task),repo:task.repo,branch:task.branch,worktreePath:task.worktreePath,kind:task.kind??"task",...task.scratch?{scratch:!0}:{},...task.noProject?{noProject:!0}:{},...task.routine?{routine:task.routine}:{},status:task.status,pinned:task.pinned??!1,...task.kept?{kept:!0}:{},...task.notes?{notes:task.notes}:{},...task.todos?{todos:task.todos}:{},...task.archived?{archived:!0}:{},vendor:task.vendor,command:task.command,prStatus:task.prStatus,modelEffort:task.modelEffort,model:task.model,tier:task.tier,groupId:task.groupId,observedLanguage:task.observedLanguage,deletion:task.deletion,quotaResume:task.quotaResume,scheduledStart:task.scheduledStart,...task.autoFixCi?{autoFixCi:task.autoFixCi}:{},linkedWorkItem:task.linkedWorkItem,dispatcher:task.dispatcher,...task.parentTaskId?{parentTaskId:task.parentTaskId}:{},...task.sharesWorkspaceOf?{sharesWorkspaceOf:task.sharesWorkspaceOf}:{},...task.cwdSubpath?{cwdSubpath:task.cwdSubpath}:{},...task.ptyAlias?{ptyAlias:task.ptyAlias}:{},...task.extraRepos?.length?{extraRepos:task.extraRepos}:{},...task.workspace?{workspace:task.workspace}:{},...task.sessionPrs?.length?{sessionPrs:task.sessionPrs}:{},requireReport:task.requireReport,...task.worktreeOnly?{worktreeOnly:!0}:{},prompt:task.prompt,baseRef:task.baseRef,worktreeName:task.worktreeName,...task.gitRepo?{gitRepo:task.gitRepo}:{},report:task.report,...repoId?{repoId}:{},createdAt:task.createdAt,updatedAt:task.updatedAt}}function deliveryDepsOf(ctx){return{deliveries:ctx.deliveries,inbox:ctx.inbox,orch:ctx.orch,automations:ctx.automations,stopEngineTab:(taskId,tabId)=>ctx.runtime.stopTaskEngineTab(taskId,tabId,ptyScopeFor(ctx.orch.listTasks(),taskId))}}function evidenceOf(payload){let raw=payload.evidence;if(raw===void 0)return;if(!Array.isArray(raw)||raw.some((item)=>typeof item!=="string"))throw Error("evidence must be an array of strings");return raw}function reportInputOf(payload){let next=optionalString(payload,"next"),evidence=evidenceOf(payload);return{outcome:requireString(payload,"outcome"),summary:requireString(payload,"summary"),...evidence?{evidence}:{},...next?{next}:{}}}async function tellDispatcher(ctx,delivery){if(delivery.source!=="send"||!delivery.report)return;let worker=ctx.orch.getTask(delivery.taskId),to=worker?.dispatcher;if(!worker||!to||to.taskId===worker.id)return;let seat=ctx.orch.getTask(to.taskId);if(!seat||seat.deletion||!seat.worktreePath)return;if(ctx.activity.stateOf(to.taskId,to.tabId)==="permission_needed"||awaitingMenu(ctx,to.taskId,to.tabId))return;let{outcome,summary}=delivery.report,line=summary.split(`
21
21
  `).find((l)=>l.trim())??summary,branch=worker.branch?`, branch ${worker.branch}`:"",text2=`[ROVE REPORT] "${displayTaskTitle(worker)}" (task ${worker.id}${branch}) ${outcome}: ${line.length>280?`${line.slice(0,279)}\u2026`:line}`;await ctx.runtime.deliverPromptToLiveEngineTabDetailed({id:seat.id,tabId:to.tabId,vendor:seat.vendor,command:seat.command,worktreePath:seat.worktreePath,scope:ptyScopeFor(ctx.orch.listTasks(),seat.id)},text2).catch((err)=>logDaemonError("delivery-report-notify",err))}var DELIVERY_HANDLERS=[{name:"delivery.arm",async handle(payload,ctx){let taskId=requireString(payload,"taskId");if(!ctx.orch.getTask(taskId))throw Error(`task not found: ${taskId}`);return{deliveryId:(await ctx.deliveries.arm({taskId,tabId:optionalString(payload,"tabId")??null,source:"send",promptHead:requireString(payload,"promptHead")})).id}}},{name:"delivery.settle",async handle(payload,ctx){let deliveryId=requireString(payload,"deliveryId");if(payload.delivered!==!0)return{cancelled:await ctx.deliveries.cancel(deliveryId)};let tabId=optionalString(payload,"tabId");if(tabId)await ctx.deliveries.setTab(deliveryId,tabId);return{cancelled:!1}}},{name:"delivery.report",async handle(payload,ctx){let deliveryId=requireString(payload,"deliveryId"),delivery=await reportDelivery(deliveryDepsOf(ctx),deliveryId,reportInputOf(payload));if(delivery)await tellDispatcher(ctx,delivery);return{delivery}}},{name:"delivery.list",handle(payload,ctx){let taskId=requireString(payload,"taskId"),limit=optionalNumber(payload,"limit");if(limit!==void 0&&(!Number.isInteger(limit)||limit<1))throw Error("limit must be a positive integer");return{deliveries:ctx.deliveries.listForTask(taskId,Math.min(limit??MAX_DELIVERIES_PER_TASK,MAX_DELIVERIES_PER_TASK))}}}];function runnerDepsOf(ctx){return{store:ctx.automations,deliveries:ctx.deliveries,orch:ctx.orch,runtime:ctx.runtime,link:ctx.selfLink,...ctx.plugins?{plugins:()=>ctx.plugins??null}:{},inbox:ctx.inbox}}function requireSchedule(payload,key){let schedule=requireString(payload,key);if(!isValidCron(schedule))throw Error(`invalid cron expression: ${schedule}`);return schedule}function readPrecheck(payload,key="precheck"){if(!(key in payload))return;let raw=payload[key];if(raw===null)return null;if(!raw||typeof raw!=="object")throw Error(`${key} must be an object or null`);let command=requireString(raw,"command"),timeoutSeconds=optionalNumber(raw,"timeoutSeconds")??120;if(timeoutSeconds<=0)throw Error(`${key}.timeoutSeconds must be greater than zero`);return{command,timeoutSeconds}}function assertScriptOptions(value){if(!value.script){if(!value.prompt)throw Error("a routine needs a prompt, or a script to run instead of an engine");return}if(value.target||value.vendor||value.model||value.modelEffort||value.baseRef||value.persistentSession)throw Error("a script routine cannot set target, vendor, model, effort, baseRef or persistentSession")}function readGraceMinutes(payload){let value=optionalNumber(payload,"missedRunGraceMinutes");if(value!==void 0&&value<0)throw Error("missedRunGraceMinutes must be zero or more minutes");return value}var NO_PROJECT_BASE_REF="a routine with no project has no base branch; drop baseRef or give it a repo",FAILURE_LOOKBACK_RUNS=50,AUTOMATION_HANDLERS=[{name:"automation.list",async handle(_payload,ctx){let automations=ctx.automations.list(),lastRunStatus={},lastFailure={};for(let automation of automations){let recent=ctx.automations.runsFor(automation.id,FAILURE_LOOKBACK_RUNS);if(recent[0])lastRunStatus[automation.id]=recent[0].status;let failure=lastRoutineFailure(recent,ctx.deliveries);if(failure)lastFailure[automation.id]=failure}return{automations,lastRunStatus,lastFailure,keepsDaemonAlive:ctx.automations.hasEnabled()}}},{name:"automation.create",async handle(payload,ctx){let precheck=readPrecheck(payload),repo=optionalString(payload,"repo"),baseRef=optionalString(payload,"baseRef"),target="target"in payload?readAutomationTarget(payload.target):void 0;if(!repo&&baseRef)throw Error(NO_PROJECT_BASE_REF);if(repo&&!target)await assertRoutineRepo(repo);if(repo&&baseRef)await assertRoutineBaseRef(repo,baseRef);let model=optionalString(payload,"model"),modelEffort=optionalString(payload,"effort"),targetOptions={target:target??void 0,vendor:optionalVendor(payload,"vendor"),model,modelEffort,baseRef,persistentSession:optionalBoolean(payload,"persistentSession"),newConversation:optionalBoolean(payload,"newConversation")};assertAutomationTargetOptions(targetOptions);let script=readPrecheck(payload,"script")??void 0,prompt=optionalString(payload,"prompt")??"";assertScriptOptions({...targetOptions,script,prompt}),await assertAutomationTargetTask({repo,target:target??void 0},ctx.orch);let automation=await ctx.automations.create({name:requireString(payload,"name"),...repo?{repo}:{},...target?{target}:{},prompt:script?"":prompt,...script?{script}:{},...optionalBoolean(payload,"notify")===!0?{notify:!0}:{},...optionalBoolean(payload,"webhook")===!0?{webhook:{secret:newWebhookSecret()}}:{},schedule:requireSchedule(payload,"schedule"),missedRunGraceMinutes:readGraceMinutes(payload)??60,...optionalVendor(payload,"vendor")?{vendor:optionalVendor(payload,"vendor")}:{},...model?{model}:{},...modelEffort?{modelEffort}:{},...precheck?{precheck}:{},...baseRef?{baseRef}:{},...optionalBoolean(payload,"persistentSession")===!0?{persistentSession:!0}:{},...optionalBoolean(payload,"newConversation")===!0?{newConversation:!0}:{},...optionalBoolean(payload,"enabled")!==void 0?{enabled:optionalBoolean(payload,"enabled")}:{}});if(!repo)await ensureRoutineCwd(automation).catch(async(error)=>{throw await ctx.automations.delete(automation.id),error});return ctx.daemon.reevaluateIdle(),{automation}}},{name:"automation.update",async handle(payload,ctx){let id=requireString(payload,"id"),nextBaseRef="baseRef"in payload?optionalString(payload,"baseRef"):void 0,currentRepo=ctx.automations.get(id)?.repo;if(nextBaseRef&&ctx.automations.get(id)&&!currentRepo)throw Error(NO_PROJECT_BASE_REF);if(nextBaseRef&&currentRepo)await assertRoutineBaseRef(currentRepo,nextBaseRef);let patch={...optionalString(payload,"name")!==void 0?{name:optionalString(payload,"name")}:{},...optionalString(payload,"prompt")!==void 0?{prompt:optionalString(payload,"prompt")}:{},...payload.vendor===null?{vendor:null}:optionalVendor(payload,"vendor")!==void 0?{vendor:optionalVendor(payload,"vendor")}:{},..."model"in payload?{model:optionalString(payload,"model")??null}:{},..."effort"in payload?{modelEffort:optionalString(payload,"effort")??null}:{},..."target"in payload?{target:readAutomationTarget(payload.target)}:{},..."schedule"in payload?{schedule:requireSchedule(payload,"schedule")}:{},...readPrecheck(payload)!==void 0?{precheck:readPrecheck(payload)}:{},...readPrecheck(payload,"script")!==void 0?{script:readPrecheck(payload,"script")}:{},...optionalBoolean(payload,"notify")!==void 0?{notify:optionalBoolean(payload,"notify")}:{},..."baseRef"in payload?{baseRef:optionalString(payload,"baseRef")??null}:{},...optionalBoolean(payload,"enabled")!==void 0?{enabled:optionalBoolean(payload,"enabled")}:{},...readGraceMinutes(payload)!==void 0?{missedRunGraceMinutes:readGraceMinutes(payload)}:{},...optionalBoolean(payload,"persistentSession")!==void 0?{persistentSession:optionalBoolean(payload,"persistentSession")}:{},...optionalBoolean(payload,"newConversation")!==void 0?{newConversation:optionalBoolean(payload,"newConversation")}:{}},current=ctx.automations.get(id);if(!current)throw Error(`automation not found: ${id}`);let webhook=optionalBoolean(payload,"webhook");if(webhook!==void 0)patch={...patch,webhook:webhook?current.webhook??{secret:newWebhookSecret()}:null};let targetOptions=mergeAutomationTargetOptions(current,patch);if(assertAutomationTargetOptions(targetOptions),assertScriptOptions({...targetOptions,script:patch.script===null?void 0:patch.script??current.script,prompt:patch.prompt??current.prompt}),patch.target)await assertAutomationTargetTask({repo:current.repo,target:patch.target},ctx.orch);let automation=await ctx.automations.update(id,patch);if(!automation)throw Error(`automation not found: ${id}`);ctx.daemon.reevaluateIdle();let released=current.sessionTaskId&&!automation.sessionTaskId?current.sessionTaskId:void 0;return{automation,...released?{releasedSessionTaskId:released}:{}}}},{name:"automation.delete",async handle(payload,ctx){let id=requireString(payload,"id"),deleted=await ctx.automations.delete(id);if(deleted)await ctx.inbox.deleteRoutineEpisode(id).catch(()=>{}),ctx.daemon.reevaluateIdle();return{deleted}}},{name:"automation.runs",async handle(payload,ctx){let automationId=requireString(payload,"id");if(!ctx.automations.get(automationId))throw Error(`automation not found: ${automationId}`);return{runs:ctx.automations.runsFor(automationId).map((run)=>withDeliveryReport(run,ctx.deliveries))}}},{name:"automation.respond",async handle(payload,ctx){let runId=requireString(payload,"runId"),text2=requireString(payload,"text");if(text2.length>ROUTINE_RESPONSE_MAX_CHARS)throw Error(`response is ${text2.length} characters; the cap is ${ROUTINE_RESPONSE_MAX_CHARS}`);let stored=ctx.automations.getRun(runId);if(!stored)return{run:null};if(stored.deliveryId&&ctx.deliveries.get(stored.deliveryId))return await reportDelivery(deliveryDepsOf(ctx),stored.deliveryId,{outcome:"done",summary:text2}),{run:withDeliveryReport(stored,ctx.deliveries)};return{run:await ctx.automations.setRunResponse(runId,text2)??null}}},{name:"automation.runNow",blocking:!0,async handle(payload,ctx){let id=requireString(payload,"id"),automation=ctx.automations.get(id);if(!automation)throw Error(`automation not found: ${id}`);return{status:await runAutomationOnce(runnerDepsOf(ctx),automation,{scheduledFor:Date.now(),trigger:"manual"})}}},{name:"automation.webhook",async handle(payload,ctx){let automation=ctx.automations.get(requireString(payload,"id"));if(!automation?.webhook)return{verdict:"not_found"};let body=typeof payload.body==="string"?payload.body:"";if(!webhookSignatureValid(automation.webhook.secret,body,optionalString(payload,"signature")))return{verdict:"bad_signature"};let name=optionalString(payload,"event");if(name==="ping")return{verdict:"pong"};if(!automation.enabled)return{verdict:"disabled"};let event=readWebhookEvent(name,body);return runAutomationOnce(runnerDepsOf(ctx),automation,{scheduledFor:Date.now(),trigger:"webhook",event}).catch((err)=>logDaemonError("automation-webhook",err)),{verdict:"fired",event:event.summary}}}];var ENGINE_BUSY={running:!0,permission_needed:!0},CHECKPOINT_HANDLERS=[{name:"task.checkpointList",async handle(payload,ctx){let taskId=requireString(payload,"taskId"),{ownerId}=ctx.orch.checkpointScope(taskId),checkpoints=await ctx.checkpoints.run(ownerId,()=>ctx.orch.listCheckpoints(taskId));return{workspaceTaskId:ownerId,checkpoints}}},{name:"task.checkpoint",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),tabId=optionalString(payload,"tabId"),{ownerId}=ctx.orch.checkpointScope(taskId),result=await ctx.checkpoints.run(ownerId,()=>ctx.orch.takeCheckpoint(taskId,tabId?{tabId}:void 0));return{workspaceTaskId:ownerId,...result}}},{name:"task.rewind",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),to=optionalNumber(payload,"to");if(to===void 0||!Number.isInteger(to)||to<1)throw Error("to must be a checkpoint number (>= 1)");let{ownerId,sharerIds}=ctx.orch.checkpointScope(taskId),busy=sharerIds.filter((id)=>ENGINE_BUSY[ctx.activity.stateOf(id,null)??"idle"]===!0);if(busy.length>0&&optionalBoolean(payload,"force")!==!0)throw Error(`TASK_BUSY: ${busy.length===1?"an engine is":`${busy.length} engines are`} mid-turn or waiting on you in ${busy.join(", ")}; rewinding rewrites files under ${busy.length===1?"it":"them"}. Pass force to rewind anyway.`);let result=await ctx.checkpoints.run(ownerId,()=>ctx.orch.rewindToCheckpoint(taskId,to));return{workspaceTaskId:ownerId,...result}}},{name:"task.exportBranch",blocking:!0,async handle(payload,ctx){let taskId=requireString(payload,"taskId"),{ownerId}=ctx.orch.checkpointScope(taskId);return{workspaceTaskId:ownerId,...await ctx.checkpoints.run(ownerId,()=>ctx.orch.exportBranch(taskId))}}}];function ledgerOf(ctx){if(!ctx.dispatches)throw Error("dispatch ledger unavailable");return ctx.dispatches}function senderOf(payload){let taskId=optionalString(payload,"fromTaskId");return taskId?{taskId,tabId:optionalString(payload,"fromTabId")??null}:null}var DISPATCH_HANDLERS=[{name:"dispatch.list",handle(_payload,ctx){return ledgerOf(ctx).list()}},{name:"dispatch.record",handle(payload,ctx){let taskId=requireString(payload,"taskId");if(typeof payload.delivered!=="boolean")throw Error("delivered must be a boolean");return{id:ledgerOf(ctx).record({kind:"send",from:senderOf(payload),to:{taskId,tabId:optionalString(payload,"tabId")??null},promptHead:requireString(payload,"promptHead").slice(0,DISPATCH_PROMPT_HEAD_CHARS*4),delivered:payload.delivered,...optionalString(payload,"reason")?{reason:optionalString(payload,"reason")}:{},...optionalString(payload,"deliveryId")?{deliveryId:optionalString(payload,"deliveryId")}:{}}).id}}}];async function ingestAgentTurns(store,runtime,orch,input){if(!input.transcriptPath)return{recorded:0,latest:void 0};let task=orch.getTask(input.taskId),vendor=input.vendor??task?.vendor;if(!vendor)return{recorded:0,latest:void 0};let turns=await runtime.readEngineTurns(vendor,input.transcriptPath);if(turns.length===0)return{recorded:0,latest:void 0};let records=turns.map((turn)=>({...turn,taskId:input.taskId,...input.tabId?{tabId:input.tabId}:{},vendor,...task?.repo?{repo:task.repo}:{}})),recorded=await store.record(records),last=records[records.length-1],latest=last?{id:last.id,model:last.model,usage:last.usage,startedAt:last.startedAt,endedAt:last.endedAt}:void 0;return{recorded,latest}}function ingestAgentTurnsBestEffort(store,runtime,orch,input,onDone){if(!store){onDone?.(void 0);return}ingestAgentTurns(store,runtime,orch,input).then(({latest})=>onDone?.(latest)).catch((err)=>{logDaemonError("agent-turns-ingest",err),onDone?.(void 0)})}async function markCompacted(ctx,taskId,tabId){await ctx.automations.markSessionCompacted(taskId,tabId).catch((err)=>logDaemonError("automation-compacted",err))}var ENGINE_REPORT_HANDLER={name:"engine.reportEvent",async handle(payload,ctx){if(payload.source==="screen"){let tabId2=requireString(payload,"tabId"),taskId2=resolvePtyOwner(ctx.orch.listTasks(),requireString(payload,"taskId"),tabId2);if(typeof payload.blocked!=="boolean")throw Error("blocked must be a boolean");if(ctx.activity.reportScreen(taskId2,tabId2,payload.blocked))await ctx.inbox.record(taskId2,payload.blocked?"awaiting-input":"turn-start",void 0,tabId2);return{}}let kind=requireString(payload,"kind");if(!ctx.runtime.isEngineActivityKind(kind))throw Error(`BAD_EVENT_KIND: unknown engine event kind: ${kind}`);let tabId=optionalString(payload,"tabId"),rawId=optionalString(payload,"taskId"),explicitId=rawId?resolvePtyOwner(ctx.orch.listTasks(),rawId,tabId):void 0,cwd=optionalString(payload,"cwd"),taskId=explicitId??(cwd?matchTaskByCwd(ctx.orch.listTasks(),cwd):void 0);if(!taskId)return{};let detail=optionalActivityDetail(payload),sessionId=optionalString(payload,"sessionId"),transcriptPath=optionalString(payload,"transcriptPath"),vendor=optionalString(payload,"engine");if(explicitId&&tabId&&sessionId&&vendor){let row=ctx.tabs?.get(taskId).state?.tabs.find((t)=>t.id===tabId);if(row?.kind==="engine"&&(row.sessionId!==sessionId||row.spawned!==!0)){if(row.sessionId&&row.sessionId!==sessionId)await markCompacted(ctx,taskId,tabId);let owner=row.vendor??ctx.orch.getTask(taskId)?.vendor;if(ctx.runtime.sessionProtocol(vendor)===ctx.runtime.sessionProtocol(typeof owner==="string"?owner:void 0))ctx.tabs?.apply(taskId,[{op:"patch",id:tabId,set:{sessionId,spawned:!0}}])}}let session=sessionId?{id:sessionId,transcriptPath}:void 0;if(ctx.runtime.affectsActivityState(kind)){if(ctx.activity.report(taskId,kind,detail,tabId,session,vendor),explicitId){if(!await trackDeliveryTurn(deliveryDepsOf(ctx),taskId,tabId??null,kind,detail))await ctx.inbox.record(taskId,kind,detail,tabId??null).catch((err)=>logDaemonError("attention-inbox-record",err))}}if(ctx.engineEvents?.append(taskId,{kind,...tabId?{tabId}:{},...vendor?{vendor}:{},...detail?{detail}:{},at:Date.now()}),kind==="pre-compact"||kind==="post-compact")await markCompacted(ctx,taskId,tabId??null);if(kind==="pre-compact"||kind==="post-compact"||kind==="subagent-start"||kind==="subagent-stop")ctx.bus.publish("engine.lifecycle",{taskId,kind,...tabId?{tabId}:{},at:Date.now()});let pluginReport={kind,taskId,...detail?{detail}:{},...vendor?{vendor}:{},...tabId?{tabId}:{},...sessionId?{sessionId}:{}};if(kind!=="turn-complete")ctx.plugins?.handleEngineReport(pluginReport);if(kind==="turn-complete")ingestAgentTurnsBestEffort(ctx.agentTurns,ctx.runtime,ctx.orch,{taskId,...tabId?{tabId}:{},...vendor?{vendor}:{},...transcriptPath?{transcriptPath}:{}},(latest)=>ctx.plugins?.handleEngineReport(latest?{...pluginReport,detail:{...pluginReport.detail??{},turn:latest}}:pluginReport));if(kind==="turn-complete"&&ctx.orch.canCheckpoint(taskId))ctx.checkpoints.schedule(ctx.orch.checkpointScope(taskId).ownerId,()=>ctx.orch.takeCheckpoint(taskId,tabId?{tabId}:void 0));if(kind==="turn-start"){if(ctx.orch.getTask(taskId)?.worktreeOnly)ctx.orch.setWorktreeOnly(taskId,!1).catch(()=>{});if(ctx.runtime.maybeAutoStart(ctx.orch,taskId).then((result)=>{if(result==="moved")console.log(`[status-rules] task ${taskId} auto-moved backlog \u2192 in_progress`)}).catch((err)=>logDaemonError("status-rules",err)),ctx.orch.getTask(taskId)?.quotaResume)ctx.orch.setQuotaResume(taskId,null).catch((err)=>logDaemonError("quota-resume",err))}if(kind==="turn-failed"&&detail?.failure==="rate_limit")scheduleQuotaResume(ctx.orch,ctx.runtime,ctx.quotaUsage,taskId,void 0,()=>ctx.plugins??null).catch((err)=>logDaemonError("quota-resume",err));return{}}};async function countGateRaiseAsReport(ctx,gate){return await reportCurrentDelivery(deliveryDepsOf(ctx),gate.taskId,gate.tabId,{outcome:"blocked",summary:gate.question,next:`awaiting owner decision ${gate.id}`})}async function armGateAnswerDelivery(ctx,task,gate){if(task.requireReport!==!0)return null;let delivery=await ctx.deliveries.arm({taskId:task.id,tabId:gate.tabId,source:"gate-answer",gateId:gate.id,promptHead:gate.question});return{deliveryId:delivery.id,footer:deliveryFooter(delivery.id,ctx.runtime.roveApiInvocation())}}var SURFACES=["tui","bridge","weixin","cli"],STATUS_FILTERS=["open","answered","withdrawn","all"];function parseOptions(raw){if(raw===void 0||raw===null)return[];if(!Array.isArray(raw))throw Error("options must be an array");return raw.map((entry)=>{let o=entry;if(!o||typeof o.key!=="string"||typeof o.label!=="string")throw Error("each option needs a string key and label");return{key:o.key,label:o.label,...typeof o.detail==="string"&&o.detail?{detail:o.detail}:{}}})}var deliveryChains=new Map;function deliverGateAnswer(ctx,gate){let run=(deliveryChains.get(gate.taskId)??Promise.resolve()).then(()=>pasteGateAnswer(ctx,gate)),next=run.catch(()=>{});return deliveryChains.set(gate.taskId,next),next.then(()=>{if(deliveryChains.get(gate.taskId)===next)deliveryChains.delete(gate.taskId)}),run}async function pasteGateAnswer(ctx,gate){let task=ctx.orch.getTask(gate.taskId);if(!task||task.deletion||!task.worktreePath)return!1;let handoff=takeUndeliveredGateAnswers(ctx.gates,gate.taskId,gate.tabId);if(!handoff)return!1;let target={id:task.id,vendor:task.vendor,command:task.command,worktreePath:task.worktreePath,scope:ptyScopeFor(ctx.orch.listTasks(),task.id)},armed=null;try{armed=await armGateAnswerDelivery(ctx,task,gate);let text2=armed?`${handoff.text}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RemoteOrchestrator}from"./chunk-qn1wqzvg.js";import{startTunnel}from"./chunk-nr8pxs18.js";import{dedupeMachines,discoverMachine,duplicateAliasOf,learnedFrom,listMachines,readMachines,setMachineIdentity,updateMachine}from"./chunk-m781veb4.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}:{}}}}
2
+ import{RemoteOrchestrator}from"./chunk-wyvy7zjq.js";import{startTunnel}from"./chunk-nr8pxs18.js";import{dedupeMachines,discoverMachine,duplicateAliasOf,learnedFrom,listMachines,readMachines,setMachineIdentity,updateMachine}from"./chunk-m781veb4.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};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{join}from"path";function webRoot(){return[join(import.meta.dir,"..","web"),join(import.meta.dir,"..","..","..","rove-web","dist")].find((dir)=>existsSync(join(dir,"index.html")))??null}async function runWebSubcommand(args){let root=webRoot();if(!root)console.error(`${ROVE_PRODUCT_NAME} --web: the browser client is not in this build. From a checkout, run \`bun --filter rove-web build\` first; the npm package ships it in dist/web.`),process.exit(2);let{runBridge}=await import("./chunk-0w81tahc.js");await runBridge(args,{name:`${ROVE_PRODUCT_NAME} --web`,web:{root}})}export{runWebSubcommand};
2
+ import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{join}from"path";function webRoot(){return[join(import.meta.dir,"..","web"),join(import.meta.dir,"..","..","..","rove-web","dist")].find((dir)=>existsSync(join(dir,"index.html")))??null}async function runWebSubcommand(args){let root=webRoot();if(!root)console.error(`${ROVE_PRODUCT_NAME} --web: the browser client is not in this build. From a checkout, run \`bun --filter rove-web build\` first; the npm package ships it in dist/web.`),process.exit(2);let{runBridge}=await import("./chunk-b83fxvne.js");await runBridge(args,{name:`${ROVE_PRODUCT_NAME} --web`,web:{root}})}export{runWebSubcommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{defaultFixRuntime}from"./chunk-0y98hsf7.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-s70prg81.js";import"./chunk-sjkk3jkf.js";import"./chunk-4bmv4jgc.js";import"./chunk-w14jz8pd.js";import"./chunk-9y21c892.js";import"./chunk-38hnq4aq.js";import"./chunk-pg1n8w1x.js";import"./chunk-rz19rphb.js";import"./chunk-zj25qsfj.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-gbe6hggt.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-atn06ncf.js";import"./chunk-mct40bd0.js";import"./chunk-b15q2s62.js";import{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-ssyt8vmv.js";import"./chunk-nr8pxs18.js";import{addMachine,dedupeMachines,defaultMachineAlias,discoverMachine,duplicateAliasOf,getMachine,hubKeyPath,isValidMachineAlias,isWindowsMachine,learnedFrom,listMachines,machineIdentityFile,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,remoteRove,removeMachine,sanitizeAlias,setMachineIdentity,sshServerIsWindows,sshTargetOf,updateMachine,windowsAuthorizeKeySteps}from"./chunk-m781veb4.js";import"./chunk-y0e28qha.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{CURRENT_VERSION}from"./chunk-3prnp53k.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-z44vb8p5.js";import"./chunk-n7rpqyjs.js";import"./chunk-6r74n1g2.js";import"./chunk-49zrnjq1.js";import"./chunk-mqfvzdpr.js";import"./chunk-v62qfbbq.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-2wakfp6d.js";import"./chunk-6jcmdxza.js";import"./chunk-6cq9t92a.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.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{shQuote}from"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-vpph4nqf.js";import"./chunk-cmp64q4j.js";import"./chunk-cqhtjxh7.js";import"./chunk-fgx76t84.js";import"./chunk-av0n24rf.js";import"./chunk-w7zv47mp.js";import"./chunk-86fzfqvw.js";import"./chunk-8yce2acw.js";import"./chunk-88cap497.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./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{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{spawn}from"child_process";import{appendFileSync,chmodSync,existsSync,mkdirSync}from"fs";import{homedir}from"os";import{dirname}from"path";function parseSshG(stdout,home=homedir()){let values=new Map;for(let line of stdout.split(`
2
+ import{defaultFixRuntime}from"./chunk-0y98hsf7.js";import{INBOUND_CLASSES,deniedClasses,setInbound}from"./chunk-172tz5gj.js";import"./chunk-7djtmcpv.js";import"./chunk-4bmv4jgc.js";import"./chunk-w14jz8pd.js";import"./chunk-9y21c892.js";import"./chunk-38hnq4aq.js";import"./chunk-pg1n8w1x.js";import"./chunk-rz19rphb.js";import"./chunk-02bkfsxf.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-gbe6hggt.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-atn06ncf.js";import"./chunk-canetc0e.js";import"./chunk-wwm5qrtx.js";import{primaryCheckouts,repoIdOf,repoIdentity,setPrimaryCheckout}from"./chunk-ssyt8vmv.js";import"./chunk-nr8pxs18.js";import{addMachine,dedupeMachines,defaultMachineAlias,discoverMachine,duplicateAliasOf,getMachine,hubKeyPath,isValidMachineAlias,isWindowsMachine,learnedFrom,listMachines,machineIdentityFile,machineSocketDir,machineSshArgs,parseSshTarget,readMachines,remoteRove,removeMachine,sanitizeAlias,setMachineIdentity,sshServerIsWindows,sshTargetOf,updateMachine,windowsAuthorizeKeySteps}from"./chunk-m781veb4.js";import"./chunk-y0e28qha.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{CURRENT_VERSION}from"./chunk-24zvsw6v.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-z44vb8p5.js";import"./chunk-n7rpqyjs.js";import"./chunk-6r74n1g2.js";import"./chunk-49zrnjq1.js";import"./chunk-mqfvzdpr.js";import"./chunk-v62qfbbq.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-2wakfp6d.js";import"./chunk-6jcmdxza.js";import"./chunk-6cq9t92a.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.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{shQuote}from"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-vpph4nqf.js";import"./chunk-cmp64q4j.js";import"./chunk-cqhtjxh7.js";import"./chunk-fgx76t84.js";import"./chunk-av0n24rf.js";import"./chunk-w7zv47mp.js";import"./chunk-86fzfqvw.js";import"./chunk-8yce2acw.js";import"./chunk-88cap497.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./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{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__require}from"./chunk-91sykzqq.js";import{spawn}from"child_process";import{appendFileSync,chmodSync,existsSync,mkdirSync}from"fs";import{homedir}from"os";import{dirname}from"path";function parseSshG(stdout,home=homedir()){let values=new Map;for(let line of stdout.split(`
3
3
  `)){let space=line.indexOf(" ");if(space>0)values.set(line.slice(0,space).toLowerCase(),line.slice(space+1).trim())}let hostname=values.get("hostname")??"",port=Number(values.get("port")??"22")||22,files=(key)=>(values.get(key)??"").split(/\s+/).filter((f)=>f&&f!=="none").map((f)=>f.startsWith("~/")?`${home}${f.slice(1)}`:f),alias=values.get("hostkeyalias"),proxy=(key)=>{let v=values.get(key);return v!==void 0&&v!=="none"};return{knownHostsName:alias&&alias!=="none"?alias:port===22?hostname:`[${hostname}]:${port}`,hostname,port,userKnownHosts:files("userknownhostsfile"),globalKnownHosts:files("globalknownhostsfile"),proxied:proxy("proxyjump")||proxy("proxycommand")}}async function checkHostKey(config){let target=sshTargetOf(config),resolved=await run(["ssh","-G",...config.port?["-p",String(config.port)]:[],target]);if(resolved.code!==0)return{state:"skipped",reason:"ssh -G failed"};let destination=parseSshG(resolved.stdout);if(!destination.hostname)return{state:"skipped",reason:"ssh -G named no host"};if(destination.proxied)return{state:"skipped",reason:"reached through a proxy"};for(let file of[...destination.userKnownHosts,...destination.globalKnownHosts]){if(!existsSync(file))continue;if((await run(["ssh-keygen","-F",destination.knownHostsName,"-f",file])).code===0)return{state:"known"}}let keys=(await run(["ssh-keyscan","-T","5","-p",String(destination.port),destination.hostname])).stdout.split(`
4
4
  `).filter((line)=>line.trim()&&!line.startsWith("#"));if(keys.length===0)return{state:"skipped",reason:"the host offered no key"};let named=keys.map((line)=>line.replace(/^\S+/,destination.knownHostsName)),fingerprints=(await run(["ssh-keygen","-l","-f","-"],`${named.join(`
5
5
  `)}
@@ -49,7 +49,7 @@ ${MACHINE_USAGE}
49
49
  `);continue}let{found}=established,learned=learnedFrom(found),sockets=learned.sockets,settled={...established.config,...learned};updateMachine(name,settled);let up=await ensureForwards({alias:name,config:settled,remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty}),version=found.status.roveVersion||"?",skew=version!==CURRENT_VERSION?` (this machine runs ${CURRENT_VERSION})`:"";process.stdout.write(`${name} ${up?"\u2713":"\u2717 socket not forwarded"} rove ${version}${skew} on ${found.status.hostname||"?"}
50
50
  `);for(let note of await doctorNotes(name,settled,found))process.stdout.write(` ${note}
51
51
  `);if(!up)failed++}if(failed>0)process.exitCode=1}async function update(argv){let alias=positionalOf(argv),entries=dedupeMachines(listMachines()).filter((m)=>!alias||m.alias===alias);if(alias&&entries.length===0)fail(`no machine named "${alias}" (see \`${CLI_NAME} machine list\`)`);if(entries.length===0){process.stdout.write(`No machines registered. Add one with \`${CLI_NAME} machine add <ssh-target>\`.
52
- `);return}let{upgradeMachine}=await import("./chunk-47g6ecty.js"),failed=0;for(let entry of entries){process.stderr.write(`${CLI_NAME} machine: updating ${entry.alias} (${sshTargetOf(entry)})\u2026
52
+ `);return}let{upgradeMachine}=await import("./chunk-616xv0af.js"),failed=0;for(let entry of entries){process.stderr.write(`${CLI_NAME} machine: updating ${entry.alias} (${sshTargetOf(entry)})\u2026
53
53
  `);try{let done=await upgradeMachine(entry),now=done.to??"?",skew=now!==CURRENT_VERSION?` (this machine runs ${CURRENT_VERSION})`:"";process.stdout.write(done.changed?`${entry.alias} \u2713 rove ${done.from??"?"} \u2192 ${now}${skew}
54
54
  `:`${entry.alias} \u2713 already on rove ${now}${skew}
55
55
  `)}catch(err){failed++,process.stdout.write(`${entry.alias} \u2717 ${err instanceof Error?err.message:String(err)}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{publishRoveTerminalTitle}from"./chunk-3aqhytyy.js";import{ensureGlobalRoveHooks}from"./chunk-e292nh2w.js";import{LAST_RUN_VERSION_KEY,enforceResetGate}from"./chunk-y9j708v1.js";import"./chunk-17e2tgyg.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import{CURRENT_VERSION,compareSemver}from"./chunk-3prnp53k.js";import{detectShell}from"./chunk-6xzx53b7.js";import"./chunk-289j5sz5.js";import"./chunk-z35jsvwk.js";import"./chunk-ws2q07kb.js";import"./chunk-zsfyj36g.js";import"./chunk-vpph4nqf.js";import"./chunk-cmp64q4j.js";import"./chunk-fgx76t84.js";import"./chunk-av0n24rf.js";import"./chunk-w7zv47mp.js";import"./chunk-86fzfqvw.js";import"./chunk-8yce2acw.js";import"./chunk-88cap497.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile,patchStateFile}from"./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{__require}from"./chunk-91sykzqq.js";var WELCOMED_KEY="welcomed";function shouldWelcome(state){if(state[WELCOMED_KEY]===!0)return!1;return typeof state[LAST_RUN_VERSION_KEY]!=="string"}function takeWelcome(){if(!shouldWelcome(loadStateFile()))return null;try{patchStateFile({[WELCOMED_KEY]:!0})}catch{}return{shell:detectShell()}}var WHATS_NEW_SEEN_KEY="app.whatsNewSeenVersion";function whatsNewFromVersion(state,current=CURRENT_VERSION){let stamped=state[WHATS_NEW_SEEN_KEY]??state[LAST_RUN_VERSION_KEY];if(typeof stamped!=="string"||stamped.length===0)return null;return compareSemver(current,stamped)>0?stamped:null}function takeWhatsNew(){let from=whatsNewFromVersion(loadStateFile());try{patchStateFile({[WHATS_NEW_SEEN_KEY]:CURRENT_VERSION})}catch{}return from}async function startTui(){let whatsNewFrom=takeWhatsNew(),welcome=takeWelcome();enforceResetGate(),publishRoveTerminalTitle(),await ensureGlobalRoveHooks();let{loadPluginEngines}=await import("./chunk-2y5fzpem.js");loadPluginEngines();let{startSkillStatus}=await import("./chunk-k0f912qf.js");startSkillStatus();let{startWorkspaceHost}=await import("./chunk-ebybc98b.js");await startWorkspaceHost({whatsNewFrom,welcome})}export{startTui};
2
+ import{publishRoveTerminalTitle}from"./chunk-3aqhytyy.js";import{ensureGlobalRoveHooks}from"./chunk-e292nh2w.js";import{LAST_RUN_VERSION_KEY,enforceResetGate}from"./chunk-6jf8qxvv.js";import"./chunk-17e2tgyg.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import{CURRENT_VERSION,compareSemver}from"./chunk-24zvsw6v.js";import{detectShell}from"./chunk-6xzx53b7.js";import"./chunk-289j5sz5.js";import"./chunk-z35jsvwk.js";import"./chunk-ws2q07kb.js";import"./chunk-zsfyj36g.js";import"./chunk-vpph4nqf.js";import"./chunk-cmp64q4j.js";import"./chunk-fgx76t84.js";import"./chunk-av0n24rf.js";import"./chunk-w7zv47mp.js";import"./chunk-86fzfqvw.js";import"./chunk-8yce2acw.js";import"./chunk-88cap497.js";import"./chunk-29b3pj9h.js";import"./chunk-96kvwzj8.js";import"./chunk-bgmpczgm.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile,patchStateFile}from"./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{__require}from"./chunk-91sykzqq.js";var WELCOMED_KEY="welcomed";function shouldWelcome(state){if(state[WELCOMED_KEY]===!0)return!1;return typeof state[LAST_RUN_VERSION_KEY]!=="string"}function takeWelcome(){if(!shouldWelcome(loadStateFile()))return null;try{patchStateFile({[WELCOMED_KEY]:!0})}catch{}return{shell:detectShell()}}var WHATS_NEW_SEEN_KEY="app.whatsNewSeenVersion";function whatsNewFromVersion(state,current=CURRENT_VERSION){let stamped=state[WHATS_NEW_SEEN_KEY]??state[LAST_RUN_VERSION_KEY];if(typeof stamped!=="string"||stamped.length===0)return null;return compareSemver(current,stamped)>0?stamped:null}function takeWhatsNew(){let from=whatsNewFromVersion(loadStateFile());try{patchStateFile({[WHATS_NEW_SEEN_KEY]:CURRENT_VERSION})}catch{}return from}async function startTui(){let whatsNewFrom=takeWhatsNew(),welcome=takeWelcome();enforceResetGate(),publishRoveTerminalTitle(),await ensureGlobalRoveHooks();let{loadPluginEngines}=await import("./chunk-2y5fzpem.js");loadPluginEngines();let{startSkillStatus}=await import("./chunk-k0f912qf.js");startSkillStatus();let{startWorkspaceHost}=await import("./chunk-w81aezsx.js");await startWorkspaceHost({whatsNewFrom,welcome})}export{startTui};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-01ekh175.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-sjkk3jkf.js";import{ensurePluginEnginesLoaded}from"./chunk-w14jz8pd.js";import{openDaemonSession}from"./chunk-9y21c892.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-ssyt8vmv.js";import{ApiError,requireVerbInstalled,verbInstalled}from"./chunk-jz1kj4sf.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{errorMessage}from"./chunk-9gctbddn.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)}
2
+ import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-jqn9m2d2.js";import{VerbArgs,apiUsage,findVerb,parseFlags,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-7djtmcpv.js";import{ensurePluginEnginesLoaded}from"./chunk-w14jz8pd.js";import{openDaemonSession}from"./chunk-9y21c892.js";import{AUTO_MACHINE,LOCAL_MACHINE,addStaysHere,forwardVerb,pickMachine,repoHosts,requireMachine,routeTarget,takeIdentityWarning}from"./chunk-ssyt8vmv.js";import{ApiError,requireVerbInstalled,verbInstalled}from"./chunk-jz1kj4sf.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{ROVE_API_VERSION}from"./chunk-96kvwzj8.js";import{errorMessage}from"./chunk-9gctbddn.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,5 +1,5 @@
1
1
  // @bun
2
- import{CURRENT_VERSION}from"./chunk-3prnp53k.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-6jcmdxza.js";import"./chunk-han0d078.js";import{flagValue}from"./chunk-zsfyj36g.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir))}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
2
+ import{CURRENT_VERSION}from"./chunk-24zvsw6v.js";import{isRemoteWorkspace,readRemoteWorkspace,rxPath}from"./chunk-6jcmdxza.js";import"./chunk-han0d078.js";import{flagValue}from"./chunk-zsfyj36g.js";import{quoteShellArg}from"./chunk-7kysxgbq.js";import"./chunk-pn5ygqn6.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{spawnSync}from"child_process";import{realpathSync}from"fs";import{dirname,resolve}from"path";import{createInterface}from"readline";async function runRemoteWorkspaceSubcommand(args){let dir=flagValue(args,"--dir")??process.cwd();if(!isRemoteWorkspace(dir))return;if(args[0]==="bash-hook")process.stdout.write(bashHookReply(await readAll(process.stdin),rxPath(dir)));else if(args[0]==="file-hook")process.stdout.write(fileHookReply(await readAll(process.stdin),dir));else if(args[0]==="mcp")await serveMcp(rxPath(dir))}async function readAll(stream){let text="";for await(let chunk of stream)text+=chunk;return text}function bashHookReply(payload,rx){let input;try{input=JSON.parse(payload).tool_input??{}}catch{return""}let command=input.command;if(typeof command!=="string"||/^\s*(\S*\/)?rx\s/.test(command))return"";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...input,command:`${quoteShellArg(rx)} ${quoteShellArg(command)}`}}})}function fileHookReply(payload,dir){let call;try{call=JSON.parse(payload)}catch{return""}let input=call.tool_input??{},named=[input.file_path,input.notebook_path,input.path].find((p)=>typeof p==="string"&&p),target=resolve(call.cwd??dir,typeof named==="string"?named:"."),ws=readRemoteWorkspace(dir);if(![dir,realPath(dir),...ws?[ws.path]:[]].some((root)=>target===root||target.startsWith(`${root}/`)))return"";let where=ws?`the machine "${ws.machine}", at ${ws.path}`:"another machine";return JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${target} is in the project, which is on ${where}. This tool only sees this machine. Use the workspace read / write / edit tools for the project's files (paths relative to its root), and the shell to search it (rg, find, ls): shell commands run there.`}})}function realPath(dir){try{return realpathSync(dir)}catch{return dir}}var runThrough=(rx)=>(command,stdin)=>{let res=spawnSync(rx,[command],{input:stdin,encoding:"utf8",maxBuffer:67108864});return{ok:res.status===0,out:res.status===0?res.stdout:(res.stderr||res.stdout||"failed").trim()}},READ_LINES=2000,TOOLS=[{name:"read",description:`Read a file of the project. Returns its text; at most ${READ_LINES} lines unless offset/limit ask for a range.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Path, relative to the project root or absolute on that machine."},offset:{type:"number",description:"First line to return (1-based)."},limit:{type:"number",description:"How many lines to return."}},required:["path"]}},{name:"write",description:"Create a file of the project or replace its whole content. Parent directories are created.",inputSchema:{type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]}},{name:"edit",description:"Replace old_string with new_string in a file of the project. old_string must match exactly and occur once, unless replace_all is true.",inputSchema:{type:"object",properties:{path:{type:"string"},old_string:{type:"string"},new_string:{type:"string"},replace_all:{type:"boolean"}},required:["path","old_string","new_string"]}}];function callWorkspaceTool(run,name,a){let path=typeof a.path==="string"?a.path:"";if(!path)throw Error("path is required");let file=quoteShellArg(path),must=(res)=>{if(!res.ok)throw Error(res.out);return res.out},write=(content)=>must(run(`mkdir -p -- ${quoteShellArg(dirname(path))} && cat > ${file}`,content));if(name==="read"){let from=Math.max(1,Math.trunc(Number(a.offset)||1)),count=Math.max(1,Math.trunc(Number(a.limit)||READ_LINES)),text=must(run(`sed -n '${from},${from+count}p' -- ${file}`)),lines=text.split(`
3
3
  `);if(lines.length<=count+1)return text;return`${lines.slice(0,count).join(`
4
4
  `)}
5
5
  [cut at line ${from+count-1}; pass offset to read on]`}if(name==="write"){if(typeof a.content!=="string")throw Error("content is required");return write(a.content),`wrote ${path}`}if(name==="edit"){let{old_string:from,new_string:to}=a;if(typeof from!=="string"||typeof to!=="string"||!from)throw Error("old_string and new_string are required");let text=must(run(`cat -- ${file}`)),hits=text.split(from).length-1;if(hits===0)throw Error(`old_string not found in ${path}`);if(hits>1&&a.replace_all!==!0)throw Error(`old_string occurs ${hits} times in ${path}; add context to make it unique, or pass replace_all`);return write(text.split(from).join(to)),`edited ${path} (${hits} replacement${hits===1?"":"s"})`}throw Error(`unknown tool: ${name}`)}function mcpReply(run,msg){if(msg.id===void 0||!msg.method)return null;let result=(value)=>({jsonrpc:"2.0",id:msg.id,result:value});if(msg.method==="initialize")return result({protocolVersion:typeof msg.params?.protocolVersion==="string"?msg.params.protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:"rove-workspace",version:CURRENT_VERSION}});if(msg.method==="ping")return result({});if(msg.method==="tools/list")return result({tools:TOOLS});if(msg.method==="tools/call"){let args=msg.params?.arguments??{};try{let text=callWorkspaceTool(run,String(msg.params?.name??""),args);return result({content:[{type:"text",text}]})}catch(err){return result({content:[{type:"text",text:err instanceof Error?err.message:String(err)}],isError:!0})}}return{jsonrpc:"2.0",id:msg.id,error:{code:-32601,message:`method not found: ${msg.method}`}}}async function serveMcp(rx){let run=runThrough(rx);for await(let line of createInterface({input:process.stdin})){if(!line.trim())continue;let msg;try{msg=JSON.parse(line)}catch{continue}let reply=mcpReply(run,msg);if(reply)process.stdout.write(`${JSON.stringify(reply)}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-qcypgc4n.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
2
+ import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-3661pvwa.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
3
3
  export{runChannelCli,startChatChannels};