@sma1lboy/rove 0.9.299 → 0.9.300-next.356

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 (58) hide show
  1. package/dist/cli/{chunk-9gg07kkc.js → chunk-11104t0c.js} +1 -1
  2. package/dist/cli/{chunk-vyqgq8ct.js → chunk-13wf7s1k.js} +1 -1
  3. package/dist/cli/{chunk-ncjwdhse.js → chunk-1e025dbe.js} +1 -1
  4. package/dist/cli/{chunk-yzzs69np.js → chunk-1wv4rj73.js} +1 -1
  5. package/dist/cli/{chunk-j6rkg0a4.js → chunk-1xygyynx.js} +1 -1
  6. package/dist/cli/{chunk-ttpwban2.js → chunk-416z99p1.js} +1 -1
  7. package/dist/cli/{chunk-yjw1wa8d.js → chunk-477a70sa.js} +1 -1
  8. package/dist/cli/chunk-56dvk7hh.js +12 -0
  9. package/dist/cli/chunk-59m9k6q4.js +3 -0
  10. package/dist/cli/{chunk-a2naafjr.js → chunk-5wzphqcr.js} +1 -1
  11. package/dist/cli/{chunk-1e1vfppc.js → chunk-6mqmayt5.js} +1 -1
  12. package/dist/cli/{chunk-xe6wrg72.js → chunk-6x66vdkv.js} +1 -1
  13. package/dist/cli/{chunk-8qr3kca5.js → chunk-6ypm3p04.js} +1 -1
  14. package/dist/cli/{chunk-8tp3vs1j.js → chunk-7fj5gt8c.js} +1 -1
  15. package/dist/cli/{chunk-3cf967q4.js → chunk-7s10s3pk.js} +1 -1
  16. package/dist/cli/{chunk-m4zacsjk.js → chunk-8y529tec.js} +1 -1
  17. package/dist/cli/{chunk-fyj9wy78.js → chunk-90c09w78.js} +1 -1
  18. package/dist/cli/{chunk-2xe3wr7g.js → chunk-9sms4rrm.js} +1 -1
  19. package/dist/cli/{chunk-ay8pwbgn.js → chunk-9zn40ecf.js} +1 -1
  20. package/dist/cli/{chunk-xxgrq4d3.js → chunk-chbamhzy.js} +1 -1
  21. package/dist/cli/{chunk-16xhmzfh.js → chunk-ctgpdtqg.js} +2 -2
  22. package/dist/cli/{chunk-88wz9zcq.js → chunk-cyzk4dwd.js} +1 -1
  23. package/dist/cli/{chunk-rvb9b1mr.js → chunk-de4d17gj.js} +1 -1
  24. package/dist/cli/{chunk-swg22z6q.js → chunk-ed27te6p.js} +1 -1
  25. package/dist/cli/{chunk-dk2vbkbv.js → chunk-efdmmfjt.js} +1 -1
  26. package/dist/cli/{chunk-a02mweev.js → chunk-ejqvfqd4.js} +1 -1
  27. package/dist/cli/{chunk-7tgkwp99.js → chunk-ethask2w.js} +1 -1
  28. package/dist/cli/{chunk-3m41b0n7.js → chunk-fq726q1e.js} +1 -1
  29. package/dist/cli/{chunk-e2xh0w1a.js → chunk-frcm9gdx.js} +1 -1
  30. package/dist/cli/{chunk-nvf8k04m.js → chunk-h87ztpkj.js} +1 -1
  31. package/dist/cli/{chunk-h0nd99vq.js → chunk-mjct4zmc.js} +1 -1
  32. package/dist/cli/{chunk-64v78t3w.js → chunk-nrxrvrnq.js} +1 -1
  33. package/dist/cli/{chunk-3aym3sba.js → chunk-phsdavw7.js} +1 -1
  34. package/dist/cli/{chunk-5xker6xn.js → chunk-qp1batct.js} +1 -1
  35. package/dist/cli/{chunk-nsfewp42.js → chunk-rb19bnax.js} +1 -1
  36. package/dist/cli/{chunk-6wssap0t.js → chunk-s69whdc3.js} +1 -1
  37. package/dist/cli/{chunk-g1drj26p.js → chunk-sa3mfbj2.js} +2 -2
  38. package/dist/cli/{chunk-xyw32jjt.js → chunk-sy8paxk6.js} +1 -1
  39. package/dist/cli/{chunk-hp4k9vpe.js → chunk-v0pk0pqc.js} +1 -1
  40. package/dist/cli/{chunk-ydvtzf74.js → chunk-v1srkcvd.js} +1 -1
  41. package/dist/cli/{chunk-wrg4bsbw.js → chunk-vw2acxf6.js} +1 -1
  42. package/dist/cli/{chunk-g6hzc2dw.js → chunk-xax447sj.js} +2 -2
  43. package/dist/cli/{chunk-tw73vrq4.js → chunk-xz36hspj.js} +1 -1
  44. package/dist/cli/{chunk-9sq7th80.js → chunk-z4e7j6fa.js} +2 -2
  45. package/dist/cli/{chunk-tjcw0fzt.js → chunk-z9h9jfkq.js} +1 -1
  46. package/dist/cli/{chunk-wxs2yqnz.js → chunk-zf0kvr96.js} +1 -1
  47. package/dist/cli/{chunk-4zb3nqs5.js → chunk-zkf5d5xd.js} +1 -1
  48. package/dist/cli/index.js +2 -2
  49. package/dist/cli/rove.js +3 -3
  50. package/dist/web/assets/{index-CidDBOEI.css → index-DYvEJ1Mu.css} +1 -1
  51. package/dist/web/assets/index-GQQlLq2C.js +83 -0
  52. package/dist/web/assets/{term-mount-pkpAikMy.js → term-mount-D_eQTRxq.js} +1 -1
  53. package/dist/web/index.html +2 -2
  54. package/dist/web/relay/index.html +2 -2
  55. package/package.json +1 -1
  56. package/dist/cli/chunk-34fhp2ck.js +0 -11
  57. package/dist/cli/chunk-xfz83737.js +0 -3
  58. package/dist/web/assets/index-Xz9-coqU.js +0 -83
@@ -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)})}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.ensureProject(create.dir):create.dir,task=await deps.orch.openDirectoryTask({dir,...create.vendor?{vendor:create.vendor}:{},...create.model?{model:create.model}:{},...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{spawn as spawn4}from"child_process";function runGit(worktreePath,args,signal){return new Promise((resolve2)=>{let stdout="",settled=!1,finish=(status)=>{if(settled)return;settled=!0,resolve2(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()=>{},upgradeProtocol=createProtocolUpgradeReporter(orch,runtime),stopActivityObserver=activity?startActivityObserver(activity,{...createActivityObserverIo(options.homeDir,runtime,activity,ownerOf),onEngineEvidence:(taskId,tabId,evidence)=>{return options.onLiveEngine?.(taskId,tabId,evidence.walkVendor),upgradeProtocol(taskId,tabId,evidence)},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):()=>{},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,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")}:{},...optionalBoolean(payload,"keep")===!0?{keep:!0}:{}})}}}];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.ensureProject(create.dir):create.dir,task=await deps.orch.openDirectoryTask({dir,...create.vendor?{vendor:create.vendor}:{},...create.model?{model:create.model}:{},...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{spawn as spawn4}from"child_process";function runGit(worktreePath,args,signal){return new Promise((resolve2)=>{let stdout="",settled=!1,finish=(status)=>{if(settled)return;settled=!0,resolve2(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()=>{},upgradeProtocol=createProtocolUpgradeReporter(orch,runtime),stopActivityObserver=activity?startActivityObserver(activity,{...createActivityObserverIo(options.homeDir,runtime,activity,ownerOf),onEngineEvidence:(taskId,tabId,evidence)=>{return options.onLiveEngine?.(taskId,tabId,evidence.walkVendor),upgradeProtocol(taskId,tabId,evidence)},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):()=>{},stopAttachmentSweep=runtime.startAttachmentSweep?.((line)=>logDaemonInfo("attachments",line))??(()=>{}),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):()=>{},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,stopMachineHub,stopAttachmentSweep,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")}:{},...optionalBoolean(payload,"keep")===!0?{keep:!0}:{}})}}}];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,5 +1,5 @@
1
1
  // @bun
2
- import{FEEDBACK_KINDS,isFeedbackKind,submitFeedback}from"./chunk-hp4k9vpe.js";import"./chunk-xxz504p6.js";import"./chunk-xfz83737.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-mg1cas61.js";import"./chunk-8trtyc98.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";var CLI_NAME=ROVE_PRODUCT_NAME,FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--kind bug|idea|question]`,"","File a GitHub issue on the Rove repository using the GitHub CLI. Rove appends its","version, OS, install kind and default engine to the body.","","Requires:"," gh auth login","Without a signed-in gh, prints a prefilled new-issue link to open instead.","","Options:"," --title <text> Issue title"," --body <text> Issue body"," --body-file <path> Read the issue body from a file; use - for stdin"," --kind <kind> bug (default, label bug), idea (enhancement) or question"," -h, --help Print this help",""].join(`
2
+ import{FEEDBACK_KINDS,isFeedbackKind,submitFeedback}from"./chunk-v0pk0pqc.js";import"./chunk-xxz504p6.js";import"./chunk-59m9k6q4.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-mg1cas61.js";import"./chunk-8trtyc98.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";var CLI_NAME=ROVE_PRODUCT_NAME,FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--kind bug|idea|question]`,"","File a GitHub issue on the Rove repository using the GitHub CLI. Rove appends its","version, OS, install kind and default engine to the body.","","Requires:"," gh auth login","Without a signed-in gh, prints a prefilled new-issue link to open instead.","","Options:"," --title <text> Issue title"," --body <text> Issue body"," --body-file <path> Read the issue body from a file; use - for stdin"," --kind <kind> bug (default, label bug), idea (enhancement) or question"," -h, --help Print this help",""].join(`
3
3
  `);function usageError(message){process.stderr.write(`${CLI_NAME} feedback: ${message}
4
4
 
5
5
  ${FEEDBACK_USAGE}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{MachineHub}from"./chunk-tw73vrq4.js";import"./chunk-1e1vfppc.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-nsfewp42.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-5xker6xn.js";import{machineDaemonSocket}from"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import{isWindowsMachine,listMachines}from"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-xfz83737.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import{RoveDaemonClient}from"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
2
+ import{MachineHub}from"./chunk-xz36hspj.js";import"./chunk-6mqmayt5.js";import"./chunk-6xr1prk6.js";import{upgradeMachine}from"./chunk-rb19bnax.js";import"./chunk-mdx18vtz.js";import{preferredReleaseChannel}from"./chunk-qp1batct.js";import{machineDaemonSocket}from"./chunk-jdfz6n5s.js";import"./chunk-cn6qc47w.js";import{isWindowsMachine,listMachines}from"./chunk-7m3txy05.js";import"./chunk-y0e28qha.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import{CURRENT_VERSION,checkLatestVersion,isNewerSemver}from"./chunk-59m9k6q4.js";import{logDaemonInfo}from"./chunk-rxqdw6s5.js";import"./chunk-4we77hfk.js";import"./chunk-6jcmdxza.js";import"./chunk-x62wqf3s.js";import"./chunk-han0d078.js";import"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-cqzkk7j0.js";import"./chunk-catrr0z3.js";import"./chunk-dvpjthdf.js";import"./chunk-tn9gtf18.js";import"./chunk-r7khfa3k.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-7y9dy9sa.js";import"./chunk-cmp64q4j.js";import"./chunk-1dxpkpqv.js";import"./chunk-76gh55cc.js";import"./chunk-ng0kaekc.js";import"./chunk-w7zv47mp.js";import"./chunk-3spvd3vw.js";import"./chunk-xq05a8a5.js";import"./chunk-0b3mxres.js";import{RoveDaemonClient}from"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import"./chunk-v9n5e14e.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import{loadStateFile}from"./chunk-8trtyc98.js";import"./chunk-x8jpnh1n.js";import"./chunk-27hpzddr.js";import"./chunk-7kysxgbq.js";import"./chunk-8g6sb0q6.js";import"./chunk-y8hjgmn0.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-pn5ygqn6.js";import"./chunk-7ghwdjdc.js";import"./chunk-m5nd44st.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import"./chunk-91sykzqq.js";var MACHINES_AUTO_UPDATE_KEY="machines.autoUpdate",DEFAULTS={hubVersion:CURRENT_VERSION,enabled:()=>loadStateFile()[MACHINES_AUTO_UPDATE_KEY]!==!1,head:async()=>(await checkLatestVersion({force:!0,channel:preferredReleaseChannel()}))?.latest??null,entryOf:(alias)=>listMachines().find((m)=>m.alias===alias),busy:async(entry)=>{let socketPath=await machineDaemonSocket(entry);if(!socketPath)return!0;let client=new RoveDaemonClient(socketPath);try{return((await client.request("daemon.status")).invoking??0)>0}catch{return!0}finally{client.close()}},upgrade:upgradeMachine,log:(line)=>logDaemonInfo("machines",line),retryMs:60000};function startMachineAutoUpdate(machines,overrides={}){let deps={...DEFAULTS,...overrides},tried=new Set,running=new Set,retry=null,attempt=async(alias,version)=>{let key=`${alias}@${version}`,entry=deps.entryOf(alias);if(!entry||isWindowsMachine(entry))return void tried.add(key);let head=await deps.head();if(!head||!isNewerSemver(head,version))return void tried.add(key);if(await deps.busy(entry)){retry??=setTimeout(()=>{retry=null,look()},deps.retryMs);return}tried.add(key);let done=await deps.upgrade(entry);deps.log(done.changed?`${alias} updated: ${done.from??"?"} \u2192 ${done.to??"?"}`:`${alias} had nothing newer to install`)},look=()=>{if(!deps.enabled())return;for(let row of machines.get()){if(row.state!=="online"||!row.version||row.duplicateOf)continue;if(!isNewerSemver(deps.hubVersion,row.version))continue;if(tried.has(`${row.alias}@${row.version}`)||running.has(row.alias))continue;running.add(row.alias),attempt(row.alias,row.version).catch((err)=>deps.log(`${row.alias} auto-update failed: ${err instanceof Error?err.message:err}`)).finally(()=>running.delete(row.alias))}},stop=machines.subscribe(look);return look(),()=>{if(stop(),retry)clearTimeout(retry)}}var PUBLISH_DEBOUNCE_MS=50;function startDaemonMachineHub(bus){let hub=new MachineHub,timer=null,publish=()=>{timer=null;let live=hub.liveSignal().get(),payload={machines:hub.machinesSignal().get(),tasks:hub.tasksSignal().get().map((task)=>({...task,kind:task.kind??"task",pinned:task.pinned??!1})),live:{activity:Object.fromEntries(live.activity),changes:Object.fromEntries(live.changes),tokens:Object.fromEntries(live.tokens)}};bus.publish("machines",payload)},schedule=()=>{timer??=setTimeout(publish,PUBLISH_DEBOUNCE_MS)},stops=[hub.machinesSignal(),hub.tasksSignal(),hub.liveSignal()].map((signal)=>signal.subscribe(schedule)),lastRegistry=null,offState=bus.onPublish((event)=>{if(event.channel!=="state")return;let state=event.payload.state,text=JSON.stringify(state.machines??null);if(text===lastRegistry)return;lastRegistry=text,hub.sync()});hub.sync(),publish();let stopAutoUpdate=startMachineAutoUpdate(hub.machinesSignal());return()=>{stopAutoUpdate(),offState();for(let stop of stops)stop();if(timer)clearTimeout(timer);hub.dispose(),bus.publish("machines",{machines:[],tasks:[],live:{activity:{},changes:{},tokens:{}}})}}export{startDaemonMachineHub};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RELEASE_CHANNELS,channelOf}from"./chunk-xfz83737.js";import{loadStateFile,patchStateFile}from"./chunk-8trtyc98.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
2
+ import{RELEASE_CHANNELS,channelOf}from"./chunk-59m9k6q4.js";import{loadStateFile,patchStateFile}from"./chunk-8trtyc98.js";var UPDATE_CHANNEL_KEY="update.channel",UPDATE_DELAY_KEY="update.delayHours",UPDATE_NOTIFY_KEY="update.notify";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function updateNotifyEnabled(raw){return raw!==!1}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}function updateDelayHours(state=loadStateFile()){let value=state[UPDATE_DELAY_KEY];return typeof value==="number"&&Number.isFinite(value)&&value>0?value:0}
3
3
  export{UPDATE_CHANNEL_KEY,UPDATE_NOTIFY_KEY,normalizeReleaseChannel,preferredReleaseChannel,updateNotifyEnabled,rememberReleaseChannel,updateDelayHours};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{preferredReleaseChannel}from"./chunk-5xker6xn.js";import{discoverMachine,remoteRove,runOnMachine}from"./chunk-7m3txy05.js";var DEFAULTS={version:async(entry)=>{let found=await discoverMachine(entry.alias,entry);return found.ok?found.status.roveVersion||null:null},installed:async(entry)=>{let out=await runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,["--version"]),{timeoutMs:30000});return/\b(\d+\.\d+\.\d+\S*)/.exec(out.stdout)?.[1]??null},run:(entry,args,timeoutMs)=>runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,args),{timeoutMs}),channel:preferredReleaseChannel},lastLines=(run)=>`${run.stdout}
2
+ import{preferredReleaseChannel}from"./chunk-qp1batct.js";import{discoverMachine,remoteRove,runOnMachine}from"./chunk-7m3txy05.js";var DEFAULTS={version:async(entry)=>{let found=await discoverMachine(entry.alias,entry);return found.ok?found.status.roveVersion||null:null},installed:async(entry)=>{let out=await runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,["--version"]),{timeoutMs:30000});return/\b(\d+\.\d+\.\d+\S*)/.exec(out.stdout)?.[1]??null},run:(entry,args,timeoutMs)=>runOnMachine(entry.alias,entry,remoteRove(entry.roveBin,args),{timeoutMs}),channel:preferredReleaseChannel},lastLines=(run)=>`${run.stdout}
3
3
  ${run.stderr}`.trim().split(`
4
4
  `).slice(-6).join(`
5
5
  `)||`exit ${run.exitCode}`;async function upgradeMachine(entry,overrides={}){let deps={...DEFAULTS,...overrides},{alias}=entry,from=await deps.version(entry),install=await deps.run(entry,["update","--channel",deps.channel()],600000);if(install.exitCode!==0)throw Error(`rove update on ${alias} failed:
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{__require}from"./chunk-91sykzqq.js";var welcomeWrite=Promise.resolve();function trackWelcomeWrite(write){welcomeWrite=write}async function launchTui(){let{startTui}=await import("./chunk-8qr3kca5.js");await startTui(),await welcomeWrite;let{runPendingWelcomeInstalls}=await import("./chunk-xhjgdsaw.js");runPendingWelcomeInstalls()}
2
+ import{__require}from"./chunk-91sykzqq.js";var welcomeWrite=Promise.resolve();function trackWelcomeWrite(write){welcomeWrite=write}async function launchTui(){let{startTui}=await import("./chunk-6ypm3p04.js");await startTui(),await welcomeWrite;let{runPendingWelcomeInstalls}=await import("./chunk-xhjgdsaw.js");runPendingWelcomeInstalls()}
3
3
  export{trackWelcomeWrite,launchTui};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{updaterShell,updaterShellFailureHint}from"./chunk-ncjwdhse.js";import{preferredReleaseChannel,rememberReleaseChannel}from"./chunk-5xker6xn.js";import{BREAKING_VERSIONS,CURRENT_VERSION,DEFAULT_RELEASE_CHANNEL,RELEASE_CHANNELS,UPDATE_COMMAND,UPDATE_SCRIPT_URL,breakingVersionsCrossed,channelOf,checkLatestVersion,fetchReleaseSummaries,recommendedGlobalInstallCommand,updateCommandFor}from"./chunk-xfz83737.js";import"./chunk-tn9gtf18.js";import"./chunk-8trtyc98.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{spawnSync}from"child_process";var CLI_NAME=ROVE_PRODUCT_NAME;function updatePlan(target){let shell=updateCommandFor(target);return{command:updaterShell(),args:["-c",shell],display:shell}}var VERSION_SHAPE=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;function isReleaseChannel(value){return RELEASE_CHANNELS.includes(value)}var CHANNEL_FLAGS={"--nightly":"nightly","--next":"next","--stable":"latest","--latest":"latest",stable:"latest"};function parseUpdateArgs(args){let dryRun=!1,list=!1,version,channel;for(let i=0;i<args.length;i+=1){let arg=args[i];if(arg===void 0)continue;if(arg==="--help"||arg==="-h"||arg==="help")return{help:!0,dryRun,list,version,channel};if(arg==="dry-run"||arg==="--dry-run"){dryRun=!0;continue}if(arg==="list"||arg==="--list"){list=!0;continue}if(arg==="--channel"||arg.startsWith("--channel=")){let value=(arg.startsWith("--channel=")?arg.slice(10):void 0)??args[++i];if(value===void 0||!isReleaseChannel(value))process.stderr.write(`${CLI_NAME} update: --channel expects one of ${RELEASE_CHANNELS.join(", ")}${value===void 0?"":` (got "${value}")`}
2
+ import{updaterShell,updaterShellFailureHint}from"./chunk-1e025dbe.js";import{preferredReleaseChannel,rememberReleaseChannel}from"./chunk-qp1batct.js";import{BREAKING_VERSIONS,CURRENT_VERSION,DEFAULT_RELEASE_CHANNEL,RELEASE_CHANNELS,UPDATE_COMMAND,UPDATE_SCRIPT_URL,breakingVersionsCrossed,channelOf,checkLatestVersion,fetchReleaseSummaries,recommendedGlobalInstallCommand,updateCommandFor}from"./chunk-59m9k6q4.js";import"./chunk-tn9gtf18.js";import"./chunk-8trtyc98.js";import"./chunk-jt9n8k7z.js";import"./chunk-apaw34c5.js";import"./chunk-yt15y085.js";import"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{spawnSync}from"child_process";var CLI_NAME=ROVE_PRODUCT_NAME;function updatePlan(target){let shell=updateCommandFor(target);return{command:updaterShell(),args:["-c",shell],display:shell}}var VERSION_SHAPE=/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;function isReleaseChannel(value){return RELEASE_CHANNELS.includes(value)}var CHANNEL_FLAGS={"--nightly":"nightly","--next":"next","--stable":"latest","--latest":"latest",stable:"latest"};function parseUpdateArgs(args){let dryRun=!1,list=!1,version,channel;for(let i=0;i<args.length;i+=1){let arg=args[i];if(arg===void 0)continue;if(arg==="--help"||arg==="-h"||arg==="help")return{help:!0,dryRun,list,version,channel};if(arg==="dry-run"||arg==="--dry-run"){dryRun=!0;continue}if(arg==="list"||arg==="--list"){list=!0;continue}if(arg==="--channel"||arg.startsWith("--channel=")){let value=(arg.startsWith("--channel=")?arg.slice(10):void 0)??args[++i];if(value===void 0||!isReleaseChannel(value))process.stderr.write(`${CLI_NAME} update: --channel expects one of ${RELEASE_CHANNELS.join(", ")}${value===void 0?"":` (got "${value}")`}
3
3
 
4
4
  `),printUsage(process.stderr),process.exit(2);channel=value;continue}let flagged=CHANNEL_FLAGS[arg];if(channel===void 0&&flagged!==void 0){channel=flagged;continue}if(channel===void 0&&isReleaseChannel(arg)){channel=arg;continue}if(version===void 0&&VERSION_SHAPE.test(arg)){version=arg;continue}process.stderr.write(`${CLI_NAME} update: unknown argument "${arg}"
5
5
 
@@ -10,7 +10,7 @@ import{updaterShell,updaterShellFailureHint}from"./chunk-ncjwdhse.js";import{pre
10
10
  install one with: ${CLI_NAME} update <version>
11
11
  `)}async function warnBreakingCrossings(target,channel,io){if(BREAKING_VERSIONS.length===0)return;let resolved=target??(await checkLatestVersion({force:!0,channel}))?.latest;if(!resolved)return;let crossed=breakingVersionsCrossed(CURRENT_VERSION,resolved);if(crossed.length===0)return;io.stderr.write([`warning: ${CURRENT_VERSION} -> ${resolved} crosses breaking version(s): ${crossed.join(", ")}.`,`After this update, Rove will refuse to start until you run \`${CLI_NAME} reset\``,"(worktrees are never touched; add --hard only to also wipe the task index).",""].join(`
12
12
  `))}var FOLLOW_UP_NOTE=["",`${CLI_NAME}: installed. Two background processes are still running the old build:`,` daemon \u2192 \`${CLI_NAME} daemon restart\` (safe; never touches live sessions)`,` pty host \u2192 only \`${CLI_NAME} reset\` replaces it, and that ends every live`," terminal and engine session \u2014 do it when you can afford to.",`Run \`${CLI_NAME} doctor\` to see which of the two is actually stale.`,""].join(`
13
- `);async function runUpdateSubcommand(args,deps){let io={spawn:deps?.spawn??spawnSync,stdout:deps?.stdout??process.stdout,stderr:deps?.stderr??process.stderr,exit:deps?.exit??((code)=>process.exit(code)),channel:deps?.channel??{get:()=>preferredReleaseChannel(),remember:rememberReleaseChannel}},parsed=parseUpdateArgs(args);if(parsed.help){printUsage(io.stdout);return}if(parsed.list){if(deps===void 0&&process.stdout.isTTY){let{startVersionsHost}=await import("./chunk-xe6wrg72.js");await startVersionsHost();return}await printVersionList(io);return}let channel=parsed.channel??io.channel.get(),target=parsed.version??(channel===DEFAULT_RELEASE_CHANNEL?void 0:channel),plan=updatePlan(target),switching=parsed.version===void 0&&channel!==channelOf();if(io.stdout.write(`${CLI_NAME} ${CURRENT_VERSION} -> ${target??channel}
13
+ `);async function runUpdateSubcommand(args,deps){let io={spawn:deps?.spawn??spawnSync,stdout:deps?.stdout??process.stdout,stderr:deps?.stderr??process.stderr,exit:deps?.exit??((code)=>process.exit(code)),channel:deps?.channel??{get:()=>preferredReleaseChannel(),remember:rememberReleaseChannel}},parsed=parseUpdateArgs(args);if(parsed.help){printUsage(io.stdout);return}if(parsed.list){if(deps===void 0&&process.stdout.isTTY){let{startVersionsHost}=await import("./chunk-6x66vdkv.js");await startVersionsHost();return}await printVersionList(io);return}let channel=parsed.channel??io.channel.get(),target=parsed.version??(channel===DEFAULT_RELEASE_CHANNEL?void 0:channel),plan=updatePlan(target),switching=parsed.version===void 0&&channel!==channelOf();if(io.stdout.write(`${CLI_NAME} ${CURRENT_VERSION} -> ${target??channel}
14
14
  `),switching)io.stdout.write(`switching channel: ${channelOf()} -> ${channel}
15
15
  `);if(io.stdout.write(`running: ${plan.display}
16
16
  `),await warnBreakingCrossings(parsed.version,channel,io),parsed.dryRun)return;let result=io.spawn(plan.command,plan.args,{stdio:"inherit"});if(result.error){io.stderr.write(`${CLI_NAME} update: failed to run ${plan.command}: ${result.error.message}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{launchTui,trackWelcomeWrite}from"./chunk-6wssap0t.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
2
+ import{launchTui,trackWelcomeWrite}from"./chunk-s69whdc3.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{getGlobalDefaultVendor}from"./chunk-xxz504p6.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-xfz83737.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{spawnSync}from"child_process";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
2
+ import{getGlobalDefaultVendor}from"./chunk-xxz504p6.js";import{CURRENT_VERSION,owningNpmPrefix,repoSlug}from"./chunk-59m9k6q4.js";import{DEFAULT_TASK_VENDOR}from"./chunk-xy8be792.js";import{spawnSync}from"child_process";import{arch,platform,release}from"os";var FEEDBACK_KINDS=["bug","idea","question"],DEFAULT_FEEDBACK_KIND="bug",KIND_LABEL={bug:"bug",idea:"enhancement",question:"question"},MAX_PREFILL_BODY=4000;function isFeedbackKind(value){return FEEDBACK_KINDS.includes(value)}function installKind(){if(import.meta.url.includes("/$bunfs/")||import.meta.url.includes("B:\\~BUN"))return"compiled binary";return owningNpmPrefix()?"npm global":"source or bun"}function defaultEngineId(){try{return getGlobalDefaultVendor()??DEFAULT_TASK_VENDOR}catch{return DEFAULT_TASK_VENDOR}}function environmentBlock(){return["---","Reported from Rove:",`- rove: ${CURRENT_VERSION}`,`- os: ${platform()} ${release()} (${arch()})`,`- install: ${installKind()}`,`- default engine: ${defaultEngineId()}`].join(`
3
3
  `)}function normalizeText(value,label){let trimmed=value.trim();if(!trimmed)throw Error(`${label} is required`);return trimmed}function issueCreateArgv(slug,title,kind){return["issue","create","-R",slug,"--title",title,"--label",KIND_LABEL[kind],"--body-file","-"]}function newIssueUrl(slug,title,body,kind){let prefilled=body.length>MAX_PREFILL_BODY?`${body.slice(0,MAX_PREFILL_BODY)}
4
4
 
5
5
  [truncated]`:body,query=new URLSearchParams({title,body:prefilled,labels:KIND_LABEL[kind]});return`https://github.com/${slug}/issues/new?${query.toString()}`}var ISSUE_URL=/https:\/\/\S+\/issues\/(\d+)/;function submitFeedback(input,deps={}){let title=normalizeText(input.title,"feedback title"),kind=input.kind??DEFAULT_FEEDBACK_KIND,body=`${normalizeText(input.body,"feedback body")}