@sma1lboy/rove 0.9.300-next.367 → 0.9.300-next.369

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 (53) hide show
  1. package/dist/cli/{chunk-ynhqfh71.js → chunk-06mgczvx.js} +1 -1
  2. package/dist/cli/{chunk-nh614cjq.js → chunk-151d804k.js} +2 -2
  3. package/dist/cli/{chunk-tse3x265.js → chunk-2b332gsw.js} +1 -1
  4. package/dist/cli/{chunk-4vz0d43g.js → chunk-32qer0h6.js} +1 -1
  5. package/dist/cli/{chunk-114th2nz.js → chunk-3xvpw4ny.js} +1 -1
  6. package/dist/cli/{chunk-k16bj9w1.js → chunk-401qa5ab.js} +1 -1
  7. package/dist/cli/{chunk-0wan276p.js → chunk-76d3fxr0.js} +1 -1
  8. package/dist/cli/{chunk-7hk7k2c5.js → chunk-793t2e5j.js} +1 -1
  9. package/dist/cli/{chunk-ghk2hyvr.js → chunk-7r723jbb.js} +1 -1
  10. package/dist/cli/{chunk-b8pr4t5v.js → chunk-8fsjvfgy.js} +1 -1
  11. package/dist/cli/{chunk-y30yphzz.js → chunk-8j9wrfs5.js} +1 -1
  12. package/dist/cli/{chunk-jmjj6gmr.js → chunk-9q0xjj8v.js} +1 -1
  13. package/dist/cli/{chunk-vj997agh.js → chunk-b37wje00.js} +1 -1
  14. package/dist/cli/{chunk-43yykcbz.js → chunk-b9nw2q0d.js} +1 -1
  15. package/dist/cli/{chunk-s510zvjm.js → chunk-c4hb49cr.js} +1 -1
  16. package/dist/cli/{chunk-a5zyjr09.js → chunk-c9ah2txg.js} +1 -1
  17. package/dist/cli/{chunk-jgrhxwg1.js → chunk-cfxfvk9y.js} +1 -1
  18. package/dist/cli/{chunk-7ndxm2an.js → chunk-ctdzevfz.js} +1 -1
  19. package/dist/cli/{chunk-d7nf113v.js → chunk-d1fw4atg.js} +1 -1
  20. package/dist/cli/{chunk-s7v4pkse.js → chunk-e0fhqncd.js} +1 -1
  21. package/dist/cli/{chunk-tsba1zh7.js → chunk-e3ts05qm.js} +1 -1
  22. package/dist/cli/{chunk-fpcbpne2.js → chunk-ecmdt54g.js} +1 -1
  23. package/dist/cli/{chunk-wxn4p6qt.js → chunk-eg7zjkdc.js} +2 -2
  24. package/dist/cli/{chunk-31mngae1.js → chunk-fd9mjy8j.js} +1 -1
  25. package/dist/cli/{chunk-ykzv9ams.js → chunk-ffdmp8ss.js} +1 -1
  26. package/dist/cli/{chunk-1nh4dcbn.js → chunk-g6t7dky3.js} +1 -1
  27. package/dist/cli/{chunk-vehnmgje.js → chunk-gdbhb3p1.js} +2 -2
  28. package/dist/cli/{chunk-khg2vjk7.js → chunk-h7kjkf9q.js} +1 -1
  29. package/dist/cli/{chunk-nhbefj4v.js → chunk-jc7a08a3.js} +1 -1
  30. package/dist/cli/{chunk-acgps858.js → chunk-jt9dw3mg.js} +1 -1
  31. package/dist/cli/{chunk-g1mznynq.js → chunk-k4vw5vfs.js} +1 -1
  32. package/dist/cli/{chunk-j9cqzws9.js → chunk-m8yn2vq9.js} +1 -1
  33. package/dist/cli/{chunk-aqk5ytzh.js → chunk-mmn57j33.js} +1 -1
  34. package/dist/cli/{chunk-kahxzmtp.js → chunk-my80whts.js} +1 -1
  35. package/dist/cli/{chunk-s6wxc0k3.js → chunk-myab1021.js} +1 -1
  36. package/dist/cli/{chunk-jkrrp3ry.js → chunk-p01zyx4w.js} +1 -1
  37. package/dist/cli/{chunk-bph6d13s.js → chunk-pjb4rhya.js} +1 -1
  38. package/dist/cli/{chunk-5w2gmjhf.js → chunk-pzwv12fg.js} +1 -1
  39. package/dist/cli/{chunk-dmx1b014.js → chunk-q83xyyk3.js} +1 -1
  40. package/dist/cli/{chunk-9pxck5rv.js → chunk-qjz34hee.js} +1 -1
  41. package/dist/cli/{chunk-09zrkwg0.js → chunk-sjkvhwwa.js} +3 -3
  42. package/dist/cli/{chunk-tj45d4e7.js → chunk-tnbky7rn.js} +1 -1
  43. package/dist/cli/{chunk-krekgf6c.js → chunk-v74bc1hy.js} +1 -1
  44. package/dist/cli/{chunk-6yj9j0ch.js → chunk-w67brnjh.js} +2 -2
  45. package/dist/cli/{chunk-pad5vn1n.js → chunk-xkbcmz38.js} +1 -1
  46. package/dist/cli/{chunk-qv3e7je1.js → chunk-xmrz7y42.js} +1 -1
  47. package/dist/cli/{chunk-rdfc3max.js → chunk-yymz4nfa.js} +1 -1
  48. package/dist/cli/index.js +2 -2
  49. package/dist/cli/rove.js +1 -1
  50. package/dist/web/assets/{index-dQ4Q4-Tu.js → index-_pvPWu1n.js} +34 -34
  51. package/dist/web/assets/{term-mount-CrW9wkpW.js → term-mount-DBxARgF4.js} +1 -1
  52. package/dist/web/index.html +1 -1
  53. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{invokeVerb}from"./chunk-tsba1zh7.js";import"./chunk-ykzv9ams.js";import{defaultApiRuntime,loadContext}from"./chunk-114th2nz.js";import"./chunk-cszxa7he.js";import{ensurePluginEnginesLoaded}from"./chunk-qz2gkej4.js";import"./chunk-zzwmz532.js";import"./chunk-38hnq4aq.js";import"./chunk-93q0k4kk.js";import"./chunk-h9z9x14k.js";import"./chunk-rdfc3max.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-79wejcs5.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-31mngae1.js";import"./chunk-tj45d4e7.js";import"./chunk-csb21bdz.js";import"./chunk-f8tst5yc.js";import"./chunk-hg50sm23.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-2x6s7z8w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-bph6d13s.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-vr26at2f.js";import"./chunk-cqretfmk.js";import"./chunk-9qe575fb.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-kzvqpyt7.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-f8dmdb40.js";import"./chunk-abrs0bnr.js";import"./chunk-34c51wqk.js";import"./chunk-han0d078.js";import{ApiError}from"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-133c884f.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-nw48bskt.js";import"./chunk-ahbw1f8n.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-jh8zqc98.js";import"./chunk-cmp64q4j.js";import"./chunk-54n9h8ne.js";import"./chunk-pe6r1mj2.js";import"./chunk-r2zfp5kg.js";import"./chunk-w7zv47mp.js";import{connectIfRunning}from"./chunk-h6jsrtr6.js";import"./chunk-xq05a8a5.js";import"./chunk-ne55pz7s.js";import{RoveDaemonClient,automationRunNeedsAttention}from"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import{getSavedRepos}from"./chunk-07665jz6.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-xasg8z9e.js";import"./chunk-vkj9q8ns.js";import"./chunk-zc35d8j0.js";import"./chunk-7kysxgbq.js";import"./chunk-f440mkz6.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-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME,readRoveEnv}from"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__commonJS,__toESM}from"./chunk-91sykzqq.js";var require_QRMode=__commonJS((exports,module)=>{module.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var require_QR8bitByte=__commonJS((exports,module)=>{var QRMode=require_QRMode();function QR8bitByte(data){this.mode=QRMode.MODE_8BIT_BYTE,this.data=data}QR8bitByte.prototype={getLength:function(){return this.data.length},write:function(buffer){for(var i=0;i<this.data.length;i++)buffer.put(this.data.charCodeAt(i),8)}};module.exports=QR8bitByte});var require_QRMath=__commonJS((exports,module)=>{var QRMath={glog:function(n){if(n<1)throw Error("glog("+n+")");return QRMath.LOG_TABLE[n]},gexp:function(n){while(n<0)n+=255;while(n>=256)n-=255;return QRMath.EXP_TABLE[n]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(i=0;i<8;i++)QRMath.EXP_TABLE[i]=1<<i;var i;for(i=8;i<256;i++)QRMath.EXP_TABLE[i]=QRMath.EXP_TABLE[i-4]^QRMath.EXP_TABLE[i-5]^QRMath.EXP_TABLE[i-6]^QRMath.EXP_TABLE[i-8];var i;for(i=0;i<255;i++)QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]]=i;var i;module.exports=QRMath});var require_QRPolynomial=__commonJS((exports,module)=>{var QRMath=require_QRMath();function QRPolynomial(num,shift){if(num.length===void 0)throw Error(num.length+"/"+shift);var offset=0;while(offset<num.length&&num[offset]===0)offset++;this.num=Array(num.length-offset+shift);for(var i=0;i<num.length-offset;i++)this.num[i]=num[i+offset]}QRPolynomial.prototype={get:function(index){return this.num[index]},getLength:function(){return this.num.length},multiply:function(e){var num=Array(this.getLength()+e.getLength()-1);for(var i=0;i<this.getLength();i++)for(var j=0;j<e.getLength();j++)num[i+j]^=QRMath.gexp(QRMath.glog(this.get(i))+QRMath.glog(e.get(j)));return new QRPolynomial(num,0)},mod:function(e){if(this.getLength()-e.getLength()<0)return this;var ratio=QRMath.glog(this.get(0))-QRMath.glog(e.get(0)),num=Array(this.getLength());for(var i=0;i<this.getLength();i++)num[i]=this.get(i);for(var x=0;x<e.getLength();x++)num[x]^=QRMath.gexp(QRMath.glog(e.get(x))+ratio);return new QRPolynomial(num,0).mod(e)}};module.exports=QRPolynomial});var require_QRMaskPattern=__commonJS((exports,module)=>{module.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var require_QRUtil=__commonJS((exports,module)=>{var QRMode=require_QRMode(),QRPolynomial=require_QRPolynomial(),QRMath=require_QRMath(),QRMaskPattern=require_QRMaskPattern(),QRUtil={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(data){var d=data<<10;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15)>=0)d^=QRUtil.G15<<QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15);return(data<<10|d)^QRUtil.G15_MASK},getBCHTypeNumber:function(data){var d=data<<12;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)>=0)d^=QRUtil.G18<<QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18);return data<<12|d},getBCHDigit:function(data){var digit=0;while(data!==0)digit++,data>>>=1;return digit},getPatternPosition:function(typeNumber){return QRUtil.PATTERN_POSITION_TABLE[typeNumber-1]},getMask:function(maskPattern,i,j){switch(maskPattern){case QRMaskPattern.PATTERN000:return(i+j)%2===0;case QRMaskPattern.PATTERN001:return i%2===0;case QRMaskPattern.PATTERN010:return j%3===0;case QRMaskPattern.PATTERN011:return(i+j)%3===0;case QRMaskPattern.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2===0;case QRMaskPattern.PATTERN101:return i*j%2+i*j%3===0;case QRMaskPattern.PATTERN110:return(i*j%2+i*j%3)%2===0;case QRMaskPattern.PATTERN111:return(i*j%3+(i+j)%2)%2===0;default:throw Error("bad maskPattern:"+maskPattern)}},getErrorCorrectPolynomial:function(errorCorrectLength){var a=new QRPolynomial([1],0);for(var i=0;i<errorCorrectLength;i++)a=a.multiply(new QRPolynomial([1,QRMath.gexp(i)],0));return a},getLengthInBits:function(mode,type){if(1<=type&&type<10)switch(mode){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:return 8;case QRMode.MODE_KANJI:return 8;default:throw Error("mode:"+mode)}else if(type<27)switch(mode){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw Error("mode:"+mode)}else if(type<41)switch(mode){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw Error("mode:"+mode)}else throw Error("type:"+type)},getLostPoint:function(qrCode){var moduleCount=qrCode.getModuleCount(),lostPoint=0,row=0,col=0;for(row=0;row<moduleCount;row++)for(col=0;col<moduleCount;col++){var sameCount=0,dark=qrCode.isDark(row,col);for(var r=-1;r<=1;r++){if(row+r<0||moduleCount<=row+r)continue;for(var c=-1;c<=1;c++){if(col+c<0||moduleCount<=col+c)continue;if(r===0&&c===0)continue;if(dark===qrCode.isDark(row+r,col+c))sameCount++}}if(sameCount>5)lostPoint+=3+sameCount-5}for(row=0;row<moduleCount-1;row++)for(col=0;col<moduleCount-1;col++){var count=0;if(qrCode.isDark(row,col))count++;if(qrCode.isDark(row+1,col))count++;if(qrCode.isDark(row,col+1))count++;if(qrCode.isDark(row+1,col+1))count++;if(count===0||count===4)lostPoint+=3}for(row=0;row<moduleCount;row++)for(col=0;col<moduleCount-6;col++)if(qrCode.isDark(row,col)&&!qrCode.isDark(row,col+1)&&qrCode.isDark(row,col+2)&&qrCode.isDark(row,col+3)&&qrCode.isDark(row,col+4)&&!qrCode.isDark(row,col+5)&&qrCode.isDark(row,col+6))lostPoint+=40;for(col=0;col<moduleCount;col++)for(row=0;row<moduleCount-6;row++)if(qrCode.isDark(row,col)&&!qrCode.isDark(row+1,col)&&qrCode.isDark(row+2,col)&&qrCode.isDark(row+3,col)&&qrCode.isDark(row+4,col)&&!qrCode.isDark(row+5,col)&&qrCode.isDark(row+6,col))lostPoint+=40;var darkCount=0;for(col=0;col<moduleCount;col++)for(row=0;row<moduleCount;row++)if(qrCode.isDark(row,col))darkCount++;var ratio=Math.abs(100*darkCount/moduleCount/moduleCount-50)/5;return lostPoint+=ratio*10,lostPoint}};module.exports=QRUtil});var require_QRErrorCorrectLevel=__commonJS((exports,module)=>{module.exports={L:1,M:0,Q:3,H:2}});var require_QRRSBlock=__commonJS((exports,module)=>{var QRErrorCorrectLevel=require_QRErrorCorrectLevel();function QRRSBlock(totalCount,dataCount){this.totalCount=totalCount,this.dataCount=dataCount}QRRSBlock.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];QRRSBlock.getRSBlocks=function(typeNumber,errorCorrectLevel){var rsBlock=QRRSBlock.getRsBlockTable(typeNumber,errorCorrectLevel);if(rsBlock===void 0)throw Error("bad rs block @ typeNumber:"+typeNumber+"/errorCorrectLevel:"+errorCorrectLevel);var length=rsBlock.length/3,list=[];for(var i=0;i<length;i++){var count=rsBlock[i*3+0],totalCount=rsBlock[i*3+1],dataCount=rsBlock[i*3+2];for(var j=0;j<count;j++)list.push(new QRRSBlock(totalCount,dataCount))}return list};QRRSBlock.getRsBlockTable=function(typeNumber,errorCorrectLevel){switch(errorCorrectLevel){case QRErrorCorrectLevel.L:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+0];case QRErrorCorrectLevel.M:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+1];case QRErrorCorrectLevel.Q:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+2];case QRErrorCorrectLevel.H:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+3];default:return}};module.exports=QRRSBlock});var require_QRBitBuffer=__commonJS((exports,module)=>{function QRBitBuffer(){this.buffer=[],this.length=0}QRBitBuffer.prototype={get:function(index){var bufIndex=Math.floor(index/8);return(this.buffer[bufIndex]>>>7-index%8&1)==1},put:function(num,length){for(var i=0;i<length;i++)this.putBit((num>>>length-i-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(bit){var bufIndex=Math.floor(this.length/8);if(this.buffer.length<=bufIndex)this.buffer.push(0);if(bit)this.buffer[bufIndex]|=128>>>this.length%8;this.length++}};module.exports=QRBitBuffer});var require_QRCode=__commonJS((exports,module)=>{var QR8bitByte=require_QR8bitByte(),QRUtil=require_QRUtil(),QRPolynomial=require_QRPolynomial(),QRRSBlock=require_QRRSBlock(),QRBitBuffer=require_QRBitBuffer();function QRCode(typeNumber,errorCorrectLevel){this.typeNumber=typeNumber,this.errorCorrectLevel=errorCorrectLevel,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}QRCode.prototype={addData:function(data){var newData=new QR8bitByte(data);this.dataList.push(newData),this.dataCache=null},isDark:function(row,col){if(row<0||this.moduleCount<=row||col<0||this.moduleCount<=col)throw Error(row+","+col);return this.modules[row][col]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var typeNumber=1;for(typeNumber=1;typeNumber<40;typeNumber++){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,this.errorCorrectLevel),buffer=new QRBitBuffer,totalDataCount=0;for(var i=0;i<rsBlocks.length;i++)totalDataCount+=rsBlocks[i].dataCount;for(var x=0;x<this.dataList.length;x++){var data=this.dataList[x];buffer.put(data.mode,4),buffer.put(data.getLength(),QRUtil.getLengthInBits(data.mode,typeNumber)),data.write(buffer)}if(buffer.getLengthInBits()<=totalDataCount*8)break}this.typeNumber=typeNumber}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(test,maskPattern){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var row=0;row<this.moduleCount;row++){this.modules[row]=Array(this.moduleCount);for(var col=0;col<this.moduleCount;col++)this.modules[row][col]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(test,maskPattern),this.typeNumber>=7)this.setupTypeNumber(test);if(this.dataCache===null)this.dataCache=QRCode.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,maskPattern)},setupPositionProbePattern:function(row,col){for(var r=-1;r<=7;r++){if(row+r<=-1||this.moduleCount<=row+r)continue;for(var c=-1;c<=7;c++){if(col+c<=-1||this.moduleCount<=col+c)continue;if(0<=r&&r<=6&&(c===0||c===6)||0<=c&&c<=6&&(r===0||r===6)||2<=r&&r<=4&&2<=c&&c<=4)this.modules[row+r][col+c]=!0;else this.modules[row+r][col+c]=!1}}},getBestMaskPattern:function(){var minLostPoint=0,pattern=0;for(var i=0;i<8;i++){this.makeImpl(!0,i);var lostPoint=QRUtil.getLostPoint(this);if(i===0||minLostPoint>lostPoint)minLostPoint=lostPoint,pattern=i}return pattern},createMovieClip:function(target_mc,instance_name,depth){var qr_mc=target_mc.createEmptyMovieClip(instance_name,depth),cs=1;this.make();for(var row=0;row<this.modules.length;row++){var y=row*cs;for(var col=0;col<this.modules[row].length;col++){var x=col*cs,dark=this.modules[row][col];if(dark)qr_mc.beginFill(0,100),qr_mc.moveTo(x,y),qr_mc.lineTo(x+cs,y),qr_mc.lineTo(x+cs,y+cs),qr_mc.lineTo(x,y+cs),qr_mc.endFill()}}return qr_mc},setupTimingPattern:function(){for(var r=8;r<this.moduleCount-8;r++){if(this.modules[r][6]!==null)continue;this.modules[r][6]=r%2===0}for(var c=8;c<this.moduleCount-8;c++){if(this.modules[6][c]!==null)continue;this.modules[6][c]=c%2===0}},setupPositionAdjustPattern:function(){var pos=QRUtil.getPatternPosition(this.typeNumber);for(var i=0;i<pos.length;i++)for(var j=0;j<pos.length;j++){var row=pos[i],col=pos[j];if(this.modules[row][col]!==null)continue;for(var r=-2;r<=2;r++)for(var c=-2;c<=2;c++)if(Math.abs(r)===2||Math.abs(c)===2||r===0&&c===0)this.modules[row+r][col+c]=!0;else this.modules[row+r][col+c]=!1}},setupTypeNumber:function(test){var bits=QRUtil.getBCHTypeNumber(this.typeNumber),mod;for(var i=0;i<18;i++)mod=!test&&(bits>>i&1)===1,this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=mod;for(var x=0;x<18;x++)mod=!test&&(bits>>x&1)===1,this.modules[x%3+this.moduleCount-8-3][Math.floor(x/3)]=mod},setupTypeInfo:function(test,maskPattern){var data=this.errorCorrectLevel<<3|maskPattern,bits=QRUtil.getBCHTypeInfo(data),mod;for(var v=0;v<15;v++)if(mod=!test&&(bits>>v&1)===1,v<6)this.modules[v][8]=mod;else if(v<8)this.modules[v+1][8]=mod;else this.modules[this.moduleCount-15+v][8]=mod;for(var h=0;h<15;h++)if(mod=!test&&(bits>>h&1)===1,h<8)this.modules[8][this.moduleCount-h-1]=mod;else if(h<9)this.modules[8][15-h-1+1]=mod;else this.modules[8][15-h-1]=mod;this.modules[this.moduleCount-8][8]=!test},mapData:function(data,maskPattern){var inc=-1,row=this.moduleCount-1,bitIndex=7,byteIndex=0;for(var col=this.moduleCount-1;col>0;col-=2){if(col===6)col--;while(!0){for(var c=0;c<2;c++)if(this.modules[row][col-c]===null){var dark=!1;if(byteIndex<data.length)dark=(data[byteIndex]>>>bitIndex&1)===1;var mask=QRUtil.getMask(maskPattern,row,col-c);if(mask)dark=!dark;if(this.modules[row][col-c]=dark,bitIndex--,bitIndex===-1)byteIndex++,bitIndex=7}if(row+=inc,row<0||this.moduleCount<=row){row-=inc,inc=-inc;break}}}}};QRCode.PAD0=236;QRCode.PAD1=17;QRCode.createData=function(typeNumber,errorCorrectLevel,dataList){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,errorCorrectLevel),buffer=new QRBitBuffer;for(var i=0;i<dataList.length;i++){var data=dataList[i];buffer.put(data.mode,4),buffer.put(data.getLength(),QRUtil.getLengthInBits(data.mode,typeNumber)),data.write(buffer)}var totalDataCount=0;for(var x=0;x<rsBlocks.length;x++)totalDataCount+=rsBlocks[x].dataCount;if(buffer.getLengthInBits()>totalDataCount*8)throw Error("code length overflow. ("+buffer.getLengthInBits()+">"+totalDataCount*8+")");if(buffer.getLengthInBits()+4<=totalDataCount*8)buffer.put(0,4);while(buffer.getLengthInBits()%8!==0)buffer.putBit(!1);while(!0){if(buffer.getLengthInBits()>=totalDataCount*8)break;if(buffer.put(QRCode.PAD0,8),buffer.getLengthInBits()>=totalDataCount*8)break;buffer.put(QRCode.PAD1,8)}return QRCode.createBytes(buffer,rsBlocks)};QRCode.createBytes=function(buffer,rsBlocks){var offset=0,maxDcCount=0,maxEcCount=0,dcdata=Array(rsBlocks.length),ecdata=Array(rsBlocks.length);for(var r=0;r<rsBlocks.length;r++){var dcCount=rsBlocks[r].dataCount,ecCount=rsBlocks[r].totalCount-dcCount;maxDcCount=Math.max(maxDcCount,dcCount),maxEcCount=Math.max(maxEcCount,ecCount),dcdata[r]=Array(dcCount);for(var i=0;i<dcdata[r].length;i++)dcdata[r][i]=255&buffer.buffer[i+offset];offset+=dcCount;var rsPoly=QRUtil.getErrorCorrectPolynomial(ecCount),rawPoly=new QRPolynomial(dcdata[r],rsPoly.getLength()-1),modPoly=rawPoly.mod(rsPoly);ecdata[r]=Array(rsPoly.getLength()-1);for(var x=0;x<ecdata[r].length;x++){var modIndex=x+modPoly.getLength()-ecdata[r].length;ecdata[r][x]=modIndex>=0?modPoly.get(modIndex):0}}var totalCodeCount=0;for(var y=0;y<rsBlocks.length;y++)totalCodeCount+=rsBlocks[y].totalCount;var data=Array(totalCodeCount),index=0;for(var z=0;z<maxDcCount;z++)for(var s=0;s<rsBlocks.length;s++)if(z<dcdata[s].length)data[index++]=dcdata[s][z];for(var xx=0;xx<maxEcCount;xx++)for(var t=0;t<rsBlocks.length;t++)if(xx<ecdata[t].length)data[index++]=ecdata[t][xx];return data};module.exports=QRCode});var require_main=__commonJS((exports,module)=>{var QRCode=require_QRCode(),QRErrorCorrectLevel=require_QRErrorCorrectLevel(),black="\x1B[40m \x1B[0m",white="\x1B[47m \x1B[0m",toCell=function(isBlack){return isBlack?black:white},repeat=function(color){return{times:function(count){return Array(count).join(color)}}},fill=function(length,value){var arr=Array(length);for(var i=0;i<length;i++)arr[i]=value;return arr};module.exports={error:QRErrorCorrectLevel.L,generate:function(input,opts,cb){if(typeof opts==="function")cb=opts,opts={};var qrcode=new QRCode(-1,this.error);qrcode.addData(input),qrcode.make();var output="";if(opts&&opts.small){var BLACK=!0,WHITE=!1,moduleCount=qrcode.getModuleCount(),moduleData=qrcode.modules.slice(),oddRow=moduleCount%2===1;if(oddRow)moduleData.push(fill(moduleCount,WHITE));var platte={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},borderTop=repeat(platte.BLACK_WHITE).times(moduleCount+3),borderBottom=repeat(platte.WHITE_BLACK).times(moduleCount+3);output+=borderTop+`
2
+ import{invokeVerb}from"./chunk-e3ts05qm.js";import"./chunk-ffdmp8ss.js";import{defaultApiRuntime,loadContext}from"./chunk-3xvpw4ny.js";import"./chunk-cszxa7he.js";import{ensurePluginEnginesLoaded}from"./chunk-qz2gkej4.js";import"./chunk-zzwmz532.js";import"./chunk-38hnq4aq.js";import"./chunk-93q0k4kk.js";import"./chunk-h9z9x14k.js";import"./chunk-yymz4nfa.js";import"./chunk-rset5pt8.js";import"./chunk-2xsxcdp6.js";import"./chunk-79wejcs5.js";import"./chunk-17e2tgyg.js";import"./chunk-q8ffd1pc.js";import"./chunk-je7egpqh.js";import"./chunk-5mhvjytn.js";import"./chunk-d1vv8xk6.js";import"./chunk-2bgmby1d.js";import"./chunk-psxhek7n.js";import"./chunk-mdx18vtz.js";import"./chunk-fd9mjy8j.js";import"./chunk-tnbky7rn.js";import"./chunk-csb21bdz.js";import"./chunk-f8tst5yc.js";import"./chunk-hg50sm23.js";import"./chunk-y0e28qha.js";import"./chunk-qkehg2c1.js";import"./chunk-2x6s7z8w.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-pjb4rhya.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import"./chunk-vr26at2f.js";import"./chunk-cqretfmk.js";import"./chunk-9qe575fb.js";import"./chunk-y0skz8j9.js";import"./chunk-mqfvzdpr.js";import"./chunk-kzvqpyt7.js";import"./chunk-rxqdw6s5.js";import"./chunk-xe3zr5b9.js";import"./chunk-gzn14mwk.js";import"./chunk-f8dmdb40.js";import"./chunk-abrs0bnr.js";import"./chunk-34c51wqk.js";import"./chunk-han0d078.js";import{ApiError}from"./chunk-jz1kj4sf.js";import"./chunk-v8nbqjwc.js";import"./chunk-ws2q07kb.js";import"./chunk-g9ba25q5.js";import"./chunk-133c884f.js";import"./chunk-catrr0z3.js";import"./chunk-xjrkvksc.js";import"./chunk-tn9gtf18.js";import"./chunk-nw48bskt.js";import"./chunk-ahbw1f8n.js";import"./chunk-sak1tphp.js";import"./chunk-y1xnjx8x.js";import"./chunk-etfh8f4z.js";import"./chunk-zsfyj36g.js";import"./chunk-1feav1w3.js";import"./chunk-jh8zqc98.js";import"./chunk-cmp64q4j.js";import"./chunk-54n9h8ne.js";import"./chunk-pe6r1mj2.js";import"./chunk-r2zfp5kg.js";import"./chunk-w7zv47mp.js";import{connectIfRunning}from"./chunk-h6jsrtr6.js";import"./chunk-xq05a8a5.js";import"./chunk-ne55pz7s.js";import{RoveDaemonClient,automationRunNeedsAttention}from"./chunk-fgb5ev6w.js";import"./chunk-96kvwzj8.js";import{getSavedRepos}from"./chunk-07665jz6.js";import"./chunk-40dgv828.js";import"./chunk-9gctbddn.js";import"./chunk-mg1cas61.js";import"./chunk-xasg8z9e.js";import"./chunk-vkj9q8ns.js";import"./chunk-zc35d8j0.js";import"./chunk-7kysxgbq.js";import"./chunk-f440mkz6.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-rxb0hw1e.js";import"./chunk-tw25g9g5.js";import"./chunk-yt15y085.js";import{resolveDaemonHomeDir}from"./chunk-2z2jwetd.js";import"./chunk-8143k3t6.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import{ROVE_STATE_DIR_BASENAME,readRoveEnv}from"./chunk-nc46gddg.js";import"./chunk-1mp632fj.js";import{__commonJS,__toESM}from"./chunk-91sykzqq.js";var require_QRMode=__commonJS((exports,module)=>{module.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var require_QR8bitByte=__commonJS((exports,module)=>{var QRMode=require_QRMode();function QR8bitByte(data){this.mode=QRMode.MODE_8BIT_BYTE,this.data=data}QR8bitByte.prototype={getLength:function(){return this.data.length},write:function(buffer){for(var i=0;i<this.data.length;i++)buffer.put(this.data.charCodeAt(i),8)}};module.exports=QR8bitByte});var require_QRMath=__commonJS((exports,module)=>{var QRMath={glog:function(n){if(n<1)throw Error("glog("+n+")");return QRMath.LOG_TABLE[n]},gexp:function(n){while(n<0)n+=255;while(n>=256)n-=255;return QRMath.EXP_TABLE[n]},EXP_TABLE:Array(256),LOG_TABLE:Array(256)};for(i=0;i<8;i++)QRMath.EXP_TABLE[i]=1<<i;var i;for(i=8;i<256;i++)QRMath.EXP_TABLE[i]=QRMath.EXP_TABLE[i-4]^QRMath.EXP_TABLE[i-5]^QRMath.EXP_TABLE[i-6]^QRMath.EXP_TABLE[i-8];var i;for(i=0;i<255;i++)QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]]=i;var i;module.exports=QRMath});var require_QRPolynomial=__commonJS((exports,module)=>{var QRMath=require_QRMath();function QRPolynomial(num,shift){if(num.length===void 0)throw Error(num.length+"/"+shift);var offset=0;while(offset<num.length&&num[offset]===0)offset++;this.num=Array(num.length-offset+shift);for(var i=0;i<num.length-offset;i++)this.num[i]=num[i+offset]}QRPolynomial.prototype={get:function(index){return this.num[index]},getLength:function(){return this.num.length},multiply:function(e){var num=Array(this.getLength()+e.getLength()-1);for(var i=0;i<this.getLength();i++)for(var j=0;j<e.getLength();j++)num[i+j]^=QRMath.gexp(QRMath.glog(this.get(i))+QRMath.glog(e.get(j)));return new QRPolynomial(num,0)},mod:function(e){if(this.getLength()-e.getLength()<0)return this;var ratio=QRMath.glog(this.get(0))-QRMath.glog(e.get(0)),num=Array(this.getLength());for(var i=0;i<this.getLength();i++)num[i]=this.get(i);for(var x=0;x<e.getLength();x++)num[x]^=QRMath.gexp(QRMath.glog(e.get(x))+ratio);return new QRPolynomial(num,0).mod(e)}};module.exports=QRPolynomial});var require_QRMaskPattern=__commonJS((exports,module)=>{module.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var require_QRUtil=__commonJS((exports,module)=>{var QRMode=require_QRMode(),QRPolynomial=require_QRPolynomial(),QRMath=require_QRMath(),QRMaskPattern=require_QRMaskPattern(),QRUtil={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(data){var d=data<<10;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15)>=0)d^=QRUtil.G15<<QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15);return(data<<10|d)^QRUtil.G15_MASK},getBCHTypeNumber:function(data){var d=data<<12;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)>=0)d^=QRUtil.G18<<QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18);return data<<12|d},getBCHDigit:function(data){var digit=0;while(data!==0)digit++,data>>>=1;return digit},getPatternPosition:function(typeNumber){return QRUtil.PATTERN_POSITION_TABLE[typeNumber-1]},getMask:function(maskPattern,i,j){switch(maskPattern){case QRMaskPattern.PATTERN000:return(i+j)%2===0;case QRMaskPattern.PATTERN001:return i%2===0;case QRMaskPattern.PATTERN010:return j%3===0;case QRMaskPattern.PATTERN011:return(i+j)%3===0;case QRMaskPattern.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2===0;case QRMaskPattern.PATTERN101:return i*j%2+i*j%3===0;case QRMaskPattern.PATTERN110:return(i*j%2+i*j%3)%2===0;case QRMaskPattern.PATTERN111:return(i*j%3+(i+j)%2)%2===0;default:throw Error("bad maskPattern:"+maskPattern)}},getErrorCorrectPolynomial:function(errorCorrectLength){var a=new QRPolynomial([1],0);for(var i=0;i<errorCorrectLength;i++)a=a.multiply(new QRPolynomial([1,QRMath.gexp(i)],0));return a},getLengthInBits:function(mode,type){if(1<=type&&type<10)switch(mode){case QRMode.MODE_NUMBER:return 10;case QRMode.MODE_ALPHA_NUM:return 9;case QRMode.MODE_8BIT_BYTE:return 8;case QRMode.MODE_KANJI:return 8;default:throw Error("mode:"+mode)}else if(type<27)switch(mode){case QRMode.MODE_NUMBER:return 12;case QRMode.MODE_ALPHA_NUM:return 11;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 10;default:throw Error("mode:"+mode)}else if(type<41)switch(mode){case QRMode.MODE_NUMBER:return 14;case QRMode.MODE_ALPHA_NUM:return 13;case QRMode.MODE_8BIT_BYTE:return 16;case QRMode.MODE_KANJI:return 12;default:throw Error("mode:"+mode)}else throw Error("type:"+type)},getLostPoint:function(qrCode){var moduleCount=qrCode.getModuleCount(),lostPoint=0,row=0,col=0;for(row=0;row<moduleCount;row++)for(col=0;col<moduleCount;col++){var sameCount=0,dark=qrCode.isDark(row,col);for(var r=-1;r<=1;r++){if(row+r<0||moduleCount<=row+r)continue;for(var c=-1;c<=1;c++){if(col+c<0||moduleCount<=col+c)continue;if(r===0&&c===0)continue;if(dark===qrCode.isDark(row+r,col+c))sameCount++}}if(sameCount>5)lostPoint+=3+sameCount-5}for(row=0;row<moduleCount-1;row++)for(col=0;col<moduleCount-1;col++){var count=0;if(qrCode.isDark(row,col))count++;if(qrCode.isDark(row+1,col))count++;if(qrCode.isDark(row,col+1))count++;if(qrCode.isDark(row+1,col+1))count++;if(count===0||count===4)lostPoint+=3}for(row=0;row<moduleCount;row++)for(col=0;col<moduleCount-6;col++)if(qrCode.isDark(row,col)&&!qrCode.isDark(row,col+1)&&qrCode.isDark(row,col+2)&&qrCode.isDark(row,col+3)&&qrCode.isDark(row,col+4)&&!qrCode.isDark(row,col+5)&&qrCode.isDark(row,col+6))lostPoint+=40;for(col=0;col<moduleCount;col++)for(row=0;row<moduleCount-6;row++)if(qrCode.isDark(row,col)&&!qrCode.isDark(row+1,col)&&qrCode.isDark(row+2,col)&&qrCode.isDark(row+3,col)&&qrCode.isDark(row+4,col)&&!qrCode.isDark(row+5,col)&&qrCode.isDark(row+6,col))lostPoint+=40;var darkCount=0;for(col=0;col<moduleCount;col++)for(row=0;row<moduleCount;row++)if(qrCode.isDark(row,col))darkCount++;var ratio=Math.abs(100*darkCount/moduleCount/moduleCount-50)/5;return lostPoint+=ratio*10,lostPoint}};module.exports=QRUtil});var require_QRErrorCorrectLevel=__commonJS((exports,module)=>{module.exports={L:1,M:0,Q:3,H:2}});var require_QRRSBlock=__commonJS((exports,module)=>{var QRErrorCorrectLevel=require_QRErrorCorrectLevel();function QRRSBlock(totalCount,dataCount){this.totalCount=totalCount,this.dataCount=dataCount}QRRSBlock.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];QRRSBlock.getRSBlocks=function(typeNumber,errorCorrectLevel){var rsBlock=QRRSBlock.getRsBlockTable(typeNumber,errorCorrectLevel);if(rsBlock===void 0)throw Error("bad rs block @ typeNumber:"+typeNumber+"/errorCorrectLevel:"+errorCorrectLevel);var length=rsBlock.length/3,list=[];for(var i=0;i<length;i++){var count=rsBlock[i*3+0],totalCount=rsBlock[i*3+1],dataCount=rsBlock[i*3+2];for(var j=0;j<count;j++)list.push(new QRRSBlock(totalCount,dataCount))}return list};QRRSBlock.getRsBlockTable=function(typeNumber,errorCorrectLevel){switch(errorCorrectLevel){case QRErrorCorrectLevel.L:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+0];case QRErrorCorrectLevel.M:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+1];case QRErrorCorrectLevel.Q:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+2];case QRErrorCorrectLevel.H:return QRRSBlock.RS_BLOCK_TABLE[(typeNumber-1)*4+3];default:return}};module.exports=QRRSBlock});var require_QRBitBuffer=__commonJS((exports,module)=>{function QRBitBuffer(){this.buffer=[],this.length=0}QRBitBuffer.prototype={get:function(index){var bufIndex=Math.floor(index/8);return(this.buffer[bufIndex]>>>7-index%8&1)==1},put:function(num,length){for(var i=0;i<length;i++)this.putBit((num>>>length-i-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(bit){var bufIndex=Math.floor(this.length/8);if(this.buffer.length<=bufIndex)this.buffer.push(0);if(bit)this.buffer[bufIndex]|=128>>>this.length%8;this.length++}};module.exports=QRBitBuffer});var require_QRCode=__commonJS((exports,module)=>{var QR8bitByte=require_QR8bitByte(),QRUtil=require_QRUtil(),QRPolynomial=require_QRPolynomial(),QRRSBlock=require_QRRSBlock(),QRBitBuffer=require_QRBitBuffer();function QRCode(typeNumber,errorCorrectLevel){this.typeNumber=typeNumber,this.errorCorrectLevel=errorCorrectLevel,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}QRCode.prototype={addData:function(data){var newData=new QR8bitByte(data);this.dataList.push(newData),this.dataCache=null},isDark:function(row,col){if(row<0||this.moduleCount<=row||col<0||this.moduleCount<=col)throw Error(row+","+col);return this.modules[row][col]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var typeNumber=1;for(typeNumber=1;typeNumber<40;typeNumber++){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,this.errorCorrectLevel),buffer=new QRBitBuffer,totalDataCount=0;for(var i=0;i<rsBlocks.length;i++)totalDataCount+=rsBlocks[i].dataCount;for(var x=0;x<this.dataList.length;x++){var data=this.dataList[x];buffer.put(data.mode,4),buffer.put(data.getLength(),QRUtil.getLengthInBits(data.mode,typeNumber)),data.write(buffer)}if(buffer.getLengthInBits()<=totalDataCount*8)break}this.typeNumber=typeNumber}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(test,maskPattern){this.moduleCount=this.typeNumber*4+17,this.modules=Array(this.moduleCount);for(var row=0;row<this.moduleCount;row++){this.modules[row]=Array(this.moduleCount);for(var col=0;col<this.moduleCount;col++)this.modules[row][col]=null}if(this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(test,maskPattern),this.typeNumber>=7)this.setupTypeNumber(test);if(this.dataCache===null)this.dataCache=QRCode.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);this.mapData(this.dataCache,maskPattern)},setupPositionProbePattern:function(row,col){for(var r=-1;r<=7;r++){if(row+r<=-1||this.moduleCount<=row+r)continue;for(var c=-1;c<=7;c++){if(col+c<=-1||this.moduleCount<=col+c)continue;if(0<=r&&r<=6&&(c===0||c===6)||0<=c&&c<=6&&(r===0||r===6)||2<=r&&r<=4&&2<=c&&c<=4)this.modules[row+r][col+c]=!0;else this.modules[row+r][col+c]=!1}}},getBestMaskPattern:function(){var minLostPoint=0,pattern=0;for(var i=0;i<8;i++){this.makeImpl(!0,i);var lostPoint=QRUtil.getLostPoint(this);if(i===0||minLostPoint>lostPoint)minLostPoint=lostPoint,pattern=i}return pattern},createMovieClip:function(target_mc,instance_name,depth){var qr_mc=target_mc.createEmptyMovieClip(instance_name,depth),cs=1;this.make();for(var row=0;row<this.modules.length;row++){var y=row*cs;for(var col=0;col<this.modules[row].length;col++){var x=col*cs,dark=this.modules[row][col];if(dark)qr_mc.beginFill(0,100),qr_mc.moveTo(x,y),qr_mc.lineTo(x+cs,y),qr_mc.lineTo(x+cs,y+cs),qr_mc.lineTo(x,y+cs),qr_mc.endFill()}}return qr_mc},setupTimingPattern:function(){for(var r=8;r<this.moduleCount-8;r++){if(this.modules[r][6]!==null)continue;this.modules[r][6]=r%2===0}for(var c=8;c<this.moduleCount-8;c++){if(this.modules[6][c]!==null)continue;this.modules[6][c]=c%2===0}},setupPositionAdjustPattern:function(){var pos=QRUtil.getPatternPosition(this.typeNumber);for(var i=0;i<pos.length;i++)for(var j=0;j<pos.length;j++){var row=pos[i],col=pos[j];if(this.modules[row][col]!==null)continue;for(var r=-2;r<=2;r++)for(var c=-2;c<=2;c++)if(Math.abs(r)===2||Math.abs(c)===2||r===0&&c===0)this.modules[row+r][col+c]=!0;else this.modules[row+r][col+c]=!1}},setupTypeNumber:function(test){var bits=QRUtil.getBCHTypeNumber(this.typeNumber),mod;for(var i=0;i<18;i++)mod=!test&&(bits>>i&1)===1,this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=mod;for(var x=0;x<18;x++)mod=!test&&(bits>>x&1)===1,this.modules[x%3+this.moduleCount-8-3][Math.floor(x/3)]=mod},setupTypeInfo:function(test,maskPattern){var data=this.errorCorrectLevel<<3|maskPattern,bits=QRUtil.getBCHTypeInfo(data),mod;for(var v=0;v<15;v++)if(mod=!test&&(bits>>v&1)===1,v<6)this.modules[v][8]=mod;else if(v<8)this.modules[v+1][8]=mod;else this.modules[this.moduleCount-15+v][8]=mod;for(var h=0;h<15;h++)if(mod=!test&&(bits>>h&1)===1,h<8)this.modules[8][this.moduleCount-h-1]=mod;else if(h<9)this.modules[8][15-h-1+1]=mod;else this.modules[8][15-h-1]=mod;this.modules[this.moduleCount-8][8]=!test},mapData:function(data,maskPattern){var inc=-1,row=this.moduleCount-1,bitIndex=7,byteIndex=0;for(var col=this.moduleCount-1;col>0;col-=2){if(col===6)col--;while(!0){for(var c=0;c<2;c++)if(this.modules[row][col-c]===null){var dark=!1;if(byteIndex<data.length)dark=(data[byteIndex]>>>bitIndex&1)===1;var mask=QRUtil.getMask(maskPattern,row,col-c);if(mask)dark=!dark;if(this.modules[row][col-c]=dark,bitIndex--,bitIndex===-1)byteIndex++,bitIndex=7}if(row+=inc,row<0||this.moduleCount<=row){row-=inc,inc=-inc;break}}}}};QRCode.PAD0=236;QRCode.PAD1=17;QRCode.createData=function(typeNumber,errorCorrectLevel,dataList){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,errorCorrectLevel),buffer=new QRBitBuffer;for(var i=0;i<dataList.length;i++){var data=dataList[i];buffer.put(data.mode,4),buffer.put(data.getLength(),QRUtil.getLengthInBits(data.mode,typeNumber)),data.write(buffer)}var totalDataCount=0;for(var x=0;x<rsBlocks.length;x++)totalDataCount+=rsBlocks[x].dataCount;if(buffer.getLengthInBits()>totalDataCount*8)throw Error("code length overflow. ("+buffer.getLengthInBits()+">"+totalDataCount*8+")");if(buffer.getLengthInBits()+4<=totalDataCount*8)buffer.put(0,4);while(buffer.getLengthInBits()%8!==0)buffer.putBit(!1);while(!0){if(buffer.getLengthInBits()>=totalDataCount*8)break;if(buffer.put(QRCode.PAD0,8),buffer.getLengthInBits()>=totalDataCount*8)break;buffer.put(QRCode.PAD1,8)}return QRCode.createBytes(buffer,rsBlocks)};QRCode.createBytes=function(buffer,rsBlocks){var offset=0,maxDcCount=0,maxEcCount=0,dcdata=Array(rsBlocks.length),ecdata=Array(rsBlocks.length);for(var r=0;r<rsBlocks.length;r++){var dcCount=rsBlocks[r].dataCount,ecCount=rsBlocks[r].totalCount-dcCount;maxDcCount=Math.max(maxDcCount,dcCount),maxEcCount=Math.max(maxEcCount,ecCount),dcdata[r]=Array(dcCount);for(var i=0;i<dcdata[r].length;i++)dcdata[r][i]=255&buffer.buffer[i+offset];offset+=dcCount;var rsPoly=QRUtil.getErrorCorrectPolynomial(ecCount),rawPoly=new QRPolynomial(dcdata[r],rsPoly.getLength()-1),modPoly=rawPoly.mod(rsPoly);ecdata[r]=Array(rsPoly.getLength()-1);for(var x=0;x<ecdata[r].length;x++){var modIndex=x+modPoly.getLength()-ecdata[r].length;ecdata[r][x]=modIndex>=0?modPoly.get(modIndex):0}}var totalCodeCount=0;for(var y=0;y<rsBlocks.length;y++)totalCodeCount+=rsBlocks[y].totalCount;var data=Array(totalCodeCount),index=0;for(var z=0;z<maxDcCount;z++)for(var s=0;s<rsBlocks.length;s++)if(z<dcdata[s].length)data[index++]=dcdata[s][z];for(var xx=0;xx<maxEcCount;xx++)for(var t=0;t<rsBlocks.length;t++)if(xx<ecdata[t].length)data[index++]=ecdata[t][xx];return data};module.exports=QRCode});var require_main=__commonJS((exports,module)=>{var QRCode=require_QRCode(),QRErrorCorrectLevel=require_QRErrorCorrectLevel(),black="\x1B[40m \x1B[0m",white="\x1B[47m \x1B[0m",toCell=function(isBlack){return isBlack?black:white},repeat=function(color){return{times:function(count){return Array(count).join(color)}}},fill=function(length,value){var arr=Array(length);for(var i=0;i<length;i++)arr[i]=value;return arr};module.exports={error:QRErrorCorrectLevel.L,generate:function(input,opts,cb){if(typeof opts==="function")cb=opts,opts={};var qrcode=new QRCode(-1,this.error);qrcode.addData(input),qrcode.make();var output="";if(opts&&opts.small){var BLACK=!0,WHITE=!1,moduleCount=qrcode.getModuleCount(),moduleData=qrcode.modules.slice(),oddRow=moduleCount%2===1;if(oddRow)moduleData.push(fill(moduleCount,WHITE));var platte={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},borderTop=repeat(platte.BLACK_WHITE).times(moduleCount+3),borderBottom=repeat(platte.WHITE_BLACK).times(moduleCount+3);output+=borderTop+`
3
3
  `;for(var row=0;row<moduleCount;row+=2){output+=platte.WHITE_ALL;for(var col=0;col<moduleCount;col++)if(moduleData[row][col]===WHITE&&moduleData[row+1][col]===WHITE)output+=platte.WHITE_ALL;else if(moduleData[row][col]===WHITE&&moduleData[row+1][col]===BLACK)output+=platte.WHITE_BLACK;else if(moduleData[row][col]===BLACK&&moduleData[row+1][col]===WHITE)output+=platte.BLACK_WHITE;else output+=platte.BLACK_ALL;output+=platte.WHITE_ALL+`
4
4
  `}if(!oddRow)output+=borderBottom}else{var border=repeat(white).times(qrcode.getModuleCount()+3);output+=border+`
5
5
  `,qrcode.modules.forEach(function(row2){output+=white,output+=row2.map(toCell).join(""),output+=white+`
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{failureHint}from"./chunk-m2tta8xz.js";import{PluginCliError,installPlugin,linkPlugin}from"./chunk-aqk5ytzh.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{buildPaneArgv}from"./chunk-38hnq4aq.js";import{buildPluginEnv}from"./chunk-d1vv8xk6.js";import{currentPluginPlatform,loadPluginRegistry,qualifiedActionId,readPluginManifest,removePluginEntry,savePluginRegistry,supportsPlatform}from"./chunk-psxhek7n.js";import"./chunk-bph6d13s.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import{BUILTIN_MODS,installedBuiltinMods,isBuiltinModId,setBuiltinModInstalled}from"./chunk-v8nbqjwc.js";import{pluginCheckoutDir,pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import{flagValue}from"./chunk-zsfyj36g.js";import"./chunk-jh8zqc98.js";import"./chunk-cmp64q4j.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import{errorMessage}from"./chunk-9gctbddn.js";import"./chunk-yt15y085.js";import{defaultDaemonSocketPath}from"./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";import{readFileSync,rmSync}from"fs";function builtinModRows(homeDir){let installed=new Set(installedBuiltinMods(homeDir));return BUILTIN_MODS.map((mod)=>`${mod.id} first-party ${installed.has(mod.id)?"installed":"not installed"} (${mod.description})`)}function setBuiltinMod(id,install,homeDir){let was=installedBuiltinMods(homeDir).includes(id);if(setBuiltinModInstalled(id,install,homeDir),install)return was?`${id} is already installed`:`installed ${id}`;return was?`uninstalled ${id} (its data stays on disk; reinstall picks it up)`:`${id} is not installed`}var CLI_NAME=ROVE_PRODUCT_NAME;function printUsage(out){out.write([`usage: ${CLI_NAME} plugin <command>`,""," install <owner/repo[/subdir]> [--yes] [--ref <rev>] clone from GitHub, preview, build, register"," install kanban | issues install a first-party mod (uninstall keeps its data)"," link <dir> register a local plugin directory (dev)"," list first-party mods, installed + linked plugins"," search [query] browse the marketplace (GitHub topic rove-plugin)"," outdated check GitHub-installed plugins against upstream"," update <id\u2026> | --all [--yes] reinstall stale plugins from GitHub"," enable <id> | disable <id> toggle a plugin without unregistering it"," unlink <id> unregister a linked plugin (files untouched)"," uninstall <id-or-spec> unregister + remove the managed checkout"," config-dir <id> print the plugin's config directory"," log <id> [-n <count>] tail the plugin's command-run log"," action list [--plugin <id>] declared actions"," action invoke <plugin-id.action-id> run an action now"," pane open <plugin-id.pane-id> [--task <task-id>] open a plugin pane as a terminal tab (JSON:"," clients \u2014 0 = no attached UI performed the split)","","Marketplace: https://github.com/topics/rove-plugin",""].join(`
2
+ import{failureHint}from"./chunk-m2tta8xz.js";import{PluginCliError,installPlugin,linkPlugin}from"./chunk-mmn57j33.js";import{resolvePluginBinPath}from"./chunk-b0ssvpht.js";import{buildPaneArgv}from"./chunk-38hnq4aq.js";import{buildPluginEnv}from"./chunk-d1vv8xk6.js";import{currentPluginPlatform,loadPluginRegistry,qualifiedActionId,readPluginManifest,removePluginEntry,savePluginRegistry,supportsPlatform}from"./chunk-psxhek7n.js";import"./chunk-pjb4rhya.js";import{SUBCOMMAND_VERBS}from"./chunk-z35jsvwk.js";import{BUILTIN_MODS,installedBuiltinMods,isBuiltinModId,setBuiltinModInstalled}from"./chunk-v8nbqjwc.js";import{pluginCheckoutDir,pluginConfigDir,pluginLogPath}from"./chunk-ws2q07kb.js";import"./chunk-tn9gtf18.js";import{flagValue}from"./chunk-zsfyj36g.js";import"./chunk-jh8zqc98.js";import"./chunk-cmp64q4j.js";import"./chunk-w7zv47mp.js";import"./chunk-96kvwzj8.js";import{errorMessage}from"./chunk-9gctbddn.js";import"./chunk-yt15y085.js";import{defaultDaemonSocketPath}from"./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";import{readFileSync,rmSync}from"fs";function builtinModRows(homeDir){let installed=new Set(installedBuiltinMods(homeDir));return BUILTIN_MODS.map((mod)=>`${mod.id} first-party ${installed.has(mod.id)?"installed":"not installed"} (${mod.description})`)}function setBuiltinMod(id,install,homeDir){let was=installedBuiltinMods(homeDir).includes(id);if(setBuiltinModInstalled(id,install,homeDir),install)return was?`${id} is already installed`:`installed ${id}`;return was?`uninstalled ${id} (its data stays on disk; reinstall picks it up)`:`${id} is not installed`}var CLI_NAME=ROVE_PRODUCT_NAME;function printUsage(out){out.write([`usage: ${CLI_NAME} plugin <command>`,""," install <owner/repo[/subdir]> [--yes] [--ref <rev>] clone from GitHub, preview, build, register"," install kanban | issues install a first-party mod (uninstall keeps its data)"," link <dir> register a local plugin directory (dev)"," list first-party mods, installed + linked plugins"," search [query] browse the marketplace (GitHub topic rove-plugin)"," outdated check GitHub-installed plugins against upstream"," update <id\u2026> | --all [--yes] reinstall stale plugins from GitHub"," enable <id> | disable <id> toggle a plugin without unregistering it"," unlink <id> unregister a linked plugin (files untouched)"," uninstall <id-or-spec> unregister + remove the managed checkout"," config-dir <id> print the plugin's config directory"," log <id> [-n <count>] tail the plugin's command-run log"," action list [--plugin <id>] declared actions"," action invoke <plugin-id.action-id> run an action now"," pane open <plugin-id.pane-id> [--task <task-id>] open a plugin pane as a terminal tab (JSON:"," clients \u2014 0 = no attached UI performed the split)","","Marketplace: https://github.com/topics/rove-plugin",""].join(`
3
3
  `))}function loadAll(){return loadPluginRegistry().plugins.map((entry)=>{try{return{entry,manifest:readPluginManifest(entry.root).manifest}}catch{return{entry,manifest:void 0}}})}function requireEntry(id){let entry=loadPluginRegistry().plugins.find((p)=>p.id===id);if(!entry)throw new PluginCliError(`no plugin registered as \`${id}\`; see \`${CLI_NAME} plugin list\``);return entry}function listPlugins(){for(let row of builtinModRows())console.log(row);let all=loadAll();if(all.length===0){console.log(`no other plugins installed. Try: ${CLI_NAME} plugin install <owner/repo> \u2014 browse the \`rove-plugin\` GitHub topic.`);return}for(let{entry,manifest}of all){let state=entry.enabled?"enabled":"disabled",kind=entry.source.kind==="link"?`linked ${entry.root}`:entry.source.spec,broken=manifest?"":" [manifest unreadable]";console.log(`${entry.id} v${entry.version} ${state} (${kind})${broken}`)}}function setEnabled(id,enabled){let entry=requireEntry(id),registry=loadPluginRegistry();savePluginRegistry({plugins:registry.plugins.map((p)=>p.id===id?{...entry,enabled}:p)}),console.log(`${enabled?"enabled":"disabled"} ${id}`)}function unlink(id){let entry=requireEntry(id);if(entry.source.kind!=="link")throw new PluginCliError(`\`${id}\` is a GitHub install; use uninstall`);savePluginRegistry(removePluginEntry(loadPluginRegistry(),id)),console.log(`unlinked ${id} (files untouched at ${entry.root})`)}function uninstall(idOrSpec){let registry=loadPluginRegistry(),entry=registry.plugins.find((p)=>p.id===idOrSpec||p.source.kind==="github"&&p.source.spec===idOrSpec);if(!entry)throw new PluginCliError(`no plugin registered as \`${idOrSpec}\``);if(entry.source.kind==="link")throw new PluginCliError(`\`${entry.id}\` is linked; use unlink`);savePluginRegistry(removePluginEntry(registry,entry.id)),rmSync(pluginCheckoutDir(entry.id),{recursive:!0,force:!0}),console.log(`uninstalled ${entry.id} (config/state kept under ~/.rove/plugins/${entry.id}/)`)}function listActions(pluginFilter){for(let{entry,manifest}of loadAll()){if(!manifest||pluginFilter&&entry.id!==pluginFilter)continue;for(let action of manifest.actions)console.log(`${qualifiedActionId(entry.id,action.id)} ${action.title}`)}}function findByLongestPluginPrefix(qualified,options,findItem){for(let{entry,manifest}of loadAll().filter(({entry:entry2,manifest:manifest2})=>Boolean(manifest2&&(!options.enabledOnly||entry2.enabled)&&qualified.startsWith(`${entry2.id}.`))).sort((a,b)=>b.entry.id.length-a.entry.id.length)){let item=findItem(manifest,qualified.slice(entry.id.length+1));if(item!==void 0)return{entry,manifest,item}}return}function assertPlatformSupported(label,item,manifest){if(supportsPlatform(item,manifest,currentPluginPlatform()))return;let declared=(item.platforms??manifest.platforms??[]).join(", ");throw new PluginCliError(`\`${label}\` is not supported on this platform (declares ${declared})`)}function invokeAction(qualified,extraArgs){let hit=findByLongestPluginPrefix(qualified,{enabledOnly:!0},(manifest,actionId)=>manifest.actions.find((a)=>a.id===actionId));if(!hit)throw new PluginCliError(`no action \`${qualified}\`; see \`${CLI_NAME} plugin action list\``);assertPlatformSupported(qualified,hit.item,hit.manifest);let action=hit.item,[cmd,...args]=[...action.command,...extraArgs],res=spawnSync(cmd,args,{cwd:hit.entry.root,stdio:"inherit",env:buildPluginEnv({socketPath:defaultDaemonSocketPath(),binPath:resolvePluginBinPath(),pluginId:hit.entry.id,pluginRoot:hit.entry.root,extra:{ROVE_PLUGIN_ACTION_ID:action.id,ROVE_PLUGIN_INVOKE_CWD:process.cwd()}})});process.exit(res.status??1)}function resolvePaneQualified(qualified){let hit=findByLongestPluginPrefix(qualified,{enabledOnly:!1},(manifest,entrypoint)=>manifest.panes.find((p)=>p.id===entrypoint));if(!hit)throw new PluginCliError(`no pane \`${qualified}\`; see \`${CLI_NAME} plugin list\``);return{pluginId:hit.entry.id,entrypoint:hit.item.id}}async function openPane(pluginId,entrypoint,taskFlag){let loaded=loadAll().find(({entry})=>entry.id===pluginId);if(!loaded?.manifest)throw new PluginCliError(`no plugin \`${pluginId}\` (or its manifest is unreadable)`);if(!loaded.entry.enabled)throw new PluginCliError(`\`${pluginId}\` is disabled`);let pane=loaded.manifest.panes.find((p)=>p.id===entrypoint);if(!pane)throw new PluginCliError(`no pane \`${entrypoint}\` in \`${pluginId}\`; declare it under [[panes]]`);assertPlatformSupported(`${pluginId}.${pane.id}`,pane,loaded.manifest);let{openDaemonSession,resolveActiveTaskId}=await import("./chunk-xk1ghdf1.js"),session=await openDaemonSession({mode:"start"});try{let taskId=taskFlag??await resolveActiveTaskId(session.client);if(!taskId)throw new PluginCliError("no active task; pass --task <id>");let argv=buildPaneArgv(loaded.entry.id,loaded.entry.root,pane,{socketPath:defaultDaemonSocketPath(),binPath:resolvePluginBinPath(),taskId}),reply=await session.client.request("tab.open",{taskId,argv,title:pane.title,placement:pane.placement});console.log(JSON.stringify({...reply,ok:!0,pane:`${pluginId}.${pane.id}`,taskId,title:pane.title}))}finally{session.close()}}function tailLog(id,count){requireEntry(id);let text;try{text=readFileSync(pluginLogPath(id),"utf8")}catch{console.log("(no runs logged yet)");return}let lines=text.trimEnd().split(`
4
- `);for(let line of lines.slice(-count))console.log(line)}async function runPluginSubcommand(rest){let[command,...args]=rest;if(command!==void 0&&!SUBCOMMAND_VERBS.plugin.includes(command)){let isHelp=command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}try{switch(command){case"install":{let spec=args.find((a)=>!a.startsWith("-"));if(!spec)throw new PluginCliError("install needs <owner/repo[/subdir]>");if(isBuiltinModId(spec)){console.log(setBuiltinMod(spec,!0));return}await installPlugin(spec,{yes:args.includes("--yes"),ref:flagValue(args,"--ref")});return}case"link":{if(!args[0])throw new PluginCliError("link needs a directory");linkPlugin(args[0]);return}case"list":listPlugins();return;case"search":{let{searchMarketplace}=await import("./chunk-094cgrcc.js");await searchMarketplace(args.find((a)=>!a.startsWith("-")));return}case"outdated":{let{printOutdated}=await import("./chunk-krekgf6c.js");printOutdated();return}case"update":{let{updatePlugins}=await import("./chunk-krekgf6c.js");await updatePlugins(args.filter((a)=>!a.startsWith("-")),{all:args.includes("--all"),yes:args.includes("--yes")});return}case"enable":case"disable":{if(!args[0])throw new PluginCliError(`${command} needs a plugin id`);if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],command==="enable"));else setEnabled(args[0],command==="enable");return}case"unlink":{if(!args[0])throw new PluginCliError("unlink needs a plugin id");unlink(args[0]);return}case"uninstall":{if(!args[0])throw new PluginCliError("uninstall needs a plugin id or owner/repo spec");if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],!1));else uninstall(args[0]);return}case"config-dir":{if(!args[0])throw new PluginCliError("config-dir needs a plugin id");requireEntry(args[0]),console.log(pluginConfigDir(args[0]));return}case"log":{if(!args[0])throw new PluginCliError("log needs a plugin id");tailLog(args[0],Number.parseInt(flagValue(args,"-n")??"20",10)||20);return}case"pane":{let[sub,...paneArgs]=args;if(sub==="open"){let positional=paneArgs.find((a)=>!a.startsWith("-")&&a!==flagValue(paneArgs,"--task")),pluginId=flagValue(paneArgs,"--plugin"),entrypoint=flagValue(paneArgs,"--entrypoint");if(!pluginId||!entrypoint){if(!positional)throw new PluginCliError("pane open needs <plugin-id.pane-id> (or --plugin <id> --entrypoint <pane-id>) [--task <task-id>]");({pluginId,entrypoint}=resolvePaneQualified(positional))}await openPane(pluginId,entrypoint,flagValue(paneArgs,"--task"));return}printUsage(process.stderr),process.exit(2);return}case"action":{let[sub,...actionArgs]=args;if(sub==="list"){listActions(flagValue(actionArgs,"--plugin"));return}if(sub==="invoke"){if(!actionArgs[0])throw new PluginCliError("action invoke needs <plugin-id.action-id>");invokeAction(actionArgs[0],actionArgs.slice(1));return}printUsage(process.stderr),process.exit(2);return}default:{let isHelp=command===void 0||command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}}}catch(err){if(err instanceof PluginCliError)console.error(`${CLI_NAME} plugin: ${err.message}
4
+ `);for(let line of lines.slice(-count))console.log(line)}async function runPluginSubcommand(rest){let[command,...args]=rest;if(command!==void 0&&!SUBCOMMAND_VERBS.plugin.includes(command)){let isHelp=command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}try{switch(command){case"install":{let spec=args.find((a)=>!a.startsWith("-"));if(!spec)throw new PluginCliError("install needs <owner/repo[/subdir]>");if(isBuiltinModId(spec)){console.log(setBuiltinMod(spec,!0));return}await installPlugin(spec,{yes:args.includes("--yes"),ref:flagValue(args,"--ref")});return}case"link":{if(!args[0])throw new PluginCliError("link needs a directory");linkPlugin(args[0]);return}case"list":listPlugins();return;case"search":{let{searchMarketplace}=await import("./chunk-094cgrcc.js");await searchMarketplace(args.find((a)=>!a.startsWith("-")));return}case"outdated":{let{printOutdated}=await import("./chunk-v74bc1hy.js");printOutdated();return}case"update":{let{updatePlugins}=await import("./chunk-v74bc1hy.js");await updatePlugins(args.filter((a)=>!a.startsWith("-")),{all:args.includes("--all"),yes:args.includes("--yes")});return}case"enable":case"disable":{if(!args[0])throw new PluginCliError(`${command} needs a plugin id`);if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],command==="enable"));else setEnabled(args[0],command==="enable");return}case"unlink":{if(!args[0])throw new PluginCliError("unlink needs a plugin id");unlink(args[0]);return}case"uninstall":{if(!args[0])throw new PluginCliError("uninstall needs a plugin id or owner/repo spec");if(isBuiltinModId(args[0]))console.log(setBuiltinMod(args[0],!1));else uninstall(args[0]);return}case"config-dir":{if(!args[0])throw new PluginCliError("config-dir needs a plugin id");requireEntry(args[0]),console.log(pluginConfigDir(args[0]));return}case"log":{if(!args[0])throw new PluginCliError("log needs a plugin id");tailLog(args[0],Number.parseInt(flagValue(args,"-n")??"20",10)||20);return}case"pane":{let[sub,...paneArgs]=args;if(sub==="open"){let positional=paneArgs.find((a)=>!a.startsWith("-")&&a!==flagValue(paneArgs,"--task")),pluginId=flagValue(paneArgs,"--plugin"),entrypoint=flagValue(paneArgs,"--entrypoint");if(!pluginId||!entrypoint){if(!positional)throw new PluginCliError("pane open needs <plugin-id.pane-id> (or --plugin <id> --entrypoint <pane-id>) [--task <task-id>]");({pluginId,entrypoint}=resolvePaneQualified(positional))}await openPane(pluginId,entrypoint,flagValue(paneArgs,"--task"));return}printUsage(process.stderr),process.exit(2);return}case"action":{let[sub,...actionArgs]=args;if(sub==="list"){listActions(flagValue(actionArgs,"--plugin"));return}if(sub==="invoke"){if(!actionArgs[0])throw new PluginCliError("action invoke needs <plugin-id.action-id>");invokeAction(actionArgs[0],actionArgs.slice(1));return}printUsage(process.stderr),process.exit(2);return}default:{let isHelp=command===void 0||command==="help"||command==="--help"||command==="-h";if(printUsage(isHelp?process.stdout:process.stderr),!isHelp)process.exit(2);return}}}catch(err){if(err instanceof PluginCliError)console.error(`${CLI_NAME} plugin: ${err.message}
5
5
  Run ${CLI_NAME} plugin --help for usage.`),process.exit(1);console.error(`${CLI_NAME} plugin: ${errorMessage(err)}
6
6
  ${failureHint(err,CLI_NAME)}`),process.exit(1)}}export{runPluginSubcommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-bph6d13s.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
2
+ import{BREAKING_VERSIONS,CURRENT_VERSION,PACKAGE_NAME,UPDATE_COMMAND,UPDATE_SCRIPT_URL,ZH_NOTES_ASSET,breakingVersionsCrossed,channelOf,checkLatestVersion,compareSemver,fetchReleaseNotes,fetchReleaseNotesRange,fetchReleaseSummaries,isNewerSemver,owningNpmPrefix,recommendedGlobalInstallCommand,releasePageUrl,repoSlug,updateCommandFor}from"./chunk-pjb4rhya.js";import"./chunk-8143k3t6.js";import"./chunk-zt7wfnva.js";import"./chunk-g6wb8p4p.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{updateCommandFor,repoSlug,releasePageUrl,recommendedGlobalInstallCommand,owningNpmPrefix,isNewerSemver,fetchReleaseSummaries,fetchReleaseNotesRange,fetchReleaseNotes,compareSemver,checkLatestVersion,channelOf,breakingVersionsCrossed,ZH_NOTES_ASSET,UPDATE_SCRIPT_URL,UPDATE_COMMAND,PACKAGE_NAME,CURRENT_VERSION,BREAKING_VERSIONS};
@@ -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):()=>{},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}
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 fs from"fs/promises";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 isRemoteRepoKey(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(isRemoteRepoKey(repo.repo)||isRemoteRepoKey(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 GIB=1073741824,LOW_DISK_BYTES=5*GIB,LOW_DISK_RECOVER_BYTES=8*GIB,LOW_DISK_REPEAT_MS=21600000,DEFAULT_LOW_DISK_TICK_MS=300000;async function readDisk(path){try{let[st,fsInfo]=await Promise.all([fs.stat(path),fs.statfs(path)]);return{device:st.dev,freeBytes:fsInfo.bavail*fsInfo.bsize}}catch{return null}}function formatGb(bytes){return`${(bytes/GIB).toFixed(1)} GB`}function createLowDiskCheck(deps){let notifiedAt=new Map;return async()=>{let owned=deps.listTasks().filter((task)=>!task.deletion&&workspaceCapabilities(task).ownsDirectory),disks=new Map;for(let path of trackedWorktreePaths(owned).keys()){let reading=await deps.readDisk(path);if(!reading)continue;let disk=disks.get(reading.device);if(disk)disk.worktrees++;else disks.set(reading.device,{freeBytes:reading.freeBytes,worktrees:1})}let now=deps.now();for(let[device,disk]of disks){if(disk.freeBytes>=LOW_DISK_RECOVER_BYTES)notifiedAt.delete(device);if(disk.freeBytes>=LOW_DISK_BYTES)continue;let last=notifiedAt.get(device);if(last!==void 0&&now-last<LOW_DISK_REPEAT_MS)continue;notifiedAt.set(device,now);let count=disk.worktrees===1?"1 task worktree is":`${disk.worktrees} task worktrees are`;deps.publish({title:`Low disk space: ${formatGb(disk.freeBytes)} free`,body:`${count} on this disk. \`rove api worktree-reclaim --merged --dry-run\` lists finished ones to free.`,kind:"needs_input",at:now,source:"low-disk"})}}}function startLowDiskWatch(deps,tickMs,gate){return startTicker({name:"low-disk",tickMs,gate,immediate:!0,run:createLowDiskCheck(deps)})}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 isRemoteRepoKey2(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(isRemoteRepoKey2(task.repo)||isRemoteRepoKey2(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}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),stopLowDiskWatch=startLowDiskWatch({listTasks:()=>orch.listTasks(),readDisk,publish:(n)=>bus.publish("notice.event",n),now:Date.now},options.lowDiskTickMs??DEFAULT_LOW_DISK_TICK_MS,()=>hasSubscribersFor("notice.event")),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,stopLowDiskWatch,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))}}}];var SUBSYSTEM="task-deletion-audit";function originText(origin,task){let parts=[];if(origin)parts.push(`client=${origin.clientId}`);if(origin?.requestedBy)parts.push(`by=${origin.requestedBy.taskId}::${origin.requestedBy.tabId}`);let dispatcher=task?.dispatcher;if(dispatcher)parts.push(`spawnedBy=${dispatcher.taskId}::${dispatcher.tabId}`);return parts.length>0?` (${parts.join(" ")})`:""}function subjectText(task,taskId){if(!task)return`task ${taskId}`;let bits=[`task ${taskId}`,`title=${JSON.stringify(task.title)}`,`kind=${task.kind}`];if(task.branch)bits.push(`branch=${task.branch}`);if(task.worktreePath)bits.push(`worktree=${task.worktreePath}`);return bits.join(" ")}function auditDeletionRequested(taskId,task,origin,opts={}){logDaemonInfo(SUBSYSTEM,`requested ${subjectText(task,taskId)} force=${opts.force===!0} deleteBranch=${opts.deleteBranch===!0}${originText(origin,task)}`)}function auditDeletionRemoved(taskId,task){logDaemonInfo(SUBSYSTEM,`removed ${subjectText(task,taskId)}`)}function auditDeletionBranchKept(taskId,branch,reason){logDaemonInfo(SUBSYSTEM,`branch kept task ${taskId} branch=${branch} \u2014 git refused the delete: ${reason.replace(/\s+/g," ").trim()}. Nothing else will remove it; \`git branch -D ${branch}\` does, and drops its reflog with it.`)}function auditDeletionFailed(taskId,task,err){let cause=err instanceof Error?err:Error(String(err)),context=`failed ${subjectText(task,taskId)} \u2014 session teardown and activity/inbox cleanup ALREADY ran; the worktree directory and task entry remain. Reason: `,line=Error(`${context}${cause.message}`);line.name=cause.name;let frames=cause.stack?.split(`
21
21
  `).slice(1)??[];if(frames.length>0)line.stack=[`${line.name}: ${line.message}`,...frames].join(`