@ashx-j/lunr 0.2.23 → 0.2.24

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 (222) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/README.md +10 -10
  3. package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
  4. package/dist/builtin-extensions/ashxj-tui.js +2 -2
  5. package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
  6. package/dist/builtin-extensions/lunr-plan-tools.d.ts +7 -7
  7. package/dist/builtin-extensions/lunr-plan-tools.d.ts.map +1 -1
  8. package/dist/builtin-extensions/lunr-plan-tools.js +12 -12
  9. package/dist/builtin-extensions/lunr-plan-tools.js.map +1 -1
  10. package/dist/builtin-extensions/pi-intercom/index.d.ts.map +1 -1
  11. package/dist/builtin-extensions/pi-intercom/index.js +2 -0
  12. package/dist/builtin-extensions/pi-intercom/index.js.map +1 -1
  13. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
  14. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +1 -0
  15. package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
  16. package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
  17. package/dist/builtin-extensions/pi-mcp-adapter/index.js +1 -1
  18. package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
  19. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
  20. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +1 -1
  21. package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
  22. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +4 -4
  23. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
  24. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +6 -4
  25. package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
  26. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts +2 -0
  27. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts.map +1 -1
  28. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js +6 -3
  29. package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js.map +1 -1
  30. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts.map +1 -1
  31. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js +7 -2
  32. package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js.map +1 -1
  33. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts +2 -0
  34. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
  35. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +4 -0
  36. package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
  37. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
  38. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +1 -1
  39. package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
  40. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts +1 -0
  41. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
  42. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +5 -1
  43. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
  44. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
  45. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +3 -2
  46. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
  47. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
  48. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +19 -0
  49. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
  50. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts +1 -1
  51. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts.map +1 -1
  52. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js +1 -1
  53. package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js.map +1 -1
  54. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts +2 -0
  55. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts.map +1 -1
  56. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js +17 -15
  57. package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js.map +1 -1
  58. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.d.ts.map +1 -1
  59. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js +3 -1
  60. package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js.map +1 -1
  61. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
  62. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +2 -2
  63. package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
  64. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +1 -0
  65. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  66. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  67. package/dist/core/agent-session.d.ts +1 -1
  68. package/dist/core/agent-session.d.ts.map +1 -1
  69. package/dist/core/agent-session.js +5 -4
  70. package/dist/core/agent-session.js.map +1 -1
  71. package/dist/core/browser/schema.d.ts +1 -1
  72. package/dist/core/browser/schema.d.ts.map +1 -1
  73. package/dist/core/browser/schema.js +1 -1
  74. package/dist/core/browser/schema.js.map +1 -1
  75. package/dist/core/catalog-cache-scope.d.ts.map +1 -1
  76. package/dist/core/catalog-cache-scope.js +3 -1
  77. package/dist/core/catalog-cache-scope.js.map +1 -1
  78. package/dist/core/model-runtime.d.ts.map +1 -1
  79. package/dist/core/model-runtime.js +3 -2
  80. package/dist/core/model-runtime.js.map +1 -1
  81. package/dist/core/permissions.d.ts +16 -23
  82. package/dist/core/permissions.d.ts.map +1 -1
  83. package/dist/core/permissions.js +66 -141
  84. package/dist/core/permissions.js.map +1 -1
  85. package/dist/core/plan-mode.d.ts +10 -12
  86. package/dist/core/plan-mode.d.ts.map +1 -1
  87. package/dist/core/plan-mode.js +16 -18
  88. package/dist/core/plan-mode.js.map +1 -1
  89. package/dist/core/runtime-bridges.d.ts.map +1 -1
  90. package/dist/core/runtime-bridges.js +2 -0
  91. package/dist/core/runtime-bridges.js.map +1 -1
  92. package/dist/core/sdk.d.ts.map +1 -1
  93. package/dist/core/sdk.js +13 -6
  94. package/dist/core/sdk.js.map +1 -1
  95. package/dist/core/session-manager.d.ts.map +1 -1
  96. package/dist/core/session-manager.js +9 -2
  97. package/dist/core/session-manager.js.map +1 -1
  98. package/dist/core/settings-manager.d.ts +9 -1
  99. package/dist/core/settings-manager.d.ts.map +1 -1
  100. package/dist/core/settings-manager.js +40 -1
  101. package/dist/core/settings-manager.js.map +1 -1
  102. package/dist/core/slash-commands.d.ts.map +1 -1
  103. package/dist/core/slash-commands.js +4 -4
  104. package/dist/core/slash-commands.js.map +1 -1
  105. package/dist/core/subagent-permission-inherit.d.ts +6 -10
  106. package/dist/core/subagent-permission-inherit.d.ts.map +1 -1
  107. package/dist/core/subagent-permission-inherit.js +14 -14
  108. package/dist/core/subagent-permission-inherit.js.map +1 -1
  109. package/dist/core/system-prompt.d.ts +2 -0
  110. package/dist/core/system-prompt.d.ts.map +1 -1
  111. package/dist/core/system-prompt.js +9 -4
  112. package/dist/core/system-prompt.js.map +1 -1
  113. package/dist/gateway/adapters/discord.d.ts.map +1 -1
  114. package/dist/gateway/adapters/discord.js +1 -1
  115. package/dist/gateway/adapters/discord.js.map +1 -1
  116. package/dist/gateway/approval.d.ts +2 -6
  117. package/dist/gateway/approval.d.ts.map +1 -1
  118. package/dist/gateway/approval.js +3 -7
  119. package/dist/gateway/approval.js.map +1 -1
  120. package/dist/gateway/mobile-commands.d.ts.map +1 -1
  121. package/dist/gateway/mobile-commands.js +12 -11
  122. package/dist/gateway/mobile-commands.js.map +1 -1
  123. package/dist/gateway/router.d.ts.map +1 -1
  124. package/dist/gateway/router.js +1 -1
  125. package/dist/gateway/router.js.map +1 -1
  126. package/dist/main.d.ts.map +1 -1
  127. package/dist/main.js +1 -2
  128. package/dist/main.js.map +1 -1
  129. package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
  130. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  131. package/dist/modes/interactive/components/settings-selector.js +23 -3
  132. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  133. package/dist/modes/interactive/components/thinking-tail.d.ts.map +1 -1
  134. package/dist/modes/interactive/components/thinking-tail.js +2 -2
  135. package/dist/modes/interactive/components/thinking-tail.js.map +1 -1
  136. package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
  137. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  138. package/dist/modes/interactive/components/tool-execution.js +12 -2
  139. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  140. package/dist/modes/interactive/interactive-mode.d.ts +1 -2
  141. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  142. package/dist/modes/interactive/interactive-mode.js +76 -90
  143. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  144. package/dist/node-runtime/{agent-session-services-GZVSOGYR.js → agent-session-services-IEF7LQWD.js} +8 -9
  145. package/dist/node-runtime/{builtin-extensions-QVCXNQT4.js → builtin-extensions-EBAWTH4M.js} +3 -3
  146. package/dist/node-runtime/{chunk-XLTL257W.js → chunk-2KIPT4HJ.js} +5 -1
  147. package/dist/node-runtime/{chunk-YHQ3NBB3.js → chunk-5Q3EHOHI.js} +17 -17
  148. package/dist/node-runtime/{chunk-TQGPP4SC.js → chunk-CDVHZOOK.js} +1 -1
  149. package/dist/node-runtime/{chunk-DQMGU675.js → chunk-DE2JB6J5.js} +20 -17
  150. package/dist/node-runtime/{chunk-YJMMG7C6.js → chunk-DSIKTUPW.js} +1 -1
  151. package/dist/node-runtime/{chunk-TVJUOJZJ.js → chunk-F4FLTQKV.js} +1 -1
  152. package/dist/node-runtime/{chunk-GMHJCCEN.js → chunk-FU6OODRZ.js} +4 -1
  153. package/dist/node-runtime/{chunk-OFKSVRV7.js → chunk-GYIXXQAO.js} +1 -1
  154. package/dist/node-runtime/{chunk-BX2RB477.js → chunk-HFVZUPFJ.js} +1 -1
  155. package/dist/node-runtime/{chunk-AZJHNQKQ.js → chunk-I54LGHWM.js} +1 -1
  156. package/dist/node-runtime/{chunk-DD5YWFSJ.js → chunk-IGV54Q5V.js} +2 -2
  157. package/dist/node-runtime/{chunk-RIR5EDDJ.js → chunk-K5AGHH57.js} +17 -12
  158. package/dist/node-runtime/{chunk-GS66LV4M.js → chunk-KJ6DWS3K.js} +4 -4
  159. package/dist/node-runtime/{chunk-LLUIPGDR.js → chunk-L3LX4SNR.js} +108 -75
  160. package/dist/node-runtime/{chunk-VSELYKWU.js → chunk-LWYIVUGV.js} +2 -1
  161. package/dist/node-runtime/{chunk-JHYKXIMM.js → chunk-MPKSOJBT.js} +1 -1
  162. package/dist/node-runtime/{chunk-W64JC4E7.js → chunk-OF7PWMG4.js} +2 -2
  163. package/dist/node-runtime/{chunk-CSUZVNYE.js → chunk-OVX6X377.js} +10 -6
  164. package/dist/node-runtime/{chunk-X3URCYCU.js → chunk-QM43FEAE.js} +14 -14
  165. package/dist/node-runtime/{chunk-QAZOULTU.js → chunk-RORY2HMJ.js} +39 -5
  166. package/dist/node-runtime/{chunk-EKVFP6YF.js → chunk-WHLRAGUQ.js} +13 -12
  167. package/dist/node-runtime/{chunk-HPUP7E4T.js → chunk-Y73WPE6S.js} +16 -16
  168. package/dist/node-runtime/{chunk-LFZDVKSP.js → chunk-YVI6L6LU.js} +5 -5
  169. package/dist/node-runtime/{chunk-5D7LC2ZQ.js → chunk-ZXSGTGJ6.js} +54 -85
  170. package/dist/node-runtime/cli-runtime.js +1 -1
  171. package/dist/node-runtime/{command-PDVTBRWA.js → command-7BG7VVTS.js} +3 -3
  172. package/dist/node-runtime/{commands-KAMO2T6P.js → commands-NZLSOHPE.js} +2 -2
  173. package/dist/node-runtime/{commands-XDCFGIGW.js → commands-QFDKNQTL.js} +7 -7
  174. package/dist/node-runtime/{direct-tool-executor-YAVOLDFY.js → direct-tool-executor-77GW4F5P.js} +3 -3
  175. package/dist/node-runtime/{export-html-KSOIMVPI.js → export-html-VM4J2MNR.js} +1 -1
  176. package/dist/node-runtime/{gateway-AYWM5DIO.js → gateway-TWR3N65G.js} +12 -12
  177. package/dist/node-runtime/index.js +16 -17
  178. package/dist/node-runtime/{init-X2LIUB2H.js → init-HS6NQXSK.js} +2 -2
  179. package/dist/node-runtime/{install-cli-3BO4MMQ6.js → install-cli-VAP6KBFN.js} +1 -1
  180. package/dist/node-runtime/{interactive-mode-4MFRKAHG.js → interactive-mode-6J5VZ2TT.js} +10 -11
  181. package/dist/node-runtime/{interactive-view-TUZHCQM3.js → interactive-view-NGFAMHPW.js} +2 -2
  182. package/dist/node-runtime/{lunr-browser-RYFIIVJN.js → lunr-browser-J5ZZYVGM.js} +1 -1
  183. package/dist/node-runtime/{lunr-cron-YWXEPZMQ.js → lunr-cron-CXOL37AL.js} +5 -5
  184. package/dist/node-runtime/main.js +14 -15
  185. package/dist/node-runtime/{mobile-commands-LVHDAUDP.js → mobile-commands-VTBM5DSZ.js} +4 -4
  186. package/dist/node-runtime/{model-runtime-PLQKAG4B.js → model-runtime-OO5HFLWE.js} +1 -1
  187. package/dist/node-runtime/{package-manager-cli-6GT3Z3CK.js → package-manager-cli-ZLW5DZXF.js} +3 -4
  188. package/dist/node-runtime/{pi-intercom-HBPK5HSJ.js → pi-intercom-QM53RLTS.js} +2 -0
  189. package/dist/node-runtime/{pi-mcp-adapter-E6WULBKF.js → pi-mcp-adapter-5UKBZP44.js} +7 -6
  190. package/dist/node-runtime/{pi-subagents-CDWK2AKY.js → pi-subagents-XPCLLKIM.js} +23 -13
  191. package/dist/node-runtime/{proxy-modes-OSQCWRBI.js → proxy-modes-LGEUYD7R.js} +3 -3
  192. package/dist/node-runtime/rpc-entry.js +14 -15
  193. package/dist/node-runtime/{runtime-bridges-3XUQ46XW.js → runtime-bridges-QYXUX2TG.js} +8 -1
  194. package/dist/node-runtime/{session-handoff-HC7R5E24.js → session-handoff-GWARVEWT.js} +2 -2
  195. package/dist/node-runtime/{session-manager-CFN4UFM2.js → session-manager-JB5J6XBN.js} +1 -1
  196. package/dist/node-runtime/{settings-manager-6VEMXRDL.js → settings-manager-WCQDUVQB.js} +7 -4
  197. package/dist/node-runtime/{setup-5SR2J35A.js → setup-YRBKH2LD.js} +2 -2
  198. package/dist/node-runtime/{subagent-executor-M5VWB3D3.js → subagent-executor-OTNISDQU.js} +40 -7
  199. package/dist/node-runtime/{update-cli-UVKJWRRJ.js → update-cli-VBR2777K.js} +1 -2
  200. package/dist/startup/interactive-view.d.ts.map +1 -1
  201. package/dist/startup/interactive-view.js +5 -1
  202. package/dist/startup/interactive-view.js.map +1 -1
  203. package/docs/browser.md +1 -1
  204. package/docs/features.md +15 -14
  205. package/docs/index.md +1 -1
  206. package/docs/keybindings.md +1 -1
  207. package/docs/providers.md +6 -2
  208. package/docs/quickstart.md +2 -2
  209. package/docs/settings.md +1 -1
  210. package/docs/usage.md +4 -4
  211. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  212. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  213. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  214. package/examples/extensions/gondolin/package-lock.json +2 -2
  215. package/examples/extensions/gondolin/package.json +1 -1
  216. package/examples/extensions/plan-mode/README.md +1 -1
  217. package/examples/extensions/sandbox/package-lock.json +2 -2
  218. package/examples/extensions/sandbox/package.json +1 -1
  219. package/examples/extensions/with-deps/package-lock.json +2 -2
  220. package/examples/extensions/with-deps/package.json +1 -1
  221. package/package.json +4 -4
  222. package/dist/node-runtime/chunk-LISUTZS3.js +0 -19
@@ -1 +1 @@
1
- {"version":3,"file":"discord.js","sourceRoot":"","sources":["../../../src/gateway/adapters/discord.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAEH,OAAO,EACN,gBAAgB,EAChB,4BAA4B,EAC5B,aAAa,EACb,WAAW,EACX,WAAW,EACX,MAAM,EACN,MAAM,EACN,iBAAiB,GAEjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAsB,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAanD,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAChC,MAAM,kBAAkB,GAAG,IAAI,CAAC,CAAC,4BAA4B;AAC7D,MAAM,gBAAgB,GAAG,OAAO,CAAC,CAAC,yCAAyC;AAC3E,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,wBAAwB,GAAG,GAAG,CAAC;AACrC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,wBAAwB,GAAG,GAAG,CAAC;AACrC,MAAM,qBAAqB,GAAG,KAAK,CA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AAC;gBACvD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;gBACrB,OAAO;YACR,CAAC;YACD,KAAK,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QAAA,CAC7B,EAAE,kBAAkB,CAAC,CAAC;QACvB,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IAAA,CAC5D;IAEO,KAAK,CAAC,QAAQ,CAAC,SAAiB,EAAiB;QACxD,IAAI,CAAC;YACJ,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;YACnD,MAAM,OAAO,EAAE,UAAU,EAAE,EAAE,CAAC;QAC/B,CAAC;QAAC,MAAM,CAAC;YACR,uCAAqC;QACtC,CAAC;IAAA,CACD;IAEO,UAAU,CAAC,GAAW,EAAQ;QACrC,MAAM,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACnC,IAAI,CAAC,KAAK;YAAE,OAAO;QACnB,IAAI,CAAC,SAAS,CAAC,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC7C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAAA,CACxB;CACD","sourcesContent":["/**\n * lunR: gateway Discord adapter (Phase 3).\n *\n * Built on discord.js v14 (gateway websocket; the library owns reconnects and\n * REST rate-limit queuing internally, so neither is handled here). No voice,\n * no native slash-command registration — commands arrive as plain message\n * text, same as Telegram.\n *\n * Intents: Guilds, GuildMessages, DirectMessages, MessageContent. GuildMembers\n * is deliberately NOT requested: it is a privileged intent, and asking for it\n * without the dev-portal opt-in makes Discord refuse the identify — the bot\n * connects and immediately goes offline. v1 has no role-based config\n * (SessionSource.roleAuthorized stays undefined), so there is nothing to gain.\n *\n * Inbound: messageToEvent() is the pure message → MessageEvent mapping\n * (dm/group/thread chat types, <@id>/<@!id> mention detection with the mention\n * stripped, thread-participation counts as a mention, own + all-bot + system +\n * attachment-only messages dropped, other-mention-without-us dropped outside\n * DMs — hermes DISCORD_IGNORE_NO_MENTION). A module-level seen-id Set\n * (cap 500, FIFO evict) drops gateway-resume replays. cfg.ignoredChannels is\n * enforced adapter-side (channel id or parent id; blacklist wins over\n * mentions). Consecutive texts from the same chat/thread/user are debounced\n * 600ms and merged (\"\\n\"-joined, latest messageId kept); texts starting with\n * \"/\" flush immediately so commands never merge.\n * Button interactions are routed via interactionCreate → buttonInteractionToEvent().\n *\n * chatId/threadId mapping (pairs with session-keys.ts buildSessionKey):\n * dm → chatId = channel.id → agent:main:discord:dm:<channelId>\n * thread → chatId = PARENT channel id, threadId = → agent:main:discord:thread:<parentId>:<threadId>\n * thread channel id (shared session, no userId)\n * guild text/announcement → chatId = channel.id → agent:main:discord:group:<channelId>[:<userId>]\n * (chatType \"group\"; userId appended when groupSessionsPerUser is on)\n *\n * autoThread (cfg.discord.autoThread, default true): a bot-mentioning message\n * in a guild TEXT channel gets a thread spun off it (startThread, 60min\n * archive); the event is re-targeted to the thread (chatType \"thread\", chatId\n * parent id, threadId thread id). On failure the event stays in-channel.\n *\n * Thread participation: an in-memory Set of thread ids the bot has sent to\n * (recorded on every successful send() into a thread and on autoThread\n * creation); messages in those threads count as mentionedBot so follow-ups\n * don't need a re-mention. NOT persisted in v1 (hermes persists it).\n *\n * Outbound: channel.send({ content, reply: { messageReference } }) with a\n * one-shot plain-send fallback when the reply reference fails. DiscordAPIError\n * 50035 (invalid form body, e.g. overlong content) is reported non-retryable;\n * 429s are queued internally by discord.js; everything else is retryable.\n * editMessage resolves the channel via a messageId → channel map recorded at\n * send() time (router passes only chatId, but thread messages live in their\n * own channel); Unknown Message (10008) is a terminal { success: false }.\n * Message splitting is NOT done here — the router owns that (text.ts).\n *\n * Buttons: ActionRowBuilder rows of ButtonBuilder components (max 5×5).\n * answerCallback acknowledges the interaction; a text argument produces an\n * ephemeral reply (used for unauthorized/expired taps), otherwise deferUpdate().\n *\n * Typing: sendTyping() is a self-contained refresher — Discord typing bubbles\n * last ~10s, so the action is re-sent on an unref'd 8s interval per target.\n * The interval stops when send() completes for that target or after 2 minutes\n * without a refresh (safety net). All errors swallowed.\n *\n * Testability: the discord.js Client goes through an injectable clientFactory\n * (tests inject a minimal fake), timers through an injectable Scheduler, and\n * messageToEvent() operates on the structural DiscordMessageLike — plain mock\n * objects, no real Client construction.\n */\n\nimport {\n\tActionRowBuilder,\n\tApplicationCommandOptionType,\n\tButtonBuilder,\n\tButtonStyle,\n\tChannelType,\n\tClient,\n\tEvents,\n\tGatewayIntentBits,\n\ttype Interaction,\n} from \"discord.js\";\nimport { isAuthorized, isGatewayOwner } from \"../authz.ts\";\nimport { type DiscordConfig, loadGatewayConfig } from \"../config.ts\";\nimport { downloadAttachment } from \"../download.ts\";\nimport { createPairingStore } from \"../pairing.ts\";\nimport type {\n\tButtonSpec,\n\tCallbackEvent,\n\tChatType,\n\tInboundAttachment,\n\tMessageEvent,\n\tPlatformAdapter,\n\tSendOptions,\n\tSendResult,\n} from \"../types.ts\";\nimport type { Scheduler } from \"./telegram.ts\";\n\nconst DEFAULT_DEBOUNCE_MS = 600;\nconst TYPING_INTERVAL_MS = 8000; // Discord typing lasts ~10s\nconst TYPING_SAFETY_MS = 120_000; // auto-stop after 2min without a refresh\nconst REPLY_TO_TEXT_MAX = 500;\nconst THREAD_NAME_MAX = 40;\nconst SEEN_CAP = 500;\nconst SENT_CHANNEL_CAP = 500;\nconst CALLBACK_INTERACTION_CAP = 500;\nconst CHANNEL_CACHE_CAP = 500;\nconst PARTICIPATING_THREAD_CAP = 500;\nconst ERR_INVALID_FORM_BODY = 50035; // e.g. content over 2000 chars — non-retryable\nconst ERR_UNKNOWN_MESSAGE = 10008; // deleted/unknown message — terminal\n\nconst THREAD_TYPES: readonly number[] = [\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.AnnouncementThread,\n];\n\n// ---------------------------------------------------------------------------\n// Structural discord.js shapes (only the fields the adapter reads)\n// ---------------------------------------------------------------------------\n\nexport interface DiscordSentMessageLike {\n\tid: string;\n}\n\nexport interface DiscordFetchedMessageLike {\n\tcontent?: string;\n\tedit?(options: string | { content: string; components?: unknown[] }): Promise<unknown>;\n}\n\nexport interface DiscordChannelLike {\n\tid: string;\n\ttype: number;\n\tparentId?: string | null;\n\tsend?(payload: {\n\t\tcontent: string;\n\t\tfiles?: string[];\n\t\treply?: { messageReference: string };\n\t\tcomponents?: unknown[];\n\t}): Promise<DiscordSentMessageLike>;\n\tsendTyping?(): Promise<unknown>;\n\tmessages?: {\n\t\tcache?: { get(id: string): { content?: string } | undefined };\n\t\tfetch(id: string): Promise<DiscordFetchedMessageLike | null>;\n\t};\n}\n\nexport interface DiscordButtonInteractionLike {\n\tid: string;\n\tcustomId: string;\n\tuser: { id: string; username?: string };\n\tmessage: { id: string; channel: DiscordChannelLike };\n\tisButton(): boolean;\n\tdeferUpdate(): Promise<unknown>;\n\treply?(options: { content: string; ephemeral: boolean }): Promise<unknown>;\n\tupdate?(options: { content: string; components?: unknown[] }): Promise<unknown>;\n}\n\nexport interface DiscordAttachmentLike {\n\tid: string;\n\t/** Direct CDN URL for the attachment content. */\n\turl: string;\n\tcontentType?: string;\n\tname?: string;\n\tsize?: number;\n}\n\nexport interface DiscordMessageLike {\n\tid: string;\n\tcontent?: string;\n\tsystem?: boolean;\n\tauthor: { id: string; bot?: boolean; username?: string };\n\tchannel: DiscordChannelLike;\n\treference?: { messageId?: string | null } | null;\n\tmentions?: {\n\t\thas(user: { id: string }): boolean;\n\t\trepliedUser?: { id: string } | null;\n\t};\n\tstartThread?(opts: { name: string; autoArchiveDuration: number }): Promise<DiscordChannelLike>;\n\tattachments?: DiscordAttachmentLike[];\n}\n\n/** Minimal Client surface; the real discord.js Client satisfies this. */\nexport interface DiscordClientLike {\n\tapplication?: Pick<NonNullable<Client[\"application\"]>, \"commands\"> | null;\n\tuser: { id: string } | null;\n\tlogin(token: string): Promise<unknown>;\n\ton(event: string, listener: (arg: unknown) => void): unknown;\n\tonce(event: string, listener: () => void): unknown;\n\tdestroy(): void;\n\tchannels: { fetch(id: string): Promise<DiscordChannelLike | null> };\n}\n\nexport type DiscordClientFactory = () => DiscordClientLike;\n\n// ---------------------------------------------------------------------------\n// Pure mapping + small helpers\n// ---------------------------------------------------------------------------\n\nfunction errMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n\n/** lunr: download an inbound Discord attachment from its CDN URL. */\n/** Discord REST error code (DiscordAPIError.code) when present. */\nfunction discordErrorCode(err: unknown): number | undefined {\n\tconst code = (err as { code?: unknown } | null)?.code;\n\treturn typeof code === \"number\" ? code : undefined;\n}\n\nexport interface MessageToEventOptions {\n\t/** Channel ids (or parent ids for threads) to drop outright — blacklist wins over mentions. */\n\tignoredChannels?: readonly string[];\n\t/** Threads the bot has spoken in; messages there count as mentionedBot. */\n\tparticipatingThreads?: ReadonlySet<string>;\n}\n\nfunction isImageContentType(contentType: string | undefined): boolean {\n\treturn typeof contentType === \"string\" && contentType.split(\";\")[0]?.trim().toLowerCase().startsWith(\"image/\");\n}\n\n/** lunr: collect inbound image attachments (contentType image/*) from a Discord message. */\nexport function collectDiscordImageAttachments(message: DiscordMessageLike): DiscordAttachmentLike[] {\n\treturn Array.from(message.attachments?.values() ?? []).filter((attachment) =>\n\t\tisImageContentType(attachment.contentType),\n\t);\n}\n\n/**\n * Map a Discord message to a MessageEvent; null = drop (own message, any bot,\n * system message, ignored channel, unsupported channel type, or a non-DM\n * message mentioning others but not us). Messages with no text but image\n * attachments are kept (v1: images inbound).\n */\nexport function messageToEvent(\n\tmessage: DiscordMessageLike,\n\tbotUser: { id: string },\n\toptions: MessageToEventOptions = {},\n): MessageEvent | null {\n\tconst author = message.author;\n\tif (!author) return null;\n\tif (author.id === botUser.id) return null; // own messages\n\tif (author.bot) return null; // all bots (same simplification as telegram)\n\tif (message.system) return null;\n\tconst content = (message.content ?? \"\").trim();\n\tconst imageAttachments = collectDiscordImageAttachments(message);\n\tif (content === \"\" && imageAttachments.length === 0 && !Array.from(message.attachments?.values() ?? []).length)\n\t\treturn null;\n\n\tconst channel = message.channel;\n\tconst ignored = options.ignoredChannels ?? [];\n\tif (ignored.includes(channel.id) || (channel.parentId != null && ignored.includes(channel.parentId))) {\n\t\treturn null; // blacklist wins over mentions\n\t}\n\n\t// chatId/threadId mapping — see the file header for the session-key pairing.\n\tlet chatType: ChatType;\n\tlet chatId: string;\n\tlet threadId: string | undefined;\n\tif (channel.type === ChannelType.DM) {\n\t\tchatType = \"dm\";\n\t\tchatId = channel.id;\n\t} else if (THREAD_TYPES.includes(channel.type)) {\n\t\tchatType = \"thread\";\n\t\tchatId = channel.parentId ?? channel.id;\n\t\tthreadId = channel.id;\n\t} else if (channel.type === ChannelType.GuildText || channel.type === ChannelType.GuildAnnouncement) {\n\t\tchatType = \"group\";\n\t\tchatId = channel.id;\n\t} else {\n\t\treturn null; // voice/category/forum containers etc. — unsupported in v1\n\t}\n\n\tconst explicitMention = message.mentions?.has(botUser) === true;\n\tconst participating = threadId !== undefined && options.participatingThreads?.has(threadId) === true;\n\tconst mentionedBot = explicitMention || participating;\n\n\t// Multi-agent filter (hermes DISCORD_IGNORE_NO_MENTION): outside DMs, a\n\t// message that mentions other users/bots but not us is not for us.\n\tif (!mentionedBot && chatType !== \"dm\") {\n\t\tconst mentionedIds = [...content.matchAll(/<@!?(\\d+)>/g)].map((m) => m[1]);\n\t\tif (mentionedIds.some((id) => id !== botUser.id)) return null;\n\t}\n\n\tlet text = content;\n\tif (explicitMention) {\n\t\ttext = text.replace(new RegExp(`<@!?${botUser.id}>`, \"g\"), \"\").trim();\n\t}\n\n\tconst refId = message.reference?.messageId;\n\tconst cachedReply = refId != null ? channel.messages?.cache?.get(refId)?.content : undefined;\n\n\treturn {\n\t\ttext,\n\t\tmessageId: message.id,\n\t\treplyToText: cachedReply !== undefined ? cachedReply.slice(0, REPLY_TO_TEXT_MAX) : undefined,\n\t\tsource: {\n\t\t\tplatform: \"discord\",\n\t\t\tchatId,\n\t\t\tchatType,\n\t\t\tuserId: author.id,\n\t\t\tuserName: author.username,\n\t\t\tthreadId,\n\t\t},\n\t\tmetadata: mentionedBot ? { mentionedBot: true } : undefined,\n\t};\n}\n\nfunction mapDiscordChannel(\n\tchannel: DiscordChannelLike,\n): { chatType: ChatType; chatId: string; threadId?: string } | null {\n\tif (channel.type === ChannelType.DM) {\n\t\treturn { chatType: \"dm\", chatId: channel.id };\n\t}\n\tif (THREAD_TYPES.includes(channel.type)) {\n\t\treturn { chatType: \"thread\", chatId: channel.parentId ?? channel.id, threadId: channel.id };\n\t}\n\tif (channel.type === ChannelType.GuildText || channel.type === ChannelType.GuildAnnouncement) {\n\t\treturn { chatType: \"group\", chatId: channel.id };\n\t}\n\treturn null;\n}\n\nexport function buttonInteractionToEvent(interaction: DiscordButtonInteractionLike): CallbackEvent | null {\n\tconst channel = interaction.message.channel;\n\tconst mapped = mapDiscordChannel(channel);\n\tif (!mapped) return null;\n\treturn {\n\t\tid: interaction.id,\n\t\tchatId: mapped.chatId,\n\t\tmessageId: interaction.message.id,\n\t\tuserId: interaction.user.id,\n\t\tuserName: interaction.user.username,\n\t\tdata: interaction.customId,\n\t\tthreadId: mapped.threadId,\n\t};\n}\n\nfunction buildDiscordComponents(buttons: ButtonSpec[][]): unknown[] {\n\tconst rows: ActionRowBuilder<ButtonBuilder>[] = [];\n\tfor (const row of buttons) {\n\t\tconst actionRow = new ActionRowBuilder<ButtonBuilder>();\n\t\tfor (const button of row) {\n\t\t\tconst style = button.data === \"\" ? ButtonStyle.Secondary : ButtonStyle.Secondary;\n\t\t\tconst builder = new ButtonBuilder().setCustomId(button.data).setLabel(button.label).setStyle(style);\n\t\t\tif (button.data === \"\") builder.setDisabled(true);\n\t\t\tactionRow.addComponents(builder);\n\t\t}\n\t\trows.push(actionRow);\n\t}\n\treturn rows;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway-resume replay dedup (module-level: one process = one bot connection)\n// ---------------------------------------------------------------------------\n\nconst seenMessageIds = new Set<string>();\n\n/** Returns true when this id was already seen (drop the replay). */\nfunction markMessageSeen(id: string): boolean {\n\tif (seenMessageIds.has(id)) return true;\n\tseenMessageIds.add(id);\n\tif (seenMessageIds.size > SEEN_CAP) {\n\t\tconst oldest = seenMessageIds.values().next().value; // Sets iterate in insertion order\n\t\tif (oldest !== undefined) seenMessageIds.delete(oldest);\n\t}\n\treturn false;\n}\n\n/** Test hook: reset RESUME dedup state between tests. */\nexport function resetSeenMessageIds(): void {\n\tseenMessageIds.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nconst defaultScheduler: Scheduler = {\n\tsetTimeout: (fn, ms) => {\n\t\tconst handle = setTimeout(fn, ms);\n\t\thandle.unref?.();\n\t\treturn handle;\n\t},\n\tclearTimeout: (handle) => clearTimeout(handle),\n\tsetInterval: (fn, ms) => {\n\t\tconst handle = setInterval(fn, ms);\n\t\thandle.unref?.();\n\t\treturn handle;\n\t},\n\tclearInterval: (handle) => clearInterval(handle),\n};\n\nfunction defaultClientFactory(): DiscordClientLike {\n\t// No GatewayIntentBits.GuildMembers — see the file header for the\n\t// privileged-intent trap (bot stays offline without the portal opt-in).\n\treturn new Client({\n\t\tintents: [\n\t\t\tGatewayIntentBits.Guilds,\n\t\t\tGatewayIntentBits.GuildMessages,\n\t\t\tGatewayIntentBits.DirectMessages,\n\t\t\tGatewayIntentBits.MessageContent,\n\t\t],\n\t}) as unknown as DiscordClientLike;\n}\n\nexport interface DiscordAdapterOptions {\n\t/** Injected Client factory (tests). When omitted, a real discord.js Client is created. */\n\tclientFactory?: DiscordClientFactory;\n\t/** lunr: injected image downloader for inbound attachments (tests). Defaults to fetch(url). */\n\tdownloadAttachment?: (url: string) => Promise<Uint8Array>;\n\t/** lunr: skip inbound media larger than this many bytes. Defaults to 10MB. */\n\tmaxMediaBytes?: number;\n\tscheduler?: Scheduler;\n\tdebounceMs?: number;\n\tnow?: () => number;\n}\n\ninterface PendingEntry {\n\tevent: MessageEvent;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\ninterface TypingEntry {\n\tinterval: ReturnType<typeof setInterval>;\n\tlastRefresh: number;\n}\n\nfunction typingKey(chatId: string, threadId?: string): string {\n\treturn `${chatId}:${threadId ?? \"\"}`;\n}\n\nexport class DiscordAdapter implements PlatformAdapter {\n\treadonly platform = \"discord\";\n\treadonly maxMessageLength = 2000;\n\n\tprivate readonly cfg: DiscordConfig;\n\tprivate readonly clientFactory: DiscordClientFactory;\n\tprivate readonly downloadAttachment: (url: string) => Promise<Uint8Array>;\n\tprivate readonly maxMediaBytes: number;\n\tprivate readonly scheduler: Scheduler;\n\tprivate readonly debounceMs: number;\n\tprivate readonly now: () => number;\n\tprivate client?: DiscordClientLike;\n\tprivate botUserId?: string;\n\tprivate handler?: (event: MessageEvent) => void;\n\tprivate commandSuggestions?: Parameters<NonNullable<PlatformAdapter[\"setCommandSuggestions\"]>>[0];\n\tprivate callbackHandler?: (event: CallbackEvent) => void;\n\tprivate readonly pending = new Map<string, PendingEntry>();\n\tprivate readonly typing = new Map<string, TypingEntry>();\n\tprivate readonly channelCache = new Map<string, DiscordChannelLike | null>();\n\t/** Threads the bot has spoken in (session memory only; hermes persists this). */\n\tprivate readonly participatingThreads = new Set<string>();\n\t/** messageId → channel it was sent to, so editMessage finds thread messages. */\n\tprivate readonly sentMessageChannels = new Map<string, string>();\n\t/** callbackId → interaction, so answerCallback can acknowledge the click. */\n\tprivate readonly callbackInteractions = new Map<string, DiscordButtonInteractionLike>();\n\n\tconstructor(cfg: DiscordConfig, options: DiscordAdapterOptions = {}) {\n\t\tthis.cfg = cfg;\n\t\tthis.scheduler = options.scheduler ?? defaultScheduler;\n\t\tthis.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n\t\tthis.now = options.now ?? Date.now;\n\t\tif (options.clientFactory) {\n\t\t\tthis.clientFactory = options.clientFactory;\n\t\t} else {\n\t\t\tif (!cfg.token) {\n\t\t\t\tthrow new Error(\"DiscordAdapter: no bot token (set discord.token or LUNR_DISCORD_BOT_TOKEN)\");\n\t\t\t}\n\t\t\tthis.clientFactory = defaultClientFactory;\n\t\t}\n\t\tthis.downloadAttachment = options.downloadAttachment ?? downloadAttachment;\n\t\tthis.maxMediaBytes = options.maxMediaBytes ?? 10 * 1024 * 1024;\n\t}\n\n\tsetCommandSuggestions(\n\t\thandler: (source: MessageEvent[\"source\"], command: string) => Promise<readonly string[]>,\n\t): void {\n\t\tthis.commandSuggestions = handler;\n\t}\n\n\tonMessage(handler: (event: MessageEvent) => void): void {\n\t\tthis.handler = handler;\n\t}\n\n\tonCallback(handler: (event: CallbackEvent) => void): void {\n\t\tthis.callbackHandler = handler;\n\t}\n\n\tasync connect(): Promise<boolean> {\n\t\tif (!this.cfg.token) {\n\t\t\tthrow new Error(\"DiscordAdapter: no bot token (set discord.token or LUNR_DISCORD_BOT_TOKEN)\");\n\t\t}\n\t\tconst client = this.clientFactory();\n\t\tthis.client = client;\n\t\tclient.on(Events.MessageCreate, (message) => {\n\t\t\tvoid this.handleMessage(message as DiscordMessageLike).catch((err) => {\n\t\t\t\tconsole.error(`[gateway] discord message handling error: ${errMessage(err)}`);\n\t\t\t});\n\t\t});\n\t\tclient.on(Events.InteractionCreate, (interaction) => {\n\t\t\tconst event = interaction as Interaction;\n\t\t\tconst handling = event.isButton()\n\t\t\t\t? this.handleInteraction(interaction as DiscordButtonInteractionLike)\n\t\t\t\t: this.handleNativeCommand(event);\n\t\t\tvoid handling.catch((err) => {\n\t\t\t\tconsole.error(`[gateway] discord interaction handling error: ${errMessage(err)}`);\n\t\t\t});\n\t\t});\n\t\tconst ready = new Promise<void>((resolve) => client.once(Events.ClientReady, () => resolve()));\n\t\ttry {\n\t\t\tawait client.login(this.cfg.token);\n\t\t} catch (err) {\n\t\t\tconsole.error(`[gateway] discord login failed: ${errMessage(err)}`);\n\t\t\treturn false;\n\t\t}\n\t\tawait ready;\n\t\tthis.botUserId = client.user?.id;\n\t\tif (this.botUserId === undefined) {\n\t\t\tconsole.error(\"[gateway] discord: client ready without a user — cannot map messages\");\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync disconnect(): Promise<void> {\n\t\tfor (const key of [...this.pending.keys()]) this.cancelPending(key);\n\t\tfor (const key of [...this.typing.keys()]) this.stopTyping(key);\n\t\tthis.channelCache.clear();\n\t\tthis.callbackInteractions.clear();\n\t\tthis.client?.destroy();\n\t\tthis.client = undefined;\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// Inbound dispatch + debounce\n\t// -----------------------------------------------------------------------\n\n\tprivate async handleMessage(message: DiscordMessageLike): Promise<void> {\n\t\tif (!this.botUserId || !this.handler) return;\n\t\tif (markMessageSeen(message.id)) return; // gateway-resume replay\n\t\tconst event = messageToEvent(\n\t\t\tmessage,\n\t\t\t{ id: this.botUserId },\n\t\t\t{\n\t\t\t\tignoredChannels: this.cfg.ignoredChannels,\n\t\t\t\tparticipatingThreads: this.participatingThreads,\n\t\t\t},\n\t\t);\n\t\tif (!event) return;\n\t\tif (!isAuthorized(event.source, { ...loadGatewayConfig(), discord: this.cfg }, createPairingStore())) {\n\t\t\tthis.dispatchEvent(event);\n\t\t\treturn;\n\t\t}\n\t\tawait this.resolveReplyToText(message, event);\n\t\tawait this.maybeAutoThread(message, event);\n\t\tawait this.downloadAttachments(message, event);\n\t\tthis.dispatchEvent(event);\n\t}\n\n\t/** Download and encode attachments after authorization. */\n\tprivate async downloadAttachments(message: DiscordMessageLike, event: MessageEvent): Promise<void> {\n\t\tconst imageAttachments = Array.from(message.attachments?.values() ?? []);\n\t\tif (imageAttachments.length === 0) return;\n\t\tconst attachments: InboundAttachment[] = [];\n\t\tfor (const attachment of imageAttachments) {\n\t\t\tif (attachment.size !== undefined && attachment.size > this.maxMediaBytes) continue;\n\t\t\ttry {\n\t\t\t\tconst bytes = await this.downloadAttachment(attachment.url);\n\t\t\t\tif (bytes.byteLength > this.maxMediaBytes) continue;\n\t\t\t\tattachments.push({\n\t\t\t\t\tdata: Buffer.from(bytes).toString(\"base64\"),\n\t\t\t\t\tmimeType: attachment.contentType ?? \"application/octet-stream\",\n\t\t\t\t\t...(attachment.name ? { filename: attachment.name } : {}),\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Media download failed — drop this attachment, keep the text turn.\n\t\t\t}\n\t\t}\n\t\tif (attachments.length > 0) event.attachments = attachments;\n\t}\n\n\tasync registerCommands(commands: { name: string; description: string }[]): Promise<void> {\n\t\tif (!this.client?.application) return;\n\t\tawait this.client.application.commands.set(\n\t\t\tcommands.slice(0, 95).map((command) => ({\n\t\t\t\tname: command.name,\n\t\t\t\tdescription: command.description.slice(0, 100),\n\t\t\t\toptions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"args\",\n\t\t\t\t\t\tdescription: \"Command arguments or search\",\n\t\t\t\t\t\ttype: ApplicationCommandOptionType.String,\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tautocomplete: [\"mode\", \"thinking\", \"project\", \"sessions\"].includes(command.name),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})),\n\t\t);\n\t}\n\n\tprivate async handleNativeCommand(interaction: Interaction): Promise<boolean> {\n\t\tif (!interaction.isChatInputCommand?.() && !interaction.isAutocomplete?.()) return false;\n\t\tif (!interaction.isChatInputCommand() && !interaction.isAutocomplete()) return false;\n\t\tconst thread = interaction.channel?.isThread() ? interaction.channel : undefined;\n\t\tconst source = {\n\t\t\tplatform: \"discord\",\n\t\t\tchatId: thread?.parentId ?? interaction.channelId ?? interaction.user.id,\n\t\t\tthreadId: thread?.id,\n\t\t\tchatType: thread ? (\"thread\" as const) : interaction.inGuild() ? (\"channel\" as const) : (\"dm\" as const),\n\t\t\tuserId: interaction.user.id,\n\t\t\tuserName: interaction.user.username,\n\t\t};\n\t\tconst cfg = loadGatewayConfig();\n\t\tconst authorized = isAuthorized(source, cfg, createPairingStore());\n\t\tif (interaction.isAutocomplete()) {\n\t\t\tif (!authorized || !isGatewayOwner(source, cfg)) {\n\t\t\t\tawait interaction.respond([]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst query = String(interaction.options.getFocused()).toLowerCase();\n\t\t\tlet values: string[] = [];\n\t\t\tif (interaction.commandName === \"mode\") values = [\"manual\", \"yolo\", \"plan\", \"auto\"];\n\t\t\tif (this.commandSuggestions && [\"thinking\", \"model\"].includes(interaction.commandName)) {\n\t\t\t\tvalues = [...(await this.commandSuggestions(source, interaction.commandName))];\n\t\t\t}\n\t\t\tif (interaction.commandName === \"project\") values = cfg.projectRoots ?? [];\n\t\t\tif (interaction.commandName === \"sessions\") {\n\t\t\t\tconst { SessionManager } = await import(\"../../core/session-manager.ts\");\n\t\t\t\tvalues = (\n\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\tSessionManager.listAll(),\n\t\t\t\t\t\tnew Promise<[]>((resolve) => setTimeout(() => resolve([]), 1500)),\n\t\t\t\t\t])\n\t\t\t\t).map((s) => s.name || s.id);\n\t\t\t}\n\t\t\tawait interaction.respond(\n\t\t\t\tvalues\n\t\t\t\t\t.filter((s) => s.toLowerCase().includes(query))\n\t\t\t\t\t.slice(0, 25)\n\t\t\t\t\t.map((value) => ({ name: value.slice(0, 100), value: value.slice(0, 100) })),\n\t\t\t);\n\t\t\treturn true;\n\t\t}\n\t\tawait interaction.reply({\n\t\t\tcontent: authorized\n\t\t\t\t? \"Command received.\"\n\t\t\t\t: \"Pair your account before using this command. Send the bot a private message for a pairing code.\",\n\t\t\tephemeral: true,\n\t\t});\n\t\tif (authorized)\n\t\t\tthis.handler?.({\n\t\t\t\ttext: `/${interaction.commandName}${interaction.options.getString(\"args\") ? ` ${interaction.options.getString(\"args\")}` : \"\"}`,\n\t\t\t\tsource,\n\t\t\t\tmessageId: \"\",\n\t\t\t\tmetadata: { mentionedBot: true, nativeCommand: true },\n\t\t\t});\n\t\treturn true;\n\t}\n\n\tasync sendFile(chatId: string, file: string, opts?: SendOptions): Promise<SendResult> {\n\t\tconst channel = await this.fetchChannel(opts?.threadId ?? chatId);\n\t\tif (!channel?.send) return { success: false, error: \"Channel is unavailable.\" };\n\t\ttry {\n\t\t\tconst message = await channel.send({ content: \"\", files: [file] });\n\t\t\treturn { success: true, messageId: message.id };\n\t\t} catch (error) {\n\t\t\treturn { success: false, error: errMessage(error) };\n\t\t}\n\t}\n\n\tprivate async handleInteraction(interaction: DiscordButtonInteractionLike): Promise<void> {\n\t\tif (!this.callbackHandler) return;\n\t\tif (!interaction.isButton()) return;\n\t\tconst event = buttonInteractionToEvent(interaction);\n\t\tif (!event) return;\n\t\tthis.callbackInteractions.set(interaction.id, interaction);\n\t\tif (this.callbackInteractions.size > CALLBACK_INTERACTION_CAP) {\n\t\t\tconst oldest = this.callbackInteractions.keys().next().value;\n\t\t\tif (oldest !== undefined) this.callbackInteractions.delete(oldest);\n\t\t}\n\t\tthis.callbackHandler(event);\n\t}\n\n\t/** Best-effort: fill replyToText from the referenced message when it wasn't cached. */\n\tprivate async resolveReplyToText(message: DiscordMessageLike, event: MessageEvent): Promise<void> {\n\t\tif (event.replyToText !== undefined) return;\n\t\tconst refId = message.reference?.messageId;\n\t\tif (refId == null) return;\n\t\tconst messages = message.channel.messages;\n\t\tif (!messages) return;\n\t\ttry {\n\t\t\tconst referenced = await messages.fetch(refId);\n\t\t\tif (referenced?.content) event.replyToText = referenced.content.slice(0, REPLY_TO_TEXT_MAX);\n\t\t} catch {\n\t\t\t// unknown/deleted reference — no reply context\n\t\t}\n\t}\n\n\t/** autoThread: spin a thread off a bot-mentioning guild-text message and re-target the event. */\n\tprivate async maybeAutoThread(message: DiscordMessageLike, event: MessageEvent): Promise<void> {\n\t\tif (!this.cfg.autoThread) return;\n\t\tif (event.metadata?.mentionedBot !== true) return;\n\t\t// Only guild TEXT channels: DMs can't thread and messages already inside\n\t\t// a thread don't need another one.\n\t\tif (message.channel.type !== ChannelType.GuildText) return;\n\t\tif (typeof message.startThread !== \"function\") return;\n\t\ttry {\n\t\t\tconst thread = await message.startThread({\n\t\t\t\tname: (event.text || \"conversation\").slice(0, THREAD_NAME_MAX),\n\t\t\t\tautoArchiveDuration: 60,\n\t\t\t});\n\t\t\tthis.participatingThreads.add(thread.id);\n\t\t\tif (this.participatingThreads.size > PARTICIPATING_THREAD_CAP) {\n\t\t\t\tconst oldest = this.participatingThreads.values().next().value;\n\t\t\t\tif (oldest !== undefined) this.participatingThreads.delete(oldest);\n\t\t\t}\n\t\t\tevent.source = { ...event.source, chatType: \"thread\", chatId: message.channel.id, threadId: thread.id };\n\t\t} catch {\n\t\t\t// e.g. missing CREATE_THREADS permission — respond in-channel instead.\n\t\t}\n\t}\n\n\tprivate debounceKey(event: MessageEvent): string {\n\t\treturn `${event.source.chatId}:${event.source.threadId ?? \"\"}:${event.source.userId}`;\n\t}\n\n\tprivate dispatchEvent(event: MessageEvent): void {\n\t\tconst key = this.debounceKey(event);\n\t\tif (event.text.trimStart().startsWith(\"/\")) {\n\t\t\t// Commands must not merge: flush any pending text, emit immediately.\n\t\t\tthis.flushPending(key);\n\t\t\tthis.handler?.(event);\n\t\t\treturn;\n\t\t}\n\t\tconst existing = this.pending.get(key);\n\t\tif (existing) {\n\t\t\tthis.scheduler.clearTimeout(existing.timer);\n\t\t\t// Merge: earlier text first, latest messageId (and other fields) win.\n\t\t\tconst mergedAttachments = [...(existing.event.attachments ?? []), ...(event.attachments ?? [])];\n\t\t\texisting.event = {\n\t\t\t\t...event,\n\t\t\t\ttext: `${existing.event.text}\\n${event.text}`,\n\t\t\t\t...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),\n\t\t\t};\n\t\t\texisting.timer = this.scheduler.setTimeout(() => this.flushPending(key), this.debounceMs);\n\t\t} else {\n\t\t\tconst timer = this.scheduler.setTimeout(() => this.flushPending(key), this.debounceMs);\n\t\t\tthis.pending.set(key, { event, timer });\n\t\t}\n\t}\n\n\tprivate flushPending(key: string): void {\n\t\tconst entry = this.pending.get(key);\n\t\tif (!entry) return;\n\t\tthis.scheduler.clearTimeout(entry.timer);\n\t\tthis.pending.delete(key);\n\t\tthis.handler?.(entry.event);\n\t}\n\n\tprivate cancelPending(key: string): void {\n\t\tconst entry = this.pending.get(key);\n\t\tif (!entry) return;\n\t\tthis.scheduler.clearTimeout(entry.timer);\n\t\tthis.pending.delete(key);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// Outbound\n\t// -----------------------------------------------------------------------\n\n\tprivate async fetchChannel(id: string): Promise<DiscordChannelLike | null> {\n\t\tif (this.channelCache.has(id)) return this.channelCache.get(id) ?? null;\n\t\tif (!this.client) return null;\n\t\ttry {\n\t\t\tconst channel = await this.client.channels.fetch(id);\n\t\t\tthis.channelCache.set(id, channel);\n\t\t\tif (this.channelCache.size > CHANNEL_CACHE_CAP) {\n\t\t\t\tconst oldest = this.channelCache.keys().next().value;\n\t\t\t\tif (oldest !== undefined) this.channelCache.delete(oldest);\n\t\t\t}\n\t\t\treturn channel;\n\t\t} catch {\n\t\t\tthis.channelCache.set(id, null);\n\t\t\tif (this.channelCache.size > CHANNEL_CACHE_CAP) {\n\t\t\t\tconst oldest = this.channelCache.keys().next().value;\n\t\t\t\tif (oldest !== undefined) this.channelCache.delete(oldest);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate recordSent(messageId: string, channel: DiscordChannelLike): void {\n\t\tif (THREAD_TYPES.includes(channel.type)) this.participatingThreads.add(channel.id);\n\t\tif (this.participatingThreads.size > PARTICIPATING_THREAD_CAP) {\n\t\t\tconst oldest = this.participatingThreads.values().next().value;\n\t\t\tif (oldest !== undefined) this.participatingThreads.delete(oldest);\n\t\t}\n\t\tthis.sentMessageChannels.set(messageId, channel.id);\n\t\tif (this.sentMessageChannels.size > SENT_CHANNEL_CAP) {\n\t\t\tconst oldest = this.sentMessageChannels.keys().next().value;\n\t\t\tif (oldest !== undefined) this.sentMessageChannels.delete(oldest);\n\t\t}\n\t}\n\n\tprivate async trySend(\n\t\tchannel: DiscordChannelLike,\n\t\tpayload: { content: string; reply?: { messageReference: string }; components?: unknown[] },\n\t): Promise<SendResult> {\n\t\tif (typeof channel.send !== \"function\") {\n\t\t\treturn { success: false, error: `channel ${channel.id} is not sendable` };\n\t\t}\n\t\ttry {\n\t\t\tconst sent = await channel.send(payload);\n\t\t\tthis.recordSent(sent.id, channel);\n\t\t\treturn { success: true, messageId: sent.id };\n\t\t} catch (err) {\n\t\t\t// 429s are queued internally by discord.js and don't surface here.\n\t\t\treturn { success: false, error: errMessage(err), retryable: discordErrorCode(err) !== ERR_INVALID_FORM_BODY };\n\t\t}\n\t}\n\n\tasync send(chatId: string, text: string, opts?: SendOptions): Promise<SendResult> {\n\t\t// A completed send ends the typing bubble — stop the refresher (see sendTyping).\n\t\tthis.stopTyping(typingKey(chatId, opts?.threadId));\n\t\tconst channel = await this.fetchChannel(opts?.threadId ?? chatId);\n\t\tif (!channel) return { success: false, error: `channel ${opts?.threadId ?? chatId} not found` };\n\t\tconst result = await this.trySend(channel, {\n\t\t\tcontent: text,\n\t\t\treply: opts?.replyTo !== undefined ? { messageReference: opts.replyTo } : undefined,\n\t\t});\n\t\tif (!result.success && opts?.replyTo !== undefined) {\n\t\t\t// The reply target may be deleted/unknown — fall back to a plain send.\n\t\t\treturn this.trySend(channel, { content: text });\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync sendButtons(chatId: string, text: string, buttons: ButtonSpec[][], opts?: SendOptions): Promise<SendResult> {\n\t\tthis.stopTyping(typingKey(chatId, opts?.threadId));\n\t\tconst channel = await this.fetchChannel(opts?.threadId ?? chatId);\n\t\tif (!channel) return { success: false, error: `channel ${opts?.threadId ?? chatId} not found` };\n\t\tconst result = await this.trySend(channel, {\n\t\t\tcontent: text,\n\t\t\treply: opts?.replyTo !== undefined ? { messageReference: opts.replyTo } : undefined,\n\t\t\tcomponents: buildDiscordComponents(buttons),\n\t\t});\n\t\tif (!result.success && opts?.replyTo !== undefined) {\n\t\t\treturn this.trySend(channel, { content: text, components: buildDiscordComponents(buttons) });\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync answerCallback(id: string, text?: string): Promise<void> {\n\t\tconst interaction = this.callbackInteractions.get(id);\n\t\tif (!interaction) return;\n\t\tthis.callbackInteractions.delete(id);\n\t\ttry {\n\t\t\tif (text !== undefined && interaction.reply) {\n\t\t\t\tawait interaction.reply({ content: text, ephemeral: true });\n\t\t\t} else {\n\t\t\t\tawait interaction.deferUpdate();\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort acknowledgment\n\t\t}\n\t}\n\n\tasync editMessage(chatId: string, messageId: string, text: string, buttons?: ButtonSpec[][]): Promise<SendResult> {\n\t\t// The router passes only chatId; thread messages live in their own\n\t\t// channel, so prefer the channel recorded at send() time.\n\t\tconst channel = await this.fetchChannel(this.sentMessageChannels.get(messageId) ?? chatId);\n\t\tif (!channel?.messages) {\n\t\t\treturn { success: false, error: `channel ${this.sentMessageChannels.get(messageId) ?? chatId} not found` };\n\t\t}\n\t\ttry {\n\t\t\tconst message = await channel.messages.fetch(messageId);\n\t\t\tif (!message || typeof message.edit !== \"function\") {\n\t\t\t\treturn { success: false, error: `message ${messageId} not found` };\n\t\t\t}\n\t\t\tconst editOptions: { content: string; components?: unknown[] } = { content: text };\n\t\t\tif (buttons !== undefined) editOptions.components = buildDiscordComponents(buttons);\n\t\t\tawait message.edit(editOptions);\n\t\t\treturn { success: true, messageId };\n\t\t} catch (err) {\n\t\t\tconst code = discordErrorCode(err);\n\t\t\tif (code === ERR_UNKNOWN_MESSAGE) return { success: false, error: errMessage(err) }; // terminal\n\t\t\treturn { success: false, error: errMessage(err), retryable: true };\n\t\t}\n\t}\n\n\tasync sendTyping(chatId: string, threadId?: string): Promise<void> {\n\t\t// Self-contained typing refresher (see file header): re-send the action\n\t\t// every 8s until send() completes for this target or the 2min safety net\n\t\t// fires — all errors swallowed.\n\t\tconst key = typingKey(chatId, threadId);\n\t\tconst targetId = threadId ?? chatId;\n\t\tawait this.doTyping(targetId);\n\t\tconst existing = this.typing.get(key);\n\t\tif (existing) {\n\t\t\texisting.lastRefresh = this.now();\n\t\t\treturn;\n\t\t}\n\t\tconst interval = this.scheduler.setInterval(() => {\n\t\t\tconst entry = this.typing.get(key);\n\t\t\tif (!entry) return;\n\t\t\tif (this.now() - entry.lastRefresh > TYPING_SAFETY_MS) {\n\t\t\t\tthis.stopTyping(key);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvoid this.doTyping(targetId);\n\t\t}, TYPING_INTERVAL_MS);\n\t\tthis.typing.set(key, { interval, lastRefresh: this.now() });\n\t}\n\n\tprivate async doTyping(channelId: string): Promise<void> {\n\t\ttry {\n\t\t\tconst channel = await this.fetchChannel(channelId);\n\t\t\tawait channel?.sendTyping?.();\n\t\t} catch {\n\t\t\t// typing is cosmetic — never surface\n\t\t}\n\t}\n\n\tprivate stopTyping(key: string): void {\n\t\tconst entry = this.typing.get(key);\n\t\tif (!entry) return;\n\t\tthis.scheduler.clearInterval(entry.interval);\n\t\tthis.typing.delete(key);\n\t}\n}\n"]}
1
+ {"version":3,"file":"discord.js","sourceRoot":"","sources":["../../../src/gateway/adapters/discord.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiEG;AAEH,OAAO,EACN,gBAAgB,EAChB,4BAA4B,EAC5B,aAAa,EACb,WAAW,EACX,WAAW,EACX,MAAM,EACN,MAAM,EACN,iBAAiB,GAEjB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC3D,OAAO,EAAsB,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CA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7C,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAAA,CACxB;CACD","sourcesContent":["/**\n * lunR: gateway Discord adapter (Phase 3).\n *\n * Built on discord.js v14 (gateway websocket; the library owns reconnects and\n * REST rate-limit queuing internally, so neither is handled here). No voice,\n * no native slash-command registration — commands arrive as plain message\n * text, same as Telegram.\n *\n * Intents: Guilds, GuildMessages, DirectMessages, MessageContent. GuildMembers\n * is deliberately NOT requested: it is a privileged intent, and asking for it\n * without the dev-portal opt-in makes Discord refuse the identify — the bot\n * connects and immediately goes offline. v1 has no role-based config\n * (SessionSource.roleAuthorized stays undefined), so there is nothing to gain.\n *\n * Inbound: messageToEvent() is the pure message → MessageEvent mapping\n * (dm/group/thread chat types, <@id>/<@!id> mention detection with the mention\n * stripped, thread-participation counts as a mention, own + all-bot + system +\n * attachment-only messages dropped, other-mention-without-us dropped outside\n * DMs — hermes DISCORD_IGNORE_NO_MENTION). A module-level seen-id Set\n * (cap 500, FIFO evict) drops gateway-resume replays. cfg.ignoredChannels is\n * enforced adapter-side (channel id or parent id; blacklist wins over\n * mentions). Consecutive texts from the same chat/thread/user are debounced\n * 600ms and merged (\"\\n\"-joined, latest messageId kept); texts starting with\n * \"/\" flush immediately so commands never merge.\n * Button interactions are routed via interactionCreate → buttonInteractionToEvent().\n *\n * chatId/threadId mapping (pairs with session-keys.ts buildSessionKey):\n * dm → chatId = channel.id → agent:main:discord:dm:<channelId>\n * thread → chatId = PARENT channel id, threadId = → agent:main:discord:thread:<parentId>:<threadId>\n * thread channel id (shared session, no userId)\n * guild text/announcement → chatId = channel.id → agent:main:discord:group:<channelId>[:<userId>]\n * (chatType \"group\"; userId appended when groupSessionsPerUser is on)\n *\n * autoThread (cfg.discord.autoThread, default true): a bot-mentioning message\n * in a guild TEXT channel gets a thread spun off it (startThread, 60min\n * archive); the event is re-targeted to the thread (chatType \"thread\", chatId\n * parent id, threadId thread id). On failure the event stays in-channel.\n *\n * Thread participation: an in-memory Set of thread ids the bot has sent to\n * (recorded on every successful send() into a thread and on autoThread\n * creation); messages in those threads count as mentionedBot so follow-ups\n * don't need a re-mention. NOT persisted in v1 (hermes persists it).\n *\n * Outbound: channel.send({ content, reply: { messageReference } }) with a\n * one-shot plain-send fallback when the reply reference fails. DiscordAPIError\n * 50035 (invalid form body, e.g. overlong content) is reported non-retryable;\n * 429s are queued internally by discord.js; everything else is retryable.\n * editMessage resolves the channel via a messageId → channel map recorded at\n * send() time (router passes only chatId, but thread messages live in their\n * own channel); Unknown Message (10008) is a terminal { success: false }.\n * Message splitting is NOT done here — the router owns that (text.ts).\n *\n * Buttons: ActionRowBuilder rows of ButtonBuilder components (max 5×5).\n * answerCallback acknowledges the interaction; a text argument produces an\n * ephemeral reply (used for unauthorized/expired taps), otherwise deferUpdate().\n *\n * Typing: sendTyping() is a self-contained refresher — Discord typing bubbles\n * last ~10s, so the action is re-sent on an unref'd 8s interval per target.\n * The interval stops when send() completes for that target or after 2 minutes\n * without a refresh (safety net). All errors swallowed.\n *\n * Testability: the discord.js Client goes through an injectable clientFactory\n * (tests inject a minimal fake), timers through an injectable Scheduler, and\n * messageToEvent() operates on the structural DiscordMessageLike — plain mock\n * objects, no real Client construction.\n */\n\nimport {\n\tActionRowBuilder,\n\tApplicationCommandOptionType,\n\tButtonBuilder,\n\tButtonStyle,\n\tChannelType,\n\tClient,\n\tEvents,\n\tGatewayIntentBits,\n\ttype Interaction,\n} from \"discord.js\";\nimport { isAuthorized, isGatewayOwner } from \"../authz.ts\";\nimport { type DiscordConfig, loadGatewayConfig } from \"../config.ts\";\nimport { downloadAttachment } from \"../download.ts\";\nimport { createPairingStore } from \"../pairing.ts\";\nimport type {\n\tButtonSpec,\n\tCallbackEvent,\n\tChatType,\n\tInboundAttachment,\n\tMessageEvent,\n\tPlatformAdapter,\n\tSendOptions,\n\tSendResult,\n} from \"../types.ts\";\nimport type { Scheduler } from \"./telegram.ts\";\n\nconst DEFAULT_DEBOUNCE_MS = 600;\nconst TYPING_INTERVAL_MS = 8000; // Discord typing lasts ~10s\nconst TYPING_SAFETY_MS = 120_000; // auto-stop after 2min without a refresh\nconst REPLY_TO_TEXT_MAX = 500;\nconst THREAD_NAME_MAX = 40;\nconst SEEN_CAP = 500;\nconst SENT_CHANNEL_CAP = 500;\nconst CALLBACK_INTERACTION_CAP = 500;\nconst CHANNEL_CACHE_CAP = 500;\nconst PARTICIPATING_THREAD_CAP = 500;\nconst ERR_INVALID_FORM_BODY = 50035; // e.g. content over 2000 chars — non-retryable\nconst ERR_UNKNOWN_MESSAGE = 10008; // deleted/unknown message — terminal\n\nconst THREAD_TYPES: readonly number[] = [\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.AnnouncementThread,\n];\n\n// ---------------------------------------------------------------------------\n// Structural discord.js shapes (only the fields the adapter reads)\n// ---------------------------------------------------------------------------\n\nexport interface DiscordSentMessageLike {\n\tid: string;\n}\n\nexport interface DiscordFetchedMessageLike {\n\tcontent?: string;\n\tedit?(options: string | { content: string; components?: unknown[] }): Promise<unknown>;\n}\n\nexport interface DiscordChannelLike {\n\tid: string;\n\ttype: number;\n\tparentId?: string | null;\n\tsend?(payload: {\n\t\tcontent: string;\n\t\tfiles?: string[];\n\t\treply?: { messageReference: string };\n\t\tcomponents?: unknown[];\n\t}): Promise<DiscordSentMessageLike>;\n\tsendTyping?(): Promise<unknown>;\n\tmessages?: {\n\t\tcache?: { get(id: string): { content?: string } | undefined };\n\t\tfetch(id: string): Promise<DiscordFetchedMessageLike | null>;\n\t};\n}\n\nexport interface DiscordButtonInteractionLike {\n\tid: string;\n\tcustomId: string;\n\tuser: { id: string; username?: string };\n\tmessage: { id: string; channel: DiscordChannelLike };\n\tisButton(): boolean;\n\tdeferUpdate(): Promise<unknown>;\n\treply?(options: { content: string; ephemeral: boolean }): Promise<unknown>;\n\tupdate?(options: { content: string; components?: unknown[] }): Promise<unknown>;\n}\n\nexport interface DiscordAttachmentLike {\n\tid: string;\n\t/** Direct CDN URL for the attachment content. */\n\turl: string;\n\tcontentType?: string;\n\tname?: string;\n\tsize?: number;\n}\n\nexport interface DiscordMessageLike {\n\tid: string;\n\tcontent?: string;\n\tsystem?: boolean;\n\tauthor: { id: string; bot?: boolean; username?: string };\n\tchannel: DiscordChannelLike;\n\treference?: { messageId?: string | null } | null;\n\tmentions?: {\n\t\thas(user: { id: string }): boolean;\n\t\trepliedUser?: { id: string } | null;\n\t};\n\tstartThread?(opts: { name: string; autoArchiveDuration: number }): Promise<DiscordChannelLike>;\n\tattachments?: DiscordAttachmentLike[];\n}\n\n/** Minimal Client surface; the real discord.js Client satisfies this. */\nexport interface DiscordClientLike {\n\tapplication?: Pick<NonNullable<Client[\"application\"]>, \"commands\"> | null;\n\tuser: { id: string } | null;\n\tlogin(token: string): Promise<unknown>;\n\ton(event: string, listener: (arg: unknown) => void): unknown;\n\tonce(event: string, listener: () => void): unknown;\n\tdestroy(): void;\n\tchannels: { fetch(id: string): Promise<DiscordChannelLike | null> };\n}\n\nexport type DiscordClientFactory = () => DiscordClientLike;\n\n// ---------------------------------------------------------------------------\n// Pure mapping + small helpers\n// ---------------------------------------------------------------------------\n\nfunction errMessage(err: unknown): string {\n\treturn err instanceof Error ? err.message : String(err);\n}\n\n/** lunr: download an inbound Discord attachment from its CDN URL. */\n/** Discord REST error code (DiscordAPIError.code) when present. */\nfunction discordErrorCode(err: unknown): number | undefined {\n\tconst code = (err as { code?: unknown } | null)?.code;\n\treturn typeof code === \"number\" ? code : undefined;\n}\n\nexport interface MessageToEventOptions {\n\t/** Channel ids (or parent ids for threads) to drop outright — blacklist wins over mentions. */\n\tignoredChannels?: readonly string[];\n\t/** Threads the bot has spoken in; messages there count as mentionedBot. */\n\tparticipatingThreads?: ReadonlySet<string>;\n}\n\nfunction isImageContentType(contentType: string | undefined): boolean {\n\treturn typeof contentType === \"string\" && contentType.split(\";\")[0]?.trim().toLowerCase().startsWith(\"image/\");\n}\n\n/** lunr: collect inbound image attachments (contentType image/*) from a Discord message. */\nexport function collectDiscordImageAttachments(message: DiscordMessageLike): DiscordAttachmentLike[] {\n\treturn Array.from(message.attachments?.values() ?? []).filter((attachment) =>\n\t\tisImageContentType(attachment.contentType),\n\t);\n}\n\n/**\n * Map a Discord message to a MessageEvent; null = drop (own message, any bot,\n * system message, ignored channel, unsupported channel type, or a non-DM\n * message mentioning others but not us). Messages with no text but image\n * attachments are kept (v1: images inbound).\n */\nexport function messageToEvent(\n\tmessage: DiscordMessageLike,\n\tbotUser: { id: string },\n\toptions: MessageToEventOptions = {},\n): MessageEvent | null {\n\tconst author = message.author;\n\tif (!author) return null;\n\tif (author.id === botUser.id) return null; // own messages\n\tif (author.bot) return null; // all bots (same simplification as telegram)\n\tif (message.system) return null;\n\tconst content = (message.content ?? \"\").trim();\n\tconst imageAttachments = collectDiscordImageAttachments(message);\n\tif (content === \"\" && imageAttachments.length === 0 && !Array.from(message.attachments?.values() ?? []).length)\n\t\treturn null;\n\n\tconst channel = message.channel;\n\tconst ignored = options.ignoredChannels ?? [];\n\tif (ignored.includes(channel.id) || (channel.parentId != null && ignored.includes(channel.parentId))) {\n\t\treturn null; // blacklist wins over mentions\n\t}\n\n\t// chatId/threadId mapping — see the file header for the session-key pairing.\n\tlet chatType: ChatType;\n\tlet chatId: string;\n\tlet threadId: string | undefined;\n\tif (channel.type === ChannelType.DM) {\n\t\tchatType = \"dm\";\n\t\tchatId = channel.id;\n\t} else if (THREAD_TYPES.includes(channel.type)) {\n\t\tchatType = \"thread\";\n\t\tchatId = channel.parentId ?? channel.id;\n\t\tthreadId = channel.id;\n\t} else if (channel.type === ChannelType.GuildText || channel.type === ChannelType.GuildAnnouncement) {\n\t\tchatType = \"group\";\n\t\tchatId = channel.id;\n\t} else {\n\t\treturn null; // voice/category/forum containers etc. — unsupported in v1\n\t}\n\n\tconst explicitMention = message.mentions?.has(botUser) === true;\n\tconst participating = threadId !== undefined && options.participatingThreads?.has(threadId) === true;\n\tconst mentionedBot = explicitMention || participating;\n\n\t// Multi-agent filter (hermes DISCORD_IGNORE_NO_MENTION): outside DMs, a\n\t// message that mentions other users/bots but not us is not for us.\n\tif (!mentionedBot && chatType !== \"dm\") {\n\t\tconst mentionedIds = [...content.matchAll(/<@!?(\\d+)>/g)].map((m) => m[1]);\n\t\tif (mentionedIds.some((id) => id !== botUser.id)) return null;\n\t}\n\n\tlet text = content;\n\tif (explicitMention) {\n\t\ttext = text.replace(new RegExp(`<@!?${botUser.id}>`, \"g\"), \"\").trim();\n\t}\n\n\tconst refId = message.reference?.messageId;\n\tconst cachedReply = refId != null ? channel.messages?.cache?.get(refId)?.content : undefined;\n\n\treturn {\n\t\ttext,\n\t\tmessageId: message.id,\n\t\treplyToText: cachedReply !== undefined ? cachedReply.slice(0, REPLY_TO_TEXT_MAX) : undefined,\n\t\tsource: {\n\t\t\tplatform: \"discord\",\n\t\t\tchatId,\n\t\t\tchatType,\n\t\t\tuserId: author.id,\n\t\t\tuserName: author.username,\n\t\t\tthreadId,\n\t\t},\n\t\tmetadata: mentionedBot ? { mentionedBot: true } : undefined,\n\t};\n}\n\nfunction mapDiscordChannel(\n\tchannel: DiscordChannelLike,\n): { chatType: ChatType; chatId: string; threadId?: string } | null {\n\tif (channel.type === ChannelType.DM) {\n\t\treturn { chatType: \"dm\", chatId: channel.id };\n\t}\n\tif (THREAD_TYPES.includes(channel.type)) {\n\t\treturn { chatType: \"thread\", chatId: channel.parentId ?? channel.id, threadId: channel.id };\n\t}\n\tif (channel.type === ChannelType.GuildText || channel.type === ChannelType.GuildAnnouncement) {\n\t\treturn { chatType: \"group\", chatId: channel.id };\n\t}\n\treturn null;\n}\n\nexport function buttonInteractionToEvent(interaction: DiscordButtonInteractionLike): CallbackEvent | null {\n\tconst channel = interaction.message.channel;\n\tconst mapped = mapDiscordChannel(channel);\n\tif (!mapped) return null;\n\treturn {\n\t\tid: interaction.id,\n\t\tchatId: mapped.chatId,\n\t\tmessageId: interaction.message.id,\n\t\tuserId: interaction.user.id,\n\t\tuserName: interaction.user.username,\n\t\tdata: interaction.customId,\n\t\tthreadId: mapped.threadId,\n\t};\n}\n\nfunction buildDiscordComponents(buttons: ButtonSpec[][]): unknown[] {\n\tconst rows: ActionRowBuilder<ButtonBuilder>[] = [];\n\tfor (const row of buttons) {\n\t\tconst actionRow = new ActionRowBuilder<ButtonBuilder>();\n\t\tfor (const button of row) {\n\t\t\tconst style = button.data === \"\" ? ButtonStyle.Secondary : ButtonStyle.Secondary;\n\t\t\tconst builder = new ButtonBuilder().setCustomId(button.data).setLabel(button.label).setStyle(style);\n\t\t\tif (button.data === \"\") builder.setDisabled(true);\n\t\t\tactionRow.addComponents(builder);\n\t\t}\n\t\trows.push(actionRow);\n\t}\n\treturn rows;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway-resume replay dedup (module-level: one process = one bot connection)\n// ---------------------------------------------------------------------------\n\nconst seenMessageIds = new Set<string>();\n\n/** Returns true when this id was already seen (drop the replay). */\nfunction markMessageSeen(id: string): boolean {\n\tif (seenMessageIds.has(id)) return true;\n\tseenMessageIds.add(id);\n\tif (seenMessageIds.size > SEEN_CAP) {\n\t\tconst oldest = seenMessageIds.values().next().value; // Sets iterate in insertion order\n\t\tif (oldest !== undefined) seenMessageIds.delete(oldest);\n\t}\n\treturn false;\n}\n\n/** Test hook: reset RESUME dedup state between tests. */\nexport function resetSeenMessageIds(): void {\n\tseenMessageIds.clear();\n}\n\n// ---------------------------------------------------------------------------\n// Adapter\n// ---------------------------------------------------------------------------\n\nconst defaultScheduler: Scheduler = {\n\tsetTimeout: (fn, ms) => {\n\t\tconst handle = setTimeout(fn, ms);\n\t\thandle.unref?.();\n\t\treturn handle;\n\t},\n\tclearTimeout: (handle) => clearTimeout(handle),\n\tsetInterval: (fn, ms) => {\n\t\tconst handle = setInterval(fn, ms);\n\t\thandle.unref?.();\n\t\treturn handle;\n\t},\n\tclearInterval: (handle) => clearInterval(handle),\n};\n\nfunction defaultClientFactory(): DiscordClientLike {\n\t// No GatewayIntentBits.GuildMembers — see the file header for the\n\t// privileged-intent trap (bot stays offline without the portal opt-in).\n\treturn new Client({\n\t\tintents: [\n\t\t\tGatewayIntentBits.Guilds,\n\t\t\tGatewayIntentBits.GuildMessages,\n\t\t\tGatewayIntentBits.DirectMessages,\n\t\t\tGatewayIntentBits.MessageContent,\n\t\t],\n\t}) as unknown as DiscordClientLike;\n}\n\nexport interface DiscordAdapterOptions {\n\t/** Injected Client factory (tests). When omitted, a real discord.js Client is created. */\n\tclientFactory?: DiscordClientFactory;\n\t/** lunr: injected image downloader for inbound attachments (tests). Defaults to fetch(url). */\n\tdownloadAttachment?: (url: string) => Promise<Uint8Array>;\n\t/** lunr: skip inbound media larger than this many bytes. Defaults to 10MB. */\n\tmaxMediaBytes?: number;\n\tscheduler?: Scheduler;\n\tdebounceMs?: number;\n\tnow?: () => number;\n}\n\ninterface PendingEntry {\n\tevent: MessageEvent;\n\ttimer: ReturnType<typeof setTimeout>;\n}\n\ninterface TypingEntry {\n\tinterval: ReturnType<typeof setInterval>;\n\tlastRefresh: number;\n}\n\nfunction typingKey(chatId: string, threadId?: string): string {\n\treturn `${chatId}:${threadId ?? \"\"}`;\n}\n\nexport class DiscordAdapter implements PlatformAdapter {\n\treadonly platform = \"discord\";\n\treadonly maxMessageLength = 2000;\n\n\tprivate readonly cfg: DiscordConfig;\n\tprivate readonly clientFactory: DiscordClientFactory;\n\tprivate readonly downloadAttachment: (url: string) => Promise<Uint8Array>;\n\tprivate readonly maxMediaBytes: number;\n\tprivate readonly scheduler: Scheduler;\n\tprivate readonly debounceMs: number;\n\tprivate readonly now: () => number;\n\tprivate client?: DiscordClientLike;\n\tprivate botUserId?: string;\n\tprivate handler?: (event: MessageEvent) => void;\n\tprivate commandSuggestions?: Parameters<NonNullable<PlatformAdapter[\"setCommandSuggestions\"]>>[0];\n\tprivate callbackHandler?: (event: CallbackEvent) => void;\n\tprivate readonly pending = new Map<string, PendingEntry>();\n\tprivate readonly typing = new Map<string, TypingEntry>();\n\tprivate readonly channelCache = new Map<string, DiscordChannelLike | null>();\n\t/** Threads the bot has spoken in (session memory only; hermes persists this). */\n\tprivate readonly participatingThreads = new Set<string>();\n\t/** messageId → channel it was sent to, so editMessage finds thread messages. */\n\tprivate readonly sentMessageChannels = new Map<string, string>();\n\t/** callbackId → interaction, so answerCallback can acknowledge the click. */\n\tprivate readonly callbackInteractions = new Map<string, DiscordButtonInteractionLike>();\n\n\tconstructor(cfg: DiscordConfig, options: DiscordAdapterOptions = {}) {\n\t\tthis.cfg = cfg;\n\t\tthis.scheduler = options.scheduler ?? defaultScheduler;\n\t\tthis.debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n\t\tthis.now = options.now ?? Date.now;\n\t\tif (options.clientFactory) {\n\t\t\tthis.clientFactory = options.clientFactory;\n\t\t} else {\n\t\t\tif (!cfg.token) {\n\t\t\t\tthrow new Error(\"DiscordAdapter: no bot token (set discord.token or LUNR_DISCORD_BOT_TOKEN)\");\n\t\t\t}\n\t\t\tthis.clientFactory = defaultClientFactory;\n\t\t}\n\t\tthis.downloadAttachment = options.downloadAttachment ?? downloadAttachment;\n\t\tthis.maxMediaBytes = options.maxMediaBytes ?? 10 * 1024 * 1024;\n\t}\n\n\tsetCommandSuggestions(\n\t\thandler: (source: MessageEvent[\"source\"], command: string) => Promise<readonly string[]>,\n\t): void {\n\t\tthis.commandSuggestions = handler;\n\t}\n\n\tonMessage(handler: (event: MessageEvent) => void): void {\n\t\tthis.handler = handler;\n\t}\n\n\tonCallback(handler: (event: CallbackEvent) => void): void {\n\t\tthis.callbackHandler = handler;\n\t}\n\n\tasync connect(): Promise<boolean> {\n\t\tif (!this.cfg.token) {\n\t\t\tthrow new Error(\"DiscordAdapter: no bot token (set discord.token or LUNR_DISCORD_BOT_TOKEN)\");\n\t\t}\n\t\tconst client = this.clientFactory();\n\t\tthis.client = client;\n\t\tclient.on(Events.MessageCreate, (message) => {\n\t\t\tvoid this.handleMessage(message as DiscordMessageLike).catch((err) => {\n\t\t\t\tconsole.error(`[gateway] discord message handling error: ${errMessage(err)}`);\n\t\t\t});\n\t\t});\n\t\tclient.on(Events.InteractionCreate, (interaction) => {\n\t\t\tconst event = interaction as Interaction;\n\t\t\tconst handling = event.isButton()\n\t\t\t\t? this.handleInteraction(interaction as DiscordButtonInteractionLike)\n\t\t\t\t: this.handleNativeCommand(event);\n\t\t\tvoid handling.catch((err) => {\n\t\t\t\tconsole.error(`[gateway] discord interaction handling error: ${errMessage(err)}`);\n\t\t\t});\n\t\t});\n\t\tconst ready = new Promise<void>((resolve) => client.once(Events.ClientReady, () => resolve()));\n\t\ttry {\n\t\t\tawait client.login(this.cfg.token);\n\t\t} catch (err) {\n\t\t\tconsole.error(`[gateway] discord login failed: ${errMessage(err)}`);\n\t\t\treturn false;\n\t\t}\n\t\tawait ready;\n\t\tthis.botUserId = client.user?.id;\n\t\tif (this.botUserId === undefined) {\n\t\t\tconsole.error(\"[gateway] discord: client ready without a user — cannot map messages\");\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tasync disconnect(): Promise<void> {\n\t\tfor (const key of [...this.pending.keys()]) this.cancelPending(key);\n\t\tfor (const key of [...this.typing.keys()]) this.stopTyping(key);\n\t\tthis.channelCache.clear();\n\t\tthis.callbackInteractions.clear();\n\t\tthis.client?.destroy();\n\t\tthis.client = undefined;\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// Inbound dispatch + debounce\n\t// -----------------------------------------------------------------------\n\n\tprivate async handleMessage(message: DiscordMessageLike): Promise<void> {\n\t\tif (!this.botUserId || !this.handler) return;\n\t\tif (markMessageSeen(message.id)) return; // gateway-resume replay\n\t\tconst event = messageToEvent(\n\t\t\tmessage,\n\t\t\t{ id: this.botUserId },\n\t\t\t{\n\t\t\t\tignoredChannels: this.cfg.ignoredChannels,\n\t\t\t\tparticipatingThreads: this.participatingThreads,\n\t\t\t},\n\t\t);\n\t\tif (!event) return;\n\t\tif (!isAuthorized(event.source, { ...loadGatewayConfig(), discord: this.cfg }, createPairingStore())) {\n\t\t\tthis.dispatchEvent(event);\n\t\t\treturn;\n\t\t}\n\t\tawait this.resolveReplyToText(message, event);\n\t\tawait this.maybeAutoThread(message, event);\n\t\tawait this.downloadAttachments(message, event);\n\t\tthis.dispatchEvent(event);\n\t}\n\n\t/** Download and encode attachments after authorization. */\n\tprivate async downloadAttachments(message: DiscordMessageLike, event: MessageEvent): Promise<void> {\n\t\tconst imageAttachments = Array.from(message.attachments?.values() ?? []);\n\t\tif (imageAttachments.length === 0) return;\n\t\tconst attachments: InboundAttachment[] = [];\n\t\tfor (const attachment of imageAttachments) {\n\t\t\tif (attachment.size !== undefined && attachment.size > this.maxMediaBytes) continue;\n\t\t\ttry {\n\t\t\t\tconst bytes = await this.downloadAttachment(attachment.url);\n\t\t\t\tif (bytes.byteLength > this.maxMediaBytes) continue;\n\t\t\t\tattachments.push({\n\t\t\t\t\tdata: Buffer.from(bytes).toString(\"base64\"),\n\t\t\t\t\tmimeType: attachment.contentType ?? \"application/octet-stream\",\n\t\t\t\t\t...(attachment.name ? { filename: attachment.name } : {}),\n\t\t\t\t});\n\t\t\t} catch {\n\t\t\t\t// Media download failed — drop this attachment, keep the text turn.\n\t\t\t}\n\t\t}\n\t\tif (attachments.length > 0) event.attachments = attachments;\n\t}\n\n\tasync registerCommands(commands: { name: string; description: string }[]): Promise<void> {\n\t\tif (!this.client?.application) return;\n\t\tawait this.client.application.commands.set(\n\t\t\tcommands.slice(0, 95).map((command) => ({\n\t\t\t\tname: command.name,\n\t\t\t\tdescription: command.description.slice(0, 100),\n\t\t\t\toptions: [\n\t\t\t\t\t{\n\t\t\t\t\t\tname: \"args\",\n\t\t\t\t\t\tdescription: \"Command arguments or search\",\n\t\t\t\t\t\ttype: ApplicationCommandOptionType.String,\n\t\t\t\t\t\trequired: false,\n\t\t\t\t\t\tautocomplete: [\"mode\", \"thinking\", \"project\", \"sessions\"].includes(command.name),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t})),\n\t\t);\n\t}\n\n\tprivate async handleNativeCommand(interaction: Interaction): Promise<boolean> {\n\t\tif (!interaction.isChatInputCommand?.() && !interaction.isAutocomplete?.()) return false;\n\t\tif (!interaction.isChatInputCommand() && !interaction.isAutocomplete()) return false;\n\t\tconst thread = interaction.channel?.isThread() ? interaction.channel : undefined;\n\t\tconst source = {\n\t\t\tplatform: \"discord\",\n\t\t\tchatId: thread?.parentId ?? interaction.channelId ?? interaction.user.id,\n\t\t\tthreadId: thread?.id,\n\t\t\tchatType: thread ? (\"thread\" as const) : interaction.inGuild() ? (\"channel\" as const) : (\"dm\" as const),\n\t\t\tuserId: interaction.user.id,\n\t\t\tuserName: interaction.user.username,\n\t\t};\n\t\tconst cfg = loadGatewayConfig();\n\t\tconst authorized = isAuthorized(source, cfg, createPairingStore());\n\t\tif (interaction.isAutocomplete()) {\n\t\t\tif (!authorized || !isGatewayOwner(source, cfg)) {\n\t\t\t\tawait interaction.respond([]);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tconst query = String(interaction.options.getFocused()).toLowerCase();\n\t\t\tlet values: string[] = [];\n\t\t\tif (interaction.commandName === \"mode\") values = [\"yolo\", \"auto\", \"read-only\"];\n\t\t\tif (this.commandSuggestions && [\"thinking\", \"model\"].includes(interaction.commandName)) {\n\t\t\t\tvalues = [...(await this.commandSuggestions(source, interaction.commandName))];\n\t\t\t}\n\t\t\tif (interaction.commandName === \"project\") values = cfg.projectRoots ?? [];\n\t\t\tif (interaction.commandName === \"sessions\") {\n\t\t\t\tconst { SessionManager } = await import(\"../../core/session-manager.ts\");\n\t\t\t\tvalues = (\n\t\t\t\t\tawait Promise.race([\n\t\t\t\t\t\tSessionManager.listAll(),\n\t\t\t\t\t\tnew Promise<[]>((resolve) => setTimeout(() => resolve([]), 1500)),\n\t\t\t\t\t])\n\t\t\t\t).map((s) => s.name || s.id);\n\t\t\t}\n\t\t\tawait interaction.respond(\n\t\t\t\tvalues\n\t\t\t\t\t.filter((s) => s.toLowerCase().includes(query))\n\t\t\t\t\t.slice(0, 25)\n\t\t\t\t\t.map((value) => ({ name: value.slice(0, 100), value: value.slice(0, 100) })),\n\t\t\t);\n\t\t\treturn true;\n\t\t}\n\t\tawait interaction.reply({\n\t\t\tcontent: authorized\n\t\t\t\t? \"Command received.\"\n\t\t\t\t: \"Pair your account before using this command. Send the bot a private message for a pairing code.\",\n\t\t\tephemeral: true,\n\t\t});\n\t\tif (authorized)\n\t\t\tthis.handler?.({\n\t\t\t\ttext: `/${interaction.commandName}${interaction.options.getString(\"args\") ? ` ${interaction.options.getString(\"args\")}` : \"\"}`,\n\t\t\t\tsource,\n\t\t\t\tmessageId: \"\",\n\t\t\t\tmetadata: { mentionedBot: true, nativeCommand: true },\n\t\t\t});\n\t\treturn true;\n\t}\n\n\tasync sendFile(chatId: string, file: string, opts?: SendOptions): Promise<SendResult> {\n\t\tconst channel = await this.fetchChannel(opts?.threadId ?? chatId);\n\t\tif (!channel?.send) return { success: false, error: \"Channel is unavailable.\" };\n\t\ttry {\n\t\t\tconst message = await channel.send({ content: \"\", files: [file] });\n\t\t\treturn { success: true, messageId: message.id };\n\t\t} catch (error) {\n\t\t\treturn { success: false, error: errMessage(error) };\n\t\t}\n\t}\n\n\tprivate async handleInteraction(interaction: DiscordButtonInteractionLike): Promise<void> {\n\t\tif (!this.callbackHandler) return;\n\t\tif (!interaction.isButton()) return;\n\t\tconst event = buttonInteractionToEvent(interaction);\n\t\tif (!event) return;\n\t\tthis.callbackInteractions.set(interaction.id, interaction);\n\t\tif (this.callbackInteractions.size > CALLBACK_INTERACTION_CAP) {\n\t\t\tconst oldest = this.callbackInteractions.keys().next().value;\n\t\t\tif (oldest !== undefined) this.callbackInteractions.delete(oldest);\n\t\t}\n\t\tthis.callbackHandler(event);\n\t}\n\n\t/** Best-effort: fill replyToText from the referenced message when it wasn't cached. */\n\tprivate async resolveReplyToText(message: DiscordMessageLike, event: MessageEvent): Promise<void> {\n\t\tif (event.replyToText !== undefined) return;\n\t\tconst refId = message.reference?.messageId;\n\t\tif (refId == null) return;\n\t\tconst messages = message.channel.messages;\n\t\tif (!messages) return;\n\t\ttry {\n\t\t\tconst referenced = await messages.fetch(refId);\n\t\t\tif (referenced?.content) event.replyToText = referenced.content.slice(0, REPLY_TO_TEXT_MAX);\n\t\t} catch {\n\t\t\t// unknown/deleted reference — no reply context\n\t\t}\n\t}\n\n\t/** autoThread: spin a thread off a bot-mentioning guild-text message and re-target the event. */\n\tprivate async maybeAutoThread(message: DiscordMessageLike, event: MessageEvent): Promise<void> {\n\t\tif (!this.cfg.autoThread) return;\n\t\tif (event.metadata?.mentionedBot !== true) return;\n\t\t// Only guild TEXT channels: DMs can't thread and messages already inside\n\t\t// a thread don't need another one.\n\t\tif (message.channel.type !== ChannelType.GuildText) return;\n\t\tif (typeof message.startThread !== \"function\") return;\n\t\ttry {\n\t\t\tconst thread = await message.startThread({\n\t\t\t\tname: (event.text || \"conversation\").slice(0, THREAD_NAME_MAX),\n\t\t\t\tautoArchiveDuration: 60,\n\t\t\t});\n\t\t\tthis.participatingThreads.add(thread.id);\n\t\t\tif (this.participatingThreads.size > PARTICIPATING_THREAD_CAP) {\n\t\t\t\tconst oldest = this.participatingThreads.values().next().value;\n\t\t\t\tif (oldest !== undefined) this.participatingThreads.delete(oldest);\n\t\t\t}\n\t\t\tevent.source = { ...event.source, chatType: \"thread\", chatId: message.channel.id, threadId: thread.id };\n\t\t} catch {\n\t\t\t// e.g. missing CREATE_THREADS permission — respond in-channel instead.\n\t\t}\n\t}\n\n\tprivate debounceKey(event: MessageEvent): string {\n\t\treturn `${event.source.chatId}:${event.source.threadId ?? \"\"}:${event.source.userId}`;\n\t}\n\n\tprivate dispatchEvent(event: MessageEvent): void {\n\t\tconst key = this.debounceKey(event);\n\t\tif (event.text.trimStart().startsWith(\"/\")) {\n\t\t\t// Commands must not merge: flush any pending text, emit immediately.\n\t\t\tthis.flushPending(key);\n\t\t\tthis.handler?.(event);\n\t\t\treturn;\n\t\t}\n\t\tconst existing = this.pending.get(key);\n\t\tif (existing) {\n\t\t\tthis.scheduler.clearTimeout(existing.timer);\n\t\t\t// Merge: earlier text first, latest messageId (and other fields) win.\n\t\t\tconst mergedAttachments = [...(existing.event.attachments ?? []), ...(event.attachments ?? [])];\n\t\t\texisting.event = {\n\t\t\t\t...event,\n\t\t\t\ttext: `${existing.event.text}\\n${event.text}`,\n\t\t\t\t...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),\n\t\t\t};\n\t\t\texisting.timer = this.scheduler.setTimeout(() => this.flushPending(key), this.debounceMs);\n\t\t} else {\n\t\t\tconst timer = this.scheduler.setTimeout(() => this.flushPending(key), this.debounceMs);\n\t\t\tthis.pending.set(key, { event, timer });\n\t\t}\n\t}\n\n\tprivate flushPending(key: string): void {\n\t\tconst entry = this.pending.get(key);\n\t\tif (!entry) return;\n\t\tthis.scheduler.clearTimeout(entry.timer);\n\t\tthis.pending.delete(key);\n\t\tthis.handler?.(entry.event);\n\t}\n\n\tprivate cancelPending(key: string): void {\n\t\tconst entry = this.pending.get(key);\n\t\tif (!entry) return;\n\t\tthis.scheduler.clearTimeout(entry.timer);\n\t\tthis.pending.delete(key);\n\t}\n\n\t// -----------------------------------------------------------------------\n\t// Outbound\n\t// -----------------------------------------------------------------------\n\n\tprivate async fetchChannel(id: string): Promise<DiscordChannelLike | null> {\n\t\tif (this.channelCache.has(id)) return this.channelCache.get(id) ?? null;\n\t\tif (!this.client) return null;\n\t\ttry {\n\t\t\tconst channel = await this.client.channels.fetch(id);\n\t\t\tthis.channelCache.set(id, channel);\n\t\t\tif (this.channelCache.size > CHANNEL_CACHE_CAP) {\n\t\t\t\tconst oldest = this.channelCache.keys().next().value;\n\t\t\t\tif (oldest !== undefined) this.channelCache.delete(oldest);\n\t\t\t}\n\t\t\treturn channel;\n\t\t} catch {\n\t\t\tthis.channelCache.set(id, null);\n\t\t\tif (this.channelCache.size > CHANNEL_CACHE_CAP) {\n\t\t\t\tconst oldest = this.channelCache.keys().next().value;\n\t\t\t\tif (oldest !== undefined) this.channelCache.delete(oldest);\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tprivate recordSent(messageId: string, channel: DiscordChannelLike): void {\n\t\tif (THREAD_TYPES.includes(channel.type)) this.participatingThreads.add(channel.id);\n\t\tif (this.participatingThreads.size > PARTICIPATING_THREAD_CAP) {\n\t\t\tconst oldest = this.participatingThreads.values().next().value;\n\t\t\tif (oldest !== undefined) this.participatingThreads.delete(oldest);\n\t\t}\n\t\tthis.sentMessageChannels.set(messageId, channel.id);\n\t\tif (this.sentMessageChannels.size > SENT_CHANNEL_CAP) {\n\t\t\tconst oldest = this.sentMessageChannels.keys().next().value;\n\t\t\tif (oldest !== undefined) this.sentMessageChannels.delete(oldest);\n\t\t}\n\t}\n\n\tprivate async trySend(\n\t\tchannel: DiscordChannelLike,\n\t\tpayload: { content: string; reply?: { messageReference: string }; components?: unknown[] },\n\t): Promise<SendResult> {\n\t\tif (typeof channel.send !== \"function\") {\n\t\t\treturn { success: false, error: `channel ${channel.id} is not sendable` };\n\t\t}\n\t\ttry {\n\t\t\tconst sent = await channel.send(payload);\n\t\t\tthis.recordSent(sent.id, channel);\n\t\t\treturn { success: true, messageId: sent.id };\n\t\t} catch (err) {\n\t\t\t// 429s are queued internally by discord.js and don't surface here.\n\t\t\treturn { success: false, error: errMessage(err), retryable: discordErrorCode(err) !== ERR_INVALID_FORM_BODY };\n\t\t}\n\t}\n\n\tasync send(chatId: string, text: string, opts?: SendOptions): Promise<SendResult> {\n\t\t// A completed send ends the typing bubble — stop the refresher (see sendTyping).\n\t\tthis.stopTyping(typingKey(chatId, opts?.threadId));\n\t\tconst channel = await this.fetchChannel(opts?.threadId ?? chatId);\n\t\tif (!channel) return { success: false, error: `channel ${opts?.threadId ?? chatId} not found` };\n\t\tconst result = await this.trySend(channel, {\n\t\t\tcontent: text,\n\t\t\treply: opts?.replyTo !== undefined ? { messageReference: opts.replyTo } : undefined,\n\t\t});\n\t\tif (!result.success && opts?.replyTo !== undefined) {\n\t\t\t// The reply target may be deleted/unknown — fall back to a plain send.\n\t\t\treturn this.trySend(channel, { content: text });\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync sendButtons(chatId: string, text: string, buttons: ButtonSpec[][], opts?: SendOptions): Promise<SendResult> {\n\t\tthis.stopTyping(typingKey(chatId, opts?.threadId));\n\t\tconst channel = await this.fetchChannel(opts?.threadId ?? chatId);\n\t\tif (!channel) return { success: false, error: `channel ${opts?.threadId ?? chatId} not found` };\n\t\tconst result = await this.trySend(channel, {\n\t\t\tcontent: text,\n\t\t\treply: opts?.replyTo !== undefined ? { messageReference: opts.replyTo } : undefined,\n\t\t\tcomponents: buildDiscordComponents(buttons),\n\t\t});\n\t\tif (!result.success && opts?.replyTo !== undefined) {\n\t\t\treturn this.trySend(channel, { content: text, components: buildDiscordComponents(buttons) });\n\t\t}\n\t\treturn result;\n\t}\n\n\tasync answerCallback(id: string, text?: string): Promise<void> {\n\t\tconst interaction = this.callbackInteractions.get(id);\n\t\tif (!interaction) return;\n\t\tthis.callbackInteractions.delete(id);\n\t\ttry {\n\t\t\tif (text !== undefined && interaction.reply) {\n\t\t\t\tawait interaction.reply({ content: text, ephemeral: true });\n\t\t\t} else {\n\t\t\t\tawait interaction.deferUpdate();\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort acknowledgment\n\t\t}\n\t}\n\n\tasync editMessage(chatId: string, messageId: string, text: string, buttons?: ButtonSpec[][]): Promise<SendResult> {\n\t\t// The router passes only chatId; thread messages live in their own\n\t\t// channel, so prefer the channel recorded at send() time.\n\t\tconst channel = await this.fetchChannel(this.sentMessageChannels.get(messageId) ?? chatId);\n\t\tif (!channel?.messages) {\n\t\t\treturn { success: false, error: `channel ${this.sentMessageChannels.get(messageId) ?? chatId} not found` };\n\t\t}\n\t\ttry {\n\t\t\tconst message = await channel.messages.fetch(messageId);\n\t\t\tif (!message || typeof message.edit !== \"function\") {\n\t\t\t\treturn { success: false, error: `message ${messageId} not found` };\n\t\t\t}\n\t\t\tconst editOptions: { content: string; components?: unknown[] } = { content: text };\n\t\t\tif (buttons !== undefined) editOptions.components = buildDiscordComponents(buttons);\n\t\t\tawait message.edit(editOptions);\n\t\t\treturn { success: true, messageId };\n\t\t} catch (err) {\n\t\t\tconst code = discordErrorCode(err);\n\t\t\tif (code === ERR_UNKNOWN_MESSAGE) return { success: false, error: errMessage(err) }; // terminal\n\t\t\treturn { success: false, error: errMessage(err), retryable: true };\n\t\t}\n\t}\n\n\tasync sendTyping(chatId: string, threadId?: string): Promise<void> {\n\t\t// Self-contained typing refresher (see file header): re-send the action\n\t\t// every 8s until send() completes for this target or the 2min safety net\n\t\t// fires — all errors swallowed.\n\t\tconst key = typingKey(chatId, threadId);\n\t\tconst targetId = threadId ?? chatId;\n\t\tawait this.doTyping(targetId);\n\t\tconst existing = this.typing.get(key);\n\t\tif (existing) {\n\t\t\texisting.lastRefresh = this.now();\n\t\t\treturn;\n\t\t}\n\t\tconst interval = this.scheduler.setInterval(() => {\n\t\t\tconst entry = this.typing.get(key);\n\t\t\tif (!entry) return;\n\t\t\tif (this.now() - entry.lastRefresh > TYPING_SAFETY_MS) {\n\t\t\t\tthis.stopTyping(key);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvoid this.doTyping(targetId);\n\t\t}, TYPING_INTERVAL_MS);\n\t\tthis.typing.set(key, { interval, lastRefresh: this.now() });\n\t}\n\n\tprivate async doTyping(channelId: string): Promise<void> {\n\t\ttry {\n\t\t\tconst channel = await this.fetchChannel(channelId);\n\t\t\tawait channel?.sendTyping?.();\n\t\t} catch {\n\t\t\t// typing is cosmetic — never surface\n\t\t}\n\t}\n\n\tprivate stopTyping(key: string): void {\n\t\tconst entry = this.typing.get(key);\n\t\tif (!entry) return;\n\t\tthis.scheduler.clearInterval(entry.interval);\n\t\tthis.typing.delete(key);\n\t}\n}\n"]}
@@ -1,10 +1,6 @@
1
1
  /**
2
- * lunR: gateway approval prompt for manual permission mode.
3
- *
4
- * The gateway runs headless sessions. When a mutating tool call arrives in
5
- * manual mode, this module posts an inline-button approve/reject prompt to
6
- * the originating chat and awaits the callback. If no chat context is present
7
- * the request is rejected (fail-closed).
2
+ * Gateway approvals for large subagent launches and plans.
3
+ * A missing chat context rejects large launches; plans pass through.
8
4
  */
9
5
  import { type ApprovalRequest, type ApprovalResponse } from "../core/permissions.ts";
10
6
  import type { CallbackEvent, PlatformAdapter, SessionSource } from "./types.ts";
@@ -1 +1 @@
1
- {"version":3,"file":"approval.d.ts","sourceRoot":"","sources":["../../src/gateway/approval.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,gBAAgB,EAIrB,MAAM,wBAAwB,CAAC;AAMhC,OAAO,KAAK,EAAc,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAO5F,UAAU,eAAe;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,eAAe,CAAC;IACzB,MAAM,EAAE,aAAa,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AA6CD,+EAA+E;AAC/E,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,GAAG,EAAE,eAAe,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAEhG;AAmED,mDAAmD;AACnD,wBAAsB,4BAA4B,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAMlG;AAED,2EAA2E;AAC3E,wBAAgB,8BAA8B,IAAI,IAAI,CAErD;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,CA+C9G;AAED,sEAAsE;AACtE,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CASxD;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAU5C;AAED,yDAAyD;AACzD,wBAAgB,mBAAmB,IAAI,MAAM,CAE5C","sourcesContent":["/**\n * lunR: gateway approval prompt for manual permission mode.\n *\n * The gateway runs headless sessions. When a mutating tool call arrives in\n * manual mode, this module posts an inline-button approve/reject prompt to\n * the originating chat and awaits the callback. If no chat context is present\n * the request is rejected (fail-closed).\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n\ttype ApprovalRequest,\n\ttype ApprovalResponse,\n\tNO_HANDLER_REASON,\n\tregisterApprovalHandler,\n\tsetPermissionMode,\n} from \"../core/permissions.ts\";\nimport { isAuthorized, isGatewayOwner } from \"./authz.ts\";\nimport { loadGatewayConfig } from \"./config.ts\";\nimport { conversationBinding } from \"./conversations.ts\";\nimport { createPairingStore } from \"./pairing.ts\";\nimport { getSession } from \"./store.ts\";\nimport type { ButtonSpec, CallbackEvent, PlatformAdapter, SessionSource } from \"./types.ts\";\n\nconst CALLBACK_PREFIX = \"ap:\";\nconst ID_LENGTH = 8;\nconst CODE_ALPHABET = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;\n\ninterface ApprovalContext {\n\tkey: string;\n\tadapter: PlatformAdapter;\n\tsource: SessionSource;\n\ttimeoutMs?: number;\n}\n\ninterface PendingApproval {\n\tkey?: string;\n\tsource: SessionSource;\n\tplan: boolean;\n\tresolve: (value: ApprovalResponse) => void;\n\treject: (reason?: unknown) => void;\n\ttimeout: ReturnType<typeof setTimeout>;\n\tmessageId?: string;\n\tadapter: PlatformAdapter;\n\tchatId: string;\n\tthreadId?: string;\n\tuserId: string;\n}\n\nconst approvalContext = new AsyncLocalStorage<ApprovalContext>();\nconst pending = new Map<string, PendingApproval>();\n\nfunction generateId(): string {\n\tlet id = \"\";\n\tconst bytes = randomBytes(ID_LENGTH);\n\tfor (let i = 0; i < ID_LENGTH; i++) {\n\t\tid += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];\n\t}\n\treturn id;\n}\n\nfunction makeCallbackData(id: string, action: ApprovalResponse | \"cancel\"): string {\n\treturn `${CALLBACK_PREFIX}${id}:${action}`;\n}\n\nfunction parseCallbackData(data: string): { id: string; action: ApprovalResponse | \"cancel\" } | null {\n\tif (!data.startsWith(CALLBACK_PREFIX)) return null;\n\tconst rest = data.slice(CALLBACK_PREFIX.length);\n\tconst colon = rest.indexOf(\":\");\n\tif (colon === -1) return null;\n\tconst id = rest.slice(0, colon);\n\tconst action = rest.slice(colon + 1);\n\tif (action === \"once\" || action === \"session\" || action === \"reject\" || action === \"cancel\") {\n\t\treturn { id, action };\n\t}\n\treturn null;\n}\n\n/** Run code with the gateway approval context available to tool-call gates. */\nexport function runWithApprovalContext<T>(ctx: ApprovalContext, fn: () => Promise<T>): Promise<T> {\n\treturn approvalContext.run(ctx, fn);\n}\n\nasync function createApprovalPrompt(\n\tadapter: PlatformAdapter,\n\tsource: SessionSource,\n\treq: ApprovalRequest,\n\ttimeoutMs = DEFAULT_TIMEOUT_MS,\n\tkey?: string,\n): Promise<ApprovalResponse> {\n\tconst id = generateId();\n\t// Large child launches get a dedicated title; inline buttons cannot capture feedback.\n\tconst title =\n\t\treq.kind === \"large-subagent-launch\"\n\t\t\t? `Approve large subagent launch?\\n${req.detail}`\n\t\t\t: `Approve ${req.toolName}?\\n${req.detail}`;\n\tconst rows: ButtonSpec[][] = [\n\t\t[\n\t\t\t{ label: \"✓ Approve once\", data: makeCallbackData(id, \"once\") },\n\t\t\t{ label: \"✓ Approve session\", data: makeCallbackData(id, \"session\") },\n\t\t],\n\t\t[{ label: \"✗ Reject\", data: makeCallbackData(id, \"reject\") }],\n\t];\n\n\treturn new Promise<ApprovalResponse>((resolve, reject) => {\n\t\tlet messageId: string | undefined;\n\t\tconst timeout = setTimeout(() => {\n\t\t\tpending.delete(id);\n\t\t\treject(new Error(\"Approval request timed out\"));\n\t\t\tif (messageId) {\n\t\t\t\tvoid adapter.editMessage(source.chatId, messageId, \"⏱ Approval expired.\", []).catch(() => {});\n\t\t\t}\n\t\t}, timeoutMs);\n\n\t\tconst entry: PendingApproval = {\n\t\t\tkey,\n\t\t\tsource,\n\t\t\tplan: req.kind === \"plan\",\n\t\t\tresolve,\n\t\t\treject,\n\t\t\ttimeout,\n\t\t\tadapter,\n\t\t\tchatId: source.chatId,\n\t\t\tthreadId: source.threadId,\n\t\t\tuserId: source.userId,\n\t\t};\n\t\tpending.set(id, entry);\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tconst result = await adapter.sendButtons(source.chatId, title, rows, { threadId: source.threadId });\n\t\t\t\tif (!result.success || !result.messageId) throw new Error(result.error ?? \"Failed to send approval prompt\");\n\t\t\t\tmessageId = result.messageId;\n\t\t\t\tif (pending.get(id) !== entry) {\n\t\t\t\t\tawait adapter\n\t\t\t\t\t\t.editMessage(source.chatId, messageId, \"Approval cancelled or expired.\", [])\n\t\t\t\t\t\t.catch(() => {});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentry.messageId = messageId;\n\t\t\t} catch (err) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tpending.delete(id);\n\t\t\t\treject(err);\n\t\t\t}\n\t\t})();\n\t});\n}\n\n/** Approval handler passed to core permissions. */\nexport async function createGatewayApprovalRequest(req: ApprovalRequest): Promise<ApprovalResponse> {\n\tconst ctx = approvalContext.getStore();\n\tif (!ctx) {\n\t\tthrow new Error(NO_HANDLER_REASON);\n\t}\n\treturn createApprovalPrompt(ctx.adapter, ctx.source, req, ctx.timeoutMs, ctx.key);\n}\n\n/** Register the gateway approval handler with the core permission gate. */\nexport function registerGatewayApprovalHandler(): void {\n\tregisterApprovalHandler(createGatewayApprovalRequest);\n}\n\n/**\n * Dispatch a callback event to an outstanding approval prompt.\n * Returns true when the data matched the approval prefix (whether or not a\n * pending prompt existed).\n */\nexport async function handleApprovalCallback(event: CallbackEvent, adapter?: PlatformAdapter): Promise<boolean> {\n\tconst parsed = parseCallbackData(event.data);\n\tif (!parsed) return false;\n\n\tconst entry = pending.get(parsed.id);\n\tif (!entry) {\n\t\t// Best-effort answer for stale callbacks.\n\t\tawait adapter?.answerCallback(event.id, \"Approval expired.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tif (\n\t\tevent.userId !== entry.userId ||\n\t\tevent.chatId !== entry.chatId ||\n\t\tevent.threadId !== entry.threadId ||\n\t\t(adapter && adapter.platform !== entry.adapter.platform)\n\t) {\n\t\tawait entry.adapter.answerCallback(event.id, \"⛔ Not your approval.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tclearTimeout(entry.timeout);\n\tpending.delete(parsed.id);\n\n\tconst response: ApprovalResponse =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"reject\" : parsed.action;\n\tconst binding = entry.key ? conversationBinding(entry.key) : undefined;\n\tif (binding?.owner && (!isGatewayOwner(entry.source, loadGatewayConfig()) || binding.owner !== event.userId)) {\n\t\tentry.resolve(\"reject\");\n\t\tawait entry.adapter.answerCallback(event.id, \"Owner access was removed.\").catch(() => {});\n\t\treturn true;\n\t}\n\tif (binding && !isAuthorized(entry.source, loadGatewayConfig(), createPairingStore())) {\n\t\tentry.resolve(\"reject\");\n\t\treturn true;\n\t}\n\tif (entry.plan && response !== \"reject\" && entry.key) {\n\t\tconst sessionId = getSession(entry.key)?.sessionId;\n\t\tif (sessionId) setPermissionMode(\"manual\", sessionId);\n\t}\n\tentry.resolve(response);\n\n\tconst label =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"Rejected.\" : `Approved (${parsed.action}).`;\n\tawait entry.adapter.editMessage(entry.chatId, entry.messageId ?? \"\", label, []).catch(() => {});\n\tawait entry.adapter.answerCallback(event.id).catch(() => {});\n\treturn true;\n}\n\n/** Test hook: clear all pending approvals and stop their timeouts. */\nexport function cancelGatewayApprovals(key: string): void {\n\tfor (const [id, entry] of pending) {\n\t\tif (entry.key !== key) continue;\n\t\tclearTimeout(entry.timeout);\n\t\tpending.delete(id);\n\t\tentry.resolve(\"reject\");\n\t\tif (entry.messageId)\n\t\t\tvoid entry.adapter.editMessage(entry.chatId, entry.messageId, \"Approval cancelled.\", []).catch(() => {});\n\t}\n}\n\nexport function resetApprovalRegistry(): void {\n\tfor (const entry of pending.values()) {\n\t\tclearTimeout(entry.timeout);\n\t\ttry {\n\t\t\tentry.reject(new Error(\"Approval registry reset\"));\n\t\t} catch {\n\t\t\t// ignore settled promise\n\t\t}\n\t}\n\tpending.clear();\n}\n\n/** Test hook: number of outstanding approval prompts. */\nexport function activeApprovalCount(): number {\n\treturn pending.size;\n}\n"]}
1
+ {"version":3,"file":"approval.d.ts","sourceRoot":"","sources":["../../src/gateway/approval.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EACN,KAAK,eAAe,EACpB,KAAK,gBAAgB,EAIrB,MAAM,wBAAwB,CAAC;AAMhC,OAAO,KAAK,EAAc,aAAa,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAO5F,UAAU,eAAe;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,eAAe,CAAC;IACzB,MAAM,EAAE,aAAa,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AA6CD,+EAA+E;AAC/E,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,GAAG,EAAE,eAAe,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAEhG;AAmED,mDAAmD;AACnD,wBAAsB,4BAA4B,CAAC,GAAG,EAAE,eAAe,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAMlG;AAED,2EAA2E;AAC3E,wBAAgB,8BAA8B,IAAI,IAAI,CAErD;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAAC,KAAK,EAAE,aAAa,EAAE,OAAO,CAAC,EAAE,eAAe,GAAG,OAAO,CAAC,OAAO,CAAC,CA+C9G;AAED,sEAAsE;AACtE,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CASxD;AAED,wBAAgB,qBAAqB,IAAI,IAAI,CAU5C;AAED,yDAAyD;AACzD,wBAAgB,mBAAmB,IAAI,MAAM,CAE5C","sourcesContent":["/**\n * Gateway approvals for large subagent launches and plans.\n * A missing chat context rejects large launches; plans pass through.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n\ttype ApprovalRequest,\n\ttype ApprovalResponse,\n\tNO_HANDLER_REASON,\n\tregisterApprovalHandler,\n\tsetPermissionMode,\n} from \"../core/permissions.ts\";\nimport { isAuthorized, isGatewayOwner } from \"./authz.ts\";\nimport { loadGatewayConfig } from \"./config.ts\";\nimport { conversationBinding } from \"./conversations.ts\";\nimport { createPairingStore } from \"./pairing.ts\";\nimport { getSession } from \"./store.ts\";\nimport type { ButtonSpec, CallbackEvent, PlatformAdapter, SessionSource } from \"./types.ts\";\n\nconst CALLBACK_PREFIX = \"ap:\";\nconst ID_LENGTH = 8;\nconst CODE_ALPHABET = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;\n\ninterface ApprovalContext {\n\tkey: string;\n\tadapter: PlatformAdapter;\n\tsource: SessionSource;\n\ttimeoutMs?: number;\n}\n\ninterface PendingApproval {\n\tkey?: string;\n\tsource: SessionSource;\n\tplan: boolean;\n\tresolve: (value: ApprovalResponse) => void;\n\treject: (reason?: unknown) => void;\n\ttimeout: ReturnType<typeof setTimeout>;\n\tmessageId?: string;\n\tadapter: PlatformAdapter;\n\tchatId: string;\n\tthreadId?: string;\n\tuserId: string;\n}\n\nconst approvalContext = new AsyncLocalStorage<ApprovalContext>();\nconst pending = new Map<string, PendingApproval>();\n\nfunction generateId(): string {\n\tlet id = \"\";\n\tconst bytes = randomBytes(ID_LENGTH);\n\tfor (let i = 0; i < ID_LENGTH; i++) {\n\t\tid += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];\n\t}\n\treturn id;\n}\n\nfunction makeCallbackData(id: string, action: ApprovalResponse | \"cancel\"): string {\n\treturn `${CALLBACK_PREFIX}${id}:${action}`;\n}\n\nfunction parseCallbackData(data: string): { id: string; action: ApprovalResponse | \"cancel\" } | null {\n\tif (!data.startsWith(CALLBACK_PREFIX)) return null;\n\tconst rest = data.slice(CALLBACK_PREFIX.length);\n\tconst colon = rest.indexOf(\":\");\n\tif (colon === -1) return null;\n\tconst id = rest.slice(0, colon);\n\tconst action = rest.slice(colon + 1);\n\tif (action === \"once\" || action === \"session\" || action === \"reject\" || action === \"cancel\") {\n\t\treturn { id, action };\n\t}\n\treturn null;\n}\n\n/** Run code with the gateway approval context available to tool-call gates. */\nexport function runWithApprovalContext<T>(ctx: ApprovalContext, fn: () => Promise<T>): Promise<T> {\n\treturn approvalContext.run(ctx, fn);\n}\n\nasync function createApprovalPrompt(\n\tadapter: PlatformAdapter,\n\tsource: SessionSource,\n\treq: ApprovalRequest,\n\ttimeoutMs = DEFAULT_TIMEOUT_MS,\n\tkey?: string,\n): Promise<ApprovalResponse> {\n\tconst id = generateId();\n\t// Large child launches get a dedicated title; inline buttons cannot capture feedback.\n\tconst title =\n\t\treq.kind === \"large-subagent-launch\"\n\t\t\t? `Approve large subagent launch?\\n${req.detail}`\n\t\t\t: `Approve ${req.toolName}?\\n${req.detail}`;\n\tconst rows: ButtonSpec[][] = [\n\t\t[\n\t\t\t{ label: \"✓ Approve once\", data: makeCallbackData(id, \"once\") },\n\t\t\t{ label: \"✓ Approve session\", data: makeCallbackData(id, \"session\") },\n\t\t],\n\t\t[{ label: \"✗ Reject\", data: makeCallbackData(id, \"reject\") }],\n\t];\n\n\treturn new Promise<ApprovalResponse>((resolve, reject) => {\n\t\tlet messageId: string | undefined;\n\t\tconst timeout = setTimeout(() => {\n\t\t\tpending.delete(id);\n\t\t\treject(new Error(\"Approval request timed out\"));\n\t\t\tif (messageId) {\n\t\t\t\tvoid adapter.editMessage(source.chatId, messageId, \"⏱ Approval expired.\", []).catch(() => {});\n\t\t\t}\n\t\t}, timeoutMs);\n\n\t\tconst entry: PendingApproval = {\n\t\t\tkey,\n\t\t\tsource,\n\t\t\tplan: req.kind === \"plan\",\n\t\t\tresolve,\n\t\t\treject,\n\t\t\ttimeout,\n\t\t\tadapter,\n\t\t\tchatId: source.chatId,\n\t\t\tthreadId: source.threadId,\n\t\t\tuserId: source.userId,\n\t\t};\n\t\tpending.set(id, entry);\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tconst result = await adapter.sendButtons(source.chatId, title, rows, { threadId: source.threadId });\n\t\t\t\tif (!result.success || !result.messageId) throw new Error(result.error ?? \"Failed to send approval prompt\");\n\t\t\t\tmessageId = result.messageId;\n\t\t\t\tif (pending.get(id) !== entry) {\n\t\t\t\t\tawait adapter\n\t\t\t\t\t\t.editMessage(source.chatId, messageId, \"Approval cancelled or expired.\", [])\n\t\t\t\t\t\t.catch(() => {});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentry.messageId = messageId;\n\t\t\t} catch (err) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tpending.delete(id);\n\t\t\t\treject(err);\n\t\t\t}\n\t\t})();\n\t});\n}\n\n/** Approval handler passed to core permissions. */\nexport async function createGatewayApprovalRequest(req: ApprovalRequest): Promise<ApprovalResponse> {\n\tconst ctx = approvalContext.getStore();\n\tif (!ctx) {\n\t\tthrow new Error(NO_HANDLER_REASON);\n\t}\n\treturn createApprovalPrompt(ctx.adapter, ctx.source, req, ctx.timeoutMs, ctx.key);\n}\n\n/** Register the gateway approval handler with the core permission gate. */\nexport function registerGatewayApprovalHandler(): void {\n\tregisterApprovalHandler(createGatewayApprovalRequest);\n}\n\n/**\n * Dispatch a callback event to an outstanding approval prompt.\n * Returns true when the data matched the approval prefix (whether or not a\n * pending prompt existed).\n */\nexport async function handleApprovalCallback(event: CallbackEvent, adapter?: PlatformAdapter): Promise<boolean> {\n\tconst parsed = parseCallbackData(event.data);\n\tif (!parsed) return false;\n\n\tconst entry = pending.get(parsed.id);\n\tif (!entry) {\n\t\t// Best-effort answer for stale callbacks.\n\t\tawait adapter?.answerCallback(event.id, \"Approval expired.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tif (\n\t\tevent.userId !== entry.userId ||\n\t\tevent.chatId !== entry.chatId ||\n\t\tevent.threadId !== entry.threadId ||\n\t\t(adapter && adapter.platform !== entry.adapter.platform)\n\t) {\n\t\tawait entry.adapter.answerCallback(event.id, \"⛔ Not your approval.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tclearTimeout(entry.timeout);\n\tpending.delete(parsed.id);\n\n\tconst response: ApprovalResponse =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"reject\" : parsed.action;\n\tconst binding = entry.key ? conversationBinding(entry.key) : undefined;\n\tif (binding?.owner && (!isGatewayOwner(entry.source, loadGatewayConfig()) || binding.owner !== event.userId)) {\n\t\tentry.resolve(\"reject\");\n\t\tawait entry.adapter.answerCallback(event.id, \"Owner access was removed.\").catch(() => {});\n\t\treturn true;\n\t}\n\tif (binding && !isAuthorized(entry.source, loadGatewayConfig(), createPairingStore())) {\n\t\tentry.resolve(\"reject\");\n\t\treturn true;\n\t}\n\tif (entry.plan && response !== \"reject\" && entry.key) {\n\t\tconst sessionId = getSession(entry.key)?.sessionId;\n\t\tif (sessionId) setPermissionMode(\"yolo\", sessionId);\n\t}\n\tentry.resolve(response);\n\n\tconst label =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"Rejected.\" : `Approved (${parsed.action}).`;\n\tawait entry.adapter.editMessage(entry.chatId, entry.messageId ?? \"\", label, []).catch(() => {});\n\tawait entry.adapter.answerCallback(event.id).catch(() => {});\n\treturn true;\n}\n\n/** Test hook: clear all pending approvals and stop their timeouts. */\nexport function cancelGatewayApprovals(key: string): void {\n\tfor (const [id, entry] of pending) {\n\t\tif (entry.key !== key) continue;\n\t\tclearTimeout(entry.timeout);\n\t\tpending.delete(id);\n\t\tentry.resolve(\"reject\");\n\t\tif (entry.messageId)\n\t\t\tvoid entry.adapter.editMessage(entry.chatId, entry.messageId, \"Approval cancelled.\", []).catch(() => {});\n\t}\n}\n\nexport function resetApprovalRegistry(): void {\n\tfor (const entry of pending.values()) {\n\t\tclearTimeout(entry.timeout);\n\t\ttry {\n\t\t\tentry.reject(new Error(\"Approval registry reset\"));\n\t\t} catch {\n\t\t\t// ignore settled promise\n\t\t}\n\t}\n\tpending.clear();\n}\n\n/** Test hook: number of outstanding approval prompts. */\nexport function activeApprovalCount(): number {\n\treturn pending.size;\n}\n"]}
@@ -1,10 +1,6 @@
1
1
  /**
2
- * lunR: gateway approval prompt for manual permission mode.
3
- *
4
- * The gateway runs headless sessions. When a mutating tool call arrives in
5
- * manual mode, this module posts an inline-button approve/reject prompt to
6
- * the originating chat and awaits the callback. If no chat context is present
7
- * the request is rejected (fail-closed).
2
+ * Gateway approvals for large subagent launches and plans.
3
+ * A missing chat context rejects large launches; plans pass through.
8
4
  */
9
5
  import { AsyncLocalStorage } from "node:async_hooks";
10
6
  import { randomBytes } from "node:crypto";
@@ -156,7 +152,7 @@ export async function handleApprovalCallback(event, adapter) {
156
152
  if (entry.plan && response !== "reject" && entry.key) {
157
153
  const sessionId = getSession(entry.key)?.sessionId;
158
154
  if (sessionId)
159
- setPermissionMode("manual", sessionId);
155
+ setPermissionMode("yolo", sessionId);
160
156
  }
161
157
  entry.resolve(response);
162
158
  const label = parsed.action === "reject" || parsed.action === "cancel" ? "Rejected." : `Approved (${parsed.action}).`;
@@ -1 +1 @@
1
- {"version":3,"file":"approval.js","sourceRoot":"","sources":["../../src/gateway/approval.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;A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,GAAW;IAC7C,OAAO,OAAO,CAAC,IAAI,CAAC;AAAA,CACpB","sourcesContent":["/**\n * lunR: gateway approval prompt for manual permission mode.\n *\n * The gateway runs headless sessions. When a mutating tool call arrives in\n * manual mode, this module posts an inline-button approve/reject prompt to\n * the originating chat and awaits the callback. If no chat context is present\n * the request is rejected (fail-closed).\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n\ttype ApprovalRequest,\n\ttype ApprovalResponse,\n\tNO_HANDLER_REASON,\n\tregisterApprovalHandler,\n\tsetPermissionMode,\n} from \"../core/permissions.ts\";\nimport { isAuthorized, isGatewayOwner } from \"./authz.ts\";\nimport { loadGatewayConfig } from \"./config.ts\";\nimport { conversationBinding } from \"./conversations.ts\";\nimport { createPairingStore } from \"./pairing.ts\";\nimport { getSession } from \"./store.ts\";\nimport type { ButtonSpec, CallbackEvent, PlatformAdapter, SessionSource } from \"./types.ts\";\n\nconst CALLBACK_PREFIX = \"ap:\";\nconst ID_LENGTH = 8;\nconst CODE_ALPHABET = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;\n\ninterface ApprovalContext {\n\tkey: string;\n\tadapter: PlatformAdapter;\n\tsource: SessionSource;\n\ttimeoutMs?: number;\n}\n\ninterface PendingApproval {\n\tkey?: string;\n\tsource: SessionSource;\n\tplan: boolean;\n\tresolve: (value: ApprovalResponse) => void;\n\treject: (reason?: unknown) => void;\n\ttimeout: ReturnType<typeof setTimeout>;\n\tmessageId?: string;\n\tadapter: PlatformAdapter;\n\tchatId: string;\n\tthreadId?: string;\n\tuserId: string;\n}\n\nconst approvalContext = new AsyncLocalStorage<ApprovalContext>();\nconst pending = new Map<string, PendingApproval>();\n\nfunction generateId(): string {\n\tlet id = \"\";\n\tconst bytes = randomBytes(ID_LENGTH);\n\tfor (let i = 0; i < ID_LENGTH; i++) {\n\t\tid += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];\n\t}\n\treturn id;\n}\n\nfunction makeCallbackData(id: string, action: ApprovalResponse | \"cancel\"): string {\n\treturn `${CALLBACK_PREFIX}${id}:${action}`;\n}\n\nfunction parseCallbackData(data: string): { id: string; action: ApprovalResponse | \"cancel\" } | null {\n\tif (!data.startsWith(CALLBACK_PREFIX)) return null;\n\tconst rest = data.slice(CALLBACK_PREFIX.length);\n\tconst colon = rest.indexOf(\":\");\n\tif (colon === -1) return null;\n\tconst id = rest.slice(0, colon);\n\tconst action = rest.slice(colon + 1);\n\tif (action === \"once\" || action === \"session\" || action === \"reject\" || action === \"cancel\") {\n\t\treturn { id, action };\n\t}\n\treturn null;\n}\n\n/** Run code with the gateway approval context available to tool-call gates. */\nexport function runWithApprovalContext<T>(ctx: ApprovalContext, fn: () => Promise<T>): Promise<T> {\n\treturn approvalContext.run(ctx, fn);\n}\n\nasync function createApprovalPrompt(\n\tadapter: PlatformAdapter,\n\tsource: SessionSource,\n\treq: ApprovalRequest,\n\ttimeoutMs = DEFAULT_TIMEOUT_MS,\n\tkey?: string,\n): Promise<ApprovalResponse> {\n\tconst id = generateId();\n\t// Large child launches get a dedicated title; inline buttons cannot capture feedback.\n\tconst title =\n\t\treq.kind === \"large-subagent-launch\"\n\t\t\t? `Approve large subagent launch?\\n${req.detail}`\n\t\t\t: `Approve ${req.toolName}?\\n${req.detail}`;\n\tconst rows: ButtonSpec[][] = [\n\t\t[\n\t\t\t{ label: \"✓ Approve once\", data: makeCallbackData(id, \"once\") },\n\t\t\t{ label: \"✓ Approve session\", data: makeCallbackData(id, \"session\") },\n\t\t],\n\t\t[{ label: \"✗ Reject\", data: makeCallbackData(id, \"reject\") }],\n\t];\n\n\treturn new Promise<ApprovalResponse>((resolve, reject) => {\n\t\tlet messageId: string | undefined;\n\t\tconst timeout = setTimeout(() => {\n\t\t\tpending.delete(id);\n\t\t\treject(new Error(\"Approval request timed out\"));\n\t\t\tif (messageId) {\n\t\t\t\tvoid adapter.editMessage(source.chatId, messageId, \"⏱ Approval expired.\", []).catch(() => {});\n\t\t\t}\n\t\t}, timeoutMs);\n\n\t\tconst entry: PendingApproval = {\n\t\t\tkey,\n\t\t\tsource,\n\t\t\tplan: req.kind === \"plan\",\n\t\t\tresolve,\n\t\t\treject,\n\t\t\ttimeout,\n\t\t\tadapter,\n\t\t\tchatId: source.chatId,\n\t\t\tthreadId: source.threadId,\n\t\t\tuserId: source.userId,\n\t\t};\n\t\tpending.set(id, entry);\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tconst result = await adapter.sendButtons(source.chatId, title, rows, { threadId: source.threadId });\n\t\t\t\tif (!result.success || !result.messageId) throw new Error(result.error ?? \"Failed to send approval prompt\");\n\t\t\t\tmessageId = result.messageId;\n\t\t\t\tif (pending.get(id) !== entry) {\n\t\t\t\t\tawait adapter\n\t\t\t\t\t\t.editMessage(source.chatId, messageId, \"Approval cancelled or expired.\", [])\n\t\t\t\t\t\t.catch(() => {});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentry.messageId = messageId;\n\t\t\t} catch (err) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tpending.delete(id);\n\t\t\t\treject(err);\n\t\t\t}\n\t\t})();\n\t});\n}\n\n/** Approval handler passed to core permissions. */\nexport async function createGatewayApprovalRequest(req: ApprovalRequest): Promise<ApprovalResponse> {\n\tconst ctx = approvalContext.getStore();\n\tif (!ctx) {\n\t\tthrow new Error(NO_HANDLER_REASON);\n\t}\n\treturn createApprovalPrompt(ctx.adapter, ctx.source, req, ctx.timeoutMs, ctx.key);\n}\n\n/** Register the gateway approval handler with the core permission gate. */\nexport function registerGatewayApprovalHandler(): void {\n\tregisterApprovalHandler(createGatewayApprovalRequest);\n}\n\n/**\n * Dispatch a callback event to an outstanding approval prompt.\n * Returns true when the data matched the approval prefix (whether or not a\n * pending prompt existed).\n */\nexport async function handleApprovalCallback(event: CallbackEvent, adapter?: PlatformAdapter): Promise<boolean> {\n\tconst parsed = parseCallbackData(event.data);\n\tif (!parsed) return false;\n\n\tconst entry = pending.get(parsed.id);\n\tif (!entry) {\n\t\t// Best-effort answer for stale callbacks.\n\t\tawait adapter?.answerCallback(event.id, \"Approval expired.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tif (\n\t\tevent.userId !== entry.userId ||\n\t\tevent.chatId !== entry.chatId ||\n\t\tevent.threadId !== entry.threadId ||\n\t\t(adapter && adapter.platform !== entry.adapter.platform)\n\t) {\n\t\tawait entry.adapter.answerCallback(event.id, \"⛔ Not your approval.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tclearTimeout(entry.timeout);\n\tpending.delete(parsed.id);\n\n\tconst response: ApprovalResponse =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"reject\" : parsed.action;\n\tconst binding = entry.key ? conversationBinding(entry.key) : undefined;\n\tif (binding?.owner && (!isGatewayOwner(entry.source, loadGatewayConfig()) || binding.owner !== event.userId)) {\n\t\tentry.resolve(\"reject\");\n\t\tawait entry.adapter.answerCallback(event.id, \"Owner access was removed.\").catch(() => {});\n\t\treturn true;\n\t}\n\tif (binding && !isAuthorized(entry.source, loadGatewayConfig(), createPairingStore())) {\n\t\tentry.resolve(\"reject\");\n\t\treturn true;\n\t}\n\tif (entry.plan && response !== \"reject\" && entry.key) {\n\t\tconst sessionId = getSession(entry.key)?.sessionId;\n\t\tif (sessionId) setPermissionMode(\"manual\", sessionId);\n\t}\n\tentry.resolve(response);\n\n\tconst label =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"Rejected.\" : `Approved (${parsed.action}).`;\n\tawait entry.adapter.editMessage(entry.chatId, entry.messageId ?? \"\", label, []).catch(() => {});\n\tawait entry.adapter.answerCallback(event.id).catch(() => {});\n\treturn true;\n}\n\n/** Test hook: clear all pending approvals and stop their timeouts. */\nexport function cancelGatewayApprovals(key: string): void {\n\tfor (const [id, entry] of pending) {\n\t\tif (entry.key !== key) continue;\n\t\tclearTimeout(entry.timeout);\n\t\tpending.delete(id);\n\t\tentry.resolve(\"reject\");\n\t\tif (entry.messageId)\n\t\t\tvoid entry.adapter.editMessage(entry.chatId, entry.messageId, \"Approval cancelled.\", []).catch(() => {});\n\t}\n}\n\nexport function resetApprovalRegistry(): void {\n\tfor (const entry of pending.values()) {\n\t\tclearTimeout(entry.timeout);\n\t\ttry {\n\t\t\tentry.reject(new Error(\"Approval registry reset\"));\n\t\t} catch {\n\t\t\t// ignore settled promise\n\t\t}\n\t}\n\tpending.clear();\n}\n\n/** Test hook: number of outstanding approval prompts. */\nexport function activeApprovalCount(): number {\n\treturn pending.size;\n}\n"]}
1
+ {"version":3,"file":"approval.js","sourceRoot":"","sources":["../../src/gateway/approval.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAGN,iBAAiB,EACjB,uBAAuB,EACvB,iBAAiB,GACjB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAGxC,MAAM,eAAe,GAAG,KAAK,CAAC;AAC9B,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,aAAa,GAAG,iCAAiC,CAAC;AACxD,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;AAuBzC,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAmB,CAAC;AACjE,MAAM,OAAO,GAAG,IAAI,GAAG,EAA2B,CAAC;AAEnD,SAAS,UAAU,GAAW;IAC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,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,EAAE,qBAAqB,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAC,CAAC,CAAC,CAAC;IAC3G,CAAC;AAAA,CACD;AAED,MAAM,UAAU,qBAAqB,GAAS;IAC7C,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;QACtC,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAC5B,IAAI,CAAC;YACJ,KAAK,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC,CAAC;QACpD,CAAC;QAAC,MAAM,CAAC;YACR,yBAAyB;QAC1B,CAAC;IACF,CAAC;IACD,OAAO,CAAC,KAAK,EAAE,CAAC;AAAA,CAChB;AAED,yDAAyD;AACzD,MAAM,UAAU,mBAAmB,GAAW;IAC7C,OAAO,OAAO,CAAC,IAAI,CAAC;AAAA,CACpB","sourcesContent":["/**\n * Gateway approvals for large subagent launches and plans.\n * A missing chat context rejects large launches; plans pass through.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n\ttype ApprovalRequest,\n\ttype ApprovalResponse,\n\tNO_HANDLER_REASON,\n\tregisterApprovalHandler,\n\tsetPermissionMode,\n} from \"../core/permissions.ts\";\nimport { isAuthorized, isGatewayOwner } from \"./authz.ts\";\nimport { loadGatewayConfig } from \"./config.ts\";\nimport { conversationBinding } from \"./conversations.ts\";\nimport { createPairingStore } from \"./pairing.ts\";\nimport { getSession } from \"./store.ts\";\nimport type { ButtonSpec, CallbackEvent, PlatformAdapter, SessionSource } from \"./types.ts\";\n\nconst CALLBACK_PREFIX = \"ap:\";\nconst ID_LENGTH = 8;\nconst CODE_ALPHABET = \"ABCDEFGHJKMNPQRSTUVWXYZ23456789\";\nconst DEFAULT_TIMEOUT_MS = 5 * 60 * 1000;\n\ninterface ApprovalContext {\n\tkey: string;\n\tadapter: PlatformAdapter;\n\tsource: SessionSource;\n\ttimeoutMs?: number;\n}\n\ninterface PendingApproval {\n\tkey?: string;\n\tsource: SessionSource;\n\tplan: boolean;\n\tresolve: (value: ApprovalResponse) => void;\n\treject: (reason?: unknown) => void;\n\ttimeout: ReturnType<typeof setTimeout>;\n\tmessageId?: string;\n\tadapter: PlatformAdapter;\n\tchatId: string;\n\tthreadId?: string;\n\tuserId: string;\n}\n\nconst approvalContext = new AsyncLocalStorage<ApprovalContext>();\nconst pending = new Map<string, PendingApproval>();\n\nfunction generateId(): string {\n\tlet id = \"\";\n\tconst bytes = randomBytes(ID_LENGTH);\n\tfor (let i = 0; i < ID_LENGTH; i++) {\n\t\tid += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];\n\t}\n\treturn id;\n}\n\nfunction makeCallbackData(id: string, action: ApprovalResponse | \"cancel\"): string {\n\treturn `${CALLBACK_PREFIX}${id}:${action}`;\n}\n\nfunction parseCallbackData(data: string): { id: string; action: ApprovalResponse | \"cancel\" } | null {\n\tif (!data.startsWith(CALLBACK_PREFIX)) return null;\n\tconst rest = data.slice(CALLBACK_PREFIX.length);\n\tconst colon = rest.indexOf(\":\");\n\tif (colon === -1) return null;\n\tconst id = rest.slice(0, colon);\n\tconst action = rest.slice(colon + 1);\n\tif (action === \"once\" || action === \"session\" || action === \"reject\" || action === \"cancel\") {\n\t\treturn { id, action };\n\t}\n\treturn null;\n}\n\n/** Run code with the gateway approval context available to tool-call gates. */\nexport function runWithApprovalContext<T>(ctx: ApprovalContext, fn: () => Promise<T>): Promise<T> {\n\treturn approvalContext.run(ctx, fn);\n}\n\nasync function createApprovalPrompt(\n\tadapter: PlatformAdapter,\n\tsource: SessionSource,\n\treq: ApprovalRequest,\n\ttimeoutMs = DEFAULT_TIMEOUT_MS,\n\tkey?: string,\n): Promise<ApprovalResponse> {\n\tconst id = generateId();\n\t// Large child launches get a dedicated title; inline buttons cannot capture feedback.\n\tconst title =\n\t\treq.kind === \"large-subagent-launch\"\n\t\t\t? `Approve large subagent launch?\\n${req.detail}`\n\t\t\t: `Approve ${req.toolName}?\\n${req.detail}`;\n\tconst rows: ButtonSpec[][] = [\n\t\t[\n\t\t\t{ label: \"✓ Approve once\", data: makeCallbackData(id, \"once\") },\n\t\t\t{ label: \"✓ Approve session\", data: makeCallbackData(id, \"session\") },\n\t\t],\n\t\t[{ label: \"✗ Reject\", data: makeCallbackData(id, \"reject\") }],\n\t];\n\n\treturn new Promise<ApprovalResponse>((resolve, reject) => {\n\t\tlet messageId: string | undefined;\n\t\tconst timeout = setTimeout(() => {\n\t\t\tpending.delete(id);\n\t\t\treject(new Error(\"Approval request timed out\"));\n\t\t\tif (messageId) {\n\t\t\t\tvoid adapter.editMessage(source.chatId, messageId, \"⏱ Approval expired.\", []).catch(() => {});\n\t\t\t}\n\t\t}, timeoutMs);\n\n\t\tconst entry: PendingApproval = {\n\t\t\tkey,\n\t\t\tsource,\n\t\t\tplan: req.kind === \"plan\",\n\t\t\tresolve,\n\t\t\treject,\n\t\t\ttimeout,\n\t\t\tadapter,\n\t\t\tchatId: source.chatId,\n\t\t\tthreadId: source.threadId,\n\t\t\tuserId: source.userId,\n\t\t};\n\t\tpending.set(id, entry);\n\t\tvoid (async () => {\n\t\t\ttry {\n\t\t\t\tconst result = await adapter.sendButtons(source.chatId, title, rows, { threadId: source.threadId });\n\t\t\t\tif (!result.success || !result.messageId) throw new Error(result.error ?? \"Failed to send approval prompt\");\n\t\t\t\tmessageId = result.messageId;\n\t\t\t\tif (pending.get(id) !== entry) {\n\t\t\t\t\tawait adapter\n\t\t\t\t\t\t.editMessage(source.chatId, messageId, \"Approval cancelled or expired.\", [])\n\t\t\t\t\t\t.catch(() => {});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tentry.messageId = messageId;\n\t\t\t} catch (err) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tpending.delete(id);\n\t\t\t\treject(err);\n\t\t\t}\n\t\t})();\n\t});\n}\n\n/** Approval handler passed to core permissions. */\nexport async function createGatewayApprovalRequest(req: ApprovalRequest): Promise<ApprovalResponse> {\n\tconst ctx = approvalContext.getStore();\n\tif (!ctx) {\n\t\tthrow new Error(NO_HANDLER_REASON);\n\t}\n\treturn createApprovalPrompt(ctx.adapter, ctx.source, req, ctx.timeoutMs, ctx.key);\n}\n\n/** Register the gateway approval handler with the core permission gate. */\nexport function registerGatewayApprovalHandler(): void {\n\tregisterApprovalHandler(createGatewayApprovalRequest);\n}\n\n/**\n * Dispatch a callback event to an outstanding approval prompt.\n * Returns true when the data matched the approval prefix (whether or not a\n * pending prompt existed).\n */\nexport async function handleApprovalCallback(event: CallbackEvent, adapter?: PlatformAdapter): Promise<boolean> {\n\tconst parsed = parseCallbackData(event.data);\n\tif (!parsed) return false;\n\n\tconst entry = pending.get(parsed.id);\n\tif (!entry) {\n\t\t// Best-effort answer for stale callbacks.\n\t\tawait adapter?.answerCallback(event.id, \"Approval expired.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tif (\n\t\tevent.userId !== entry.userId ||\n\t\tevent.chatId !== entry.chatId ||\n\t\tevent.threadId !== entry.threadId ||\n\t\t(adapter && adapter.platform !== entry.adapter.platform)\n\t) {\n\t\tawait entry.adapter.answerCallback(event.id, \"⛔ Not your approval.\").catch(() => {});\n\t\treturn true;\n\t}\n\n\tclearTimeout(entry.timeout);\n\tpending.delete(parsed.id);\n\n\tconst response: ApprovalResponse =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"reject\" : parsed.action;\n\tconst binding = entry.key ? conversationBinding(entry.key) : undefined;\n\tif (binding?.owner && (!isGatewayOwner(entry.source, loadGatewayConfig()) || binding.owner !== event.userId)) {\n\t\tentry.resolve(\"reject\");\n\t\tawait entry.adapter.answerCallback(event.id, \"Owner access was removed.\").catch(() => {});\n\t\treturn true;\n\t}\n\tif (binding && !isAuthorized(entry.source, loadGatewayConfig(), createPairingStore())) {\n\t\tentry.resolve(\"reject\");\n\t\treturn true;\n\t}\n\tif (entry.plan && response !== \"reject\" && entry.key) {\n\t\tconst sessionId = getSession(entry.key)?.sessionId;\n\t\tif (sessionId) setPermissionMode(\"yolo\", sessionId);\n\t}\n\tentry.resolve(response);\n\n\tconst label =\n\t\tparsed.action === \"reject\" || parsed.action === \"cancel\" ? \"Rejected.\" : `Approved (${parsed.action}).`;\n\tawait entry.adapter.editMessage(entry.chatId, entry.messageId ?? \"\", label, []).catch(() => {});\n\tawait entry.adapter.answerCallback(event.id).catch(() => {});\n\treturn true;\n}\n\n/** Test hook: clear all pending approvals and stop their timeouts. */\nexport function cancelGatewayApprovals(key: string): void {\n\tfor (const [id, entry] of pending) {\n\t\tif (entry.key !== key) continue;\n\t\tclearTimeout(entry.timeout);\n\t\tpending.delete(id);\n\t\tentry.resolve(\"reject\");\n\t\tif (entry.messageId)\n\t\t\tvoid entry.adapter.editMessage(entry.chatId, entry.messageId, \"Approval cancelled.\", []).catch(() => {});\n\t}\n}\n\nexport function resetApprovalRegistry(): void {\n\tfor (const entry of pending.values()) {\n\t\tclearTimeout(entry.timeout);\n\t\ttry {\n\t\t\tentry.reject(new Error(\"Approval registry reset\"));\n\t\t} catch {\n\t\t\t// ignore settled promise\n\t\t}\n\t}\n\tpending.clear();\n}\n\n/** Test hook: number of outstanding approval prompts. */\nexport function activeApprovalCount(): number {\n\treturn pending.size;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"mobile-commands.d.ts","sourceRoot":"","sources":["../../src/gateway/mobile-commands.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,aAAa,EAAqB,MAAM,aAAa,CAAC;AAGpE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEhE,eAAO,MAAM,eAAe;;;GAc3B,CAAC;AAEF,eAAO,MAAM,kBAAkB;;;GAQ9B,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAiBxE;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAazF;AAED,UAAU,aAAa;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,YAAY,CAAC;IACpB,OAAO,EAAE,eAAe,CAAC;IACzB,MAAM,EAAE,UAAU,CAAC;IACnB,GAAG,EAAE,aAAa,CAAC;CACnB;AA8ED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEtD;AA6JD,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAiJ7G","sourcesContent":["import { mkdirSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { getPermissionMode, PERMISSION_MODES, setPermissionMode } from \"../core/permissions.ts\";\nimport { SessionManager } from \"../core/session-manager.ts\";\nimport { getSubagentCancellation } from \"../core/subagent-cancellation.ts\";\nimport { isGatewayOwner, requireGatewayOwner } from \"./authz.ts\";\nimport { createPicker, type PickerItem, type PickerResolveResult } from \"./buttons.ts\";\nimport { type GatewayConfig, loadGatewayConfig } from \"./config.ts\";\nimport { bindConversation, conversationBinding } from \"./conversations.ts\";\nimport { gatewayInput, gatewaySelect } from \"./presenter.ts\";\nimport type { BridgeLike } from \"./router.ts\";\nimport type { MessageEvent, PlatformAdapter } from \"./types.ts\";\n\nexport const MOBILE_COMMANDS = [\n\t{ name: \"project\", description: \"Browse folders and choose a project\" },\n\t{ name: \"continue\", description: \"Continue a handoff or the latest TUI session\" },\n\t{ name: \"sessions\", description: \"Browse saved sessions across projects\" },\n\t{ name: \"mode\", description: \"Choose manual, yolo, plan, or auto permissions\" },\n\t{ name: \"plan\", description: \"Plan work and approve it from this chat\" },\n\t{ name: \"settings\", description: \"Change this session's model, thinking, or permissions\" },\n\t{ name: \"stopall\", description: \"Stop this session and its background subagents\" },\n\t{ name: \"download\", description: \"Send a file from the current project\" },\n\t{ name: \"usage\", description: \"Show session tokens and subscription usage\" },\n\t{ name: \"processes\", description: \"List or stop this session's shell processes\" },\n\t{ name: \"refresh\", description: \"Refresh available models\" },\n\t{ name: \"skill\", description: \"Choose a skill and send it a task\" },\n\t{ name: \"fast\", description: \"Toggle OpenAI Codex fast mode\" },\n];\n\nexport const FORWARDED_COMMANDS = [\n\t{ name: \"goal\", description: \"Set or manage the session goal\" },\n\t{ name: \"cron\", description: \"Schedule prompts and manage scheduled jobs\" },\n\t{ name: \"run\", description: \"Launch a subagent task\" },\n\t{ name: \"chain\", description: \"Run a sequence of subagent tasks\" },\n\t{ name: \"parallel\", description: \"Run independent subagent tasks\" },\n\t{ name: \"mcp\", description: \"Show configured MCP servers\" },\n\t{ name: \"lsp\", description: \"Show language server status\" },\n];\n\nexport function resolveWithinRoots(path: string, roots: string[]): string {\n\tconst actual = realpathSync(resolve(path));\n\tif (\n\t\t!roots.some((root) => {\n\t\t\ttry {\n\t\t\t\tconst rel = relative(realpathSync(root), actual);\n\t\t\t\treturn (\n\t\t\t\t\trel === \"\" ||\n\t\t\t\t\t(!rel.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) && rel !== \"..\" && !isAbsolute(rel))\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t})\n\t)\n\t\tthrow new Error(\"That path is outside the approved folders.\");\n\treturn actual;\n}\n\nexport function createProjectFolder(parent: string, name: string, roots: string[]): string {\n\tif (\n\t\t!name ||\n\t\tname === \".\" ||\n\t\tname === \"..\" ||\n\t\t/[\\\\/\\x00-\\x1f<>:\"|?*]/.test(name) ||\n\t\t/[. ]$/.test(name) ||\n\t\t/^(con|prn|aux|nul|com\\d|lpt\\d)(\\.|$)/i.test(name)\n\t)\n\t\tthrow new Error(\"Use a simple folder name without slashes or reserved characters.\");\n\tconst actual = resolveWithinRoots(parent, roots);\n\tmkdirSync(join(actual, name));\n\treturn resolveWithinRoots(join(actual, name), roots);\n}\n\ninterface MobileContext {\n\tkey: string;\n\tevent: MessageEvent;\n\tadapter: PlatformAdapter;\n\tbridge: BridgeLike;\n\tcfg: GatewayConfig;\n}\n\nasync function browseProject(ctx: MobileContext, initialPath?: string): Promise<void> {\n\tconst { key, event, adapter, bridge } = ctx;\n\tconst roots = ctx.cfg.projectRoots ?? [];\n\tif (!roots.length) throw new Error(\"Add approved project folders with lunr gateway setup first.\");\n\tlet current: string | undefined = initialPath\n\t\t? resolveWithinRoots(initialPath, ctx.cfg.projectRoots ?? [])\n\t\t: undefined;\n\tconst view = (): { title: string; items: PickerItem[] } => {\n\t\tif (!current)\n\t\t\treturn {\n\t\t\t\ttitle: \"Choose a project folder\",\n\t\t\t\titems: [...new Set([...(conversationBinding(key)?.recentProjects ?? []), ...roots])]\n\t\t\t\t\t.filter((p) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tresolveWithinRoots(p, roots);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.map((p) => ({ label: p, value: p })),\n\t\t\t};\n\t\tcurrent = resolveWithinRoots(current, roots);\n\t\tconst items: PickerItem[] = [\n\t\t\t{ label: \"Use this folder\", value: \"use\" },\n\t\t\t{ label: \"New folder\", value: \"new\" },\n\t\t\t{ label: \"Recent and roots\", value: \"roots\" },\n\t\t];\n\t\ttry {\n\t\t\tconst up = resolveWithinRoots(dirname(current), roots);\n\t\t\tif (up !== current) items.push({ label: \"Up\", value: up });\n\t\t} catch {}\n\t\tfor (const item of readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n\t\t\tif (!item.isDirectory() && !item.isSymbolicLink()) continue;\n\t\t\ttry {\n\t\t\t\tconst path = resolveWithinRoots(join(current, item.name), roots);\n\t\t\t\tif (statSync(path).isDirectory()) items.push({ label: item.name, value: path });\n\t\t\t} catch {}\n\t\t}\n\t\treturn { title: current, items };\n\t};\n\tconst initial = view();\n\tawait createPicker(\n\t\tadapter,\n\t\tevent.source,\n\t\t{\n\t\t\tkind: \"project\",\n\t\t\tsessionKey: key,\n\t\t\tinvokerId: event.source.userId,\n\t\t\t...initial,\n\t\t\tvalidate: () => isGatewayOwner(event.source, loadGatewayConfig()),\n\t\t\tresolve: async (item): Promise<PickerResolveResult> => {\n\t\t\t\trequireGatewayOwner(event.source);\n\t\t\t\tif (item.value === \"use\" && current) {\n\t\t\t\t\tconst cwd = resolveWithinRoots(current, loadGatewayConfig().projectRoots ?? []);\n\t\t\t\t\tif (bridge.getStatus(key).busy)\n\t\t\t\t\t\tthrow new Error(\"Stop the current turn or wait before switching projects.\");\n\t\t\t\t\tawait bridge.reset(key);\n\t\t\t\t\tbindConversation(key, event.source, { cwd, owner: event.source.userId });\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\ttext: `Project selected: ${cwd}\\nSend a task to begin. Existing sessions are still available through /sessions.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (item.value === \"new\" && current) {\n\t\t\t\t\tconst name = await gatewayInput(key, \"New folder name\");\n\t\t\t\t\tif (name) current = createProjectFolder(current, name, loadGatewayConfig().projectRoots ?? []);\n\t\t\t\t} else current = item.value === \"roots\" ? undefined : item.value;\n\t\t\t\treturn { done: false, ...view() };\n\t\t\t},\n\t\t},\n\t\t{ threadId: event.source.threadId },\n\t);\n}\n\nconst transfers = new Map<string, AbortController>();\nexport function cancelMobileTransfer(key: string): void {\n\ttransfers.get(key)?.abort();\n}\n\nasync function continueSession(ctx: MobileContext, file: string): Promise<void> {\n\tif (transfers.has(ctx.key)) throw new Error(\"A session transfer is already pending. Use /stop to cancel it.\");\n\tconst controller = new AbortController();\n\ttransfers.set(ctx.key, controller);\n\ttry {\n\t\tawait performContinue(ctx, file, controller.signal);\n\t} finally {\n\t\ttransfers.delete(ctx.key);\n\t}\n}\n\nasync function performContinue(ctx: MobileContext, file: string, signal: AbortSignal): Promise<void> {\n\trequireGatewayOwner(ctx.event.source);\n\tconst { requestSessionTransfer, SessionTransferError } = await import(\"../core/session-handoff.ts\");\n\tconst { key, bridge } = ctx;\n\tconst current = await bridge.getSession(key);\n\tif (current?.sessionManager?.getSessionFile() === file) {\n\t\tawait ctx.adapter.send(ctx.event.source.chatId, \"This session is already open here.\");\n\t\treturn;\n\t}\n\tif (bridge.getStatus(key).busy) throw new Error(\"Stop the current phone session before switching.\");\n\ttry {\n\t\tawait requestSessionTransfer(file, { timeoutMs: 3000, signal });\n\t} catch (error) {\n\t\tif (!(error instanceof SessionTransferError) || error.code !== \"busy\") throw error;\n\t\tconst choice = await gatewaySelect(\n\t\t\tkey,\n\t\t\t`${error instanceof Error ? error.message : \"Session is in use\"}\\nHow should lunR continue?`,\n\t\t\t[\"Wait until idle\", \"Stop and continue\", \"Cancel\"],\n\t\t\t{ signal },\n\t\t);\n\t\tif (!choice || choice === \"Cancel\") return;\n\t\tif (choice === \"Stop and continue\") await requestSessionTransfer(file, { stop: true, timeoutMs: 30_000, signal });\n\t\telse {\n\t\t\tconst deadline = Date.now() + 120_000;\n\t\t\tfor (;;) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\trequireGatewayOwner(ctx.event.source);\n\t\t\t\ttry {\n\t\t\t\t\tawait requestSessionTransfer(file, { timeoutMs: 3000, signal });\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (retryError) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!(retryError instanceof SessionTransferError) ||\n\t\t\t\t\t\tretryError.code !== \"busy\" ||\n\t\t\t\t\t\tDate.now() >= deadline\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow retryError;\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\t\t\t}\n\t\t}\n\t}\n\tsignal.throwIfAborted();\n\trequireGatewayOwner(ctx.event.source);\n\tawait bridge.switchSession(key, file);\n\tconst session = await bridge.getSession(key);\n\tconst cwd = session?.sessionManager?.getCwd();\n\tbindConversation(key, ctx.event.source, { cwd, owner: ctx.event.source.userId });\n\tconst id = session?.sessionManager?.getSessionId();\n\tif (id && [\"auto\", \"yolo\"].includes(getPermissionMode(id))) {\n\t\tconst requested = getPermissionMode(id);\n\t\tsetPermissionMode(\"manual\", id);\n\t\tsession?.sessionManager?.setPermissionMode?.(\"manual\");\n\t\tif (\n\t\t\t(await gatewaySelect(\n\t\t\t\tkey,\n\t\t\t\t`Continue with ${requested} permissions? Tools can change files and run commands without individual approval.`,\n\t\t\t\t[\"Keep manual\", `Use ${requested}`],\n\t\t\t)) === `Use ${requested}`\n\t\t) {\n\t\t\tsetPermissionMode(requested, id);\n\t\t\tsession?.sessionManager?.setPermissionMode?.(requested);\n\t\t}\n\t}\n\tawait ctx.adapter.send(\n\t\tctx.event.source.chatId,\n\t\t`Continuing ${session?.sessionManager?.getSessionName() ?? basename(file)}\\nProject: ${cwd}\\nSend your next instruction.`,\n\t\t{ threadId: ctx.event.source.threadId },\n\t);\n}\n\nasync function browseSessions(ctx: MobileContext, args: string, quick: boolean): Promise<void> {\n\tconst handoff = await import(\"../core/session-handoff.ts\");\n\tif (quick) {\n\t\tconst candidates = handoff.listHandoffCandidates();\n\t\tif (!candidates.length) {\n\t\t\tconst latest = handoff.latestTuiSession();\n\t\t\tif (!latest)\n\t\t\t\tthrow new Error(\"No recent TUI session found. Use /sessions or mark one in the terminal with /handoff.\");\n\t\t\tawait continueSession(ctx, latest.sessionFile);\n\t\t\treturn;\n\t\t}\n\t\tif (candidates.length === 1) {\n\t\t\tawait continueSession(ctx, candidates[0].sessionFile);\n\t\t\treturn;\n\t\t}\n\t\tawait sessionPicker(\n\t\t\tctx,\n\t\t\tcandidates.map((s) => ({ label: `${s.cwd} · ${basename(s.sessionFile)}`, value: s.sessionFile })),\n\t\t);\n\t\treturn;\n\t}\n\tconst sessions = await SessionManager.listAll();\n\tconst known = new Set(sessions.map((s) => s.path));\n\tfor (const file of handoff.listRegisteredSessionPaths()) {\n\t\tif (known.has(file)) continue;\n\t\ttry {\n\t\t\tconst manager = SessionManager.openReadOnly(file);\n\t\t\tconst header = manager.getHeader();\n\t\t\tif (header)\n\t\t\t\tsessions.push({\n\t\t\t\t\tid: header.id,\n\t\t\t\t\tpath: file,\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tname: manager.getSessionName(),\n\t\t\t\t\tcreated: new Date(header.timestamp),\n\t\t\t\t\tmodified: statSync(file).mtime,\n\t\t\t\t\tmessageCount: manager.getEntries().length,\n\t\t\t\t\tfirstMessage: \"\",\n\t\t\t\t\tallMessagesText: \"\",\n\t\t\t\t});\n\t\t} catch {}\n\t}\n\tconst query = args.toLowerCase();\n\tconst items = sessions\n\t\t.sort((a, b) => b.modified.getTime() - a.modified.getTime())\n\t\t.filter((s) => !query || `${s.name ?? \"\"} ${s.cwd} ${s.id}`.toLowerCase().includes(query))\n\t\t.map((s) => ({\n\t\t\tlabel: `${s.name || s.firstMessage.slice(0, 35) || s.id.slice(0, 8)} · ${basename(s.cwd)} · ${s.modified.toLocaleDateString()}`,\n\t\t\tvalue: s.path,\n\t\t}));\n\tawait sessionPicker(ctx, items);\n}\n\nasync function sessionPicker(ctx: MobileContext, items: PickerItem[]): Promise<void> {\n\tawait createPicker(\n\t\tctx.adapter,\n\t\tctx.event.source,\n\t\t{\n\t\t\tkind: \"sessions\",\n\t\t\tsessionKey: ctx.key,\n\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\ttitle: \"Choose a session. Use /sessions <search> to filter.\",\n\t\t\titems,\n\t\t\tvalidate: () => isGatewayOwner(ctx.event.source, loadGatewayConfig()),\n\t\t\tresolve: async (item) => {\n\t\t\t\tawait continueSession(ctx, item.value);\n\t\t\t\treturn { done: true, text: \"Session selection finished.\" };\n\t\t\t},\n\t\t},\n\t\t{ threadId: ctx.event.source.threadId },\n\t);\n}\n\nexport async function handleMobileCommand(ctx: MobileContext, command: string, args: string): Promise<boolean> {\n\tif (!MOBILE_COMMANDS.some((c) => c.name === command) && command !== \"resume\") return false;\n\trequireGatewayOwner(ctx.event.source, ctx.cfg);\n\tbindConversation(ctx.key, ctx.event.source, { owner: ctx.event.source.userId });\n\tif (command === \"project\") {\n\t\tawait browseProject(ctx, args.trim() || undefined);\n\t\treturn true;\n\t}\n\tif (command === \"sessions\" || command === \"resume\" || command === \"continue\") {\n\t\tawait browseSessions(ctx, args, command === \"continue\");\n\t\treturn true;\n\t}\n\tconst session = await ctx.bridge.getSession(ctx.key);\n\tif (!session) throw new Error(\"Select a project and send a task, or use /continue first.\");\n\tconst id = session.sessionManager?.getSessionId();\n\tif (command === \"usage\") {\n\t\tconst stats = session.getSessionStats();\n\t\tconst plans = await (await import(\"../core/usage-service.ts\")).getAllPlanUsageResults(\n\t\t\tsession.model?.provider,\n\t\t\tsession.modelRuntime,\n\t\t);\n\t\tawait ctx.adapter.send(\n\t\t\tctx.event.source.chatId,\n\t\t\t[\n\t\t\t\t`Tokens: ${stats.tokens.total} · cost: $${stats.cost.toFixed(4)}`,\n\t\t\t\t...plans.usages.flatMap((p) =>\n\t\t\t\t\tp.windows.map((w) => `${p.provider} ${w.label}: ${w.usedPercent.toFixed(1)}% used`),\n\t\t\t\t),\n\t\t\t\t...plans.errors,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t\treturn true;\n\t}\n\tif (command === \"processes\") {\n\t\tif (!id) throw new Error(\"No session identity.\");\n\t\tconst processes = await import(\"../core/process-registry.ts\");\n\t\tconst own = processes.list(id);\n\t\tif (args) {\n\t\t\tconst [action, raw] = args.split(/\\s+/);\n\t\t\tconst pid = Number(raw);\n\t\t\tif (action !== \"stop\" || !own.some((p) => p.pid === pid))\n\t\t\t\tthrow new Error(\"Usage: /processes stop <pid> from this session's process list.\");\n\t\t\tprocesses.kill(pid);\n\t\t\tawait ctx.adapter.send(ctx.event.source.chatId, `Stop requested for process ${pid}.`);\n\t\t} else\n\t\t\tawait ctx.adapter.send(\n\t\t\t\tctx.event.source.chatId,\n\t\t\t\town.length\n\t\t\t\t\t? own\n\t\t\t\t\t\t\t.map((p) => `${p.pid} · ${p.status} · ${p.command}`)\n\t\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t\t\t\t.slice(0, ctx.adapter.maxMessageLength)\n\t\t\t\t\t: \"No tracked processes.\",\n\t\t\t);\n\t\treturn true;\n\t}\n\tif (command === \"stopall\") {\n\t\tawait ctx.bridge.abort(ctx.key);\n\t\tconst result = id ? await getSubagentCancellation(id)?.stop() : undefined;\n\t\tconst processes = await import(\"../core/process-registry.ts\");\n\t\tconst count = id ? processes.list(id).filter((p) => p.status !== \"exited\").length : 0;\n\t\tif (id) processes.killAll(id);\n\t\tawait ctx.adapter.send(\n\t\t\tctx.event.source.chatId,\n\t\t\t`Stopped the current turn. Requested stop for ${result?.requested ?? 0} background runs and ${count} tracked processes${result?.failed ? `; ${result.failed} requests failed` : \"\"}. Wait for them to exit before transferring.`,\n\t\t);\n\t\treturn true;\n\t}\n\tif (ctx.bridge.getStatus(ctx.key).busy) throw new Error(\"Wait for the current turn or use /stop first.\");\n\tif (command === \"refresh\") {\n\t\tawait session.modelRuntime.refresh();\n\t\tawait ctx.adapter.send(ctx.event.source.chatId, \"Model catalog refreshed. Use /model to choose.\");\n\t\treturn true;\n\t}\n\tif (command === \"fast\") {\n\t\tif (session.model?.provider !== \"openai-codex\" || !session.settingsManager)\n\t\t\tthrow new Error(\"Fast mode is available only for OpenAI Codex subscriptions.\");\n\t\tconst current = session.settingsManager.getOpenAIFastMode();\n\t\tif (args && ![\"on\", \"off\", \"status\"].includes(args)) throw new Error(\"Usage: /fast on|off|status\");\n\t\tif (args !== \"status\") session.settingsManager.setOpenAIFastMode(args ? args === \"on\" : !current);\n\t\tawait ctx.adapter.send(\n\t\t\tctx.event.source.chatId,\n\t\t\t`Fast mode: ${session.settingsManager.getOpenAIFastMode() ? \"on\" : \"off\"}`,\n\t\t);\n\t\treturn true;\n\t}\n\tif (command === \"skill\") {\n\t\tconst names = session.resourceLoader?.getSkills().skills.map((s) => s.name) ?? [];\n\t\tconst [name, ...task] = args.split(/\\s+/).filter(Boolean);\n\t\tconst chosen = name || (await gatewaySelect(ctx.key, \"Choose a skill\", names));\n\t\tif (!chosen) return true;\n\t\tif (!names.includes(chosen)) throw new Error(\"That skill is not loaded for this project.\");\n\t\tctx.event.text = `/skill:${chosen} ${task.join(\" \") || (await gatewayInput(ctx.key, \"What should this skill do?\")) || \"\"}`;\n\t\treturn false;\n\t}\n\tif (command === \"download\") {\n\t\tif (!ctx.adapter.sendFile) throw new Error(\"This platform cannot send files.\");\n\t\tif (!args) throw new Error(\"Usage: /download <project-relative path>\");\n\t\tconst cwd = session.sessionManager?.getCwd();\n\t\tif (!cwd) throw new Error(\"No project selected.\");\n\t\tconst file = resolveWithinRoots(resolve(cwd, args), [cwd]);\n\t\tconst stat = statSync(file);\n\t\tif (!stat.isFile() || stat.size > 8 * 1024 * 1024) throw new Error(\"Choose a file no larger than 8 MB.\");\n\t\tif (\n\t\t\t/(^|[\\\\/])(?:\\.env(?:\\.[^\\\\/]*)?|auth\\.json|gateway\\.json|credentials[^\\\\/]*|id_rsa|id_ed25519)([\\\\/]|$)/i.test(\n\t\t\t\tfile,\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Credential files cannot be sent through chat.\");\n\t\tconst result = await ctx.adapter.sendFile(ctx.event.source.chatId, file, { threadId: ctx.event.source.threadId });\n\t\tif (!result.success) throw new Error(result.error ?? \"File delivery failed.\");\n\t\treturn true;\n\t}\n\tif (command === \"settings\") {\n\t\tconst choice = await gatewaySelect(ctx.key, \"Session settings\", [\"Model\", \"Thinking\", \"Permissions\"]);\n\t\tif (choice === \"Model\" || choice === \"Thinking\") {\n\t\t\tconst { CHAT_COMMANDS, runChatCommand } = await import(\"./commands.ts\");\n\t\t\tconst cmd = CHAT_COMMANDS.find((c) => c.name === choice.toLowerCase());\n\t\t\tif (cmd)\n\t\t\t\tawait runChatCommand(cmd, {\n\t\t\t\t\t...ctx,\n\t\t\t\t\targs: \"\",\n\t\t\t\t\treply: async (text) => {\n\t\t\t\t\t\tawait ctx.adapter.send(ctx.event.source.chatId, text);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\treturn true;\n\t\t}\n\t\tif (choice !== \"Permissions\") return true;\n\t}\n\tconst requested =\n\t\tcommand === \"plan\"\n\t\t\t? \"plan\"\n\t\t\t: args || (await gatewaySelect(ctx.key, `Permission mode: ${getPermissionMode(id)}`, [...PERMISSION_MODES]));\n\tif (!requested) return true;\n\tif (!PERMISSION_MODES.includes(requested as (typeof PERMISSION_MODES)[number]))\n\t\tthrow new Error(\"Choose manual, yolo, plan, or auto.\");\n\tsetPermissionMode(requested as (typeof PERMISSION_MODES)[number], id);\n\tsession.sessionManager?.setPermissionMode?.(requested as (typeof PERMISSION_MODES)[number]);\n\tawait ctx.adapter.send(ctx.event.source.chatId, `Permission mode: ${requested}`);\n\tif (command === \"plan\" && args) {\n\t\tctx.event.text = args;\n\t\treturn false;\n\t}\n\treturn true;\n}\n"]}
1
+ {"version":3,"file":"mobile-commands.d.ts","sourceRoot":"","sources":["../../src/gateway/mobile-commands.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,aAAa,EAAqB,MAAM,aAAa,CAAC;AAGpE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAEhE,eAAO,MAAM,eAAe;;;GAc3B,CAAC;AAEF,eAAO,MAAM,kBAAkB;;;GAQ9B,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAiBxE;AAED,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,MAAM,CAazF;AAED,UAAU,aAAa;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,YAAY,CAAC;IACpB,OAAO,EAAE,eAAe,CAAC;IACzB,MAAM,EAAE,UAAU,CAAC;IACnB,GAAG,EAAE,aAAa,CAAC;CACnB;AA8ED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAEtD;AA6JD,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAkJ7G","sourcesContent":["import { mkdirSync, readdirSync, realpathSync, statSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport { getPermissionMode, PERMISSION_MODES, setPermissionMode } from \"../core/permissions.ts\";\nimport { SessionManager } from \"../core/session-manager.ts\";\nimport { getSubagentCancellation } from \"../core/subagent-cancellation.ts\";\nimport { isGatewayOwner, requireGatewayOwner } from \"./authz.ts\";\nimport { createPicker, type PickerItem, type PickerResolveResult } from \"./buttons.ts\";\nimport { type GatewayConfig, loadGatewayConfig } from \"./config.ts\";\nimport { bindConversation, conversationBinding } from \"./conversations.ts\";\nimport { gatewayInput, gatewaySelect } from \"./presenter.ts\";\nimport type { BridgeLike } from \"./router.ts\";\nimport type { MessageEvent, PlatformAdapter } from \"./types.ts\";\n\nexport const MOBILE_COMMANDS = [\n\t{ name: \"project\", description: \"Browse folders and choose a project\" },\n\t{ name: \"continue\", description: \"Continue a handoff or the latest TUI session\" },\n\t{ name: \"sessions\", description: \"Browse saved sessions across projects\" },\n\t{ name: \"mode\", description: \"Choose yolo, auto, or read-only permissions\" },\n\t{ name: \"plan\", description: \"Plan work and approve it from this chat\" },\n\t{ name: \"settings\", description: \"Change this session's model, thinking, or permissions\" },\n\t{ name: \"stopall\", description: \"Stop this session and its background subagents\" },\n\t{ name: \"download\", description: \"Send a file from the current project\" },\n\t{ name: \"usage\", description: \"Show session tokens and subscription usage\" },\n\t{ name: \"processes\", description: \"List or stop this session's shell processes\" },\n\t{ name: \"refresh\", description: \"Refresh available models\" },\n\t{ name: \"skill\", description: \"Choose a skill and send it a task\" },\n\t{ name: \"fast\", description: \"Toggle OpenAI Codex fast mode\" },\n];\n\nexport const FORWARDED_COMMANDS = [\n\t{ name: \"goal\", description: \"Set or manage the session goal\" },\n\t{ name: \"cron\", description: \"Schedule prompts and manage scheduled jobs\" },\n\t{ name: \"run\", description: \"Launch a subagent task\" },\n\t{ name: \"chain\", description: \"Run a sequence of subagent tasks\" },\n\t{ name: \"parallel\", description: \"Run independent subagent tasks\" },\n\t{ name: \"mcp\", description: \"Show configured MCP servers\" },\n\t{ name: \"lsp\", description: \"Show language server status\" },\n];\n\nexport function resolveWithinRoots(path: string, roots: string[]): string {\n\tconst actual = realpathSync(resolve(path));\n\tif (\n\t\t!roots.some((root) => {\n\t\t\ttry {\n\t\t\t\tconst rel = relative(realpathSync(root), actual);\n\t\t\t\treturn (\n\t\t\t\t\trel === \"\" ||\n\t\t\t\t\t(!rel.startsWith(`..${process.platform === \"win32\" ? \"\\\\\" : \"/\"}`) && rel !== \"..\" && !isAbsolute(rel))\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t})\n\t)\n\t\tthrow new Error(\"That path is outside the approved folders.\");\n\treturn actual;\n}\n\nexport function createProjectFolder(parent: string, name: string, roots: string[]): string {\n\tif (\n\t\t!name ||\n\t\tname === \".\" ||\n\t\tname === \"..\" ||\n\t\t/[\\\\/\\x00-\\x1f<>:\"|?*]/.test(name) ||\n\t\t/[. ]$/.test(name) ||\n\t\t/^(con|prn|aux|nul|com\\d|lpt\\d)(\\.|$)/i.test(name)\n\t)\n\t\tthrow new Error(\"Use a simple folder name without slashes or reserved characters.\");\n\tconst actual = resolveWithinRoots(parent, roots);\n\tmkdirSync(join(actual, name));\n\treturn resolveWithinRoots(join(actual, name), roots);\n}\n\ninterface MobileContext {\n\tkey: string;\n\tevent: MessageEvent;\n\tadapter: PlatformAdapter;\n\tbridge: BridgeLike;\n\tcfg: GatewayConfig;\n}\n\nasync function browseProject(ctx: MobileContext, initialPath?: string): Promise<void> {\n\tconst { key, event, adapter, bridge } = ctx;\n\tconst roots = ctx.cfg.projectRoots ?? [];\n\tif (!roots.length) throw new Error(\"Add approved project folders with lunr gateway setup first.\");\n\tlet current: string | undefined = initialPath\n\t\t? resolveWithinRoots(initialPath, ctx.cfg.projectRoots ?? [])\n\t\t: undefined;\n\tconst view = (): { title: string; items: PickerItem[] } => {\n\t\tif (!current)\n\t\t\treturn {\n\t\t\t\ttitle: \"Choose a project folder\",\n\t\t\t\titems: [...new Set([...(conversationBinding(key)?.recentProjects ?? []), ...roots])]\n\t\t\t\t\t.filter((p) => {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tresolveWithinRoots(p, roots);\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t\t.map((p) => ({ label: p, value: p })),\n\t\t\t};\n\t\tcurrent = resolveWithinRoots(current, roots);\n\t\tconst items: PickerItem[] = [\n\t\t\t{ label: \"Use this folder\", value: \"use\" },\n\t\t\t{ label: \"New folder\", value: \"new\" },\n\t\t\t{ label: \"Recent and roots\", value: \"roots\" },\n\t\t];\n\t\ttry {\n\t\t\tconst up = resolveWithinRoots(dirname(current), roots);\n\t\t\tif (up !== current) items.push({ label: \"Up\", value: up });\n\t\t} catch {}\n\t\tfor (const item of readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n\t\t\tif (!item.isDirectory() && !item.isSymbolicLink()) continue;\n\t\t\ttry {\n\t\t\t\tconst path = resolveWithinRoots(join(current, item.name), roots);\n\t\t\t\tif (statSync(path).isDirectory()) items.push({ label: item.name, value: path });\n\t\t\t} catch {}\n\t\t}\n\t\treturn { title: current, items };\n\t};\n\tconst initial = view();\n\tawait createPicker(\n\t\tadapter,\n\t\tevent.source,\n\t\t{\n\t\t\tkind: \"project\",\n\t\t\tsessionKey: key,\n\t\t\tinvokerId: event.source.userId,\n\t\t\t...initial,\n\t\t\tvalidate: () => isGatewayOwner(event.source, loadGatewayConfig()),\n\t\t\tresolve: async (item): Promise<PickerResolveResult> => {\n\t\t\t\trequireGatewayOwner(event.source);\n\t\t\t\tif (item.value === \"use\" && current) {\n\t\t\t\t\tconst cwd = resolveWithinRoots(current, loadGatewayConfig().projectRoots ?? []);\n\t\t\t\t\tif (bridge.getStatus(key).busy)\n\t\t\t\t\t\tthrow new Error(\"Stop the current turn or wait before switching projects.\");\n\t\t\t\t\tawait bridge.reset(key);\n\t\t\t\t\tbindConversation(key, event.source, { cwd, owner: event.source.userId });\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\ttext: `Project selected: ${cwd}\\nSend a task to begin. Existing sessions are still available through /sessions.`,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tif (item.value === \"new\" && current) {\n\t\t\t\t\tconst name = await gatewayInput(key, \"New folder name\");\n\t\t\t\t\tif (name) current = createProjectFolder(current, name, loadGatewayConfig().projectRoots ?? []);\n\t\t\t\t} else current = item.value === \"roots\" ? undefined : item.value;\n\t\t\t\treturn { done: false, ...view() };\n\t\t\t},\n\t\t},\n\t\t{ threadId: event.source.threadId },\n\t);\n}\n\nconst transfers = new Map<string, AbortController>();\nexport function cancelMobileTransfer(key: string): void {\n\ttransfers.get(key)?.abort();\n}\n\nasync function continueSession(ctx: MobileContext, file: string): Promise<void> {\n\tif (transfers.has(ctx.key)) throw new Error(\"A session transfer is already pending. Use /stop to cancel it.\");\n\tconst controller = new AbortController();\n\ttransfers.set(ctx.key, controller);\n\ttry {\n\t\tawait performContinue(ctx, file, controller.signal);\n\t} finally {\n\t\ttransfers.delete(ctx.key);\n\t}\n}\n\nasync function performContinue(ctx: MobileContext, file: string, signal: AbortSignal): Promise<void> {\n\trequireGatewayOwner(ctx.event.source);\n\tconst { requestSessionTransfer, SessionTransferError } = await import(\"../core/session-handoff.ts\");\n\tconst { key, bridge } = ctx;\n\tconst current = await bridge.getSession(key);\n\tif (current?.sessionManager?.getSessionFile() === file) {\n\t\tawait ctx.adapter.send(ctx.event.source.chatId, \"This session is already open here.\");\n\t\treturn;\n\t}\n\tif (bridge.getStatus(key).busy) throw new Error(\"Stop the current phone session before switching.\");\n\ttry {\n\t\tawait requestSessionTransfer(file, { timeoutMs: 3000, signal });\n\t} catch (error) {\n\t\tif (!(error instanceof SessionTransferError) || error.code !== \"busy\") throw error;\n\t\tconst choice = await gatewaySelect(\n\t\t\tkey,\n\t\t\t`${error instanceof Error ? error.message : \"Session is in use\"}\\nHow should lunR continue?`,\n\t\t\t[\"Wait until idle\", \"Stop and continue\", \"Cancel\"],\n\t\t\t{ signal },\n\t\t);\n\t\tif (!choice || choice === \"Cancel\") return;\n\t\tif (choice === \"Stop and continue\") await requestSessionTransfer(file, { stop: true, timeoutMs: 30_000, signal });\n\t\telse {\n\t\t\tconst deadline = Date.now() + 120_000;\n\t\t\tfor (;;) {\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\trequireGatewayOwner(ctx.event.source);\n\t\t\t\ttry {\n\t\t\t\t\tawait requestSessionTransfer(file, { timeoutMs: 3000, signal });\n\t\t\t\t\tbreak;\n\t\t\t\t} catch (retryError) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t!(retryError instanceof SessionTransferError) ||\n\t\t\t\t\t\tretryError.code !== \"busy\" ||\n\t\t\t\t\t\tDate.now() >= deadline\n\t\t\t\t\t)\n\t\t\t\t\t\tthrow retryError;\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 500));\n\t\t\t}\n\t\t}\n\t}\n\tsignal.throwIfAborted();\n\trequireGatewayOwner(ctx.event.source);\n\tawait bridge.switchSession(key, file);\n\tconst session = await bridge.getSession(key);\n\tconst cwd = session?.sessionManager?.getCwd();\n\tbindConversation(key, ctx.event.source, { cwd, owner: ctx.event.source.userId });\n\tconst id = session?.sessionManager?.getSessionId();\n\tif (id && [\"auto\", \"yolo\"].includes(getPermissionMode(id))) {\n\t\tconst requested = getPermissionMode(id);\n\t\tsetPermissionMode(\"read-only\", id);\n\t\tsession?.sessionManager?.setPermissionMode?.(\"read-only\");\n\t\tif (\n\t\t\t(await gatewaySelect(\n\t\t\t\tkey,\n\t\t\t\t`Continue with ${requested} permissions? Tools can change files and run commands without individual approval.`,\n\t\t\t\t[\"Keep read-only\", `Use ${requested}`],\n\t\t\t)) === `Use ${requested}`\n\t\t) {\n\t\t\tsetPermissionMode(requested, id);\n\t\t\tsession?.sessionManager?.setPermissionMode?.(requested);\n\t\t}\n\t}\n\tawait ctx.adapter.send(\n\t\tctx.event.source.chatId,\n\t\t`Continuing ${session?.sessionManager?.getSessionName() ?? basename(file)}\\nProject: ${cwd}\\nSend your next instruction.`,\n\t\t{ threadId: ctx.event.source.threadId },\n\t);\n}\n\nasync function browseSessions(ctx: MobileContext, args: string, quick: boolean): Promise<void> {\n\tconst handoff = await import(\"../core/session-handoff.ts\");\n\tif (quick) {\n\t\tconst candidates = handoff.listHandoffCandidates();\n\t\tif (!candidates.length) {\n\t\t\tconst latest = handoff.latestTuiSession();\n\t\t\tif (!latest)\n\t\t\t\tthrow new Error(\"No recent TUI session found. Use /sessions or mark one in the terminal with /handoff.\");\n\t\t\tawait continueSession(ctx, latest.sessionFile);\n\t\t\treturn;\n\t\t}\n\t\tif (candidates.length === 1) {\n\t\t\tawait continueSession(ctx, candidates[0].sessionFile);\n\t\t\treturn;\n\t\t}\n\t\tawait sessionPicker(\n\t\t\tctx,\n\t\t\tcandidates.map((s) => ({ label: `${s.cwd} · ${basename(s.sessionFile)}`, value: s.sessionFile })),\n\t\t);\n\t\treturn;\n\t}\n\tconst sessions = await SessionManager.listAll();\n\tconst known = new Set(sessions.map((s) => s.path));\n\tfor (const file of handoff.listRegisteredSessionPaths()) {\n\t\tif (known.has(file)) continue;\n\t\ttry {\n\t\t\tconst manager = SessionManager.openReadOnly(file);\n\t\t\tconst header = manager.getHeader();\n\t\t\tif (header)\n\t\t\t\tsessions.push({\n\t\t\t\t\tid: header.id,\n\t\t\t\t\tpath: file,\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tname: manager.getSessionName(),\n\t\t\t\t\tcreated: new Date(header.timestamp),\n\t\t\t\t\tmodified: statSync(file).mtime,\n\t\t\t\t\tmessageCount: manager.getEntries().length,\n\t\t\t\t\tfirstMessage: \"\",\n\t\t\t\t\tallMessagesText: \"\",\n\t\t\t\t});\n\t\t} catch {}\n\t}\n\tconst query = args.toLowerCase();\n\tconst items = sessions\n\t\t.sort((a, b) => b.modified.getTime() - a.modified.getTime())\n\t\t.filter((s) => !query || `${s.name ?? \"\"} ${s.cwd} ${s.id}`.toLowerCase().includes(query))\n\t\t.map((s) => ({\n\t\t\tlabel: `${s.name || s.firstMessage.slice(0, 35) || s.id.slice(0, 8)} · ${basename(s.cwd)} · ${s.modified.toLocaleDateString()}`,\n\t\t\tvalue: s.path,\n\t\t}));\n\tawait sessionPicker(ctx, items);\n}\n\nasync function sessionPicker(ctx: MobileContext, items: PickerItem[]): Promise<void> {\n\tawait createPicker(\n\t\tctx.adapter,\n\t\tctx.event.source,\n\t\t{\n\t\t\tkind: \"sessions\",\n\t\t\tsessionKey: ctx.key,\n\t\t\tinvokerId: ctx.event.source.userId,\n\t\t\ttitle: \"Choose a session. Use /sessions <search> to filter.\",\n\t\t\titems,\n\t\t\tvalidate: () => isGatewayOwner(ctx.event.source, loadGatewayConfig()),\n\t\t\tresolve: async (item) => {\n\t\t\t\tawait continueSession(ctx, item.value);\n\t\t\t\treturn { done: true, text: \"Session selection finished.\" };\n\t\t\t},\n\t\t},\n\t\t{ threadId: ctx.event.source.threadId },\n\t);\n}\n\nexport async function handleMobileCommand(ctx: MobileContext, command: string, args: string): Promise<boolean> {\n\tif (!MOBILE_COMMANDS.some((c) => c.name === command) && command !== \"resume\") return false;\n\trequireGatewayOwner(ctx.event.source, ctx.cfg);\n\tbindConversation(ctx.key, ctx.event.source, { owner: ctx.event.source.userId });\n\tif (command === \"project\") {\n\t\tawait browseProject(ctx, args.trim() || undefined);\n\t\treturn true;\n\t}\n\tif (command === \"sessions\" || command === \"resume\" || command === \"continue\") {\n\t\tawait browseSessions(ctx, args, command === \"continue\");\n\t\treturn true;\n\t}\n\tconst session = await ctx.bridge.getSession(ctx.key);\n\tif (!session) throw new Error(\"Select a project and send a task, or use /continue first.\");\n\tconst id = session.sessionManager?.getSessionId();\n\tif (command === \"usage\") {\n\t\tconst stats = session.getSessionStats();\n\t\tconst plans = await (await import(\"../core/usage-service.ts\")).getAllPlanUsageResults(\n\t\t\tsession.model?.provider,\n\t\t\tsession.modelRuntime,\n\t\t);\n\t\tawait ctx.adapter.send(\n\t\t\tctx.event.source.chatId,\n\t\t\t[\n\t\t\t\t`Tokens: ${stats.tokens.total} · cost: $${stats.cost.toFixed(4)}`,\n\t\t\t\t...plans.usages.flatMap((p) =>\n\t\t\t\t\tp.windows.map((w) => `${p.provider} ${w.label}: ${w.usedPercent.toFixed(1)}% used`),\n\t\t\t\t),\n\t\t\t\t...plans.errors,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t\treturn true;\n\t}\n\tif (command === \"processes\") {\n\t\tif (!id) throw new Error(\"No session identity.\");\n\t\tconst processes = await import(\"../core/process-registry.ts\");\n\t\tconst own = processes.list(id);\n\t\tif (args) {\n\t\t\tconst [action, raw] = args.split(/\\s+/);\n\t\t\tconst pid = Number(raw);\n\t\t\tif (action !== \"stop\" || !own.some((p) => p.pid === pid))\n\t\t\t\tthrow new Error(\"Usage: /processes stop <pid> from this session's process list.\");\n\t\t\tprocesses.kill(pid);\n\t\t\tawait ctx.adapter.send(ctx.event.source.chatId, `Stop requested for process ${pid}.`);\n\t\t} else\n\t\t\tawait ctx.adapter.send(\n\t\t\t\tctx.event.source.chatId,\n\t\t\t\town.length\n\t\t\t\t\t? own\n\t\t\t\t\t\t\t.map((p) => `${p.pid} · ${p.status} · ${p.command}`)\n\t\t\t\t\t\t\t.join(\"\\n\")\n\t\t\t\t\t\t\t.slice(0, ctx.adapter.maxMessageLength)\n\t\t\t\t\t: \"No tracked processes.\",\n\t\t\t);\n\t\treturn true;\n\t}\n\tif (command === \"stopall\") {\n\t\tawait ctx.bridge.abort(ctx.key);\n\t\tconst result = id ? await getSubagentCancellation(id)?.stop() : undefined;\n\t\tconst processes = await import(\"../core/process-registry.ts\");\n\t\tconst count = id ? processes.list(id).filter((p) => p.status !== \"exited\").length : 0;\n\t\tif (id) processes.killAll(id);\n\t\tawait ctx.adapter.send(\n\t\t\tctx.event.source.chatId,\n\t\t\t`Stopped the current turn. Requested stop for ${result?.requested ?? 0} background runs and ${count} tracked processes${result?.failed ? `; ${result.failed} requests failed` : \"\"}. Wait for them to exit before transferring.`,\n\t\t);\n\t\treturn true;\n\t}\n\tif (ctx.bridge.getStatus(ctx.key).busy) throw new Error(\"Wait for the current turn or use /stop first.\");\n\tif (command === \"refresh\") {\n\t\tawait session.modelRuntime.refresh();\n\t\tawait ctx.adapter.send(ctx.event.source.chatId, \"Model catalog refreshed. Use /model to choose.\");\n\t\treturn true;\n\t}\n\tif (command === \"fast\") {\n\t\tif (session.model?.provider !== \"openai-codex\" || !session.settingsManager)\n\t\t\tthrow new Error(\"Fast mode is available only for OpenAI Codex subscriptions.\");\n\t\tconst current = session.settingsManager.getOpenAIFastMode();\n\t\tif (args && ![\"on\", \"off\", \"status\"].includes(args)) throw new Error(\"Usage: /fast on|off|status\");\n\t\tif (args !== \"status\") session.settingsManager.setOpenAIFastMode(args ? args === \"on\" : !current);\n\t\tawait ctx.adapter.send(\n\t\t\tctx.event.source.chatId,\n\t\t\t`Fast mode: ${session.settingsManager.getOpenAIFastMode() ? \"on\" : \"off\"}`,\n\t\t);\n\t\treturn true;\n\t}\n\tif (command === \"skill\") {\n\t\tconst names = session.resourceLoader?.getSkills().skills.map((s) => s.name) ?? [];\n\t\tconst [name, ...task] = args.split(/\\s+/).filter(Boolean);\n\t\tconst chosen = name || (await gatewaySelect(ctx.key, \"Choose a skill\", names));\n\t\tif (!chosen) return true;\n\t\tif (!names.includes(chosen)) throw new Error(\"That skill is not loaded for this project.\");\n\t\tctx.event.text = `/skill:${chosen} ${task.join(\" \") || (await gatewayInput(ctx.key, \"What should this skill do?\")) || \"\"}`;\n\t\treturn false;\n\t}\n\tif (command === \"download\") {\n\t\tif (!ctx.adapter.sendFile) throw new Error(\"This platform cannot send files.\");\n\t\tif (!args) throw new Error(\"Usage: /download <project-relative path>\");\n\t\tconst cwd = session.sessionManager?.getCwd();\n\t\tif (!cwd) throw new Error(\"No project selected.\");\n\t\tconst file = resolveWithinRoots(resolve(cwd, args), [cwd]);\n\t\tconst stat = statSync(file);\n\t\tif (!stat.isFile() || stat.size > 8 * 1024 * 1024) throw new Error(\"Choose a file no larger than 8 MB.\");\n\t\tif (\n\t\t\t/(^|[\\\\/])(?:\\.env(?:\\.[^\\\\/]*)?|auth\\.json|gateway\\.json|credentials[^\\\\/]*|id_rsa|id_ed25519)([\\\\/]|$)/i.test(\n\t\t\t\tfile,\n\t\t\t)\n\t\t)\n\t\t\tthrow new Error(\"Credential files cannot be sent through chat.\");\n\t\tconst result = await ctx.adapter.sendFile(ctx.event.source.chatId, file, { threadId: ctx.event.source.threadId });\n\t\tif (!result.success) throw new Error(result.error ?? \"File delivery failed.\");\n\t\treturn true;\n\t}\n\tif (command === \"settings\") {\n\t\tconst choice = await gatewaySelect(ctx.key, \"Session settings\", [\"Model\", \"Thinking\", \"Permissions\"]);\n\t\tif (choice === \"Model\" || choice === \"Thinking\") {\n\t\t\tconst { CHAT_COMMANDS, runChatCommand } = await import(\"./commands.ts\");\n\t\t\tconst cmd = CHAT_COMMANDS.find((c) => c.name === choice.toLowerCase());\n\t\t\tif (cmd)\n\t\t\t\tawait runChatCommand(cmd, {\n\t\t\t\t\t...ctx,\n\t\t\t\t\targs: \"\",\n\t\t\t\t\treply: async (text) => {\n\t\t\t\t\t\tawait ctx.adapter.send(ctx.event.source.chatId, text);\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\treturn true;\n\t\t}\n\t\tif (choice !== \"Permissions\") return true;\n\t}\n\tconst requested =\n\t\tcommand === \"plan\"\n\t\t\t? \"read-only\"\n\t\t\t: args || (await gatewaySelect(ctx.key, `Permission mode: ${getPermissionMode(id)}`, [...PERMISSION_MODES]));\n\tif (!requested) return true;\n\tconst mode = requested === \"read\" ? \"read-only\" : requested;\n\tif (!PERMISSION_MODES.includes(mode as (typeof PERMISSION_MODES)[number]))\n\t\tthrow new Error(\"Choose yolo, auto, or read-only.\");\n\tsetPermissionMode(mode as (typeof PERMISSION_MODES)[number], id);\n\tsession.sessionManager?.setPermissionMode?.(mode as (typeof PERMISSION_MODES)[number]);\n\tawait ctx.adapter.send(ctx.event.source.chatId, `Permission mode: ${mode}`);\n\tif (command === \"plan\" && args) {\n\t\tctx.event.text = `Create a plan for: ${args}`;\n\t\treturn false;\n\t}\n\treturn true;\n}\n"]}