@sma1lboy/rove 0.9.262 → 0.9.264

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 (117) hide show
  1. package/dist/cli/{chunk-qc376zm1.js → chunk-02f0matw.js} +1 -1
  2. package/dist/cli/{chunk-31h3d4re.js → chunk-04zwds1k.js} +2 -2
  3. package/dist/cli/{chunk-qk9tgve2.js → chunk-09sfrqkr.js} +1 -1
  4. package/dist/cli/{chunk-5js4agdd.js → chunk-0rrmz6k6.js} +1 -1
  5. package/dist/cli/{chunk-7nqzg7h6.js → chunk-1cmcaarg.js} +1 -1
  6. package/dist/cli/{chunk-kqdq5g1x.js → chunk-1gxb0bd3.js} +1 -1
  7. package/dist/cli/{chunk-b7w3q5f1.js → chunk-26mf16v9.js} +1 -1
  8. package/dist/cli/{chunk-zsth2jk6.js → chunk-27k612fg.js} +1 -1
  9. package/dist/cli/{chunk-65kx9ksj.js → chunk-2amvwfah.js} +3 -3
  10. package/dist/cli/{chunk-karefnj8.js → chunk-2bq6877b.js} +3 -3
  11. package/dist/cli/{chunk-esk09jfb.js → chunk-2cbzp9t1.js} +1 -1
  12. package/dist/cli/{chunk-4t1dvw2h.js → chunk-2k0f7837.js} +1 -1
  13. package/dist/cli/{chunk-7697syt8.js → chunk-3ac75tqw.js} +1 -1
  14. package/dist/cli/{chunk-m5kxc6m3.js → chunk-3khq4hhf.js} +3 -3
  15. package/dist/cli/{chunk-36y93k92.js → chunk-3zjdbdwy.js} +1 -1
  16. package/dist/cli/{chunk-5a3c9fnd.js → chunk-4kzqv6rq.js} +1 -1
  17. package/dist/cli/{chunk-kkzmdwfr.js → chunk-4tb0h00q.js} +2 -2
  18. package/dist/cli/{chunk-4ntrjm11.js → chunk-59g5tbc7.js} +1 -1
  19. package/dist/cli/{chunk-mgx6w27b.js → chunk-5p8ws3an.js} +1 -1
  20. package/dist/cli/{chunk-c7j05xps.js → chunk-5v02t4pz.js} +1 -1
  21. package/dist/cli/{chunk-m2qajv9v.js → chunk-61nwtmyh.js} +1 -1
  22. package/dist/cli/{chunk-fg55dc4s.js → chunk-65333881.js} +1 -1
  23. package/dist/cli/{chunk-hrgd7vws.js → chunk-69dz852g.js} +1 -1
  24. package/dist/cli/{chunk-53p99fe7.js → chunk-6h9bd4z6.js} +1 -1
  25. package/dist/cli/{chunk-68xcxsbg.js → chunk-7hr9k9kg.js} +1 -1
  26. package/dist/cli/chunk-7kwk5kxn.js +3 -0
  27. package/dist/cli/{chunk-sp9cmc7p.js → chunk-7y7v9x3n.js} +1 -1
  28. package/dist/cli/{chunk-y7nkgnzn.js → chunk-8021rerp.js} +15 -15
  29. package/dist/cli/chunk-8gzqcx6x.js +3 -0
  30. package/dist/cli/{chunk-rh5vxymy.js → chunk-8vkma6c4.js} +1 -1
  31. package/dist/cli/{chunk-rcqckj34.js → chunk-9axe1by1.js} +1 -1
  32. package/dist/cli/{chunk-edrw4tby.js → chunk-9ykm0dcz.js} +1 -1
  33. package/dist/cli/{chunk-nwevnc6k.js → chunk-a2epp2ad.js} +1 -1
  34. package/dist/cli/{chunk-dc3n6nf7.js → chunk-ax5c2qmv.js} +1 -1
  35. package/dist/cli/{chunk-0wy0w6jd.js → chunk-b2h6jfrg.js} +1 -1
  36. package/dist/cli/{chunk-73fw8277.js → chunk-b3vz95wb.js} +1 -1
  37. package/dist/cli/{chunk-xywr9nj6.js → chunk-bc72rgkm.js} +1 -1
  38. package/dist/cli/{chunk-zqfvxz1g.js → chunk-bmk52w06.js} +1 -1
  39. package/dist/cli/{chunk-t228jyth.js → chunk-bnv1mm5h.js} +1 -1
  40. package/dist/cli/{chunk-8e8y2m0b.js → chunk-bqscpzvh.js} +1 -1
  41. package/dist/cli/{chunk-gc3f7zbs.js → chunk-bs04j8rh.js} +1 -1
  42. package/dist/cli/{chunk-db61d8dz.js → chunk-c2cj2bye.js} +1 -1
  43. package/dist/cli/{chunk-7t9q7k4d.js → chunk-c6kw0s9a.js} +1 -1
  44. package/dist/cli/{chunk-z5evzj1q.js → chunk-cy1c8jmz.js} +1 -1
  45. package/dist/cli/{chunk-rrqjk4rn.js → chunk-cyq9pwqz.js} +5 -5
  46. package/dist/cli/{chunk-06wk3r66.js → chunk-dxk134bp.js} +1 -1
  47. package/dist/cli/{chunk-yxsec1f1.js → chunk-e5489crb.js} +2 -2
  48. package/dist/cli/{chunk-syqbc3a3.js → chunk-f6tqc1cc.js} +1 -1
  49. package/dist/cli/{chunk-k71h719j.js → chunk-fdexrh6h.js} +1 -1
  50. package/dist/cli/{chunk-1bfcy0n9.js → chunk-g0kq5ng6.js} +1 -1
  51. package/dist/cli/{chunk-4tgz542w.js → chunk-gzj9nk7k.js} +1 -1
  52. package/dist/cli/chunk-har2ggte.js +2 -0
  53. package/dist/cli/{chunk-74e3k701.js → chunk-hgf4cz78.js} +1 -1
  54. package/dist/cli/{chunk-6an1v8vq.js → chunk-hpakh6zr.js} +1 -1
  55. package/dist/cli/{chunk-vznz1yf0.js → chunk-hv9qjnvj.js} +1 -1
  56. package/dist/cli/{chunk-dq3m7rhj.js → chunk-jaqa26ab.js} +1 -1
  57. package/dist/cli/{chunk-zt0dmqn5.js → chunk-jt994bhe.js} +1 -1
  58. package/dist/cli/{chunk-951xzbsm.js → chunk-jwqdhbe9.js} +1 -1
  59. package/dist/cli/chunk-k04s1eb9.js +2 -0
  60. package/dist/cli/{chunk-6ks6s8b2.js → chunk-kmgheesn.js} +2 -2
  61. package/dist/cli/{chunk-1x6yahf1.js → chunk-mccgj97d.js} +1 -1
  62. package/dist/cli/{chunk-37v3752z.js → chunk-md3m1qts.js} +1 -1
  63. package/dist/cli/{chunk-c3g1bfn6.js → chunk-mhbc490p.js} +1 -1
  64. package/dist/cli/chunk-mn134nhp.js +2 -0
  65. package/dist/cli/chunk-mtvcw6te.js +55 -0
  66. package/dist/cli/{chunk-n8p8b9qd.js → chunk-n22008wk.js} +1 -1
  67. package/dist/cli/{chunk-wqcs5mz0.js → chunk-n7vtv1rw.js} +1 -1
  68. package/dist/cli/{chunk-traxwyfz.js → chunk-ns2f9b6r.js} +1 -1
  69. package/dist/cli/{chunk-jc2jwy0j.js → chunk-nze6pmm7.js} +1 -1
  70. package/dist/cli/chunk-pjae8k74.js +70 -0
  71. package/dist/cli/{chunk-m3773n9n.js → chunk-qga9xd2f.js} +1 -1
  72. package/dist/cli/{chunk-3ds88mym.js → chunk-qy4tma9z.js} +1 -1
  73. package/dist/cli/chunk-r240tf5j.js +3 -0
  74. package/dist/cli/{chunk-r7p1dhrv.js → chunk-re15t5r1.js} +1 -1
  75. package/dist/cli/{chunk-h5znx9v9.js → chunk-rtcevh2t.js} +1 -1
  76. package/dist/cli/{chunk-xwynw0t0.js → chunk-s0x0yw8x.js} +1 -1
  77. package/dist/cli/chunk-sgngkkp3.js +2 -0
  78. package/dist/cli/chunk-spt9e3zk.js +31 -0
  79. package/dist/cli/{chunk-fq3s9q62.js → chunk-szjgjrar.js} +1 -1
  80. package/dist/cli/{chunk-r1epx453.js → chunk-tgfn5ykb.js} +1 -1
  81. package/dist/cli/{chunk-z3qhpthz.js → chunk-tjj9bt7n.js} +1 -1
  82. package/dist/cli/{chunk-nnda6138.js → chunk-va5mjg68.js} +1 -1
  83. package/dist/cli/{chunk-6nw0s0ab.js → chunk-vjew0mqm.js} +1 -1
  84. package/dist/cli/{chunk-q55z079p.js → chunk-vkbgm18p.js} +1 -1
  85. package/dist/cli/{chunk-qwhajjyw.js → chunk-vy6q9m4e.js} +3 -3
  86. package/dist/cli/{chunk-1pfsfpcg.js → chunk-wkv4aw6c.js} +1 -1
  87. package/dist/cli/{chunk-2676cb62.js → chunk-ws4cg819.js} +1 -1
  88. package/dist/cli/{chunk-2cwzyxcs.js → chunk-wv5hvxcd.js} +2 -2
  89. package/dist/cli/{chunk-y5wt6c1s.js → chunk-xjvrcx07.js} +1 -1
  90. package/dist/cli/{chunk-p0ycfqw2.js → chunk-y1a673xg.js} +1 -1
  91. package/dist/cli/{chunk-tykb6n4m.js → chunk-y5p9wm83.js} +1 -1
  92. package/dist/cli/{chunk-gc78tfn9.js → chunk-ykp6efg0.js} +1 -1
  93. package/dist/cli/{chunk-8k04kxqq.js → chunk-ytw1twda.js} +1 -1
  94. package/dist/cli/{chunk-nxdm60xy.js → chunk-yyjskza5.js} +1 -1
  95. package/dist/cli/index.js +4 -4
  96. package/dist/cli/pty-host-node.mjs +1 -0
  97. package/dist/cli/rove.js +1 -1
  98. package/dist/completions/rove.bash +1 -1
  99. package/dist/completions/rove.fish +1 -1
  100. package/dist/completions/rove.zsh +1 -1
  101. package/dist/skills/rove/SKILL.md +1 -1
  102. package/dist/skills/rove/references/api-flags.md +7 -5
  103. package/dist/web/assets/index-CWRZWwbL.css +1 -0
  104. package/dist/web/assets/{index-BLCf4p1g.js → index-apAwSqkl.js} +28 -28
  105. package/dist/web/index.html +2 -2
  106. package/package.json +3 -3
  107. package/dist/cli/chunk-1dzr3fba.js +0 -2
  108. package/dist/cli/chunk-95gk3twe.js +0 -3
  109. package/dist/cli/chunk-ephcyh6v.js +0 -3
  110. package/dist/cli/chunk-h0pg8e0g.js +0 -70
  111. package/dist/cli/chunk-k21hb0rj.js +0 -41
  112. package/dist/cli/chunk-m3nfbnxy.js +0 -2
  113. package/dist/cli/chunk-q07r6hf7.js +0 -3
  114. package/dist/cli/chunk-r03m4san.js +0 -2
  115. package/dist/cli/chunk-tj1w7jb7.js +0 -31
  116. package/dist/cli/chunk-tx4b93j7.js +0 -2
  117. package/dist/web/assets/index-CdjFB6v7.css +0 -1
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{BUNDLED_THEME_JSONS,parseRgbLiteral}from"./chunk-z3zaa155.js";import{loadStateFile,patchStateFile}from"./chunk-g4281a0g.js";import{kvStatePath}from"./chunk-prqeddy7.js";import{DEFAULT_LOCALE,isLocaleId}from"./chunk-q07r6hf7.js";import{RGBA as RGBA3}from"@opentui/core";import{RGBA}from"@opentui/core";var BREATH_TICKS=30,SPEED_MIN=0.2,SPEED_SWING=0.9333333333333333,INK_FLOOR=0.3;function breathLevel(tick){return 0.5-0.5*Math.cos(2*Math.PI*tick/BREATH_TICKS)}function breathPhase(tick){let wave=tick/2-BREATH_TICKS/(4*Math.PI)*Math.sin(2*Math.PI*tick/BREATH_TICKS);return SPEED_MIN*tick+SPEED_SWING*wave}function breathGlyph(frames,tick){let index=Math.floor(breathPhase(tick)+0.000000001)%frames.length;return frames[index]??frames[0]??""}function mixInk(accent,muted,share){if(accent.intent!=="rgb"||muted.intent!=="rgb")return accent;let[ar,ag,ab,aa]=accent.toInts(),[mr,mg,mb]=muted.toInts(),mix=(a,m)=>Math.round(m+(a-m)*share);return RGBA.fromInts(mix(ar,mr),mix(ag,mg),mix(ab,mb),aa)}function breathColor(accent,muted,tick){return mixInk(accent,muted,INK_FLOOR+(1-INK_FLOOR)*breathLevel(tick))}var toLinear=(v)=>v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4,toGamma=(v)=>v<=0.0031308?12.92*v:1.055*v**0.4166666666666667-0.055;function toOklch(color){let[r,g,b]=color.toInts().map((v)=>toLinear(v/255)),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b),L=0.2104542553*l+0.793617785*m-0.0040720468*s,A=1.9779984951*l-2.428592205*m+0.4505937099*s,B=0.0259040371*l+0.7827717662*m-0.808675766*s;return{l:L,c:Math.hypot(A,B),h:Math.atan2(B,A)}}function linearRgb({l:L,c,h}){let A=c*Math.cos(h),B=c*Math.sin(h),l=(L+0.3963377774*A+0.2158037573*B)**3,m=(L-0.1055613458*A-0.0638541728*B)**3,s=(L-0.0894841775*A-1.291485548*B)**3;return[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s]}function fromOklch(color,alpha){let ch=(v)=>Math.round(Math.min(1,Math.max(0,toGamma(v)))*255),[r,g,b]=linearRgb(color);return RGBA.fromInts(ch(r),ch(g),ch(b),alpha)}function turnHue(accent,deg,lightness=1,chroma=1){if(accent.intent!=="rgb")return accent;let base=toOklch(accent),turned={l:base.l*lightness,c:base.c*chroma,h:base.h+deg*Math.PI/180};return fromOklch(turned,accent.toInts()[3])}var inGamut=(color)=>linearRgb(color).every((v)=>v>=-0.0001&&v<=1.0001);function inkAtHue(deg,lightness,chroma,alpha=255){let h=deg*Math.PI/180,c=chroma;while(c>0&&!inGamut({l:lightness,c,h}))c-=0.005;return fromOklch({l:lightness,c:Math.max(0,c),h},alpha)}function oklchCusp(deg){let key=Math.round(deg)%360,hit=cuspCache.get(key);if(hit)return hit;let h=key*Math.PI/180,best={l:1,c:0};for(let l=0.2;l<=1;l+=0.01){let lo=0,hi=0.4;for(let i=0;i<16;i++){let mid=(lo+hi)/2;if(inGamut({l,c:mid,h}))lo=mid;else hi=mid}if(lo>best.c)best={l,c:lo}}return cuspCache.set(key,best),best}var cuspCache=new Map;import{RGBA as RGBA2}from"@opentui/core";var HOST_TEXT_MIN_CONTRAST=4.5;function srgbChannelToLinear(c){let v=c/255;return v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4}function relativeLuminance([r,g,b]){return 0.2126*srgbChannelToLinear(r)+0.7152*srgbChannelToLinear(g)+0.0722*srgbChannelToLinear(b)}function contrastRatioTriplet(fg,bg){let l1=relativeLuminance(fg),l2=relativeLuminance(bg),lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+0.05)/(darker+0.05)}function rgbToHsl([r,g,b]){let rn=r/255,gn=g/255,bn=b/255,max=Math.max(rn,gn,bn),min=Math.min(rn,gn,bn),l=(max+min)/2;if(max===min)return[0,0,l];let d=max-min,s=l>0.5?d/(2-max-min):d/(max+min),h;if(max===rn)h=((gn-bn)/d+(gn<bn?6:0))*60;else if(max===gn)h=((bn-rn)/d+2)*60;else h=((rn-gn)/d+4)*60;return[h,s,l]}function hslToRgb(h,s,l){if(s===0){let v=Math.round(l*255);return[v,v,v]}let q=l<0.5?l*(1+s):l+s-l*s,p=2*l-q,channel=(t)=>{let tn=t;if(tn<0)tn+=1;if(tn>1)tn-=1;let c=tn<0.16666666666666666?p+(q-p)*6*tn:tn<0.5?q:tn<0.6666666666666666?p+(q-p)*(0.6666666666666666-tn)*6:p;return Math.round(c*255)};return[channel(h/360+0.3333333333333333),channel(h/360),channel(h/360-0.3333333333333333)]}var MID_HOST_LUMINANCE=0.5;function ensureContrast(fg,bg,minRatio=HOST_TEXT_MIN_CONTRAST){let fgInts=fg.toInts(),bgInts=bg.toInts(),fgTriplet=[fgInts[0],fgInts[1],fgInts[2]],bgTriplet=[bgInts[0],bgInts[1],bgInts[2]];if(contrastRatioTriplet(fgTriplet,bgTriplet)>=minRatio)return fg;let[h,s,l]=rgbToHsl(fgTriplet),lighten=relativeLuminance(bgTriplet)<=MID_HOST_LUMINANCE,at=(lightness)=>contrastRatioTriplet(hslToRgb(h,s,lightness),bgTriplet),lo=lighten?l:0,hi=lighten?1:l;for(let i=0;i<32;i++){let mid=(lo+hi)/2;if(at(mid)>=minRatio)if(lighten)hi=mid;else lo=mid;else if(lighten)lo=mid;else hi=mid}let[r,g,b]=hslToRgb(h,s,lighten?hi:lo);return RGBA2.fromInts(r,g,b,fgInts[3])}var BUNDLED_THEMES=BUNDLED_THEME_JSONS,DEFAULT_THEME="claude";function hasBundledTheme(name){return Boolean(BUNDLED_THEMES[name])}var THEME_MODE_PREFERENCES=["dark","light","auto"],DEFAULT_THEME_MODE="dark";function resolveThemeMode(preference,detected){return preference==="auto"?detected??"dark":preference}var FOCUS_ACCENT_SLOTS=["primary","success","info"];function resolveTheme(theme,mode="dark"){let defs=theme.defs??{};function resolve(c,chain=[]){if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA3.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA3.fromHex(c);let rgb=parseRgbLiteral(c);if(rgb)return RGBA3.fromInts(rgb.r,rgb.g,rgb.b,rgb.a);if(chain.includes(c))return RGBA3.fromInts(0,0,0);let next=defs[c]??theme.theme[c];if(next===void 0)return RGBA3.fromInts(0,0,0);return resolve(next,[...chain,c])}return resolve(c[mode],chain)}let out={};for(let[k,v]of Object.entries(theme.theme))out[k]=resolve(v);let text=out.text??RGBA3.fromHex("#ffffff"),background=out.background??RGBA3.fromHex("#000000");return{...{primary:out.primary??text,secondary:out.secondary??text,accent:out.accent??out.primary??text,error:out.error??text,warning:out.warning??text,warningOnHost:out.warning??text,success:out.success??text,info:out.info??text,text,textMuted:out.textMuted??text,background,backgroundPanel:out.backgroundPanel??background,backgroundElement:out.backgroundElement??background,backgroundMenu:out.backgroundMenu??out.backgroundElement??background,backgroundDialog:out.backgroundDialog??out.backgroundPanel??background,border:out.border??text,borderActive:out.borderActive??out.border??text,borderSubtle:out.borderSubtle??out.border??text,diffAdded:out.diffAdded??out.success??text,diffRemoved:out.diffRemoved??out.error??text,diffContext:out.diffContext??out.textMuted??text,diffHunkHeader:out.diffHunkHeader??out.textMuted??text,diffAddedBg:out.diffAddedBg??background,diffRemovedBg:out.diffRemovedBg??background,selectedListItemText:out.selectedListItemText??background},...out}}function applyDisplayOverlay(base,focusAccent,transparentBackground,hostBackground){let v={...base,focusAccent:base[focusAccent]??base.primary,warningOnHost:base.warning};if(!transparentBackground)return v;let[backgroundR,backgroundG,backgroundB]=base.background.toInts(),[panelR,panelG,panelB]=base.backgroundPanel.toInts(),transparent={...v,background:RGBA3.fromInts(backgroundR,backgroundG,backgroundB,0),backgroundPanel:RGBA3.fromInts(panelR,panelG,panelB,0)};if(!hostBackground)return transparent;return{...transparent,text:ensureContrast(transparent.text,hostBackground),textMuted:ensureContrast(transparent.textMuted,hostBackground),warningOnHost:ensureContrast(transparent.warning,hostBackground)}}function diffInks(theme,colorblind){let added=(ink)=>colorblind?turnHue(ink,60,1,0.71):ink;return{added:added(theme.diffAdded),removed:theme.diffRemoved,addedBg:added(theme.diffAddedBg),removedBg:theme.diffRemovedBg}}import{readFileSync}from"fs";var LOCALE_KEY="locale";function defaultTransparentBackground(platform=process.platform){return platform!=="win32"}function readPersistedUiPrefs(fallbackTheme,isKnownTheme=hasBundledTheme){try{let parsed=JSON.parse(readFileSync(kvStatePath(),"utf8")),theme=typeof parsed.activeTheme==="string"&&isKnownTheme(parsed.activeTheme)?parsed.activeTheme:fallbackTheme,themeMode=THEME_MODE_PREFERENCES.includes(parsed.themeMode)?parsed.themeMode:DEFAULT_THEME_MODE,transparent=typeof parsed.transparentBackground==="boolean"?parsed.transparentBackground:defaultTransparentBackground(),focusAccent=typeof parsed.focusAccent==="string"&&FOCUS_ACCENT_SLOTS.includes(parsed.focusAccent)?parsed.focusAccent:null,locale=isLocaleId(parsed[LOCALE_KEY])?parsed[LOCALE_KEY]:DEFAULT_LOCALE;return{theme,themeMode,transparent,focusAccent,locale}}catch{return{theme:fallbackTheme,themeMode:DEFAULT_THEME_MODE,transparent:defaultTransparentBackground(),focusAccent:null,locale:DEFAULT_LOCALE}}}var TERMINAL_TABS_PREFIX="terminalTabs.";function terminalTabsKey(taskId){return`${TERMINAL_TABS_PREFIX}${taskId}`}var stateFileTabsPersistence={load(){let out={};for(let[key,value]of Object.entries(loadStateFile())){if(!key.startsWith(TERMINAL_TABS_PREFIX))continue;let state=value;if(state&&Array.isArray(state.tabs))out[key.slice(TERMINAL_TABS_PREFIX.length)]=state}return out},save(changes){let patch={};for(let[taskId,state]of Object.entries(changes))patch[terminalTabsKey(taskId)]=state??void 0;patchStateFile(patch)}};
2
+ import{BUNDLED_THEME_JSONS,parseRgbLiteral}from"./chunk-z3zaa155.js";import{loadStateFile,patchStateFile}from"./chunk-g4281a0g.js";import{kvStatePath}from"./chunk-prqeddy7.js";import{DEFAULT_LOCALE,isLocaleId}from"./chunk-7kwk5kxn.js";import{RGBA as RGBA3}from"@opentui/core";import{RGBA}from"@opentui/core";var BREATH_TICKS=30,SPEED_MIN=0.2,SPEED_SWING=0.9333333333333333,INK_FLOOR=0.3;function breathLevel(tick){return 0.5-0.5*Math.cos(2*Math.PI*tick/BREATH_TICKS)}function breathPhase(tick){let wave=tick/2-BREATH_TICKS/(4*Math.PI)*Math.sin(2*Math.PI*tick/BREATH_TICKS);return SPEED_MIN*tick+SPEED_SWING*wave}function breathGlyph(frames,tick){let index=Math.floor(breathPhase(tick)+0.000000001)%frames.length;return frames[index]??frames[0]??""}function mixInk(accent,muted,share){if(accent.intent!=="rgb"||muted.intent!=="rgb")return accent;let[ar,ag,ab,aa]=accent.toInts(),[mr,mg,mb]=muted.toInts(),mix=(a,m)=>Math.round(m+(a-m)*share);return RGBA.fromInts(mix(ar,mr),mix(ag,mg),mix(ab,mb),aa)}function breathColor(accent,muted,tick){return mixInk(accent,muted,INK_FLOOR+(1-INK_FLOOR)*breathLevel(tick))}var toLinear=(v)=>v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4,toGamma=(v)=>v<=0.0031308?12.92*v:1.055*v**0.4166666666666667-0.055;function toOklch(color){let[r,g,b]=color.toInts().map((v)=>toLinear(v/255)),l=Math.cbrt(0.4122214708*r+0.5363325363*g+0.0514459929*b),m=Math.cbrt(0.2119034982*r+0.6806995451*g+0.1073969566*b),s=Math.cbrt(0.0883024619*r+0.2817188376*g+0.6299787005*b),L=0.2104542553*l+0.793617785*m-0.0040720468*s,A=1.9779984951*l-2.428592205*m+0.4505937099*s,B=0.0259040371*l+0.7827717662*m-0.808675766*s;return{l:L,c:Math.hypot(A,B),h:Math.atan2(B,A)}}function linearRgb({l:L,c,h}){let A=c*Math.cos(h),B=c*Math.sin(h),l=(L+0.3963377774*A+0.2158037573*B)**3,m=(L-0.1055613458*A-0.0638541728*B)**3,s=(L-0.0894841775*A-1.291485548*B)**3;return[4.0767416621*l-3.3077115913*m+0.2309699292*s,-1.2684380046*l+2.6097574011*m-0.3413193965*s,-0.0041960863*l-0.7034186147*m+1.707614701*s]}function fromOklch(color,alpha){let ch=(v)=>Math.round(Math.min(1,Math.max(0,toGamma(v)))*255),[r,g,b]=linearRgb(color);return RGBA.fromInts(ch(r),ch(g),ch(b),alpha)}function turnHue(accent,deg,lightness=1,chroma=1){if(accent.intent!=="rgb")return accent;let base=toOklch(accent),turned={l:base.l*lightness,c:base.c*chroma,h:base.h+deg*Math.PI/180};return fromOklch(turned,accent.toInts()[3])}var inGamut=(color)=>linearRgb(color).every((v)=>v>=-0.0001&&v<=1.0001);function inkAtHue(deg,lightness,chroma,alpha=255){let h=deg*Math.PI/180,c=chroma;while(c>0&&!inGamut({l:lightness,c,h}))c-=0.005;return fromOklch({l:lightness,c:Math.max(0,c),h},alpha)}function oklchCusp(deg){let key=Math.round(deg)%360,hit=cuspCache.get(key);if(hit)return hit;let h=key*Math.PI/180,best={l:1,c:0};for(let l=0.2;l<=1;l+=0.01){let lo=0,hi=0.4;for(let i=0;i<16;i++){let mid=(lo+hi)/2;if(inGamut({l,c:mid,h}))lo=mid;else hi=mid}if(lo>best.c)best={l,c:lo}}return cuspCache.set(key,best),best}var cuspCache=new Map;import{RGBA as RGBA2}from"@opentui/core";var HOST_TEXT_MIN_CONTRAST=4.5;function srgbChannelToLinear(c){let v=c/255;return v<=0.04045?v/12.92:((v+0.055)/1.055)**2.4}function relativeLuminance([r,g,b]){return 0.2126*srgbChannelToLinear(r)+0.7152*srgbChannelToLinear(g)+0.0722*srgbChannelToLinear(b)}function contrastRatioTriplet(fg,bg){let l1=relativeLuminance(fg),l2=relativeLuminance(bg),lighter=Math.max(l1,l2),darker=Math.min(l1,l2);return(lighter+0.05)/(darker+0.05)}function rgbToHsl([r,g,b]){let rn=r/255,gn=g/255,bn=b/255,max=Math.max(rn,gn,bn),min=Math.min(rn,gn,bn),l=(max+min)/2;if(max===min)return[0,0,l];let d=max-min,s=l>0.5?d/(2-max-min):d/(max+min),h;if(max===rn)h=((gn-bn)/d+(gn<bn?6:0))*60;else if(max===gn)h=((bn-rn)/d+2)*60;else h=((rn-gn)/d+4)*60;return[h,s,l]}function hslToRgb(h,s,l){if(s===0){let v=Math.round(l*255);return[v,v,v]}let q=l<0.5?l*(1+s):l+s-l*s,p=2*l-q,channel=(t)=>{let tn=t;if(tn<0)tn+=1;if(tn>1)tn-=1;let c=tn<0.16666666666666666?p+(q-p)*6*tn:tn<0.5?q:tn<0.6666666666666666?p+(q-p)*(0.6666666666666666-tn)*6:p;return Math.round(c*255)};return[channel(h/360+0.3333333333333333),channel(h/360),channel(h/360-0.3333333333333333)]}var MID_HOST_LUMINANCE=0.5;function ensureContrast(fg,bg,minRatio=HOST_TEXT_MIN_CONTRAST){let fgInts=fg.toInts(),bgInts=bg.toInts(),fgTriplet=[fgInts[0],fgInts[1],fgInts[2]],bgTriplet=[bgInts[0],bgInts[1],bgInts[2]];if(contrastRatioTriplet(fgTriplet,bgTriplet)>=minRatio)return fg;let[h,s,l]=rgbToHsl(fgTriplet),lighten=relativeLuminance(bgTriplet)<=MID_HOST_LUMINANCE,at=(lightness)=>contrastRatioTriplet(hslToRgb(h,s,lightness),bgTriplet),lo=lighten?l:0,hi=lighten?1:l;for(let i=0;i<32;i++){let mid=(lo+hi)/2;if(at(mid)>=minRatio)if(lighten)hi=mid;else lo=mid;else if(lighten)lo=mid;else hi=mid}let[r,g,b]=hslToRgb(h,s,lighten?hi:lo);return RGBA2.fromInts(r,g,b,fgInts[3])}var BUNDLED_THEMES=BUNDLED_THEME_JSONS,DEFAULT_THEME="claude";function hasBundledTheme(name){return Boolean(BUNDLED_THEMES[name])}var THEME_MODE_PREFERENCES=["dark","light","auto"],DEFAULT_THEME_MODE="dark";function resolveThemeMode(preference,detected){return preference==="auto"?detected??"dark":preference}var FOCUS_ACCENT_SLOTS=["primary","success","info"];function resolveTheme(theme,mode="dark"){let defs=theme.defs??{};function resolve(c,chain=[]){if(typeof c==="string"){if(c==="transparent"||c==="none")return RGBA3.fromInts(0,0,0,0);if(c.startsWith("#"))return RGBA3.fromHex(c);let rgb=parseRgbLiteral(c);if(rgb)return RGBA3.fromInts(rgb.r,rgb.g,rgb.b,rgb.a);if(chain.includes(c))return RGBA3.fromInts(0,0,0);let next=defs[c]??theme.theme[c];if(next===void 0)return RGBA3.fromInts(0,0,0);return resolve(next,[...chain,c])}return resolve(c[mode],chain)}let out={};for(let[k,v]of Object.entries(theme.theme))out[k]=resolve(v);let text=out.text??RGBA3.fromHex("#ffffff"),background=out.background??RGBA3.fromHex("#000000");return{...{primary:out.primary??text,secondary:out.secondary??text,accent:out.accent??out.primary??text,error:out.error??text,warning:out.warning??text,warningOnHost:out.warning??text,success:out.success??text,info:out.info??text,text,textMuted:out.textMuted??text,background,backgroundPanel:out.backgroundPanel??background,backgroundElement:out.backgroundElement??background,backgroundMenu:out.backgroundMenu??out.backgroundElement??background,backgroundDialog:out.backgroundDialog??out.backgroundPanel??background,border:out.border??text,borderActive:out.borderActive??out.border??text,borderSubtle:out.borderSubtle??out.border??text,diffAdded:out.diffAdded??out.success??text,diffRemoved:out.diffRemoved??out.error??text,diffContext:out.diffContext??out.textMuted??text,diffHunkHeader:out.diffHunkHeader??out.textMuted??text,diffAddedBg:out.diffAddedBg??background,diffRemovedBg:out.diffRemovedBg??background,selectedListItemText:out.selectedListItemText??background},...out}}function applyDisplayOverlay(base,focusAccent,transparentBackground,hostBackground){let v={...base,focusAccent:base[focusAccent]??base.primary,warningOnHost:base.warning};if(!transparentBackground)return v;let[backgroundR,backgroundG,backgroundB]=base.background.toInts(),[panelR,panelG,panelB]=base.backgroundPanel.toInts(),transparent={...v,background:RGBA3.fromInts(backgroundR,backgroundG,backgroundB,0),backgroundPanel:RGBA3.fromInts(panelR,panelG,panelB,0)};if(!hostBackground)return transparent;return{...transparent,text:ensureContrast(transparent.text,hostBackground),textMuted:ensureContrast(transparent.textMuted,hostBackground),warningOnHost:ensureContrast(transparent.warning,hostBackground)}}function diffInks(theme,colorblind){let added=(ink)=>colorblind?turnHue(ink,60,1,0.71):ink;return{added:added(theme.diffAdded),removed:theme.diffRemoved,addedBg:added(theme.diffAddedBg),removedBg:theme.diffRemovedBg}}import{readFileSync}from"fs";var LOCALE_KEY="locale";function defaultTransparentBackground(platform=process.platform){return platform!=="win32"}function readPersistedUiPrefs(fallbackTheme,isKnownTheme=hasBundledTheme){try{let parsed=JSON.parse(readFileSync(kvStatePath(),"utf8")),theme=typeof parsed.activeTheme==="string"&&isKnownTheme(parsed.activeTheme)?parsed.activeTheme:fallbackTheme,themeMode=THEME_MODE_PREFERENCES.includes(parsed.themeMode)?parsed.themeMode:DEFAULT_THEME_MODE,transparent=typeof parsed.transparentBackground==="boolean"?parsed.transparentBackground:defaultTransparentBackground(),focusAccent=typeof parsed.focusAccent==="string"&&FOCUS_ACCENT_SLOTS.includes(parsed.focusAccent)?parsed.focusAccent:null,locale=isLocaleId(parsed[LOCALE_KEY])?parsed[LOCALE_KEY]:DEFAULT_LOCALE;return{theme,themeMode,transparent,focusAccent,locale}}catch{return{theme:fallbackTheme,themeMode:DEFAULT_THEME_MODE,transparent:defaultTransparentBackground(),focusAccent:null,locale:DEFAULT_LOCALE}}}var TERMINAL_TABS_PREFIX="terminalTabs.";function terminalTabsKey(taskId){return`${TERMINAL_TABS_PREFIX}${taskId}`}var stateFileTabsPersistence={load(){let out={};for(let[key,value]of Object.entries(loadStateFile())){if(!key.startsWith(TERMINAL_TABS_PREFIX))continue;let state=value;if(state&&Array.isArray(state.tabs))out[key.slice(TERMINAL_TABS_PREFIX.length)]=state}return out},save(changes){let patch={};for(let[taskId,state]of Object.entries(changes))patch[terminalTabsKey(taskId)]=state??void 0;patchStateFile(patch)}};
3
3
  export{breathGlyph,mixInk,breathColor,toOklch,turnHue,inkAtHue,oklchCusp,relativeLuminance,ensureContrast,BUNDLED_THEMES,DEFAULT_THEME,THEME_MODE_PREFERENCES,DEFAULT_THEME_MODE,resolveThemeMode,FOCUS_ACCENT_SLOTS,resolveTheme,applyDisplayOverlay,diffInks,LOCALE_KEY,defaultTransparentBackground,readPersistedUiPrefs,TERMINAL_TABS_PREFIX,terminalTabsKey,stateFileTabsPersistence};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{argvToParams,booleanFlagsOf,callVerb,errorBody,errorEnvelope,executeVerb,paramsToFlags,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-va5mjg68.js";import"./chunk-cyq9pwqz.js";import"./chunk-s0x0yw8x.js";import"./chunk-fdexrh6h.js";import"./chunk-ns2f9b6r.js";import"./chunk-3zjdbdwy.js";import"./chunk-j11hzmwy.js";import"./chunk-re15t5r1.js";import"./chunk-17e2tgyg.js";import"./chunk-cbc1h345.js";import"./chunk-jjv7xem7.js";import"./chunk-4hestsjp.js";import"./chunk-3ac75tqw.js";import"./chunk-2bgmby1d.js";import"./chunk-41x1hrqe.js";import"./chunk-5mhvjytn.js";import"./chunk-a2epp2ad.js";import"./chunk-atn06ncf.js";import"./chunk-65333881.js";import"./chunk-qkehg2c1.js";import"./chunk-gzj9nk7k.js";import"./chunk-1cmcaarg.js";import"./chunk-4kzqv6rq.js";import"./chunk-ampdybqg.js";import"./chunk-sak1tphp.js";import"./chunk-1gxb0bd3.js";import"./chunk-4250pw6r.js";import"./chunk-bnv1mm5h.js";import"./chunk-rxqdw6s5.js";import"./chunk-jwqdhbe9.js";import"./chunk-f5n0tgky.js";import"./chunk-z3zaa155.js";import"./chunk-yewmtant.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-jt994bhe.js";import"./chunk-rtcevh2t.js";import"./chunk-2tfnscxk.js";import"./chunk-9ecnsh42.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-c6kw0s9a.js";import"./chunk-b7xjhgts.js";import"./chunk-x7r75e3p.js";import"./chunk-zsfyj36g.js";import"./chunk-tgfn5ykb.js";import"./chunk-qga9xd2f.js";import"./chunk-5v02t4pz.js";import"./chunk-ag3txfg2.js";import"./chunk-2brn8e1y.js";import"./chunk-b3vz95wb.js";import"./chunk-7zyyvc3d.js";import"./chunk-r6k3ve2g.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import"./chunk-hgf4cz78.js";import"./chunk-22d0yc7m.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-ws4cg819.js";import"./chunk-7kwk5kxn.js";import"./chunk-cmp64q4j.js";import"./chunk-kmgheesn.js";import"./chunk-szjgjrar.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{toApiError,successEnvelope,runVerb,repeatableFlagsOf,paramsToFlags,executeVerb,errorEnvelope,errorBody,callVerb,booleanFlagsOf,argvToParams};
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{DAEMON_CHANNELS}from"./chunk-fq3s9q62.js";import{logClientError}from"./chunk-gskbzgc3.js";import{samePath}from"./chunk-pn5ygqn6.js";import{preRenameRuntimePaths}from"./chunk-b39sdtt0.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{connect}from"net";import{StringDecoder}from"string_decoder";import{spawnSync}from"child_process";import{existsSync}from"fs";function normalizeRemoteUrl(url){let u=url.trim();return u=u.replace(/^[a-z+]+:\/\//i,""),u=u.replace(/^[^@/]+@/,""),u=u.replace(/^([^/:]+):(?!\d+\/)/,"$1/"),u=u.replace(/^([^/:]+):\d+\//,"$1/"),u=u.replace(/\/+$/,"").replace(/\.git$/i,""),u=u.replace(/^ssh\.github\.com\//i,"github.com/"),u.toLowerCase()}function git(cwd,args){let res=spawnSync("git",["-C",cwd,...args],{encoding:"utf8",timeout:5000,windowsHide:!0});return res.status===0?res.stdout.trim():null}function computeRepoId(path){let origin=git(path,["remote","get-url","origin"]);if(origin)return normalizeRemoteUrl(origin);let root=git(path,["rev-list","--max-parents=0","HEAD"])?.split(`
3
- `).filter(Boolean).sort()[0];return root?`root:${root}`:void 0}var memo=new Map;function repoIdOf(path){if(!path)return;if(memo.has(path))return memo.get(path);if(!existsSync(path))return;let id=computeRepoId(path);return memo.set(path,id),id}function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"}var ROUTINE_RESPONSE_MAX_CHARS=32000,ROUTINE_RESPONSE_WINDOW_MS=7200000;function routineRunResponseState(run,nowMs){if(run.response)return"responded";if(run.status!=="dispatched"&&run.status!=="revived")return null;if(run.deliveryStatus==="missing")return"missing";if(run.deliveryStatus==="awaiting")return"awaiting";return nowMs-Date.parse(run.at)>ROUTINE_RESPONSE_WINDOW_MS?"missing":"awaiting"}var GATE_QUESTION_MAX=500,GATE_CONTEXT_MAX=4000,GATE_OPTIONS_MAX=6;function gateInboxKey(gateId){return`\x00gate\x00${gateId}`}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","dead","routine_failed","routine_responded","report_missing","decision_needed"];function isRoutineInboxState(state){return state==="routine_failed"||state==="routine_responded"}function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(isRoutineInboxState(item.state)&&item.detail?.routine)return`\x00${item.state}\x00${item.detail.routine.automationId}`;if(item.state==="report_missing"&&item.detail?.delivery)return`\x00delivery\x00${item.detail.delivery.id}`;if(item.state==="decision_needed"&&item.detail?.gate)return gateInboxKey(item.detail.gate.id);return`${item.taskId}\x00${item.tabId??""}`}var DELIVERY_OUTCOMES=["done","partial","blocked","failed"],DELIVERY_SUMMARY_MAX_CHARS=32000,DELIVERY_EVIDENCE_MAX_ITEMS=50,DELIVERY_EVIDENCE_MAX_CHARS=2000,DELIVERY_NEXT_MAX_CHARS=4000,DELIVERY_PROMPT_HEAD_CHARS=200,MAX_DELIVERIES_PER_TASK=50,DELIVERY_STALL_MS=600000;function deliveryFooter(deliveryId,api){return`[ROVE] When this turn ends, report: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026]`}var SKIP_REASONS=["task-missing","awaiting-owner","report-missing","quota","engine-error","engine-dead","awaiting-permission","busy"],SHOULD_RUN_SKIP_EXIT_CODE=3;function parseSkipVerdict(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(raw.run!==!1||!SKIP_REASONS.includes(raw.reason))return;let text=(v)=>typeof v==="string"&&v.length>0?v:void 0;return{run:!1,reason:raw.reason,...text(raw.detail)?{detail:raw.detail}:{},...text(raw.until)?{until:raw.until}:{},...Array.isArray(raw.gateIds)?{gateIds:raw.gateIds.filter((g)=>typeof g==="string")}:{}}}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var DAEMON_PROTOCOL_VERSION=5,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;return!samePath(daemonHome,clientHome)}var BLOCKING_RPCS=new Set(["api.invoke","ui.prompt","task.land","workitem.start","automation.runNow","pr.rerunFailedChecks","task.ensureWorktree","task.ensureMain","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove"]);function parseDaemonStopReason(value){return value==="restart"||value==="stop"||value==="idle"||value==="socket-lost"?value:void 0}function displayTaskTitle(task){return task.title||task.branch||task.worktreePath||task.repo||"scratch"}function serializeTask(task){let repoId=repoIdOf(task.repo);return{id:task.id,title:displayTaskTitle(task),repo:task.repo,branch:task.branch,worktreePath:task.worktreePath,kind:task.kind??"task",...task.scratch?{scratch:!0}:{},...task.routine?{routine:task.routine}:{},status:task.status,pinned:task.pinned??!1,vendor:task.vendor,command:task.command,prStatus:task.prStatus,modelEffort:task.modelEffort,model:task.model,tier:task.tier,groupId:task.groupId,observedLanguage:task.observedLanguage,deletion:task.deletion,quotaResume:task.quotaResume,linkedWorkItem:task.linkedWorkItem,dispatcher:task.dispatcher,requireReport:task.requireReport,prompt:task.prompt,baseRef:task.baseRef,worktreeName:task.worktreeName,report:task.report,...repoId?{repoId}:{},createdAt:task.createdAt,updatedAt:task.updatedAt}}function frameToLine(frame){return`${JSON.stringify(frame)}
2
+ import{DAEMON_CHANNELS}from"./chunk-szjgjrar.js";import{logClientError}from"./chunk-gskbzgc3.js";import{samePath}from"./chunk-pn5ygqn6.js";import{preRenameRuntimePaths}from"./chunk-b39sdtt0.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{connect}from"net";import{StringDecoder}from"string_decoder";import{spawnSync}from"child_process";import{existsSync}from"fs";function normalizeRemoteUrl(url){let u=url.trim();return u=u.replace(/^[a-z+]+:\/\//i,""),u=u.replace(/^[^@/]+@/,""),u=u.replace(/^([^/:]+):(?!\d+\/)/,"$1/"),u=u.replace(/^([^/:]+):\d+\//,"$1/"),u=u.replace(/\/+$/,"").replace(/\.git$/i,""),u=u.replace(/^ssh\.github\.com\//i,"github.com/"),u.toLowerCase()}function git(cwd,args){let res=spawnSync("git",["-C",cwd,...args],{encoding:"utf8",timeout:5000,windowsHide:!0});return res.status===0?res.stdout.trim():null}function computeRepoId(path){let origin=git(path,["remote","get-url","origin"]);if(origin)return normalizeRemoteUrl(origin);let root=git(path,["rev-list","--max-parents=0","HEAD"])?.split(`
3
+ `).filter(Boolean).sort()[0];return root?`root:${root}`:void 0}var memo=new Map;function repoIdOf(path){if(!path)return;if(memo.has(path))return memo.get(path);if(!existsSync(path))return;let id=computeRepoId(path);return memo.set(path,id),id}function automationRunNeedsAttention(status){return status==="dispatch_failed"||status==="skipped_unavailable"||status==="script_failed"}var ROUTINE_RESPONSE_MAX_CHARS=32000,ROUTINE_RESPONSE_WINDOW_MS=7200000;function routineRunResponseState(run,nowMs){if(run.response)return"responded";if(run.status!=="dispatched"&&run.status!=="revived")return null;if(run.deliveryStatus==="missing")return"missing";if(run.deliveryStatus==="awaiting")return"awaiting";return nowMs-Date.parse(run.at)>ROUTINE_RESPONSE_WINDOW_MS?"missing":"awaiting"}var GATE_QUESTION_MAX=500,GATE_CONTEXT_MAX=4000,GATE_OPTIONS_MAX=6;function gateInboxKey(gateId){return`\x00gate\x00${gateId}`}var ATTENTION_INBOX_STATES=["turn_complete","permission_needed","error","rate_limited","dead","routine_failed","routine_responded","report_missing","decision_needed"];function isRoutineInboxState(state){return state==="routine_failed"||state==="routine_responded"}function isAttentionInboxState(value){return typeof value==="string"&&ATTENTION_INBOX_STATES.includes(value)}function attentionInboxItemKey(item){if(isRoutineInboxState(item.state)&&item.detail?.routine)return`\x00${item.state}\x00${item.detail.routine.automationId}`;if(item.state==="report_missing"&&item.detail?.delivery)return`\x00delivery\x00${item.detail.delivery.id}`;if(item.state==="decision_needed"&&item.detail?.gate)return gateInboxKey(item.detail.gate.id);return`${item.taskId}\x00${item.tabId??""}`}var DELIVERY_OUTCOMES=["done","partial","blocked","failed"],DELIVERY_SUMMARY_MAX_CHARS=32000,DELIVERY_EVIDENCE_MAX_ITEMS=50,DELIVERY_EVIDENCE_MAX_CHARS=2000,DELIVERY_NEXT_MAX_CHARS=4000,DELIVERY_PROMPT_HEAD_CHARS=200,MAX_DELIVERIES_PER_TASK=50,DELIVERY_STALL_MS=600000;function deliveryFooter(deliveryId,api){return`[ROVE] When this turn ends, report: ${api} report --delivery ${deliveryId} --outcome done|partial|blocked|failed --summary \u2026 [--evidence \u2026]\u2026 [--next \u2026]`}var SKIP_REASONS=["task-missing","awaiting-owner","report-missing","quota","engine-error","engine-dead","awaiting-permission","busy"],SHOULD_RUN_SKIP_EXIT_CODE=3;function parseSkipVerdict(value){if(!value||typeof value!=="object"||Array.isArray(value))return;let raw=value;if(raw.run!==!1||!SKIP_REASONS.includes(raw.reason))return;let text=(v)=>typeof v==="string"&&v.length>0?v:void 0;return{run:!1,reason:raw.reason,...text(raw.detail)?{detail:raw.detail}:{},...text(raw.until)?{until:raw.until}:{},...Array.isArray(raw.gateIds)?{gateIds:raw.gateIds.filter((g)=>typeof g==="string")}:{}}}var CHANNEL_NAMES=DAEMON_CHANNELS;var CHANNEL_NAME_SET=new Set(CHANNEL_NAMES);function isChannelName(value){return typeof value==="string"&&CHANNEL_NAME_SET.has(value)}function normalizeChannelFilter(value){if(!Array.isArray(value))return null;let set=new Set;for(let name of value)if(isChannelName(name))set.add(name);return set.size>0?set:null}var DAEMON_PROTOCOL_VERSION=5,MIN_COMPATIBLE_PROTOCOL_VERSION=2;function isProtocolCompatible(args){return args.remoteVersion>=args.localMin&&args.localVersion>=args.remoteMin}function isDaemonVersionStale(daemonVersion,clientVersion){if(!daemonVersion)return!1;return daemonVersion!==clientVersion}function isForeignDaemonHome(daemonHome,clientHome){if(!daemonHome)return!1;return!samePath(daemonHome,clientHome)}var BLOCKING_RPCS=new Set(["api.invoke","ui.prompt","task.land","workitem.start","automation.runNow","pr.rerunFailedChecks","task.ensureWorktree","task.ensureMain","worktree.discoverAdoptable","worktree.adopt","worktree.list","worktree.remove"]);function parseDaemonStopReason(value){return value==="restart"||value==="stop"||value==="idle"||value==="socket-lost"?value:void 0}function displayTaskTitle(task){return task.title||task.branch||task.worktreePath||task.repo||"scratch"}function serializeTask(task){let repoId=repoIdOf(task.repo);return{id:task.id,title:displayTaskTitle(task),repo:task.repo,branch:task.branch,worktreePath:task.worktreePath,kind:task.kind??"task",...task.scratch?{scratch:!0}:{},...task.routine?{routine:task.routine}:{},status:task.status,pinned:task.pinned??!1,vendor:task.vendor,command:task.command,prStatus:task.prStatus,modelEffort:task.modelEffort,model:task.model,tier:task.tier,groupId:task.groupId,observedLanguage:task.observedLanguage,deletion:task.deletion,quotaResume:task.quotaResume,linkedWorkItem:task.linkedWorkItem,dispatcher:task.dispatcher,requireReport:task.requireReport,prompt:task.prompt,baseRef:task.baseRef,worktreeName:task.worktreeName,report:task.report,...repoId?{repoId}:{},createdAt:task.createdAt,updatedAt:task.updatedAt}}function frameToLine(frame){return`${JSON.stringify(frame)}
4
4
  `}class RpcTimeoutError extends Error{constructor(name,timeoutMs){super(`daemon rpc "${name}" timed out after ${timeoutMs}ms (daemon wedged?)`);this.name="RpcTimeoutError"}}function rpcTimeoutMs(){let raw=readRoveEnv("RPC_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 20000}class ConnectTimeoutError extends Error{constructor(socketPath,timeoutMs){super(`connecting to ${socketPath} timed out after ${timeoutMs}ms \u2014 nothing accepted the connection (daemon or PTY host not listening at that address)`);this.name="ConnectTimeoutError"}}function connectTimeoutMs(){let raw=readRoveEnv("CONNECT_TIMEOUT_MS")?.trim();if(raw){let parsed=Number.parseInt(raw,10);if(Number.isFinite(parsed))return parsed}return 5000}class RoveDaemonClient{socketPath;socket=null;buffer="";nextId=1;pending=new Map;handlers=new Map;lifecycleHandlers=new Map;connecting=null;disposed=!1;constructor(socketPath){this.socketPath=socketPath}connect(){if(this.socket)return Promise.resolve();if(this.disposed)return Promise.reject(Error("daemon client disposed"));if(this.connecting)return this.connecting;let p=this.openSocketWithFallback();this.connecting=p;let cleanup=()=>{if(this.connecting===p)this.connecting=null};return p.then(cleanup,cleanup),p}get isDisposed(){return this.disposed}close(){this.disposed=!0,this.socket?.end(),this.socket=null,this.failPending()}forceDisconnect(){let socket=this.socket;if(!socket)return;this.socket=null,socket.destroy(),this.failPending()}failPending(){if(this.pending.size===0)return;let err=Error("daemon connection closed");for(let pending of this.pending.values()){if(pending.timer)clearTimeout(pending.timer);pending.reject(err)}this.pending.clear()}on(name,handler){let set=this.handlers.get(name);if(!set)set=new Set,this.handlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.handlers.delete(name)}}onChannel(channel,handler){return this.on(channel,(frame)=>handler(frame.payload))}subscribe(opts={}){let payload={};if(opts.channels)payload.channels=opts.channels;if(opts.role)payload.role=opts.role;if(opts.cellPixelSize)payload.cellPixelWidth=opts.cellPixelSize.width,payload.cellPixelHeight=opts.cellPixelSize.height;return this.request("subscribe",payload)}onLifecycle(name,handler){let set=this.lifecycleHandlers.get(name);if(!set)set=new Set,this.lifecycleHandlers.set(name,set);return set.add(handler),()=>{if(set?.delete(handler),set?.size===0)this.lifecycleHandlers.delete(name)}}async request(name,payload){await this.connect();let socket=this.socket;if(!socket)throw Error("daemon connection is not open");let id=String(this.nextId++),promise=new Promise((resolve,reject)=>{let entry={resolve:(value)=>resolve(value),reject},timeoutMs=rpcTimeoutMs();if(timeoutMs>0&&!BLOCKING_RPCS.has(name))entry.timer=setTimeout(()=>this.onRequestTimeout(id,name,timeoutMs),timeoutMs);this.pending.set(id,entry)});return socket.write(frameToLine({type:"request",id,name,payload})),promise}onRequestTimeout(id,name,timeoutMs){let pending=this.pending.get(id);if(!pending)return;this.pending.delete(id),pending.reject(new RpcTimeoutError(name,timeoutMs)),this.forceDisconnect(),this.emitLifecycle("close")}async openSocketWithFallback(){try{await this.openSocket(this.socketPath);return}catch(err){if(!(err instanceof Error)||!("code"in err)||!["ENOENT","ECONNREFUSED"].includes(String(err.code)))throw err;for(let path of preRenameRuntimePaths(this.socketPath)){if(this.disposed)throw err;try{await this.openSocket(path);return}catch{}}throw err}}openSocket(path){return new Promise((resolve,reject)=>{let socket=connect(path);this.socket=socket;let timeoutMs=connectTimeoutMs(),timer;if(timeoutMs>0)timer=setTimeout(()=>{if(socket.off("connect",onConnect),socket.off("error",onError),socket.destroy(),this.socket===socket)this.socket=null;reject(new ConnectTimeoutError(this.socketPath,timeoutMs))},timeoutMs);let onConnect=()=>{if(timer)clearTimeout(timer);socket.off("error",onError),socket.on("error",()=>socket.destroy()),resolve()},onError=(err)=>{if(timer)clearTimeout(timer);if(socket.off("connect",onConnect),this.socket===socket)this.socket=null;reject(err)};socket.once("connect",onConnect),socket.once("error",onError);let decoder=new StringDecoder("utf8");this.buffer="",socket.on("data",(chunk)=>this.onData(decoder.write(chunk))),socket.on("close",()=>this.onSocketClose(socket))})}onSocketClose(which){if(this.socket!==which)return;this.socket=null,this.failPending(),this.emitLifecycle("close")}emitLifecycle(name){for(let handler of this.lifecycleHandlers.get(name)??[])try{handler()}catch(err){console.error(`[rove] lifecycle handler for "${name}" threw:`,err)}}onData(chunk){this.buffer+=chunk;let nl=this.buffer.indexOf(`
5
5
  `);while(nl!==-1){let line=this.buffer.slice(0,nl);if(this.buffer=this.buffer.slice(nl+1),line.trim().length>0)this.onLine(line);nl=this.buffer.indexOf(`
6
6
  `)}}onLine(line){let frame;try{frame=JSON.parse(line)}catch(err){logClientError("client-frame",err);return}if(frame.type==="event"){this.emit(frame);return}if(frame.type!=="response")return;let pending=this.pending.get(frame.id);if(!pending)return;if(this.pending.delete(frame.id),pending.timer)clearTimeout(pending.timer);if(frame.error){let err=Error(frame.error.message);if(frame.error.name)err.name=frame.error.name;pending.reject(err)}else pending.resolve(frame.payload)}emit(frame){for(let handler of this.handlers.get(frame.name)??[])try{handler(frame)}catch(err){logClientError("client-event",err)}for(let handler of this.handlers.get("*")??[])try{handler(frame)}catch(err){logClientError("client-event",err)}}}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-2676cb62.js";import"./chunk-q07r6hf7.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
2
+ import{currentLang,intlLocale,localeState,registerMessages,setLocaleLang,t,tKeys}from"./chunk-ws4cg819.js";import"./chunk-7kwk5kxn.js";import"./chunk-cmp64q4j.js";import"./chunk-91sykzqq.js";export{tKeys,t,setLocaleLang,registerMessages,localeState,intlLocale,currentLang};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{MachineHub,classifyHandshakeFailure}from"./chunk-db61d8dz.js";import"./chunk-ephcyh6v.js";import"./chunk-atn06ncf.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-c0gvp57p.js";import"./chunk-r3zkpbf5.js";import"./chunk-b7xjhgts.js";import"./chunk-r1epx453.js";import"./chunk-m3773n9n.js";import"./chunk-c7j05xps.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-74e3k701.js";import"./chunk-40dgv828.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cmp64q4j.js";import"./chunk-6ks6s8b2.js";import"./chunk-fq3s9q62.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{classifyHandshakeFailure,MachineHub};
2
+ import{MachineHub,classifyHandshakeFailure}from"./chunk-c2cj2bye.js";import"./chunk-8gzqcx6x.js";import"./chunk-atn06ncf.js";import"./chunk-55ajzrj6.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-6xppe9bj.js";import"./chunk-c0gvp57p.js";import"./chunk-r3zkpbf5.js";import"./chunk-b7xjhgts.js";import"./chunk-tgfn5ykb.js";import"./chunk-qga9xd2f.js";import"./chunk-5v02t4pz.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-hgf4cz78.js";import"./chunk-40dgv828.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-cmp64q4j.js";import"./chunk-kmgheesn.js";import"./chunk-szjgjrar.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{classifyHandshakeFailure,MachineHub};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{isEngineActivityKind}from"./chunk-17e2tgyg.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-nwevnc6k.js";import{activityHookAdapters}from"./chunk-h5znx9v9.js";import{flagValue}from"./chunk-zsfyj36g.js";import{connectIfRunning}from"./chunk-r1epx453.js";import{getPersistedString,setPersistedString}from"./chunk-22d0yc7m.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{join,resolve}from"path";var STDIN_READ_TIMEOUT_MS=500;async function readTextWithTimeout(read,timeoutMs=STDIN_READ_TIMEOUT_MS){let raceTimer;try{return await Promise.race([read(),new Promise((resolve2)=>{raceTimer=setTimeout(()=>resolve2(""),timeoutMs)})])}finally{if(raceTimer!==void 0)clearTimeout(raceTimer)}}async function readStdinText(isComplete){let bun=globalThis.Bun;if(bun)return bun.stdin.text();if(process.stdin.isTTY)return"";let chunks=[];try{for await(let chunk of process.stdin)if(chunks.push(chunk),isComplete?.(Buffer.concat(chunks).toString("utf8")))break}finally{process.stdin.destroy()}return Buffer.concat(chunks).toString("utf8")}function isCompleteJson(text){try{return JSON.parse(text),!0}catch{return!1}}async function readStdinPayload(){try{let text=await readTextWithTimeout(()=>readStdinText(isCompleteJson));if(!text.trim())return{};let parsed=JSON.parse(text);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}async function runHookSubcommand(argv){let[verb,...rest]=argv;if(verb==="setup"){await runHookSetup(rest);return}if(verb==="cleanup"){await runHookCleanup();return}try{if(!verb||!isEngineActivityKind(verb))return;let payload=await readStdinPayload(),payloadFlag=flagValue(rest,"--payload");if(payloadFlag)try{let extra=JSON.parse(payloadFlag);if(extra&&typeof extra==="object"&&!Array.isArray(extra))Object.assign(payload,extra)}catch{}let taskId=flagValue(rest,"--task-id"),envTaskId=process.env.ROVE_TASK_ID,envTabId=process.env.ROVE_TAB_ID,engine=flagValue(rest,"--engine"),adapters=activityHookAdapters().filter((a)=>!engine||a.vendor===engine);if(!taskId&&adapters.some((a)=>a.isUnattendedSession?.(process.env)===!0))return;let cwd=typeof payload.cwd==="string"&&payload.cwd?payload.cwd:void 0;for(let adapter of adapters){if(cwd)break;cwd=adapter.cwdFromPayload?.(payload)}cwd||=process.cwd();let detail;for(let adapter of adapters)if(detail=adapter.activityDetailFromPayload(verb,payload),detail)break;let session;for(let adapter of adapters)if(session=adapter.sessionFromPayload(payload),session)break;let client=await connectIfRunning();if(!client)return;try{let effectiveTaskId=taskId??envTaskId;await client.request("engine.reportEvent",{...effectiveTaskId?{taskId:effectiveTaskId}:{cwd},kind:verb,...engine?{engine}:{},...envTabId?{tabId:envTabId}:{},...detail?{detail}:{},...session?{sessionId:session.sessionId}:{},...session?.transcriptPath?{transcriptPath:session.transcriptPath}:{}})}finally{client.close()}}catch(err){if(readRoveEnv("HOOK_DEBUG"))console.error(`[rove hook] ${verb} failed:`,err instanceof Error?err.message:String(err))}}var SYNC_SETTING_KEY="externalWorktreeSync";function worktreeSyncAdapters(){return activityHookAdapters().filter((a)=>a.supportsWorktreeSync())}function globalSettingsPath(){return worktreeSyncAdapters()[0]?.globalSettingsPath()}function persistedSyncPath(stored){if(!stored||stored==="off")return;if(stored==="global")return globalSettingsPath();if(stored.startsWith("repo:"))return join(resolve(stored.slice(5)),".claude","settings.json");return stored}async function ensureGlobalRoveHooks(opts={}){try{let toolEvents=pluginsWantToolEvents();for(let a of activityHookAdapters()){let external=await a.externallyManagedHooks?.();if(external){if(external.notice)process.stderr.write(`
2
+ import{isEngineActivityKind}from"./chunk-17e2tgyg.js";import{loadPluginRegistry,readPluginManifest}from"./chunk-a2epp2ad.js";import{activityHookAdapters}from"./chunk-rtcevh2t.js";import{flagValue}from"./chunk-zsfyj36g.js";import{connectIfRunning}from"./chunk-tgfn5ykb.js";import{getPersistedString,setPersistedString}from"./chunk-22d0yc7m.js";import{readRoveEnv}from"./chunk-nc46gddg.js";import{join,resolve}from"path";var STDIN_READ_TIMEOUT_MS=500;async function readTextWithTimeout(read,timeoutMs=STDIN_READ_TIMEOUT_MS){let raceTimer;try{return await Promise.race([read(),new Promise((resolve2)=>{raceTimer=setTimeout(()=>resolve2(""),timeoutMs)})])}finally{if(raceTimer!==void 0)clearTimeout(raceTimer)}}async function readStdinText(isComplete){let bun=globalThis.Bun;if(bun)return bun.stdin.text();if(process.stdin.isTTY)return"";let chunks=[];try{for await(let chunk of process.stdin)if(chunks.push(chunk),isComplete?.(Buffer.concat(chunks).toString("utf8")))break}finally{process.stdin.destroy()}return Buffer.concat(chunks).toString("utf8")}function isCompleteJson(text){try{return JSON.parse(text),!0}catch{return!1}}async function readStdinPayload(){try{let text=await readTextWithTimeout(()=>readStdinText(isCompleteJson));if(!text.trim())return{};let parsed=JSON.parse(text);return parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:{}}catch{return{}}}async function runHookSubcommand(argv){let[verb,...rest]=argv;if(verb==="setup"){await runHookSetup(rest);return}if(verb==="cleanup"){await runHookCleanup();return}try{if(!verb||!isEngineActivityKind(verb))return;let payload=await readStdinPayload(),payloadFlag=flagValue(rest,"--payload");if(payloadFlag)try{let extra=JSON.parse(payloadFlag);if(extra&&typeof extra==="object"&&!Array.isArray(extra))Object.assign(payload,extra)}catch{}let taskId=flagValue(rest,"--task-id"),envTaskId=process.env.ROVE_TASK_ID,envTabId=process.env.ROVE_TAB_ID,engine=flagValue(rest,"--engine"),adapters=activityHookAdapters().filter((a)=>!engine||a.vendor===engine);if(!taskId&&adapters.some((a)=>a.isUnattendedSession?.(process.env)===!0))return;let cwd=typeof payload.cwd==="string"&&payload.cwd?payload.cwd:void 0;for(let adapter of adapters){if(cwd)break;cwd=adapter.cwdFromPayload?.(payload)}cwd||=process.cwd();let detail;for(let adapter of adapters)if(detail=adapter.activityDetailFromPayload(verb,payload),detail)break;let session;for(let adapter of adapters)if(session=adapter.sessionFromPayload(payload),session)break;let client=await connectIfRunning();if(!client)return;try{let effectiveTaskId=taskId??envTaskId;await client.request("engine.reportEvent",{...effectiveTaskId?{taskId:effectiveTaskId}:{cwd},kind:verb,...engine?{engine}:{},...envTabId?{tabId:envTabId}:{},...detail?{detail}:{},...session?{sessionId:session.sessionId}:{},...session?.transcriptPath?{transcriptPath:session.transcriptPath}:{}})}finally{client.close()}}catch(err){if(readRoveEnv("HOOK_DEBUG"))console.error(`[rove hook] ${verb} failed:`,err instanceof Error?err.message:String(err))}}var SYNC_SETTING_KEY="externalWorktreeSync";function worktreeSyncAdapters(){return activityHookAdapters().filter((a)=>a.supportsWorktreeSync())}function globalSettingsPath(){return worktreeSyncAdapters()[0]?.globalSettingsPath()}function persistedSyncPath(stored){if(!stored||stored==="off")return;if(stored==="global")return globalSettingsPath();if(stored.startsWith("repo:"))return join(resolve(stored.slice(5)),".claude","settings.json");return stored}async function ensureGlobalRoveHooks(opts={}){try{let toolEvents=pluginsWantToolEvents();for(let a of activityHookAdapters()){let external=await a.externallyManagedHooks?.();if(external){if(external.notice)process.stderr.write(`
3
3
  ${external.notice}
4
4
  `);continue}let enginePath=a.globalSettingsPath();if(!enginePath)continue;await a.installActivityHooks(enginePath,{toolEvents,quiet:opts.quiet}),await a.removeWorktreeWatchHook(enginePath)}await cleanupWorktreeSyncHook()}catch{}}function pluginsWantToolEvents(){try{for(let entry of loadPluginRegistry().plugins){if(!entry.enabled)continue;try{if(readPluginManifest(entry.root).manifest.events.some((e)=>e.on.startsWith("tool.")))return!0}catch{}}}catch{}return!1}async function cleanupWorktreeSyncHook(){let adapters=worktreeSyncAdapters();if(adapters.length===0)return;let stored=getPersistedString(SYNC_SETTING_KEY),paths=new Set;for(let adapter of adapters){let file=adapter.globalSettingsPath();if(file)paths.add(file)}let prev=persistedSyncPath(stored);if(prev)paths.add(prev);for(let a of adapters)for(let p of paths)await a.removeWorktreeSyncHook(p);if(stored!=="off")setPersistedString(SYNC_SETTING_KEY,"off")}async function runHookCleanup(){let claude=activityHookAdapters().find((a)=>a.vendor==="claude"),path=claude?.globalSettingsPath();if(!claude||!path){process.stdout.write(`rove hook cleanup: no Claude hook adapter \u2014 nothing to do.
5
5
  `);return}await claude.removeActivityHooks(path),await claude.removeWorktreeWatchHook(path),process.stdout.write([`rove hook cleanup: removed Rove's settings-managed hooks from ${path}.`,"Only Rove's own entries were touched; your other hooks are intact.","The Claude Code plugin's hooks.json now carries these events (if the plugin","is not installed, the next Rove launch reinstalls the settings-managed set).",""].join(`
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{API_VERBS,VERBS,VERB_ALIASES,VERB_GROUPS,findVerb,unknownVerbError}from"./chunk-cyq9pwqz.js";import"./chunk-s0x0yw8x.js";import"./chunk-fdexrh6h.js";import"./chunk-ns2f9b6r.js";import"./chunk-3zjdbdwy.js";import"./chunk-j11hzmwy.js";import"./chunk-re15t5r1.js";import"./chunk-17e2tgyg.js";import"./chunk-cbc1h345.js";import"./chunk-jjv7xem7.js";import"./chunk-4hestsjp.js";import"./chunk-3ac75tqw.js";import"./chunk-2bgmby1d.js";import"./chunk-41x1hrqe.js";import"./chunk-5mhvjytn.js";import"./chunk-a2epp2ad.js";import"./chunk-atn06ncf.js";import"./chunk-65333881.js";import"./chunk-qkehg2c1.js";import"./chunk-gzj9nk7k.js";import"./chunk-1cmcaarg.js";import"./chunk-4kzqv6rq.js";import"./chunk-ampdybqg.js";import"./chunk-sak1tphp.js";import"./chunk-1gxb0bd3.js";import"./chunk-4250pw6r.js";import"./chunk-bnv1mm5h.js";import"./chunk-rxqdw6s5.js";import"./chunk-jwqdhbe9.js";import"./chunk-f5n0tgky.js";import"./chunk-z3zaa155.js";import"./chunk-yewmtant.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-jt994bhe.js";import"./chunk-rtcevh2t.js";import"./chunk-2tfnscxk.js";import"./chunk-9ecnsh42.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-c6kw0s9a.js";import"./chunk-b7xjhgts.js";import"./chunk-x7r75e3p.js";import"./chunk-zsfyj36g.js";import"./chunk-tgfn5ykb.js";import"./chunk-qga9xd2f.js";import"./chunk-5v02t4pz.js";import"./chunk-ag3txfg2.js";import"./chunk-2brn8e1y.js";import"./chunk-b3vz95wb.js";import"./chunk-7zyyvc3d.js";import"./chunk-r6k3ve2g.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import"./chunk-hgf4cz78.js";import"./chunk-22d0yc7m.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-ws4cg819.js";import"./chunk-7kwk5kxn.js";import"./chunk-cmp64q4j.js";import"./chunk-kmgheesn.js";import"./chunk-szjgjrar.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{unknownVerbError,findVerb,VERB_GROUPS,VERB_ALIASES,VERBS,API_VERBS};
@@ -0,0 +1,55 @@
1
+ // @bun
2
+ import{invokeVerb}from"./chunk-4tb0h00q.js";import"./chunk-va5mjg68.js";import{defaultApiRuntime,loadContext}from"./chunk-cyq9pwqz.js";import"./chunk-s0x0yw8x.js";import"./chunk-fdexrh6h.js";import{ensurePluginEnginesLoaded}from"./chunk-ns2f9b6r.js";import"./chunk-3zjdbdwy.js";import"./chunk-j11hzmwy.js";import"./chunk-re15t5r1.js";import"./chunk-17e2tgyg.js";import"./chunk-cbc1h345.js";import"./chunk-jjv7xem7.js";import"./chunk-4hestsjp.js";import"./chunk-3ac75tqw.js";import"./chunk-2bgmby1d.js";import"./chunk-41x1hrqe.js";import"./chunk-5mhvjytn.js";import"./chunk-a2epp2ad.js";import"./chunk-atn06ncf.js";import"./chunk-65333881.js";import"./chunk-qkehg2c1.js";import"./chunk-gzj9nk7k.js";import"./chunk-1cmcaarg.js";import"./chunk-4kzqv6rq.js";import"./chunk-ampdybqg.js";import"./chunk-sak1tphp.js";import"./chunk-1gxb0bd3.js";import"./chunk-4250pw6r.js";import"./chunk-bnv1mm5h.js";import"./chunk-rxqdw6s5.js";import"./chunk-jwqdhbe9.js";import"./chunk-f5n0tgky.js";import"./chunk-z3zaa155.js";import"./chunk-yewmtant.js";import"./chunk-hpay0ax8.js";import"./chunk-catrr0z3.js";import"./chunk-jt994bhe.js";import"./chunk-rtcevh2t.js";import"./chunk-2tfnscxk.js";import"./chunk-9ecnsh42.js";import"./chunk-w7zv47mp.js";import"./chunk-etfh8f4z.js";import"./chunk-t7j8g9f6.js";import"./chunk-dmzg9zdc.js";import"./chunk-kg9kmwt9.js";import"./chunk-6xppe9bj.js";import"./chunk-b2h6jfrg.js";import"./chunk-c0gvp57p.js";import"./chunk-r3zkpbf5.js";import"./chunk-c6kw0s9a.js";import"./chunk-b7xjhgts.js";import{ApiError}from"./chunk-x7r75e3p.js";import"./chunk-zsfyj36g.js";import{connectIfRunning}from"./chunk-tgfn5ykb.js";import"./chunk-qga9xd2f.js";import"./chunk-5v02t4pz.js";import"./chunk-ag3txfg2.js";import"./chunk-2brn8e1y.js";import"./chunk-b3vz95wb.js";import"./chunk-7zyyvc3d.js";import"./chunk-r6k3ve2g.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import{SUBCOMMAND_VERBS}from"./chunk-tjj9bt7n.js";import"./chunk-hgf4cz78.js";import{getSavedRepos}from"./chunk-22d0yc7m.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-ws4cg819.js";import"./chunk-7kwk5kxn.js";import"./chunk-cmp64q4j.js";import{RoveDaemonClient,automationRunNeedsAttention}from"./chunk-kmgheesn.js";import"./chunk-szjgjrar.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import{resolveDaemonHomeDir}from"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import{ROVE_STATE_DIR_BASENAME,readRoveEnv}from"./chunk-nc46gddg.js";import"./chunk-pxk2c2vj.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
+ `;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
+ `}if(!oddRow)output+=borderBottom}else{var border=repeat(white).times(qrcode.getModuleCount()+3);output+=border+`
5
+ `,qrcode.modules.forEach(function(row2){output+=white,output+=row2.map(toCell).join(""),output+=white+`
6
+ `}),output+=border}if(cb)cb(output);else console.log(output)},setErrorLevel:function(error){this.error=QRErrorCorrectLevel[error]||this.error}}});import{setTimeout as delay}from"timers/promises";import{basename}from"path";function shortId(taskId){return taskId.slice(-6)}function head(text){let match=/^(\S+)\s*([\s\S]*)$/.exec(text.trim());return match?[match[1]??"",match[2]??""]:["",""]}function clip(text,max){let flat=text.replace(/\s+/g," ").trim();return flat.length<=max?flat:`${flat.slice(0,max-1)}\u2026`}function rowDetail(row){let bits=[];if(row.group==="waiting-on-you"&&row.activity)bits.push(row.activity.state.replace(/_/g," "));if(row.pr!==void 0)bits.push(`PR#${row.pr}`);if(row.checkState&&row.checkState!=="none")bits.push(`CI ${row.checkState}`);if(row.report?.summary)bits.push(`\u201C${clip(row.report.summary,48)}\u201D`);return bits.join(" \xB7 ")}function rowLine(row){let detail=rowDetail(row);return`\u2022 ${shortId(row.taskId)} ${clip(row.title||row.branch||"(untitled)",36)}${detail?` \u2014 ${detail}`:""}`}var SECTIONS=[["waiting-on-you","Needs you"],["landing","Ready to merge"],["ready-for-review","To review"],["working","Running"]];function renderStatus(payload){let count=(group)=>payload.tasks.filter((t)=>t.group===group).length,needs=count("waiting-on-you"),merge=count("landing"),review=count("ready-for-review"),running=count("working"),quiet=payload.tasks.length-needs-merge-review-running+(payload.omittedTasks??0);if(payload.tasks.length===0)return"No tasks right now.";let headline=[needs>0?`${needs} need you`:null,merge>0?`${merge} ready to merge`:null,review>0?`${review} to review`:null,`${running} running`,quiet>0?`${quiet} quiet`:null].filter(Boolean).join(" \xB7 "),lines=[needs+merge+review===0?`Nothing needs you. ${headline}`:headline];for(let[group,label]of SECTIONS){let rows=payload.tasks.filter((t)=>t.group===group);if(rows.length===0)continue;lines.push("",`${label}:`);for(let row of rows.slice(0,5))lines.push(rowLine(row));if(rows.length>5)lines.push(` +${rows.length-5} more`)}let unreported=payload.attention.filter((a)=>a.state==="report_missing"&&a.detail?.delivery?.id);if(unreported.length>0){lines.push("","Unreported ticks (reply `clear d-N` to unblock):");for(let item of unreported.slice(0,5)){let row=payload.tasks.find((t)=>t.taskId===item.taskId);lines.push(`\u2022 ${item.detail?.delivery?.id} ${row?shortId(row.taskId):""} ${clip(row?.title??"",36)}`.trimEnd())}}return lines.join(`
7
+ `)}function toBubbles(text){let pieces=text.trim().split(`
8
+ `).flatMap((line)=>line.match(new RegExp("[\\s\\S]{1,1800}","g"))??[""]),bubbles=[],current=null;for(let piece of pieces)if(current!==null&&current.length+1+piece.length<=1800)current=`${current}
9
+ ${piece}`;else{if(current!==null)bubbles.push(current);current=piece}if(current?.trim())bubbles.push(current);if(bubbles.length<=3)return bubbles;let marker=`\u2026(cut, ${bubbles.slice(3).reduce((n,b)=>n+b.split(`
10
+ `).length,0)} more lines)`,kept=bubbles.slice(0,3),last=kept[2]??"";return kept[2]=`${last.slice(0,1800-marker.length-1)}
11
+ ${marker}`,kept}var GATES_USAGE="Usage: answer g-12 <key> [note]";function gateLines(gate,titles){let lines=[`${gate.id} ${shortId(gate.taskId)} ${titles.get(gate.taskId)??""}`.trimEnd(),gate.question];for(let o of gate.options){let mark=o.key===gate.recommended?" (recommended)":"";lines.push(` ${o.key}${mark} \u2014 ${o.label}${o.detail?` (${o.detail})`:""}`)}if(gate.options.length===0)lines.push(" free text only");return lines}function renderGates(gates,titles){if(gates.length===0)return"No open decisions.";let lines=[`${gates.length} open decision${gates.length===1?"":"s"}:`];for(let gate of gates)lines.push("",...gateLines(gate,titles));return lines.push("",GATES_USAGE),lines.join(`
12
+ `)}function renderGateArrivals(gates,titles){let lines=["Decision needed:"];for(let gate of gates)lines.push(...gateLines(gate,titles));let first=gates[0];if(first)lines.push(`Reply: answer ${first.id} ${first.options[0]?.key??"<text>"}`);return lines.join(`
13
+ `)}function gateId(ref){let m=/^(?:g-?)?(\d{1,9})$/i.exec(ref);return m?`g-${Number(m[1])}`:null}function parseAnswer(rest,open){let[ref,afterRef]=head(rest);if(!ref||!afterRef.trim())return{ok:!1,reply:GATES_USAGE};let id=gateId(ref),gate=id?open.find((g)=>g.id===id):void 0;if(!gate)return{ok:!1,reply:`No open decision "${ref}". Send "gates" for the list.`};if(gate.options.length===0){let[word2,note2]=head(afterRef),text=(word2==="-"?note2:afterRef).trim();return text?{ok:!0,answer:{gate,text}}:{ok:!1,reply:`Usage: answer ${gate.id} - <text>`}}let[word,note]=head(afterRef);if(word==="-")return note.trim()?{ok:!0,answer:{gate,text:note.trim()}}:{ok:!1,reply:`Usage: answer ${gate.id} - <text>`};let option=gate.options.find((o)=>o.key.toLowerCase()===word.toLowerCase());if(!option)return{ok:!1,reply:`"${word}" is not an option of ${gate.id}. Options: ${gate.options.map((o)=>o.key).join(", ")} (or "answer ${gate.id} - <text>").`};return{ok:!0,answer:{gate,option:option.key,...note.trim()?{text:note.trim()}:{}}}}function answeredReply(answer,delivered){let picked=answer.gate.options.find((o)=>o.key===answer.option),what=picked?`${picked.key} (${picked.label})`:"your text";return`Answered ${answer.gate.id} with ${what}. ${delivered?"Sent to the agent.":"The agent is not running; it gets this with the task's next message."}`}var MIN_ID_CHARS=4,TAB_RE=/^tab-\d+$/,HELP_TEXT=["Rove commands:","status \u2014 what needs you, what's running","status <repo> \u2014 one repo only","send <id> <text> \u2014 message a task's agent","send <id> tab-2 <text> \u2014 a specific tab","add <repo> <prompt> \u2014 start a new task","gates \u2014 open decisions waiting on you","answer g-12 <key> [note] \u2014 answer one","answer g-12 - <text> \u2014 free-text answer","clear d-41 \u2014 dismiss an unreported-tick flag (status lists them)","<id> is the 6-char code from status."].join(`
14
+ `);function resolveTask(tasks,ref){let needle=ref.toLowerCase(),exact=tasks.find((t)=>t.id.toLowerCase()===needle);if(exact)return{ok:!0,value:exact};if(needle.length<MIN_ID_CHARS)return{ok:!1,reply:`"${ref}" is too short \u2014 use the 6-char code from status.`};let hits=tasks.filter((t)=>t.id.toLowerCase().endsWith(needle));if(hits.length===1&&hits[0])return{ok:!0,value:hits[0]};if(hits.length===0)return{ok:!1,reply:`No task ending in "${ref}". Send "status" for the list.`};return{ok:!1,reply:[`"${ref}" matches ${hits.length} tasks:`,...hits.slice(0,5).map((t)=>`\u2022 ${t.id} ${t.title}`)].join(`
15
+ `)}}function resolveRepo(repos,ref){let unique=[...new Set(repos)],exact=unique.find((r)=>r===ref);if(exact)return{ok:!0,value:exact};let hits=unique.filter((r)=>basename(r).toLowerCase()===ref.toLowerCase());if(hits.length===1&&hits[0])return{ok:!0,value:hits[0]};let names=unique.map((r)=>basename(r)).sort();if(hits.length===0)return{ok:!1,reply:names.length>0?`No repo "${ref}". Known: ${names.join(", ")}`:`No repo "${ref}" \u2014 none saved yet.`};return{ok:!1,reply:[`"${ref}" names ${hits.length} repos; use the full path:`,...hits].join(`
16
+ `)}}function failure(err){if(err instanceof ApiError)return`Failed (${err.code}): ${err.message}`;return`Failed: ${err instanceof Error?err.message:String(err)}`}var COMMAND_WORDS=new Set(["","help","h","?","\u5E2E\u52A9","status","s","ls","\u72B6\u6001","send","add","new","gates","decisions","\u51B3\u5B9A","answer","\u56DE\u7B54","clear","\u6E05\u9664"]);function agentPrompt(text,cli){return`[WeChat] ${text}
17
+
18
+ (From the owner on WeChat. Reply there with \`${cli} weixin send "<reply>"\` \u2014 or --file for long text \u2014 in the language they wrote in.)`}async function handleInbound(text,ops,agent,cli="rove"){let[word]=head(text);if(!agent||COMMAND_WORDS.has(word.toLowerCase()))return await handleCommand(text,ops,agent!==null);try{return(await ops.send(agent.taskId,agent.tab,agentPrompt(text.trim(),cli))).started?"Agent was not running \u2014 started it; it will reply here.":""}catch(err){return`${failure(err)}
19
+ The bound agent did not get your message (${CLI_HINT}).`}}var CLI_HINT="rebind with `rove weixin agent <task-id>` on the Rove machine";async function handleCommand(text,ops,agentBound=!1){let[word,rest]=head(text);try{switch(word.toLowerCase()){case"":case"help":case"h":case"?":case"\u5E2E\u52A9":return agentBound?`${HELP_TEXT}
20
+ Anything else goes to your bound agent.`:HELP_TEXT;case"status":case"s":case"ls":case"\u72B6\u6001":{if(!rest.trim())return renderStatus(await ops.status(null));let repo=resolveRepo(await ops.repos(),rest.trim());return repo.ok?`${basename(repo.value)}: ${renderStatus(await ops.status(repo.value))}`:repo.reply}case"send":{let[ref,afterRef]=head(rest),[tab,prompt]=head(afterRef);if(!TAB_RE.test(tab))prompt=afterRef,tab="";if(!ref||!prompt.trim())return"Usage: send <id> [tab-N] <text>";let task=resolveTask(await ops.tasks(),ref);if(!task.ok)return task.reply;let result=await ops.send(task.value.id,tab||void 0,prompt.trim()),where=result.tab??tab;return`Sent to ${shortId(task.value.id)} ${task.value.title}${where?` (${where})`:""}${result.started?" \u2014 started a new engine":""}.`}case"add":case"new":{let[repoRef,prompt]=head(rest);if(!repoRef||!prompt.trim())return"Usage: add <repo> <prompt>";let repo=resolveRepo(await ops.repos(),repoRef);if(!repo.ok)return repo.reply;let{taskId}=await ops.add(repo.value,prompt.trim());return`Started task ${shortId(taskId)} in ${basename(repo.value)}. I'll message you when it needs you.`}case"gates":case"decisions":case"\u51B3\u5B9A":{let[gates,tasks]=await Promise.all([ops.gates(),ops.tasks()]);return renderGates(gates,new Map(tasks.map((t)=>[t.id,t.title])))}case"answer":case"\u56DE\u7B54":{let parsed=parseAnswer(rest,await ops.gates());if(!parsed.ok)return parsed.reply;let{gate,option,text:text2}=parsed.answer,{delivered}=await ops.answerGate(gate.id,{...option?{option}:{},...text2?{text:text2}:{}});return answeredReply(parsed.answer,delivered)}case"clear":case"\u6E05\u9664":{let[ref]=head(rest);if(!ref||!/^d-\d+$/i.test(ref))return"Usage: clear d-N \u2014 the delivery id from status";return await ops.clearReport(ref.toLowerCase()),`Cleared ${ref.toLowerCase()}. That task can be ticked again.`}default:return`Unknown command "${word}".
21
+ ${HELP_TEXT}
22
+ To chat in plain text, bind an agent: \`rove weixin agent <task-id>\` on the Rove machine.`}}catch(err){return failure(err)}}import{randomBytes,randomUUID}from"crypto";var ILINK_BASE_URL="https://ilinkai.weixin.qq.com",APP_ID="bot",CHANNEL_VERSION="2.2.0",APP_CLIENT_VERSION=String(131584),BOT_TYPE="3",LONG_POLL_TIMEOUT_MS=35000,API_TIMEOUT_MS=15000,ITEM_TEXT=1,ITEM_VOICE=3,MSG_TYPE_BOT=2,MSG_STATE_FINISH=2,SESSION_EXPIRED=-14,RATE_LIMITED=-2;function resolveIlinkBaseUrl(env=process.env){return(readRoveEnv("WEIXIN_BASE_URL",env)??ILINK_BASE_URL).replace(/\/+$/,"")}function classifyIlink(resp){let ret=resp.ret??0,errcode=resp.errcode??0;if(ret===0&&errcode===0)return"ok";if(ret===SESSION_EXPIRED||errcode===SESSION_EXPIRED)return"session-expired";if(ret===RATE_LIMITED||errcode===RATE_LIMITED){let msg=(resp.errmsg??resp.msg??"").toLowerCase();return msg==="unknown error"||msg==="prepare failed"?"session-expired":"rate-limited"}return"error"}function describeIlink(resp){return`ret=${resp.ret??0} errcode=${resp.errcode??0}${resp.errmsg||resp.msg?` (${resp.errmsg??resp.msg})`:""}`}function messageText(message){let items=message.item_list??[];for(let item of items)if(item.type===ITEM_TEXT)return(item.text_item?.text??"").trim();for(let item of items)if(item.type===ITEM_VOICE&&item.voice_item?.text)return item.voice_item.text.trim();return""}function isDirectUserMessage(message){return!message.room_id&&!message.chat_room_id&&message.message_type!==MSG_TYPE_BOT}async function requestJson(fetchFn,url,init,timeoutMs){let res=await fetchFn(url,{...init,signal:AbortSignal.timeout(timeoutMs)}),raw=await res.text();if(!res.ok)throw Error(`iLink HTTP ${res.status}`);return JSON.parse(raw)}function isTimeout(err){return err instanceof Error&&(err.name==="TimeoutError"||err.name==="AbortError")}function loginHeaders(){return{"iLink-App-Id":APP_ID,"iLink-App-ClientVersion":APP_CLIENT_VERSION}}async function fetchLoginQr(baseUrl,fetchFn=fetch){let resp=await requestJson(fetchFn,`${baseUrl}/ilink/bot/get_bot_qrcode?bot_type=${BOT_TYPE}`,{method:"GET",headers:loginHeaders()},LONG_POLL_TIMEOUT_MS);if(!resp.qrcode)throw Error("iLink returned no QR code");return{qrcode:resp.qrcode,url:resp.qrcode_img_content||resp.qrcode}}async function pollLoginStatus(baseUrl,qrcode,fetchFn=fetch){let resp;try{resp=await requestJson(fetchFn,`${baseUrl}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`,{method:"GET",headers:loginHeaders()},LONG_POLL_TIMEOUT_MS)}catch(err){if(isTimeout(err))return{status:"wait"};throw err}switch(resp.status){case"scaned":case"expired":return{status:resp.status};case"scaned_but_redirect":return resp.redirect_host?{status:"redirect",baseUrl:`https://${resp.redirect_host}`}:{status:"scaned"};case"confirmed":if(!resp.ilink_bot_id||!resp.bot_token)throw Error("iLink confirmed the login without credentials");return{status:"confirmed",accountId:resp.ilink_bot_id,token:resp.bot_token,baseUrl:(resp.baseurl||baseUrl).replace(/\/+$/,""),userId:resp.ilink_user_id??""};default:return{status:"wait"}}}class IlinkClient{baseUrl;token;fetchFn;constructor(baseUrl,token,fetchFn=fetch){this.baseUrl=baseUrl;this.token=token;this.fetchFn=fetchFn}post(endpoint,payload,timeoutMs){let body=JSON.stringify({...payload,base_info:{channel_version:CHANNEL_VERSION}});return requestJson(this.fetchFn,`${this.baseUrl}/${endpoint}`,{method:"POST",headers:{"Content-Type":"application/json",AuthorizationType:"ilink_bot_token",Authorization:`Bearer ${this.token}`,"X-WECHAT-UIN":Buffer.from(String(randomBytes(4).readUInt32BE(0))).toString("base64"),...loginHeaders()},body},timeoutMs)}async getUpdates(syncBuf,timeoutMs=LONG_POLL_TIMEOUT_MS){try{return await this.post("ilink/bot/getupdates",{get_updates_buf:syncBuf},timeoutMs)}catch(err){if(isTimeout(err))return{ret:0,msgs:[],get_updates_buf:syncBuf};throw err}}sendText(to,text,contextToken){return this.post("ilink/bot/sendmessage",{msg:{from_user_id:"",to_user_id:to,client_id:`rove-weixin-${randomUUID()}`,message_type:MSG_TYPE_BOT,message_state:MSG_STATE_FINISH,item_list:[{type:ITEM_TEXT,text_item:{text}}],...contextToken?{context_token:contextToken}:{}}},API_TIMEOUT_MS)}}var PUSH_LABEL={"waiting-on-you":"Needs you",landing:"Ready to merge","ready-for-review":"Ready for review"};class GroupTracker{settled=new Map;pending=new Map;seeded=!1;observe(rows){let arrivals=[],present=new Set;for(let row of rows){if(present.add(row.taskId),!this.seeded){this.settled.set(row.taskId,row.group);continue}if(this.settled.get(row.taskId)===row.group){this.pending.delete(row.taskId);continue}if(this.pending.get(row.taskId)!==row.group){this.pending.set(row.taskId,row.group);continue}if(this.pending.delete(row.taskId),this.settled.set(row.taskId,row.group),PUSH_LABEL[row.group])arrivals.push(row)}this.seeded=!0;for(let id of[...this.settled.keys()])if(!present.has(id))this.settled.delete(id);for(let id of[...this.pending.keys()])if(!present.has(id))this.pending.delete(id);return arrivals}}class GateTracker{seen=new Set;seeded=!1;observe(gates){if(gates===null)return[];let fresh=this.seeded?gates.filter((g)=>!this.seen.has(g.id)):[];this.seeded=!0,this.seen.clear();for(let g of gates)this.seen.add(g.id);return fresh}}function renderArrivals(rows){let lines=[];for(let row of rows)lines.push(`${PUSH_LABEL[row.group]??row.group}:`,rowLine(row));let first=rows[0];if(first?.group==="waiting-on-you")lines.push(`Reply: send ${first.taskId.slice(-6)} <text>`);return lines.join(`
23
+ `)}function awaitingReport(run){return(run.status==="dispatched"||run.status==="revived")&&run.deliveryStatus==="awaiting"}class RoutineTracker{handled=new Set;seeded=!1;observe(routines){let pushes=[],current=new Set;for(let routine of routines)for(let run of routine.runs){if(current.add(run.id),this.handled.has(run.id))continue;if(!this.seeded){this.handled.add(run.id);continue}if(run.response||automationRunNeedsAttention(run.status))pushes.push({name:routine.name,run}),this.handled.add(run.id);else if(!awaitingReport(run))this.handled.add(run.id)}this.seeded=!0;for(let id of this.handled)if(!current.has(id))this.handled.delete(id);return pushes.reverse()}}function renderRoutineRuns(pushes){return pushes.map(({name,run})=>{let failed=automationRunNeedsAttention(run.status),header=`[${name}] #${run.runNumber}${failed?` ${run.status.replace(/_/g," ")}`:""}`,body=[run.response?.text,failed?run.error:void 0].filter(Boolean).join(`
24
+ `);return body?`${header}
25
+ ${body}`:header})}var RETRY_MS=2000,BUBBLE_GAP_MS=300;async function sendBubbles(client,to,text,contextToken,sleep){let bubbles=toBubbles(text);for(let i=0;i<bubbles.length;i++){let bubble=bubbles[i]??"",token=contextToken,retried=!1;for(;;){let resp;try{resp=await client.sendText(to,bubble,token)}catch(err){return{ok:!1,reason:`network: ${err instanceof Error?err.message:String(err)}`,rest:bubbles.slice(i).join(`
26
+ `)}}let outcome=classifyIlink(resp);if(outcome==="ok")break;if(!retried&&outcome==="session-expired"&&token){retried=!0,token=null;continue}if(!retried&&outcome==="rate-limited"){retried=!0,await sleep(RETRY_MS);continue}let hint=outcome==="session-expired"?" \u2014 they need to message the bot first":"";return{ok:!1,reason:`iLink refused: ${describeIlink(resp)}${hint}`,rest:bubbles.slice(i).join(`
27
+ `)}}if(i<bubbles.length-1)await sleep(BUBBLE_GAP_MS)}return{ok:!0}}import{appendFileSync,mkdirSync,readFileSync,renameSync,rmSync,writeFileSync}from"fs";import{join}from"path";var DIR_MODE=448,FILE_MODE=384,REJECTED_CAP=10;function readJson(path){try{return JSON.parse(readFileSync(path,"utf8"))}catch{return null}}function writeJson(path,value){let tmp=`${path}.${process.pid}.tmp`;writeFileSync(tmp,`${JSON.stringify(value,null,2)}
28
+ `,{mode:FILE_MODE}),renameSync(tmp,path)}function ensureDir(dir){mkdirSync(dir,{recursive:!0,mode:DIR_MODE})}class WeixinStore{dir;constructor(homeDir){this.dir=join(resolveDaemonHomeDir(homeDir),ROVE_STATE_DIR_BASENAME,"weixin")}get accountPath(){return join(this.dir,"account.json")}get statePath(){return join(this.dir,"state.json")}get undeliveredPath(){return join(this.dir,"undelivered.jsonl")}readAccount(){let raw=readJson(this.accountPath);if(!raw||typeof raw.accountId!=="string"||typeof raw.token!=="string"||!raw.accountId||!raw.token)return null;return{accountId:raw.accountId,token:raw.token,baseUrl:typeof raw.baseUrl==="string"&&raw.baseUrl?raw.baseUrl:"",ownerUserId:typeof raw.ownerUserId==="string"?raw.ownerUserId:"",allow:Array.isArray(raw.allow)?raw.allow.filter((id)=>typeof id==="string"):[],savedAt:typeof raw.savedAt==="string"?raw.savedAt:"",...raw.agent&&typeof raw.agent.taskId==="string"&&raw.agent.taskId?{agent:{taskId:raw.agent.taskId,...typeof raw.agent.tab==="string"&&raw.agent.tab?{tab:raw.agent.tab}:{}}}:{}}}writeAccount(account){ensureDir(this.dir),writeJson(this.accountPath,account)}clearAccount(){let had=this.readAccount()!==null;return rmSync(this.accountPath,{force:!0}),rmSync(this.statePath,{force:!0}),had}readState(accountId){let raw=readJson(this.statePath);if(!raw||raw.accountId!==accountId)return{accountId,syncBuf:"",peers:{},rejected:[]};return{accountId,syncBuf:typeof raw.syncBuf==="string"?raw.syncBuf:"",peers:raw.peers&&typeof raw.peers==="object"?raw.peers:{},rejected:Array.isArray(raw.rejected)?raw.rejected:[]}}writeState(state){ensureDir(this.dir),writeJson(this.statePath,{...state,rejected:state.rejected.slice(0,REJECTED_CAP)})}appendUndelivered(entry){ensureDir(this.dir),appendFileSync(this.undeliveredPath,`${JSON.stringify(entry)}
29
+ `,{mode:FILE_MODE})}readUndelivered(){let text;try{text=readFileSync(this.undeliveredPath,"utf8")}catch{return[]}let entries=[];for(let line of text.split(`
30
+ `)){if(!line.trim())continue;try{entries.push(JSON.parse(line))}catch{}}return entries}}function isAllowedSender(account,userId){return userId!==""&&(userId===account.ownerUserId||account.allow.includes(userId))}var REPLY_WINDOW_MS=86400000,ACCOUNT_RECHECK_MS=5000,RETRY_MS2=2000,BACKOFF_MS=30000,MAX_CONSECUTIVE_FAILURES=3,EXPIRED_PAUSE_MS=600000,DEFAULT_NOTIFY_TICK_MS=20000,SEEN_CAP=256;function redact(id){return id.length>8?`${id.slice(0,8)}\u2026`:id}function startWeixinBridge(deps){let now=deps.now??Date.now,pollTimeoutMs=deps.pollTimeoutMs??LONG_POLL_TIMEOUT_MS,stopped=!1,account=deps.store.readAccount(),client=null,state=null,seen=new Set,tracker=new GroupTracker,gateTracker=new GateTracker,routineTracker=new RoutineTracker,sleep=(ms)=>delay(ms,void 0,{ref:!1});async function pause(ms){let before=account?.token,until=now()+ms;while(!stopped&&now()<until)if(await sleep(Math.min(ACCOUNT_RECHECK_MS,until-now())),deps.store.readAccount()?.token!==before)return}function saveState(next){state=next,deps.store.writeState(next)}function refreshAccount(){let next=deps.store.readAccount();if(!next){let wasBound=account!==null;if(account=null,client=null,state=null,wasBound)deps.log("weixin","unbound \u2014 stopped polling"),deps.onUnbound?.();return!1}if(!client||!account||next.token!==account.token||next.accountId!==account.accountId)client=new IlinkClient(next.baseUrl||ILINK_BASE_URL,next.token,deps.fetch),state=deps.store.readState(next.accountId),deps.log("weixin",`bound to ${redact(next.accountId)} \u2014 polling`);return account=next,!0}function recordUndelivered(to,reason,text){deps.store.appendUndelivered({at:new Date(now()).toISOString(),to,reason,text}),deps.log("weixin",`push to ${redact(to)} not delivered: ${reason}`)}async function deliver(to,text){if(!client||!state)return!1;let result=await sendBubbles(client,to,text,state.peers[to]?.contextToken??null,sleep);if(!result.ok)recordUndelivered(to,result.reason,result.rest);return result.ok}async function handleInbound2(message){if(!account||!state)return;let from=message.from_user_id?.trim()??"";if(!from||from===account.accountId||!isDirectUserMessage(message))return;let id=message.message_id===void 0?"":String(message.message_id);if(id){if(seen.has(id))return;if(seen.add(id),seen.size>SEEN_CAP)seen.delete(seen.values().next().value??"")}if(!isAllowedSender(account,from)){deps.log("weixin",`dropped a message from unlisted sender ${redact(from)}`),saveState({...state,rejected:[{userId:from,at:now()},...state.rejected.filter((r)=>r.userId!==from)]});return}let peer=state.peers[from];saveState({...state,peers:{...state.peers,[from]:{contextToken:message.context_token||peer?.contextToken,lastInboundAt:now()}}});let text=messageText(message),reply=text?await handleInbound(text,deps.ops,account.agent??null):"Text messages only. Send help for commands.";if(reply)await deliver(from,reply)}async function pollLoop(){let failures=0;while(!stopped){if(!refreshAccount()||!client||!state){await pause(ACCOUNT_RECHECK_MS);continue}let resp;try{resp=await client.getUpdates(state.syncBuf,pollTimeoutMs)}catch(err){if(failures++,deps.log("weixin",`getupdates failed (${failures}): ${err instanceof Error?err.message:String(err)}`),await pause(failures>=MAX_CONSECUTIVE_FAILURES?BACKOFF_MS:RETRY_MS2),failures>=MAX_CONSECUTIVE_FAILURES)failures=0;continue}let outcome=classifyIlink(resp);if(outcome==="session-expired"){deps.log("weixin","binding expired \u2014 run `rove weixin login` again; pausing 10m"),await pause(EXPIRED_PAUSE_MS);continue}if(outcome!=="ok"){if(failures++,deps.log("weixin",`getupdates refused: ${describeIlink(resp)}`),await pause(failures>=MAX_CONSECUTIVE_FAILURES?BACKOFF_MS:RETRY_MS2),failures>=MAX_CONSECUTIVE_FAILURES)failures=0;continue}failures=0;for(let message of resp.msgs??[])try{await handleInbound2(message)}catch(err){deps.log("weixin",`inbound failed: ${err instanceof Error?err.message:String(err)}`)}if(state&&resp.get_updates_buf&&resp.get_updates_buf!==state.syncBuf)saveState({...state,syncBuf:resp.get_updates_buf})}}async function push(text){if(!account||!state)return;let targets=[...new Set([account.ownerUserId,...account.allow].filter(Boolean))];for(let to of targets){let last=state.peers[to]?.lastInboundAt;if(last===void 0||now()-last>REPLY_WINDOW_MS){recordUndelivered(to,last===void 0?"no message from this user yet":"reply window closed (>24h since their last message)",text);continue}await deliver(to,text)}}let notifying=!1;async function notifyTick(){if(notifying||stopped||!account)return;notifying=!0;try{let snapshot=await deps.ops.status(null),arrivals=tracker.observe(snapshot.tasks);if(arrivals.length>0)await push(renderArrivals(arrivals));let decisions=gateTracker.observe(snapshot.gatesUnreadable?null:snapshot.gates);if(decisions.length>0)await push(renderGateArrivals(decisions,new Map(snapshot.tasks.map((t)=>[t.taskId,t.title]))));let runs=routineTracker.observe(await deps.ops.notifyingRoutineRuns());for(let text of renderRoutineRuns(runs))await push(text)}catch(err){deps.log("weixin",`notify tick failed: ${err instanceof Error?err.message:String(err)}`)}finally{notifying=!1}}pollLoop().catch((err)=>deps.log("weixin",`poll loop died: ${err instanceof Error?err.message:String(err)}`));let notifyTimer=setInterval(()=>void notifyTick(),deps.notifyTickMs??DEFAULT_NOTIFY_TICK_MS);return notifyTimer.unref?.(),notifyTick(),{isBound:()=>account!==null,stop:()=>{stopped=!0,clearInterval(notifyTimer)}}}var STATUS_TASK_LIMIT=500;function stringField(value,key){if(value&&typeof value==="object"&&key in value){let field=Reflect.get(value,key);if(typeof field==="string")return field}return}async function liveTasks(client){let{tasks}=await client.request("task.list");return tasks.filter((t)=>t.deletion?.phase!=="queued"&&t.deletion?.phase!=="running")}function createRoveOps(client){return{status:async(repo)=>{let{payload,gatesUnreadable}=await loadContext(client,defaultApiRuntime,{repo,limit:STATUS_TASK_LIMIT});return{...payload,gatesUnreadable}},tasks:async()=>(await liveTasks(client)).map((t)=>({id:t.id,title:t.title,repo:t.repo})),repos:async()=>[...new Set([...getSavedRepos(),...(await liveTasks(client)).map((t)=>t.repo)])],send:async(taskId,tab,prompt)=>{let result=await invokeVerb("send",["--task-id",taskId,...tab?["--tab",tab]:[],"--plain","--prompt",prompt],{client}),landedTab=stringField(result,"session")?.split("::")[1],started=Boolean(result&&typeof result==="object"&&Reflect.get(result,"started")===!0);return{...landedTab?{tab:landedTab}:{},started}},gates:async()=>{let{gates}=await client.request("gate.list",{status:"open"});return gates},answerGate:async(gateId2,{option,text})=>{return{delivered:(await client.request("gate.answer",{gateId:gateId2,...option?{option}:{},...text?{text}:{},by:"weixin"})).delivered===!0}},notifyingRoutineRuns:async()=>{let{automations}=await client.request("automation.list");return await Promise.all(automations.filter((a)=>a.notify).map(async(a)=>{let{runs}=await client.request("automation.runs",{id:a.id});return{id:a.id,name:a.name,runs}}))},clearReport:async(deliveryId)=>{await invokeVerb("attention-dismiss",["--delivery",deliveryId],{client})},add:async(repo,prompt)=>{ensurePluginEnginesLoaded();let result=await invokeVerb("add",["--repo",repo,"--prompt",prompt],{client}),taskId=stringField(result,"taskId");if(!taskId)throw Error("add returned no task id");return{taskId}}}}function createWeixinChannel(){let bridge=null;return{async start(ctx){let client=new RoveDaemonClient(ctx.socketPath);try{await client.connect()}catch(err){ctx.log("weixin",`could not reach the daemon socket: ${err instanceof Error?err.message:String(err)}`);return}bridge=startWeixinBridge({store:new WeixinStore,ops:createRoveOps(client),log:(event,message)=>ctx.log(event,message),onUnbound:()=>ctx.keepAliveChanged()})},stop:()=>bridge?.stop(),keepAlive:()=>bridge?.isBound()??!1}}import{readFileSync as readFileSync2}from"fs";import{setTimeout as delay2}from"timers/promises";var import_qrcode_terminal=__toESM(require_main(),1);var MAX_QR_REFRESHES=3,DEFAULT_TIMEOUT_MS=480000,POLL_GAP_MS=1000;async function runQrLogin(store,baseUrl,io,fetchFn=fetch,timeoutMs=DEFAULT_TIMEOUT_MS){let qr=await fetchLoginQr(baseUrl,fetchFn);io.say("Scan with WeChat (\u5FAE\u4FE1 \u2192 \u626B\u4E00\u626B), then confirm on the phone:"),io.showQr(qr.url);let pollBase=baseUrl,refreshes=0,announcedScan=!1,deadline=io.now()+timeoutMs;while(io.now()<deadline){let status=await pollLoginStatus(pollBase,qr.qrcode,fetchFn).catch(()=>({status:"wait"}));switch(status.status){case"scaned":if(!announcedScan)io.say("Scanned \u2014 confirm on your phone\u2026");announcedScan=!0;break;case"redirect":pollBase=status.baseUrl;break;case"expired":if(refreshes++,refreshes>MAX_QR_REFRESHES)return{ok:!1,reason:"the QR code expired too many times"};io.say(`QR expired \u2014 here is a new one (${refreshes}/${MAX_QR_REFRESHES}):`),qr=await fetchLoginQr(baseUrl,fetchFn),pollBase=baseUrl,announcedScan=!1,io.showQr(qr.url);break;case"confirmed":{let previous=store.readAccount(),account={accountId:status.accountId,token:status.token,baseUrl:status.baseUrl,ownerUserId:status.userId,allow:previous?.accountId===status.accountId?previous.allow:[],savedAt:new Date(io.now()).toISOString()};return store.writeAccount(account),{ok:!0,account}}case"wait":break}await io.sleep(POLL_GAP_MS)}return{ok:!1,reason:"timed out waiting for the scan"}}var CLI_NAME=ROVE_PRODUCT_NAME,WEIXIN_USAGE=[`Usage: ${CLI_NAME} weixin <login|logout|status|allow|deny|send|agent>`,"","Talk to Rove from WeChat (\u5FAE\u4FE1): ask for status, message a task's agent,","start a task, and get pinged when a task needs you. The daemon must be","running for messages to flow.","","Commands:"," login Show a QR code; scan it in WeChat to bind (re-run to re-bind)"," logout Remove the binding and its credentials"," status Binding, allowed senders, reply windows, undelivered pushes"," allow <user-id> Let another WeChat user command Rove (ids: see status)"," deny <user-id> Revoke a user added with allow"," send [text] Message the owner (routines, scripts, agents). Text from the"," arguments, --file <path>, or stdin; --subject <line> prepends a header"," agent [<task-id> [tab-N]] Send plain (non-command) messages to this task's engine tab;"," no argument shows the binding, `agent off` removes it",""].join(`
31
+ `);function usageError(message){process.stderr.write(`${CLI_NAME} weixin: ${message}
32
+
33
+ ${WEIXIN_USAGE}
34
+ `),process.exit(2)}function fail(message){process.stderr.write(`${CLI_NAME} weixin: ${message}
35
+ `),process.exit(1)}function age(ms){let m=Math.floor(ms/60000);if(m<60)return`${m}m ago`;let h=Math.floor(m/60);return h<48?`${h}h ago`:`${Math.floor(h/24)}d ago`}async function runWeixinCli(argv){let[verb,arg]=argv;if(!verb||verb==="--help"||verb==="-h"||verb==="help"){process.stdout.write(`${WEIXIN_USAGE}
36
+ `);return}if(!SUBCOMMAND_VERBS.weixin.includes(verb))usageError(`unknown verb "${verb}"`);let store=new WeixinStore;switch(verb){case"login":return await login(store);case"logout":process.stdout.write(store.clearAccount()?`WeChat binding removed.
37
+ `:`No WeChat binding to remove.
38
+ `);return;case"status":return await status(store);case"allow":case"deny":return editAllow(store,verb,arg);case"send":return await send(store,argv.slice(1));case"agent":return await bindAgent(store,argv.slice(1));default:usageError(`"${verb}" has no handler`)}}async function login(store){let result=await runQrLogin(store,resolveIlinkBaseUrl(),{showQr:(url)=>{import_qrcode_terminal.default.generate(url,{small:!0},(art)=>process.stdout.write(`${art}
39
+ `)),process.stdout.write(`Or open: ${url}
40
+ `)},say:(line)=>process.stdout.write(`${line}
41
+ `),sleep:(ms)=>delay2(ms),now:Date.now}).catch((err)=>fail(`login failed: ${err instanceof Error?err.message:String(err)}`));if(!result.ok)fail(`login failed: ${result.reason}`);process.stdout.write(["Bound. Send the bot `help` from WeChat to try it.",`Credentials: ${store.accountPath} (owner-only)`,await daemonRunning()?"The running daemon picks this up within seconds.":`The daemon is not running \u2014 start it with \`${CLI_NAME} daemon start\`.`,""].join(`
42
+ `))}async function daemonRunning(){let client=await connectIfRunning().catch(()=>null);return client?.close(),client!==null}async function status(store){let account=store.readAccount();if(!account){process.stdout.write(`Not bound. Run \`${CLI_NAME} weixin login\`.
43
+ `);return}let state=store.readState(account.accountId),now=Date.now(),lines=[`Bound to bot ${account.accountId} since ${account.savedAt||"unknown"}`,`Daemon: ${await daemonRunning()?"running":`not running \u2014 \`${CLI_NAME} daemon start\``}`,`Owner: ${account.ownerUserId||"(unknown \u2014 re-run login)"}`,`Allowed: ${account.allow.length>0?account.allow.join(", "):"owner only"}`],peers=Object.entries(state.peers);if(peers.length>0){lines.push("Reply windows:");for(let[id,peer]of peers)lines.push(` ${id} last message ${age(now-peer.lastInboundAt)} \u2014 ${now-peer.lastInboundAt<=REPLY_WINDOW_MS?"open":"closed"}`)}if(state.rejected.length>0){lines.push(`Refused senders (\`${CLI_NAME} weixin allow <id>\` to let one in):`);for(let r of state.rejected)lines.push(` ${r.userId} ${age(now-r.at)}`)}let undelivered=store.readUndelivered();if(undelivered.length>0){let last=undelivered[undelivered.length-1];if(lines.push(`Undelivered pushes: ${undelivered.length} (${store.undeliveredPath})`),last)lines.push(` latest ${last.at}: ${last.reason}`)}process.stdout.write(`${lines.join(`
44
+ `)}
45
+ `)}async function readStdin(){let chunks=[];for await(let chunk of process.stdin)chunks.push(typeof chunk==="string"?Buffer.from(chunk):chunk);return Buffer.concat(chunks).toString("utf8")}async function send(store,args){let subject,file,words=[];for(let i=0;i<args.length;i++){let a=args[i]??"";if(a==="--subject"||a==="-s")subject=args[++i];else if(a==="--file"||a==="-f")file=args[++i];else words.push(a)}if(subject===void 0&&args.includes("--subject")||file===void 0&&args.includes("--file"))usageError("--subject and --file need a value");if(file!==void 0&&words.length>0)usageError("pass the text or --file, not both");let body=(file==="-"||file===void 0&&words.length===0?await readStdin():file!==void 0?readFileSync2(file,"utf8"):words.join(" ")).trim();if(!body&&!subject)usageError("nothing to send");let text=subject?body?`${subject}
46
+ ${body}`:subject:body,account=store.readAccount();if(!account)fail(`not bound \u2014 run \`${CLI_NAME} weixin login\` first`);let to=account.ownerUserId;if(!to)fail(`the binding has no owner id \u2014 re-run \`${CLI_NAME} weixin login\``);let peer=store.readState(account.accountId).peers[to],now=Date.now();if(!peer||now-peer.lastInboundAt>REPLY_WINDOW_MS){let reason=peer?"reply window closed (>24h since their last message)":"no message from the owner yet";store.appendUndelivered({at:new Date(now).toISOString(),to,reason,text}),fail(`not sent: ${reason}. WeChat only lets the bot write within a day of your last message to it.`)}let client=new IlinkClient(account.baseUrl||ILINK_BASE_URL,account.token),result=await sendBubbles(client,to,text,peer.contextToken??null,(ms)=>delay2(ms));if(!result.ok)store.appendUndelivered({at:new Date().toISOString(),to,reason:result.reason,text:result.rest}),fail(`not sent: ${result.reason}`);process.stdout.write(`Sent.
47
+ `)}async function bindAgent(store,args){let account=store.readAccount();if(!account)fail(`not bound \u2014 run \`${CLI_NAME} weixin login\` first`);let[ref,tab]=args;if(!ref){process.stdout.write(account.agent?`Plain messages go to ${account.agent.taskId}${account.agent.tab?` ${account.agent.tab}`:""}.
48
+ `:`No agent bound: plain messages get the command help. Bind one with \`${CLI_NAME} weixin agent <task-id> [tab-N]\`.
49
+ `);return}if(ref==="off"){let{agent:_dropped,...rest}=account;store.writeAccount(rest),process.stdout.write(account.agent?`Agent unbound.
50
+ `:`No agent was bound.
51
+ `);return}if(tab!==void 0&&!/^tab-[A-Za-z0-9-]+$/.test(tab))usageError(`expected a tab id like tab-2, got "${tab}"`);let taskId=await resolveTaskId(ref);store.writeAccount({...account,agent:{taskId,...tab?{tab}:{}}}),process.stdout.write(`Plain WeChat messages now go to ${taskId}${tab?` ${tab}`:""}; commands (status, send, \u2026) work as before.
52
+ `)}async function resolveTaskId(ref){let client=await connectIfRunning().catch(()=>null);if(!client)fail(`the daemon is not running \u2014 start it with \`${CLI_NAME} daemon start\``);try{let{tasks}=await client.request("task.list"),needle=ref.toLowerCase(),hits=tasks.filter((t)=>t.id.toLowerCase()===needle||t.id.toLowerCase().endsWith(needle));if(hits.length===1&&hits[0])return hits[0].id;fail(hits.length===0?`no task matches "${ref}"`:`"${ref}" matches ${hits.length} tasks; use more characters`)}finally{client.close()}}function editAllow(store,verb,userId){if(!userId)usageError(`${verb} needs a WeChat user id (see \`${CLI_NAME} weixin status\`)`);let account=store.readAccount();if(!account)fail(`not bound \u2014 run \`${CLI_NAME} weixin login\` first`);let allow=verb==="allow"?[...new Set([...account.allow,userId])]:account.allow.filter((id)=>id!==userId);store.writeAccount({...account,allow}),process.stdout.write(verb==="allow"?`Allowed ${userId}.
53
+ `:allow.length===account.allow.length?`${userId} was not on the list.
54
+ `:`Removed ${userId}.
55
+ `)}var weixin={id:"weixin",createChannel:createWeixinChannel,runCli:runWeixinCli},src_default=weixin;export{src_default as default};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{RELEASE_CHANNELS,channelOf}from"./chunk-74e3k701.js";import{loadStateFile,patchStateFile}from"./chunk-g4281a0g.js";var UPDATE_CHANNEL_KEY="update.channel";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function tryOutChannel(){return channelOf()==="nightly"?"latest":"nightly"}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}
2
+ import{RELEASE_CHANNELS,channelOf}from"./chunk-hgf4cz78.js";import{loadStateFile,patchStateFile}from"./chunk-g4281a0g.js";var UPDATE_CHANNEL_KEY="update.channel";function normalizeReleaseChannel(value){return RELEASE_CHANNELS.includes(value)?value:null}function preferredReleaseChannel(state=loadStateFile()){return normalizeReleaseChannel(state[UPDATE_CHANNEL_KEY])??channelOf()}function tryOutChannel(){return channelOf()==="nightly"?"latest":"nightly"}function rememberReleaseChannel(channel){patchStateFile({[UPDATE_CHANNEL_KEY]:channel})}
3
3
  export{UPDATE_CHANNEL_KEY,normalizeReleaseChannel,preferredReleaseChannel,tryOutChannel,rememberReleaseChannel};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{t}from"./chunk-2676cb62.js";function failureHint(error,cliName="rove"){let details=typeof error==="object"&&error!==null?error:null,hint=details&&"hint"in details&&typeof details.hint==="string"?details.hint:null,args=details&&"nextCommandArgs"in details?details.nextCommandArgs:null,command=Array.isArray(args)&&args.length>0&&args.every((arg)=>typeof arg==="string")?[cliName,...args].map((arg)=>/^[\w./:@=-]+$/.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" "):null;return[hint,command].filter(Boolean).join(`
2
+ import{t}from"./chunk-ws4cg819.js";function failureHint(error,cliName="rove"){let details=typeof error==="object"&&error!==null?error:null,hint=details&&"hint"in details&&typeof details.hint==="string"?details.hint:null,args=details&&"nextCommandArgs"in details?details.nextCommandArgs:null,command=Array.isArray(args)&&args.length>0&&args.every((arg)=>typeof arg==="string")?[cliName,...args].map((arg)=>/^[\w./:@=-]+$/.test(arg)?arg:`'${arg.replaceAll("'","'\\''")}'`).join(" "):null;return[hint,command].filter(Boolean).join(`
3
3
  `)||t("common.failureHint",{command:`${cliName} doctor`})}
4
4
  export{failureHint};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{loadPluginRegistry,readPluginManifest}from"./chunk-nwevnc6k.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-9ecnsh42.js";import{getCustomEngineIds}from"./chunk-22d0yc7m.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
2
+ import{loadPluginRegistry,readPluginManifest}from"./chunk-a2epp2ad.js";import{CONTRIB_ENGINE_IDS,clearPluginEngines,registerPluginEngine,resetAvailableVendorsCache}from"./chunk-9ecnsh42.js";import{getCustomEngineIds}from"./chunk-22d0yc7m.js";function loadPluginEngines(homeDir){let registered=[];try{for(let entry of loadPluginRegistry(homeDir).plugins){if(!entry.enabled)continue;try{let{manifest}=readPluginManifest(entry.root);for(let engine of manifest.engines){let identity={shortName:engine.identity?.shortName??engine.name};if(registerPluginEngine(engine.id,{displayName:engine.name,defaultCommand:engine.command,...engine.processNames?{processNames:engine.processNames}:{},screenManifest:{rules:engine.rules},identity,...engine.firstMessageDelivery?{firstMessageDelivery:engine.firstMessageDelivery}:{}}))registered.push(engine.id);else console.warn(`[rove] plugin ${entry.id}: engine id \`${engine.id}\` shadows a built-in or shipped engine \u2014 skipped`)}}catch{}}}catch{}return registered}function reloadPluginEngines(homeDir){clearPluginEngines();let registered=loadPluginEngines(homeDir);return loadedOnce=registered,resetAvailableVendorsCache(),registered}var loadedOnce;function ensurePluginEnginesLoaded(){return loadedOnce??=loadPluginEngines(),loadedOnce}function registeredEngineIds(){return[...new Set([...CONTRIB_ENGINE_IDS,...getCustomEngineIds(),...ensurePluginEnginesLoaded()])]}
3
3
  export{loadPluginEngines,reloadPluginEngines,ensurePluginEnginesLoaded,registeredEngineIds};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{machineTasks}from"./chunk-0wy0w6jd.js";import"./chunk-c0gvp57p.js";import{dedupeMachines,listMachines}from"./chunk-r3zkpbf5.js";import"./chunk-7t9q7k4d.js";import"./chunk-b7xjhgts.js";import"./chunk-x7r75e3p.js";import"./chunk-2brn8e1y.js";import"./chunk-7kysxgbq.js";import"./chunk-22d0yc7m.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-6ks6s8b2.js";import"./chunk-fq3s9q62.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";async function mergeTaskList(local){let machines=dedupeMachines(listMachines());if(machines.length===0)return local;let tasks=(local.tasks??[]).map((task)=>({...task,origin:{machineId:"local",hostLabel:"local"}}));for(let entry of machines){let remote=await machineTasks(entry);if(!remote)continue;let hostLabel=entry.alias;for(let task of remote)tasks.push({...task,origin:{machineId:entry.alias,hostLabel}})}return{tasks}}export{mergeTaskList};
2
+ import{machineTasks}from"./chunk-b2h6jfrg.js";import"./chunk-c0gvp57p.js";import{dedupeMachines,listMachines}from"./chunk-r3zkpbf5.js";import"./chunk-c6kw0s9a.js";import"./chunk-b7xjhgts.js";import"./chunk-x7r75e3p.js";import"./chunk-2brn8e1y.js";import"./chunk-7kysxgbq.js";import"./chunk-22d0yc7m.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-g4281a0g.js";import"./chunk-zh0c8yzw.js";import"./chunk-wqckm0k6.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-kmgheesn.js";import"./chunk-szjgjrar.js";import"./chunk-gskbzgc3.js";import"./chunk-pn5ygqn6.js";import"./chunk-n0rtj4z7.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";async function mergeTaskList(local){let machines=dedupeMachines(listMachines());if(machines.length===0)return local;let tasks=(local.tasks??[]).map((task)=>({...task,origin:{machineId:"local",hostLabel:"local"}}));for(let entry of machines){let remote=await machineTasks(entry);if(!remote)continue;let hostLabel=entry.alias;for(let task of remote)tasks.push({...task,origin:{machineId:entry.alias,hostLabel}})}return{tasks}}export{mergeTaskList};