@openclaw/discord 2026.10.10 → 2026.11.5-beta.1

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 (217) hide show
  1. package/dist/.setup/{account-inspect-X_Xlr42B.mjs → account-inspect-CSz5Qodj.mjs} +1 -1
  2. package/dist/.setup/{accounts-C18HNgge.mjs → accounts-DtjvhJUj.mjs} +9 -6
  3. package/dist/.setup/{active-turn-thread-route-BAc_Xik-.mjs → active-turn-thread-route-DkPnk2x8.mjs} +1 -2
  4. package/dist/.setup/{allow-list-D1ZGfhXh.mjs → allow-list-DahA0Jxh.mjs} +3 -150
  5. package/dist/.setup/{api-Bth1wKF9.mjs → api-Bp0HI4q3.mjs} +10 -20
  6. package/dist/.setup/{approval-handler.runtime-BAoEELJJ.mjs → approval-handler.runtime-Cy53ugTf.mjs} +80 -61
  7. package/dist/.setup/{approval-message-updates-Cks-MSCJ.mjs → approval-message-updates-DqOXxPss.mjs} +2 -2
  8. package/dist/.setup/{audit-Dw_rAZIz.mjs → audit-DoPKOfQE.mjs} +4 -4
  9. package/dist/.setup/{channel-BMpMAeQL.mjs → channel-Ds6iuNdy.mjs} +134 -201
  10. package/dist/.setup/channel-access-DhJhVrdZ.mjs +23 -0
  11. package/dist/.setup/channel.setup-BLt9dkIG.mjs +235 -0
  12. package/dist/.setup/{components-BvOWSPxr.mjs → components-WTfUxead.mjs} +208 -426
  13. package/dist/.setup/components.base-C5sAPHe4.mjs +31 -0
  14. package/dist/.setup/{config-schema-Coyq5wOr.mjs → config-schema-GX2yDgIH.mjs} +6 -7
  15. package/dist/.setup/{conversation-binding-route-DOPUZNYo.mjs → conversation-binding-route-CZdm-X5A.mjs} +2 -2
  16. package/dist/.setup/{directory-config-CIqVnQtn.mjs → directory-config-BXJuh9-J.mjs} +1 -1
  17. package/dist/.setup/{directory-live-DUuPEWub.mjs → directory-live-CEopeb8Q.mjs} +55 -62
  18. package/dist/.setup/{discord-eFlHX1Gn.mjs → discord-r79VFjJp.mjs} +1087 -1664
  19. package/dist/.setup/{doctor-Dty_Ossy.mjs → doctor-UfLW8nye.mjs} +3 -5
  20. package/dist/.setup/endpoint-runtime-BM3x-m6O.mjs +138 -0
  21. package/dist/.setup/guilds-DQucP5Tn.mjs +21 -0
  22. package/dist/.setup/{handle-action-DXY91jF-.mjs → handle-action-BarHOi-v.mjs} +15 -15
  23. package/dist/.setup/{handle-action.guild-admin-BvBCfhXF.mjs → handle-action.guild-admin-oRUb8p_O.mjs} +5 -5
  24. package/dist/.setup/listeners-CHgTENFu.mjs +46 -0
  25. package/dist/.setup/{live-policy-config-DO1Fk2hp.mjs → live-policy-config-EKp4O6zx.mjs} +2 -3
  26. package/dist/.setup/{message-handler-fL1j1NiR.mjs → message-handler-DUeT8Asf.mjs} +154 -113
  27. package/dist/.setup/{message-handler.preflight-DkjwNZAd.mjs → message-handler.preflight-C6TNtKW0.mjs} +30 -104
  28. package/dist/.setup/{message-handler.preflight-pluralkit-DR4BnvMU.mjs → message-handler.preflight-pluralkit-6E9TFmmN.mjs} +9 -22
  29. package/dist/.setup/{message-handler.process-ClOwIPDK.mjs → message-handler.process-D8_oQ5Cp.mjs} +256 -367
  30. package/dist/.setup/outbound-payload-DUsrFICb.mjs +445 -0
  31. package/dist/.setup/{outbound-session-route-TFBPPkoz.mjs → outbound-session-route-Cb8cv4Oi.mjs} +138 -86
  32. package/dist/.setup/{preflight-audio-CwtPIsvk.mjs → preflight-audio-r4BbaJxh.mjs} +1 -5
  33. package/dist/.setup/{presence-cache-CgutE4NN.mjs → presence-cache-B3xj3b0l.mjs} +1 -6
  34. package/dist/.setup/{probe-DNge7OEP.mjs → probe-BUmJyH35.mjs} +5 -9
  35. package/dist/.setup/{provider-BBDuE14w.mjs → provider-Dm2ERSxe.mjs} +3600 -4454
  36. package/dist/.setup/{provider-session.runtime-D8hMXXqJ.mjs → provider-session.runtime-DCIqDsIg.mjs} +3 -3
  37. package/dist/.setup/provider.runtime-DmxPGoUg.mjs +1 -0
  38. package/dist/.setup/proxy-fetch-B8cK6FLQ.mjs +29 -0
  39. package/dist/.setup/{realtime-session.runtime-cetognkp.mjs → realtime-session.runtime-WJL6NdwK.mjs} +43 -81
  40. package/dist/.setup/{receive-recovery-C77CVdGM.mjs → receive-recovery-DV_v5ROf.mjs} +13 -27
  41. package/dist/.setup/{resolve-allowlist-common-CI77288n.mjs → resolve-allowlist-common-C37fgnYG.mjs} +3 -12
  42. package/dist/.setup/{resolve-channels-DYc6-xgV.mjs → resolve-channels-CwpnQ7C2.mjs} +5 -4
  43. package/dist/.setup/{resolve-users-BQT7XWF2.mjs → resolve-users-D6jSwe8R.mjs} +4 -7
  44. package/dist/.setup/{runtime-CcijhTJT.mjs → runtime-B-PgPsGR.mjs} +6 -6
  45. package/dist/.setup/{runtime-CI0UJqeS.mjs → runtime-DhOMlnYS.mjs} +196 -235
  46. package/dist/.setup/{secret-config-contract-BdbCvqnM.mjs → secret-config-contract-CP6teHec.mjs} +4 -9
  47. package/dist/.setup/{send-Cbq-IVsS.mjs → send-DnLL6XoO.mjs} +149 -174
  48. package/dist/.setup/{send.components-BV6ucNpJ.mjs → send.components-xB43CksK.mjs} +61 -71
  49. package/dist/.setup/{send.outbound-CGhBhzjQ.mjs → send.outbound-B11X6TOE.mjs} +75 -129
  50. package/dist/.setup/{send.receipt-Dw-_r5Bx.mjs → send.receipt-CMteCIZS.mjs} +29 -31
  51. package/dist/.setup/{send.shared-D4MioxW_.mjs → send.shared-BcLLZBul.mjs} +38 -112
  52. package/dist/.setup/{sender-identity-DrN5c4ec.mjs → sender-identity-CGNpdJmb.mjs} +3 -9
  53. package/dist/.setup/setup-plugin-api-C6AMx3hu.mjs +2 -0
  54. package/dist/.setup/{shared-Bp0sxD5R.mjs → shared-BEYw16he.mjs} +8 -10
  55. package/dist/.setup/shared-interactive-DKBw4SNV.mjs +311 -0
  56. package/dist/.setup/{subagent-hooks-mQbDkvuD.mjs → subagent-hooks-DlYElpXa.mjs} +1 -1
  57. package/dist/.setup/{system-events-2zc2eGfF.mjs → system-events--Pk6y9aP.mjs} +2 -2
  58. package/dist/.setup/{target-resolver-CAHeVfmZ.mjs → target-resolver-Bo9EpGp_.mjs} +3 -3
  59. package/dist/.setup/{thread-bindings-Dg7X_ZXP.mjs → thread-bindings-BF-hr-bg.mjs} +12 -20
  60. package/dist/.setup/{thread-bindings.manager-DCDYksah.mjs → thread-bindings.manager-CQCkha5r.mjs} +22 -42
  61. package/dist/.setup/{thread-bindings.session-updates-C76plLS3.mjs → thread-bindings.session-updates-C2gJAj_I.mjs} +11 -18
  62. package/dist/.setup/{threading-l0UfrE6x.mjs → threading-HA9C2wYR.mjs} +68 -104
  63. package/dist/.setup/{timeouts-DTrUsJ_W.mjs → timeouts-CT9hnmo4.mjs} +1 -1
  64. package/dist/.setup/{transcripts-source-CGgOaWcu.mjs → transcripts-source-DzpzETZR.mjs} +102 -172
  65. package/dist/.setup/{voice-runtime-DY1EwDfi.mjs → voice-runtime-Bo_nsVvX.mjs} +231 -448
  66. package/dist/.source-module-urls/d6c089460280c5a04184542d6712e04545caeb1ebb290d3504377b4cc5e22fea.json +1 -1
  67. package/dist/account-inspect-api.js +1 -1
  68. package/dist/action-runtime-api.js +1 -1
  69. package/dist/activities-api.js +285 -337
  70. package/dist/api.js +16 -16
  71. package/dist/assets/embedded-app-sdk.mjs +1 -1
  72. package/dist/channel-config-api.js +1 -1
  73. package/dist/channel-plugin-api.js +1 -1
  74. package/dist/directory-contract-api.js +1 -1
  75. package/dist/runtime-api.js +22 -22
  76. package/dist/secret-contract-api.js +1 -1
  77. package/dist/setup-entry.js +1 -1
  78. package/dist/setup-plugin-api.js +1 -1
  79. package/dist/src/voice/audio-worker.runtime.js +56 -68
  80. package/dist/subagent-hooks-api.js +1 -1
  81. package/dist/transcripts-source-api.js +1 -1
  82. package/node_modules/@discord/embedded-app-sdk/output/lib/zod/lib/index.cjs +2 -3
  83. package/node_modules/@discord/embedded-app-sdk/output/lib/zod/lib/index.mjs +2 -3
  84. package/node_modules/@napi-rs/wasm-runtime/dist/fs.js +3339 -4021
  85. package/node_modules/@napi-rs/wasm-runtime/package.json +1 -1
  86. package/node_modules/@types/lodash/README.md +1 -1
  87. package/node_modules/@types/lodash/common/function.d.ts +2 -2
  88. package/node_modules/@types/lodash/package.json +2 -2
  89. package/node_modules/@types/node/README.md +1 -1
  90. package/node_modules/@types/node/package.json +2 -2
  91. package/node_modules/@types/node/util.d.ts +6 -3
  92. package/node_modules/discord-api-types/package.json +4 -4
  93. package/node_modules/discord-api-types/rest/v10/index.d.ts +8 -0
  94. package/node_modules/discord-api-types/rest/v10/index.d.ts.map +1 -1
  95. package/node_modules/discord-api-types/rest/v10/index.js +8 -0
  96. package/node_modules/discord-api-types/rest/v10/index.js.map +1 -1
  97. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts +26 -2
  98. package/node_modules/discord-api-types/rest/v10/oauth2.d.ts.map +1 -1
  99. package/node_modules/discord-api-types/rest/v9/index.d.ts +8 -0
  100. package/node_modules/discord-api-types/rest/v9/index.d.ts.map +1 -1
  101. package/node_modules/discord-api-types/rest/v9/index.js +8 -0
  102. package/node_modules/discord-api-types/rest/v9/index.js.map +1 -1
  103. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts +26 -2
  104. package/node_modules/discord-api-types/rest/v9/oauth2.d.ts.map +1 -1
  105. package/node_modules/typebox/build/format/duration.d.mts +2 -2
  106. package/node_modules/typebox/build/format/duration.mjs +2 -2
  107. package/node_modules/typebox/build/format/idn_email.d.mts +1 -0
  108. package/node_modules/typebox/build/format/idn_email.mjs +1 -0
  109. package/node_modules/typebox/build/format/idn_hostname.d.mts +1 -1
  110. package/node_modules/typebox/build/format/idn_hostname.mjs +1 -1
  111. package/node_modules/typebox/build/format/ipv4.d.mts +2 -2
  112. package/node_modules/typebox/build/format/ipv4.mjs +2 -2
  113. package/node_modules/typebox/build/format/ipv6.d.mts +1 -1
  114. package/node_modules/typebox/build/format/ipv6.mjs +1 -1
  115. package/node_modules/typebox/build/format/relative_json_pointer.d.mts +2 -2
  116. package/node_modules/typebox/build/format/relative_json_pointer.mjs +2 -2
  117. package/node_modules/typebox/build/schema/build.mjs +1 -0
  118. package/node_modules/typebox/build/schema/engine/_unique.d.mts +4 -2
  119. package/node_modules/typebox/build/schema/engine/_unique.mjs +7 -3
  120. package/node_modules/typebox/build/schema/engine/additionalItems.mjs +3 -3
  121. package/node_modules/typebox/build/schema/engine/additionalProperties.d.mts +0 -3
  122. package/node_modules/typebox/build/schema/engine/additionalProperties.mjs +15 -17
  123. package/node_modules/typebox/build/schema/engine/contains.mjs +3 -3
  124. package/node_modules/typebox/build/schema/engine/index.d.mts +1 -0
  125. package/node_modules/typebox/build/schema/engine/index.mjs +1 -0
  126. package/node_modules/typebox/build/schema/engine/items.mjs +7 -4
  127. package/node_modules/typebox/build/schema/engine/maxContains.mjs +2 -2
  128. package/node_modules/typebox/build/schema/engine/minContains.mjs +3 -3
  129. package/node_modules/typebox/build/schema/engine/oneOf.mjs +2 -2
  130. package/node_modules/typebox/build/schema/engine/patternProperties.mjs +2 -2
  131. package/node_modules/typebox/build/schema/engine/propertyNames.mjs +2 -2
  132. package/node_modules/typebox/build/schema/engine/unevaluatedItems.mjs +2 -2
  133. package/node_modules/typebox/build/schema/engine/unevaluatedProperties.mjs +2 -2
  134. package/node_modules/typebox/build/system/hashing/hash.mjs +63 -34
  135. package/node_modules/typebox/build/system/locale/en_US.mjs +2 -1
  136. package/node_modules/typebox/build/system/memory/assign.d.mts +2 -8
  137. package/node_modules/typebox/build/system/memory/assign.mjs +13 -6
  138. package/node_modules/typebox/build/system/memory/clone.d.mts +4 -5
  139. package/node_modules/typebox/build/system/memory/clone.mjs +8 -96
  140. package/node_modules/typebox/build/system/memory/create.d.mts +1 -5
  141. package/node_modules/typebox/build/system/memory/create.mjs +18 -13
  142. package/node_modules/typebox/build/system/memory/deep.d.mts +2 -0
  143. package/node_modules/typebox/build/system/memory/deep.mjs +108 -0
  144. package/node_modules/typebox/build/system/memory/discard.d.mts +1 -1
  145. package/node_modules/typebox/build/system/memory/discard.mjs +9 -8
  146. package/node_modules/typebox/build/system/memory/finalize.d.mts +4 -0
  147. package/node_modules/typebox/build/system/memory/finalize.mjs +30 -0
  148. package/node_modules/typebox/build/system/memory/keys.d.mts +2 -0
  149. package/node_modules/typebox/build/system/memory/keys.mjs +8 -0
  150. package/node_modules/typebox/build/system/memory/update.d.mts +1 -4
  151. package/node_modules/typebox/build/system/memory/update.mjs +43 -16
  152. package/node_modules/typebox/build/type/engine/call/index.d.mts +1 -0
  153. package/node_modules/typebox/build/type/engine/call/index.mjs +1 -0
  154. package/node_modules/typebox/build/type/engine/evaluate/composite.d.mts +2 -24
  155. package/node_modules/typebox/build/type/engine/evaluate/composite.mjs +2 -29
  156. package/node_modules/typebox/build/type/engine/evaluate/index.d.mts +1 -0
  157. package/node_modules/typebox/build/type/engine/evaluate/index.mjs +1 -0
  158. package/node_modules/typebox/build/type/engine/evaluate/narrow.d.mts +5 -1
  159. package/node_modules/typebox/build/type/engine/evaluate/narrow.mjs +6 -1
  160. package/node_modules/typebox/build/type/engine/evaluate/property.d.mts +30 -0
  161. package/node_modules/typebox/build/type/engine/evaluate/property.mjs +29 -0
  162. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.d.mts +1 -3
  163. package/node_modules/typebox/build/type/engine/immutable/instantiate_add.mjs +1 -4
  164. package/node_modules/typebox/build/type/engine/object/from_intersect.d.mts +2 -2
  165. package/node_modules/typebox/build/type/engine/object/from_intersect.mjs +2 -2
  166. package/node_modules/typebox/build/type/engine/object/from_union.d.mts +2 -2
  167. package/node_modules/typebox/build/type/engine/object/from_union.mjs +2 -2
  168. package/node_modules/typebox/build/type/engine/optional/instantiate_add.d.mts +1 -3
  169. package/node_modules/typebox/build/type/engine/optional/instantiate_add.mjs +1 -4
  170. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.d.mts +1 -3
  171. package/node_modules/typebox/build/type/engine/readonly/instantiate_add.mjs +1 -4
  172. package/node_modules/typebox/build/type/engine/this/index.d.mts +1 -0
  173. package/node_modules/typebox/build/type/engine/this/index.mjs +1 -0
  174. package/node_modules/typebox/build/value/clone/clone.d.mts +4 -3
  175. package/node_modules/typebox/build/value/clone/clone.mjs +5 -7
  176. package/node_modules/typebox/build/value/repair/from_cyclic.d.mts +2 -0
  177. package/node_modules/typebox/build/value/repair/from_cyclic.mjs +6 -0
  178. package/node_modules/typebox/build/value/shared/union_priority_sort.mjs +25 -14
  179. package/node_modules/typebox/package.json +1 -1
  180. package/node_modules/typebox/readme.md +1 -1
  181. package/node_modules/undici/docs/docs/api/Interceptors.md +15 -2
  182. package/node_modules/undici/lib/dispatcher/client-h2.js +78 -3
  183. package/node_modules/undici/lib/dispatcher/pool-base.js +20 -3
  184. package/node_modules/undici/package.json +3 -3
  185. package/node_modules/undici/types/api.d.ts +1 -1
  186. package/node_modules/undici/types/utility.d.ts +4 -4
  187. package/node_modules/uuid/package.json +17 -17
  188. package/node_modules/zod/package.json +1 -1
  189. package/node_modules/zod/src/v4/classic/tests/array.test.ts +27 -0
  190. package/node_modules/zod/src/v4/classic/tests/map.test.ts +7 -0
  191. package/node_modules/zod/src/v4/classic/tests/set.test.ts +6 -0
  192. package/node_modules/zod/src/v4/core/compile.ts +9 -0
  193. package/node_modules/zod/src/v4/core/schemas.ts +35 -1
  194. package/node_modules/zod/src/v4/core/util.ts +13 -0
  195. package/node_modules/zod/src/v4/core/versions.ts +1 -1
  196. package/node_modules/zod/v4/core/compile.cjs +8 -0
  197. package/node_modules/zod/v4/core/compile.js +8 -0
  198. package/node_modules/zod/v4/core/schemas.cjs +30 -0
  199. package/node_modules/zod/v4/core/schemas.d.cts +3 -1
  200. package/node_modules/zod/v4/core/schemas.d.ts +3 -1
  201. package/node_modules/zod/v4/core/schemas.js +30 -0
  202. package/node_modules/zod/v4/core/util.cjs +15 -0
  203. package/node_modules/zod/v4/core/util.d.cts +2 -0
  204. package/node_modules/zod/v4/core/util.d.ts +2 -0
  205. package/node_modules/zod/v4/core/util.js +14 -0
  206. package/node_modules/zod/v4/core/versions.cjs +1 -1
  207. package/node_modules/zod/v4/core/versions.js +1 -1
  208. package/openclaw.plugin.json +1 -31
  209. package/package.json +8 -8
  210. package/dist/.setup/channel-access-BPrWoEXM.mjs +0 -47
  211. package/dist/.setup/channel.setup-DVe7Y3Jf.mjs +0 -245
  212. package/dist/.setup/outbound-adapter-DWyAWBFh.mjs +0 -537
  213. package/dist/.setup/provider.runtime-BQ1z4Aq1.mjs +0 -1
  214. package/dist/.setup/setup-plugin-api-B4J6wmL1.mjs +0 -2
  215. package/dist/.setup/targets-BaklhOqq.mjs +0 -3
  216. package/node_modules/typebox/build/system/memory/freeze.d.mts +0 -4
  217. package/node_modules/typebox/build/system/memory/freeze.mjs +0 -6
@@ -1,12 +1,11 @@
1
- import { t as __exportAll } from "./rolldown-runtime-nwUcYXjP.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-C77CVdGM.mjs";
3
- import { S as formatDiscordUserTag, g as resolveDiscordOwnerAccess, o as normalizeDiscordSlug } from "./allow-list-D1ZGfhXh.mjs";
4
- import { B as isUnknownDiscordVoiceStateError, f as VoiceStateUpdateListener, t as discord_exports, yt as getGuildVoiceState } from "./discord-eFlHX1Gn.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-DV_v5ROf.mjs";
2
+ import { F as getGuildVoiceState, H as isUnknownDiscordVoiceStateError } from "./discord-r79VFjJp.mjs";
3
+ import { S as formatDiscordUserTag, g as resolveDiscordOwnerAccess, o as normalizeDiscordSlug } from "./allow-list-DahA0Jxh.mjs";
5
4
  import { t as parseDiscordTarget } from "./target-parsing-BiuhcK9Q.mjs";
6
- import { s as formatMention } from "./send.outbound-CGhBhzjQ.mjs";
5
+ import { s as formatMention } from "./send.outbound-B11X6TOE.mjs";
7
6
  import { t as getDiscordRuntime } from "./runtime-DcBvHOm1.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-BBDuE14w.mjs";
9
- import { a as authorizeDiscordVoiceIngress, c as resolveDiscordVoiceEnabled, o as resolveDiscordVoiceAccess, r as resolveDiscordTranscriptsCapture, s as resolveDiscordVoiceAccessTarget, t as bindDiscordCaptureReceipts } from "./transcripts-source-CGgOaWcu.mjs";
7
+ import { S as buildDiscordGroupSystemPrompt, _ as isDiscordRealtimeVoiceMode, b as resolveDiscordVoiceMode, m as MIN_SEGMENT_SECONDS, v as isVoiceChannel, y as logVoiceVerbose } from "./provider-Dm2ERSxe.mjs";
8
+ import { a as resolveDiscordVoiceEnabled, c as resolveDiscordVoiceAccessTarget, o as authorizeDiscordVoiceIngress, r as resolveDiscordTranscriptsCapture, s as resolveDiscordVoiceAccess, t as bindDiscordCaptureReceipts } from "./transcripts-source-DzpzETZR.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,48 +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
- // 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
- }
28
+ import { createCpuTrackedWorker, createPluginRuntimeProcessEntrypoint, resolveRuntimeWorkerArgv, resolveRuntimeWorkerUrl } from "openclaw/plugin-sdk/process-runtime";
58
29
  // extensions/discord/src/voice/agent-control.ts
59
- const logger$10 = createSubsystemLogger("discord/voice");
30
+ const logger$9 = createSubsystemLogger("discord/voice");
60
31
  async function controlDiscordVoiceAgentRun(params) {
61
32
  const context = params.resolveContext ? await params.resolveContext() : params.context;
62
33
  const assertCurrent = () => {
@@ -105,7 +76,7 @@ async function maybeControlDiscordVoiceAgentRun(params) {
105
76
  };
106
77
  }
107
78
  function logDiscordVoiceAgentControlResult(entry, result) {
108
- 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}`);
109
80
  }
110
81
  async function handleDiscordVoiceAgentControlToolCall(params) {
111
82
  let result;
@@ -157,7 +128,6 @@ var DiscordRealtimeRecordingInput = class {
157
128
  batch: false
158
129
  };
159
130
  this.pending = 0;
160
- this.listeners = /* @__PURE__ */ new Set();
161
131
  this.unavailable = batchDisabled;
162
132
  }
163
133
  noteReceipt(receipt) {
@@ -170,7 +140,7 @@ var DiscordRealtimeRecordingInput = class {
170
140
  this.startedAt = receipt?.startedAt;
171
141
  }
172
142
  if (!receipt?.capture || receipt.capture !== this.capture) this.eligible = false;
173
- this.notify();
143
+ this.onChange?.();
174
144
  }
175
145
  observeBatch(result) {
176
146
  this.pending += 1;
@@ -181,33 +151,26 @@ var DiscordRealtimeRecordingInput = class {
181
151
  this.eligible = false;
182
152
  }).finally(() => {
183
153
  this.pending -= 1;
184
- this.notify();
154
+ this.onChange?.();
185
155
  });
186
156
  }
187
157
  exclude() {
188
158
  this.eligible = false;
189
- this.notify();
159
+ this.onChange?.();
190
160
  }
191
161
  seal(input) {
192
162
  this.sealed[input] = true;
193
- this.notify();
163
+ this.onChange?.();
194
164
  }
195
165
  get complete() {
196
166
  return this.sealed.audio && this.sealed.batch && this.pending === 0;
197
167
  }
198
- subscribe(listener) {
199
- this.listeners.add(listener);
200
- return () => this.listeners.delete(listener);
201
- }
202
- notify() {
203
- for (const listener of this.listeners) listener();
204
- }
205
168
  };
206
169
  /** Realtime text is usable only when the whole provider generation has one recording owner. */
207
170
  var DiscordRealtimeRecording = class {
208
171
  constructor(params) {
209
172
  this.params = params;
210
- this.inputs = /* @__PURE__ */ new Map();
173
+ this.inputs = /* @__PURE__ */ new Set();
211
174
  this.inputCount = 0;
212
175
  this.unavailable = false;
213
176
  this.stopped = false;
@@ -240,12 +203,13 @@ var DiscordRealtimeRecording = class {
240
203
  return;
241
204
  }
242
205
  this.unavailable ||= input.hasAudio && input.unavailable;
243
- this.inputs.get(input)?.();
206
+ input.onChange = void 0;
244
207
  this.inputs.delete(input);
245
208
  }
246
209
  this.publish();
247
210
  };
248
- this.inputs.set(input, input.subscribe(changed));
211
+ this.inputs.add(input);
212
+ input.onChange = changed;
249
213
  changed();
250
214
  }
251
215
  transcript(text) {
@@ -275,7 +239,7 @@ var DiscordRealtimeRecording = class {
275
239
  }
276
240
  close() {
277
241
  this.stopped = true;
278
- for (const unsubscribe of this.inputs.values()) unsubscribe();
242
+ for (const input of this.inputs) input.onChange = void 0;
279
243
  this.inputs.clear();
280
244
  this.bytes -= this.finals.reduce((total, final) => total + final.bytes, 0);
281
245
  this.finals = [];
@@ -321,7 +285,7 @@ var DiscordRealtimeRecording = class {
321
285
  };
322
286
  // extensions/discord/src/voice/ingress.ts
323
287
  const DISCORD_VOICE_MESSAGE_PROVIDER = "discord-voice";
324
- const logger$9 = createSubsystemLogger("discord/voice");
288
+ const logger$8 = createSubsystemLogger("discord/voice");
325
289
  function summarizeAgentTurnPayloads(payloads) {
326
290
  const nonEmptyTextPayloads = payloads.filter((payload) => payload.text.trim()).length;
327
291
  const errorPayloads = payloads.filter((payload) => payload.isError === true).length;
@@ -332,10 +296,9 @@ async function resolveDiscordVoiceIngressContext(params) {
332
296
  const { entry, userId } = params;
333
297
  if (!entry.guildName) {
334
298
  const guild = await params.client.fetchGuild(entry.guildId).catch(() => null);
335
- entry.guildName = guild && typeof guild.name === "string" && guild.name.trim() ? guild.name : void 0;
299
+ entry.guildName = guild?.name.trim() ? guild.name : void 0;
336
300
  }
337
301
  const speaker = await params.speakerContext.resolveContext(entry.guildId, userId);
338
- const speakerIdentity = await params.speakerContext.resolveIdentity(entry.guildId, userId);
339
302
  const access = await authorizeDiscordVoiceIngress({
340
303
  readPolicy: params.readPolicy,
341
304
  cfg: params.cfg,
@@ -346,12 +309,12 @@ async function resolveDiscordVoiceIngressContext(params) {
346
309
  channelName: entry.channelName,
347
310
  channelSlug: entry.channelName ? normalizeDiscordSlug(entry.channelName) : "",
348
311
  channelLabel: formatMention({ channelId: entry.channelId }),
349
- memberRoleIds: speakerIdentity.memberRoleIds,
312
+ memberRoleIds: speaker.memberRoleIds,
350
313
  admissionAllowFrom: params.admissionAllowFrom,
351
314
  sender: {
352
- id: speakerIdentity.id,
353
- name: speakerIdentity.name,
354
- tag: speakerIdentity.tag
315
+ id: speaker.id,
316
+ name: speaker.name,
317
+ tag: speaker.tag
355
318
  }
356
319
  });
357
320
  if (!access.ok) return null;
@@ -398,7 +361,7 @@ async function runDiscordVoiceAgentTurn(params) {
398
361
  }
399
362
  const payloads = result.payloads ?? [];
400
363
  const text = payloads.map((payload) => payload.text).filter((entry) => entry?.trim()).join("\n").trim();
401
- 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)}`);
364
+ 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)}`);
402
365
  return text;
403
366
  }
404
367
  async function resolveDiscordVoiceRealtimeAgentContext(params) {
@@ -407,7 +370,7 @@ async function resolveDiscordVoiceRealtimeAgentContext(params) {
407
370
  agentId: params.entry.route.agentId,
408
371
  sessionKey: params.entry.route.sessionKey,
409
372
  files: params.discordConfig.voice?.realtime?.bootstrapContextFiles,
410
- warn: (message) => logger$9.warn(`discord voice: realtime agent context: ${message}`)
373
+ warn: (message) => logger$8.warn(`discord voice: realtime agent context: ${message}`)
411
374
  };
412
375
  return await resolveRealtimeVoiceAgentContextInstructions(contextParams);
413
376
  }
@@ -424,7 +387,7 @@ function memberLabel(state) {
424
387
  }
425
388
  function listDiscordVoiceParticipantStates(params) {
426
389
  const gateway = params.client.getPlugin("gateway");
427
- if (!gateway || typeof gateway.listVoiceChannelStates !== "function") return null;
390
+ if (!gateway) return null;
428
391
  return gateway.listVoiceChannelStates(params.guildId, params.channelId);
429
392
  }
430
393
  function createDiscordVoiceOccupancyWatcher(params, listener) {
@@ -451,14 +414,13 @@ function createDiscordVoiceOccupancyWatcher(params, listener) {
451
414
  }
452
415
  };
453
416
  }
454
- function retainParticipantId(selected, userId) {
455
- if (selected.includes(userId)) return;
456
- selected.push(userId);
457
- selected.sort((left, right) => left.localeCompare(right));
417
+ function retainParticipant(selected, participant) {
418
+ selected.push(participant);
419
+ selected.sort((left, right) => left.userId.localeCompare(right.userId));
458
420
  if (selected.length > MAX_PARTICIPANTS) selected.pop();
459
421
  }
460
422
  function collectDiscordVoiceParticipants(params) {
461
- const selectedUserIds = [];
423
+ const participants = [];
462
424
  const additionalUserIds = /* @__PURE__ */ new Set();
463
425
  const addAdditionalUserId = (rawUserId) => {
464
426
  const userId = rawUserId?.trim();
@@ -473,23 +435,17 @@ function collectDiscordVoiceParticipants(params) {
473
435
  if (!userId || userId === params.botUserId) continue;
474
436
  totalCount += 1;
475
437
  additionalUserIds.delete(userId);
476
- retainParticipantId(selectedUserIds, userId);
438
+ retainParticipant(participants, {
439
+ userId,
440
+ state
441
+ });
477
442
  }
478
443
  for (const additionalUserId of additionalUserIds) {
479
444
  totalCount += 1;
480
- retainParticipantId(selectedUserIds, additionalUserId);
481
- }
482
- const selected = new Set(selectedUserIds);
483
- const statesByUserId = /* @__PURE__ */ new Map();
484
- for (const state of params.states) {
485
- const userId = state.user_id?.trim();
486
- if (userId && selected.has(userId)) statesByUserId.set(userId, state);
445
+ retainParticipant(participants, { userId: additionalUserId });
487
446
  }
488
447
  return {
489
- participants: selectedUserIds.map((userId) => ({
490
- userId,
491
- state: statesByUserId.get(userId)
492
- })),
448
+ participants,
493
449
  totalCount
494
450
  };
495
451
  }
@@ -511,20 +467,20 @@ function countDiscordVoiceHumanParticipants(params) {
511
467
  return count;
512
468
  }
513
469
  function formatDiscordVoiceParticipantLine(userId, displayName) {
514
- const label = normalizeLabel(displayName) ?? userId;
470
+ const label = displayName ?? userId;
515
471
  return `- user_id=${JSON.stringify(userId)} display_name=${JSON.stringify(label)}`;
516
472
  }
517
473
  function formatDiscordVoiceParticipantStateLine(participant) {
518
474
  return formatDiscordVoiceParticipantLine(participant.userId, participant.state ? memberLabel(participant.state) : void 0);
519
475
  }
520
476
  function formatDiscordVoiceParticipantStateLines(roster) {
521
- const participants = roster.participants.slice(0, MAX_PARTICIPANTS);
477
+ const participants = roster.participants;
522
478
  const lines = participants.map(formatDiscordVoiceParticipantStateLine);
523
479
  if (roster.totalCount > participants.length) lines.push(`- ${roster.totalCount - participants.length} more participant(s)`);
524
480
  return lines;
525
481
  }
526
482
  async function resolveDiscordVoiceParticipantLines(params) {
527
- const participants = params.roster.participants.slice(0, MAX_PARTICIPANTS);
483
+ const participants = params.roster.participants;
528
484
  const lines = await Promise.all(participants.map(async ({ userId, state }) => {
529
485
  return formatDiscordVoiceParticipantLine(userId, (state ? memberLabel(state) : void 0) ?? normalizeLabel((await params.speakerContext.resolveContext(params.guildId, userId)).label) ?? userId);
530
486
  }));
@@ -559,7 +515,7 @@ async function resolveDiscordVoiceIngressContextWithParticipants(params) {
559
515
  } : context;
560
516
  }
561
517
  // extensions/discord/src/voice/membership.ts
562
- const logger$8 = createSubsystemLogger("discord/voice");
518
+ const logger$7 = createSubsystemLogger("discord/voice");
563
519
  const MAX_INFERRED_PARTICIPANTS = 256;
564
520
  var DiscordVoiceMembershipTracker = class {
565
521
  constructor(client, speakerContext, accountId) {
@@ -588,7 +544,7 @@ var DiscordVoiceMembershipTracker = class {
588
544
  };
589
545
  this.states.set(entry, state);
590
546
  const initialLines = formatDiscordVoiceParticipantStateLines(roster);
591
- 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}`);
547
+ 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}`);
592
548
  const activationRevision = state.revision;
593
549
  (async () => {
594
550
  const lines = await resolveDiscordVoiceParticipantLines({
@@ -599,7 +555,7 @@ var DiscordVoiceMembershipTracker = class {
599
555
  if (lines.join("\n") === initialLines.join("\n")) return;
600
556
  if (!state.active || state.revision !== activationRevision || entry.sessionLifecycle.status === "stopped") return;
601
557
  if (!this.publish(entry, this.initialRosterEvent(entry, lines))) return;
602
- logger$8.info(`discord voice: enriched participant roster event queued guild=${entry.guildId} channel=${entry.channelId} participants=${roster.totalCount} supervisorSession=${entry.route.sessionKey}`);
558
+ logger$7.info(`discord voice: enriched participant roster event queued guild=${entry.guildId} channel=${entry.channelId} participants=${roster.totalCount} supervisorSession=${entry.route.sessionKey}`);
603
559
  })().catch((err) => {
604
560
  this.logFailure(entry, err);
605
561
  });
@@ -615,7 +571,7 @@ var DiscordVoiceMembershipTracker = class {
615
571
  `The agent left guild_id=${JSON.stringify(entry.guildId)} channel_id=${JSON.stringify(entry.channelId)}.`,
616
572
  "Any prior roster or membership updates for this voice session are no longer live. Do not respond to this event on its own."
617
573
  ].join("\n"))) return;
618
- logger$8.info(`discord voice: participant session-ended event queued guild=${entry.guildId} channel=${entry.channelId} supervisorSession=${entry.route.sessionKey}`);
574
+ logger$7.info(`discord voice: participant session-ended event queued guild=${entry.guildId} channel=${entry.channelId} supervisorSession=${entry.route.sessionKey}`);
619
575
  }
620
576
  countHumanParticipants(entry, botUserId) {
621
577
  const state = this.states.get(entry);
@@ -671,7 +627,7 @@ var DiscordVoiceMembershipTracker = class {
671
627
  "This roster snapshot supersedes prior voice membership context. Do not respond to this event on its own."
672
628
  ].join("\n"))) return;
673
629
  const event = action === "inferred-present" ? "inferred participant-present" : `participant ${action}`;
674
- logger$8.info(`discord voice: ${event} event queued guild=${entry.guildId} channel=${entry.channelId} user=${participant.userId} supervisorSession=${entry.route.sessionKey}`);
630
+ logger$7.info(`discord voice: ${event} event queued guild=${entry.guildId} channel=${entry.channelId} user=${participant.userId} supervisorSession=${entry.route.sessionKey}`);
675
631
  }
676
632
  publish(entry, text) {
677
633
  try {
@@ -685,7 +641,7 @@ var DiscordVoiceMembershipTracker = class {
685
641
  }
686
642
  }
687
643
  logFailure(entry, err) {
688
- logger$8.warn(`discord voice: participant notification failed guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(err)}`);
644
+ logger$7.warn(`discord voice: participant notification failed guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(err)}`);
689
645
  }
690
646
  initialRosterEvent(entry, lines) {
691
647
  return [
@@ -705,52 +661,36 @@ var DiscordVoiceMembershipTracker = class {
705
661
  }
706
662
  };
707
663
  // extensions/discord/src/voice/speaker-context.ts
708
- const SPEAKER_CONTEXT_CACHE_TTL_MS = 6e4;
709
664
  var DiscordVoiceSpeakerContextResolver = class {
710
665
  constructor(params) {
711
666
  this.params = params;
712
- this.cache = /* @__PURE__ */ new Map();
713
667
  }
714
668
  async resolveContext(guildId, userId) {
715
- const key = `${guildId}:${userId}`;
716
- const cached = this.cache.get(key);
717
- if (cached) {
718
- if (cached.expiresAt > Date.now()) return { ...cached.context };
719
- this.cache.delete(key);
720
- }
721
669
  const identity = await this.resolveIdentity(guildId, userId);
722
- const context = {
723
- id: identity.id,
724
- label: identity.label,
725
- name: identity.name,
726
- tag: identity.tag,
670
+ return {
671
+ ...identity,
727
672
  senderIsOwner: resolveDiscordOwnerAccess({
728
673
  allowFrom: this.params.ownerAllowFrom,
729
674
  sender: identity,
730
675
  allowNameMatching: false
731
676
  }).ownerAllowed
732
677
  };
733
- this.cache.set(key, {
734
- context: { ...context },
735
- expiresAt: Date.now() + SPEAKER_CONTEXT_CACHE_TTL_MS
736
- });
737
- return context;
738
678
  }
739
679
  async resolveIdentity(guildId, userId) {
740
680
  try {
741
681
  const member = await this.params.client.fetchMember(guildId, userId);
742
- const username = member.user?.username ?? void 0;
682
+ const username = member.user?.username;
743
683
  return {
744
684
  id: userId,
745
685
  label: member.nickname ?? member.user?.globalName ?? username ?? userId,
746
686
  name: username,
747
687
  tag: member.user ? formatDiscordUserTag(member.user) : void 0,
748
- memberRoleIds: Array.isArray(member.roles) ? member.roles.map((role) => typeof role === "string" ? role : typeof role?.id === "string" ? role.id : "").filter(Boolean) : []
688
+ memberRoleIds: member.roles
749
689
  };
750
690
  } catch {
751
691
  try {
752
692
  const user = await this.params.client.fetchUser(userId);
753
- const username = user.username ?? void 0;
693
+ const username = user.username;
754
694
  return {
755
695
  id: userId,
756
696
  label: user.globalName ?? username ?? userId,
@@ -769,7 +709,7 @@ var DiscordVoiceSpeakerContextResolver = class {
769
709
  }
770
710
  };
771
711
  // extensions/discord/src/voice/voice-following.ts
772
- const logger$7 = createSubsystemLogger("discord/voice");
712
+ const logger$6 = createSubsystemLogger("discord/voice");
773
713
  const FOLLOW_USERS_RECONCILE_INTERVAL_MS = 1e4;
774
714
  const FOLLOW_USERS_RECONCILE_MAX_GUILDS_PER_RUN = 4;
775
715
  const FOLLOW_USERS_RECONCILE_MAX_REST_LOOKUPS_PER_RUN = 32;
@@ -787,13 +727,6 @@ function normalizeVoiceChannelResidencies(entries) {
787
727
  function normalizeDiscordUserIds(entries) {
788
728
  return new Set(Array.from(entries ?? [], (entry) => entry.trim().replace(/^discord:/, "").replace(/^user:/, "").trim()).filter(Boolean));
789
729
  }
790
- function logFollowUserReconcileVerbose(reason, message) {
791
- if (reason === "interval") {
792
- logger$7.trace(`discord voice: ${message}`);
793
- return;
794
- }
795
- logVoiceVerbose(message);
796
- }
797
730
  var DiscordVoiceFollowing = class {
798
731
  constructor(params) {
799
732
  this.params = params;
@@ -815,7 +748,7 @@ var DiscordVoiceFollowing = class {
815
748
  delayMs: FOLLOW_USERS_RECONCILE_INTERVAL_MS,
816
749
  everyMs: FOLLOW_USERS_RECONCILE_INTERVAL_MS,
817
750
  run: () => this.reconcileFollowedUsers("interval").catch((err) => {
818
- logger$7.warn(`discord voice: follow user reconciliation failed: ${formatErrorMessage$1(err)}`);
751
+ logger$6.warn(`discord voice: follow user reconciliation failed: ${formatErrorMessage$1(err)}`);
819
752
  })
820
753
  });
821
754
  await this.reconcileFollowedUsers("startup");
@@ -823,13 +756,13 @@ var DiscordVoiceFollowing = class {
823
756
  async handleBotVoiceStateUpdate(params) {
824
757
  const { guildId, channelId } = params;
825
758
  if (!channelId) return;
826
- const existing = this.params.getSession(guildId);
759
+ const existing = this.params.sessions.get(guildId);
827
760
  if (this.params.isAllowedVoiceChannel({
828
761
  guildId,
829
762
  channelId
830
763
  })) {
831
764
  if (existing && existing.channelId !== channelId) {
832
- logger$7.warn(`discord voice: bot moved to allowed channel guild=${guildId} from=${existing.channelId} to=${channelId}; rebuilding voice session`);
765
+ logger$6.warn(`discord voice: bot moved to allowed channel guild=${guildId} from=${existing.channelId} to=${channelId}; rebuilding voice session`);
833
766
  await this.params.join({
834
767
  guildId,
835
768
  channelId
@@ -837,12 +770,12 @@ var DiscordVoiceFollowing = class {
837
770
  }
838
771
  return;
839
772
  }
840
- logger$7.warn(`discord voice: bot moved to non-allowed channel guild=${guildId} channel=${channelId}; leaving`);
773
+ logger$6.warn(`discord voice: bot moved to non-allowed channel guild=${guildId} channel=${channelId}; leaving`);
841
774
  if (existing) await this.params.leave({ guildId });
842
775
  else await this.params.stopTransport(guildId);
843
776
  const target = this.resolveVoiceResidencyTarget(guildId);
844
777
  if (target) {
845
- logger$7.warn(`discord voice: rejoining allowed voice channel guild=${guildId} channel=${target.channelId}`);
778
+ logger$6.warn(`discord voice: rejoining allowed voice channel guild=${guildId} channel=${target.channelId}`);
846
779
  await this.params.join(target);
847
780
  }
848
781
  }
@@ -851,21 +784,31 @@ var DiscordVoiceFollowing = class {
851
784
  const { guildId, channelId, userId } = params;
852
785
  const followKey = `${guildId}:${userId}`;
853
786
  const previousFollowedChannelId = this.followedUserChannels.get(followKey)?.channelId;
854
- const existing = this.params.getSession(guildId);
787
+ const existing = this.params.sessions.get(guildId);
855
788
  const wasFollowedVoiceSession = this.followedUserChannels.has(followKey) || this.followedVoiceGuilds.has(guildId);
856
789
  if (!channelId || !this.params.isAllowedVoiceChannel({
857
790
  guildId,
858
791
  channelId
859
792
  })) {
860
793
  this.followedUserChannels.delete(followKey);
861
- if (channelId) logger$7.warn(`discord voice: followed user joined non-allowed channel guild=${guildId} user=${userId} channel=${channelId}; ignoring`);
862
- if (existing && wasFollowedVoiceSession && !this.hasFollowedUserInChannel(existing)) await this.handoffToAnotherFollowedUserOrLeave({
863
- guildId,
864
- userId,
865
- existing,
866
- reason: channelId ? "joined non-allowed channel" : "disconnected"
867
- });
868
- else if (!channelId && !existing && wasFollowedVoiceSession && this.params.hasVoiceLifecycle(guildId)) await this.params.leave({ guildId });
794
+ if (channelId) logger$6.warn(`discord voice: followed user joined non-allowed channel guild=${guildId} user=${userId} channel=${channelId}; ignoring`);
795
+ if (existing && wasFollowedVoiceSession && !this.hasFollowedUserInChannel(existing)) {
796
+ const reason = channelId ? "joined non-allowed channel" : "disconnected";
797
+ const target = this.resolveFollowedUserHandoffTarget(guildId, existing.channelId);
798
+ if (target) {
799
+ logger$6.info(`discord voice: followed user ${reason} guild=${guildId} user=${userId}; moving to remaining followed user channel=${target.channelId}`);
800
+ const result = await this.params.join(target, { preserveFollowState: true });
801
+ if (result.ok) this.followedVoiceGuilds.add(guildId);
802
+ else {
803
+ logger$6.warn(`discord voice: failed to hand off followed user session guild=${guildId} channel=${target.channelId}: ${result.message}`);
804
+ this.clearFollowedGuild(guildId);
805
+ await this.params.leave({ guildId });
806
+ }
807
+ return;
808
+ }
809
+ logger$6.info(`discord voice: followed user ${reason} guild=${guildId} user=${userId}; leaving channel=${existing.channelId}`);
810
+ await this.params.leave({ guildId });
811
+ } else if (!channelId && !existing && wasFollowedVoiceSession && this.params.hasVoiceLifecycle(guildId)) await this.params.leave({ guildId });
869
812
  return;
870
813
  }
871
814
  const followedChannel = {
@@ -877,24 +820,24 @@ var DiscordVoiceFollowing = class {
877
820
  this.followedVoiceGuilds.add(guildId);
878
821
  return;
879
822
  }
880
- const recoveryAttemptAt = this.params.getRecoveryAttempt(guildId);
823
+ const recoveryAttemptAt = this.params.daveRecoveryAttempts.get(guildId);
881
824
  if (!existing && previousFollowedChannelId === channelId && recoveryAttemptAt !== void 0) {
882
825
  if (Date.now() - recoveryAttemptAt < 3e4) {
883
- logger$7.warn(`discord voice: automatic follow suppressed during DAVE recovery cooldown guild=${guildId} channel=${channelId}; retry /vc join after the voice gateway recovers`);
826
+ logger$6.warn(`discord voice: automatic follow suppressed during DAVE recovery cooldown guild=${guildId} channel=${channelId}; retry /vc join after the voice gateway recovers`);
884
827
  return;
885
828
  }
886
- this.params.deleteRecoveryAttempt(guildId);
829
+ this.params.daveRecoveryAttempts.delete(guildId);
887
830
  }
888
- logger$7.info(`discord voice: following user guild=${guildId} user=${userId} channel=${channelId}`);
831
+ logger$6.info(`discord voice: following user guild=${guildId} user=${userId} channel=${channelId}`);
889
832
  const result = await this.params.join({
890
833
  guildId,
891
834
  channelId
892
835
  }, { preserveFollowState: true });
893
836
  if (this.followedUserChannels.get(followKey) !== followedChannel) return;
894
837
  if (!result.ok) {
895
- if (this.params.getSession(guildId)?.channelId === channelId) this.followedVoiceGuilds.add(guildId);
838
+ if (this.params.sessions.get(guildId)?.channelId === channelId) this.followedVoiceGuilds.add(guildId);
896
839
  else this.followedUserChannels.delete(followKey);
897
- logger$7.warn(`discord voice: failed to follow user guild=${guildId} user=${userId} channel=${channelId}: ${result.message}`);
840
+ logger$6.warn(`discord voice: failed to follow user guild=${guildId} user=${userId} channel=${channelId}: ${result.message}`);
898
841
  return;
899
842
  }
900
843
  this.followedVoiceGuilds.add(guildId);
@@ -917,7 +860,7 @@ var DiscordVoiceFollowing = class {
917
860
  for (const entries of [
918
861
  this.params.autoJoinChannels,
919
862
  this.params.allowedChannels ?? [],
920
- this.params.listSessions()
863
+ this.params.sessions.values()
921
864
  ]) for (const entry of entries) guildIds.add(entry.guildId);
922
865
  return Array.from(guildIds);
923
866
  }
@@ -936,9 +879,8 @@ var DiscordVoiceFollowing = class {
936
879
  logVoiceVerbose(`follow user reconcile skipped reason=${reason}: no Discord guild ids are configured`);
937
880
  return;
938
881
  }
939
- logFollowUserReconcileVerbose(reason, `follow user reconcile reason=${reason}: ${this.followUserIds.size} users across ${guildIds.length} guilds`);
940
882
  const userIds = [...this.followUserIds];
941
- const slotsPerGuild = userIds.length + (this.params.botUserId() ? 1 : 0);
883
+ const slotsPerGuild = userIds.length + (this.params.botUserId ? 1 : 0);
942
884
  const totalSlots = guildIds.length * slotsPerGuild;
943
885
  const start = this.reconcileCursor % totalSlots;
944
886
  const visitedGuilds = /* @__PURE__ */ new Set();
@@ -974,35 +916,19 @@ var DiscordVoiceFollowing = class {
974
916
  for (const entry of this.followedUserChannels.values()) if (entry.guildId === guildId && entry.channelId !== currentChannelId && this.params.isAllowedVoiceChannel(entry)) return entry;
975
917
  return null;
976
918
  }
977
- async handoffToAnotherFollowedUserOrLeave(params) {
978
- const target = this.resolveFollowedUserHandoffTarget(params.guildId, params.existing.channelId);
979
- if (target) {
980
- logger$7.info(`discord voice: followed user ${params.reason} guild=${params.guildId} user=${params.userId}; moving to remaining followed user channel=${target.channelId}`);
981
- const result = await this.params.join(target, { preserveFollowState: true });
982
- if (result.ok) this.followedVoiceGuilds.add(params.guildId);
983
- else {
984
- logger$7.warn(`discord voice: failed to hand off followed user session guild=${params.guildId} channel=${target.channelId}: ${result.message}`);
985
- this.clearFollowedGuild(params.guildId);
986
- await this.params.leave({ guildId: params.guildId });
987
- }
988
- return;
989
- }
990
- logger$7.info(`discord voice: followed user ${params.reason} guild=${params.guildId} user=${params.userId}; leaving channel=${params.existing.channelId}`);
991
- await this.params.leave({ guildId: params.guildId });
992
- }
993
919
  async disconnectStaleFollowedBotVoiceState(params) {
994
920
  if (this.scheduler.signal.aborted) return;
995
921
  const { guildId, reason } = params;
996
922
  if (Array.from(this.followedUserChannels.values()).some((entry) => entry.guildId === guildId)) return;
997
- const existing = this.params.getSession(guildId);
923
+ const existing = this.params.sessions.get(guildId);
998
924
  if (existing) {
999
925
  if (this.followedVoiceGuilds.has(guildId)) {
1000
- logger$7.info(`discord voice: follow reconcile leaving local session guild=${guildId} channel=${existing.channelId} reason=${reason}`);
926
+ logger$6.info(`discord voice: follow reconcile leaving local session guild=${guildId} channel=${existing.channelId} reason=${reason}`);
1001
927
  await this.params.leave({ guildId });
1002
928
  }
1003
929
  return;
1004
930
  }
1005
- const botUserId = this.params.botUserId();
931
+ const botUserId = this.params.botUserId;
1006
932
  if (!botUserId) return;
1007
933
  const botVoiceState = await this.readReconcileVoiceState(guildId, botUserId, reason, true);
1008
934
  if (this.scheduler.signal.aborted || botVoiceState === "transient-error") return;
@@ -1010,10 +936,10 @@ var DiscordVoiceFollowing = class {
1010
936
  if (!botChannelId) return;
1011
937
  const gateway = this.params.client.getPlugin("voice")?.getGateway(guildId);
1012
938
  if (!gateway) {
1013
- logger$7.warn(`discord voice: follow reconcile cannot disconnect stale bot voice state guild=${guildId} channel=${botChannelId}; gateway unavailable`);
939
+ logger$6.warn(`discord voice: follow reconcile cannot disconnect stale bot voice state guild=${guildId} channel=${botChannelId}; gateway unavailable`);
1014
940
  return;
1015
941
  }
1016
- logger$7.info(`discord voice: follow reconcile disconnecting stale bot voice state guild=${guildId} channel=${botChannelId} reason=${reason}`);
942
+ logger$6.info(`discord voice: follow reconcile disconnecting stale bot voice state guild=${guildId} channel=${botChannelId} reason=${reason}`);
1017
943
  gateway.updateVoiceState({
1018
944
  guild_id: guildId,
1019
945
  channel_id: null,
@@ -1032,10 +958,9 @@ var DiscordVoiceFollowing = class {
1032
958
  readReconcileVoiceState(guildId, userId, reason, isBot = false) {
1033
959
  return getGuildVoiceState(this.params.client.rest, guildId, userId).catch((err) => {
1034
960
  if (!isUnknownDiscordVoiceStateError(err)) {
1035
- 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)}`);
961
+ 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)}`);
1036
962
  return "transient-error";
1037
963
  }
1038
- 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)}`);
1039
964
  });
1040
965
  }
1041
966
  };
@@ -1077,40 +1002,15 @@ function finishVoiceCapture(state, userId, capture) {
1077
1002
  function scheduleVoiceCaptureFinalize(params) {
1078
1003
  const { state, userId, delayMs } = params;
1079
1004
  const capture = state.get(userId);
1080
- if (!capture) return false;
1005
+ if (!capture) return;
1081
1006
  clearVoiceCaptureFinalizeTimer(capture);
1082
1007
  capture.finalizeTimer = setTimeout(() => {
1083
1008
  if (!finishVoiceCapture(state, userId, capture)) return;
1084
1009
  capture.stream?.destroy();
1085
1010
  }, delayMs);
1086
- return true;
1087
- }
1088
- // extensions/discord/src/voice/sanitize.ts
1089
- const SPEECH_EMOJI_RE = /(?:\p{Extended_Pictographic}(?:\uFE0F|\u200D|\p{Extended_Pictographic}|\p{Emoji_Modifier})*)+/gu;
1090
- function sanitizeVoiceReplyTextForSpeech(text, speakerLabel) {
1091
- let cleaned = stripInlineDirectiveTagsForDisplay(text).text.trim();
1092
- if (!cleaned) return "";
1093
- const label = speakerLabel?.trim();
1094
- if (label) {
1095
- const prefix = new RegExp(`^${escapeRegExp(label)}\\s*:\\s*`, "i");
1096
- cleaned = cleaned.replace(prefix, "").trim();
1097
- }
1098
- return cleaned.replace(SPEECH_EMOJI_RE, " ").replace(/\s+([?!.,:;])/g, "$1").replace(/[ \t]{2,}/g, " ").replace(/ *\n */g, "\n").trim();
1099
1011
  }
1100
1012
  // extensions/discord/src/voice/tts.ts
1101
- async function transcribeVoiceAudio(params) {
1102
- const result = await getDiscordRuntime().mediaUnderstanding.transcribeAudioFile({
1103
- filePath: params.filePath,
1104
- cfg: params.cfg,
1105
- agentDir: resolveAgentDir(params.cfg, params.agentId),
1106
- mime: "audio/wav"
1107
- });
1108
- return {
1109
- text: normalizeOptionalString(result.text),
1110
- processing: result.decision?.attachmentProcessing?.[0],
1111
- 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)
1112
- };
1113
- }
1013
+ const SPEECH_EMOJI_RE = /(?:\p{Extended_Pictographic}(?:\uFE0F|\u200D|\p{Extended_Pictographic}|\p{Emoji_Modifier})*)+/gu;
1114
1014
  async function synthesizeVoiceReplyAudio(params) {
1115
1015
  const runtime = getDiscordRuntime();
1116
1016
  const prepared = await runtime.tts.prepareTtsRequest({
@@ -1119,7 +1019,15 @@ async function synthesizeVoiceReplyAudio(params) {
1119
1019
  text: params.replyText
1120
1020
  });
1121
1021
  const directive = prepared.directives;
1122
- const speakText = sanitizeVoiceReplyTextForSpeech(directive.overrides.ttsText ?? directive.cleanedText.trim(), params.speakerLabel);
1022
+ const rawSpeakText = directive.overrides.ttsText ?? directive.cleanedText.trim();
1023
+ let cleaned = stripInlineDirectiveTagsForDisplay(rawSpeakText).text.trim();
1024
+ if (!cleaned) return { status: "empty" };
1025
+ const label = params.speakerLabel?.trim();
1026
+ if (label) {
1027
+ const prefix = new RegExp(`^${escapeRegExp(label)}\\s*:\\s*`, "i");
1028
+ cleaned = cleaned.replace(prefix, "").trim();
1029
+ }
1030
+ const speakText = cleaned.replace(SPEECH_EMOJI_RE, " ").replace(/\s+([?!.,:;])/g, "$1").replace(/[ \t]{2,}/g, " ").replace(/ *\n */g, "\n").trim();
1123
1031
  if (!speakText) return { status: "empty" };
1124
1032
  const request = {
1125
1033
  text: speakText,
@@ -1127,18 +1035,17 @@ async function synthesizeVoiceReplyAudio(params) {
1127
1035
  channel: "discord",
1128
1036
  overrides: directive.overrides
1129
1037
  };
1130
- const streamResult = await runtime.tts.textToSpeechStream?.({
1038
+ const streamResult = await runtime.tts.textToSpeechStream({
1131
1039
  ...request,
1132
1040
  disableFallback: true
1133
1041
  });
1134
- if (streamResult?.success && streamResult.audioStream) return {
1042
+ if (streamResult.success && streamResult.audioStream) return {
1135
1043
  status: "ok",
1136
1044
  mode: "stream",
1137
1045
  audioStream: streamResult.audioStream,
1138
- release: streamResult.release,
1139
- speakText
1046
+ release: streamResult.release
1140
1047
  };
1141
- const streamFailure = streamResult && !streamResult.success ? streamResult.attempts?.findLast((attempt) => attempt.outcome === "failed") : void 0;
1048
+ const streamFailure = !streamResult.success ? streamResult.attempts?.findLast((attempt) => attempt.outcome === "failed") : void 0;
1142
1049
  const result = await runtime.tts.textToSpeech(request);
1143
1050
  if (!result.success || !result.audioPath) return {
1144
1051
  status: "failed",
@@ -1148,7 +1055,6 @@ async function synthesizeVoiceReplyAudio(params) {
1148
1055
  status: "ok",
1149
1056
  mode: "file",
1150
1057
  audioPath: result.audioPath,
1151
- speakText,
1152
1058
  ...streamFailure ? { streamFailure: {
1153
1059
  provider: streamFailure.provider,
1154
1060
  reasonCode: streamFailure.reasonCode
@@ -1156,13 +1062,12 @@ async function synthesizeVoiceReplyAudio(params) {
1156
1062
  };
1157
1063
  }
1158
1064
  // extensions/discord/src/voice/segment.ts
1159
- const logger$6 = createSubsystemLogger("discord/voice");
1065
+ const logger$5 = createSubsystemLogger("discord/voice");
1160
1066
  async function processDiscordVoiceSegment(params) {
1161
- const { entry, wavPath, userId, durationSeconds } = params;
1067
+ const { entry, wavPath, userId } = params;
1162
1068
  const conversationCurrent = () => !entry.captureOnly && entry.sessionLifecycle.status === "active" && params.isConversationCurrent();
1163
- logVoiceVerbose(`segment processing (${durationSeconds.toFixed(2)}s): guild ${entry.guildId} channel ${entry.channelId}`);
1164
1069
  const ingress = params.resolveIngressContext().catch((error) => {
1165
- logger$6.warn(`discord voice: conversation authorization failed: ${formatErrorMessage(error)}`);
1070
+ logger$5.warn(`discord voice: conversation authorization failed: ${formatErrorMessage(error)}`);
1166
1071
  return null;
1167
1072
  });
1168
1073
  const conversationAuthorized = ingress.then((context) => Boolean(context) && conversationCurrent());
@@ -1182,12 +1087,17 @@ async function processDiscordVoiceSegment(params) {
1182
1087
  admitted = await ingress;
1183
1088
  }
1184
1089
  if (!recording?.capture.isCurrent() && (!admitted || !conversationCurrent())) return { status: "excluded" };
1185
- const { text: transcript, processing, unavailable } = await transcribeVoiceAudio({
1186
- cfg: params.cfg,
1187
- agentId: entry.route.agentId,
1188
- filePath: wavPath
1090
+ const cfg = params.cfg;
1091
+ const agentId = entry.route.agentId;
1092
+ const result = await getDiscordRuntime().mediaUnderstanding.transcribeAudioFile({
1093
+ filePath: wavPath,
1094
+ cfg,
1095
+ agentDir: resolveAgentDir(cfg, agentId),
1096
+ mime: "audio/wav"
1189
1097
  });
1190
- if (unavailable) {
1098
+ const transcript = normalizeOptionalString(result.text);
1099
+ const processing = result.decision?.attachmentProcessing?.[0];
1100
+ 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)) {
1191
1101
  recording?.capture.onBatchUnavailable?.();
1192
1102
  return { status: "unavailable" };
1193
1103
  }
@@ -1199,8 +1109,6 @@ async function processDiscordVoiceSegment(params) {
1199
1109
  conversationAuthorized
1200
1110
  };
1201
1111
  }
1202
- logVoiceVerbose(`transcription ok (${transcript.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1203
- logVoiceVerbose(`transcript from ${speakerLabel} (${userId}) in guild ${entry.guildId} channel ${entry.channelId}: ${formatVoiceLogPreview(transcript)}`);
1204
1112
  if (recording?.capture.isCurrent()) await recording.capture.onUtterance({
1205
1113
  sessionId: recording.capture.sessionId,
1206
1114
  startedAt: new Date(recording.startedAt).toISOString(),
@@ -1236,16 +1144,14 @@ async function respondToDiscordVoiceTranscript(params) {
1236
1144
  text: transcript
1237
1145
  }).catch((error) => {
1238
1146
  if (readErrorName(error) === "AbortError") {
1239
- logger$6.warn(`discord voice: active-run control cancelled: ${formatErrorMessage(error)}`);
1147
+ logger$5.warn(`discord voice: active-run control cancelled: ${formatErrorMessage(error)}`);
1240
1148
  return null;
1241
1149
  }
1242
- logger$6.warn(`discord voice: active-run control failed; falling back to normal segment handling: ${formatErrorMessage(error)}`);
1150
+ logger$5.warn(`discord voice: active-run control failed; falling back to normal segment handling: ${formatErrorMessage(error)}`);
1243
1151
  });
1244
1152
  if (control === null || !conversationCurrent()) return;
1245
- if (control?.handled) {
1246
- 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}`);
1247
- replyText = control.speakText ?? "";
1248
- } else {
1153
+ if (control?.handled) replyText = control.speakText ?? "";
1154
+ else {
1249
1155
  const prompt = formatVoiceIngressPrompt(transcript, ingress.speakerLabel);
1250
1156
  const text = await runDiscordVoiceAgentTurn({
1251
1157
  ...params,
@@ -1263,7 +1169,6 @@ async function respondToDiscordVoiceTranscript(params) {
1263
1169
  logVoiceVerbose(`reply empty: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1264
1170
  return;
1265
1171
  }
1266
- logVoiceVerbose(`reply ok (${replyText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1267
1172
  const voiceReplyAudio = await synthesizeVoiceReplyAudio({
1268
1173
  cfg: params.cfg,
1269
1174
  override: params.discordConfig.voice?.tts,
@@ -1275,15 +1180,14 @@ async function respondToDiscordVoiceTranscript(params) {
1275
1180
  return;
1276
1181
  }
1277
1182
  if (voiceReplyAudio.status === "failed") {
1278
- logger$6.warn(`discord voice: TTS failed: ${voiceReplyAudio.error}`);
1183
+ logger$5.warn(`discord voice: TTS failed: ${voiceReplyAudio.error}`);
1279
1184
  return;
1280
1185
  }
1281
1186
  const streamFailure = voiceReplyAudio.mode === "file" ? voiceReplyAudio.streamFailure : void 0;
1282
1187
  if (streamFailure && !entry.ttsStreamFallbackWarned) {
1283
1188
  entry.ttsStreamFallbackWarned = true;
1284
- logger$6.warn(`discord voice: streaming TTS failed provider=${streamFailure.provider} reasonCode=${streamFailure.reasonCode}; using file fallback`);
1189
+ logger$5.warn(`discord voice: streaming TTS failed provider=${streamFailure.provider} reasonCode=${streamFailure.reasonCode}; using file fallback`);
1285
1190
  }
1286
- logVoiceVerbose(`tts ok (${voiceReplyAudio.speakText.length} chars): guild ${entry.guildId} channel ${entry.channelId}`);
1287
1191
  const releaseAudio = voiceReplyAudio.mode === "stream" ? voiceReplyAudio.release : () => unlinkIfExists(voiceReplyAudio.audioPath);
1288
1192
  if (entry.sessionLifecycle.status === "stopped") {
1289
1193
  await releaseAudio?.();
@@ -1293,9 +1197,7 @@ async function respondToDiscordVoiceTranscript(params) {
1293
1197
  try {
1294
1198
  if (entry.sessionLifecycle.status === "stopped") return;
1295
1199
  const input = voiceReplyAudio.mode === "stream" ? Readable.fromWeb(voiceReplyAudio.audioStream) : voiceReplyAudio.audioPath;
1296
- logVoiceVerbose(`playback start: guild ${entry.guildId} channel ${entry.channelId} ${voiceReplyAudio.mode}`);
1297
1200
  await entry.audio.play(input);
1298
- logVoiceVerbose("playback done: guild " + entry.guildId + " channel " + entry.channelId);
1299
1201
  } catch (error) {
1300
1202
  if (entry.sessionLifecycle.status !== "stopped") throw error;
1301
1203
  } finally {
@@ -1304,7 +1206,7 @@ async function respondToDiscordVoiceTranscript(params) {
1304
1206
  });
1305
1207
  }
1306
1208
  // extensions/discord/src/voice/voice-recording.ts
1307
- const logger$5 = createSubsystemLogger("discord/voice");
1209
+ const logger$4 = createSubsystemLogger("discord/voice");
1308
1210
  const PCM_BYTES_PER_MILLISECOND = 192;
1309
1211
  const MAX_PENDING_RECORDING_JOBS = 128;
1310
1212
  const MAX_PENDING_RECORDING_BYTES = 67108864;
@@ -1348,7 +1250,7 @@ var DiscordVoiceRecording = class {
1348
1250
  this.chunks = [];
1349
1251
  this.bytes = 0;
1350
1252
  this.overflow = /* @__PURE__ */ new Error("Discord voice audio exceeds the transcription limit; speak a shorter segment.");
1351
- logger$5.warn(`discord voice: ${this.overflow.message}`);
1253
+ logger$4.warn(`discord voice: ${this.overflow.message}`);
1352
1254
  throw this.overflow;
1353
1255
  }
1354
1256
  for (let offset = 0; offset < pcm.length;) {
@@ -1394,7 +1296,7 @@ var DiscordVoiceRecording = class {
1394
1296
  try {
1395
1297
  await wav.cleanup();
1396
1298
  } catch (error) {
1397
- logger$5.warn(`discord voice: recording cleanup failed: ${formatErrorMessage$1(error)}`);
1299
+ logger$4.warn(`discord voice: recording cleanup failed: ${formatErrorMessage$1(error)}`);
1398
1300
  } finally {
1399
1301
  releaseBudget();
1400
1302
  }
@@ -1412,14 +1314,13 @@ var DiscordVoiceRecording = class {
1412
1314
  return await processDiscordVoiceSegment({
1413
1315
  ...this.params,
1414
1316
  wavPath: wav.path,
1415
- durationSeconds: wav.durationSeconds,
1416
1317
  isConversationCurrent: this.params.canConverse,
1417
1318
  onConversationOnly: () => conversationOnly.resolve(),
1418
1319
  recording
1419
1320
  });
1420
1321
  } catch (error) {
1421
1322
  this.params.onExcluded();
1422
- logger$5.warn(`discord voice: recording failed: ${formatErrorMessage$1(error)}`);
1323
+ logger$4.warn(`discord voice: recording failed: ${formatErrorMessage$1(error)}`);
1423
1324
  return { status: "excluded" };
1424
1325
  } finally {
1425
1326
  await cleanup();
@@ -1430,9 +1331,7 @@ var DiscordVoiceRecording = class {
1430
1331
  }
1431
1332
  };
1432
1333
  // extensions/discord/src/voice/voice-receive.ts
1433
- const logger$4 = createSubsystemLogger("discord/voice");
1434
- const MAX_PENDING_OPUS_PACKETS = 1e3;
1435
- const MAX_PENDING_OPUS_BYTES = 1048576;
1334
+ const logger$3 = createSubsystemLogger("discord/voice");
1436
1335
  var DiscordVoiceReceive = class {
1437
1336
  constructor(params) {
1438
1337
  this.params = params;
@@ -1443,12 +1342,12 @@ var DiscordVoiceReceive = class {
1443
1342
  scheduleVoiceCaptureFinalize({
1444
1343
  state: entry.capture,
1445
1344
  userId,
1446
- delayMs: resolveVoiceTimeoutMs(this.params.discordConfig.voice?.captureSilenceGraceMs, CAPTURE_FINALIZE_GRACE_MS)
1345
+ delayMs: this.params.discordConfig.voice?.captureSilenceGraceMs ?? 2e3
1447
1346
  });
1448
1347
  }
1449
1348
  async handleSpeakingStart(entry, userId, origin = "native") {
1450
1349
  if (!userId || !this.params.isEntryCurrent(entry)) return;
1451
- if (userId === this.params.botUserId()) return;
1350
+ if (userId === this.params.botUserId) return;
1452
1351
  this.params.membership.notePresent(entry, userId);
1453
1352
  const activeCapture = entry.capture.get(userId);
1454
1353
  if (activeCapture) {
@@ -1489,7 +1388,7 @@ var DiscordVoiceReceive = class {
1489
1388
  }
1490
1389
  }
1491
1390
  captureCurrentSpeakers(entry) {
1492
- for (const userId of entry.audio.speakingUsers) this.handleSpeakingStart(entry, userId, "scan").catch((error) => logger$4.warn(`discord voice: capture failed: ${formatErrorMessage$1(error)}`));
1391
+ for (const userId of entry.audio.speakingUsers) this.handleSpeakingStart(entry, userId, "scan").catch((error) => logger$3.warn(`discord voice: capture failed: ${formatErrorMessage$1(error)}`));
1493
1392
  }
1494
1393
  responseContext(entry, userId) {
1495
1394
  return {
@@ -1497,7 +1396,7 @@ var DiscordVoiceReceive = class {
1497
1396
  entry,
1498
1397
  userId,
1499
1398
  enqueuePlayback: (playbackEntry, task) => {
1500
- playbackEntry.playbackQueue = playbackEntry.playbackQueue.then(task).catch((err) => logger$4.warn(`discord voice: playback failed: ${formatErrorMessage$1(err)}`));
1399
+ playbackEntry.playbackQueue = playbackEntry.playbackQueue.then(task).catch((err) => logger$3.warn(`discord voice: playback failed: ${formatErrorMessage$1(err)}`));
1501
1400
  }
1502
1401
  };
1503
1402
  }
@@ -1506,7 +1405,7 @@ var DiscordVoiceReceive = class {
1506
1405
  const protectedPlayback = () => entry.audio.playerStatus === "playing" && !realtime?.canReceiveDuringPlayback();
1507
1406
  entry.audio.enablePassthrough(`speaker ${userId} start`, 15);
1508
1407
  if (!entry.audioInputBudget.enabled && !realtime) {
1509
- logger$4.warn("discord voice: capture skipped: audio understanding is disabled; enable tools.media.audio.enabled to transcribe voice.");
1408
+ logger$3.warn("discord voice: capture skipped: audio understanding is disabled; enable tools.media.audio.enabled to transcribe voice.");
1510
1409
  return;
1511
1410
  }
1512
1411
  const captureReceipts = this.params.bindCaptureReceipts(entry);
@@ -1525,12 +1424,9 @@ var DiscordVoiceReceive = class {
1525
1424
  else stream.once("finalized", finalizeReservation);
1526
1425
  const input = new PassThrough({ objectMode: true });
1527
1426
  let failed = false;
1528
- let pendingPackets = 0;
1529
- let pendingBytes = 0;
1530
1427
  let resetReceiveRecovery = false;
1531
1428
  const acceptPacket = (frame) => {
1532
- const packetBytes = frame.packet.byteLength;
1533
- if (failed || !packetBytes || stream.destroyed) {
1429
+ if (failed || !frame.packet.byteLength || stream.destroyed) {
1534
1430
  stream.acknowledge(frame);
1535
1431
  return;
1536
1432
  }
@@ -1539,18 +1435,10 @@ var DiscordVoiceReceive = class {
1539
1435
  stream.acknowledge(frame);
1540
1436
  return;
1541
1437
  }
1542
- if (pendingPackets >= MAX_PENDING_OPUS_PACKETS || packetBytes > MAX_PENDING_OPUS_BYTES - pendingBytes) {
1543
- onError(/* @__PURE__ */ new Error("Discord voice receive backlog exceeded; try speaking again."));
1544
- input.destroy();
1545
- stream.destroy();
1546
- return;
1547
- }
1548
1438
  if (!resetReceiveRecovery && frame.pcm.byteLength > 0 && this.params.isEntryCurrent(entry)) {
1549
1439
  resetReceiveRecovery = true;
1550
1440
  this.resetDecryptFailureState(entry);
1551
1441
  }
1552
- pendingPackets += 1;
1553
- pendingBytes += packetBytes;
1554
1442
  const receipt = {
1555
1443
  capture,
1556
1444
  startedAt: frame.receivedAt,
@@ -1558,7 +1446,6 @@ var DiscordVoiceReceive = class {
1558
1446
  };
1559
1447
  input.write({
1560
1448
  pcm: Buffer.from(frame.pcm),
1561
- packetBytes,
1562
1449
  receipt,
1563
1450
  frame
1564
1451
  });
@@ -1589,7 +1476,7 @@ var DiscordVoiceReceive = class {
1589
1476
  isCurrent: () => this.params.isEntryCurrent(entry),
1590
1477
  canAdmit: () => !protectedPlayback(),
1591
1478
  createTurn: realtime ? (context) => realtime.beginSpeakerTurn(context, userId, realtimeRecording) : void 0,
1592
- warn: (message) => logger$4.warn(message)
1479
+ warn: (message) => logger$3.warn(message)
1593
1480
  }) : void 0;
1594
1481
  const recording = new DiscordVoiceRecording({
1595
1482
  entry,
@@ -1620,8 +1507,6 @@ var DiscordVoiceReceive = class {
1620
1507
  const frame = decoded;
1621
1508
  try {
1622
1509
  if (failed) continue;
1623
- pendingPackets -= 1;
1624
- pendingBytes -= frame.packetBytes;
1625
1510
  const { pcm, receipt } = frame;
1626
1511
  if (!receipt.capture && conversation && !conversation.ingress) {
1627
1512
  if (!await waitForVoiceCaptureAdmission({
@@ -1661,12 +1546,12 @@ var DiscordVoiceReceive = class {
1661
1546
  ingress: currentIngress,
1662
1547
  transcript
1663
1548
  });
1664
- }).catch((error) => logger$4.warn(`discord voice: processing failed: ${formatErrorMessage$1(error)}`));
1549
+ }).catch((error) => logger$3.warn(`discord voice: processing failed: ${formatErrorMessage$1(error)}`));
1665
1550
  }
1666
1551
  }
1667
1552
  } finally {
1668
1553
  realtimeRecording?.seal("batch");
1669
- if (conversationCompletion) conversationCompletion.catch((error) => logger$4.warn(`discord voice: conversation failed: ${formatErrorMessage$1(error)}`));
1554
+ if (conversationCompletion) conversationCompletion.catch((error) => logger$3.warn(`discord voice: conversation failed: ${formatErrorMessage$1(error)}`));
1670
1555
  else if (conversation) entry.conversations.release(conversation);
1671
1556
  captureReceipts.close();
1672
1557
  stream.off("data", acceptPacket);
@@ -1686,14 +1571,14 @@ var DiscordVoiceReceive = class {
1686
1571
  logVoiceVerbose(`receive decode skipped: ${analysis.message}`);
1687
1572
  return;
1688
1573
  }
1689
- logger$4.warn(`discord voice: receive error: ${analysis.message}`);
1574
+ logger$3.warn(`discord voice: receive error: ${analysis.message}`);
1690
1575
  if (err instanceof Error && "daveRecoveryFailed" in err && err.daveRecoveryFailed === true) {
1691
1576
  this.startDecryptRecovery(entry, true);
1692
1577
  return;
1693
1578
  }
1694
1579
  if (!analysis.countsAsDecryptFailure) return;
1695
1580
  const decryptFailure = noteVoiceDecryptFailure(entry.receiveRecovery);
1696
- if (decryptFailure.firstFailure) logger$4.warn("discord voice: DAVE decrypt failures detected; voice receive may be unstable (upstream: discordjs/discord.js#11419)");
1581
+ if (decryptFailure.firstFailure) logger$3.warn("discord voice: DAVE decrypt failures detected; voice receive may be unstable (upstream: discordjs/discord.js#11419)");
1697
1582
  if (!decryptFailure.shouldRecover) return;
1698
1583
  this.startDecryptRecovery(entry);
1699
1584
  }
@@ -1701,8 +1586,7 @@ var DiscordVoiceReceive = class {
1701
1586
  return await resolveDiscordVoiceIngressContextWithParticipants({
1702
1587
  ...this.params,
1703
1588
  entry,
1704
- userId,
1705
- botUserId: this.params.botUserId()
1589
+ userId
1706
1590
  });
1707
1591
  }
1708
1592
  async runDiscordRealtimeAgentTurn(params) {
@@ -1711,7 +1595,7 @@ var DiscordVoiceReceive = class {
1711
1595
  const currentContext = await this.resolveDiscordVoiceIngressContext(entry, userId);
1712
1596
  params.signal?.throwIfAborted();
1713
1597
  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");
1714
- 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)}`);
1598
+ 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}`);
1715
1599
  const text = await runDiscordVoiceAgentTurn({
1716
1600
  ...this.params,
1717
1601
  ...params,
@@ -1721,27 +1605,27 @@ var DiscordVoiceReceive = class {
1721
1605
  logVoiceVerbose(`realtime agent unauthorized: guild ${entry.guildId} channel ${entry.channelId} user ${userId}`);
1722
1606
  return "";
1723
1607
  }
1724
- 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)}`);
1608
+ 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}`);
1725
1609
  return text;
1726
1610
  }
1727
1611
  startDecryptRecovery(entry, force = false) {
1728
1612
  let recovery;
1729
1613
  if (force) {
1730
- if (this.params.getSession(entry.guildId) !== entry || entry.sessionLifecycle.status === "stopped" || entry.receiveRecovery.decryptRecoveryInFlight) return;
1614
+ if (this.params.sessions.get(entry.guildId) !== entry || entry.sessionLifecycle.status === "stopped" || entry.receiveRecovery.decryptRecoveryInFlight) return;
1731
1615
  const now = Date.now();
1732
1616
  for (const [guildId, attemptedAt] of this.daveRecoveryAttempts) if (now - attemptedAt >= 3e4) this.daveRecoveryAttempts.delete(guildId);
1733
1617
  resetVoiceReceiveRecoveryState(entry.receiveRecovery);
1734
1618
  entry.receiveRecovery.decryptRecoveryInFlight = true;
1735
1619
  if (this.daveRecoveryAttempts.has(entry.guildId)) {
1736
1620
  const windowSeconds = DECRYPT_FAILURE_WINDOW_MS / 1e3;
1737
- 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`);
1621
+ 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`);
1738
1622
  recovery = this.params.leave({ guildId: entry.guildId }, { preserveFollowState: this.params.isFollowOwnedGuild(entry.guildId) });
1739
1623
  } else {
1740
1624
  this.daveRecoveryAttempts.set(entry.guildId, now);
1741
1625
  recovery = this.recoverFromDecryptFailures(entry);
1742
1626
  }
1743
1627
  } else recovery = this.recoverFromDecryptFailures(entry);
1744
- recovery.catch((recoverErr) => logger$4.warn(`discord voice: decrypt recovery failed: ${formatErrorMessage$1(recoverErr)}`)).finally(() => {
1628
+ recovery.catch((recoverErr) => logger$3.warn(`discord voice: decrypt recovery failed: ${formatErrorMessage$1(recoverErr)}`)).finally(() => {
1745
1629
  entry.receiveRecovery.decryptRecoveryInFlight = false;
1746
1630
  });
1747
1631
  }
@@ -1750,13 +1634,13 @@ var DiscordVoiceReceive = class {
1750
1634
  if (this.params.isEntryCurrent(entry)) this.daveRecoveryAttempts.delete(entry.guildId);
1751
1635
  }
1752
1636
  async recoverFromDecryptFailures(entry) {
1753
- const active = this.params.getSession(entry.guildId);
1637
+ const active = this.params.sessions.get(entry.guildId);
1754
1638
  if (!active || active.audio !== entry.audio) return;
1755
1639
  const preserveFollowState = this.params.isFollowOwnedGuild(entry.guildId);
1756
- logger$4.warn(`discord voice: repeated decrypt failures; attempting rejoin for guild ${entry.guildId} channel ${entry.channelId}`);
1640
+ logger$3.warn(`discord voice: repeated decrypt failures; attempting rejoin for guild ${entry.guildId} channel ${entry.channelId}`);
1757
1641
  const leaveResult = await this.params.leave({ guildId: entry.guildId }, { preserveFollowState });
1758
1642
  if (!leaveResult.ok) {
1759
- logger$4.warn(`discord voice: decrypt recovery leave failed: ${leaveResult.message}`);
1643
+ logger$3.warn(`discord voice: decrypt recovery leave failed: ${leaveResult.message}`);
1760
1644
  return;
1761
1645
  }
1762
1646
  const result = await this.params.join({
@@ -1767,21 +1651,13 @@ var DiscordVoiceReceive = class {
1767
1651
  autoJoinWhenOccupied: entry.autoJoinWhenOccupied,
1768
1652
  captureOnly: entry.captureOnly
1769
1653
  });
1770
- if (!result.ok) logger$4.warn(`discord voice: rejoin after decrypt failures failed: ${result.message}`);
1654
+ if (!result.ok) logger$3.warn(`discord voice: rejoin after decrypt failures failed: ${result.message}`);
1771
1655
  }
1772
1656
  };
1773
1657
  // extensions/discord/src/voice/audio-worker-thread.ts
1774
1658
  /** Source, core-bundled and standalone plugin workers use the same launch owner. */
1775
1659
  function createDiscordAudioWorkerThread(options) {
1776
- const url = resolveRuntimeWorkerUrl({
1777
- currentModuleUrl: import.meta.url,
1778
- sourceWorkerName: "audio-worker.runtime",
1779
- distWorkerPath: "extensions/discord/src/voice/audio-worker.runtime.js",
1780
- package: {
1781
- name: "@openclaw/discord",
1782
- distWorkerPath: "src/voice/audio-worker.runtime.js"
1783
- }
1784
- });
1660
+ const url = resolveRuntimeWorkerUrl(createPluginRuntimeProcessEntrypoint("discordAudio", import.meta.url));
1785
1661
  const workerOptions = {
1786
1662
  workerData: options,
1787
1663
  execArgv: resolveRuntimeWorkerArgv(url).slice(0, -1)
@@ -1789,7 +1665,7 @@ function createDiscordAudioWorkerThread(options) {
1789
1665
  return createCpuTrackedWorker(url, workerOptions);
1790
1666
  }
1791
1667
  // extensions/discord/src/voice/audio-transport.ts
1792
- const logger$3 = createSubsystemLogger("discord/voice");
1668
+ const logger$2 = createSubsystemLogger("discord/voice");
1793
1669
  const STOP_GRACE_MS = 2e3;
1794
1670
  /** A received frame owns cloned PCM; its credit remains held until the consumer settles. */
1795
1671
  var DiscordAudioCapture = class extends Readable {
@@ -1832,7 +1708,6 @@ var DiscordAudioTransport = class extends EventEmitter {
1832
1708
  super();
1833
1709
  this.speakingUsers = /* @__PURE__ */ new Set();
1834
1710
  this.playerStatus = "idle";
1835
- this.connectionStatus = "signalling";
1836
1711
  this.captures = /* @__PURE__ */ new Map();
1837
1712
  this.files = /* @__PURE__ */ new Map();
1838
1713
  this.nextId = 0;
@@ -1968,15 +1843,9 @@ var DiscordAudioTransport = class extends EventEmitter {
1968
1843
  this.stopping = true;
1969
1844
  this.send({ type: "stop" });
1970
1845
  const drained = (async () => {
1971
- let timer;
1972
1846
  try {
1973
- await Promise.race([this.exited, new Promise((resolve) => {
1974
- timer = setTimeout(() => {
1975
- this.worker.terminate().then(() => resolve());
1976
- }, STOP_GRACE_MS);
1977
- })]);
1847
+ await raceWithTimeout(this.exited, STOP_GRACE_MS, () => this.worker.terminate());
1978
1848
  } finally {
1979
- clearTimeout(timer);
1980
1849
  this.finish(/* @__PURE__ */ new Error("Discord voice session stopped."));
1981
1850
  }
1982
1851
  })();
@@ -2000,7 +1869,6 @@ var DiscordAudioTransport = class extends EventEmitter {
2000
1869
  this.finish(/* @__PURE__ */ new Error("Discord voice session stopped."), true);
2001
1870
  break;
2002
1871
  case "connection":
2003
- this.connectionStatus = event.status;
2004
1872
  if (event.status === "destroyed") this.emit("stopped");
2005
1873
  break;
2006
1874
  case "player":
@@ -2013,11 +1881,7 @@ var DiscordAudioTransport = class extends EventEmitter {
2013
1881
  break;
2014
1882
  case "capture-frame": {
2015
1883
  const capture = this.captures.get(event.id);
2016
- if (capture && !capture.destroyed) capture.push({
2017
- ...event.frame,
2018
- pcm: Buffer.from(event.frame.pcm),
2019
- packet: Buffer.from(event.frame.packet)
2020
- });
1884
+ if (capture && !capture.destroyed) capture.push(event.frame);
2021
1885
  break;
2022
1886
  }
2023
1887
  case "capture-error":
@@ -2049,9 +1913,9 @@ var DiscordAudioTransport = class extends EventEmitter {
2049
1913
  }
2050
1914
  case "error":
2051
1915
  this.readiness.reject(restoreDiscordAudioError(event.error));
2052
- logger$3.warn("discord voice: " + event.error.message);
1916
+ logger$2.warn("discord voice: audio worker failed", { code: event.error.code });
2053
1917
  break;
2054
- case "log": if (event.level === "warn") logger$3.warn(event.message);
1918
+ case "log": if (event.level === "warn") logger$2.warn(event.message);
2055
1919
  else logVerbose(event.message);
2056
1920
  }
2057
1921
  if (!this.stopping) this.emit("event", event);
@@ -2064,7 +1928,6 @@ var DiscordAudioTransport = class extends EventEmitter {
2064
1928
  finish(error, drained = false) {
2065
1929
  if (this.terminal) return;
2066
1930
  this.terminal = true;
2067
- this.connectionStatus = "destroyed";
2068
1931
  this.playerStatus = "idle";
2069
1932
  this.readiness.reject(error);
2070
1933
  this.destroyAdapter();
@@ -2138,7 +2001,7 @@ var DiscordVoiceConversationInput = class {
2138
2001
  }
2139
2002
  this.pendingAudioBytes += pcm.length;
2140
2003
  if (this.params.createTurn) this.audio.push({
2141
- pcm: Buffer.from(pcm),
2004
+ pcm,
2142
2005
  receipt
2143
2006
  });
2144
2007
  return;
@@ -2257,43 +2120,8 @@ var DiscordVoiceConversationQueue = class {
2257
2120
  this.inputs.clear();
2258
2121
  }
2259
2122
  };
2260
- // extensions/discord/src/voice/voice-route.ts
2261
- function resolveDiscordVoiceAgentRoute(params) {
2262
- const voiceRoute = resolveAgentRoute({
2263
- ...params,
2264
- channel: "discord",
2265
- peer: {
2266
- kind: "channel",
2267
- id: params.sessionChannelId
2268
- }
2269
- });
2270
- const agentSession = params.voiceConfig?.agentSession;
2271
- if (agentSession?.mode !== "target") return {
2272
- route: voiceRoute,
2273
- voiceRoute,
2274
- agentSessionMode: "voice",
2275
- agentSessionTarget: void 0
2276
- };
2277
- const target = agentSession.target?.trim();
2278
- if (!target) throw new Error("channels.discord.voice.agentSession.target is required when mode is \"target\"");
2279
- const parsed = parseDiscordTarget(target, { defaultKind: "channel" });
2280
- if (!parsed) throw new Error(`Invalid Discord voice agent session target "${target}"`);
2281
- return {
2282
- route: resolveAgentRoute({
2283
- ...params,
2284
- channel: "discord",
2285
- peer: {
2286
- kind: parsed.kind === "user" ? "direct" : "channel",
2287
- id: parsed.id
2288
- }
2289
- }),
2290
- voiceRoute,
2291
- agentSessionMode: "target",
2292
- agentSessionTarget: parsed.normalized
2293
- };
2294
- }
2295
2123
  // extensions/discord/src/voice/voice-session.ts
2296
- const logger$2 = createSubsystemLogger("discord/voice");
2124
+ const logger$1 = createSubsystemLogger("discord/voice");
2297
2125
  function isVoiceSessionStopped(entry) {
2298
2126
  return entry.sessionLifecycle.status === "stopped";
2299
2127
  }
@@ -2315,7 +2143,7 @@ var DiscordVoiceSessions = class {
2315
2143
  refreshGuildRoster(guildId) {
2316
2144
  const entry = this.params.sessions.get(guildId.trim());
2317
2145
  if (!entry || entry.sessionLifecycle.status === "stopped") return;
2318
- this.params.membership.activate(entry, this.params.botUserId());
2146
+ this.params.membership.activate(entry, this.params.botUserId);
2319
2147
  }
2320
2148
  async resolveChannel({ guildId, channelId }) {
2321
2149
  let channelInfo;
@@ -2366,11 +2194,11 @@ var DiscordVoiceSessions = class {
2366
2194
  if (existing && existing.channelId === channelId) {
2367
2195
  if (authority) existing.generation = authority.generation;
2368
2196
  if ((!options?.captureOnly || !existing.captureOnly) && isDiscordRealtimeVoiceMode(voiceMode) && existing.realtimeLifecycle.status !== "active" && existing.realtimeLifecycle.status !== "starting") {
2369
- const realtimeResult = await this.attachRealtimeSession(existing, voiceMode, {
2197
+ const realtimeError = await this.attachRealtimeSession(existing, voiceMode, {
2370
2198
  requireLiveEntry: true,
2371
2199
  isCurrent: authority?.isCurrent
2372
2200
  });
2373
- if (!realtimeResult.ok) return failedJoinResult(realtimeResult.message);
2201
+ if (realtimeError) return failedJoinResult(realtimeError);
2374
2202
  }
2375
2203
  logVoiceVerbose(`join: already connected to guild ${guildId} channel ${channelId}`);
2376
2204
  return {
@@ -2401,8 +2229,8 @@ var DiscordVoiceSessions = class {
2401
2229
  const adapterCreator = voicePlugin.getGatewayAdapterCreator(guildId);
2402
2230
  const daveEncryption = voiceConfig?.daveEncryption;
2403
2231
  const decryptionFailureTolerance = voiceConfig?.decryptionFailureTolerance;
2404
- const connectReadyTimeoutMs = resolveVoiceTimeoutMs(voiceConfig?.connectTimeoutMs, VOICE_CONNECT_READY_TIMEOUT_MS);
2405
- const reconnectGraceMs = resolveVoiceTimeoutMs(voiceConfig?.reconnectGraceMs, VOICE_RECONNECT_GRACE_MS);
2232
+ const connectReadyTimeoutMs = voiceConfig?.connectTimeoutMs ?? 3e4;
2233
+ const reconnectGraceMs = voiceConfig?.reconnectGraceMs ?? 15e3;
2406
2234
  logVoiceVerbose(`join: DAVE settings encryption=${daveEncryption === false ? "off" : "on"} tolerance=${decryptionFailureTolerance ?? "default"} connectTimeout=${connectReadyTimeoutMs}ms reconnectGrace=${reconnectGraceMs}ms`);
2407
2235
  await this.stopTransport(guildId);
2408
2236
  if (this.params.destroyed() || authority?.isCurrent() === false) return failedJoinResult("Discord voice join was cancelled.");
@@ -2416,7 +2244,7 @@ var DiscordVoiceSessions = class {
2416
2244
  decryptionFailureTolerance,
2417
2245
  connectTimeoutMs: connectReadyTimeoutMs,
2418
2246
  reconnectGraceMs,
2419
- captureSilenceGraceMs: resolveVoiceTimeoutMs(voiceConfig?.captureSilenceGraceMs, CAPTURE_FINALIZE_GRACE_MS),
2247
+ captureSilenceGraceMs: voiceConfig?.captureSilenceGraceMs ?? 2e3,
2420
2248
  realtime: isDiscordRealtimeVoiceMode(voiceMode)
2421
2249
  }, adapterCreator);
2422
2250
  this.transports.set(guildId, audio);
@@ -2430,22 +2258,50 @@ var DiscordVoiceSessions = class {
2430
2258
  await this.stopTransport(guildId);
2431
2259
  return failedJoinResult("Discord voice join was cancelled.");
2432
2260
  }
2433
- const sessionChannelId = channelInfo?.id ?? channelId;
2261
+ const sessionChannelId = channelInfo.id;
2434
2262
  if (sessionChannelId !== channelId) logVoiceVerbose(`join: using session channel ${sessionChannelId} for voice channel ${channelId}`);
2435
- let routeInfo;
2263
+ let route;
2264
+ let voiceRoute;
2265
+ let agentSessionMode = "voice";
2266
+ let agentSessionTarget;
2436
2267
  try {
2437
- routeInfo = resolveDiscordVoiceAgentRoute({
2268
+ const routeParams = {
2438
2269
  ...this.params,
2439
2270
  guildId,
2440
2271
  sessionChannelId,
2441
2272
  voiceConfig
2273
+ };
2274
+ voiceRoute = resolveAgentRoute({
2275
+ ...routeParams,
2276
+ channel: "discord",
2277
+ peer: {
2278
+ kind: "channel",
2279
+ id: sessionChannelId
2280
+ }
2442
2281
  });
2282
+ route = voiceRoute;
2283
+ const agentSession = routeParams.voiceConfig?.agentSession;
2284
+ if (agentSession?.mode === "target") {
2285
+ const target = agentSession.target?.trim();
2286
+ if (!target) throw new Error("channels.discord.voice.agentSession.target is required when mode is \"target\"");
2287
+ const parsed = parseDiscordTarget(target, { defaultKind: "channel" });
2288
+ if (!parsed) throw new Error(`Invalid Discord voice agent session target "${target}"`);
2289
+ route = resolveAgentRoute({
2290
+ ...routeParams,
2291
+ channel: "discord",
2292
+ peer: {
2293
+ kind: parsed.kind === "user" ? "direct" : "channel",
2294
+ id: parsed.id
2295
+ }
2296
+ });
2297
+ agentSessionMode = "target";
2298
+ agentSessionTarget = parsed.normalized;
2299
+ }
2443
2300
  } catch (err) {
2444
2301
  await this.stopTransport(guildId);
2445
2302
  return failedJoinResult(`Failed to resolve Discord voice agent session: ${formatErrorMessage$1(err)}`);
2446
2303
  }
2447
- const { route, voiceRoute, agentSessionMode, agentSessionTarget } = routeInfo;
2448
- 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"}`);
2304
+ 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"}`);
2449
2305
  let stopCompletion;
2450
2306
  const stopEntry = (reason, disposition = "abort") => {
2451
2307
  if (entry.sessionLifecycle.status === "stopped") return stopCompletion;
@@ -2461,14 +2317,13 @@ var DiscordVoiceSessions = class {
2461
2317
  const realtimeLifecycle = entry.realtimeLifecycle;
2462
2318
  entry.realtimeLifecycle = {
2463
2319
  status: "stopped",
2464
- generation: realtimeLifecycle.generation,
2465
2320
  reason
2466
2321
  };
2467
2322
  let realtimeCompletion = void 0;
2468
2323
  try {
2469
2324
  if (realtimeLifecycle.status === "starting" || realtimeLifecycle.status === "active") realtimeCompletion = realtimeLifecycle.instance.close(disposition);
2470
2325
  } catch (error) {
2471
- logger$2.warn(`discord voice: realtime close failed: ${formatErrorMessage$1(error)}`);
2326
+ logger$1.warn(`discord voice: realtime close failed: ${formatErrorMessage$1(error)}`);
2472
2327
  }
2473
2328
  const audioCompletion = this.stopTransport(guildId, audio);
2474
2329
  stopCompletion = Promise.allSettled([realtimeCompletion, audioCompletion]).then(() => {
@@ -2482,7 +2337,7 @@ var DiscordVoiceSessions = class {
2482
2337
  };
2483
2338
  completion.then(forget, (error) => {
2484
2339
  forget();
2485
- logger$2.warn(`discord voice: session stop failed: ${formatErrorMessage$1(error)}`);
2340
+ logger$1.warn(`discord voice: session stop failed: ${formatErrorMessage$1(error)}`);
2486
2341
  });
2487
2342
  return stopCompletion;
2488
2343
  };
@@ -2493,10 +2348,9 @@ var DiscordVoiceSessions = class {
2493
2348
  autoJoinWhenOccupied: options?.autoJoinWhenOccupied === true,
2494
2349
  sessionLifecycle: { status: "active" },
2495
2350
  guildId,
2496
- guildName: channelInfo && "guild" in channelInfo && channelInfo.guild && typeof channelInfo.guild.name === "string" ? channelInfo.guild.name : void 0,
2351
+ guildName: channelInfo.guild?.name,
2497
2352
  channelId,
2498
- channelName: channelInfo && "name" in channelInfo && typeof channelInfo.name === "string" ? channelInfo.name : void 0,
2499
- sessionChannelId,
2353
+ channelName: channelInfo.name,
2500
2354
  voiceSessionKey: voiceRoute.sessionKey,
2501
2355
  route,
2502
2356
  audio,
@@ -2514,17 +2368,14 @@ var DiscordVoiceSessions = class {
2514
2368
  lastDecryptFailureAt: 0,
2515
2369
  decryptRecoveryInFlight: false
2516
2370
  },
2517
- realtimeLifecycle: {
2518
- status: "inactive",
2519
- generation: 0
2520
- },
2371
+ realtimeLifecycle: { status: "inactive" },
2521
2372
  stop(reason, disposition) {
2522
2373
  return stopEntry(reason ?? `stop guild ${guildId} channel ${channelId}`, disposition);
2523
2374
  }
2524
2375
  };
2525
2376
  const speakingHandler = (userId, speaking) => {
2526
2377
  if (speaking) this.params.receive.handleSpeakingStart(entry, userId).catch((error) => {
2527
- logger$2.warn("discord voice: capture failed: " + formatErrorMessage$1(error));
2378
+ logger$1.warn("discord voice: capture failed: " + formatErrorMessage$1(error));
2528
2379
  });
2529
2380
  else this.params.receive.scheduleCaptureFinalize(entry, userId);
2530
2381
  };
@@ -2533,10 +2384,10 @@ var DiscordVoiceSessions = class {
2533
2384
  };
2534
2385
  audio.on("stopped", destroyedHandler);
2535
2386
  if (!entry.captureOnly && isDiscordRealtimeVoiceMode(voiceMode)) {
2536
- const realtimeResult = await this.attachRealtimeSession(entry, voiceMode, { isCurrent: authority?.isCurrent });
2537
- if (!realtimeResult.ok) {
2387
+ const realtimeError = await this.attachRealtimeSession(entry, voiceMode, { isCurrent: authority?.isCurrent });
2388
+ if (realtimeError) {
2538
2389
  await entry.stop(`realtime setup failed guild ${guildId} channel ${channelId}`);
2539
- return failedJoinResult(realtimeResult.message);
2390
+ return failedJoinResult(realtimeError);
2540
2391
  }
2541
2392
  }
2542
2393
  if (isVoiceSessionStopped(entry) || this.params.destroyed() || authority && !authority.isCurrent()) {
@@ -2546,8 +2397,8 @@ var DiscordVoiceSessions = class {
2546
2397
  entry.audio.enablePassthrough("post-join warmup", 30);
2547
2398
  audio.on("speaking", speakingHandler);
2548
2399
  this.params.sessions.set(guildId, entry);
2549
- this.params.membership.activate(entry, this.params.botUserId());
2550
- 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"}`);
2400
+ this.params.membership.activate(entry, this.params.botUserId);
2401
+ 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"}`);
2551
2402
  return {
2552
2403
  ok: true,
2553
2404
  message: `Joined ${formatMention({ channelId })}.`,
@@ -2585,24 +2436,20 @@ var DiscordVoiceSessions = class {
2585
2436
  entry
2586
2437
  });
2587
2438
  const isCurrent = () => !isVoiceSessionStopped(entry) && options?.isCurrent?.() !== false && (options?.requireLiveEntry !== true || this.params.sessions.get(entry.guildId) === entry);
2588
- if (!isCurrent()) return {
2589
- ok: false,
2590
- message: "Discord realtime voice session stopped before startup completed."
2591
- };
2592
- const { DiscordRealtimeVoiceSession } = await import("./realtime-session.runtime-cetognkp.mjs");
2439
+ if (!isCurrent()) return "Discord realtime voice session stopped before startup completed.";
2440
+ const { DiscordRealtimeVoiceSession } = await import("./realtime-session.runtime-WJL6NdwK.mjs");
2593
2441
  const realtime = new DiscordRealtimeVoiceSession({
2594
2442
  ...this.params,
2595
2443
  bootstrapContextInstructions,
2596
2444
  entry,
2597
- getHumanParticipantCount: () => this.params.membership.countHumanParticipants(entry, this.params.botUserId()),
2445
+ getHumanParticipantCount: () => this.params.membership.countHumanParticipants(entry, this.params.botUserId),
2598
2446
  mode: voiceMode,
2599
2447
  onTerminalError: (error) => {
2600
- logger$2.error(`discord voice: realtime session failed terminally guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2448
+ logger$1.error(`discord voice: realtime session failed terminally guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2601
2449
  const lifecycle = entry.realtimeLifecycle;
2602
2450
  if (options?.requireLiveEntry && lifecycle.status === "starting" && lifecycle.instance === realtime) {
2603
2451
  entry.realtimeLifecycle = {
2604
2452
  status: "stopped",
2605
- generation: lifecycle.generation,
2606
2453
  reason: "realtime terminal error"
2607
2454
  };
2608
2455
  realtime.close();
@@ -2620,103 +2467,44 @@ var DiscordVoiceSessions = class {
2620
2467
  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");
2621
2468
  };
2622
2469
  assertCurrent();
2623
- const { sendMessageDiscord } = await import("./send.outbound-CGhBhzjQ.mjs").then((n) => n.i);
2470
+ const { sendMessageDiscord } = await import("./send.outbound-B11X6TOE.mjs").then((n) => n.i);
2624
2471
  await sendMessageDiscord(`channel:${entry.channelId}`, text, {
2625
2472
  cfg: this.params.cfg,
2626
2473
  accountId: this.params.accountId,
2627
2474
  assertPlatformSendAuthorized: assertCurrent
2628
2475
  });
2629
2476
  } catch (error) {
2630
- logger$2.warn(`discord voice: text fallback dropped guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2477
+ logger$1.warn(`discord voice: text fallback dropped guild=${entry.guildId} channel=${entry.channelId}: ${formatErrorMessage$1(error)}`);
2631
2478
  }
2632
2479
  },
2633
2480
  resolveSpeakerContext: (userId) => this.params.receive.resolveDiscordVoiceIngressContext(entry, userId)
2634
2481
  });
2635
- const generation = entry.realtimeLifecycle.generation + 1;
2636
2482
  entry.realtimeLifecycle = {
2637
2483
  status: "starting",
2638
- generation,
2639
2484
  instance: realtime
2640
2485
  };
2641
2486
  try {
2642
2487
  await realtime.connect();
2643
- if (entry.realtimeLifecycle.status !== "starting" || entry.realtimeLifecycle.generation !== generation || entry.realtimeLifecycle.instance !== realtime || !isCurrent()) {
2488
+ if (entry.realtimeLifecycle.status !== "starting" || entry.realtimeLifecycle.instance !== realtime || !isCurrent()) {
2644
2489
  await realtime.close();
2645
- return {
2646
- ok: false,
2647
- message: "Discord realtime voice session stopped before startup completed."
2648
- };
2490
+ return "Discord realtime voice session stopped before startup completed.";
2649
2491
  }
2650
2492
  entry.realtimeLifecycle = {
2651
2493
  status: "active",
2652
- generation,
2653
2494
  instance: realtime
2654
2495
  };
2655
- return { ok: true };
2496
+ return;
2656
2497
  } catch (err) {
2657
2498
  await realtime.close();
2658
- if (entry.realtimeLifecycle.status === "starting" && entry.realtimeLifecycle.generation === generation) entry.realtimeLifecycle = {
2499
+ if (entry.realtimeLifecycle.status === "starting" && entry.realtimeLifecycle.instance === realtime) entry.realtimeLifecycle = {
2659
2500
  status: "stopped",
2660
- generation,
2661
2501
  reason: "connect failed"
2662
2502
  };
2663
- return {
2664
- ok: false,
2665
- message: `Failed to start Discord realtime voice: ${formatErrorMessage$1(err)}`
2666
- };
2503
+ return `Failed to start Discord realtime voice: ${formatErrorMessage$1(err)}`;
2667
2504
  }
2668
2505
  }
2669
2506
  };
2670
- // extensions/discord/src/voice/listeners.ts
2671
- const logger$1 = createSubsystemLogger("discord/voice");
2672
- function startAutoJoin(operation, context = "") {
2673
- operation().catch((err) => logger$1.warn(`discord voice: autoJoin${context} failed: ${formatErrorMessage$1(err)}`));
2674
- }
2675
- var DiscordVoiceReadyListener = class {
2676
- constructor(manager) {
2677
- this.manager = manager;
2678
- this.type = discord_exports.GatewayDispatchEvents.Ready;
2679
- }
2680
- async handle(_data, _client) {
2681
- startAutoJoin(() => this.manager.autoJoin());
2682
- }
2683
- };
2684
- var DiscordVoiceResumedListener = class extends DiscordVoiceReadyListener {
2685
- constructor(..._args) {
2686
- super(..._args);
2687
- this.type = discord_exports.GatewayDispatchEvents.Resumed;
2688
- }
2689
- };
2690
- var DiscordVoiceGuildCreateListener = class {
2691
- constructor(manager) {
2692
- this.manager = manager;
2693
- this.type = discord_exports.GatewayDispatchEvents.GuildCreate;
2694
- }
2695
- async handle(data, _client) {
2696
- if (!data.unavailable) {
2697
- this.manager.refreshGuildRoster(data.id);
2698
- startAutoJoin(() => this.manager.reconcileAutoJoinGuild(data.id), ` occupancy reconciliation guild=${data.id}`);
2699
- }
2700
- }
2701
- };
2702
- var DiscordVoiceStateUpdateListener = class extends VoiceStateUpdateListener {
2703
- constructor(manager) {
2704
- super();
2705
- this.manager = manager;
2706
- }
2707
- async handle(data, client) {
2708
- const transition = client.getPlugin("gateway")?.takeVoiceStateTransition(data);
2709
- await this.manager.handleVoiceStateUpdate(data, transition ? transition.previous ?? null : void 0);
2710
- }
2711
- };
2712
2507
  // extensions/discord/src/voice/voice-runtime.ts
2713
- var voice_runtime_exports = /* @__PURE__ */ __exportAll({
2714
- DiscordVoiceGuildCreateListener: () => DiscordVoiceGuildCreateListener,
2715
- DiscordVoiceManager: () => DiscordVoiceManager,
2716
- DiscordVoiceReadyListener: () => DiscordVoiceReadyListener,
2717
- DiscordVoiceResumedListener: () => DiscordVoiceResumedListener,
2718
- DiscordVoiceStateUpdateListener: () => DiscordVoiceStateUpdateListener
2719
- });
2720
2508
  const logger = createSubsystemLogger("discord/voice");
2721
2509
  const DISCORD_VOICE_FATAL_AUTOJOIN_ERROR_PATTERNS = [
2722
2510
  "api key missing",
@@ -2768,8 +2556,7 @@ var DiscordVoiceManager = class {
2768
2556
  }, this),
2769
2557
  readPolicy: this.readPolicy,
2770
2558
  admissionAllowFrom,
2771
- botUserId: () => this.botUserId,
2772
- getSession: (guildId) => this.sessions.get(guildId),
2559
+ sessions: this.sessions,
2773
2560
  isEntryCurrent: (entry) => this.isEntryCurrent(entry),
2774
2561
  isFollowOwnedGuild: (guildId) => this.following.isFollowOwnedGuild(guildId),
2775
2562
  join: (entry, options) => this.join(entry, options),
@@ -2781,11 +2568,9 @@ var DiscordVoiceManager = class {
2781
2568
  ...params,
2782
2569
  allowedChannels: this.allowedChannels,
2783
2570
  autoJoinChannels: this.autoJoinChannels,
2784
- botUserId: () => this.botUserId,
2785
- deleteRecoveryAttempt: (guildId) => this.receive.daveRecoveryAttempts.delete(guildId),
2571
+ daveRecoveryAttempts: this.receive.daveRecoveryAttempts,
2786
2572
  stopTransport: (guildId) => this.voiceSessions.stopTransport(guildId),
2787
- getRecoveryAttempt: (guildId) => this.receive.daveRecoveryAttempts.get(guildId),
2788
- getSession: (guildId) => this.sessions.get(guildId),
2573
+ sessions: this.sessions,
2789
2574
  hasVoiceLifecycle: (guildId) => {
2790
2575
  const lifecycle = this.guildLifecycles.get(guildId);
2791
2576
  return lifecycle?.status === "starting" || lifecycle?.status === "active";
@@ -2793,14 +2578,12 @@ var DiscordVoiceManager = class {
2793
2578
  isAllowedVoiceChannel: (entry) => this.isAllowedVoiceChannel(entry),
2794
2579
  join: (entry, options) => this.join(entry, options),
2795
2580
  leave: (entry, options) => this.leave(entry, options),
2796
- listSessions: () => this.sessions.values(),
2797
2581
  voiceEnabled: this.voiceEnabled
2798
2582
  });
2799
2583
  this.voiceSessions = new DiscordVoiceSessions({
2800
2584
  ...params,
2801
2585
  signal: this.abort.signal,
2802
2586
  isSessionGenerationCurrent: (entry) => this.guildLifecycles.get(entry.guildId)?.generation === entry.generation,
2803
- botUserId: () => this.botUserId,
2804
2587
  destroyed: () => this.destroyed,
2805
2588
  getTranscripts: this.getTranscripts,
2806
2589
  membership: this.membership,
@@ -3072,7 +2855,7 @@ var DiscordVoiceManager = class {
3072
2855
  }
3073
2856
  return result;
3074
2857
  } finally {
3075
- if (this.joinTasks.get(guildId) === joinCompletion.promise) this.joinTasks.delete(guildId);
2858
+ this.joinTasks.delete(guildId);
3076
2859
  joinCompletion.resolve();
3077
2860
  }
3078
2861
  }
@@ -3164,11 +2947,11 @@ var DiscordVoiceManager = class {
3164
2947
  });
3165
2948
  }
3166
2949
  enqueueAutoJoin(entry, captureOrigin) {
3167
- const task = (this.autoJoinTasks.get(entry.guildId) ?? Promise.resolve()).catch(() => void 0).then(async () => await this.reconcileAutoJoinEntry(entry, captureOrigin)).finally(() => {
3168
- if (this.autoJoinTasks.get(entry.guildId) === task) this.autoJoinTasks.delete(entry.guildId);
2950
+ return enqueueKeyedTask({
2951
+ tails: this.autoJoinTasks,
2952
+ key: entry.guildId,
2953
+ task: () => this.reconcileAutoJoinEntry(entry, captureOrigin)
3169
2954
  });
3170
- this.autoJoinTasks.set(entry.guildId, task);
3171
- return task;
3172
2955
  }
3173
2956
  async reconcileAutoJoinEntry(entry, captureOrigin) {
3174
2957
  if (this.destroyed) return {
@@ -3227,4 +3010,4 @@ var DiscordVoiceManager = class {
3227
3010
  return result;
3228
3011
  }
3229
3012
  };
3230
- 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 };
3013
+ export { DiscordVoiceManager, maybeControlDiscordVoiceAgentRun as a, logDiscordVoiceAgentControlResult as i, formatVoiceIngressPrompt as n, handleDiscordVoiceAgentControlToolCall as r, DiscordRealtimeRecording as t };