@sma1lboy/rove 0.9.258 → 0.9.263

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 (144) hide show
  1. package/dist/cli/{chunk-x8rkpfqd.js → chunk-0079aw9z.js} +1 -1
  2. package/dist/cli/{chunk-xnaehfby.js → chunk-02f0matw.js} +1 -1
  3. package/dist/cli/chunk-09sfrqkr.js +2 -0
  4. package/dist/cli/{chunk-ke3t032y.js → chunk-0rrmz6k6.js} +1 -1
  5. package/dist/cli/{chunk-3q1rv3rm.js → chunk-1cmcaarg.js} +2 -2
  6. package/dist/cli/chunk-1gxb0bd3.js +3 -0
  7. package/dist/cli/{chunk-ebea569y.js → chunk-1h68wb7r.js} +1 -1
  8. package/dist/cli/chunk-26mf16v9.js +2 -0
  9. package/dist/cli/{chunk-1zqzqbek.js → chunk-27k612fg.js} +1 -1
  10. package/dist/cli/{chunk-jd02zgwf.js → chunk-2cbzp9t1.js} +1 -1
  11. package/dist/cli/{chunk-stcvcsfm.js → chunk-3ac75tqw.js} +1 -1
  12. package/dist/cli/{chunk-68113ts1.js → chunk-3zjdbdwy.js} +1 -1
  13. package/dist/cli/chunk-495kp7gj.js +16 -0
  14. package/dist/cli/{chunk-cq5qv93a.js → chunk-4gt375ve.js} +1 -1
  15. package/dist/cli/{chunk-sabpcket.js → chunk-4kzqv6rq.js} +1 -1
  16. package/dist/cli/{chunk-cewyvr3c.js → chunk-59g5tbc7.js} +1 -1
  17. package/dist/cli/chunk-5pkyrzfc.js +3 -0
  18. package/dist/cli/{chunk-yktnbb14.js → chunk-5v02t4pz.js} +37 -37
  19. package/dist/cli/{chunk-kgddz8pw.js → chunk-60ppphcx.js} +1 -1
  20. package/dist/cli/chunk-69dz852g.js +2 -0
  21. package/dist/cli/{chunk-8q1g1xq0.js → chunk-6qyd3ny6.js} +1 -1
  22. package/dist/cli/chunk-744netc1.js +55 -0
  23. package/dist/cli/chunk-7kwk5kxn.js +3 -0
  24. package/dist/cli/{chunk-rnxk3587.js → chunk-7y7v9x3n.js} +1 -1
  25. package/dist/cli/{chunk-9v18qy3s.js → chunk-87ar2d2r.js} +1 -1
  26. package/dist/cli/{chunk-r6f8h111.js → chunk-8mx0egn7.js} +2 -2
  27. package/dist/cli/{chunk-qpc8bv02.js → chunk-8p4ah1m9.js} +4 -4
  28. package/dist/cli/{chunk-zam29b9x.js → chunk-8vkma6c4.js} +1 -1
  29. package/dist/cli/chunk-98pfg06f.js +70 -0
  30. package/dist/cli/{chunk-edsm15ht.js → chunk-a2epp2ad.js} +1 -1
  31. package/dist/cli/{chunk-wyt2vgjv.js → chunk-a89xzxv2.js} +1 -1
  32. package/dist/cli/{chunk-0d57z680.js → chunk-aaz3wnp3.js} +1 -1
  33. package/dist/cli/{chunk-pw87thvf.js → chunk-asez7vm6.js} +1 -1
  34. package/dist/cli/{chunk-95jzkqp2.js → chunk-ax5c2qmv.js} +1 -1
  35. package/dist/cli/chunk-b2h6jfrg.js +3 -0
  36. package/dist/cli/{chunk-t25xke74.js → chunk-b3vz95wb.js} +1 -1
  37. package/dist/cli/{chunk-k2cnmb5q.js → chunk-bc72rgkm.js} +1 -1
  38. package/dist/cli/{chunk-eyzjma6q.js → chunk-bmk52w06.js} +1 -1
  39. package/dist/cli/{chunk-1egwgg6p.js → chunk-bntczetj.js} +1 -1
  40. package/dist/cli/chunk-bnv1mm5h.js +4 -0
  41. package/dist/cli/{chunk-hfvz23r6.js → chunk-c09jfhpp.js} +1 -1
  42. package/dist/cli/chunk-c0gvp57p.js +3 -0
  43. package/dist/cli/chunk-c6kw0s9a.js +4 -0
  44. package/dist/cli/{chunk-cqychwvw.js → chunk-ca4dvdj4.js} +1 -1
  45. package/dist/cli/chunk-cwk568n5.js +2 -0
  46. package/dist/cli/chunk-dnmq3c4k.js +11 -0
  47. package/dist/cli/chunk-dx12gkf5.js +2 -0
  48. package/dist/cli/{chunk-rx2604ry.js → chunk-efr0fy7z.js} +1 -1
  49. package/dist/cli/{chunk-80zzjcvp.js → chunk-f6tqc1cc.js} +1 -1
  50. package/dist/cli/{chunk-rc2nwsdd.js → chunk-fdexrh6h.js} +1 -1
  51. package/dist/cli/{chunk-jf46jsdp.js → chunk-fr4mwfe1.js} +1 -1
  52. package/dist/cli/{chunk-y0gybgba.js → chunk-gbbx9zpz.js} +1 -1
  53. package/dist/cli/chunk-gzj9nk7k.js +3 -0
  54. package/dist/cli/chunk-h8zvgpzd.js +82 -0
  55. package/dist/cli/{chunk-0604fza5.js → chunk-hk0s2bbn.js} +1 -1
  56. package/dist/cli/{chunk-y8xb4ys7.js → chunk-jqkzg4dd.js} +1 -1
  57. package/dist/cli/{chunk-hdnqq66w.js → chunk-jt994bhe.js} +1 -1
  58. package/dist/cli/chunk-jwqdhbe9.js +3 -0
  59. package/dist/cli/{chunk-s0jbtyd9.js → chunk-kmgheesn.js} +3 -2
  60. package/dist/cli/{chunk-jtpjdmb6.js → chunk-mccgj97d.js} +1 -1
  61. package/dist/cli/{chunk-pwbtezsa.js → chunk-mhbc490p.js} +1 -1
  62. package/dist/cli/{chunk-jv11f2c2.js → chunk-mqrn27h8.js} +3 -3
  63. package/dist/cli/{chunk-v7prawj1.js → chunk-n7vtv1rw.js} +1 -1
  64. package/dist/cli/chunk-ndrcjcv5.js +2 -0
  65. package/dist/cli/{chunk-t60qcvcj.js → chunk-ns2f9b6r.js} +1 -1
  66. package/dist/cli/chunk-nze6pmm7.js +2 -0
  67. package/dist/cli/{chunk-zqq3djrw.js → chunk-pdn1r8rf.js} +3 -3
  68. package/dist/cli/{chunk-1vwngrmf.js → chunk-qga9xd2f.js} +1 -1
  69. package/dist/cli/chunk-r1cvs8v1.js +2 -0
  70. package/dist/cli/chunk-r240tf5j.js +3 -0
  71. package/dist/cli/chunk-r3zkpbf5.js +9 -0
  72. package/dist/cli/chunk-r6nmjtze.js +2 -0
  73. package/dist/cli/{chunk-6p9yxt3q.js → chunk-re15t5r1.js} +1 -1
  74. package/dist/cli/{chunk-b47k0cnw.js → chunk-rtcevh2t.js} +1 -1
  75. package/dist/cli/{chunk-tpt3fn1q.js → chunk-s0x0yw8x.js} +1 -1
  76. package/dist/cli/chunk-s83qnstd.js +2 -0
  77. package/dist/cli/chunk-sgngkkp3.js +2 -0
  78. package/dist/cli/chunk-spt9e3zk.js +31 -0
  79. package/dist/cli/{chunk-yjyjg7sk.js → chunk-stng29vp.js} +2 -2
  80. package/dist/cli/{chunk-278sc87n.js → chunk-szjgjrar.js} +1 -1
  81. package/dist/cli/{chunk-6x0trw81.js → chunk-t6txrkad.js} +1 -1
  82. package/dist/cli/{chunk-kqf371ff.js → chunk-tgfn5ykb.js} +1 -1
  83. package/dist/cli/chunk-tjj9bt7n.js +3 -0
  84. package/dist/cli/chunk-tmr45c9p.js +3 -0
  85. package/dist/cli/chunk-w2d69c89.js +7 -0
  86. package/dist/cli/{chunk-mmc662x2.js → chunk-wkv4aw6c.js} +1 -1
  87. package/dist/cli/{chunk-tq6pq1ws.js → chunk-ws4cg819.js} +1 -1
  88. package/dist/cli/{chunk-ehb0hbrg.js → chunk-wv5hvxcd.js} +2 -2
  89. package/dist/cli/chunk-wv6d96t6.js +2 -0
  90. package/dist/cli/chunk-xkyf0ws5.js +20 -0
  91. package/dist/cli/{chunk-edpbz0gz.js → chunk-xn4494n9.js} +3 -3
  92. package/dist/cli/{chunk-pb5g6161.js → chunk-xt82hp6y.js} +1 -1
  93. package/dist/cli/{chunk-1xrbb7gf.js → chunk-xwyp7bvy.js} +1 -1
  94. package/dist/cli/{chunk-c8anewjn.js → chunk-y5p9wm83.js} +1 -1
  95. package/dist/cli/chunk-yhcsp07b.js +66 -0
  96. package/dist/cli/{chunk-cb7hc2xm.js → chunk-ymb3ag9d.js} +1 -1
  97. package/dist/cli/{chunk-7cd1epfw.js → chunk-yyjskza5.js} +1 -1
  98. package/dist/cli/{chunk-45thgqdr.js → chunk-zns1zx6s.js} +1 -1
  99. package/dist/cli/chunk-zr3kwred.js +3 -0
  100. package/dist/cli/index.js +4 -4
  101. package/dist/cli/pty-host-node.mjs +5 -0
  102. package/dist/cli/rove.js +1 -1
  103. package/dist/completions/rove.bash +3 -3
  104. package/dist/completions/rove.fish +3 -3
  105. package/dist/completions/rove.zsh +3 -3
  106. package/dist/skills/rove/SKILL.md +1 -1
  107. package/dist/skills/rove/references/api-flags.md +35 -16
  108. package/dist/web/assets/index-CdjFB6v7.css +1 -0
  109. package/dist/web/assets/index-bEO8TjwB.js +109 -0
  110. package/dist/web/index.html +2 -2
  111. package/package.json +3 -3
  112. package/dist/cli/chunk-1378mh2w.js +0 -3
  113. package/dist/cli/chunk-1qge84t7.js +0 -3
  114. package/dist/cli/chunk-1vxykwb9.js +0 -3
  115. package/dist/cli/chunk-2yjpqb47.js +0 -3
  116. package/dist/cli/chunk-4ab8y1yp.js +0 -15
  117. package/dist/cli/chunk-4d4d59vp.js +0 -20
  118. package/dist/cli/chunk-658859k9.js +0 -31
  119. package/dist/cli/chunk-6t5d02s4.js +0 -2
  120. package/dist/cli/chunk-79r3wbhh.js +0 -2
  121. package/dist/cli/chunk-7nr405tr.js +0 -9
  122. package/dist/cli/chunk-82zpp3yx.js +0 -4
  123. package/dist/cli/chunk-8dggnfaf.js +0 -2
  124. package/dist/cli/chunk-8gjpnb83.js +0 -41
  125. package/dist/cli/chunk-csdne12x.js +0 -3
  126. package/dist/cli/chunk-dd0mtzje.js +0 -3
  127. package/dist/cli/chunk-dqprpnd6.js +0 -3
  128. package/dist/cli/chunk-fehxbwcb.js +0 -6
  129. package/dist/cli/chunk-g846fbp7.js +0 -52
  130. package/dist/cli/chunk-hkv6t5v9.js +0 -2
  131. package/dist/cli/chunk-jetsx9zr.js +0 -3
  132. package/dist/cli/chunk-q301ewyq.js +0 -2
  133. package/dist/cli/chunk-qn04z4zb.js +0 -2
  134. package/dist/cli/chunk-rmk69hvh.js +0 -2
  135. package/dist/cli/chunk-s1rg1zae.js +0 -3
  136. package/dist/cli/chunk-skpkscne.js +0 -11
  137. package/dist/cli/chunk-sma961wh.js +0 -3
  138. package/dist/cli/chunk-x7cv6deh.js +0 -2
  139. package/dist/cli/chunk-y85e24s9.js +0 -2
  140. package/dist/cli/chunk-ya0h6hcd.js +0 -31
  141. package/dist/cli/chunk-yaqkajw4.js +0 -82
  142. package/dist/cli/chunk-yc9bytrj.js +0 -2
  143. package/dist/web/assets/index-BiUiNIOp.css +0 -1
  144. package/dist/web/assets/index-jy27XaL0.js +0 -109
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ensurePluginEnginesLoaded,loadPluginEngines,registeredEngineIds,reloadPluginEngines}from"./chunk-t60qcvcj.js";import"./chunk-edsm15ht.js";import"./chunk-9ecnsh42.js";import"./chunk-w7zv47mp.js";import"./chunk-2brn8e1y.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-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-278sc87n.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{reloadPluginEngines,registeredEngineIds,loadPluginEngines,ensurePluginEnginesLoaded};
2
+ import{ensurePluginEnginesLoaded,loadPluginEngines,registeredEngineIds,reloadPluginEngines}from"./chunk-ns2f9b6r.js";import"./chunk-a2epp2ad.js";import"./chunk-9ecnsh42.js";import"./chunk-w7zv47mp.js";import"./chunk-2brn8e1y.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-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-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{reloadPluginEngines,registeredEngineIds,loadPluginEngines,ensurePluginEnginesLoaded};
@@ -0,0 +1,3 @@
1
+ // @bun
2
+ import{findVerb}from"./chunk-495kp7gj.js";import{VERB_GROUP_IDS}from"./chunk-x7r75e3p.js";import{loadStateFile,updateStateFile}from"./chunk-g4281a0g.js";var INBOUND_KEY="machineInbound",INBOUND_CLASSES=[...VERB_GROUP_IDS,"land"],LAND_VERBS=new Set(["land","publish"]);function inboundClassOf(verb){if(LAND_VERBS.has(verb))return"land";return findVerb(verb)?.group??null}function deniedClasses(state=loadStateFile()){let raw=state[INBOUND_KEY],deny=raw&&typeof raw==="object"?raw.deny:void 0;return Array.isArray(deny)?deny.filter((c)=>typeof c==="string"):[]}function inboundRefusal(verb,state){let cls=inboundClassOf(verb);return cls&&deniedClasses(state).includes(cls)?cls:null}function setInbound(cls,allow){let next=[];return updateStateFile((state)=>{let current=new Set(deniedClasses(state));if(allow)current.delete(cls);else current.add(cls);return next=[...current].sort(),state[INBOUND_KEY]={deny:next},!0}),next}
3
+ export{INBOUND_KEY,INBOUND_CLASSES,inboundClassOf,deniedClasses,inboundRefusal,setInbound};
@@ -1,5 +1,40 @@
1
1
  // @bun
2
- import{RoveDaemonClient}from"./chunk-s0jbtyd9.js";import{defaultDaemonSocketPath,defaultPtyHostSocketPath}from"./chunk-n0rtj4z7.js";import{spawn as spawn2}from"child_process";import{appendFileSync,closeSync,mkdirSync,openSync}from"fs";import{dirname}from"path";import{join,resolve}from"path";var PTY_JOB_ENV="ROVE_PTY_JOB",PTY_JOB_OWNER_ENV="ROVE_PTY_JOB_OWNER",PTY_JOB_LAUNCHER_CS=`
2
+ import{RoveDaemonClient}from"./chunk-kmgheesn.js";import{defaultDaemonSocketPath,defaultPtyHostSocketPath}from"./chunk-n0rtj4z7.js";import{spawn}from"child_process";import{existsSync}from"fs";import{join}from"path";var LAUNCH_CMD_ENV="ROVE_LAUNCH_CMD",LAUNCH_LOG_ENV="ROVE_LAUNCH_LOG",WIN_DETACHED_LAUNCHER_PS=`
3
+ $ErrorActionPreference = 'Stop'
4
+ $cmd = $env:${LAUNCH_CMD_ENV}
5
+ $log = $env:${LAUNCH_LOG_ENV}
6
+ if (-not $cmd -or -not $log) { [Console]::Error.WriteLine('rove launcher: ${LAUNCH_CMD_ENV}/${LAUNCH_LOG_ENV} not set'); exit 1 }
7
+ Remove-Item Env:${LAUNCH_CMD_ENV}, Env:${LAUNCH_LOG_ENV}
8
+ Add-Type -TypeDefinition @'
9
+ using System;
10
+ using System.Runtime.InteropServices;
11
+ public static class RoveDetachedLaunch {
12
+ [StructLayout(LayoutKind.Sequential)] public struct SA { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
13
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct SI { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags; public short wShowWindow, cbReserved2; public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError; }
14
+ [StructLayout(LayoutKind.Sequential)] public struct PI { public IntPtr hProcess, hThread; public int dwProcessId, dwThreadId; }
15
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr CreateFile(string name, uint access, uint share, ref SA sa, uint disposition, uint flags, IntPtr template);
16
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool CreateProcess(string app, string cmd, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr env, string cwd, ref SI si, out PI pi);
17
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
18
+ public static int Launch(string cmd, string log) {
19
+ SA sa = new SA(); sa.nLength = Marshal.SizeOf(sa); sa.bInheritHandle = true;
20
+ // FILE_APPEND_DATA | GENERIC_READ, shared read/write, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL
21
+ IntPtr h = CreateFile(log, 0x0004 | 0x80000000, 0x1 | 0x2, ref sa, 4, 0x80, IntPtr.Zero);
22
+ if (h == (IntPtr)(-1)) throw new Exception("CreateFile(" + log + ") failed: " + Marshal.GetLastWin32Error());
23
+ IntPtr nul = CreateFile("NUL", 0x80000000, 0x1 | 0x2, ref sa, 3, 0x80, IntPtr.Zero);
24
+ SI si = new SI(); si.cb = Marshal.SizeOf(si);
25
+ si.dwFlags = 0x100 | 0x1; // STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
26
+ si.wShowWindow = 0; // SW_HIDE
27
+ si.hStdInput = nul; si.hStdOutput = h; si.hStdError = h;
28
+ PI pi;
29
+ uint flags = 0x00000010 | 0x01000000 | 0x00000200; // CREATE_NEW_CONSOLE | CREATE_BREAKAWAY_FROM_JOB | CREATE_NEW_PROCESS_GROUP
30
+ if (!CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, null, ref si, out pi)) throw new Exception("CreateProcess failed: " + Marshal.GetLastWin32Error());
31
+ CloseHandle(h); CloseHandle(nul); CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
32
+ return pi.dwProcessId;
33
+ }
34
+ }
35
+ '@
36
+ [RoveDetachedLaunch]::Launch($cmd, $log) | Out-Null
37
+ `;function windowsCommandLine(argv){return argv.map(quoteWindowsArg).join(" ")}function quoteWindowsArg(arg){if(arg!==""&&!/[\s"]/.test(arg))return arg;let out='"',backslashes=0;for(let ch of arg){if(ch==="\\"){backslashes++;continue}if(ch==='"'){out+=`${"\\".repeat(backslashes*2+1)}"`,backslashes=0;continue}out+="\\".repeat(backslashes)+ch,backslashes=0}return`${out}${"\\".repeat(backslashes*2)}"`}function windowsPowershellPath(env=process.env,exists=existsSync){let root=env.SystemRoot||env.windir||"C:\\Windows",absolute=join(root,"System32","WindowsPowerShell","v1.0","powershell.exe");return exists(absolute)?absolute:"powershell.exe"}function encodePowershellCommand(script){return Buffer.from(script,"utf16le").toString("base64")}function windowsDetachedLauncherArgs(){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",encodePowershellCommand(WIN_DETACHED_LAUNCHER_PS)]}function spawnWindowsDetached(command,args,env,logPath,spawnImpl=spawn){let child=spawnImpl(windowsPowershellPath(env),windowsDetachedLauncherArgs(),{windowsHide:!0,stdio:"ignore",env:{...env,[LAUNCH_CMD_ENV]:windowsCommandLine([command,...args]),[LAUNCH_LOG_ENV]:logPath}});return child.unref(),child}import{spawn as spawn2}from"child_process";import{appendFileSync,closeSync,mkdirSync,openSync}from"fs";import{dirname}from"path";import{join as join2,resolve}from"path";var PTY_JOB_ENV="ROVE_PTY_JOB",PTY_JOB_OWNER_ENV="ROVE_PTY_JOB_OWNER",PTY_JOB_LAUNCHER_CS=`
3
38
  using System;
4
39
  using System.Runtime.InteropServices;
5
40
  using System.Text;
@@ -56,41 +91,6 @@ static class RovePtyJob {
56
91
  return (int)code;
57
92
  }
58
93
  }
59
- `;function sameSocket(a,b){let norm=(p)=>resolve(p.replace(/\//g,"\\")).toLowerCase();return norm(a)===norm(b)}function withoutPtyJob(env){let out={...env};return delete out[PTY_JOB_ENV],delete out[PTY_JOB_OWNER_ENV],out}function ptyJobLaunch(env,ownDaemonSocket){let job=env[PTY_JOB_ENV],owner=env[PTY_JOB_OWNER_ENV];if(!job||!owner)return null;return{job,mode:sameSocket(owner,ownDaemonSocket)?"escape":"join"}}import{spawn}from"child_process";import{existsSync}from"fs";import{join as join2}from"path";var LAUNCH_CMD_ENV="ROVE_LAUNCH_CMD",LAUNCH_LOG_ENV="ROVE_LAUNCH_LOG",WIN_DETACHED_LAUNCHER_PS=`
60
- $ErrorActionPreference = 'Stop'
61
- $cmd = $env:${LAUNCH_CMD_ENV}
62
- $log = $env:${LAUNCH_LOG_ENV}
63
- if (-not $cmd -or -not $log) { [Console]::Error.WriteLine('rove launcher: ${LAUNCH_CMD_ENV}/${LAUNCH_LOG_ENV} not set'); exit 1 }
64
- Remove-Item Env:${LAUNCH_CMD_ENV}, Env:${LAUNCH_LOG_ENV}
65
- Add-Type -TypeDefinition @'
66
- using System;
67
- using System.Runtime.InteropServices;
68
- public static class RoveDetachedLaunch {
69
- [StructLayout(LayoutKind.Sequential)] public struct SA { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
70
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct SI { public int cb; public string lpReserved; public string lpDesktop; public string lpTitle; public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags; public short wShowWindow, cbReserved2; public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError; }
71
- [StructLayout(LayoutKind.Sequential)] public struct PI { public IntPtr hProcess, hThread; public int dwProcessId, dwThreadId; }
72
- [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr CreateFile(string name, uint access, uint share, ref SA sa, uint disposition, uint flags, IntPtr template);
73
- [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool CreateProcess(string app, string cmd, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr env, string cwd, ref SI si, out PI pi);
74
- [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
75
- public static int Launch(string cmd, string log) {
76
- SA sa = new SA(); sa.nLength = Marshal.SizeOf(sa); sa.bInheritHandle = true;
77
- // FILE_APPEND_DATA | GENERIC_READ, shared read/write, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL
78
- IntPtr h = CreateFile(log, 0x0004 | 0x80000000, 0x1 | 0x2, ref sa, 4, 0x80, IntPtr.Zero);
79
- if (h == (IntPtr)(-1)) throw new Exception("CreateFile(" + log + ") failed: " + Marshal.GetLastWin32Error());
80
- IntPtr nul = CreateFile("NUL", 0x80000000, 0x1 | 0x2, ref sa, 3, 0x80, IntPtr.Zero);
81
- SI si = new SI(); si.cb = Marshal.SizeOf(si);
82
- si.dwFlags = 0x100 | 0x1; // STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
83
- si.wShowWindow = 0; // SW_HIDE
84
- si.hStdInput = nul; si.hStdOutput = h; si.hStdError = h;
85
- PI pi;
86
- uint flags = 0x00000010 | 0x01000000 | 0x00000200; // CREATE_NEW_CONSOLE | CREATE_BREAKAWAY_FROM_JOB | CREATE_NEW_PROCESS_GROUP
87
- if (!CreateProcess(null, cmd, IntPtr.Zero, IntPtr.Zero, true, flags, IntPtr.Zero, null, ref si, out pi)) throw new Exception("CreateProcess failed: " + Marshal.GetLastWin32Error());
88
- CloseHandle(h); CloseHandle(nul); CloseHandle(pi.hThread); CloseHandle(pi.hProcess);
89
- return pi.dwProcessId;
90
- }
91
- }
92
- '@
93
- [RoveDetachedLaunch]::Launch($cmd, $log) | Out-Null
94
- `;function windowsCommandLine(argv){return argv.map(quoteWindowsArg).join(" ")}function quoteWindowsArg(arg){if(arg!==""&&!/[\s"]/.test(arg))return arg;let out='"',backslashes=0;for(let ch of arg){if(ch==="\\"){backslashes++;continue}if(ch==='"'){out+=`${"\\".repeat(backslashes*2+1)}"`,backslashes=0;continue}out+="\\".repeat(backslashes)+ch,backslashes=0}return`${out}${"\\".repeat(backslashes*2)}"`}function windowsPowershellPath(env=process.env,exists=existsSync){let root=env.SystemRoot||env.windir||"C:\\Windows",absolute=join2(root,"System32","WindowsPowerShell","v1.0","powershell.exe");return exists(absolute)?absolute:"powershell.exe"}function encodePowershellCommand(script){return Buffer.from(script,"utf16le").toString("base64")}function windowsDetachedLauncherArgs(){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",encodePowershellCommand(WIN_DETACHED_LAUNCHER_PS)]}function spawnWindowsDetached(command,args,env,logPath,spawnImpl=spawn){let child=spawnImpl(windowsPowershellPath(env),windowsDetachedLauncherArgs(),{windowsHide:!0,stdio:"ignore",env:{...env,[LAUNCH_CMD_ENV]:windowsCommandLine([command,...args]),[LAUNCH_LOG_ENV]:logPath}});return child.unref(),child}var ESCAPE_REQUEST_TIMEOUT_MS=5000;function appendLaunchLog(logPath,line){try{appendFileSync(logPath,`[${new Date().toISOString()}] rove: ${line}
94
+ `;function sameSocket(a,b){let norm=(p)=>resolve(p.replace(/\//g,"\\")).toLowerCase();return norm(a)===norm(b)}function withoutPtyJob(env){let out={...env};return delete out[PTY_JOB_ENV],delete out[PTY_JOB_OWNER_ENV],out}function ptyJobLaunch(env,ownDaemonSocket){let job=env[PTY_JOB_ENV],owner=env[PTY_JOB_OWNER_ENV];if(!job||!owner)return null;return{job,mode:sameSocket(owner,ownDaemonSocket)?"escape":"join"}}var ESCAPE_REQUEST_TIMEOUT_MS=5000;function appendLaunchLog(logPath,line){try{appendFileSync(logPath,`[${new Date().toISOString()}] rove: ${line}
95
95
  `)}catch{}}async function launchViaPtyHost(command,args,env,logPath,socketPath){let client=new RoveDaemonClient(socketPath),timer;try{await Promise.race([client.request("spawn.detached",{command,args:[...args],env,logPath}),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error("timed out")),ESCAPE_REQUEST_TIMEOUT_MS)})])}finally{if(timer)clearTimeout(timer);client.close()}}function detachOptions(platform=process.platform){return platform==="win32"?{windowsHide:!0}:{detached:!0}}function spawnDetachedDaemon(command,args,env,logPath,platform=process.platform){try{mkdirSync(dirname(logPath),{recursive:!0})}catch{}if(platform==="win32"){if(ptyJobLaunch(env,defaultDaemonSocketPath())?.mode==="escape"){let free=withoutPtyJob(env);launchViaPtyHost(command,args,free,logPath,defaultPtyHostSocketPath()).catch((err)=>{appendLaunchLog(logPath,`PTY host could not launch outside the tab (${err.message}) \u2014 it ends with the tab`),launchWindowsDetached(command,args,free,logPath,platform)});return}launchWindowsDetached(command,args,env,logPath,platform);return}spawnDirect(command,args,env,logPath,platform)}function launchWindowsDetached(command,args,env,logPath,platform){let launcher=spawnWindowsDetached(command,args,env,logPath),fallback=(reason)=>{appendLaunchLog(logPath,`detached launcher ${reason} \u2014 spawning directly; this process will not outlive its parent`),spawnDirect(command,args,env,logPath,platform)};launcher.once("error",(err)=>fallback(`could not start (${err.message})`)),launcher.once("exit",(code,signal)=>{if(code!==0)fallback(`exited ${code??signal}`)})}function spawnDirect(command,args,env,logPath,platform){let stdio="ignore",logFd;try{mkdirSync(dirname(logPath),{recursive:!0}),logFd=openSync(logPath,"a"),stdio=["ignore",logFd,logFd]}catch{stdio="ignore"}if(spawn2(command,[...args],{...detachOptions(platform),stdio,env}).unref(),logFd!==void 0)try{closeSync(logFd)}catch{}}
96
96
  export{withoutPtyJob,windowsPowershellPath,detachOptions,spawnDetachedDaemon};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{launchTui,trackWelcomeWrite}from"./chunk-y0gybgba.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
2
+ import{launchTui,trackWelcomeWrite}from"./chunk-gbbx9zpz.js";import"./chunk-91sykzqq.js";export{trackWelcomeWrite,launchTui};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{ENGINE_NOT_OBSERVED_REASON,ENGINE_START_POLL_MS,ENGINE_START_PROBE_MS,deliverHostedPrompt,deliverToKey,ensurePtyHost,findEngineKey,isTaskKey,killTaskSessions,listSessions,listSessionsOrNull,openPtyHost,outcomeFields,taskKeys}from"./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-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-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{taskKeys,outcomeFields,openPtyHost,listSessionsOrNull,listSessions,killTaskSessions,isTaskKey,findEngineKey,ensurePtyHost,deliverToKey,deliverHostedPrompt,ENGINE_START_PROBE_MS,ENGINE_START_POLL_MS,ENGINE_NOT_OBSERVED_REASON};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{submitFeedback}from"./chunk-cq5qv93a.js";import"./chunk-1xrbb7gf.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";var CLI_NAME=ROVE_PRODUCT_NAME,FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--category <slug>]`,"","Create a GitHub Discussion in the Rove repository using the GitHub CLI.","","Requires:"," gh auth login","","Options:"," --title <text> Discussion title"," --body <text> Discussion body"," --body-file <path> Read the Discussion body from a file; use - for stdin"," --category <slug> Discussion category slug (default: feedback)"," -h, --help Print this help",""].join(`
2
+ import{submitFeedback}from"./chunk-4gt375ve.js";import"./chunk-xwyp7bvy.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{readFileSync}from"fs";var CLI_NAME=ROVE_PRODUCT_NAME,FEEDBACK_USAGE=[`Usage: ${CLI_NAME} feedback --title <text> (--body <text> | --body-file <path>) [--category <slug>]`,"","Create a GitHub Discussion in the Rove repository using the GitHub CLI.","","Requires:"," gh auth login","","Options:"," --title <text> Discussion title"," --body <text> Discussion body"," --body-file <path> Read the Discussion body from a file; use - for stdin"," --category <slug> Discussion category slug (default: feedback)"," -h, --help Print this help",""].join(`
3
3
  `);function usageError(message){process.stderr.write(`${CLI_NAME} feedback: ${message}
4
4
 
5
5
  ${FEEDBACK_USAGE}
@@ -0,0 +1,55 @@
1
+ // @bun
2
+ import{invokeVerb}from"./chunk-w2d69c89.js";import"./chunk-87ar2d2r.js";import{defaultApiRuntime,loadContext}from"./chunk-495kp7gj.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-4gt375ve.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-xwyp7bvy.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};