@openclaw/discord 2026.11.3 → 2026.11.5-beta.2

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 (220) hide show
  1. package/dist/.setup/{account-inspect-8cCu6uPG.mjs → account-inspect-DGkdWwix.mjs} +1 -1
  2. package/dist/.setup/{accounts-ljrzXBJi.mjs → accounts-C_25wyxC.mjs} +9 -6
  3. package/dist/.setup/{active-turn-thread-route-C4tp9noA.mjs → active-turn-thread-route-KvRTAVE3.mjs} +1 -2
  4. package/dist/.setup/{allow-list-BKqOldGy.mjs → allow-list-BXrS8-R9.mjs} +4 -152
  5. package/dist/.setup/{api-DqmMUZau.mjs → api-BlBD4ism.mjs} +10 -20
  6. package/dist/.setup/{approval-handler.runtime-D0qu1um7.mjs → approval-handler.runtime-BGYjX1t9.mjs} +80 -61
  7. package/dist/.setup/{approval-message-updates-CdurC9Ej.mjs → approval-message-updates-DKsCfxSW.mjs} +2 -2
  8. package/dist/.setup/{audit-ChorIwio.mjs → audit-5b-FXj9R.mjs} +4 -4
  9. package/dist/.setup/{channel-ZilgdF5e.mjs → channel-CWwTHWFo.mjs} +134 -202
  10. package/dist/.setup/channel-access-9cyzozUP.mjs +24 -0
  11. package/dist/.setup/channel.setup-B3MtmBQG.mjs +238 -0
  12. package/dist/.setup/{components-Du9NhD8h.mjs → components-YCvQ6YLS.mjs} +209 -430
  13. package/dist/.setup/components.base-CiS0h_XP.mjs +32 -0
  14. package/dist/.setup/{config-schema-_uBILpQf.mjs → config-schema-BNKN1cu5.mjs} +6 -7
  15. package/dist/.setup/{conversation-binding-route-8Ul1KpGF.mjs → conversation-binding-route-kCTw8cij.mjs} +2 -2
  16. package/dist/.setup/{directory-config-3iVub-3m.mjs → directory-config-Ble81PWH.mjs} +1 -1
  17. package/dist/.setup/{directory-live-BDVl2DoC.mjs → directory-live-DH3tpS3x.mjs} +52 -57
  18. package/dist/.setup/{discord-BMD-JiVS.mjs → discord-DGVSguhx.mjs} +1124 -1710
  19. package/dist/.setup/{doctor-hQKbkNKq.mjs → doctor-eujgbnpZ.mjs} +3 -5
  20. package/dist/.setup/endpoint-runtime-lf4DeLas.mjs +139 -0
  21. package/dist/.setup/guilds-eDq22iSM.mjs +22 -0
  22. package/dist/.setup/{handle-action-B1lmt4ms.mjs → handle-action-CktwmzMz.mjs} +15 -15
  23. package/dist/.setup/{handle-action.guild-admin-B6g31cwt.mjs → handle-action.guild-admin-WLQ7fRqI.mjs} +5 -5
  24. package/dist/.setup/listeners-Df8lx3vK.mjs +47 -0
  25. package/dist/.setup/{live-policy-config-C_Q966Wh.mjs → live-policy-config-DiBVuaU6.mjs} +2 -3
  26. package/dist/.setup/{message-handler-CkI3yMjL.mjs → message-handler-hhNSioxo.mjs} +154 -115
  27. package/dist/.setup/{message-handler.preflight-CEfkFV9U.mjs → message-handler.preflight-BZcZE1o-.mjs} +30 -105
  28. package/dist/.setup/{message-handler.preflight-pluralkit-D5si80_L.mjs → message-handler.preflight-pluralkit-CYZfXXb6.mjs} +9 -22
  29. package/dist/.setup/{message-handler.process-DsMtetRf.mjs → message-handler.process-B0n-mQ99.mjs} +256 -373
  30. package/dist/.setup/outbound-payload-BaZmjewa.mjs +447 -0
  31. package/dist/.setup/{outbound-session-route-BtUpGBTb.mjs → outbound-session-route-Cgx4i9cS.mjs} +139 -86
  32. package/dist/.setup/{preflight-audio-wWgsZG5F.mjs → preflight-audio-C6QtD6HX.mjs} +1 -5
  33. package/dist/.setup/{presence-cache-DCeTsL73.mjs → presence-cache-Dq-3nH7R.mjs} +1 -6
  34. package/dist/.setup/{probe-CBaoCs-c.mjs → probe-DezB-6xz.mjs} +5 -9
  35. package/dist/.setup/{provider-CI_OLfvz.mjs → provider-BN2bCIUp.mjs} +3440 -4308
  36. package/dist/.setup/{provider-session.runtime-TWOo_JZx.mjs → provider-session.runtime-Dr_5X43t.mjs} +3 -3
  37. package/dist/.setup/provider.runtime-BuJpl0Pv.mjs +1 -0
  38. package/dist/.setup/proxy-fetch-BzXwBAXt.mjs +30 -0
  39. package/dist/.setup/{realtime-session.runtime-DvfS4vJj.mjs → realtime-session.runtime-BTDWsV4d.mjs} +44 -81
  40. package/dist/.setup/{receive-recovery-CKvaG2Hf.mjs → receive-recovery-C3Ks4wAQ.mjs} +13 -27
  41. package/dist/.setup/{resolve-allowlist-common-cIjtqh2F.mjs → resolve-allowlist-common-Bk8Fj6Ik.mjs} +3 -13
  42. package/dist/.setup/{resolve-channels-Cj5i7hzj.mjs → resolve-channels-Bp8frXvc.mjs} +7 -8
  43. package/dist/.setup/{resolve-users-BQLbysRB.mjs → resolve-users-Cvcj22sG.mjs} +4 -7
  44. package/dist/.setup/{runtime-RWnuJgWB.mjs → runtime-BJaCvlmq.mjs} +196 -239
  45. package/dist/.setup/{runtime-plifsKg9.mjs → runtime-BMgTyuwg.mjs} +6 -6
  46. package/dist/.setup/{secret-config-contract-z6FhbT8E.mjs → secret-config-contract-B1kE4sDv.mjs} +4 -9
  47. package/dist/.setup/{send-da6ENJ9f.mjs → send-CVW7V-VZ.mjs} +149 -175
  48. package/dist/.setup/{send.components-CWZUuGvA.mjs → send.components-C8YXdnO_.mjs} +59 -71
  49. package/dist/.setup/{send.outbound-qZ3iK3Vq.mjs → send.outbound-Uzcmh3Yd.mjs} +76 -129
  50. package/dist/.setup/{send.receipt-C18khRYH.mjs → send.receipt-NZDOTZBU.mjs} +30 -32
  51. package/dist/.setup/{send.shared-CnlMgoqQ.mjs → send.shared-a_6Oeyg1.mjs} +38 -115
  52. package/dist/.setup/{sender-identity-DgbJykq0.mjs → sender-identity-76HFb8eK.mjs} +3 -9
  53. package/dist/.setup/setup-plugin-api-BExhGEhL.mjs +2 -0
  54. package/dist/.setup/shared-interactive-DmzaoKOM.mjs +316 -0
  55. package/dist/.setup/{shared-CY5vJM48.mjs → shared-yDUSExm2.mjs} +8 -11
  56. package/dist/.setup/{subagent-hooks-CIu2TFz3.mjs → subagent-hooks-CDkdHQyy.mjs} +1 -1
  57. package/dist/.setup/{system-events-DCOLXkwS.mjs → system-events-yfWz150v.mjs} +2 -2
  58. package/dist/.setup/{target-resolver-CApivu3G.mjs → target-resolver-BOOzqxxM.mjs} +3 -3
  59. package/dist/.setup/{thread-bindings-DcvT_JgI.mjs → thread-bindings-zce4cpu_.mjs} +12 -20
  60. package/dist/.setup/{thread-bindings.manager-5Sh7yedN.mjs → thread-bindings.manager-NywKzUtc.mjs} +22 -42
  61. package/dist/.setup/{thread-bindings.session-updates-BMdJeJMc.mjs → thread-bindings.session-updates-D0j7oh8S.mjs} +11 -18
  62. package/dist/.setup/{threading-CzjFeUSe.mjs → threading-DodLYDt-.mjs} +68 -105
  63. package/dist/.setup/{timeouts-CuNARfyw.mjs → timeouts-cIxzatmv.mjs} +1 -1
  64. package/dist/.setup/{transcripts-source-8RDQrSVb.mjs → transcripts-source-ie9GBWaU.mjs} +110 -179
  65. package/dist/.setup/{voice-runtime-BsDILmAv.mjs → voice-runtime-B7V_LTdX.mjs} +231 -452
  66. package/dist/.source-module-urls/d6c089460280c5a04184542d6712e04545caeb1ebb290d3504377b4cc5e22fea.json +1 -0
  67. package/dist/account-inspect-api.js +1 -1
  68. package/dist/action-runtime-api.js +1 -2
  69. package/dist/activities-api.js +286 -341
  70. package/dist/api.js +16 -16
  71. package/dist/channel-config-api.js +1 -2
  72. package/dist/channel-plugin-api.js +1 -2
  73. package/dist/contract-api.js +1 -2
  74. package/dist/directory-contract-api.js +1 -1
  75. package/dist/runtime-api.js +22 -22
  76. package/dist/runtime-setter-api.js +1 -2
  77. package/dist/secret-contract-api.js +1 -2
  78. package/dist/security-audit-contract-api.js +1 -2
  79. package/dist/security-contract-api.js +1 -2
  80. package/dist/session-key-api.js +1 -2
  81. package/dist/setup-entry.js +1 -1
  82. package/dist/setup-plugin-api.js +1 -2
  83. package/dist/src/voice/audio-worker.runtime.js +56 -68
  84. package/dist/subagent-hooks-api.js +1 -1
  85. package/dist/thread-binding-api.js +1 -2
  86. package/dist/transcripts-source-api.js +1 -1
  87. package/node_modules/@napi-rs/wasm-runtime/dist/fs.js +3339 -4021
  88. package/node_modules/@napi-rs/wasm-runtime/package.json +1 -1
  89. package/node_modules/@types/lodash/README.md +1 -1
  90. package/node_modules/@types/lodash/common/function.d.ts +2 -2
  91. package/node_modules/@types/lodash/package.json +2 -2
  92. package/node_modules/@types/node/README.md +1 -1
  93. package/node_modules/@types/node/package.json +2 -2
  94. package/node_modules/@types/node/util.d.ts +6 -3
  95. package/node_modules/discord-api-types/package.json +4 -4
  96. package/node_modules/discord-api-types/rest/v10/index.d.ts +8 -0
  97. package/node_modules/discord-api-types/rest/v10/index.d.ts.map +1 -1
  98. package/node_modules/discord-api-types/rest/v10/index.js +8 -0
  99. package/node_modules/discord-api-types/rest/v10/index.js.map +1 -1
  100. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts +26 -2
  101. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts.map +1 -1
  102. package/node_modules/discord-api-types/rest/v9/index.d.ts +8 -0
  103. package/node_modules/discord-api-types/rest/v9/index.d.ts.map +1 -1
  104. package/node_modules/discord-api-types/rest/v9/index.js +8 -0
  105. package/node_modules/discord-api-types/rest/v9/index.js.map +1 -1
  106. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts +26 -2
  107. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts.map +1 -1
  108. package/node_modules/typebox/build/format/duration.d.mts +2 -2
  109. package/node_modules/typebox/build/format/duration.mjs +2 -2
  110. package/node_modules/typebox/build/format/idn_email.d.mts +1 -0
  111. package/node_modules/typebox/build/format/idn_email.mjs +1 -0
  112. package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -1
  113. package/node_modules/typebox/build/format/idn_hostname.mjs +1 -1
  114. package/node_modules/typebox/build/format/ipv4.d.mts +2 -2
  115. package/node_modules/typebox/build/format/ipv4.mjs +2 -2
  116. package/node_modules/typebox/build/format/ipv6.d.mts +1 -1
  117. package/node_modules/typebox/build/format/ipv6.mjs +1 -1
  118. package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
  119. package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
  120. package/node_modules/typebox/build/schema/build.mjs +1 -0
  121. package/node_modules/typebox/build/schema/engine/_unique.d.mts +4 -2
  122. package/node_modules/typebox/build/schema/engine/_unique.mjs +7 -3
  123. package/node_modules/typebox/build/schema/engine/additionalItems.mjs +3 -3
  124. package/node_modules/typebox/build/schema/engine/additionalProperties.d.mts +0 -3
  125. package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +15 -17
  126. package/node_modules/typebox/build/schema/engine/contains.mjs +3 -3
  127. package/node_modules/typebox/build/schema/engine/index.d.mts +1 -0
  128. package/node_modules/typebox/build/schema/engine/index.mjs +1 -0
  129. package/node_modules/typebox/build/schema/engine/items.mjs +7 -4
  130. package/node_modules/typebox/build/schema/engine/maxContains.mjs +2 -2
  131. package/node_modules/typebox/build/schema/engine/minContains.mjs +3 -3
  132. package/node_modules/typebox/build/schema/engine/oneOf.mjs +2 -2
  133. package/node_modules/typebox/build/schema/engine/patternProperties.mjs +2 -2
  134. package/node_modules/typebox/build/schema/engine/propertyNames.mjs +2 -2
  135. package/node_modules/typebox/build/schema/engine/unevaluatedItems.mjs +2 -2
  136. package/node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs +2 -2
  137. package/node_modules/typebox/build/system/hashing/hash.mjs +63 -34
  138. package/node_modules/typebox/build/system/locale/en_US.mjs +2 -1
  139. package/node_modules/typebox/build/system/memory/assign.d.mts +2 -8
  140. package/node_modules/typebox/build/system/memory/assign.mjs +13 -6
  141. package/node_modules/typebox/build/system/memory/clone.d.mts +4 -5
  142. package/node_modules/typebox/build/system/memory/clone.mjs +8 -96
  143. package/node_modules/typebox/build/system/memory/create.d.mts +1 -5
  144. package/node_modules/typebox/build/system/memory/create.mjs +18 -13
  145. package/node_modules/typebox/build/system/memory/deep.d.mts +2 -0
  146. package/node_modules/typebox/build/system/memory/deep.mjs +108 -0
  147. package/node_modules/typebox/build/system/memory/discard.d.mts +1 -1
  148. package/node_modules/typebox/build/system/memory/discard.mjs +9 -8
  149. package/node_modules/typebox/build/system/memory/finalize.d.mts +4 -0
  150. package/node_modules/typebox/build/system/memory/finalize.mjs +30 -0
  151. package/node_modules/typebox/build/system/memory/keys.d.mts +2 -0
  152. package/node_modules/typebox/build/system/memory/keys.mjs +8 -0
  153. package/node_modules/typebox/build/system/memory/update.d.mts +1 -4
  154. package/node_modules/typebox/build/system/memory/update.mjs +43 -16
  155. package/node_modules/typebox/build/type/engine/call/index.d.mts +1 -0
  156. package/node_modules/typebox/build/type/engine/call/index.mjs +1 -0
  157. package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +2 -24
  158. package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +2 -29
  159. package/node_modules/typebox/build/type/engine/evaluate/index.d.mts +1 -0
  160. package/node_modules/typebox/build/type/engine/evaluate/index.mjs +1 -0
  161. package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +5 -1
  162. package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +6 -1
  163. package/node_modules/typebox/build/type/engine/evaluate/property.d.mts +30 -0
  164. package/node_modules/typebox/build/type/engine/evaluate/property.mjs +29 -0
  165. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.d.mts +1 -3
  166. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -4
  167. package/node_modules/typebox/build/type/engine/object/from_intersect.d.mts +2 -2
  168. package/node_modules/typebox/build/type/engine/object/from_intersect.mjs +2 -2
  169. package/node_modules/typebox/build/type/engine/object/from_union.d.mts +2 -2
  170. package/node_modules/typebox/build/type/engine/object/from_union.mjs +2 -2
  171. package/node_modules/typebox/build/type/engine/optional/instantiate_add.d.mts +1 -3
  172. package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -4
  173. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.d.mts +1 -3
  174. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -4
  175. package/node_modules/typebox/build/type/engine/this/index.d.mts +1 -0
  176. package/node_modules/typebox/build/type/engine/this/index.mjs +1 -0
  177. package/node_modules/typebox/build/value/clone/clone.d.mts +4 -3
  178. package/node_modules/typebox/build/value/clone/clone.mjs +5 -7
  179. package/node_modules/typebox/build/value/repair/from_cyclic.d.mts +2 -0
  180. package/node_modules/typebox/build/value/repair/from_cyclic.mjs +6 -0
  181. package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +25 -14
  182. package/node_modules/typebox/package.json +1 -1
  183. package/node_modules/typebox/readme.md +1 -1
  184. package/node_modules/undici/docs/docs/api/Interceptors.md +15 -2
  185. package/node_modules/undici/lib/dispatcher/client-h2.js +78 -3
  186. package/node_modules/undici/lib/dispatcher/pool-base.js +20 -3
  187. package/node_modules/undici/package.json +3 -3
  188. package/node_modules/undici/types/api.d.ts +1 -1
  189. package/node_modules/undici/types/utility.d.ts +4 -4
  190. package/node_modules/uuid/package.json +17 -17
  191. package/node_modules/zod/package.json +1 -1
  192. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  193. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  194. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  195. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  196. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  197. package/node_modules/zod/src/v4/core/util.ts +13 -0
  198. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  199. package/node_modules/zod/v4/core/compile.cjs +8 -0
  200. package/node_modules/zod/v4/core/compile.js +8 -0
  201. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  202. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  203. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  204. package/node_modules/zod/v4/core/schemas.js +30 -0
  205. package/node_modules/zod/v4/core/util.cjs +15 -0
  206. package/node_modules/zod/v4/core/util.d.cts +2 -0
  207. package/node_modules/zod/v4/core/util.d.ts +2 -0
  208. package/node_modules/zod/v4/core/util.js +14 -0
  209. package/node_modules/zod/v4/core/versions.cjs +1 -1
  210. package/node_modules/zod/v4/core/versions.js +1 -1
  211. package/openclaw.plugin.json +1 -31
  212. package/package.json +8 -8
  213. package/dist/.setup/channel-access-DasWY_OV.mjs +0 -48
  214. package/dist/.setup/channel.setup-DaDQdctj.mjs +0 -249
  215. package/dist/.setup/outbound-adapter-DfAanoCO.mjs +0 -543
  216. package/dist/.setup/provider.runtime-DnionCyo.mjs +0 -2
  217. package/dist/.setup/setup-plugin-api-D1QuM187.mjs +0 -3
  218. package/dist/.setup/targets-UWWZ6gF7.mjs +0 -3
  219. package/node_modules/typebox/build/system/memory/freeze.d.mts +0 -4
  220. package/node_modules/typebox/build/system/memory/freeze.mjs +0 -6
@@ -1,12 +1,11 @@
1
- import { t as __exportAll } from "./rolldown-runtime-B4FMCO8f.mjs";
2
- import { f as writeVoiceWavFile, h as restoreDiscordAudioError, i as noteVoiceDecryptFailure, n as analyzeVoiceReceiveError, o as resetVoiceReceiveRecoveryState, t as DECRYPT_FAILURE_WINDOW_MS } from "./receive-recovery-CKvaG2Hf.mjs";
3
- import { S as formatDiscordUserTag, g as resolveDiscordOwnerAccess, o as normalizeDiscordSlug } from "./allow-list-BKqOldGy.mjs";
4
- import { B as isUnknownDiscordVoiceStateError, f as VoiceStateUpdateListener, t as discord_exports, yt as getGuildVoiceState } from "./discord-BMD-JiVS.mjs";
1
+ import { f as writeVoiceWavFile, h as restoreDiscordAudioError, i as noteVoiceDecryptFailure, n as analyzeVoiceReceiveError, o as resetVoiceReceiveRecoveryState, t as DECRYPT_FAILURE_WINDOW_MS } from "./receive-recovery-C3Ks4wAQ.mjs";
2
+ import { F as getGuildVoiceState, H as isUnknownDiscordVoiceStateError } from "./discord-DGVSguhx.mjs";
3
+ import { S as formatDiscordUserTag, g as resolveDiscordOwnerAccess, o as normalizeDiscordSlug } from "./allow-list-BXrS8-R9.mjs";
5
4
  import { t as parseDiscordTarget } from "./target-parsing-C-HyNxcE.mjs";
6
- import { s as formatMention } from "./send.outbound-qZ3iK3Vq.mjs";
5
+ import { s as formatMention } from "./send.outbound-Uzcmh3Yd.mjs";
7
6
  import { t as getDiscordRuntime } from "./runtime-DgnVQ7zW.mjs";
8
- import { C as buildDiscordGroupSystemPrompt, _ as isDiscordRealtimeVoiceMode, b as resolveDiscordVoiceMode, g as VOICE_RECONNECT_GRACE_MS, h as VOICE_CONNECT_READY_TIMEOUT_MS, m as MIN_SEGMENT_SECONDS, p as CAPTURE_FINALIZE_GRACE_MS, v as isVoiceChannel, x as resolveVoiceTimeoutMs, y as logVoiceVerbose } from "./provider-CI_OLfvz.mjs";
9
- import { a as authorizeDiscordVoiceIngress, c as resolveDiscordVoiceEnabled, o as resolveDiscordVoiceAccess, r as resolveDiscordTranscriptsCapture, s as resolveDiscordVoiceAccessTarget, t as bindDiscordCaptureReceipts } from "./transcripts-source-8RDQrSVb.mjs";
7
+ import { S as buildDiscordGroupSystemPrompt, _ as isDiscordRealtimeVoiceMode, b as resolveDiscordVoiceMode, m as MIN_SEGMENT_SECONDS, v as isVoiceChannel, y as logVoiceVerbose } from "./provider-BN2bCIUp.mjs";
8
+ import { a as resolveDiscordVoiceEnabled, c as resolveDiscordVoiceAccessTarget, o as authorizeDiscordVoiceIngress, r as resolveDiscordTranscriptsCapture, s as resolveDiscordVoiceAccess, t as bindDiscordCaptureReceipts } from "./transcripts-source-ie9GBWaU.mjs";
10
9
  import { PassThrough, Readable } from "node:stream";
11
10
  import { formatErrorMessage, readErrorName, toErrorObject, toStringifiedError } from "openclaw/plugin-sdk/error-runtime";
12
11
  import { createSubsystemLogger, logVerbose } from "openclaw/plugin-sdk/runtime-env";
@@ -15,49 +14,20 @@ import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runti
15
14
  import { unlinkIfExists } from "openclaw/plugin-sdk/media-runtime";
16
15
  import { expectDefined } from "openclaw/plugin-sdk/expect-runtime";
17
16
  import { stripInlineDirectiveTagsForDisplay } from "openclaw/plugin-sdk/text-chunking";
18
- import { randomUUID } from "node:crypto";
19
17
  import { formatErrorMessage as formatErrorMessage$1 } from "openclaw/plugin-sdk/ssrf-runtime";
18
+ import { randomUUID } from "node:crypto";
20
19
  import { escapeRegExp, truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
21
20
  import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
21
+ import { raceWithTimeout } from "openclaw/plugin-sdk/time-runtime";
22
+ import { enqueueKeyedTask } from "openclaw/plugin-sdk/keyed-async-queue";
22
23
  import { resolveAgentDir } from "openclaw/plugin-sdk/agent-scope-runtime";
23
24
  import { enqueueRoutedSystemEvent } from "openclaw/plugin-sdk/system-event-runtime";
24
25
  import { EventEmitter } from "node:events";
25
26
  import { controlRealtimeVoiceAgentRun, parseRealtimeVoiceAgentControlToolArgs, shouldAutoControlRealtimeVoiceAgentText } from "openclaw/plugin-sdk/realtime-voice";
26
27
  import { resolveRealtimeVoiceAgentContextInstructions } from "openclaw/plugin-sdk/realtime-bootstrap-context";
27
- import { createCpuTrackedWorker, resolveRuntimeWorkerArgv, resolveRuntimeWorkerUrl } from "openclaw/plugin-sdk/process-runtime";
28
- //#region extensions/discord/src/voice/log-preview.ts
29
- const DISCORD_VOICE_LOG_PREVIEW_CHARS = 500;
30
- function formatVoiceLogPreview(text) {
31
- const oneLine = text.replace(/\s+/g, " ").trim();
32
- if (oneLine.length <= DISCORD_VOICE_LOG_PREVIEW_CHARS) return oneLine;
33
- return `${truncateUtf16Safe(oneLine, DISCORD_VOICE_LOG_PREVIEW_CHARS)}...`;
34
- }
35
- const DISCORD_REALTIME_VERBOSE_OMITTED_EVENTS = /* @__PURE__ */ new Set([
36
- "conversation.output_audio.delta",
37
- "input_audio_buffer.append",
38
- "response.audio.delta",
39
- "response.output_audio.delta"
40
- ]);
41
- const DISCORD_REALTIME_INTERRUPTION_MESSAGES = /* @__PURE__ */ new Map([
42
- ["client:response.cancel", "interrupt requested"],
43
- ["client:conversation.item.truncate.skipped", "interrupt ignored"],
44
- ["client:conversation.item.truncate", "audio truncated"],
45
- ["server:response.cancelled", "interrupt confirmed"]
46
- ]);
47
- function formatRealtimeInfoLog(event) {
48
- const eventKey = `${event.direction}:${event.type}`;
49
- const message = eventKey === "server:error" && event.detail === "Cancellation failed: no active response found" ? "interrupt raced" : DISCORD_REALTIME_INTERRUPTION_MESSAGES.get(eventKey);
50
- if (message) return `discord voice: realtime model ${message} ${eventKey}${event.detail ? ` ${event.detail}` : ""}`;
51
- if (!event.type.startsWith("session.") || event.type.startsWith("session.output_audio") || event.type.endsWith(".delta") || event.type.endsWith(".append")) return;
52
- const detail = event.detail ? ` ${event.detail}` : "";
53
- return `discord voice: realtime lifecycle ${event.direction}:${event.type}${detail}`;
54
- }
55
- function shouldLogRealtimeVerboseEvent(event) {
56
- return !DISCORD_REALTIME_VERBOSE_OMITTED_EVENTS.has(event.type);
57
- }
58
- //#endregion
28
+ import { createCpuTrackedWorker, createPluginRuntimeProcessEntrypoint, resolveRuntimeWorkerArgv, resolveRuntimeWorkerUrl } from "openclaw/plugin-sdk/process-runtime";
59
29
  //#region extensions/discord/src/voice/agent-control.ts
60
- const logger$10 = createSubsystemLogger("discord/voice");
30
+ const logger$9 = createSubsystemLogger("discord/voice");
61
31
  async function controlDiscordVoiceAgentRun(params) {
62
32
  const context = params.resolveContext ? await params.resolveContext() : params.context;
63
33
  const assertCurrent = () => {
@@ -106,7 +76,7 @@ async function maybeControlDiscordVoiceAgentRun(params) {
106
76
  };
107
77
  }
108
78
  function logDiscordVoiceAgentControlResult(entry, result) {
109
- logger$10.info(`discord voice: realtime active-run control handled mode=${result.mode} ok=${result.ok} active=${result.active} reason=${result.reason ?? "none"} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId}`);
79
+ if (result.active && !result.ok) logger$9.warn(`discord voice: realtime active-run control failed mode=${result.mode} reason=${result.reason ?? "none"} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId}`);
110
80
  }
111
81
  async function handleDiscordVoiceAgentControlToolCall(params) {
112
82
  let result;
@@ -160,7 +130,6 @@ var DiscordRealtimeRecordingInput = class {
160
130
  batch: false
161
131
  };
162
132
  this.pending = 0;
163
- this.listeners = /* @__PURE__ */ new Set();
164
133
  this.unavailable = batchDisabled;
165
134
  }
166
135
  noteReceipt(receipt) {
@@ -173,7 +142,7 @@ var DiscordRealtimeRecordingInput = class {
173
142
  this.startedAt = receipt?.startedAt;
174
143
  }
175
144
  if (!receipt?.capture || receipt.capture !== this.capture) this.eligible = false;
176
- this.notify();
145
+ this.onChange?.();
177
146
  }
178
147
  observeBatch(result) {
179
148
  this.pending += 1;
@@ -184,33 +153,26 @@ var DiscordRealtimeRecordingInput = class {
184
153
  this.eligible = false;
185
154
  }).finally(() => {
186
155
  this.pending -= 1;
187
- this.notify();
156
+ this.onChange?.();
188
157
  });
189
158
  }
190
159
  exclude() {
191
160
  this.eligible = false;
192
- this.notify();
161
+ this.onChange?.();
193
162
  }
194
163
  seal(input) {
195
164
  this.sealed[input] = true;
196
- this.notify();
165
+ this.onChange?.();
197
166
  }
198
167
  get complete() {
199
168
  return this.sealed.audio && this.sealed.batch && this.pending === 0;
200
169
  }
201
- subscribe(listener) {
202
- this.listeners.add(listener);
203
- return () => this.listeners.delete(listener);
204
- }
205
- notify() {
206
- for (const listener of this.listeners) listener();
207
- }
208
170
  };
209
171
  /** Realtime text is usable only when the whole provider generation has one recording owner. */
210
172
  var DiscordRealtimeRecording = class {
211
173
  constructor(params) {
212
174
  this.params = params;
213
- this.inputs = /* @__PURE__ */ new Map();
175
+ this.inputs = /* @__PURE__ */ new Set();
214
176
  this.inputCount = 0;
215
177
  this.unavailable = false;
216
178
  this.stopped = false;
@@ -243,12 +205,13 @@ var DiscordRealtimeRecording = class {
243
205
  return;
244
206
  }
245
207
  this.unavailable ||= input.hasAudio && input.unavailable;
246
- this.inputs.get(input)?.();
208
+ input.onChange = void 0;
247
209
  this.inputs.delete(input);
248
210
  }
249
211
  this.publish();
250
212
  };
251
- this.inputs.set(input, input.subscribe(changed));
213
+ this.inputs.add(input);
214
+ input.onChange = changed;
252
215
  changed();
253
216
  }
254
217
  transcript(text) {
@@ -278,7 +241,7 @@ var DiscordRealtimeRecording = class {
278
241
  }
279
242
  close() {
280
243
  this.stopped = true;
281
- for (const unsubscribe of this.inputs.values()) unsubscribe();
244
+ for (const input of this.inputs) input.onChange = void 0;
282
245
  this.inputs.clear();
283
246
  this.bytes -= this.finals.reduce((total, final) => total + final.bytes, 0);
284
247
  this.finals = [];
@@ -325,7 +288,7 @@ var DiscordRealtimeRecording = class {
325
288
  //#endregion
326
289
  //#region extensions/discord/src/voice/ingress.ts
327
290
  const DISCORD_VOICE_MESSAGE_PROVIDER = "discord-voice";
328
- const logger$9 = createSubsystemLogger("discord/voice");
291
+ const logger$8 = createSubsystemLogger("discord/voice");
329
292
  function summarizeAgentTurnPayloads(payloads) {
330
293
  const nonEmptyTextPayloads = payloads.filter((payload) => payload.text.trim()).length;
331
294
  const errorPayloads = payloads.filter((payload) => payload.isError === true).length;
@@ -336,10 +299,9 @@ async function resolveDiscordVoiceIngressContext(params) {
336
299
  const { entry, userId } = params;
337
300
  if (!entry.guildName) {
338
301
  const guild = await params.client.fetchGuild(entry.guildId).catch(() => null);
339
- entry.guildName = guild && typeof guild.name === "string" && guild.name.trim() ? guild.name : void 0;
302
+ entry.guildName = guild?.name.trim() ? guild.name : void 0;
340
303
  }
341
304
  const speaker = await params.speakerContext.resolveContext(entry.guildId, userId);
342
- const speakerIdentity = await params.speakerContext.resolveIdentity(entry.guildId, userId);
343
305
  const access = await authorizeDiscordVoiceIngress({
344
306
  readPolicy: params.readPolicy,
345
307
  cfg: params.cfg,
@@ -350,12 +312,12 @@ async function resolveDiscordVoiceIngressContext(params) {
350
312
  channelName: entry.channelName,
351
313
  channelSlug: entry.channelName ? normalizeDiscordSlug(entry.channelName) : "",
352
314
  channelLabel: formatMention({ channelId: entry.channelId }),
353
- memberRoleIds: speakerIdentity.memberRoleIds,
315
+ memberRoleIds: speaker.memberRoleIds,
354
316
  admissionAllowFrom: params.admissionAllowFrom,
355
317
  sender: {
356
- id: speakerIdentity.id,
357
- name: speakerIdentity.name,
358
- tag: speakerIdentity.tag
318
+ id: speaker.id,
319
+ name: speaker.name,
320
+ tag: speaker.tag
359
321
  }
360
322
  });
361
323
  if (!access.ok) return null;
@@ -402,7 +364,7 @@ async function runDiscordVoiceAgentTurn(params) {
402
364
  }
403
365
  const payloads = result.payloads ?? [];
404
366
  const text = payloads.map((payload) => payload.text).filter((entry) => entry?.trim()).join("\n").trim();
405
- if (!text) logger$9.info(`discord voice: agent turn produced no speakable payloads guild=${params.entry.guildId} channel=${params.entry.channelId} voiceSession=${params.entry.voiceSessionKey} supervisorSession=${params.entry.route.sessionKey} agent=${params.entry.route.agentId} user=${params.userId} ${summarizeAgentTurnPayloads(payloads)}`);
367
+ if (!text) logger$8.info(`discord voice: agent turn produced no speakable payloads guild=${params.entry.guildId} channel=${params.entry.channelId} voiceSession=${params.entry.voiceSessionKey} supervisorSession=${params.entry.route.sessionKey} agent=${params.entry.route.agentId} user=${params.userId} ${summarizeAgentTurnPayloads(payloads)}`);
406
368
  return text;
407
369
  }
408
370
  async function resolveDiscordVoiceRealtimeAgentContext(params) {
@@ -411,7 +373,7 @@ async function resolveDiscordVoiceRealtimeAgentContext(params) {
411
373
  agentId: params.entry.route.agentId,
412
374
  sessionKey: params.entry.route.sessionKey,
413
375
  files: params.discordConfig.voice?.realtime?.bootstrapContextFiles,
414
- warn: (message) => logger$9.warn(`discord voice: realtime agent context: ${message}`)
376
+ warn: (message) => logger$8.warn(`discord voice: realtime agent context: ${message}`)
415
377
  };
416
378
  return await resolveRealtimeVoiceAgentContextInstructions(contextParams);
417
379
  }
@@ -429,7 +391,7 @@ function memberLabel(state) {
429
391
  }
430
392
  function listDiscordVoiceParticipantStates(params) {
431
393
  const gateway = params.client.getPlugin("gateway");
432
- if (!gateway || typeof gateway.listVoiceChannelStates !== "function") return null;
394
+ if (!gateway) return null;
433
395
  return gateway.listVoiceChannelStates(params.guildId, params.channelId);
434
396
  }
435
397
  function createDiscordVoiceOccupancyWatcher(params, listener) {
@@ -456,14 +418,13 @@ function createDiscordVoiceOccupancyWatcher(params, listener) {
456
418
  }
457
419
  };
458
420
  }
459
- function retainParticipantId(selected, userId) {
460
- if (selected.includes(userId)) return;
461
- selected.push(userId);
462
- selected.sort((left, right) => left.localeCompare(right));
421
+ function retainParticipant(selected, participant) {
422
+ selected.push(participant);
423
+ selected.sort((left, right) => left.userId.localeCompare(right.userId));
463
424
  if (selected.length > MAX_PARTICIPANTS) selected.pop();
464
425
  }
465
426
  function collectDiscordVoiceParticipants(params) {
466
- const selectedUserIds = [];
427
+ const participants = [];
467
428
  const additionalUserIds = /* @__PURE__ */ new Set();
468
429
  const addAdditionalUserId = (rawUserId) => {
469
430
  const userId = rawUserId?.trim();
@@ -478,23 +439,17 @@ function collectDiscordVoiceParticipants(params) {
478
439
  if (!userId || userId === params.botUserId) continue;
479
440
  totalCount += 1;
480
441
  additionalUserIds.delete(userId);
481
- retainParticipantId(selectedUserIds, userId);
442
+ retainParticipant(participants, {
443
+ userId,
444
+ state
445
+ });
482
446
  }
483
447
  for (const additionalUserId of additionalUserIds) {
484
448
  totalCount += 1;
485
- retainParticipantId(selectedUserIds, additionalUserId);
486
- }
487
- const selected = new Set(selectedUserIds);
488
- const statesByUserId = /* @__PURE__ */ new Map();
489
- for (const state of params.states) {
490
- const userId = state.user_id?.trim();
491
- if (userId && selected.has(userId)) statesByUserId.set(userId, state);
449
+ retainParticipant(participants, { userId: additionalUserId });
492
450
  }
493
451
  return {
494
- participants: selectedUserIds.map((userId) => ({
495
- userId,
496
- state: statesByUserId.get(userId)
497
- })),
452
+ participants,
498
453
  totalCount
499
454
  };
500
455
  }
@@ -516,20 +471,20 @@ function countDiscordVoiceHumanParticipants(params) {
516
471
  return count;
517
472
  }
518
473
  function formatDiscordVoiceParticipantLine(userId, displayName) {
519
- const label = normalizeLabel(displayName) ?? userId;
474
+ const label = displayName ?? userId;
520
475
  return `- user_id=${JSON.stringify(userId)} display_name=${JSON.stringify(label)}`;
521
476
  }
522
477
  function formatDiscordVoiceParticipantStateLine(participant) {
523
478
  return formatDiscordVoiceParticipantLine(participant.userId, participant.state ? memberLabel(participant.state) : void 0);
524
479
  }
525
480
  function formatDiscordVoiceParticipantStateLines(roster) {
526
- const participants = roster.participants.slice(0, MAX_PARTICIPANTS);
481
+ const participants = roster.participants;
527
482
  const lines = participants.map(formatDiscordVoiceParticipantStateLine);
528
483
  if (roster.totalCount > participants.length) lines.push(`- ${roster.totalCount - participants.length} more participant(s)`);
529
484
  return lines;
530
485
  }
531
486
  async function resolveDiscordVoiceParticipantLines(params) {
532
- const participants = params.roster.participants.slice(0, MAX_PARTICIPANTS);
487
+ const participants = params.roster.participants;
533
488
  const lines = await Promise.all(participants.map(async ({ userId, state }) => {
534
489
  return formatDiscordVoiceParticipantLine(userId, (state ? memberLabel(state) : void 0) ?? normalizeLabel((await params.speakerContext.resolveContext(params.guildId, userId)).label) ?? userId);
535
490
  }));
@@ -565,7 +520,7 @@ async function resolveDiscordVoiceIngressContextWithParticipants(params) {
565
520
  }
566
521
  //#endregion
567
522
  //#region extensions/discord/src/voice/membership.ts
568
- const logger$8 = createSubsystemLogger("discord/voice");
523
+ const logger$7 = createSubsystemLogger("discord/voice");
569
524
  const MAX_INFERRED_PARTICIPANTS = 256;
570
525
  var DiscordVoiceMembershipTracker = class {
571
526
  constructor(client, speakerContext, accountId) {
@@ -594,7 +549,7 @@ var DiscordVoiceMembershipTracker = class {
594
549
  };
595
550
  this.states.set(entry, state);
596
551
  const initialLines = formatDiscordVoiceParticipantStateLines(roster);
597
- if (this.publish(entry, this.initialRosterEvent(entry, initialLines))) logger$8.info(`discord voice: participant roster event queued guild=${entry.guildId} channel=${entry.channelId} participants=${roster.totalCount} supervisorSession=${entry.route.sessionKey}`);
552
+ if (this.publish(entry, this.initialRosterEvent(entry, initialLines))) logger$7.info(`discord voice: participant roster event queued guild=${entry.guildId} channel=${entry.channelId} participants=${roster.totalCount} supervisorSession=${entry.route.sessionKey}`);
598
553
  const activationRevision = state.revision;
599
554
  (async () => {
600
555
  const lines = await resolveDiscordVoiceParticipantLines({
@@ -605,7 +560,7 @@ var DiscordVoiceMembershipTracker = class {
605
560
  if (lines.join("\n") === initialLines.join("\n")) return;
606
561
  if (!state.active || state.revision !== activationRevision || entry.sessionLifecycle.status === "stopped") return;
607
562
  if (!this.publish(entry, this.initialRosterEvent(entry, lines))) return;
608
- logger$8.info(`discord voice: enriched participant roster event queued guild=${entry.guildId} channel=${entry.channelId} participants=${roster.totalCount} supervisorSession=${entry.route.sessionKey}`);
563
+ logger$7.info(`discord voice: enriched participant roster event queued guild=${entry.guildId} channel=${entry.channelId} participants=${roster.totalCount} supervisorSession=${entry.route.sessionKey}`);
609
564
  })().catch((err) => {
610
565
  this.logFailure(entry, err);
611
566
  });
@@ -621,7 +576,7 @@ var DiscordVoiceMembershipTracker = class {
621
576
  `The agent left guild_id=${JSON.stringify(entry.guildId)} channel_id=${JSON.stringify(entry.channelId)}.`,
622
577
  "Any prior roster or membership updates for this voice session are no longer live. Do not respond to this event on its own."
623
578
  ].join("\n"))) return;
624
- logger$8.info(`discord voice: participant session-ended event queued guild=${entry.guildId} channel=${entry.channelId} supervisorSession=${entry.route.sessionKey}`);
579
+ logger$7.info(`discord voice: participant session-ended event queued guild=${entry.guildId} channel=${entry.channelId} supervisorSession=${entry.route.sessionKey}`);
625
580
  }
626
581
  countHumanParticipants(entry, botUserId) {
627
582
  const state = this.states.get(entry);
@@ -677,7 +632,7 @@ var DiscordVoiceMembershipTracker = class {
677
632
  "This roster snapshot supersedes prior voice membership context. Do not respond to this event on its own."
678
633
  ].join("\n"))) return;
679
634
  const event = action === "inferred-present" ? "inferred participant-present" : `participant ${action}`;
680
- logger$8.info(`discord voice: ${event} event queued guild=${entry.guildId} channel=${entry.channelId} user=${participant.userId} supervisorSession=${entry.route.sessionKey}`);
635
+ logger$7.info(`discord voice: ${event} event queued guild=${entry.guildId} channel=${entry.channelId} user=${participant.userId} supervisorSession=${entry.route.sessionKey}`);
681
636
  }
682
637
  publish(entry, text) {
683
638
  try {
@@ -691,7 +646,7 @@ var DiscordVoiceMembershipTracker = class {
691
646
  }
692
647
  }
693
648
  logFailure(entry, err) {
694
- logger$8.warn(`discord voice: participant notification failed guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(err)}`);
649
+ logger$7.warn(`discord voice: participant notification failed guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(err)}`);
695
650
  }
696
651
  initialRosterEvent(entry, lines) {
697
652
  return [
@@ -712,52 +667,36 @@ var DiscordVoiceMembershipTracker = class {
712
667
  };
713
668
  //#endregion
714
669
  //#region extensions/discord/src/voice/speaker-context.ts
715
- const SPEAKER_CONTEXT_CACHE_TTL_MS = 6e4;
716
670
  var DiscordVoiceSpeakerContextResolver = class {
717
671
  constructor(params) {
718
672
  this.params = params;
719
- this.cache = /* @__PURE__ */ new Map();
720
673
  }
721
674
  async resolveContext(guildId, userId) {
722
- const key = `${guildId}:${userId}`;
723
- const cached = this.cache.get(key);
724
- if (cached) {
725
- if (cached.expiresAt > Date.now()) return { ...cached.context };
726
- this.cache.delete(key);
727
- }
728
675
  const identity = await this.resolveIdentity(guildId, userId);
729
- const context = {
730
- id: identity.id,
731
- label: identity.label,
732
- name: identity.name,
733
- tag: identity.tag,
676
+ return {
677
+ ...identity,
734
678
  senderIsOwner: resolveDiscordOwnerAccess({
735
679
  allowFrom: this.params.ownerAllowFrom,
736
680
  sender: identity,
737
681
  allowNameMatching: false
738
682
  }).ownerAllowed
739
683
  };
740
- this.cache.set(key, {
741
- context: { ...context },
742
- expiresAt: Date.now() + SPEAKER_CONTEXT_CACHE_TTL_MS
743
- });
744
- return context;
745
684
  }
746
685
  async resolveIdentity(guildId, userId) {
747
686
  try {
748
687
  const member = await this.params.client.fetchMember(guildId, userId);
749
- const username = member.user?.username ?? void 0;
688
+ const username = member.user?.username;
750
689
  return {
751
690
  id: userId,
752
691
  label: member.nickname ?? member.user?.globalName ?? username ?? userId,
753
692
  name: username,
754
693
  tag: member.user ? formatDiscordUserTag(member.user) : void 0,
755
- memberRoleIds: Array.isArray(member.roles) ? member.roles.map((role) => typeof role === "string" ? role : typeof role?.id === "string" ? role.id : "").filter(Boolean) : []
694
+ memberRoleIds: member.roles
756
695
  };
757
696
  } catch {
758
697
  try {
759
698
  const user = await this.params.client.fetchUser(userId);
760
- const username = user.username ?? void 0;
699
+ const username = user.username;
761
700
  return {
762
701
  id: userId,
763
702
  label: user.globalName ?? username ?? userId,
@@ -777,7 +716,7 @@ var DiscordVoiceSpeakerContextResolver = class {
777
716
  };
778
717
  //#endregion
779
718
  //#region extensions/discord/src/voice/voice-following.ts
780
- const logger$7 = createSubsystemLogger("discord/voice");
719
+ const logger$6 = createSubsystemLogger("discord/voice");
781
720
  const FOLLOW_USERS_RECONCILE_INTERVAL_MS = 1e4;
782
721
  const FOLLOW_USERS_RECONCILE_MAX_GUILDS_PER_RUN = 4;
783
722
  const FOLLOW_USERS_RECONCILE_MAX_REST_LOOKUPS_PER_RUN = 32;
@@ -795,13 +734,6 @@ function normalizeVoiceChannelResidencies(entries) {
795
734
  function normalizeDiscordUserIds(entries) {
796
735
  return new Set(Array.from(entries ?? [], (entry) => entry.trim().replace(/^discord:/, "").replace(/^user:/, "").trim()).filter(Boolean));
797
736
  }
798
- function logFollowUserReconcileVerbose(reason, message) {
799
- if (reason === "interval") {
800
- logger$7.trace(`discord voice: ${message}`);
801
- return;
802
- }
803
- logVoiceVerbose(message);
804
- }
805
737
  var DiscordVoiceFollowing = class {
806
738
  constructor(params) {
807
739
  this.params = params;
@@ -823,7 +755,7 @@ var DiscordVoiceFollowing = class {
823
755
  delayMs: FOLLOW_USERS_RECONCILE_INTERVAL_MS,
824
756
  everyMs: FOLLOW_USERS_RECONCILE_INTERVAL_MS,
825
757
  run: () => this.reconcileFollowedUsers("interval").catch((err) => {
826
- logger$7.warn(`discord voice: follow user reconciliation failed: ${formatErrorMessage$1(err)}`);
758
+ logger$6.warn(`discord voice: follow user reconciliation failed: ${formatErrorMessage$1(err)}`);
827
759
  })
828
760
  });
829
761
  await this.reconcileFollowedUsers("startup");
@@ -831,13 +763,13 @@ var DiscordVoiceFollowing = class {
831
763
  async handleBotVoiceStateUpdate(params) {
832
764
  const { guildId, channelId } = params;
833
765
  if (!channelId) return;
834
- const existing = this.params.getSession(guildId);
766
+ const existing = this.params.sessions.get(guildId);
835
767
  if (this.params.isAllowedVoiceChannel({
836
768
  guildId,
837
769
  channelId
838
770
  })) {
839
771
  if (existing && existing.channelId !== channelId) {
840
- logger$7.warn(`discord voice: bot moved to allowed channel guild=${guildId} from=${existing.channelId} to=${channelId}; rebuilding voice session`);
772
+ logger$6.warn(`discord voice: bot moved to allowed channel guild=${guildId} from=${existing.channelId} to=${channelId}; rebuilding voice session`);
841
773
  await this.params.join({
842
774
  guildId,
843
775
  channelId
@@ -845,12 +777,12 @@ var DiscordVoiceFollowing = class {
845
777
  }
846
778
  return;
847
779
  }
848
- logger$7.warn(`discord voice: bot moved to non-allowed channel guild=${guildId} channel=${channelId}; leaving`);
780
+ logger$6.warn(`discord voice: bot moved to non-allowed channel guild=${guildId} channel=${channelId}; leaving`);
849
781
  if (existing) await this.params.leave({ guildId });
850
782
  else await this.params.stopTransport(guildId);
851
783
  const target = this.resolveVoiceResidencyTarget(guildId);
852
784
  if (target) {
853
- logger$7.warn(`discord voice: rejoining allowed voice channel guild=${guildId} channel=${target.channelId}`);
785
+ logger$6.warn(`discord voice: rejoining allowed voice channel guild=${guildId} channel=${target.channelId}`);
854
786
  await this.params.join(target);
855
787
  }
856
788
  }
@@ -859,21 +791,31 @@ var DiscordVoiceFollowing = class {
859
791
  const { guildId, channelId, userId } = params;
860
792
  const followKey = `${guildId}:${userId}`;
861
793
  const previousFollowedChannelId = this.followedUserChannels.get(followKey)?.channelId;
862
- const existing = this.params.getSession(guildId);
794
+ const existing = this.params.sessions.get(guildId);
863
795
  const wasFollowedVoiceSession = this.followedUserChannels.has(followKey) || this.followedVoiceGuilds.has(guildId);
864
796
  if (!channelId || !this.params.isAllowedVoiceChannel({
865
797
  guildId,
866
798
  channelId
867
799
  })) {
868
800
  this.followedUserChannels.delete(followKey);
869
- if (channelId) logger$7.warn(`discord voice: followed user joined non-allowed channel guild=${guildId} user=${userId} channel=${channelId}; ignoring`);
870
- if (existing && wasFollowedVoiceSession && !this.hasFollowedUserInChannel(existing)) await this.handoffToAnotherFollowedUserOrLeave({
871
- guildId,
872
- userId,
873
- existing,
874
- reason: channelId ? "joined non-allowed channel" : "disconnected"
875
- });
876
- else if (!channelId && !existing && wasFollowedVoiceSession && this.params.hasVoiceLifecycle(guildId)) await this.params.leave({ guildId });
801
+ if (channelId) logger$6.warn(`discord voice: followed user joined non-allowed channel guild=${guildId} user=${userId} channel=${channelId}; ignoring`);
802
+ if (existing && wasFollowedVoiceSession && !this.hasFollowedUserInChannel(existing)) {
803
+ const reason = channelId ? "joined non-allowed channel" : "disconnected";
804
+ const target = this.resolveFollowedUserHandoffTarget(guildId, existing.channelId);
805
+ if (target) {
806
+ logger$6.info(`discord voice: followed user ${reason} guild=${guildId} user=${userId}; moving to remaining followed user channel=${target.channelId}`);
807
+ const result = await this.params.join(target, { preserveFollowState: true });
808
+ if (result.ok) this.followedVoiceGuilds.add(guildId);
809
+ else {
810
+ logger$6.warn(`discord voice: failed to hand off followed user session guild=${guildId} channel=${target.channelId}: ${result.message}`);
811
+ this.clearFollowedGuild(guildId);
812
+ await this.params.leave({ guildId });
813
+ }
814
+ return;
815
+ }
816
+ logger$6.info(`discord voice: followed user ${reason} guild=${guildId} user=${userId}; leaving channel=${existing.channelId}`);
817
+ await this.params.leave({ guildId });
818
+ } else if (!channelId && !existing && wasFollowedVoiceSession && this.params.hasVoiceLifecycle(guildId)) await this.params.leave({ guildId });
877
819
  return;
878
820
  }
879
821
  const followedChannel = {
@@ -885,24 +827,24 @@ var DiscordVoiceFollowing = class {
885
827
  this.followedVoiceGuilds.add(guildId);
886
828
  return;
887
829
  }
888
- const recoveryAttemptAt = this.params.getRecoveryAttempt(guildId);
830
+ const recoveryAttemptAt = this.params.daveRecoveryAttempts.get(guildId);
889
831
  if (!existing && previousFollowedChannelId === channelId && recoveryAttemptAt !== void 0) {
890
832
  if (Date.now() - recoveryAttemptAt < 3e4) {
891
- logger$7.warn(`discord voice: automatic follow suppressed during DAVE recovery cooldown guild=${guildId} channel=${channelId}; retry /vc join after the voice gateway recovers`);
833
+ logger$6.warn(`discord voice: automatic follow suppressed during DAVE recovery cooldown guild=${guildId} channel=${channelId}; retry /vc join after the voice gateway recovers`);
892
834
  return;
893
835
  }
894
- this.params.deleteRecoveryAttempt(guildId);
836
+ this.params.daveRecoveryAttempts.delete(guildId);
895
837
  }
896
- logger$7.info(`discord voice: following user guild=${guildId} user=${userId} channel=${channelId}`);
838
+ logger$6.info(`discord voice: following user guild=${guildId} user=${userId} channel=${channelId}`);
897
839
  const result = await this.params.join({
898
840
  guildId,
899
841
  channelId
900
842
  }, { preserveFollowState: true });
901
843
  if (this.followedUserChannels.get(followKey) !== followedChannel) return;
902
844
  if (!result.ok) {
903
- if (this.params.getSession(guildId)?.channelId === channelId) this.followedVoiceGuilds.add(guildId);
845
+ if (this.params.sessions.get(guildId)?.channelId === channelId) this.followedVoiceGuilds.add(guildId);
904
846
  else this.followedUserChannels.delete(followKey);
905
- logger$7.warn(`discord voice: failed to follow user guild=${guildId} user=${userId} channel=${channelId}: ${result.message}`);
847
+ logger$6.warn(`discord voice: failed to follow user guild=${guildId} user=${userId} channel=${channelId}: ${result.message}`);
906
848
  return;
907
849
  }
908
850
  this.followedVoiceGuilds.add(guildId);
@@ -925,7 +867,7 @@ var DiscordVoiceFollowing = class {
925
867
  for (const entries of [
926
868
  this.params.autoJoinChannels,
927
869
  this.params.allowedChannels ?? [],
928
- this.params.listSessions()
870
+ this.params.sessions.values()
929
871
  ]) for (const entry of entries) guildIds.add(entry.guildId);
930
872
  return Array.from(guildIds);
931
873
  }
@@ -944,9 +886,8 @@ var DiscordVoiceFollowing = class {
944
886
  logVoiceVerbose(`follow user reconcile skipped reason=${reason}: no Discord guild ids are configured`);
945
887
  return;
946
888
  }
947
- logFollowUserReconcileVerbose(reason, `follow user reconcile reason=${reason}: ${this.followUserIds.size} users across ${guildIds.length} guilds`);
948
889
  const userIds = [...this.followUserIds];
949
- const slotsPerGuild = userIds.length + (this.params.botUserId() ? 1 : 0);
890
+ const slotsPerGuild = userIds.length + (this.params.botUserId ? 1 : 0);
950
891
  const totalSlots = guildIds.length * slotsPerGuild;
951
892
  const start = this.reconcileCursor % totalSlots;
952
893
  const visitedGuilds = /* @__PURE__ */ new Set();
@@ -982,35 +923,19 @@ var DiscordVoiceFollowing = class {
982
923
  for (const entry of this.followedUserChannels.values()) if (entry.guildId === guildId && entry.channelId !== currentChannelId && this.params.isAllowedVoiceChannel(entry)) return entry;
983
924
  return null;
984
925
  }
985
- async handoffToAnotherFollowedUserOrLeave(params) {
986
- const target = this.resolveFollowedUserHandoffTarget(params.guildId, params.existing.channelId);
987
- if (target) {
988
- logger$7.info(`discord voice: followed user ${params.reason} guild=${params.guildId} user=${params.userId}; moving to remaining followed user channel=${target.channelId}`);
989
- const result = await this.params.join(target, { preserveFollowState: true });
990
- if (result.ok) this.followedVoiceGuilds.add(params.guildId);
991
- else {
992
- logger$7.warn(`discord voice: failed to hand off followed user session guild=${params.guildId} channel=${target.channelId}: ${result.message}`);
993
- this.clearFollowedGuild(params.guildId);
994
- await this.params.leave({ guildId: params.guildId });
995
- }
996
- return;
997
- }
998
- logger$7.info(`discord voice: followed user ${params.reason} guild=${params.guildId} user=${params.userId}; leaving channel=${params.existing.channelId}`);
999
- await this.params.leave({ guildId: params.guildId });
1000
- }
1001
926
  async disconnectStaleFollowedBotVoiceState(params) {
1002
927
  if (this.scheduler.signal.aborted) return;
1003
928
  const { guildId, reason } = params;
1004
929
  if (Array.from(this.followedUserChannels.values()).some((entry) => entry.guildId === guildId)) return;
1005
- const existing = this.params.getSession(guildId);
930
+ const existing = this.params.sessions.get(guildId);
1006
931
  if (existing) {
1007
932
  if (this.followedVoiceGuilds.has(guildId)) {
1008
- logger$7.info(`discord voice: follow reconcile leaving local session guild=${guildId} channel=${existing.channelId} reason=${reason}`);
933
+ logger$6.info(`discord voice: follow reconcile leaving local session guild=${guildId} channel=${existing.channelId} reason=${reason}`);
1009
934
  await this.params.leave({ guildId });
1010
935
  }
1011
936
  return;
1012
937
  }
1013
- const botUserId = this.params.botUserId();
938
+ const botUserId = this.params.botUserId;
1014
939
  if (!botUserId) return;
1015
940
  const botVoiceState = await this.readReconcileVoiceState(guildId, botUserId, reason, true);
1016
941
  if (this.scheduler.signal.aborted || botVoiceState === "transient-error") return;
@@ -1018,10 +943,10 @@ var DiscordVoiceFollowing = class {
1018
943
  if (!botChannelId) return;
1019
944
  const gateway = this.params.client.getPlugin("voice")?.getGateway(guildId);
1020
945
  if (!gateway) {
1021
- logger$7.warn(`discord voice: follow reconcile cannot disconnect stale bot voice state guild=${guildId} channel=${botChannelId}; gateway unavailable`);
946
+ logger$6.warn(`discord voice: follow reconcile cannot disconnect stale bot voice state guild=${guildId} channel=${botChannelId}; gateway unavailable`);
1022
947
  return;
1023
948
  }
1024
- logger$7.info(`discord voice: follow reconcile disconnecting stale bot voice state guild=${guildId} channel=${botChannelId} reason=${reason}`);
949
+ logger$6.info(`discord voice: follow reconcile disconnecting stale bot voice state guild=${guildId} channel=${botChannelId} reason=${reason}`);
1025
950
  gateway.updateVoiceState({
1026
951
  guild_id: guildId,
1027
952
  channel_id: null,
@@ -1040,10 +965,9 @@ var DiscordVoiceFollowing = class {
1040
965
  readReconcileVoiceState(guildId, userId, reason, isBot = false) {
1041
966
  return getGuildVoiceState(this.params.client.rest, guildId, userId).catch((err) => {
1042
967
  if (!isUnknownDiscordVoiceStateError(err)) {
1043
- logger$7.warn(isBot ? `discord voice: follow reconcile skipped transient bot voice state error guild=${guildId} reason=${reason}: ${formatErrorMessage$1(err)}` : `follow-user reconcile skipped (transient voice-state error) guild=${guildId} user=${userId} trigger=${reason}: ${formatErrorMessage$1(err)}`);
968
+ logger$6.warn(isBot ? `discord voice: follow reconcile skipped transient bot voice state error guild=${guildId} reason=${reason}: ${formatErrorMessage$1(err)}` : `follow-user reconcile skipped (transient voice-state error) guild=${guildId} user=${userId} trigger=${reason}: ${formatErrorMessage$1(err)}`);
1044
969
  return "transient-error";
1045
970
  }
1046
- logFollowUserReconcileVerbose(reason, isBot ? `follow user reconcile reason=${reason}: no bot voice state guild ${guildId}: ${formatErrorMessage$1(err)}` : `follow user reconcile reason=${reason}: no voice state guild ${guildId} user ${userId}: ${formatErrorMessage$1(err)}`);
1047
971
  });
1048
972
  }
1049
973
  };
@@ -1086,42 +1010,16 @@ function finishVoiceCapture(state, userId, capture) {
1086
1010
  function scheduleVoiceCaptureFinalize(params) {
1087
1011
  const { state, userId, delayMs } = params;
1088
1012
  const capture = state.get(userId);
1089
- if (!capture) return false;
1013
+ if (!capture) return;
1090
1014
  clearVoiceCaptureFinalizeTimer(capture);
1091
1015
  capture.finalizeTimer = setTimeout(() => {
1092
1016
  if (!finishVoiceCapture(state, userId, capture)) return;
1093
1017
  capture.stream?.destroy();
1094
1018
  }, delayMs);
1095
- return true;
1096
- }
1097
- //#endregion
1098
- //#region extensions/discord/src/voice/sanitize.ts
1099
- const SPEECH_EMOJI_RE = /(?:\p{Extended_Pictographic}(?:\uFE0F|\u200D|\p{Extended_Pictographic}|\p{Emoji_Modifier})*)+/gu;
1100
- function sanitizeVoiceReplyTextForSpeech(text, speakerLabel) {
1101
- let cleaned = stripInlineDirectiveTagsForDisplay(text).text.trim();
1102
- if (!cleaned) return "";
1103
- const label = speakerLabel?.trim();
1104
- if (label) {
1105
- const prefix = new RegExp(`^${escapeRegExp(label)}\\s*:\\s*`, "i");
1106
- cleaned = cleaned.replace(prefix, "").trim();
1107
- }
1108
- return cleaned.replace(SPEECH_EMOJI_RE, " ").replace(/\s+([?!.,:;])/g, "$1").replace(/[ \t]{2,}/g, " ").replace(/ *\n */g, "\n").trim();
1109
1019
  }
1110
1020
  //#endregion
1111
1021
  //#region extensions/discord/src/voice/tts.ts
1112
- async function transcribeVoiceAudio(params) {
1113
- const result = await getDiscordRuntime().mediaUnderstanding.transcribeAudioFile({
1114
- filePath: params.filePath,
1115
- cfg: params.cfg,
1116
- agentDir: resolveAgentDir(params.cfg, params.agentId),
1117
- mime: "audio/wav"
1118
- });
1119
- return {
1120
- text: normalizeOptionalString(result.text),
1121
- processing: result.decision?.attachmentProcessing?.[0],
1122
- unavailable: result.decision?.outcome === "skipped" && result.decision.attachmentDispositions?.[0]?.kind === "no-model" && result.decision.attachmentProcessing?.[0] === "omitted" && result.decision.attachments.length > 0 && result.decision.attachments.every((attachment) => attachment.attempts.length === 0)
1123
- };
1124
- }
1022
+ const SPEECH_EMOJI_RE = /(?:\p{Extended_Pictographic}(?:\uFE0F|\u200D|\p{Extended_Pictographic}|\p{Emoji_Modifier})*)+/gu;
1125
1023
  async function synthesizeVoiceReplyAudio(params) {
1126
1024
  const runtime = getDiscordRuntime();
1127
1025
  const prepared = await runtime.tts.prepareTtsRequest({
@@ -1130,7 +1028,15 @@ async function synthesizeVoiceReplyAudio(params) {
1130
1028
  text: params.replyText
1131
1029
  });
1132
1030
  const directive = prepared.directives;
1133
- const speakText = sanitizeVoiceReplyTextForSpeech(directive.overrides.ttsText ?? directive.cleanedText.trim(), params.speakerLabel);
1031
+ const rawSpeakText = directive.overrides.ttsText ?? directive.cleanedText.trim();
1032
+ let cleaned = stripInlineDirectiveTagsForDisplay(rawSpeakText).text.trim();
1033
+ if (!cleaned) return { status: "empty" };
1034
+ const label = params.speakerLabel?.trim();
1035
+ if (label) {
1036
+ const prefix = new RegExp(`^${escapeRegExp(label)}\\s*:\\s*`, "i");
1037
+ cleaned = cleaned.replace(prefix, "").trim();
1038
+ }
1039
+ const speakText = cleaned.replace(SPEECH_EMOJI_RE, " ").replace(/\s+([?!.,:;])/g, "$1").replace(/[ \t]{2,}/g, " ").replace(/ *\n */g, "\n").trim();
1134
1040
  if (!speakText) return { status: "empty" };
1135
1041
  const request = {
1136
1042
  text: speakText,
@@ -1138,18 +1044,17 @@ async function synthesizeVoiceReplyAudio(params) {
1138
1044
  channel: "discord",
1139
1045
  overrides: directive.overrides
1140
1046
  };
1141
- const streamResult = await runtime.tts.textToSpeechStream?.({
1047
+ const streamResult = await runtime.tts.textToSpeechStream({
1142
1048
  ...request,
1143
1049
  disableFallback: true
1144
1050
  });
1145
- if (streamResult?.success && streamResult.audioStream) return {
1051
+ if (streamResult.success && streamResult.audioStream) return {
1146
1052
  status: "ok",
1147
1053
  mode: "stream",
1148
1054
  audioStream: streamResult.audioStream,
1149
- release: streamResult.release,
1150
- speakText
1055
+ release: streamResult.release
1151
1056
  };
1152
- const streamFailure = streamResult && !streamResult.success ? streamResult.attempts?.findLast((attempt) => attempt.outcome === "failed") : void 0;
1057
+ const streamFailure = !streamResult.success ? streamResult.attempts?.findLast((attempt) => attempt.outcome === "failed") : void 0;
1153
1058
  const result = await runtime.tts.textToSpeech(request);
1154
1059
  if (!result.success || !result.audioPath) return {
1155
1060
  status: "failed",
@@ -1159,7 +1064,6 @@ async function synthesizeVoiceReplyAudio(params) {
1159
1064
  status: "ok",
1160
1065
  mode: "file",
1161
1066
  audioPath: result.audioPath,
1162
- speakText,
1163
1067
  ...streamFailure ? { streamFailure: {
1164
1068
  provider: streamFailure.provider,
1165
1069
  reasonCode: streamFailure.reasonCode
@@ -1168,13 +1072,12 @@ async function synthesizeVoiceReplyAudio(params) {
1168
1072
  }
1169
1073
  //#endregion
1170
1074
  //#region extensions/discord/src/voice/segment.ts
1171
- const logger$6 = createSubsystemLogger("discord/voice");
1075
+ const logger$5 = createSubsystemLogger("discord/voice");
1172
1076
  async function processDiscordVoiceSegment(params) {
1173
- const { entry, wavPath, userId, durationSeconds } = params;
1077
+ const { entry, wavPath, userId } = params;
1174
1078
  const conversationCurrent = () => !entry.captureOnly && entry.sessionLifecycle.status === "active" && params.isConversationCurrent();
1175
- logVoiceVerbose(`segment processing (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId}`);
1176
1079
  const ingress = params.resolveIngressContext().catch((error) => {
1177
- logger$6.warn(`discord voice: conversation authorization failed: ${formatErrorMessage(error)}`);
1080
+ logger$5.warn(`discord voice: conversation authorization failed: ${formatErrorMessage(error)}`);
1178
1081
  return null;
1179
1082
  });
1180
1083
  const conversationAuthorized = ingress.then((context) => Boolean(context) && conversationCurrent());
@@ -1194,12 +1097,17 @@ async function processDiscordVoiceSegment(params) {
1194
1097
  admitted = await ingress;
1195
1098
  }
1196
1099
  if (!recording?.capture.isCurrent() && (!admitted || !conversationCurrent())) return { status: "excluded" };
1197
- const { text: transcript, processing, unavailable } = await transcribeVoiceAudio({
1198
- cfg: params.cfg,
1199
- agentId: entry.route.agentId,
1200
- filePath: wavPath
1100
+ const cfg = params.cfg;
1101
+ const agentId = entry.route.agentId;
1102
+ const result = await getDiscordRuntime().mediaUnderstanding.transcribeAudioFile({
1103
+ filePath: wavPath,
1104
+ cfg,
1105
+ agentDir: resolveAgentDir(cfg, agentId),
1106
+ mime: "audio/wav"
1201
1107
  });
1202
- if (unavailable) {
1108
+ const transcript = normalizeOptionalString(result.text);
1109
+ const processing = result.decision?.attachmentProcessing?.[0];
1110
+ if (result.decision?.outcome === "skipped" && result.decision.attachmentDispositions?.[0]?.kind === "no-model" && result.decision.attachmentProcessing?.[0] === "omitted" && result.decision.attachments.length > 0 && result.decision.attachments.every((attachment) => attachment.attempts.length === 0)) {
1203
1111
  recording?.capture.onBatchUnavailable?.();
1204
1112
  return { status: "unavailable" };
1205
1113
  }
@@ -1211,8 +1119,6 @@ async function processDiscordVoiceSegment(params) {
1211
1119
  conversationAuthorized
1212
1120
  };
1213
1121
  }
1214
- logVoiceVerbose(`transcription ok (${transcript.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1215
- logVoiceVerbose(`transcript from ${speakerLabel} (${userId}) in guild ${entry.guildId} channel ${entry.channelId}: ${formatVoiceLogPreview(transcript)}`);
1216
1122
  if (recording?.capture.isCurrent()) await recording.capture.onUtterance({
1217
1123
  sessionId: recording.capture.sessionId,
1218
1124
  startedAt: new Date(recording.startedAt).toISOString(),
@@ -1248,16 +1154,14 @@ async function respondToDiscordVoiceTranscript(params) {
1248
1154
  text: transcript
1249
1155
  }).catch((error) => {
1250
1156
  if (readErrorName(error) === "AbortError") {
1251
- logger$6.warn(`discord voice: active-run control cancelled: ${formatErrorMessage(error)}`);
1157
+ logger$5.warn(`discord voice: active-run control cancelled: ${formatErrorMessage(error)}`);
1252
1158
  return null;
1253
1159
  }
1254
- logger$6.warn(`discord voice: active-run control failed; falling back to normal segment handling: ${formatErrorMessage(error)}`);
1160
+ logger$5.warn(`discord voice: active-run control failed; falling back to normal segment handling: ${formatErrorMessage(error)}`);
1255
1161
  });
1256
1162
  if (control === null || !conversationCurrent()) return;
1257
- if (control?.handled) {
1258
- logger$6.info(`discord voice: active-run control handled mode=${control.result.mode} ok=${control.result.ok} active=${control.result.active} reason=${control.result.reason ?? "none"} session=${entry.route.sessionKey}`);
1259
- replyText = control.speakText ?? "";
1260
- } else {
1163
+ if (control?.handled) replyText = control.speakText ?? "";
1164
+ else {
1261
1165
  const prompt = formatVoiceIngressPrompt(transcript, ingress.speakerLabel);
1262
1166
  const text = await runDiscordVoiceAgentTurn({
1263
1167
  ...params,
@@ -1275,7 +1179,6 @@ async function respondToDiscordVoiceTranscript(params) {
1275
1179
  logVoiceVerbose(`reply empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1276
1180
  return;
1277
1181
  }
1278
- logVoiceVerbose(`reply ok (${replyText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1279
1182
  const voiceReplyAudio = await synthesizeVoiceReplyAudio({
1280
1183
  cfg: params.cfg,
1281
1184
  override: params.discordConfig.voice?.tts,
@@ -1287,15 +1190,14 @@ async function respondToDiscordVoiceTranscript(params) {
1287
1190
  return;
1288
1191
  }
1289
1192
  if (voiceReplyAudio.status === "failed") {
1290
- logger$6.warn(`discord voice: TTS failed: ${voiceReplyAudio.error}`);
1193
+ logger$5.warn(`discord voice: TTS failed: ${voiceReplyAudio.error}`);
1291
1194
  return;
1292
1195
  }
1293
1196
  const streamFailure = voiceReplyAudio.mode === "file" ? voiceReplyAudio.streamFailure : void 0;
1294
1197
  if (streamFailure && !entry.ttsStreamFallbackWarned) {
1295
1198
  entry.ttsStreamFallbackWarned = true;
1296
- logger$6.warn(`discord voice: streaming TTS failed provider=${streamFailure.provider} reasonCode=${streamFailure.reasonCode}; using file fallback`);
1199
+ logger$5.warn(`discord voice: streaming TTS failed provider=${streamFailure.provider} reasonCode=${streamFailure.reasonCode}; using file fallback`);
1297
1200
  }
1298
- logVoiceVerbose(`tts ok (${voiceReplyAudio.speakText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1299
1201
  const releaseAudio = voiceReplyAudio.mode === "stream" ? voiceReplyAudio.release : () => unlinkIfExists(voiceReplyAudio.audioPath);
1300
1202
  if (entry.sessionLifecycle.status === "stopped") {
1301
1203
  await releaseAudio?.();
@@ -1305,9 +1207,7 @@ async function respondToDiscordVoiceTranscript(params) {
1305
1207
  try {
1306
1208
  if (entry.sessionLifecycle.status === "stopped") return;
1307
1209
  const input = voiceReplyAudio.mode === "stream" ? Readable.fromWeb(voiceReplyAudio.audioStream) : voiceReplyAudio.audioPath;
1308
- logVoiceVerbose(`playback start: guild ${entry.guildId} channel ${entry.channelId} ${voiceReplyAudio.mode}`);
1309
1210
  await entry.audio.play(input);
1310
- logVoiceVerbose("playback done: guild " + entry.guildId + " channel " + entry.channelId);
1311
1211
  } catch (error) {
1312
1212
  if (entry.sessionLifecycle.status !== "stopped") throw error;
1313
1213
  } finally {
@@ -1317,7 +1217,7 @@ async function respondToDiscordVoiceTranscript(params) {
1317
1217
  }
1318
1218
  //#endregion
1319
1219
  //#region extensions/discord/src/voice/voice-recording.ts
1320
- const logger$5 = createSubsystemLogger("discord/voice");
1220
+ const logger$4 = createSubsystemLogger("discord/voice");
1321
1221
  const PCM_BYTES_PER_MILLISECOND = 192;
1322
1222
  const MAX_PENDING_RECORDING_JOBS = 128;
1323
1223
  const MAX_PENDING_RECORDING_BYTES = 67108864;
@@ -1361,7 +1261,7 @@ var DiscordVoiceRecording = class {
1361
1261
  this.chunks = [];
1362
1262
  this.bytes = 0;
1363
1263
  this.overflow = /* @__PURE__ */ new Error("Discord voice audio exceeds the transcription limit; speak a shorter segment.");
1364
- logger$5.warn(`discord voice: ${this.overflow.message}`);
1264
+ logger$4.warn(`discord voice: ${this.overflow.message}`);
1365
1265
  throw this.overflow;
1366
1266
  }
1367
1267
  for (let offset = 0; offset < pcm.length;) {
@@ -1407,7 +1307,7 @@ var DiscordVoiceRecording = class {
1407
1307
  try {
1408
1308
  await wav.cleanup();
1409
1309
  } catch (error) {
1410
- logger$5.warn(`discord voice: recording cleanup failed: ${formatErrorMessage$1(error)}`);
1310
+ logger$4.warn(`discord voice: recording cleanup failed: ${formatErrorMessage$1(error)}`);
1411
1311
  } finally {
1412
1312
  releaseBudget();
1413
1313
  }
@@ -1425,14 +1325,13 @@ var DiscordVoiceRecording = class {
1425
1325
  return await processDiscordVoiceSegment({
1426
1326
  ...this.params,
1427
1327
  wavPath: wav.path,
1428
- durationSeconds: wav.durationSeconds,
1429
1328
  isConversationCurrent: this.params.canConverse,
1430
1329
  onConversationOnly: () => conversationOnly.resolve(),
1431
1330
  recording
1432
1331
  });
1433
1332
  } catch (error) {
1434
1333
  this.params.onExcluded();
1435
- logger$5.warn(`discord voice: recording failed: ${formatErrorMessage$1(error)}`);
1334
+ logger$4.warn(`discord voice: recording failed: ${formatErrorMessage$1(error)}`);
1436
1335
  return { status: "excluded" };
1437
1336
  } finally {
1438
1337
  await cleanup();
@@ -1444,9 +1343,7 @@ var DiscordVoiceRecording = class {
1444
1343
  };
1445
1344
  //#endregion
1446
1345
  //#region extensions/discord/src/voice/voice-receive.ts
1447
- const logger$4 = createSubsystemLogger("discord/voice");
1448
- const MAX_PENDING_OPUS_PACKETS = 1e3;
1449
- const MAX_PENDING_OPUS_BYTES = 1048576;
1346
+ const logger$3 = createSubsystemLogger("discord/voice");
1450
1347
  var DiscordVoiceReceive = class {
1451
1348
  constructor(params) {
1452
1349
  this.params = params;
@@ -1457,12 +1354,12 @@ var DiscordVoiceReceive = class {
1457
1354
  scheduleVoiceCaptureFinalize({
1458
1355
  state: entry.capture,
1459
1356
  userId,
1460
- delayMs: resolveVoiceTimeoutMs(this.params.discordConfig.voice?.captureSilenceGraceMs, CAPTURE_FINALIZE_GRACE_MS)
1357
+ delayMs: this.params.discordConfig.voice?.captureSilenceGraceMs ?? 2e3
1461
1358
  });
1462
1359
  }
1463
1360
  async handleSpeakingStart(entry, userId, origin = "native") {
1464
1361
  if (!userId || !this.params.isEntryCurrent(entry)) return;
1465
- if (userId === this.params.botUserId()) return;
1362
+ if (userId === this.params.botUserId) return;
1466
1363
  this.params.membership.notePresent(entry, userId);
1467
1364
  const activeCapture = entry.capture.get(userId);
1468
1365
  if (activeCapture) {
@@ -1503,7 +1400,7 @@ var DiscordVoiceReceive = class {
1503
1400
  }
1504
1401
  }
1505
1402
  captureCurrentSpeakers(entry) {
1506
- for (const userId of entry.audio.speakingUsers) this.handleSpeakingStart(entry, userId, "scan").catch((error) => logger$4.warn(`discord voice: capture failed: ${formatErrorMessage$1(error)}`));
1403
+ for (const userId of entry.audio.speakingUsers) this.handleSpeakingStart(entry, userId, "scan").catch((error) => logger$3.warn(`discord voice: capture failed: ${formatErrorMessage$1(error)}`));
1507
1404
  }
1508
1405
  responseContext(entry, userId) {
1509
1406
  return {
@@ -1511,7 +1408,7 @@ var DiscordVoiceReceive = class {
1511
1408
  entry,
1512
1409
  userId,
1513
1410
  enqueuePlayback: (playbackEntry, task) => {
1514
- playbackEntry.playbackQueue = playbackEntry.playbackQueue.then(task).catch((err) => logger$4.warn(`discord voice: playback failed: ${formatErrorMessage$1(err)}`));
1411
+ playbackEntry.playbackQueue = playbackEntry.playbackQueue.then(task).catch((err) => logger$3.warn(`discord voice: playback failed: ${formatErrorMessage$1(err)}`));
1515
1412
  }
1516
1413
  };
1517
1414
  }
@@ -1520,7 +1417,7 @@ var DiscordVoiceReceive = class {
1520
1417
  const protectedPlayback = () => entry.audio.playerStatus === "playing" && !realtime?.canReceiveDuringPlayback();
1521
1418
  entry.audio.enablePassthrough(`speaker ${userId} start`, 15);
1522
1419
  if (!entry.audioInputBudget.enabled && !realtime) {
1523
- logger$4.warn("discord voice: capture skipped: audio understanding is disabled; enable tools.media.audio.enabled to transcribe voice.");
1420
+ logger$3.warn("discord voice: capture skipped: audio understanding is disabled; enable tools.media.audio.enabled to transcribe voice.");
1524
1421
  return;
1525
1422
  }
1526
1423
  const captureReceipts = this.params.bindCaptureReceipts(entry);
@@ -1539,12 +1436,9 @@ var DiscordVoiceReceive = class {
1539
1436
  else stream.once("finalized", finalizeReservation);
1540
1437
  const input = new PassThrough({ objectMode: true });
1541
1438
  let failed = false;
1542
- let pendingPackets = 0;
1543
- let pendingBytes = 0;
1544
1439
  let resetReceiveRecovery = false;
1545
1440
  const acceptPacket = (frame) => {
1546
- const packetBytes = frame.packet.byteLength;
1547
- if (failed || !packetBytes || stream.destroyed) {
1441
+ if (failed || !frame.packet.byteLength || stream.destroyed) {
1548
1442
  stream.acknowledge(frame);
1549
1443
  return;
1550
1444
  }
@@ -1553,18 +1447,10 @@ var DiscordVoiceReceive = class {
1553
1447
  stream.acknowledge(frame);
1554
1448
  return;
1555
1449
  }
1556
- if (pendingPackets >= MAX_PENDING_OPUS_PACKETS || packetBytes > MAX_PENDING_OPUS_BYTES - pendingBytes) {
1557
- onError(/* @__PURE__ */ new Error("Discord voice receive backlog exceeded; try speaking again."));
1558
- input.destroy();
1559
- stream.destroy();
1560
- return;
1561
- }
1562
1450
  if (!resetReceiveRecovery && frame.pcm.byteLength > 0 && this.params.isEntryCurrent(entry)) {
1563
1451
  resetReceiveRecovery = true;
1564
1452
  this.resetDecryptFailureState(entry);
1565
1453
  }
1566
- pendingPackets += 1;
1567
- pendingBytes += packetBytes;
1568
1454
  const receipt = {
1569
1455
  capture,
1570
1456
  startedAt: frame.receivedAt,
@@ -1572,7 +1458,6 @@ var DiscordVoiceReceive = class {
1572
1458
  };
1573
1459
  input.write({
1574
1460
  pcm: Buffer.from(frame.pcm),
1575
- packetBytes,
1576
1461
  receipt,
1577
1462
  frame
1578
1463
  });
@@ -1603,7 +1488,7 @@ var DiscordVoiceReceive = class {
1603
1488
  isCurrent: () => this.params.isEntryCurrent(entry),
1604
1489
  canAdmit: () => !protectedPlayback(),
1605
1490
  createTurn: realtime ? (context) => realtime.beginSpeakerTurn(context, userId, realtimeRecording) : void 0,
1606
- warn: (message) => logger$4.warn(message)
1491
+ warn: (message) => logger$3.warn(message)
1607
1492
  }) : void 0;
1608
1493
  const recording = new DiscordVoiceRecording({
1609
1494
  entry,
@@ -1634,8 +1519,6 @@ var DiscordVoiceReceive = class {
1634
1519
  const frame = decoded;
1635
1520
  try {
1636
1521
  if (failed) continue;
1637
- pendingPackets -= 1;
1638
- pendingBytes -= frame.packetBytes;
1639
1522
  const { pcm, receipt } = frame;
1640
1523
  if (!receipt.capture && conversation && !conversation.ingress) {
1641
1524
  if (!await waitForVoiceCaptureAdmission({
@@ -1675,12 +1558,12 @@ var DiscordVoiceReceive = class {
1675
1558
  ingress: currentIngress,
1676
1559
  transcript
1677
1560
  });
1678
- }).catch((error) => logger$4.warn(`discord voice: processing failed: ${formatErrorMessage$1(error)}`));
1561
+ }).catch((error) => logger$3.warn(`discord voice: processing failed: ${formatErrorMessage$1(error)}`));
1679
1562
  }
1680
1563
  }
1681
1564
  } finally {
1682
1565
  realtimeRecording?.seal("batch");
1683
- if (conversationCompletion) conversationCompletion.catch((error) => logger$4.warn(`discord voice: conversation failed: ${formatErrorMessage$1(error)}`));
1566
+ if (conversationCompletion) conversationCompletion.catch((error) => logger$3.warn(`discord voice: conversation failed: ${formatErrorMessage$1(error)}`));
1684
1567
  else if (conversation) entry.conversations.release(conversation);
1685
1568
  captureReceipts.close();
1686
1569
  stream.off("data", acceptPacket);
@@ -1700,14 +1583,14 @@ var DiscordVoiceReceive = class {
1700
1583
  logVoiceVerbose(`receive decode skipped: ${analysis.message}`);
1701
1584
  return;
1702
1585
  }
1703
- logger$4.warn(`discord voice: receive error: ${analysis.message}`);
1586
+ logger$3.warn(`discord voice: receive error: ${analysis.message}`);
1704
1587
  if (err instanceof Error && "daveRecoveryFailed" in err && err.daveRecoveryFailed === true) {
1705
1588
  this.startDecryptRecovery(entry, true);
1706
1589
  return;
1707
1590
  }
1708
1591
  if (!analysis.countsAsDecryptFailure) return;
1709
1592
  const decryptFailure = noteVoiceDecryptFailure(entry.receiveRecovery);
1710
- if (decryptFailure.firstFailure) logger$4.warn("discord voice: DAVE decrypt failures detected; voice receive may be unstable (upstream: discordjs/discord.js#11419)");
1593
+ if (decryptFailure.firstFailure) logger$3.warn("discord voice: DAVE decrypt failures detected; voice receive may be unstable (upstream: discordjs/discord.js#11419)");
1711
1594
  if (!decryptFailure.shouldRecover) return;
1712
1595
  this.startDecryptRecovery(entry);
1713
1596
  }
@@ -1715,8 +1598,7 @@ var DiscordVoiceReceive = class {
1715
1598
  return await resolveDiscordVoiceIngressContextWithParticipants({
1716
1599
  ...this.params,
1717
1600
  entry,
1718
- userId,
1719
- botUserId: this.params.botUserId()
1601
+ userId
1720
1602
  });
1721
1603
  }
1722
1604
  async runDiscordRealtimeAgentTurn(params) {
@@ -1725,7 +1607,7 @@ var DiscordVoiceReceive = class {
1725
1607
  const currentContext = await this.resolveDiscordVoiceIngressContext(entry, userId);
1726
1608
  params.signal?.throwIfAborted();
1727
1609
  if (!this.params.isEntryCurrent(entry) || !params.isCurrent() || !currentContext || currentContext.isCurrent?.() === false || currentContext.senderIsOwner !== context.senderIsOwner) throw new DOMException("Discord voice speaker authorization changed before delegation", "AbortError");
1728
- logger$4.info(`discord voice: agent turn start guild=${entry.guildId} channel=${entry.channelId} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId} user=${userId} speaker=${context.speakerLabel} owner=${context.senderIsOwner} model=${this.params.discordConfig.voice?.model ?? "route-default"} message=${formatVoiceLogPreview(message)}`);
1610
+ logger$3.info(`discord voice: agent turn start guild=${entry.guildId} channel=${entry.channelId} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId} user=${userId} owner=${context.senderIsOwner} model=${this.params.discordConfig.voice?.model ?? "route-default"} chars=${message.length}`);
1729
1611
  const text = await runDiscordVoiceAgentTurn({
1730
1612
  ...this.params,
1731
1613
  ...params,
@@ -1735,27 +1617,27 @@ var DiscordVoiceReceive = class {
1735
1617
  logVoiceVerbose(`realtime agent unauthorized: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1736
1618
  return "";
1737
1619
  }
1738
- logger$4.info(`discord voice: agent turn answer (${text.length} chars) guild=${entry.guildId} channel=${entry.channelId} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId}: ${formatVoiceLogPreview(text)}`);
1620
+ logger$3.info(`discord voice: agent turn answer (${text.length} chars) guild=${entry.guildId} channel=${entry.channelId} voiceSession=${entry.voiceSessionKey} supervisorSession=${entry.route.sessionKey} agent=${entry.route.agentId}`);
1739
1621
  return text;
1740
1622
  }
1741
1623
  startDecryptRecovery(entry, force = false) {
1742
1624
  let recovery;
1743
1625
  if (force) {
1744
- if (this.params.getSession(entry.guildId) !== entry || entry.sessionLifecycle.status === "stopped" || entry.receiveRecovery.decryptRecoveryInFlight) return;
1626
+ if (this.params.sessions.get(entry.guildId) !== entry || entry.sessionLifecycle.status === "stopped" || entry.receiveRecovery.decryptRecoveryInFlight) return;
1745
1627
  const now = Date.now();
1746
1628
  for (const [guildId, attemptedAt] of this.daveRecoveryAttempts) if (now - attemptedAt >= 3e4) this.daveRecoveryAttempts.delete(guildId);
1747
1629
  resetVoiceReceiveRecoveryState(entry.receiveRecovery);
1748
1630
  entry.receiveRecovery.decryptRecoveryInFlight = true;
1749
1631
  if (this.daveRecoveryAttempts.has(entry.guildId)) {
1750
1632
  const windowSeconds = DECRYPT_FAILURE_WINDOW_MS / 1e3;
1751
- logger$4.warn(`discord voice: DAVE recovery failed again within ${windowSeconds} seconds; disconnecting guild=${entry.guildId} channel=${entry.channelId} to avoid a reconnect loop; retry /vc join after the voice gateway recovers`);
1633
+ logger$3.warn(`discord voice: DAVE recovery failed again within ${windowSeconds} seconds; disconnecting guild=${entry.guildId} channel=${entry.channelId} to avoid a reconnect loop; retry /vc join after the voice gateway recovers`);
1752
1634
  recovery = this.params.leave({ guildId: entry.guildId }, { preserveFollowState: this.params.isFollowOwnedGuild(entry.guildId) });
1753
1635
  } else {
1754
1636
  this.daveRecoveryAttempts.set(entry.guildId, now);
1755
1637
  recovery = this.recoverFromDecryptFailures(entry);
1756
1638
  }
1757
1639
  } else recovery = this.recoverFromDecryptFailures(entry);
1758
- recovery.catch((recoverErr) => logger$4.warn(`discord voice: decrypt recovery failed: ${formatErrorMessage$1(recoverErr)}`)).finally(() => {
1640
+ recovery.catch((recoverErr) => logger$3.warn(`discord voice: decrypt recovery failed: ${formatErrorMessage$1(recoverErr)}`)).finally(() => {
1759
1641
  entry.receiveRecovery.decryptRecoveryInFlight = false;
1760
1642
  });
1761
1643
  }
@@ -1764,13 +1646,13 @@ var DiscordVoiceReceive = class {
1764
1646
  if (this.params.isEntryCurrent(entry)) this.daveRecoveryAttempts.delete(entry.guildId);
1765
1647
  }
1766
1648
  async recoverFromDecryptFailures(entry) {
1767
- const active = this.params.getSession(entry.guildId);
1649
+ const active = this.params.sessions.get(entry.guildId);
1768
1650
  if (!active || active.audio !== entry.audio) return;
1769
1651
  const preserveFollowState = this.params.isFollowOwnedGuild(entry.guildId);
1770
- logger$4.warn(`discord voice: repeated decrypt failures; attempting rejoin for guild ${entry.guildId} channel ${entry.channelId}`);
1652
+ logger$3.warn(`discord voice: repeated decrypt failures; attempting rejoin for guild ${entry.guildId} channel ${entry.channelId}`);
1771
1653
  const leaveResult = await this.params.leave({ guildId: entry.guildId }, { preserveFollowState });
1772
1654
  if (!leaveResult.ok) {
1773
- logger$4.warn(`discord voice: decrypt recovery leave failed: ${leaveResult.message}`);
1655
+ logger$3.warn(`discord voice: decrypt recovery leave failed: ${leaveResult.message}`);
1774
1656
  return;
1775
1657
  }
1776
1658
  const result = await this.params.join({
@@ -1781,22 +1663,14 @@ var DiscordVoiceReceive = class {
1781
1663
  autoJoinWhenOccupied: entry.autoJoinWhenOccupied,
1782
1664
  captureOnly: entry.captureOnly
1783
1665
  });
1784
- if (!result.ok) logger$4.warn(`discord voice: rejoin after decrypt failures failed: ${result.message}`);
1666
+ if (!result.ok) logger$3.warn(`discord voice: rejoin after decrypt failures failed: ${result.message}`);
1785
1667
  }
1786
1668
  };
1787
1669
  //#endregion
1788
1670
  //#region extensions/discord/src/voice/audio-worker-thread.ts
1789
1671
  /** Source, core-bundled and standalone plugin workers use the same launch owner. */
1790
1672
  function createDiscordAudioWorkerThread(options) {
1791
- const url = resolveRuntimeWorkerUrl({
1792
- currentModuleUrl: import.meta.url,
1793
- sourceWorkerName: "audio-worker.runtime",
1794
- distWorkerPath: "extensions/discord/src/voice/audio-worker.runtime.js",
1795
- package: {
1796
- name: "@openclaw/discord",
1797
- distWorkerPath: "src/voice/audio-worker.runtime.js"
1798
- }
1799
- });
1673
+ const url = resolveRuntimeWorkerUrl(createPluginRuntimeProcessEntrypoint("discordAudio", import.meta.url));
1800
1674
  const workerOptions = {
1801
1675
  workerData: options,
1802
1676
  execArgv: resolveRuntimeWorkerArgv(url).slice(0, -1)
@@ -1805,7 +1679,7 @@ function createDiscordAudioWorkerThread(options) {
1805
1679
  }
1806
1680
  //#endregion
1807
1681
  //#region extensions/discord/src/voice/audio-transport.ts
1808
- const logger$3 = createSubsystemLogger("discord/voice");
1682
+ const logger$2 = createSubsystemLogger("discord/voice");
1809
1683
  const STOP_GRACE_MS = 2e3;
1810
1684
  /** A received frame owns cloned PCM; its credit remains held until the consumer settles. */
1811
1685
  var DiscordAudioCapture = class extends Readable {
@@ -1848,7 +1722,6 @@ var DiscordAudioTransport = class extends EventEmitter {
1848
1722
  super();
1849
1723
  this.speakingUsers = /* @__PURE__ */ new Set();
1850
1724
  this.playerStatus = "idle";
1851
- this.connectionStatus = "signalling";
1852
1725
  this.captures = /* @__PURE__ */ new Map();
1853
1726
  this.files = /* @__PURE__ */ new Map();
1854
1727
  this.nextId = 0;
@@ -1984,15 +1857,9 @@ var DiscordAudioTransport = class extends EventEmitter {
1984
1857
  this.stopping = true;
1985
1858
  this.send({ type: "stop" });
1986
1859
  const drained = (async () => {
1987
- let timer;
1988
1860
  try {
1989
- await Promise.race([this.exited, new Promise((resolve) => {
1990
- timer = setTimeout(() => {
1991
- this.worker.terminate().then(() => resolve());
1992
- }, STOP_GRACE_MS);
1993
- })]);
1861
+ await raceWithTimeout(this.exited, STOP_GRACE_MS, () => this.worker.terminate());
1994
1862
  } finally {
1995
- clearTimeout(timer);
1996
1863
  this.finish(/* @__PURE__ */ new Error("Discord voice session stopped."));
1997
1864
  }
1998
1865
  })();
@@ -2016,7 +1883,6 @@ var DiscordAudioTransport = class extends EventEmitter {
2016
1883
  this.finish(/* @__PURE__ */ new Error("Discord voice session stopped."), true);
2017
1884
  break;
2018
1885
  case "connection":
2019
- this.connectionStatus = event.status;
2020
1886
  if (event.status === "destroyed") this.emit("stopped");
2021
1887
  break;
2022
1888
  case "player":
@@ -2029,11 +1895,7 @@ var DiscordAudioTransport = class extends EventEmitter {
2029
1895
  break;
2030
1896
  case "capture-frame": {
2031
1897
  const capture = this.captures.get(event.id);
2032
- if (capture && !capture.destroyed) capture.push({
2033
- ...event.frame,
2034
- pcm: Buffer.from(event.frame.pcm),
2035
- packet: Buffer.from(event.frame.packet)
2036
- });
1898
+ if (capture && !capture.destroyed) capture.push(event.frame);
2037
1899
  break;
2038
1900
  }
2039
1901
  case "capture-error":
@@ -2065,9 +1927,9 @@ var DiscordAudioTransport = class extends EventEmitter {
2065
1927
  }
2066
1928
  case "error":
2067
1929
  this.readiness.reject(restoreDiscordAudioError(event.error));
2068
- logger$3.warn("discord voice: " + event.error.message);
1930
+ logger$2.warn("discord voice: audio worker failed", { code: event.error.code });
2069
1931
  break;
2070
- case "log": if (event.level === "warn") logger$3.warn(event.message);
1932
+ case "log": if (event.level === "warn") logger$2.warn(event.message);
2071
1933
  else logVerbose(event.message);
2072
1934
  }
2073
1935
  if (!this.stopping) this.emit("event", event);
@@ -2080,7 +1942,6 @@ var DiscordAudioTransport = class extends EventEmitter {
2080
1942
  finish(error, drained = false) {
2081
1943
  if (this.terminal) return;
2082
1944
  this.terminal = true;
2083
- this.connectionStatus = "destroyed";
2084
1945
  this.playerStatus = "idle";
2085
1946
  this.readiness.reject(error);
2086
1947
  this.destroyAdapter();
@@ -2155,7 +2016,7 @@ var DiscordVoiceConversationInput = class {
2155
2016
  }
2156
2017
  this.pendingAudioBytes += pcm.length;
2157
2018
  if (this.params.createTurn) this.audio.push({
2158
- pcm: Buffer.from(pcm),
2019
+ pcm,
2159
2020
  receipt
2160
2021
  });
2161
2022
  return;
@@ -2275,44 +2136,8 @@ var DiscordVoiceConversationQueue = class {
2275
2136
  }
2276
2137
  };
2277
2138
  //#endregion
2278
- //#region extensions/discord/src/voice/voice-route.ts
2279
- function resolveDiscordVoiceAgentRoute(params) {
2280
- const voiceRoute = resolveAgentRoute({
2281
- ...params,
2282
- channel: "discord",
2283
- peer: {
2284
- kind: "channel",
2285
- id: params.sessionChannelId
2286
- }
2287
- });
2288
- const agentSession = params.voiceConfig?.agentSession;
2289
- if (agentSession?.mode !== "target") return {
2290
- route: voiceRoute,
2291
- voiceRoute,
2292
- agentSessionMode: "voice",
2293
- agentSessionTarget: void 0
2294
- };
2295
- const target = agentSession.target?.trim();
2296
- if (!target) throw new Error("channels.discord.voice.agentSession.target is required when mode is \"target\"");
2297
- const parsed = parseDiscordTarget(target, { defaultKind: "channel" });
2298
- if (!parsed) throw new Error(`Invalid Discord voice agent session target "${target}"`);
2299
- return {
2300
- route: resolveAgentRoute({
2301
- ...params,
2302
- channel: "discord",
2303
- peer: {
2304
- kind: parsed.kind === "user" ? "direct" : "channel",
2305
- id: parsed.id
2306
- }
2307
- }),
2308
- voiceRoute,
2309
- agentSessionMode: "target",
2310
- agentSessionTarget: parsed.normalized
2311
- };
2312
- }
2313
- //#endregion
2314
2139
  //#region extensions/discord/src/voice/voice-session.ts
2315
- const logger$2 = createSubsystemLogger("discord/voice");
2140
+ const logger$1 = createSubsystemLogger("discord/voice");
2316
2141
  function isVoiceSessionStopped(entry) {
2317
2142
  return entry.sessionLifecycle.status === "stopped";
2318
2143
  }
@@ -2334,7 +2159,7 @@ var DiscordVoiceSessions = class {
2334
2159
  refreshGuildRoster(guildId) {
2335
2160
  const entry = this.params.sessions.get(guildId.trim());
2336
2161
  if (!entry || entry.sessionLifecycle.status === "stopped") return;
2337
- this.params.membership.activate(entry, this.params.botUserId());
2162
+ this.params.membership.activate(entry, this.params.botUserId);
2338
2163
  }
2339
2164
  async resolveChannel({ guildId, channelId }) {
2340
2165
  let channelInfo;
@@ -2385,11 +2210,11 @@ var DiscordVoiceSessions = class {
2385
2210
  if (existing && existing.channelId === channelId) {
2386
2211
  if (authority) existing.generation = authority.generation;
2387
2212
  if ((!options?.captureOnly || !existing.captureOnly) && isDiscordRealtimeVoiceMode(voiceMode) && existing.realtimeLifecycle.status !== "active" && existing.realtimeLifecycle.status !== "starting") {
2388
- const realtimeResult = await this.attachRealtimeSession(existing, voiceMode, {
2213
+ const realtimeError = await this.attachRealtimeSession(existing, voiceMode, {
2389
2214
  requireLiveEntry: true,
2390
2215
  isCurrent: authority?.isCurrent
2391
2216
  });
2392
- if (!realtimeResult.ok) return failedJoinResult(realtimeResult.message);
2217
+ if (realtimeError) return failedJoinResult(realtimeError);
2393
2218
  }
2394
2219
  logVoiceVerbose(`join: already connected to guild ${guildId} channel ${channelId}`);
2395
2220
  return {
@@ -2420,8 +2245,8 @@ var DiscordVoiceSessions = class {
2420
2245
  const adapterCreator = voicePlugin.getGatewayAdapterCreator(guildId);
2421
2246
  const daveEncryption = voiceConfig?.daveEncryption;
2422
2247
  const decryptionFailureTolerance = voiceConfig?.decryptionFailureTolerance;
2423
- const connectReadyTimeoutMs = resolveVoiceTimeoutMs(voiceConfig?.connectTimeoutMs, VOICE_CONNECT_READY_TIMEOUT_MS);
2424
- const reconnectGraceMs = resolveVoiceTimeoutMs(voiceConfig?.reconnectGraceMs, VOICE_RECONNECT_GRACE_MS);
2248
+ const connectReadyTimeoutMs = voiceConfig?.connectTimeoutMs ?? 3e4;
2249
+ const reconnectGraceMs = voiceConfig?.reconnectGraceMs ?? 15e3;
2425
2250
  logVoiceVerbose(`join: DAVE settings encryption=${daveEncryption === false ? "off" : "on"} tolerance=${decryptionFailureTolerance ?? "default"} connectTimeout=${connectReadyTimeoutMs}ms reconnectGrace=${reconnectGraceMs}ms`);
2426
2251
  await this.stopTransport(guildId);
2427
2252
  if (this.params.destroyed() || authority?.isCurrent() === false) return failedJoinResult("Discord voice join was cancelled.");
@@ -2435,7 +2260,7 @@ var DiscordVoiceSessions = class {
2435
2260
  decryptionFailureTolerance,
2436
2261
  connectTimeoutMs: connectReadyTimeoutMs,
2437
2262
  reconnectGraceMs,
2438
- captureSilenceGraceMs: resolveVoiceTimeoutMs(voiceConfig?.captureSilenceGraceMs, CAPTURE_FINALIZE_GRACE_MS),
2263
+ captureSilenceGraceMs: voiceConfig?.captureSilenceGraceMs ?? 2e3,
2439
2264
  realtime: isDiscordRealtimeVoiceMode(voiceMode)
2440
2265
  }, adapterCreator);
2441
2266
  this.transports.set(guildId, audio);
@@ -2449,22 +2274,50 @@ var DiscordVoiceSessions = class {
2449
2274
  await this.stopTransport(guildId);
2450
2275
  return failedJoinResult("Discord voice join was cancelled.");
2451
2276
  }
2452
- const sessionChannelId = channelInfo?.id ?? channelId;
2277
+ const sessionChannelId = channelInfo.id;
2453
2278
  if (sessionChannelId !== channelId) logVoiceVerbose(`join: using session channel ${sessionChannelId} for voice channel ${channelId}`);
2454
- let routeInfo;
2279
+ let route;
2280
+ let voiceRoute;
2281
+ let agentSessionMode = "voice";
2282
+ let agentSessionTarget;
2455
2283
  try {
2456
- routeInfo = resolveDiscordVoiceAgentRoute({
2284
+ const routeParams = {
2457
2285
  ...this.params,
2458
2286
  guildId,
2459
2287
  sessionChannelId,
2460
2288
  voiceConfig
2289
+ };
2290
+ voiceRoute = resolveAgentRoute({
2291
+ ...routeParams,
2292
+ channel: "discord",
2293
+ peer: {
2294
+ kind: "channel",
2295
+ id: sessionChannelId
2296
+ }
2461
2297
  });
2298
+ route = voiceRoute;
2299
+ const agentSession = routeParams.voiceConfig?.agentSession;
2300
+ if (agentSession?.mode === "target") {
2301
+ const target = agentSession.target?.trim();
2302
+ if (!target) throw new Error("channels.discord.voice.agentSession.target is required when mode is \"target\"");
2303
+ const parsed = parseDiscordTarget(target, { defaultKind: "channel" });
2304
+ if (!parsed) throw new Error(`Invalid Discord voice agent session target "${target}"`);
2305
+ route = resolveAgentRoute({
2306
+ ...routeParams,
2307
+ channel: "discord",
2308
+ peer: {
2309
+ kind: parsed.kind === "user" ? "direct" : "channel",
2310
+ id: parsed.id
2311
+ }
2312
+ });
2313
+ agentSessionMode = "target";
2314
+ agentSessionTarget = parsed.normalized;
2315
+ }
2462
2316
  } catch (err) {
2463
2317
  await this.stopTransport(guildId);
2464
2318
  return failedJoinResult(`Failed to resolve Discord voice agent session: ${formatErrorMessage$1(err)}`);
2465
2319
  }
2466
- const { route, voiceRoute, agentSessionMode, agentSessionTarget } = routeInfo;
2467
- logger$2.info(`discord voice: joining guild=${guildId} channel=${channelId} mode=${voiceMode} agent=${route.agentId} voiceSession=${voiceRoute.sessionKey} supervisorSession=${route.sessionKey} agentSessionMode=${agentSessionMode}${agentSessionTarget ? ` agentSessionTarget=${agentSessionTarget}` : ""} voiceModel=${voiceConfig?.model ?? "route-default"} realtimeProvider=${voiceConfig?.realtime?.provider ?? "auto"} realtimeModel=${voiceConfig?.realtime?.model ?? "provider-default"} realtimeVoice=${voiceConfig?.realtime?.speakerVoice ?? voiceConfig?.realtime?.speakerVoiceId ?? "provider-default"}`);
2320
+ logger$1.info(`discord voice: joining guild=${guildId} channel=${channelId} mode=${voiceMode} agent=${route.agentId} voiceSession=${voiceRoute.sessionKey} supervisorSession=${route.sessionKey} agentSessionMode=${agentSessionMode}${agentSessionTarget ? ` agentSessionTarget=${agentSessionTarget}` : ""} voiceModel=${voiceConfig?.model ?? "route-default"} realtimeProvider=${voiceConfig?.realtime?.provider ?? "auto"} realtimeModel=${voiceConfig?.realtime?.model ?? "provider-default"} realtimeVoice=${voiceConfig?.realtime?.speakerVoice ?? voiceConfig?.realtime?.speakerVoiceId ?? "provider-default"}`);
2468
2321
  let stopCompletion;
2469
2322
  const stopEntry = (reason, disposition = "abort") => {
2470
2323
  if (entry.sessionLifecycle.status === "stopped") return stopCompletion;
@@ -2480,14 +2333,13 @@ var DiscordVoiceSessions = class {
2480
2333
  const realtimeLifecycle = entry.realtimeLifecycle;
2481
2334
  entry.realtimeLifecycle = {
2482
2335
  status: "stopped",
2483
- generation: realtimeLifecycle.generation,
2484
2336
  reason
2485
2337
  };
2486
2338
  let realtimeCompletion = void 0;
2487
2339
  try {
2488
2340
  if (realtimeLifecycle.status === "starting" || realtimeLifecycle.status === "active") realtimeCompletion = realtimeLifecycle.instance.close(disposition);
2489
2341
  } catch (error) {
2490
- logger$2.warn(`discord voice: realtime close failed: ${formatErrorMessage$1(error)}`);
2342
+ logger$1.warn(`discord voice: realtime close failed: ${formatErrorMessage$1(error)}`);
2491
2343
  }
2492
2344
  const audioCompletion = this.stopTransport(guildId, audio);
2493
2345
  stopCompletion = Promise.allSettled([realtimeCompletion, audioCompletion]).then(() => {
@@ -2501,7 +2353,7 @@ var DiscordVoiceSessions = class {
2501
2353
  };
2502
2354
  completion.then(forget, (error) => {
2503
2355
  forget();
2504
- logger$2.warn(`discord voice: session stop failed: ${formatErrorMessage$1(error)}`);
2356
+ logger$1.warn(`discord voice: session stop failed: ${formatErrorMessage$1(error)}`);
2505
2357
  });
2506
2358
  return stopCompletion;
2507
2359
  };
@@ -2512,10 +2364,9 @@ var DiscordVoiceSessions = class {
2512
2364
  autoJoinWhenOccupied: options?.autoJoinWhenOccupied === true,
2513
2365
  sessionLifecycle: { status: "active" },
2514
2366
  guildId,
2515
- guildName: channelInfo && "guild" in channelInfo && channelInfo.guild && typeof channelInfo.guild.name === "string" ? channelInfo.guild.name : void 0,
2367
+ guildName: channelInfo.guild?.name,
2516
2368
  channelId,
2517
- channelName: channelInfo && "name" in channelInfo && typeof channelInfo.name === "string" ? channelInfo.name : void 0,
2518
- sessionChannelId,
2369
+ channelName: channelInfo.name,
2519
2370
  voiceSessionKey: voiceRoute.sessionKey,
2520
2371
  route,
2521
2372
  audio,
@@ -2533,17 +2384,14 @@ var DiscordVoiceSessions = class {
2533
2384
  lastDecryptFailureAt: 0,
2534
2385
  decryptRecoveryInFlight: false
2535
2386
  },
2536
- realtimeLifecycle: {
2537
- status: "inactive",
2538
- generation: 0
2539
- },
2387
+ realtimeLifecycle: { status: "inactive" },
2540
2388
  stop(reason, disposition) {
2541
2389
  return stopEntry(reason ?? `stop guild ${guildId} channel ${channelId}`, disposition);
2542
2390
  }
2543
2391
  };
2544
2392
  const speakingHandler = (userId, speaking) => {
2545
2393
  if (speaking) this.params.receive.handleSpeakingStart(entry, userId).catch((error) => {
2546
- logger$2.warn("discord voice: capture failed: " + formatErrorMessage$1(error));
2394
+ logger$1.warn("discord voice: capture failed: " + formatErrorMessage$1(error));
2547
2395
  });
2548
2396
  else this.params.receive.scheduleCaptureFinalize(entry, userId);
2549
2397
  };
@@ -2552,10 +2400,10 @@ var DiscordVoiceSessions = class {
2552
2400
  };
2553
2401
  audio.on("stopped", destroyedHandler);
2554
2402
  if (!entry.captureOnly && isDiscordRealtimeVoiceMode(voiceMode)) {
2555
- const realtimeResult = await this.attachRealtimeSession(entry, voiceMode, { isCurrent: authority?.isCurrent });
2556
- if (!realtimeResult.ok) {
2403
+ const realtimeError = await this.attachRealtimeSession(entry, voiceMode, { isCurrent: authority?.isCurrent });
2404
+ if (realtimeError) {
2557
2405
  await entry.stop(`realtime setup failed guild ${guildId} channel ${channelId}`);
2558
- return failedJoinResult(realtimeResult.message);
2406
+ return failedJoinResult(realtimeError);
2559
2407
  }
2560
2408
  }
2561
2409
  if (isVoiceSessionStopped(entry) || this.params.destroyed() || authority && !authority.isCurrent()) {
@@ -2565,8 +2413,8 @@ var DiscordVoiceSessions = class {
2565
2413
  entry.audio.enablePassthrough("post-join warmup", 30);
2566
2414
  audio.on("speaking", speakingHandler);
2567
2415
  this.params.sessions.set(guildId, entry);
2568
- this.params.membership.activate(entry, this.params.botUserId());
2569
- logger$2.info(`discord voice: joined guild=${guildId} channel=${channelId} mode=${voiceMode} agent=${route.agentId} voiceSession=${voiceRoute.sessionKey} supervisorSession=${route.sessionKey} voiceModel=${voiceConfig?.model ?? "route-default"}`);
2416
+ this.params.membership.activate(entry, this.params.botUserId);
2417
+ logger$1.info(`discord voice: joined guild=${guildId} channel=${channelId} mode=${voiceMode} agent=${route.agentId} voiceSession=${voiceRoute.sessionKey} supervisorSession=${route.sessionKey} voiceModel=${voiceConfig?.model ?? "route-default"}`);
2570
2418
  return {
2571
2419
  ok: true,
2572
2420
  message: `Joined ${formatMention({ channelId })}.`,
@@ -2604,24 +2452,20 @@ var DiscordVoiceSessions = class {
2604
2452
  entry
2605
2453
  });
2606
2454
  const isCurrent = () => !isVoiceSessionStopped(entry) && options?.isCurrent?.() !== false && (options?.requireLiveEntry !== true || this.params.sessions.get(entry.guildId) === entry);
2607
- if (!isCurrent()) return {
2608
- ok: false,
2609
- message: "Discord realtime voice session stopped before startup completed."
2610
- };
2611
- const { DiscordRealtimeVoiceSession } = await import("./realtime-session.runtime-DvfS4vJj.mjs");
2455
+ if (!isCurrent()) return "Discord realtime voice session stopped before startup completed.";
2456
+ const { DiscordRealtimeVoiceSession } = await import("./realtime-session.runtime-BTDWsV4d.mjs");
2612
2457
  const realtime = new DiscordRealtimeVoiceSession({
2613
2458
  ...this.params,
2614
2459
  bootstrapContextInstructions,
2615
2460
  entry,
2616
- getHumanParticipantCount: () => this.params.membership.countHumanParticipants(entry, this.params.botUserId()),
2461
+ getHumanParticipantCount: () => this.params.membership.countHumanParticipants(entry, this.params.botUserId),
2617
2462
  mode: voiceMode,
2618
2463
  onTerminalError: (error) => {
2619
- logger$2.error(`discord voice: realtime session failed terminally guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2464
+ logger$1.error(`discord voice: realtime session failed terminally guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2620
2465
  const lifecycle = entry.realtimeLifecycle;
2621
2466
  if (options?.requireLiveEntry && lifecycle.status === "starting" && lifecycle.instance === realtime) {
2622
2467
  entry.realtimeLifecycle = {
2623
2468
  status: "stopped",
2624
- generation: lifecycle.generation,
2625
2469
  reason: "realtime terminal error"
2626
2470
  };
2627
2471
  realtime.close();
@@ -2639,105 +2483,45 @@ var DiscordVoiceSessions = class {
2639
2483
  if (!this.params.isSessionGenerationCurrent(entry) || !context || context.isCurrent?.() === false || context.senderIsOwner !== turn.context.senderIsOwner) throw new Error("Discord voice reply authorization is no longer current");
2640
2484
  };
2641
2485
  assertCurrent();
2642
- const { sendMessageDiscord } = await import("./send.outbound-qZ3iK3Vq.mjs").then((n) => n.i);
2486
+ const { sendMessageDiscord } = await import("./send.outbound-Uzcmh3Yd.mjs").then((n) => n.i);
2643
2487
  await sendMessageDiscord(`channel:${entry.channelId}`, text, {
2644
2488
  cfg: this.params.cfg,
2645
2489
  accountId: this.params.accountId,
2646
2490
  assertPlatformSendAuthorized: assertCurrent
2647
2491
  });
2648
2492
  } catch (error) {
2649
- logger$2.warn(`discord voice: text fallback dropped guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2493
+ logger$1.warn(`discord voice: text fallback dropped guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2650
2494
  }
2651
2495
  },
2652
2496
  resolveSpeakerContext: (userId) => this.params.receive.resolveDiscordVoiceIngressContext(entry, userId)
2653
2497
  });
2654
- const generation = entry.realtimeLifecycle.generation + 1;
2655
2498
  entry.realtimeLifecycle = {
2656
2499
  status: "starting",
2657
- generation,
2658
2500
  instance: realtime
2659
2501
  };
2660
2502
  try {
2661
2503
  await realtime.connect();
2662
- if (entry.realtimeLifecycle.status !== "starting" || entry.realtimeLifecycle.generation !== generation || entry.realtimeLifecycle.instance !== realtime || !isCurrent()) {
2504
+ if (entry.realtimeLifecycle.status !== "starting" || entry.realtimeLifecycle.instance !== realtime || !isCurrent()) {
2663
2505
  await realtime.close();
2664
- return {
2665
- ok: false,
2666
- message: "Discord realtime voice session stopped before startup completed."
2667
- };
2506
+ return "Discord realtime voice session stopped before startup completed.";
2668
2507
  }
2669
2508
  entry.realtimeLifecycle = {
2670
2509
  status: "active",
2671
- generation,
2672
2510
  instance: realtime
2673
2511
  };
2674
- return { ok: true };
2512
+ return;
2675
2513
  } catch (err) {
2676
2514
  await realtime.close();
2677
- if (entry.realtimeLifecycle.status === "starting" && entry.realtimeLifecycle.generation === generation) entry.realtimeLifecycle = {
2515
+ if (entry.realtimeLifecycle.status === "starting" && entry.realtimeLifecycle.instance === realtime) entry.realtimeLifecycle = {
2678
2516
  status: "stopped",
2679
- generation,
2680
2517
  reason: "connect failed"
2681
2518
  };
2682
- return {
2683
- ok: false,
2684
- message: `Failed to start Discord realtime voice: ${formatErrorMessage$1(err)}`
2685
- };
2519
+ return `Failed to start Discord realtime voice: ${formatErrorMessage$1(err)}`;
2686
2520
  }
2687
2521
  }
2688
2522
  };
2689
2523
  //#endregion
2690
- //#region extensions/discord/src/voice/listeners.ts
2691
- const logger$1 = createSubsystemLogger("discord/voice");
2692
- function startAutoJoin(operation, context = "") {
2693
- operation().catch((err) => logger$1.warn(`discord voice: autoJoin${context} failed: ${formatErrorMessage$1(err)}`));
2694
- }
2695
- var DiscordVoiceReadyListener = class {
2696
- constructor(manager) {
2697
- this.manager = manager;
2698
- this.type = discord_exports.GatewayDispatchEvents.Ready;
2699
- }
2700
- async handle(_data, _client) {
2701
- startAutoJoin(() => this.manager.autoJoin());
2702
- }
2703
- };
2704
- var DiscordVoiceResumedListener = class extends DiscordVoiceReadyListener {
2705
- constructor(..._args) {
2706
- super(..._args);
2707
- this.type = discord_exports.GatewayDispatchEvents.Resumed;
2708
- }
2709
- };
2710
- var DiscordVoiceGuildCreateListener = class {
2711
- constructor(manager) {
2712
- this.manager = manager;
2713
- this.type = discord_exports.GatewayDispatchEvents.GuildCreate;
2714
- }
2715
- async handle(data, _client) {
2716
- if (!data.unavailable) {
2717
- this.manager.refreshGuildRoster(data.id);
2718
- startAutoJoin(() => this.manager.reconcileAutoJoinGuild(data.id), ` occupancy reconciliation guild=${data.id}`);
2719
- }
2720
- }
2721
- };
2722
- var DiscordVoiceStateUpdateListener = class extends VoiceStateUpdateListener {
2723
- constructor(manager) {
2724
- super();
2725
- this.manager = manager;
2726
- }
2727
- async handle(data, client) {
2728
- const transition = client.getPlugin("gateway")?.takeVoiceStateTransition(data);
2729
- await this.manager.handleVoiceStateUpdate(data, transition ? transition.previous ?? null : void 0);
2730
- }
2731
- };
2732
- //#endregion
2733
2524
  //#region extensions/discord/src/voice/voice-runtime.ts
2734
- var voice_runtime_exports = /* @__PURE__ */ __exportAll({
2735
- DiscordVoiceGuildCreateListener: () => DiscordVoiceGuildCreateListener,
2736
- DiscordVoiceManager: () => DiscordVoiceManager,
2737
- DiscordVoiceReadyListener: () => DiscordVoiceReadyListener,
2738
- DiscordVoiceResumedListener: () => DiscordVoiceResumedListener,
2739
- DiscordVoiceStateUpdateListener: () => DiscordVoiceStateUpdateListener
2740
- });
2741
2525
  const logger = createSubsystemLogger("discord/voice");
2742
2526
  const DISCORD_VOICE_FATAL_AUTOJOIN_ERROR_PATTERNS = [
2743
2527
  "api key missing",
@@ -2789,8 +2573,7 @@ var DiscordVoiceManager = class {
2789
2573
  }, this),
2790
2574
  readPolicy: this.readPolicy,
2791
2575
  admissionAllowFrom,
2792
- botUserId: () => this.botUserId,
2793
- getSession: (guildId) => this.sessions.get(guildId),
2576
+ sessions: this.sessions,
2794
2577
  isEntryCurrent: (entry) => this.isEntryCurrent(entry),
2795
2578
  isFollowOwnedGuild: (guildId) => this.following.isFollowOwnedGuild(guildId),
2796
2579
  join: (entry, options) => this.join(entry, options),
@@ -2802,11 +2585,9 @@ var DiscordVoiceManager = class {
2802
2585
  ...params,
2803
2586
  allowedChannels: this.allowedChannels,
2804
2587
  autoJoinChannels: this.autoJoinChannels,
2805
- botUserId: () => this.botUserId,
2806
- deleteRecoveryAttempt: (guildId) => this.receive.daveRecoveryAttempts.delete(guildId),
2588
+ daveRecoveryAttempts: this.receive.daveRecoveryAttempts,
2807
2589
  stopTransport: (guildId) => this.voiceSessions.stopTransport(guildId),
2808
- getRecoveryAttempt: (guildId) => this.receive.daveRecoveryAttempts.get(guildId),
2809
- getSession: (guildId) => this.sessions.get(guildId),
2590
+ sessions: this.sessions,
2810
2591
  hasVoiceLifecycle: (guildId) => {
2811
2592
  const lifecycle = this.guildLifecycles.get(guildId);
2812
2593
  return lifecycle?.status === "starting" || lifecycle?.status === "active";
@@ -2814,14 +2595,12 @@ var DiscordVoiceManager = class {
2814
2595
  isAllowedVoiceChannel: (entry) => this.isAllowedVoiceChannel(entry),
2815
2596
  join: (entry, options) => this.join(entry, options),
2816
2597
  leave: (entry, options) => this.leave(entry, options),
2817
- listSessions: () => this.sessions.values(),
2818
2598
  voiceEnabled: this.voiceEnabled
2819
2599
  });
2820
2600
  this.voiceSessions = new DiscordVoiceSessions({
2821
2601
  ...params,
2822
2602
  signal: this.abort.signal,
2823
2603
  isSessionGenerationCurrent: (entry) => this.guildLifecycles.get(entry.guildId)?.generation === entry.generation,
2824
- botUserId: () => this.botUserId,
2825
2604
  destroyed: () => this.destroyed,
2826
2605
  getTranscripts: this.getTranscripts,
2827
2606
  membership: this.membership,
@@ -3093,7 +2872,7 @@ var DiscordVoiceManager = class {
3093
2872
  }
3094
2873
  return result;
3095
2874
  } finally {
3096
- if (this.joinTasks.get(guildId) === joinCompletion.promise) this.joinTasks.delete(guildId);
2875
+ this.joinTasks.delete(guildId);
3097
2876
  joinCompletion.resolve();
3098
2877
  }
3099
2878
  }
@@ -3185,11 +2964,11 @@ var DiscordVoiceManager = class {
3185
2964
  });
3186
2965
  }
3187
2966
  enqueueAutoJoin(entry, captureOrigin) {
3188
- const task = (this.autoJoinTasks.get(entry.guildId) ?? Promise.resolve()).catch(() => void 0).then(async () => await this.reconcileAutoJoinEntry(entry, captureOrigin)).finally(() => {
3189
- if (this.autoJoinTasks.get(entry.guildId) === task) this.autoJoinTasks.delete(entry.guildId);
2967
+ return enqueueKeyedTask({
2968
+ tails: this.autoJoinTasks,
2969
+ key: entry.guildId,
2970
+ task: () => this.reconcileAutoJoinEntry(entry, captureOrigin)
3190
2971
  });
3191
- this.autoJoinTasks.set(entry.guildId, task);
3192
- return task;
3193
2972
  }
3194
2973
  async reconcileAutoJoinEntry(entry, captureOrigin) {
3195
2974
  if (this.destroyed) return {
@@ -3249,4 +3028,4 @@ var DiscordVoiceManager = class {
3249
3028
  }
3250
3029
  };
3251
3030
  //#endregion
3252
- export { DiscordVoiceGuildCreateListener, DiscordVoiceManager, DiscordVoiceReadyListener, DiscordVoiceResumedListener, DiscordVoiceStateUpdateListener, logDiscordVoiceAgentControlResult as a, formatVoiceLogPreview as c, handleDiscordVoiceAgentControlToolCall as i, shouldLogRealtimeVerboseEvent as l, DiscordRealtimeRecording as n, maybeControlDiscordVoiceAgentRun as o, formatVoiceIngressPrompt as r, formatRealtimeInfoLog as s, voice_runtime_exports as t };
3031
+ export { DiscordVoiceManager, maybeControlDiscordVoiceAgentRun as a, logDiscordVoiceAgentControlResult as i, formatVoiceIngressPrompt as n, handleDiscordVoiceAgentControlToolCall as r, DiscordRealtimeRecording as t };